forked from mtusi2026/mtusi2026lab7
88 lines
2.3 KiB
Go
88 lines
2.3 KiB
Go
// Package transportsecurity centralizes verified TLS. It never enables insecure verification.
|
|
package transportsecurity
|
|
|
|
import (
|
|
"crypto/tls"
|
|
"crypto/x509"
|
|
"encoding/pem"
|
|
"errors"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
func Directory() string {
|
|
if p := os.Getenv("TLS_IDENTITY_DIR"); p != "" {
|
|
return p
|
|
}
|
|
return "/run/identity"
|
|
}
|
|
func roots() (*x509.CertPool, error) {
|
|
b, err := os.ReadFile(filepath.Join(Directory(), "ca.crt"))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
p := x509.NewCertPool()
|
|
if !p.AppendCertsFromPEM(b) {
|
|
return nil, errors.New("invalid TLS CA")
|
|
}
|
|
return p, nil
|
|
}
|
|
func Client() (*tls.Config, error) {
|
|
roots, err := roots()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
cert, err := tls.LoadX509KeyPair(filepath.Join(Directory(), "tls.crt"), filepath.Join(Directory(), "tls.key"))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &tls.Config{MinVersion: tls.VersionTLS12, RootCAs: roots, Certificates: []tls.Certificate{cert}}, nil
|
|
}
|
|
func Server(allowed ...string) (*tls.Config, error) {
|
|
c, err := Client()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
c.ClientCAs = c.RootCAs
|
|
c.ClientAuth = tls.RequireAndVerifyClientCert
|
|
c.SessionTicketsDisabled = true
|
|
c.VerifyConnection = func(s tls.ConnectionState) error {
|
|
if len(s.VerifiedChains) == 0 {
|
|
return errors.New("unverified client")
|
|
}
|
|
leaf := s.PeerCertificates[0]
|
|
b, e := os.ReadFile(filepath.Join(Directory(), "ca.crl"))
|
|
if e != nil {
|
|
return errors.New("revocation list unavailable")
|
|
}
|
|
block, _ := pem.Decode(b)
|
|
if block == nil {
|
|
return errors.New("invalid revocation list")
|
|
}
|
|
crl, e := x509.ParseRevocationList(block.Bytes)
|
|
if e != nil || len(s.VerifiedChains[0]) < 2 {
|
|
return errors.New("invalid revocation list")
|
|
}
|
|
if crl.CheckSignatureFrom(s.VerifiedChains[0][1]) != nil || time.Now().After(crl.NextUpdate) {
|
|
return errors.New("untrusted or stale revocation list")
|
|
}
|
|
for _, entry := range crl.RevokedCertificateEntries {
|
|
if entry.SerialNumber.Cmp(leaf.SerialNumber) == 0 {
|
|
return errors.New("revoked client")
|
|
}
|
|
}
|
|
for _, san := range leaf.DNSNames {
|
|
for _, a := range allowed {
|
|
if san == a {
|
|
return nil
|
|
}
|
|
}
|
|
}
|
|
return errors.New("client identity denied")
|
|
}
|
|
return c, nil
|
|
}
|
|
func Enabled() bool { return strings.EqualFold(os.Getenv("TLS_REQUIRED"), "true") }
|