forked from mtusi2026/mtusi2026lab7
55 lines
1.5 KiB
Go
55 lines
1.5 KiB
Go
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
|
|
}
|