forked from mtusi2026/mtusi2026lab7
58 lines
1.6 KiB
Go
58 lines
1.6 KiB
Go
// Package security centralizes verified TLS and fail-closed secret leases.
|
|
package security
|
|
|
|
import (
|
|
"crypto/tls"
|
|
"crypto/x509"
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
)
|
|
|
|
func ClientTLS() (*tls.Config, error) {
|
|
ca, err := os.ReadFile(os.Getenv("TLS_CA_FILE"))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("CA unavailable")
|
|
}
|
|
roots := x509.NewCertPool()
|
|
if !roots.AppendCertsFromPEM(ca) {
|
|
return nil, fmt.Errorf("invalid CA")
|
|
}
|
|
c := &tls.Config{MinVersion: tls.VersionTLS12, RootCAs: roots}
|
|
c.GetClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) {
|
|
pair, e := tls.LoadX509KeyPair(os.Getenv("TLS_CERT_FILE"), os.Getenv("TLS_KEY_FILE"))
|
|
return &pair, e
|
|
}
|
|
return c, nil
|
|
}
|
|
|
|
func ServerTLS() (*tls.Config, error) {
|
|
c, err := ClientTLS()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
c.ClientCAs = c.RootCAs
|
|
c.ClientAuth = tls.RequireAndVerifyClientCert
|
|
c.GetCertificate = func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
|
|
p, e := tls.LoadX509KeyPair(os.Getenv("TLS_CERT_FILE"), os.Getenv("TLS_KEY_FILE"))
|
|
return &p, e
|
|
}
|
|
c.VerifyConnection = func(s tls.ConnectionState) error {
|
|
if len(s.PeerCertificates) == 0 {
|
|
return fmt.Errorf("client identity missing")
|
|
}
|
|
cert := s.PeerCertificates[0]
|
|
for _, san := range cert.DNSNames {
|
|
if san == "lb" || san == os.Getenv("TLS_SERVER_NAME") {
|
|
revoked, _ := os.ReadFile("/run/ca/revoked-serials")
|
|
if strings.Contains("\n"+string(revoked)+"\n", "\n"+cert.SerialNumber.Text(16)+"\n") {
|
|
return fmt.Errorf("revoked identity")
|
|
}
|
|
return nil
|
|
}
|
|
}
|
|
return fmt.Errorf("client identity denied")
|
|
}
|
|
return c, nil
|
|
}
|