44 lines
1.3 KiB
Go
44 lines
1.3 KiB
Go
package security
|
|
|
|
import (
|
|
"crypto/tls"
|
|
"crypto/x509"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
)
|
|
|
|
// ClientMTLSConfig builds a TLS 1.3 client configuration with an explicit
|
|
// workload certificate. The service name is verified against the server
|
|
// certificate; neither InsecureSkipVerify nor the host trust store is used.
|
|
func ClientMTLSConfig(caFile, certFile, keyFile, serverName string) (*tls.Config, error) {
|
|
caFile = strings.TrimSpace(caFile)
|
|
certFile = strings.TrimSpace(certFile)
|
|
keyFile = strings.TrimSpace(keyFile)
|
|
serverName = strings.TrimSpace(serverName)
|
|
if caFile == "" || certFile == "" || keyFile == "" || serverName == "" {
|
|
return nil, errors.New("client CA, certificate, key, and server name are required")
|
|
}
|
|
|
|
caPEM, err := os.ReadFile(caFile)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read client TLS CA: %w", err)
|
|
}
|
|
roots := x509.NewCertPool()
|
|
if !roots.AppendCertsFromPEM(caPEM) {
|
|
return nil, errors.New("client TLS CA file contains no certificate")
|
|
}
|
|
certificate, err := tls.LoadX509KeyPair(certFile, keyFile)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("load client TLS identity: %w", err)
|
|
}
|
|
|
|
return &tls.Config{
|
|
MinVersion: tls.VersionTLS13,
|
|
RootCAs: roots,
|
|
Certificates: []tls.Certificate{certificate},
|
|
ServerName: serverName,
|
|
}, nil
|
|
}
|