105 lines
2.3 KiB
Go
105 lines
2.3 KiB
Go
package tls
|
|
|
|
import (
|
|
"crypto/tls"
|
|
"fmt"
|
|
"os"
|
|
)
|
|
|
|
// Note: This package is named "tls" but provides configuration for crypto/tls
|
|
|
|
// Config holds TLS configuration
|
|
type Config struct {
|
|
CertFile string
|
|
KeyFile string
|
|
MinVersion uint16
|
|
MaxVersion uint16
|
|
Enabled bool
|
|
}
|
|
|
|
// LoadConfig loads TLS configuration from environment variables
|
|
func LoadConfig() *Config {
|
|
cfg := &Config{
|
|
CertFile: os.Getenv("ATLAS_TLS_CERT"),
|
|
KeyFile: os.Getenv("ATLAS_TLS_KEY"),
|
|
MinVersion: tls.VersionTLS12,
|
|
MaxVersion: tls.VersionTLS13,
|
|
Enabled: false,
|
|
}
|
|
|
|
// Enable TLS if certificate and key are provided
|
|
if cfg.CertFile != "" && cfg.KeyFile != "" {
|
|
cfg.Enabled = true
|
|
}
|
|
|
|
// Check if TLS is explicitly enabled
|
|
if os.Getenv("ATLAS_TLS_ENABLED") == "true" {
|
|
cfg.Enabled = true
|
|
}
|
|
|
|
return cfg
|
|
}
|
|
|
|
// BuildTLSConfig builds a crypto/tls.Config from the configuration
|
|
func (c *Config) BuildTLSConfig() (*tls.Config, error) {
|
|
if !c.Enabled {
|
|
return nil, nil
|
|
}
|
|
|
|
// Verify certificate and key files exist
|
|
if _, err := os.Stat(c.CertFile); os.IsNotExist(err) {
|
|
return nil, fmt.Errorf("TLS certificate file not found: %s", c.CertFile)
|
|
}
|
|
|
|
if _, err := os.Stat(c.KeyFile); os.IsNotExist(err) {
|
|
return nil, fmt.Errorf("TLS key file not found: %s", c.KeyFile)
|
|
}
|
|
|
|
// Load certificate
|
|
cert, err := tls.LoadX509KeyPair(c.CertFile, c.KeyFile)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("load TLS certificate: %w", err)
|
|
}
|
|
|
|
config := &tls.Config{
|
|
Certificates: []tls.Certificate{cert},
|
|
MinVersion: c.MinVersion,
|
|
MaxVersion: c.MaxVersion,
|
|
// Security best practices
|
|
PreferServerCipherSuites: true,
|
|
CurvePreferences: []tls.CurveID{
|
|
tls.CurveP256,
|
|
tls.CurveP384,
|
|
tls.CurveP521,
|
|
tls.X25519,
|
|
},
|
|
CipherSuites: []uint16{
|
|
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
|
|
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
|
|
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
|
|
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
|
|
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
|
|
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
|
|
},
|
|
}
|
|
|
|
return config, nil
|
|
}
|
|
|
|
// Validate validates the TLS configuration
|
|
func (c *Config) Validate() error {
|
|
if !c.Enabled {
|
|
return nil
|
|
}
|
|
|
|
if c.CertFile == "" {
|
|
return fmt.Errorf("TLS certificate file is required when TLS is enabled")
|
|
}
|
|
|
|
if c.KeyFile == "" {
|
|
return fmt.Errorf("TLS key file is required when TLS is enabled")
|
|
}
|
|
|
|
return nil
|
|
}
|