|
1 | 1 | package main |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "crypto/x509" |
| 5 | + "encoding/pem" |
4 | 6 | "fmt" |
5 | 7 | "io/ioutil" |
6 | 8 | "net" |
7 | 9 | "os" |
| 10 | + "regexp" |
8 | 11 | ) |
9 | 12 |
|
10 | 13 | func server(config Config) { |
@@ -33,19 +36,33 @@ func server(config Config) { |
33 | 36 | IP: clientAddr.IP, |
34 | 37 | Port: clientAddr.Port + 1, |
35 | 38 | }) |
36 | | - |
37 | | - response := os.Getenv(KEY_DATA_ENV_VAR) |
38 | | - if response == `` { |
39 | | - keyData, err := ioutil.ReadFile(config.KeyPath) |
40 | | - if err == nil { |
41 | | - response = string(keyData) |
42 | | - } else { |
43 | | - response = fmt.Sprintf("ERROR reading keyfile %s: %s!", |
44 | | - config.KeyPath, err) |
45 | | - fmt.Println(response) |
| 39 | + var keyData []byte |
| 40 | + keyData = []byte(os.Getenv(KEY_DATA_ENV_VAR)) |
| 41 | + if len(keyData) == 0 { |
| 42 | + keyData, err = ioutil.ReadFile(config.KeyPath) |
| 43 | + if err != nil { |
| 44 | + fmt.Printf("ERROR reading keyfile %s: %s!\n", config.KeyPath, err) |
| 45 | + } |
| 46 | + } |
| 47 | + pemBlock, _ := pem.Decode(keyData) |
| 48 | + if pemBlock != nil { |
| 49 | + if x509.IsEncryptedPEMBlock(pemBlock) { |
| 50 | + fmt.Println("Decrypting private key with passphrase...") |
| 51 | + decoded, err := x509.DecryptPEMBlock(pemBlock, []byte(config.Pwd)) |
| 52 | + if err == nil { |
| 53 | + header := `PRIVATE KEY` // default key type in header |
| 54 | + matcher := regexp.MustCompile("-----BEGIN (.*)-----") |
| 55 | + if matches := matcher.FindSubmatch(keyData); len(matches) > 1 { |
| 56 | + header = string(matches[1]) |
| 57 | + } |
| 58 | + keyData = pem.EncodeToMemory( |
| 59 | + &pem.Block{Type: header, Bytes: decoded}) |
| 60 | + } else { |
| 61 | + fmt.Printf("Error decrypting PEM-encoded secret: %s\n", err) |
| 62 | + } |
46 | 63 | } |
47 | 64 | } |
48 | | - _, err = writeSocket.Write([]byte(response)) |
| 65 | + _, err = writeSocket.Write(keyData) |
49 | 66 | if err != nil { |
50 | 67 | fmt.Printf("ERROR writing data to socket:%s!\n", err) |
51 | 68 | } |
|
0 commit comments