Debian Codegraph @

config/configtls/configtls.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package configtls // import "go.opentelemetry.io/collector/config/configtls"
5
6 import (
7 "context"
8 "crypto/tls"
9 "crypto/x509"
10 "errors"
11 "fmt"
12 "maps"
13 "os"
14 "path/filepath"
15 "slices"
16 "sync"
17 "time"
18
19 "go.opentelemetry.io/collector/config/configopaque"
20 )
21
22 // We should avoid that users unknowingly use a vulnerable TLS version.
23 // The defaults should be a safe configuration
24 const defaultMinTLSVersion = tls.VersionTLS12
25
26 // Uses the default MaxVersion from "crypto/tls" which is the maximum supported version
27 const defaultMaxTLSVersion = 0
28
29 var systemCertPool = x509.SystemCertPool
30
31 // Config exposes the common client and server TLS configurations.
32 // Note: Since there isn't anything specific to a server connection. Components
33 // with server connections should use Config.
34 type Config struct {
35 // Path to the CA cert. For a client this verifies the server certificate.
36 // For a server this verifies client certificates. If empty uses system root CA.
37 // (optional)
38 CAFile string `mapstructure:"ca_file,omitempty"`
39
40 // In memory PEM encoded cert. (optional)
41 CAPem configopaque.String `mapstructure:"ca_pem,omitempty"`
42
43 // If true, load system CA certificates pool in addition to the certificates
44 // configured in this struct.
45 IncludeSystemCACertsPool bool `mapstructure:"include_system_ca_certs_pool,omitempty"`
46
47 // Path to the TLS cert to use for TLS required connections. (optional)
48 CertFile string `mapstructure:"cert_file,omitempty"`
49
50 // In memory PEM encoded TLS cert to use for TLS required connections. (optional)
51 CertPem configopaque.String `mapstructure:"cert_pem,omitempty"`
52
53 // Path to the TLS key to use for TLS required connections. (optional)
54 KeyFile string `mapstructure:"key_file,omitempty"`
55
56 // In memory PEM encoded TLS key to use for TLS required connections. (optional)
57 KeyPem configopaque.String `mapstructure:"key_pem,omitempty"`
58
59 // MinVersion sets the minimum TLS version that is acceptable.
60 // If not set, TLS 1.2 will be used. (optional)
61 MinVersion string `mapstructure:"min_version,omitempty"`
62
63 // MaxVersion sets the maximum TLS version that is acceptable.
64 // If not set, refer to crypto/tls for defaults. (optional)
65 MaxVersion string `mapstructure:"max_version,omitempty"`
66
67 // CipherSuites is a list of TLS cipher suites that the TLS transport can use.
68 // If left blank, a safe default list is used.
69 // See https://go.dev/src/crypto/tls/cipher_suites.go for a list of supported cipher suites.
70 CipherSuites []string `mapstructure:"cipher_suites,omitempty"`
71
72 // ReloadInterval specifies the duration after which the certificate will be reloaded
73 // If not set, it will never be reloaded (optional)
74 ReloadInterval time.Duration `mapstructure:"reload_interval,omitempty"`
75
76 // contains the elliptic curves that will be used in
77 // an ECDHE handshake, in preference order
78 // Defaults to empty list and "crypto/tls" defaults are used, internally.
79 CurvePreferences []string `mapstructure:"curve_preferences,omitempty"`
80
81 // Trusted platform module configuration
82 TPMConfig TPMConfig `mapstructure:"tpm,omitempty"`
83 }
84
85 // NewDefaultConfig creates a new Config with any default values set.
86 func NewDefaultConfig() Config {
87 return Config{}
88 }
89
90 // ClientConfig contains TLS configurations that are specific to client
91 // connections in addition to the common configurations. This should be used by
92 // components configuring TLS client connections.
93 type ClientConfig struct {
94 // squash ensures fields are correctly decoded in embedded struct.
95 Config `mapstructure:",squash"`
96
97 // These are config options specific to client connections.
98
99 // In gRPC and HTTP when set to true, this is used to disable the client transport security.
100 // See https://godoc.org/google.golang.org/grpc#WithInsecure for gRPC.
101 // Please refer to https://godoc.org/crypto/tls#Config for more information.
102 // (optional, default false)
103 Insecure bool `mapstructure:"insecure,omitempty"`
104 // InsecureSkipVerify will enable TLS but not verify the certificate.
105 InsecureSkipVerify bool `mapstructure:"insecure_skip_verify,omitempty"`
106 // ServerName requested by client for virtual hosting.
107 // This sets the ServerName in the TLSConfig. Please refer to
108 // https://godoc.org/crypto/tls#Config for more information. (optional)
109 ServerName string `mapstructure:"server_name_override,omitempty"`
110 // prevent unkeyed literal initialization
111 _ struct{}
112 }
113
114 // NewDefaultClientConfig creates a new ClientConfig with any default values set.
115 func NewDefaultClientConfig() ClientConfig {
116 return ClientConfig{
117 Config: NewDefaultConfig(),
118 }
119 }
120
121 // ServerConfig contains TLS configurations that are specific to server
122 // connections in addition to the common configurations. This should be used by
123 // components configuring TLS server connections.
124 type ServerConfig struct {
125 // squash ensures fields are correctly decoded in embedded struct.
126 Config `mapstructure:",squash"`
127
128 // These are config options specific to server connections.
129
130 // Path to the TLS cert to use by the server to verify a client certificate. (optional)
131 // This sets the ClientCAs and ClientAuth to RequireAndVerifyClientCert in the TLSConfig. Please refer to
132 // https://godoc.org/crypto/tls#Config for more information. (optional)
133 ClientCAFile string `mapstructure:"client_ca_file,omitempty"`
134
135 // Reload the ClientCAs file when it is modified
136 // (optional, default false)
137 ReloadClientCAFile bool `mapstructure:"client_ca_file_reload,omitempty"`
138 // prevent unkeyed literal initialization
139 _ struct{}
140 }
141
142 // NewDefaultServerConfig creates a new ServerConfig with any default values set.
143 func NewDefaultServerConfig() ServerConfig {
144 return ServerConfig{
145 Config: NewDefaultConfig(),
146 }
147 }
148
149 // certReloader is a wrapper object for certificate reloading
150 // Its GetCertificate method will either return the current certificate or reload from disk
151 // if the last reload happened more than ReloadInterval ago
152 type certReloader struct {
153 nextReload time.Time
154 cert *tls.Certificate
155 lock sync.RWMutex
156 tls Config
157 }
158
159 func (c Config) newCertReloader() (*certReloader, error) {
160 cert, err := c.loadCertificate()
161 if err != nil {
162 return nil, err
163 }
164 return &certReloader{
165 tls: c,
166 nextReload: time.Now().Add(c.ReloadInterval),
167 cert: &cert,
168 }, nil
169 }
170
171 func (r *certReloader) GetCertificate() (*tls.Certificate, error) {
172 now := time.Now()
173 // Read locking here before we do the time comparison
174 // If a reload is in progress this will block and we will skip reloading in the current
175 // call once we can continue
176 r.lock.RLock()
177 if r.tls.ReloadInterval != 0 && r.nextReload.Before(now) && (r.tls.hasCertFile() || r.tls.hasKeyFile()) {
178 // Need to release the read lock, otherwise we deadlock
179 r.lock.RUnlock()
180 r.lock.Lock()
181 defer r.lock.Unlock()
182 cert, err := r.tls.loadCertificate()
183 if err != nil {
184 return nil, fmt.Errorf("failed to load TLS cert and key: %w", err)
185 }
186 r.cert = &cert
187 r.nextReload = now.Add(r.tls.ReloadInterval)
188 return r.cert, nil
189 }
190 defer r.lock.RUnlock()
191 return r.cert, nil
192 }
193
194 func (c Config) Validate() error {
195 if c.hasCAFile() && c.hasCAPem() {
196 return errors.New("provide either a CA file or the PEM-encoded string, but not both")
197 }
198
199 // Ensure certificate is not set using both file and PEM
200 if c.hasCertFile() && c.hasCertPem() {
201 return errors.New("provide either certificate file or PEM, but not both")
202 }
203
204 // Ensure key is not set using both file and PEM
205 if c.hasKeyFile() && c.hasKeyPem() {
206 return errors.New("provide either key file or PEM, but not both")
207 }
208
209 // Fail if only one of cert/key is provided (mismatch case)
210 if c.hasCert() != c.hasKey() {
211 return errors.New("TLS configuration must include both certificate and key (CertFile/CertPem and KeyFile/KeyPem)")
212 }
213
214 minTLS, err := convertVersion(c.MinVersion, defaultMinTLSVersion)
215 if err != nil {
216 return fmt.Errorf("invalid TLS min_version: %w", err)
217 }
218
219 maxTLS, err := convertVersion(c.MaxVersion, defaultMaxTLSVersion)
220 if err != nil {
221 return fmt.Errorf("invalid TLS max_version: %w", err)
222 }
223
224 if maxTLS < minTLS && maxTLS != defaultMaxTLSVersion {
225 return errors.New("invalid TLS configuration: min_version cannot be greater than max_version")
226 }
227
228 return nil
229 }
230
231 func (c ServerConfig) Validate() error {
232 // For servers, both certificate and key are required:
233 // - If both are missing, error.
234 // - If only one is provided (mismatch), error.
235 if !c.hasCert() && !c.hasKey() {
236 return errors.New("TLS configuration must include both certificate and key for server connections")
237 }
238 return nil
239 }
240
241 // loadTLSConfig loads TLS certificates and returns a tls.Config.
242 // This will set the RootCAs and Certificates of a tls.Config.
243 func (c Config) loadTLSConfig() (*tls.Config, error) {
244 certPool, err := c.loadCACertPool()
245 if err != nil {
246 return nil, err
247 }
248
249 var getCertificate func(*tls.ClientHelloInfo) (*tls.Certificate, error)
250 var getClientCertificate func(*tls.CertificateRequestInfo) (*tls.Certificate, error)
251 if c.hasCert() || c.hasKey() {
252 var certReloader *certReloader
253 certReloader, err = c.newCertReloader()
254 if err != nil {
255 return nil, fmt.Errorf("failed to load TLS cert and key: %w", err)
256 }
257 getCertificate = func(*tls.ClientHelloInfo) (*tls.Certificate, error) { return certReloader.GetCertificate() }
258 getClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) { return certReloader.GetCertificate() }
259 }
260
261 minTLS, err := convertVersion(c.MinVersion, defaultMinTLSVersion)
262 if err != nil {
263 return nil, fmt.Errorf("invalid TLS min_version: %w", err)
264 }
265 maxTLS, err := convertVersion(c.MaxVersion, defaultMaxTLSVersion)
266 if err != nil {
267 return nil, fmt.Errorf("invalid TLS max_version: %w", err)
268 }
269 cipherSuites, err := convertCipherSuites(c.CipherSuites)
270 if err != nil {
271 return nil, err
272 }
273
274 allowedCurves := slices.Collect(maps.Values(tlsCurveTypes))
275 curvePreferences := make([]tls.CurveID, 0, len(c.CurvePreferences))
276 for _, curve := range c.CurvePreferences {
277 curveID, ok := tlsCurveTypes[curve]
278 if !ok {
279 return nil, fmt.Errorf("invalid curve type: %s. Expected values are %s", curveID, allowedCurves)
280 }
281 curvePreferences = append(curvePreferences, curveID)
282 }
283
284 // If no curve preferences were explicitly specified in the configuration, use
285 // the ones we allow. This helps in particular with FIPS builds where not all curves
286 // are allowed.
287 if len(curvePreferences) == 0 {
288 curvePreferences = allowedCurves
289 }
290
291 return &tls.Config{
292 RootCAs: certPool,
293 GetCertificate: getCertificate,
294 GetClientCertificate: getClientCertificate,
295 MinVersion: minTLS,
296 MaxVersion: maxTLS,
297 CipherSuites: cipherSuites,
298 CurvePreferences: curvePreferences,
299 }, nil
300 }
301
302 func convertCipherSuites(cipherSuites []string) ([]uint16, error) {
303 var result []uint16
304 var errs []error
305 for _, suite := range cipherSuites {
306 found := false
307 for _, supported := range tls.CipherSuites() {
308 if suite == supported.Name {
309 result = append(result, supported.ID)
310 found = true
311 break
312 }
313 }
314 if !found {
315 errs = append(errs, fmt.Errorf("invalid TLS cipher suite: %q", suite))
316 }
317 }
318 return result, errors.Join(errs...)
319 }
320
321 func (c Config) loadCACertPool() (*x509.CertPool, error) {
322 // There is no need to load the System Certs for RootCAs because
323 // if the value is nil, it will default to checking against th System Certs.
324 var err error
325 var certPool *x509.CertPool
326
327 switch {
328 case c.hasCAFile() && c.hasCAPem():
329 return nil, errors.New("failed to load CA CertPool: provide either a CA file or the PEM-encoded string, but not both")
330 case c.hasCAFile():
331 // Set up user specified truststore from file
332 certPool, err = c.loadCertFile(c.CAFile)
333 if err != nil {
334 return nil, fmt.Errorf("failed to load CA CertPool File: %w", err)
335 }
336 case c.hasCAPem():
337 // Set up user specified truststore from PEM
338 certPool, err = c.loadCertPem([]byte(c.CAPem))
339 if err != nil {
340 return nil, fmt.Errorf("failed to load CA CertPool PEM: %w", err)
341 }
342 }
343
344 return certPool, nil
345 }
346
347 func (c Config) loadCertFile(certPath string) (*x509.CertPool, error) {
348 certPem, err := os.ReadFile(filepath.Clean(certPath))
349 if err != nil {
350 return nil, fmt.Errorf("failed to load cert %s: %w", certPath, err)
351 }
352
353 return c.loadCertPem(certPem)
354 }
355
356 func (c Config) loadCertPem(certPem []byte) (*x509.CertPool, error) {
357 certPool := x509.NewCertPool()
358 if c.IncludeSystemCACertsPool {
359 scp, err := systemCertPool()
360 if err != nil {
361 return nil, err
362 }
363 if scp != nil {
364 certPool = scp
365 }
366 }
367 if !certPool.AppendCertsFromPEM(certPem) {
368 return nil, errors.New("failed to parse cert")
369 }
370 return certPool, nil
371 }
372
373 func (c Config) loadCertificate() (tls.Certificate, error) {
374 switch {
375 case c.hasCert() != c.hasKey():
376 return tls.Certificate{}, errors.New("for auth via TLS, provide both certificate and key, or neither")
377 case !c.hasCert() && !c.hasKey():
378 return tls.Certificate{}, nil
379 case c.hasCertFile() && c.hasCertPem():
380 return tls.Certificate{}, errors.New("for auth via TLS, provide either a certificate or the PEM-encoded string, but not both")
381 case c.hasKeyFile() && c.hasKeyPem():
382 return tls.Certificate{}, errors.New("for auth via TLS, provide either a key or the PEM-encoded string, but not both")
383 }
384
385 var certPem, keyPem []byte
386 var err error
387 if c.hasCertFile() {
388 certPem, err = os.ReadFile(c.CertFile)
389 if err != nil {
390 return tls.Certificate{}, err
391 }
392 } else {
393 certPem = []byte(c.CertPem)
394 }
395
396 if c.hasKeyFile() {
397 keyPem, err = os.ReadFile(c.KeyFile)
398 if err != nil {
399 return tls.Certificate{}, err
400 }
401 } else {
402 keyPem = []byte(c.KeyPem)
403 }
404
405 if c.TPMConfig.Enabled {
406 certificate, errTPM := c.TPMConfig.tpmCertificate(keyPem, certPem, openTPM(c.TPMConfig.Path))
407 if errTPM != nil {
408 return tls.Certificate{}, fmt.Errorf("failed to load private key from TPM: %w", errTPM)
409 }
410 return certificate, nil
411 }
412
413 certificate, errKeyPair := tls.X509KeyPair(certPem, keyPem)
414 if errKeyPair != nil {
415 return tls.Certificate{}, fmt.Errorf("failed to load TLS cert and key PEMs: %w", errKeyPair)
416 }
417 return certificate, err
418 }
419
420 func (c Config) loadCert(caPath string) (*x509.CertPool, error) {
421 caPEM, err := os.ReadFile(filepath.Clean(caPath))
422 if err != nil {
423 return nil, fmt.Errorf("failed to load CA %s: %w", caPath, err)
424 }
425
426 var certPool *x509.CertPool
427 if c.IncludeSystemCACertsPool {
428 if certPool, err = systemCertPool(); err != nil {
429 return nil, err
430 }
431 }
432 if certPool == nil {
433 certPool = x509.NewCertPool()
434 }
435 if !certPool.AppendCertsFromPEM(caPEM) {
436 return nil, fmt.Errorf("failed to parse CA %s", caPath)
437 }
438 return certPool, nil
439 }
440
441 // LoadTLSConfig loads the TLS configuration.
442 func (c ClientConfig) LoadTLSConfig(_ context.Context) (*tls.Config, error) {
443 if c.Insecure && !c.hasCA() {
444 return nil, nil
445 }
446
447 tlsCfg, err := c.loadTLSConfig()
448 if err != nil {
449 return nil, fmt.Errorf("failed to load TLS config: %w", err)
450 }
451 tlsCfg.ServerName = c.ServerName
452 tlsCfg.InsecureSkipVerify = c.InsecureSkipVerify
453 return tlsCfg, nil
454 }
455
456 // LoadTLSConfig loads the TLS configuration.
457 func (c ServerConfig) LoadTLSConfig(_ context.Context) (*tls.Config, error) {
458 tlsCfg, err := c.loadTLSConfig()
459 if err != nil {
460 return nil, fmt.Errorf("failed to load TLS config: %w", err)
461 }
462 if c.ClientCAFile != "" {
463 reloader, err := newClientCAsReloader(c.ClientCAFile, &c)
464 if err != nil {
465 return nil, err
466 }
467 if c.ReloadClientCAFile {
468 err = reloader.startWatching()
469 if err != nil {
470 return nil, err
471 }
472 tlsCfg.GetConfigForClient = func(*tls.ClientHelloInfo) (*tls.Config, error) { return reloader.getClientConfig(tlsCfg) }
473 }
474 tlsCfg.ClientCAs = reloader.certPool
475 tlsCfg.ClientAuth = tls.RequireAndVerifyClientCert
476 }
477 return tlsCfg, nil
478 }
479
480 func (c ServerConfig) loadClientCAFile() (*x509.CertPool, error) {
481 return c.loadCert(c.ClientCAFile)
482 }
483
484 func (c Config) hasCA() bool { return c.hasCAFile() || c.hasCAPem() }
485 func (c Config) hasCert() bool { return c.hasCertFile() || c.hasCertPem() }
486 func (c Config) hasKey() bool { return c.hasKeyFile() || c.hasKeyPem() }
487
488 func (c Config) hasCAFile() bool { return c.CAFile != "" }
489 func (c Config) hasCAPem() bool { return len(c.CAPem) != 0 }
490
491 func (c Config) hasCertFile() bool { return c.CertFile != "" }
492 func (c Config) hasCertPem() bool { return len(c.CertPem) != 0 }
493
494 func (c Config) hasKeyFile() bool { return c.KeyFile != "" }
495 func (c Config) hasKeyPem() bool { return len(c.KeyPem) != 0 }
496
497 func convertVersion(v string, defaultVersion uint16) (uint16, error) {
498 // Use a default that is explicitly defined
499 if v == "" {
500 return defaultVersion, nil
501 }
502 val, ok := tlsVersions[v]
503 if !ok {
504 return 0, fmt.Errorf("unsupported TLS version: %q", v)
505 }
506 return val, nil
507 }
508
509 var tlsVersions = map[string]uint16{
510 "1.0": tls.VersionTLS10,
511 "1.1": tls.VersionTLS11,
512 "1.2": tls.VersionTLS12,
513 "1.3": tls.VersionTLS13,
514 }