feat: secure service connections and login

This commit is contained in:
2026-11-06 21:14:49 +03:00
parent cb51354889
commit 48918e8b19
59 changed files with 1980 additions and 316 deletions
+95
View File
@@ -0,0 +1,95 @@
package mtlsproxy
import (
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"net"
"sync"
"time"
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/security/tlsconfig"
)
type Config struct {
ListenAddress string
TargetAddress string
CAPath string
CertificatePath string
PrivateKeyPath string
AllowedClientURI string
ALPNProtocols []string
DialTimeout time.Duration
}
func Run(ctx context.Context, config Config) error {
if config.ListenAddress == "" || config.TargetAddress == "" || config.DialTimeout <= 0 {
return errors.New("invalid mTLS proxy configuration")
}
tlsConfiguration, err := tlsconfig.LoadServer(tlsconfig.ServerConfig{
CAPath: config.CAPath, CertificatePath: config.CertificatePath,
PrivateKeyPath: config.PrivateKeyPath, AllowedClientURI: config.AllowedClientURI,
})
if err != nil {
return err
}
tlsConfiguration.NextProtos = config.ALPNProtocols
listener, err := net.Listen("tcp", config.ListenAddress)
if err != nil {
return fmt.Errorf("listen: %w", err)
}
defer listener.Close()
go func() {
<-ctx.Done()
_ = listener.Close()
}()
var connections sync.WaitGroup
defer connections.Wait()
for {
connection, err := listener.Accept()
if err != nil {
if ctx.Err() != nil {
return nil
}
return fmt.Errorf("accept: %w", err)
}
connections.Add(1)
go func() {
defer connections.Done()
serve(ctx, connection, config, tlsConfiguration)
}()
}
}
func serve(ctx context.Context, connection net.Conn, config Config, tlsConfiguration *tls.Config) {
client := tls.Server(connection, tlsConfiguration)
defer client.Close()
handshakeCtx, cancel := context.WithTimeout(ctx, config.DialTimeout)
defer cancel()
if err := client.HandshakeContext(handshakeCtx); err != nil {
return
}
target, err := (&net.Dialer{Timeout: config.DialTimeout}).DialContext(ctx, "tcp", config.TargetAddress)
if err != nil {
return
}
defer target.Close()
result := make(chan struct{}, 2)
copyConnection := func(destination, source net.Conn) {
_, _ = io.Copy(destination, source)
if writer, ok := destination.(interface{ CloseWrite() error }); ok {
_ = writer.CloseWrite()
}
result <- struct{}{}
}
go copyConnection(target, client)
go copyConnection(client, target)
select {
case <-ctx.Done():
case <-result:
}
}
+50
View File
@@ -0,0 +1,50 @@
package tlsconfig
import (
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"os"
"strings"
)
type ClientConfig struct {
CAPath string
CertificatePath string
PrivateKeyPath string
ServerName string
}
func LoadClient(config ClientConfig) (*tls.Config, error) {
if strings.TrimSpace(config.ServerName) == "" {
return nil, errors.New("TLS server name is required")
}
caPEM, err := os.ReadFile(config.CAPath)
if err != nil {
return nil, fmt.Errorf("read server CA: %w", err)
}
roots := x509.NewCertPool()
if !roots.AppendCertsFromPEM(caPEM) {
return nil, errors.New("server CA does not contain a certificate")
}
var certificates []tls.Certificate
if config.CertificatePath != "" || config.PrivateKeyPath != "" {
if config.CertificatePath == "" || config.PrivateKeyPath == "" {
return nil, errors.New("TLS client certificate and private key must be configured together")
}
certificate, err := tls.LoadX509KeyPair(config.CertificatePath, config.PrivateKeyPath)
if err != nil {
return nil, fmt.Errorf("load client certificate: %w", err)
}
certificates = []tls.Certificate{certificate}
}
return &tls.Config{
MinVersion: tls.VersionTLS13,
RootCAs: roots,
Certificates: certificates,
ServerName: config.ServerName,
}, nil
}
@@ -0,0 +1,60 @@
package tlsconfig
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestLoadClientLoadsTrustAndIdentity(t *testing.T) {
caPath, certificatePath, keyPath := writeClientCertificate(t)
configuration, err := LoadClient(ClientConfig{
CAPath: caPath, CertificatePath: certificatePath, PrivateKeyPath: keyPath, ServerName: "collector",
})
require.NoError(t, err)
require.Equal(t, uint16(0x0304), configuration.MinVersion)
require.Equal(t, "collector", configuration.ServerName)
require.Len(t, configuration.Certificates, 1)
require.NotNil(t, configuration.RootCAs)
}
func TestLoadClientRejectsPartialIdentity(t *testing.T) {
caPath, certificatePath, _ := writeClientCertificate(t)
_, err := LoadClient(ClientConfig{CAPath: caPath, CertificatePath: certificatePath, ServerName: "collector"})
require.ErrorContains(t, err, "configured together")
}
func writeClientCertificate(t *testing.T) (string, string, string) {
t.Helper()
directory := t.TempDir()
key, err := rsa.GenerateKey(rand.Reader, 2048)
require.NoError(t, err)
template := &x509.Certificate{
SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "test"},
NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
BasicConstraintsValid: true, IsCA: true,
}
der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
require.NoError(t, err)
certificate := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
privateKey := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
caPath := filepath.Join(directory, "ca.crt")
certificatePath := filepath.Join(directory, "tls.crt")
keyPath := filepath.Join(directory, "tls.key")
require.NoError(t, os.WriteFile(caPath, certificate, 0o600))
require.NoError(t, os.WriteFile(certificatePath, certificate, 0o600))
require.NoError(t, os.WriteFile(keyPath, privateKey, 0o600))
return caPath, certificatePath, keyPath
}
+54
View File
@@ -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
}
+185
View File
@@ -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
}