72 lines
2.0 KiB
Go
72 lines
2.0 KiB
Go
package mariadb
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"crypto/tls"
|
|
"crypto/x509"
|
|
"fmt"
|
|
"strings"
|
|
|
|
mysql "github.com/go-sql-driver/mysql"
|
|
)
|
|
|
|
// ConfigureTLS configures the DSN so setup and runtime use the same TLS policy.
|
|
func ConfigureTLS(cfg *mysql.Config, mode, caPEM string) error {
|
|
mode = strings.TrimSpace(mode)
|
|
if mode == "" {
|
|
mode = "preferred"
|
|
}
|
|
caPEM = strings.TrimSpace(caPEM)
|
|
if caPEM != "" && mode != "verify-ca" && mode != "verify-full" {
|
|
return fmt.Errorf("CA certificate requires verify-ca or verify-full")
|
|
}
|
|
switch mode {
|
|
case "preferred":
|
|
cfg.TLSConfig = "preferred"
|
|
return nil
|
|
case "required":
|
|
cfg.TLSConfig = "skip-verify"
|
|
return nil
|
|
case "verify-full":
|
|
if caPEM == "" {
|
|
cfg.TLSConfig = "true"
|
|
return nil
|
|
}
|
|
case "verify-ca":
|
|
if caPEM == "" {
|
|
return fmt.Errorf("verify-ca requires a CA certificate")
|
|
}
|
|
default:
|
|
return fmt.Errorf("unsupported MariaDB TLS mode")
|
|
}
|
|
roots := x509.NewCertPool()
|
|
if !roots.AppendCertsFromPEM([]byte(caPEM)) {
|
|
return fmt.Errorf("invalid CA certificate PEM")
|
|
}
|
|
tlsConfig := &tls.Config{MinVersion: tls.VersionTLS12, RootCAs: roots}
|
|
if mode == "verify-ca" {
|
|
// Verify the certificate chain explicitly; this mode omits hostname checks.
|
|
tlsConfig.InsecureSkipVerify = true
|
|
tlsConfig.VerifyConnection = func(state tls.ConnectionState) error {
|
|
if len(state.PeerCertificates) == 0 {
|
|
return fmt.Errorf("MariaDB did not provide a certificate")
|
|
}
|
|
intermediates := x509.NewCertPool()
|
|
for _, cert := range state.PeerCertificates[1:] {
|
|
intermediates.AddCert(cert)
|
|
}
|
|
_, err := state.PeerCertificates[0].Verify(x509.VerifyOptions{Roots: roots, Intermediates: intermediates, KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}})
|
|
if err != nil {
|
|
return fmt.Errorf("verify MariaDB certificate: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
}
|
|
name := fmt.Sprintf("qfs-%x", sha256.Sum256([]byte(mode+"\n"+caPEM)))
|
|
if err := mysql.RegisterTLSConfig(name, tlsConfig); err != nil {
|
|
return fmt.Errorf("register MariaDB TLS: %w", err)
|
|
}
|
|
cfg.TLSConfig = name
|
|
return nil
|
|
}
|