-
Notifications
You must be signed in to change notification settings - Fork 199
/
Copy pathtls.go
238 lines (192 loc) · 6.4 KB
/
tls.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
// Copyright 2014-2022 Aerospike, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
)
func initAerospikeTLS() *tls.Config {
if len(*rootCA) == 0 && len(*certFile) == 0 && len(*keyFile) == 0 {
return nil
}
var clientPool []tls.Certificate
var serverPool *x509.CertPool
var err error
serverPool, err = loadCACert(*rootCA)
if err != nil {
log.Fatal(err)
}
if len(*certFile) > 0 || len(*keyFile) > 0 {
clientPool, err = loadServerCertAndKey(*certFile, *keyFile, *keyFilePassphrase)
if err != nil {
log.Fatal(err)
}
}
tlsConfig := &tls.Config{
Certificates: clientPool,
RootCAs: serverPool,
InsecureSkipVerify: false,
PreferServerCipherSuites: true,
}
tlsConfig.BuildNameToCertificate()
return tlsConfig
}
// Get secret
// secretConfig can be one of the following,
// 1. "<secret>" (secret directly)
// 2. "file:<file-that-contains-secret>" (file containing secret)
// 3. "env:<environment-variable-that-contains-secret>" (environment variable containing secret)
// 4. "env-b64:<environment-variable-that-contains-base64-encoded-secret>" (environment variable containing base64 encoded secret)
// 5. "b64:<base64-encoded-secret>" (base64 encoded secret)
func getSecret(secretConfig string) ([]byte, error) {
secretSource := strings.SplitN(secretConfig, ":", 2)
if len(secretSource) == 2 {
switch secretSource[0] {
case "file":
return readFromFile(secretSource[1])
case "env":
secret, ok := os.LookupEnv(secretSource[1])
if !ok {
return nil, fmt.Errorf("environment variable %s not set", secretSource[1])
}
return []byte(secret), nil
case "env-b64":
return getValueFromBase64EnvVar(secretSource[1])
case "b64":
return getValueFromBase64(secretSource[1])
default:
return nil, fmt.Errorf("invalid source: %s", secretSource[0])
}
}
return []byte(secretConfig), nil
}
// Get certificate
// certConfig can be one of the following,
// 1. "<file-path>" (certificate file path directly)
// 2. "file:<file-path>" (certificate file path)
// 3. "env-b64:<environment-variable-that-contains-base64-encoded-certificate>" (environment variable containing base64 encoded certificate)
// 4. "b64:<base64-encoded-certificate>" (base64 encoded certificate)
func getCertificate(certConfig string) ([]byte, error) {
certificateSource := strings.SplitN(certConfig, ":", 2)
if len(certificateSource) == 2 {
switch certificateSource[0] {
case "file":
return readFromFile(certificateSource[1])
case "env-b64":
return getValueFromBase64EnvVar(certificateSource[1])
case "b64":
return getValueFromBase64(certificateSource[1])
default:
return nil, fmt.Errorf("invalid source %s", certificateSource[0])
}
}
// Assume certConfig is a file path (backward compatible)
return readFromFile(certConfig)
}
// Read content from file
func readFromFile(filePath string) ([]byte, error) {
dataBytes, err := ioutil.ReadFile(filePath)
if err != nil {
return nil, fmt.Errorf("failed to read from file `%s`: `%v`", filePath, err)
}
data := bytes.TrimSuffix(dataBytes, []byte("\n"))
return data, nil
}
// Get decoded base64 value from environment variable
func getValueFromBase64EnvVar(envVar string) ([]byte, error) {
b64Value, ok := os.LookupEnv(envVar)
if !ok {
return nil, fmt.Errorf("environment variable %s not set", envVar)
}
return getValueFromBase64(b64Value)
}
// Get decoded base64 value
func getValueFromBase64(b64Value string) ([]byte, error) {
value, err := base64.StdEncoding.DecodeString(b64Value)
if err != nil {
return nil, fmt.Errorf("failed to decode base64 value: %v", err)
}
return value, nil
}
// loadCACert returns CA set of certificates (cert pool)
// reads CA certificate based on the certConfig and adds it to the pool
func loadCACert(certConfig string) (*x509.CertPool, error) {
certificates, err := x509.SystemCertPool()
if certificates == nil || err != nil {
certificates = x509.NewCertPool()
}
if len(certConfig) > 0 {
caCert, err := getCertificate(certConfig)
if err != nil {
return nil, err
}
certificates.AppendCertsFromPEM(caCert)
}
return certificates, nil
}
// loadServerCertAndKey reads server certificate and associated key file based on certConfig and keyConfig
// returns parsed server certificate
// if the private key is encrypted, it will be decrypted using key file passphrase
func loadServerCertAndKey(certConfig, keyConfig, keyPassConfig string) ([]tls.Certificate, error) {
var certificates []tls.Certificate
// Read cert file
certFileBytes, err := getCertificate(certConfig)
if err != nil {
return nil, err
}
// Read key file
keyFileBytes, err := getCertificate(keyConfig)
if err != nil {
return nil, err
}
// Decode PEM data
keyBlock, _ := pem.Decode(keyFileBytes)
certBlock, _ := pem.Decode(certFileBytes)
if keyBlock == nil || certBlock == nil {
return nil, fmt.Errorf("failed to decode PEM data for key or certificate")
}
// Check and Decrypt the the Key Block using passphrase
if x509.IsEncryptedPEMBlock(keyBlock) {
keyFilePassphraseBytes, err := getSecret(keyPassConfig)
if err != nil {
return nil, fmt.Errorf("failed to get key passphrase: `%s`", err)
}
decryptedDERBytes, err := x509.DecryptPEMBlock(keyBlock, keyFilePassphraseBytes)
if err != nil {
return nil, fmt.Errorf("failed to decrypt PEM Block: `%s`", err)
}
keyBlock.Bytes = decryptedDERBytes
keyBlock.Headers = nil
}
// Encode PEM data
keyPEM := pem.EncodeToMemory(keyBlock)
certPEM := pem.EncodeToMemory(certBlock)
if keyPEM == nil || certPEM == nil {
return nil, fmt.Errorf("failed to encode PEM data for key or certificate")
}
cert, err := tls.X509KeyPair(certPEM, keyPEM)
if err != nil {
return nil, fmt.Errorf("failed to add certificate and key to the pool: `%s`", err)
}
certificates = append(certificates, cert)
return certificates, nil
}