forked from mtusi2026/mtusi2026lab7
feat: enforce TLS service identities
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
package tlsconfig
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
)
|
||||
|
||||
type ServerConfig struct {
|
||||
CAPath string
|
||||
CertificatePath string
|
||||
PrivateKeyPath string
|
||||
AllowedClientURI string
|
||||
}
|
||||
|
||||
func LoadServer(config ServerConfig) (*tls.Config, error) {
|
||||
allowedURI, err := url.Parse(config.AllowedClientURI)
|
||||
if err != nil || allowedURI.Scheme == "" || allowedURI.Host == "" || allowedURI.String() != config.AllowedClientURI {
|
||||
return nil, errors.New("allowed client URI must be an absolute canonical URI")
|
||||
}
|
||||
caPEM, err := os.ReadFile(config.CAPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read client CA: %w", err)
|
||||
}
|
||||
clientCAs := x509.NewCertPool()
|
||||
if !clientCAs.AppendCertsFromPEM(caPEM) {
|
||||
return nil, errors.New("client CA does not contain a certificate")
|
||||
}
|
||||
certificate, err := tls.LoadX509KeyPair(config.CertificatePath, config.PrivateKeyPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load server certificate: %w", err)
|
||||
}
|
||||
|
||||
return &tls.Config{
|
||||
MinVersion: tls.VersionTLS13,
|
||||
Certificates: []tls.Certificate{certificate},
|
||||
ClientAuth: tls.RequireAndVerifyClientCert,
|
||||
ClientCAs: clientCAs,
|
||||
VerifyConnection: func(state tls.ConnectionState) error {
|
||||
if len(state.PeerCertificates) == 0 {
|
||||
return errors.New("client certificate is required")
|
||||
}
|
||||
for _, identity := range state.PeerCertificates[0].URIs {
|
||||
if identity.String() == config.AllowedClientURI {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("client certificate URI SAN is not allowed: want %s", config.AllowedClientURI)
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package tlsconfig
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/pem"
|
||||
"math/big"
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const allowedClientURI = "spiffe://mtusi/lab7/load-balancer"
|
||||
|
||||
func TestServerRequiresAllowedClientIdentity(t *testing.T) {
|
||||
files := issueTestCertificates(t)
|
||||
serverConfig, err := LoadServer(ServerConfig{
|
||||
CAPath: files.caPath, CertificatePath: files.serverCertificatePath,
|
||||
PrivateKeyPath: files.serverPrivateKeyPath, AllowedClientURI: allowedClientURI,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
certificatePath string
|
||||
privateKeyPath string
|
||||
wantServerError bool
|
||||
}{
|
||||
{name: "allowed identity", certificatePath: files.allowedCertificatePath, privateKeyPath: files.allowedPrivateKeyPath},
|
||||
{name: "other identity from trusted CA", certificatePath: files.otherCertificatePath, privateKeyPath: files.otherPrivateKeyPath, wantServerError: true},
|
||||
{name: "missing certificate", wantServerError: true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
clientConfig := &tls.Config{RootCAs: files.caPool, ServerName: "api.internal", MinVersion: tls.VersionTLS13}
|
||||
if tt.certificatePath != "" {
|
||||
certificate, loadErr := tls.LoadX509KeyPair(tt.certificatePath, tt.privateKeyPath)
|
||||
require.NoError(t, loadErr)
|
||||
clientConfig.Certificates = []tls.Certificate{certificate}
|
||||
}
|
||||
serverErr, clientErr := handshake(serverConfig, clientConfig)
|
||||
if tt.wantServerError {
|
||||
require.Error(t, serverErr)
|
||||
return
|
||||
}
|
||||
require.NoError(t, serverErr)
|
||||
require.NoError(t, clientErr)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadServerRejectsInvalidClientCA(t *testing.T) {
|
||||
directory := t.TempDir()
|
||||
caPath := filepath.Join(directory, "ca.pem")
|
||||
require.NoError(t, os.WriteFile(caPath, []byte("not a certificate"), 0o600))
|
||||
|
||||
_, err := LoadServer(ServerConfig{CAPath: caPath, AllowedClientURI: allowedClientURI})
|
||||
require.ErrorContains(t, err, "client CA does not contain a certificate")
|
||||
}
|
||||
|
||||
func handshake(serverConfig, clientConfig *tls.Config) (error, error) {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
return err, err
|
||||
}
|
||||
defer listener.Close()
|
||||
serverResult := make(chan error, 1)
|
||||
go func() {
|
||||
connection, acceptErr := listener.Accept()
|
||||
if acceptErr != nil {
|
||||
serverResult <- acceptErr
|
||||
return
|
||||
}
|
||||
server := tls.Server(connection, serverConfig)
|
||||
serverResult <- server.Handshake()
|
||||
_ = server.Close()
|
||||
}()
|
||||
client, clientErr := tls.Dial("tcp", listener.Addr().String(), clientConfig)
|
||||
if client != nil {
|
||||
_ = client.Close()
|
||||
}
|
||||
serverErr := <-serverResult
|
||||
return serverErr, clientErr
|
||||
}
|
||||
|
||||
type testCertificateFiles struct {
|
||||
caPath string
|
||||
serverCertificatePath string
|
||||
serverPrivateKeyPath string
|
||||
allowedCertificatePath string
|
||||
allowedPrivateKeyPath string
|
||||
otherCertificatePath string
|
||||
otherPrivateKeyPath string
|
||||
caPool *x509.CertPool
|
||||
}
|
||||
|
||||
func issueTestCertificates(t *testing.T) testCertificateFiles {
|
||||
t.Helper()
|
||||
directory := t.TempDir()
|
||||
caCertificate, caKey := issueCA(t)
|
||||
caPath := filepath.Join(directory, "ca.pem")
|
||||
writeCertificate(t, caPath, caCertificate.Raw)
|
||||
caPool := x509.NewCertPool()
|
||||
caPool.AddCert(caCertificate)
|
||||
|
||||
serverCertificatePath, serverPrivateKeyPath := issueLeaf(t, directory, caCertificate, caKey, "server", nil, []string{"api.internal"}, x509.ExtKeyUsageServerAuth)
|
||||
allowed := mustParseURI(t, allowedClientURI)
|
||||
allowedCertificatePath, allowedPrivateKeyPath := issueLeaf(t, directory, caCertificate, caKey, "allowed", []*url.URL{allowed}, nil, x509.ExtKeyUsageClientAuth)
|
||||
other := mustParseURI(t, "spiffe://mtusi/lab7/worker")
|
||||
otherCertificatePath, otherPrivateKeyPath := issueLeaf(t, directory, caCertificate, caKey, "other", []*url.URL{other}, nil, x509.ExtKeyUsageClientAuth)
|
||||
|
||||
return testCertificateFiles{
|
||||
caPath: caPath, serverCertificatePath: serverCertificatePath, serverPrivateKeyPath: serverPrivateKeyPath,
|
||||
allowedCertificatePath: allowedCertificatePath, allowedPrivateKeyPath: allowedPrivateKeyPath,
|
||||
otherCertificatePath: otherCertificatePath, otherPrivateKeyPath: otherPrivateKeyPath, caPool: caPool,
|
||||
}
|
||||
}
|
||||
|
||||
func issueCA(t *testing.T) (*x509.Certificate, *ecdsa.PrivateKey) {
|
||||
t.Helper()
|
||||
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
require.NoError(t, err)
|
||||
template := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "test CA"},
|
||||
NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour),
|
||||
IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign,
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
|
||||
require.NoError(t, err)
|
||||
certificate, err := x509.ParseCertificate(der)
|
||||
require.NoError(t, err)
|
||||
return certificate, key
|
||||
}
|
||||
|
||||
func issueLeaf(
|
||||
t *testing.T,
|
||||
directory string,
|
||||
ca *x509.Certificate,
|
||||
caKey *ecdsa.PrivateKey,
|
||||
name string,
|
||||
identities []*url.URL,
|
||||
dnsNames []string,
|
||||
usage x509.ExtKeyUsage,
|
||||
) (string, string) {
|
||||
t.Helper()
|
||||
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
require.NoError(t, err)
|
||||
template := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(time.Now().UnixNano()), Subject: pkix.Name{CommonName: name},
|
||||
NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour),
|
||||
KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{usage},
|
||||
URIs: identities, DNSNames: dnsNames,
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, template, ca, &key.PublicKey, caKey)
|
||||
require.NoError(t, err)
|
||||
certificatePath := filepath.Join(directory, name+".crt")
|
||||
privateKeyPath := filepath.Join(directory, name+".key")
|
||||
writeCertificate(t, certificatePath, der)
|
||||
keyDER, err := x509.MarshalPKCS8PrivateKey(key)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.WriteFile(privateKeyPath, pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER}), 0o600))
|
||||
return certificatePath, privateKeyPath
|
||||
}
|
||||
|
||||
func writeCertificate(t *testing.T, path string, der []byte) {
|
||||
t.Helper()
|
||||
require.NoError(t, os.WriteFile(path, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0o600))
|
||||
}
|
||||
|
||||
func mustParseURI(t *testing.T, value string) *url.URL {
|
||||
t.Helper()
|
||||
identity, err := url.Parse(value)
|
||||
require.NoError(t, err)
|
||||
return identity
|
||||
}
|
||||
Reference in New Issue
Block a user