mirror of
https://github.com/netbirdio/netbird.git
synced 2026-04-18 08:16:39 +00:00
[proxy] Wildcard certificate support (#5583)
This commit is contained in:
@@ -53,6 +53,7 @@ var (
|
|||||||
certFile string
|
certFile string
|
||||||
certKeyFile string
|
certKeyFile string
|
||||||
certLockMethod string
|
certLockMethod string
|
||||||
|
wildcardCertDir string
|
||||||
wgPort int
|
wgPort int
|
||||||
proxyProtocol bool
|
proxyProtocol bool
|
||||||
preSharedKey string
|
preSharedKey string
|
||||||
@@ -87,6 +88,7 @@ func init() {
|
|||||||
rootCmd.Flags().StringVar(&certFile, "cert-file", envStringOrDefault("NB_PROXY_CERTIFICATE_FILE", "tls.crt"), "TLS certificate filename within the certificate directory")
|
rootCmd.Flags().StringVar(&certFile, "cert-file", envStringOrDefault("NB_PROXY_CERTIFICATE_FILE", "tls.crt"), "TLS certificate filename within the certificate directory")
|
||||||
rootCmd.Flags().StringVar(&certKeyFile, "cert-key-file", envStringOrDefault("NB_PROXY_CERTIFICATE_KEY_FILE", "tls.key"), "TLS certificate key filename within the certificate directory")
|
rootCmd.Flags().StringVar(&certKeyFile, "cert-key-file", envStringOrDefault("NB_PROXY_CERTIFICATE_KEY_FILE", "tls.key"), "TLS certificate key filename within the certificate directory")
|
||||||
rootCmd.Flags().StringVar(&certLockMethod, "cert-lock-method", envStringOrDefault("NB_PROXY_CERT_LOCK_METHOD", "auto"), "Certificate lock method for cross-replica coordination: auto, flock, or k8s-lease")
|
rootCmd.Flags().StringVar(&certLockMethod, "cert-lock-method", envStringOrDefault("NB_PROXY_CERT_LOCK_METHOD", "auto"), "Certificate lock method for cross-replica coordination: auto, flock, or k8s-lease")
|
||||||
|
rootCmd.Flags().StringVar(&wildcardCertDir, "wildcard-cert-dir", envStringOrDefault("NB_PROXY_WILDCARD_CERT_DIR", ""), "Directory containing wildcard certificate pairs (<name>.crt/<name>.key). Wildcard patterns are extracted from SANs automatically")
|
||||||
rootCmd.Flags().IntVar(&wgPort, "wg-port", envIntOrDefault("NB_PROXY_WG_PORT", 0), "WireGuard listen port (0 = random). Fixed port only works with single-account deployments")
|
rootCmd.Flags().IntVar(&wgPort, "wg-port", envIntOrDefault("NB_PROXY_WG_PORT", 0), "WireGuard listen port (0 = random). Fixed port only works with single-account deployments")
|
||||||
rootCmd.Flags().BoolVar(&proxyProtocol, "proxy-protocol", envBoolOrDefault("NB_PROXY_PROXY_PROTOCOL", false), "Enable PROXY protocol on TCP listeners to preserve client IPs behind L4 proxies")
|
rootCmd.Flags().BoolVar(&proxyProtocol, "proxy-protocol", envBoolOrDefault("NB_PROXY_PROXY_PROTOCOL", false), "Enable PROXY protocol on TCP listeners to preserve client IPs behind L4 proxies")
|
||||||
rootCmd.Flags().StringVar(&preSharedKey, "preshared-key", envStringOrDefault("NB_PROXY_PRESHARED_KEY", ""), "Define a pre-shared key for the tunnel between proxy and peers")
|
rootCmd.Flags().StringVar(&preSharedKey, "preshared-key", envStringOrDefault("NB_PROXY_PRESHARED_KEY", ""), "Define a pre-shared key for the tunnel between proxy and peers")
|
||||||
@@ -162,6 +164,7 @@ func runServer(cmd *cobra.Command, args []string) error {
|
|||||||
ForwardedProto: forwardedProto,
|
ForwardedProto: forwardedProto,
|
||||||
TrustedProxies: parsedTrustedProxies,
|
TrustedProxies: parsedTrustedProxies,
|
||||||
CertLockMethod: nbacme.CertLockMethod(certLockMethod),
|
CertLockMethod: nbacme.CertLockMethod(certLockMethod),
|
||||||
|
WildcardCertDir: wildcardCertDir,
|
||||||
WireguardPort: wgPort,
|
WireguardPort: wgPort,
|
||||||
ProxyProtocol: proxyProtocol,
|
ProxyProtocol: proxyProtocol,
|
||||||
PreSharedKey: preSharedKey,
|
PreSharedKey: preSharedKey,
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"math/rand/v2"
|
"math/rand/v2"
|
||||||
"net"
|
"net"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
"slices"
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
@@ -20,6 +22,7 @@ import (
|
|||||||
"golang.org/x/crypto/acme"
|
"golang.org/x/crypto/acme"
|
||||||
"golang.org/x/crypto/acme/autocert"
|
"golang.org/x/crypto/acme/autocert"
|
||||||
|
|
||||||
|
"github.com/netbirdio/netbird/proxy/internal/certwatch"
|
||||||
"github.com/netbirdio/netbird/shared/management/domain"
|
"github.com/netbirdio/netbird/shared/management/domain"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -49,6 +52,34 @@ type metricsRecorder interface {
|
|||||||
RecordCertificateIssuance(duration time.Duration)
|
RecordCertificateIssuance(duration time.Duration)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// wildcardEntry maps a domain suffix (e.g. ".example.com") to a certwatch
|
||||||
|
// watcher that hot-reloads the corresponding wildcard certificate from disk.
|
||||||
|
type wildcardEntry struct {
|
||||||
|
suffix string // e.g. ".example.com"
|
||||||
|
pattern string // e.g. "*.example.com"
|
||||||
|
watcher *certwatch.Watcher
|
||||||
|
}
|
||||||
|
|
||||||
|
// ManagerConfig holds the configuration values for the ACME certificate manager.
|
||||||
|
type ManagerConfig struct {
|
||||||
|
// CertDir is the directory used for caching ACME certificates.
|
||||||
|
CertDir string
|
||||||
|
// ACMEURL is the ACME directory URL (e.g. Let's Encrypt).
|
||||||
|
ACMEURL string
|
||||||
|
// EABKID and EABHMACKey are optional External Account Binding credentials
|
||||||
|
// required by some CAs (e.g. ZeroSSL). EABHMACKey is the base64
|
||||||
|
// URL-encoded string provided by the CA.
|
||||||
|
EABKID string
|
||||||
|
EABHMACKey string
|
||||||
|
// LockMethod controls the cross-replica coordination strategy.
|
||||||
|
LockMethod CertLockMethod
|
||||||
|
// WildcardDir is an optional path to a directory containing wildcard
|
||||||
|
// certificate pairs (<name>.crt / <name>.key). Wildcard patterns are
|
||||||
|
// extracted from the certificates' SAN lists. Domains matching a
|
||||||
|
// wildcard are served from disk; all others go through ACME.
|
||||||
|
WildcardDir string
|
||||||
|
}
|
||||||
|
|
||||||
// Manager wraps autocert.Manager with domain tracking and cross-replica
|
// Manager wraps autocert.Manager with domain tracking and cross-replica
|
||||||
// coordination via a pluggable locking strategy. The locker prevents
|
// coordination via a pluggable locking strategy. The locker prevents
|
||||||
// duplicate ACME requests when multiple replicas share a certificate cache.
|
// duplicate ACME requests when multiple replicas share a certificate cache.
|
||||||
@@ -60,54 +91,182 @@ type Manager struct {
|
|||||||
mu sync.RWMutex
|
mu sync.RWMutex
|
||||||
domains map[domain.Domain]*domainInfo
|
domains map[domain.Domain]*domainInfo
|
||||||
|
|
||||||
|
// wildcards holds all loaded wildcard certificates, keyed by suffix.
|
||||||
|
wildcards []wildcardEntry
|
||||||
|
|
||||||
certNotifier certificateNotifier
|
certNotifier certificateNotifier
|
||||||
logger *log.Logger
|
logger *log.Logger
|
||||||
metrics metricsRecorder
|
metrics metricsRecorder
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewManager creates a new ACME certificate manager. The certDir is used
|
// NewManager creates a new ACME certificate manager.
|
||||||
// for caching certificates. The lockMethod controls cross-replica
|
func NewManager(cfg ManagerConfig, notifier certificateNotifier, logger *log.Logger, metrics metricsRecorder) (*Manager, error) {
|
||||||
// coordination strategy (see CertLockMethod constants).
|
|
||||||
// eabKID and eabHMACKey are optional External Account Binding credentials
|
|
||||||
// required for some CAs like ZeroSSL. The eabHMACKey should be the base64
|
|
||||||
// URL-encoded string provided by the CA.
|
|
||||||
func NewManager(certDir, acmeURL, eabKID, eabHMACKey string, notifier certificateNotifier, logger *log.Logger, lockMethod CertLockMethod, metrics metricsRecorder) *Manager {
|
|
||||||
if logger == nil {
|
if logger == nil {
|
||||||
logger = log.StandardLogger()
|
logger = log.StandardLogger()
|
||||||
}
|
}
|
||||||
mgr := &Manager{
|
mgr := &Manager{
|
||||||
certDir: certDir,
|
certDir: cfg.CertDir,
|
||||||
locker: newCertLocker(lockMethod, certDir, logger),
|
locker: newCertLocker(cfg.LockMethod, cfg.CertDir, logger),
|
||||||
domains: make(map[domain.Domain]*domainInfo),
|
domains: make(map[domain.Domain]*domainInfo),
|
||||||
certNotifier: notifier,
|
certNotifier: notifier,
|
||||||
logger: logger,
|
logger: logger,
|
||||||
metrics: metrics,
|
metrics: metrics,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if cfg.WildcardDir != "" {
|
||||||
|
entries, err := loadWildcardDir(cfg.WildcardDir, logger)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("load wildcard certificates from %q: %w", cfg.WildcardDir, err)
|
||||||
|
}
|
||||||
|
mgr.wildcards = entries
|
||||||
|
}
|
||||||
|
|
||||||
var eab *acme.ExternalAccountBinding
|
var eab *acme.ExternalAccountBinding
|
||||||
if eabKID != "" && eabHMACKey != "" {
|
if cfg.EABKID != "" && cfg.EABHMACKey != "" {
|
||||||
decodedKey, err := base64.RawURLEncoding.DecodeString(eabHMACKey)
|
decodedKey, err := base64.RawURLEncoding.DecodeString(cfg.EABHMACKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Errorf("failed to decode EAB HMAC key: %v", err)
|
logger.Errorf("failed to decode EAB HMAC key: %v", err)
|
||||||
} else {
|
} else {
|
||||||
eab = &acme.ExternalAccountBinding{
|
eab = &acme.ExternalAccountBinding{
|
||||||
KID: eabKID,
|
KID: cfg.EABKID,
|
||||||
Key: decodedKey,
|
Key: decodedKey,
|
||||||
}
|
}
|
||||||
logger.Infof("configured External Account Binding with KID: %s", eabKID)
|
logger.Infof("configured External Account Binding with KID: %s", cfg.EABKID)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
mgr.Manager = &autocert.Manager{
|
mgr.Manager = &autocert.Manager{
|
||||||
Prompt: autocert.AcceptTOS,
|
Prompt: autocert.AcceptTOS,
|
||||||
HostPolicy: mgr.hostPolicy,
|
HostPolicy: mgr.hostPolicy,
|
||||||
Cache: autocert.DirCache(certDir),
|
Cache: autocert.DirCache(cfg.CertDir),
|
||||||
ExternalAccountBinding: eab,
|
ExternalAccountBinding: eab,
|
||||||
Client: &acme.Client{
|
Client: &acme.Client{
|
||||||
DirectoryURL: acmeURL,
|
DirectoryURL: cfg.ACMEURL,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
return mgr
|
return mgr, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// WatchWildcards starts watching all wildcard certificate files for changes.
|
||||||
|
// It blocks until ctx is cancelled. It is a no-op if no wildcards are loaded.
|
||||||
|
func (mgr *Manager) WatchWildcards(ctx context.Context) {
|
||||||
|
if len(mgr.wildcards) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
seen := make(map[*certwatch.Watcher]struct{})
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
for i := range mgr.wildcards {
|
||||||
|
w := mgr.wildcards[i].watcher
|
||||||
|
if _, ok := seen[w]; ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[w] = struct{}{}
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
w.Watch(ctx)
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadWildcardDir scans dir for .crt files, pairs each with a matching .key
|
||||||
|
// file, loads them, and extracts wildcard SANs (*.example.com) to build
|
||||||
|
// the suffix lookup entries.
|
||||||
|
func loadWildcardDir(dir string, logger *log.Logger) ([]wildcardEntry, error) {
|
||||||
|
crtFiles, err := filepath.Glob(filepath.Join(dir, "*.crt"))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("glob certificate files: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(crtFiles) == 0 {
|
||||||
|
return nil, fmt.Errorf("no .crt files found in %s", dir)
|
||||||
|
}
|
||||||
|
|
||||||
|
var entries []wildcardEntry
|
||||||
|
|
||||||
|
for _, crtPath := range crtFiles {
|
||||||
|
base := strings.TrimSuffix(filepath.Base(crtPath), ".crt")
|
||||||
|
keyPath := filepath.Join(dir, base+".key")
|
||||||
|
if _, err := os.Stat(keyPath); err != nil {
|
||||||
|
logger.Warnf("skipping %s: no matching key file %s", crtPath, keyPath)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
watcher, err := certwatch.NewWatcher(crtPath, keyPath, logger)
|
||||||
|
if err != nil {
|
||||||
|
logger.Warnf("skipping %s: %v", crtPath, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
leaf := watcher.Leaf()
|
||||||
|
if leaf == nil {
|
||||||
|
logger.Warnf("skipping %s: no parsed leaf certificate", crtPath)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, san := range leaf.DNSNames {
|
||||||
|
suffix, ok := parseWildcard(san)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
entries = append(entries, wildcardEntry{
|
||||||
|
suffix: suffix,
|
||||||
|
pattern: san,
|
||||||
|
watcher: watcher,
|
||||||
|
})
|
||||||
|
logger.Infof("wildcard certificate loaded: %s (from %s)", san, filepath.Base(crtPath))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(entries) == 0 {
|
||||||
|
return nil, fmt.Errorf("no wildcard SANs (*.example.com) found in certificates in %s", dir)
|
||||||
|
}
|
||||||
|
|
||||||
|
return entries, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseWildcard validates a wildcard domain pattern like "*.example.com"
|
||||||
|
// and returns the suffix ".example.com" for matching.
|
||||||
|
func parseWildcard(pattern string) (suffix string, ok bool) {
|
||||||
|
if !strings.HasPrefix(pattern, "*.") {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
parent := pattern[1:] // ".example.com"
|
||||||
|
if strings.Count(parent, ".") < 1 {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return strings.ToLower(parent), true
|
||||||
|
}
|
||||||
|
|
||||||
|
// findWildcardEntry returns the wildcard entry that covers host, or nil.
|
||||||
|
func (mgr *Manager) findWildcardEntry(host string) *wildcardEntry {
|
||||||
|
if len(mgr.wildcards) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
host = strings.ToLower(host)
|
||||||
|
for i := range mgr.wildcards {
|
||||||
|
e := &mgr.wildcards[i]
|
||||||
|
if !strings.HasSuffix(host, e.suffix) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// Single-level match: prefix before suffix must have no dots.
|
||||||
|
prefix := strings.TrimSuffix(host, e.suffix)
|
||||||
|
if len(prefix) > 0 && !strings.Contains(prefix, ".") {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// WildcardPatterns returns the wildcard patterns that are currently loaded.
|
||||||
|
func (mgr *Manager) WildcardPatterns() []string {
|
||||||
|
patterns := make([]string, len(mgr.wildcards))
|
||||||
|
for i, e := range mgr.wildcards {
|
||||||
|
patterns[i] = e.pattern
|
||||||
|
}
|
||||||
|
slices.Sort(patterns)
|
||||||
|
return patterns
|
||||||
}
|
}
|
||||||
|
|
||||||
func (mgr *Manager) hostPolicy(_ context.Context, host string) error {
|
func (mgr *Manager) hostPolicy(_ context.Context, host string) error {
|
||||||
@@ -123,8 +282,39 @@ func (mgr *Manager) hostPolicy(_ context.Context, host string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// AddDomain registers a domain for ACME certificate prefetching.
|
// GetCertificate returns the TLS certificate for the given ClientHello.
|
||||||
func (mgr *Manager) AddDomain(d domain.Domain, accountID, serviceID string) {
|
// If the requested domain matches a loaded wildcard, the static wildcard
|
||||||
|
// certificate is returned. Otherwise, the ACME autocert manager handles
|
||||||
|
// the request.
|
||||||
|
func (mgr *Manager) GetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
|
||||||
|
if e := mgr.findWildcardEntry(hello.ServerName); e != nil {
|
||||||
|
return e.watcher.GetCertificate(hello)
|
||||||
|
}
|
||||||
|
return mgr.Manager.GetCertificate(hello)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddDomain registers a domain for certificate management. Domains that
|
||||||
|
// match a loaded wildcard are marked ready immediately (they use the
|
||||||
|
// static wildcard certificate) and the method returns true. All other
|
||||||
|
// domains go through ACME prefetch and the method returns false.
|
||||||
|
//
|
||||||
|
// When AddDomain returns true the caller is responsible for sending any
|
||||||
|
// certificate-ready notifications after the surrounding operation (e.g.
|
||||||
|
// mapping update) has committed successfully.
|
||||||
|
func (mgr *Manager) AddDomain(d domain.Domain, accountID, serviceID string) (wildcardHit bool) {
|
||||||
|
name := d.PunycodeString()
|
||||||
|
if e := mgr.findWildcardEntry(name); e != nil {
|
||||||
|
mgr.mu.Lock()
|
||||||
|
mgr.domains[d] = &domainInfo{
|
||||||
|
accountID: accountID,
|
||||||
|
serviceID: serviceID,
|
||||||
|
state: domainReady,
|
||||||
|
}
|
||||||
|
mgr.mu.Unlock()
|
||||||
|
mgr.logger.Debugf("domain %q matches wildcard %q, using static certificate", name, e.pattern)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
mgr.mu.Lock()
|
mgr.mu.Lock()
|
||||||
mgr.domains[d] = &domainInfo{
|
mgr.domains[d] = &domainInfo{
|
||||||
accountID: accountID,
|
accountID: accountID,
|
||||||
@@ -134,6 +324,7 @@ func (mgr *Manager) AddDomain(d domain.Domain, accountID, serviceID string) {
|
|||||||
mgr.mu.Unlock()
|
mgr.mu.Unlock()
|
||||||
|
|
||||||
go mgr.prefetchCertificate(d)
|
go mgr.prefetchCertificate(d)
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// prefetchCertificate proactively triggers certificate generation for a domain.
|
// prefetchCertificate proactively triggers certificate generation for a domain.
|
||||||
|
|||||||
@@ -2,6 +2,16 @@ package acme
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"crypto/ecdsa"
|
||||||
|
"crypto/elliptic"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/tls"
|
||||||
|
"crypto/x509"
|
||||||
|
"crypto/x509/pkix"
|
||||||
|
"encoding/pem"
|
||||||
|
"math/big"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -10,7 +20,8 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func TestHostPolicy(t *testing.T) {
|
func TestHostPolicy(t *testing.T) {
|
||||||
mgr := NewManager(t.TempDir(), "https://acme.example.com/directory", "", "", nil, nil, "", nil)
|
mgr, err := NewManager(ManagerConfig{CertDir: t.TempDir(), ACMEURL: "https://acme.example.com/directory"}, nil, nil, nil)
|
||||||
|
require.NoError(t, err)
|
||||||
mgr.AddDomain("example.com", "acc1", "rp1")
|
mgr.AddDomain("example.com", "acc1", "rp1")
|
||||||
|
|
||||||
// Wait for the background prefetch goroutine to finish so the temp dir
|
// Wait for the background prefetch goroutine to finish so the temp dir
|
||||||
@@ -70,7 +81,8 @@ func TestHostPolicy(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestDomainStates(t *testing.T) {
|
func TestDomainStates(t *testing.T) {
|
||||||
mgr := NewManager(t.TempDir(), "https://acme.example.com/directory", "", "", nil, nil, "", nil)
|
mgr, err := NewManager(ManagerConfig{CertDir: t.TempDir(), ACMEURL: "https://acme.example.com/directory"}, nil, nil, nil)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
assert.Equal(t, 0, mgr.PendingCerts(), "initially zero")
|
assert.Equal(t, 0, mgr.PendingCerts(), "initially zero")
|
||||||
assert.Equal(t, 0, mgr.TotalDomains(), "initially zero domains")
|
assert.Equal(t, 0, mgr.TotalDomains(), "initially zero domains")
|
||||||
@@ -100,3 +112,193 @@ func TestDomainStates(t *testing.T) {
|
|||||||
assert.Contains(t, failed, "b.example.com")
|
assert.Contains(t, failed, "b.example.com")
|
||||||
assert.Empty(t, mgr.ReadyDomains())
|
assert.Empty(t, mgr.ReadyDomains())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestParseWildcard(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
pattern string
|
||||||
|
wantSuffix string
|
||||||
|
wantOK bool
|
||||||
|
}{
|
||||||
|
{"*.example.com", ".example.com", true},
|
||||||
|
{"*.foo.example.com", ".foo.example.com", true},
|
||||||
|
{"*.COM", ".com", true}, // single-label TLD
|
||||||
|
{"example.com", "", false}, // no wildcard prefix
|
||||||
|
{"*example.com", "", false}, // missing dot
|
||||||
|
{"**.example.com", "", false}, // double star
|
||||||
|
{"", "", false},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
t.Run(tc.pattern, func(t *testing.T) {
|
||||||
|
suffix, ok := parseWildcard(tc.pattern)
|
||||||
|
assert.Equal(t, tc.wantOK, ok)
|
||||||
|
if ok {
|
||||||
|
assert.Equal(t, tc.wantSuffix, suffix)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMatchesWildcard(t *testing.T) {
|
||||||
|
wcDir := t.TempDir()
|
||||||
|
generateSelfSignedCert(t, wcDir, "example", "*.example.com")
|
||||||
|
|
||||||
|
acmeDir := t.TempDir()
|
||||||
|
mgr, err := NewManager(ManagerConfig{CertDir: acmeDir, ACMEURL: "https://acme.example.com/directory", WildcardDir: wcDir}, nil, nil, nil)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
host string
|
||||||
|
match bool
|
||||||
|
}{
|
||||||
|
{"foo.example.com", true},
|
||||||
|
{"bar.example.com", true},
|
||||||
|
{"FOO.Example.COM", true}, // case insensitive
|
||||||
|
{"example.com", false}, // bare parent
|
||||||
|
{"sub.foo.example.com", false}, // multi-level
|
||||||
|
{"notexample.com", false},
|
||||||
|
{"", false},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
t.Run(tc.host, func(t *testing.T) {
|
||||||
|
assert.Equal(t, tc.match, mgr.findWildcardEntry(tc.host) != nil)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// generateSelfSignedCert creates a temporary self-signed certificate and key
|
||||||
|
// for testing purposes. The baseName controls the output filenames:
|
||||||
|
// <baseName>.crt and <baseName>.key.
|
||||||
|
func generateSelfSignedCert(t *testing.T, dir, baseName string, dnsNames ...string) {
|
||||||
|
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: dnsNames[0]},
|
||||||
|
DNSNames: dnsNames,
|
||||||
|
NotBefore: time.Now().Add(-time.Hour),
|
||||||
|
NotAfter: time.Now().Add(24 * time.Hour),
|
||||||
|
}
|
||||||
|
|
||||||
|
certDER, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
certFile, err := os.Create(filepath.Join(dir, baseName+".crt"))
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.NoError(t, pem.Encode(certFile, &pem.Block{Type: "CERTIFICATE", Bytes: certDER}))
|
||||||
|
require.NoError(t, certFile.Close())
|
||||||
|
|
||||||
|
keyDER, err := x509.MarshalECPrivateKey(key)
|
||||||
|
require.NoError(t, err)
|
||||||
|
keyFile, err := os.Create(filepath.Join(dir, baseName+".key"))
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.NoError(t, pem.Encode(keyFile, &pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER}))
|
||||||
|
require.NoError(t, keyFile.Close())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWildcardAddDomainSkipsACME(t *testing.T) {
|
||||||
|
wcDir := t.TempDir()
|
||||||
|
generateSelfSignedCert(t, wcDir, "example", "*.example.com")
|
||||||
|
|
||||||
|
acmeDir := t.TempDir()
|
||||||
|
mgr, err := NewManager(ManagerConfig{CertDir: acmeDir, ACMEURL: "https://acme.example.com/directory", WildcardDir: wcDir}, nil, nil, nil)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
// Add a wildcard-matching domain — should be immediately ready.
|
||||||
|
mgr.AddDomain("foo.example.com", "acc1", "svc1")
|
||||||
|
assert.Equal(t, 0, mgr.PendingCerts(), "wildcard domain should not be pending")
|
||||||
|
assert.Equal(t, []string{"foo.example.com"}, mgr.ReadyDomains())
|
||||||
|
|
||||||
|
// Add a non-wildcard domain — should go through ACME (pending then failed).
|
||||||
|
mgr.AddDomain("other.net", "acc2", "svc2")
|
||||||
|
assert.Equal(t, 2, mgr.TotalDomains())
|
||||||
|
|
||||||
|
// Wait for the ACME prefetch to fail.
|
||||||
|
assert.Eventually(t, func() bool {
|
||||||
|
return mgr.PendingCerts() == 0
|
||||||
|
}, 30*time.Second, 100*time.Millisecond)
|
||||||
|
|
||||||
|
assert.Equal(t, []string{"foo.example.com"}, mgr.ReadyDomains())
|
||||||
|
assert.Contains(t, mgr.FailedDomains(), "other.net")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWildcardGetCertificate(t *testing.T) {
|
||||||
|
wcDir := t.TempDir()
|
||||||
|
generateSelfSignedCert(t, wcDir, "example", "*.example.com")
|
||||||
|
|
||||||
|
acmeDir := t.TempDir()
|
||||||
|
mgr, err := NewManager(ManagerConfig{CertDir: acmeDir, ACMEURL: "https://acme.example.com/directory", WildcardDir: wcDir}, nil, nil, nil)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
mgr.AddDomain("foo.example.com", "acc1", "svc1")
|
||||||
|
|
||||||
|
// GetCertificate for a wildcard-matching domain should return the static cert.
|
||||||
|
cert, err := mgr.GetCertificate(&tls.ClientHelloInfo{ServerName: "foo.example.com"})
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.NotNil(t, cert)
|
||||||
|
assert.Contains(t, cert.Leaf.DNSNames, "*.example.com")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMultipleWildcards(t *testing.T) {
|
||||||
|
wcDir := t.TempDir()
|
||||||
|
generateSelfSignedCert(t, wcDir, "example", "*.example.com")
|
||||||
|
generateSelfSignedCert(t, wcDir, "other", "*.other.org")
|
||||||
|
|
||||||
|
acmeDir := t.TempDir()
|
||||||
|
mgr, err := NewManager(ManagerConfig{CertDir: acmeDir, ACMEURL: "https://acme.example.com/directory", WildcardDir: wcDir}, nil, nil, nil)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
assert.ElementsMatch(t, []string{"*.example.com", "*.other.org"}, mgr.WildcardPatterns())
|
||||||
|
|
||||||
|
// Both wildcards should resolve.
|
||||||
|
mgr.AddDomain("foo.example.com", "acc1", "svc1")
|
||||||
|
mgr.AddDomain("bar.other.org", "acc2", "svc2")
|
||||||
|
|
||||||
|
assert.Equal(t, 0, mgr.PendingCerts())
|
||||||
|
assert.ElementsMatch(t, []string{"foo.example.com", "bar.other.org"}, mgr.ReadyDomains())
|
||||||
|
|
||||||
|
// GetCertificate routes to the correct cert.
|
||||||
|
cert1, err := mgr.GetCertificate(&tls.ClientHelloInfo{ServerName: "foo.example.com"})
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Contains(t, cert1.Leaf.DNSNames, "*.example.com")
|
||||||
|
|
||||||
|
cert2, err := mgr.GetCertificate(&tls.ClientHelloInfo{ServerName: "bar.other.org"})
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Contains(t, cert2.Leaf.DNSNames, "*.other.org")
|
||||||
|
|
||||||
|
// Non-matching domain falls through to ACME.
|
||||||
|
mgr.AddDomain("custom.net", "acc3", "svc3")
|
||||||
|
assert.Eventually(t, func() bool {
|
||||||
|
return mgr.PendingCerts() == 0
|
||||||
|
}, 30*time.Second, 100*time.Millisecond)
|
||||||
|
assert.Contains(t, mgr.FailedDomains(), "custom.net")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWildcardDirEmpty(t *testing.T) {
|
||||||
|
wcDir := t.TempDir()
|
||||||
|
// Empty directory — no .crt files.
|
||||||
|
_, err := NewManager(ManagerConfig{CertDir: t.TempDir(), ACMEURL: "https://acme.example.com/directory", WildcardDir: wcDir}, nil, nil, nil)
|
||||||
|
require.Error(t, err)
|
||||||
|
assert.Contains(t, err.Error(), "no .crt files found")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWildcardDirNonWildcardCert(t *testing.T) {
|
||||||
|
wcDir := t.TempDir()
|
||||||
|
// Certificate without a wildcard SAN.
|
||||||
|
generateSelfSignedCert(t, wcDir, "plain", "plain.example.com")
|
||||||
|
|
||||||
|
_, err := NewManager(ManagerConfig{CertDir: t.TempDir(), ACMEURL: "https://acme.example.com/directory", WildcardDir: wcDir}, nil, nil, nil)
|
||||||
|
require.Error(t, err)
|
||||||
|
assert.Contains(t, err.Error(), "no wildcard SANs")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNoWildcardDir(t *testing.T) {
|
||||||
|
// Empty string means no wildcard dir — pure ACME mode.
|
||||||
|
mgr, err := NewManager(ManagerConfig{CertDir: t.TempDir(), ACMEURL: "https://acme.example.com/directory"}, nil, nil, nil)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Empty(t, mgr.WildcardPatterns())
|
||||||
|
}
|
||||||
|
|||||||
@@ -67,6 +67,13 @@ func (w *Watcher) GetCertificate(_ *tls.ClientHelloInfo) (*tls.Certificate, erro
|
|||||||
return w.cert, nil
|
return w.cert, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Leaf returns the parsed leaf certificate, or nil if not yet loaded.
|
||||||
|
func (w *Watcher) Leaf() *x509.Certificate {
|
||||||
|
w.mu.RLock()
|
||||||
|
defer w.mu.RUnlock()
|
||||||
|
return w.leaf
|
||||||
|
}
|
||||||
|
|
||||||
// Watch starts watching for certificate file changes. It blocks until
|
// Watch starts watching for certificate file changes. It blocks until
|
||||||
// ctx is cancelled. It uses fsnotify for immediate detection and falls
|
// ctx is cancelled. It uses fsnotify for immediate detection and falls
|
||||||
// back to polling if fsnotify is unavailable (e.g. on NFS).
|
// back to polling if fsnotify is unavailable (e.g. on NFS).
|
||||||
|
|||||||
@@ -97,6 +97,11 @@ type Server struct {
|
|||||||
// CertLockMethod controls how ACME certificate locks are coordinated
|
// CertLockMethod controls how ACME certificate locks are coordinated
|
||||||
// across replicas. Default: CertLockAuto (detect environment).
|
// across replicas. Default: CertLockAuto (detect environment).
|
||||||
CertLockMethod acme.CertLockMethod
|
CertLockMethod acme.CertLockMethod
|
||||||
|
// WildcardCertDir is an optional directory containing wildcard certificate
|
||||||
|
// pairs (<name>.crt / <name>.key). Wildcard patterns are extracted from
|
||||||
|
// the certificates' SAN lists. Matching domains use these static certs
|
||||||
|
// instead of ACME.
|
||||||
|
WildcardCertDir string
|
||||||
|
|
||||||
// DebugEndpointEnabled enables the debug HTTP endpoint.
|
// DebugEndpointEnabled enables the debug HTTP endpoint.
|
||||||
DebugEndpointEnabled bool
|
DebugEndpointEnabled bool
|
||||||
@@ -437,7 +442,20 @@ func (s *Server) configureTLS(ctx context.Context) (*tls.Config, error) {
|
|||||||
"acme_server": s.ACMEDirectory,
|
"acme_server": s.ACMEDirectory,
|
||||||
"challenge_type": s.ACMEChallengeType,
|
"challenge_type": s.ACMEChallengeType,
|
||||||
}).Debug("ACME certificates enabled, configuring certificate manager")
|
}).Debug("ACME certificates enabled, configuring certificate manager")
|
||||||
s.acme = acme.NewManager(s.CertificateDirectory, s.ACMEDirectory, s.ACMEEABKID, s.ACMEEABHMACKey, s, s.Logger, s.CertLockMethod, s.meter)
|
var err error
|
||||||
|
s.acme, err = acme.NewManager(acme.ManagerConfig{
|
||||||
|
CertDir: s.CertificateDirectory,
|
||||||
|
ACMEURL: s.ACMEDirectory,
|
||||||
|
EABKID: s.ACMEEABKID,
|
||||||
|
EABHMACKey: s.ACMEEABHMACKey,
|
||||||
|
LockMethod: s.CertLockMethod,
|
||||||
|
WildcardDir: s.WildcardCertDir,
|
||||||
|
}, s, s.Logger, s.meter)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("create ACME manager: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
go s.acme.WatchWildcards(ctx)
|
||||||
|
|
||||||
if s.ACMEChallengeType == "http-01" {
|
if s.ACMEChallengeType == "http-01" {
|
||||||
s.http = &http.Server{
|
s.http = &http.Server{
|
||||||
@@ -453,6 +471,10 @@ func (s *Server) configureTLS(ctx context.Context) (*tls.Config, error) {
|
|||||||
}
|
}
|
||||||
tlsConfig = s.acme.TLSConfig()
|
tlsConfig = s.acme.TLSConfig()
|
||||||
|
|
||||||
|
// autocert.Manager.TLSConfig() wires its own GetCertificate, which
|
||||||
|
// bypasses our override that checks wildcards first.
|
||||||
|
tlsConfig.GetCertificate = s.acme.GetCertificate
|
||||||
|
|
||||||
// ServerName needs to be set to allow for ACME to work correctly
|
// ServerName needs to be set to allow for ACME to work correctly
|
||||||
// when using CNAME URLs to access the proxy.
|
// when using CNAME URLs to access the proxy.
|
||||||
tlsConfig.ServerName = s.ProxyURL
|
tlsConfig.ServerName = s.ProxyURL
|
||||||
@@ -675,8 +697,9 @@ func (s *Server) addMapping(ctx context.Context, mapping *proto.ProxyMapping) er
|
|||||||
if err := s.netbird.AddPeer(ctx, accountID, d, authToken, serviceID); err != nil {
|
if err := s.netbird.AddPeer(ctx, accountID, d, authToken, serviceID); err != nil {
|
||||||
return fmt.Errorf("create peer for domain %q: %w", d, err)
|
return fmt.Errorf("create peer for domain %q: %w", d, err)
|
||||||
}
|
}
|
||||||
|
var wildcardHit bool
|
||||||
if s.acme != nil {
|
if s.acme != nil {
|
||||||
s.acme.AddDomain(d, string(accountID), serviceID)
|
wildcardHit = s.acme.AddDomain(d, string(accountID), serviceID)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pass the mapping through to the update function to avoid duplicating the
|
// Pass the mapping through to the update function to avoid duplicating the
|
||||||
@@ -686,6 +709,13 @@ func (s *Server) addMapping(ctx context.Context, mapping *proto.ProxyMapping) er
|
|||||||
s.removeMapping(ctx, mapping)
|
s.removeMapping(ctx, mapping)
|
||||||
return fmt.Errorf("update mapping for domain %q: %w", d, err)
|
return fmt.Errorf("update mapping for domain %q: %w", d, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if wildcardHit {
|
||||||
|
if err := s.NotifyCertificateIssued(ctx, string(accountID), serviceID, string(d)); err != nil {
|
||||||
|
s.Logger.Warnf("notify certificate ready for domain %q: %v", d, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user