github.com/verrazzano/verrazzano@v1.7.0/tools/vz/pkg/helpers/vzsanitize.go (about)

     1  // Copyright (c) 2022, 2023, Oracle and/or its affiliates.
     2  // Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
     3  
     4  package helpers
     5  
     6  import (
     7  	"crypto/sha256"
     8  	"encoding/hex"
     9  	"regexp"
    10  	"sync"
    11  )
    12  
    13  var regexToReplacementList = []string{}
    14  var KnownHostNames = make(map[string]bool)
    15  var knownHostNamesMutex = &sync.Mutex{}
    16  
    17  const ipv4Regex = "[[:digit:]]{1,3}\\.[[:digit:]]{1,3}\\.[[:digit:]]{1,3}\\.[[:digit:]]{1,3}"
    18  const userData = "\"user_data\":\\s+\"[A-Za-z0-9=+]+\""
    19  const sshAuthKeys = "ssh-rsa\\s+[A-Za-z0-9=+ \\-\\/@]+"
    20  const ocid = "ocid1\\.[[:lower:]]+\\.[[:alnum:]]+\\.[[:alnum:]]*\\.[[:alnum:]]+"
    21  
    22  // InitRegexToReplacementMap Initialize the regex string to replacement string map
    23  // Append to this map for any future additions
    24  func InitRegexToReplacementMap() {
    25  	regexToReplacementList = append(regexToReplacementList, ipv4Regex)
    26  	regexToReplacementList = append(regexToReplacementList, userData)
    27  	regexToReplacementList = append(regexToReplacementList, sshAuthKeys)
    28  	regexToReplacementList = append(regexToReplacementList, ocid)
    29  }
    30  
    31  // SanitizeString sanitizes each line in a given file,
    32  // Sanitizes based on the regex map initialized above, which is currently filtering for IPv4 addresses and hostnames
    33  func SanitizeString(l string) string {
    34  	if len(regexToReplacementList) == 0 {
    35  		InitRegexToReplacementMap()
    36  	}
    37  	knownHostNamesMutex.Lock()
    38  	for knownHost := range KnownHostNames {
    39  		wholeOccurrenceHostPattern := "\"" + knownHost + "\""
    40  		l = regexp.MustCompile(wholeOccurrenceHostPattern).ReplaceAllString(l, "\""+getSha256Hash(knownHost)+"\"")
    41  	}
    42  	knownHostNamesMutex.Unlock()
    43  	for _, eachRegex := range regexToReplacementList {
    44  		l = regexp.MustCompile(eachRegex).ReplaceAllString(l, getSha256Hash(l))
    45  	}
    46  	return l
    47  }
    48  
    49  // getSha256Hash generates the one way hash for the input string
    50  func getSha256Hash(line string) string {
    51  	data := []byte(line)
    52  	hashedVal := sha256.Sum256(data)
    53  	hexString := hex.EncodeToString(hashedVal[:])
    54  	return hexString
    55  }