-
Notifications
You must be signed in to change notification settings - Fork 2
/
tls.go
294 lines (266 loc) · 8.05 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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"math/big"
"net"
"os"
"path/filepath"
"time"
logrus "github.com/sirupsen/logrus"
)
// loadTLSCredentials loads the appropriate TLS credentials based on the
// availability of third-party certificates or falls back to self-signed
// certificates.
//
// It checks for the presence of third-party TLS certificates and, if not found,
// generates and uses local self-signed TLS certificates.
//
// Parameters:
// - config: A pointer to the Config struct containing TLS configuration
// settings.
//
// Returns:
// - A TransportCredentials instance for gRPC if successful, or an error if any
// step fails.
func loadTLSCredentials(config *Config) (*tls.Config, error) {
var certFile, keyFile string
// Check if the third-party TLS certificate and key files are
// configured.
if config.TLS.ThirdPartyTLSCertFile != "" &&
config.TLS.ThirdPartyTLSKeyFile != "" {
logrus.Debug("Attempting to use third-party TLS certificate.")
certFile = filepath.Join(
config.TLS.ThirdPartyTLSDirPath,
config.TLS.ThirdPartyTLSCertFile,
)
keyFile = filepath.Join(
config.TLS.ThirdPartyTLSDirPath,
config.TLS.ThirdPartyTLSKeyFile,
)
// Check if both third-party files exist.
err := checkFilesExist(certFile, keyFile)
if err == nil {
logrus.Debug("All third-party TLS files found. Using " +
"third-party TLS certificates.")
} else {
logrus.Warn("One or more third-party TLS files are " +
"missing. Falling back to local TLS " +
"certificates.")
certFile, keyFile = "", ""
}
} else {
logrus.Debug("Third-party TLS certificate files not fully " +
"configured. Using local TLS certificates.")
}
// If TLS files are still empty, fall back to local self-signed TLS
// certificates.
if certFile == "" && keyFile == "" {
logrus.Debug("Falling back to use local self-signed TLS " +
"certificate.")
certFile = filepath.Join(
config.TLS.SelfSignedTLSDirPath,
config.TLS.SelfSignedTLSCertFile,
)
keyFile = filepath.Join(
config.TLS.SelfSignedTLSDirPath,
config.TLS.SelfSignedTLSKeyFile,
)
// Ensure local self-signed TLS certificates exist.
err := checkAndCreateSelfSignedTLS(certFile, keyFile)
if err != nil {
return nil, fmt.Errorf("failed to check/create local "+
"self-signed TLS certificates: %v", err)
}
}
// Update internal fields.
config.TLS.TLSCertFile = certFile
config.TLS.TLSKeyFile = keyFile
// Load server's certificate and private key.
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, err
}
// Return the TLS credentials for server-side TLS only.
return &tls.Config{
Certificates: []tls.Certificate{cert},
MinVersion: tls.VersionTLS12,
ClientAuth: tls.NoClientCert,
}, nil
}
// checkAndCreateSelfSignedTLS checks if local self-signed certificates exist and creates them if necessary.
func checkAndCreateSelfSignedTLS(certFile, keyFile string) error {
err := checkFilesExist(certFile, keyFile)
if err != nil {
// If any of them do not exist, re-create them.
return generateSelfSignedTLS(certFile, keyFile)
}
// Load the existing certificate.
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return generateSelfSignedTLS(certFile, keyFile)
}
// Check the validity of the existing certificate.
for _, certData := range cert.Certificate {
cert, err := x509.ParseCertificate(certData)
if err != nil {
return err
}
if time.Now().After(cert.NotAfter) {
logrus.Warning("Self-Signed TLS certificate is " +
"expired. Creating a new one...")
return generateSelfSignedTLS(certFile, keyFile)
}
}
return nil
}
// generateSelfSignedTLS generates new self-signed TLS certificates.
//
// It creates a new CA certificate and a server certificate signed by the CA,
// and saves them to the specified file paths.
//
// Parameters:
// - certFile: Path to the server certificate file.
// - keyFile: Path to the server key file.
//
// Returns:
// - An error if the certificate generation fails, or nil if successful.
func generateSelfSignedTLS(certFile, keyFile string) error {
// Define default domain names.
domainNames := []string{"localhost", "localhost.localdomain"}
// Get IP addresses for the eth0 interface.
ipAddresses, err := getIPAddresses("eth0")
if err != nil {
return err
}
// Add loopback addresses for localhost (IPv4 and IPv6).
ipAddresses = append(ipAddresses, net.ParseIP("127.0.0.1"))
ipAddresses = append(ipAddresses, net.ParseIP("::1"))
// Generate a new private key for the server using the P-256 curve.
serverPriv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return err
}
// Valid for one year.
notBefore := time.Now()
notAfter := time.Now().Add(365 * 24 * time.Hour)
// Create a certificate template for the server.
serverTemplate := x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
Organization: []string{"Development Certificate"},
},
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
ExtKeyUsage: []x509.ExtKeyUsage{
x509.ExtKeyUsageServerAuth,
},
IsCA: true,
BasicConstraintsValid: true,
DNSNames: domainNames,
IPAddresses: ipAddresses,
}
// Create the server certificate signed by itself (self-signed).
serverBytes, err := x509.CreateCertificate(
rand.Reader, &serverTemplate, &serverTemplate,
&serverPriv.PublicKey, serverPriv,
)
if err != nil {
return err
}
// Save the server certificate to the specified file.
certOut, err := os.Create(certFile)
if err != nil {
return err
}
defer certOut.Close()
// Encode the server certificate to PEM format and write it to the file.
err = pem.Encode(
certOut, &pem.Block{Type: "CERTIFICATE", Bytes: serverBytes},
)
if err != nil {
return err
}
// Save the server private key to the specified file.
keyOut, err := os.Create(keyFile)
if err != nil {
return err
}
defer keyOut.Close()
// Marshal the server private key to DER-encoded format.
serverPrivBytes, err := x509.MarshalECPrivateKey(serverPriv)
if err != nil {
return err
}
// Encode the server private key to PEM format and write it to the file.
err = pem.Encode(
keyOut,
&pem.Block{Type: "EC PRIVATE KEY", Bytes: serverPrivBytes},
)
if err != nil {
return err
}
return nil
}
// getIPAddresses retrieves the IP addresses associated with a given network
// interface.
func getIPAddresses(interfaceName string) ([]net.IP, error) {
var ipAddresses []net.IP
ifaces, err := net.Interfaces()
if err != nil {
return nil, err
}
for _, iface := range ifaces {
if iface.Name == interfaceName {
addrs, err := iface.Addrs()
if err != nil {
return nil, err
}
for _, addr := range addrs {
ipNet, ok := addr.(*net.IPNet)
if ok && ipNet.IP != nil {
ipAddresses = append(ipAddresses, ipNet.IP)
}
}
}
}
return ipAddresses, nil
}
// CreateThirdPartyTLSDirIfNotExist checks if the directory for third-party TLS
// certificates exists, and creates it if it does not.
//
// This function ensures that the directory specified in the TLS configuration
// for third-party TLS certificates is present. If the directory does not
// exist, it attempts to create it with the specified permissions.
//
// Parameters:
// - config: A pointer to the Config struct containing the TLS configuration,
// including the path to the directory for third-party TLS
// certificates.
//
// Returns:
// - An error if the directory creation fails, or nil if the directory already
// exists or is successfully created.
func CreateThirdPartyTLSDirIfNotExist(config *Config) error {
// Check if the directory for third-party TLS certificates exists.
_, err := os.Stat(config.TLS.ThirdPartyTLSDirPath)
if os.IsNotExist(err) {
// If the directory does not exist, create it with the
// specified permissions.
err := os.Mkdir(
config.TLS.ThirdPartyTLSDirPath,
ThirdPartyTLSDirPermissions,
)
if err != nil {
return err
}
}
return nil
}