mirror of
https://github.com/tailscale/tailscale.git
synced 2026-12-06 23:36:34 +09:00
feature/acme,tailcfg: let control set the ACME directory URL
Add nodecap.ACMEDirectoryURL so a control server can point clients at a private ACME CA instead of Let's Encrypt. The CA's root must be in the node's system roots. TS_DEBUG_ACME_DIRECTORY_URL still wins. The domain is authorized and the CA picked from one netmap snapshot, so a profile switch can't send a name to another profile's CA. An invalid attribute fails issuance rather than falling back to Let's Encrypt, and a client for an attribute-selected directory refuses non-https requests. CAs without ARI renew by expiry. Updates #4454 Updates juanfont/headscale#3764 RELNOTE: Control servers can choose the ACME CA used for HTTPS certificates. Change-Id: Ifcc8069c6821e2f7bb145c2a496f4598b3ae0344 Signed-off-by: Kristoffer Dalby <kristoffer@tailscale.com>
This commit is contained in:
1 parent
2a77483f57
commit
6ebb4c9ffb
7 files changed
+370
-28
No files matched your search
@@ -28,6 +28,7 @@ import (
|
||||
"tailscale.com/tailcfg"
|
||||
"tailscale.com/tstest"
|
||||
"tailscale.com/types/logger"
|
||||
"tailscale.com/types/netmap"
|
||||
"tailscale.com/util/must"
|
||||
)
|
||||
|
||||
@@ -36,6 +37,12 @@ func TestHandleC2NTLSCertStatus(t *testing.T) {
|
||||
t.Setenv("TS_DEBUG_ACME_DIRECTORY_URL", "")
|
||||
b := ipnlocaltest.NewBackend(t)
|
||||
b.SetVarRoot(t.TempDir())
|
||||
// getCertPEM re-authorizes the domain and reads the ACME directory URL
|
||||
// from the netmap.
|
||||
b.ForTest().SetNetMap(&netmap.NetworkMap{
|
||||
SelfNode: (&tailcfg.Node{}).View(),
|
||||
DNS: tailcfg.DNSConfig{CertDomains: []string{"example.com", "other.example.com"}},
|
||||
})
|
||||
e := extOf(t, b)
|
||||
|
||||
certDirPath, err := certDir(b)
|
||||
|
||||
+27
-12
@@ -30,6 +30,7 @@ import (
|
||||
"tailscale.com/tailcfg/nodecap"
|
||||
xacme "tailscale.com/tempfork/acme"
|
||||
"tailscale.com/types/logger"
|
||||
"tailscale.com/types/netmap"
|
||||
"tailscale.com/util/mak"
|
||||
"tailscale.com/util/set"
|
||||
"tailscale.com/util/slicesx"
|
||||
@@ -100,7 +101,8 @@ func (e *extension) getCertPEMWithValidity(ctx context.Context, b *ipnlocal.Loca
|
||||
return nil, errors.New("invalid domain")
|
||||
}
|
||||
|
||||
certDomain, err := e.resolveCertDomain(b, domain)
|
||||
nm := b.NetMapNoPeers()
|
||||
certDomain, err := e.resolveCertDomain(b, nm, domain)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -126,7 +128,7 @@ func (e *extension) getCertPEMWithValidity(ctx context.Context, b *ipnlocal.Loca
|
||||
}
|
||||
// If we got here, we have a valid unexpired cert.
|
||||
// Check whether we should start an async renewal.
|
||||
shouldRenew, err := e.shouldStartDomainRenewal(b, cs, certDomain, now, pair, minValidity)
|
||||
shouldRenew, err := e.shouldStartDomainRenewal(b, nm, cs, certDomain, now, pair, minValidity)
|
||||
if err != nil {
|
||||
logf("error checking for certificate renewal: %v", err)
|
||||
// Renewal check failed, but the current cert is valid and not
|
||||
@@ -171,7 +173,7 @@ func (e *extension) getCertPEMWithValidity(ctx context.Context, b *ipnlocal.Loca
|
||||
// shouldStartDomainRenewal reports whether the domain's cert should be
|
||||
// renewed based on the current time, the cert's expiry, and the ARI
|
||||
// check.
|
||||
func (e *extension) shouldStartDomainRenewal(b *ipnlocal.LocalBackend, cs certStore, domain string, now time.Time, pair *ipnlocal.TLSCertKeyPair, minValidity time.Duration) (bool, error) {
|
||||
func (e *extension) shouldStartDomainRenewal(b *ipnlocal.LocalBackend, nm *netmap.NetworkMap, cs certStore, domain string, now time.Time, pair *ipnlocal.TLSCertKeyPair, minValidity time.Duration) (bool, error) {
|
||||
if minValidity != 0 {
|
||||
cert, err := parseCertificate(pair)
|
||||
if err != nil {
|
||||
@@ -185,7 +187,7 @@ func (e *extension) shouldStartDomainRenewal(b *ipnlocal.LocalBackend, cs certSt
|
||||
return now.After(renewAt), nil
|
||||
}
|
||||
|
||||
renewTime, err := e.domainRenewalTimeByARI(b, cs, pair)
|
||||
renewTime, err := e.domainRenewalTimeByARI(b, nm, cs, pair)
|
||||
if err != nil {
|
||||
// Log any ARI failure and fall back to checking for renewal by expiry.
|
||||
b.Logger()("acme: ARI check failed: %v; falling back to expiry-based check", err)
|
||||
@@ -304,7 +306,7 @@ func isWildcardDomain(domain string) bool {
|
||||
return strings.HasPrefix(domain, "*.")
|
||||
}
|
||||
|
||||
func (e *extension) domainRenewalTimeByARI(b *ipnlocal.LocalBackend, cs certStore, pair *ipnlocal.TLSCertKeyPair) (time.Time, error) {
|
||||
func (e *extension) domainRenewalTimeByARI(b *ipnlocal.LocalBackend, nm *netmap.NetworkMap, cs certStore, pair *ipnlocal.TLSCertKeyPair) (time.Time, error) {
|
||||
var blocks []*pem.Block
|
||||
rest := pair.CertPEM
|
||||
for len(rest) > 0 {
|
||||
@@ -318,12 +320,19 @@ func (e *extension) domainRenewalTimeByARI(b *ipnlocal.LocalBackend, cs certStor
|
||||
if len(blocks) < 1 {
|
||||
return time.Time{}, fmt.Errorf("could not parse certificate chain from certStore, got %d PEM block(s)", len(blocks))
|
||||
}
|
||||
ac, err := e.acmeClient(cs)
|
||||
ac, err := e.acmeClient(nm, cs)
|
||||
if err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
dir, err := ac.Discover(ctx)
|
||||
if err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
if dir.RenewalInfoURL == "" {
|
||||
return time.Time{}, errors.New("ACME server does not advertise renewalInfo")
|
||||
}
|
||||
ri, err := ac.FetchRenewalInfo(ctx, blocks[0].Bytes)
|
||||
if err != nil {
|
||||
return time.Time{}, fmt.Errorf("failed to fetch renewal info from ACME server: %w", err)
|
||||
@@ -351,6 +360,14 @@ var getCertPEM = func(ctx context.Context, e *extension, b *ipnlocal.LocalBacken
|
||||
dm.Lock()
|
||||
defer dm.Unlock()
|
||||
|
||||
// Authorize the domain and pick the CA from one netmap snapshot, so a
|
||||
// profile or control change since the caller's check can't send this
|
||||
// name to another profile's CA.
|
||||
nm := b.NetMapNoPeers()
|
||||
if _, err := e.resolveCertDomain(b, nm, domain); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// In case this method was triggered multiple times in parallel (when
|
||||
// serving incoming requests), check whether one of the other goroutines
|
||||
// already renewed the cert before us.
|
||||
@@ -358,7 +375,7 @@ var getCertPEM = func(ctx context.Context, e *extension, b *ipnlocal.LocalBacken
|
||||
if err == nil {
|
||||
// shouldStartDomainRenewal caches its result so it's OK to call this
|
||||
// frequently.
|
||||
shouldRenew, err := e.shouldStartDomainRenewal(b, cs, domain, now, previous, minValidity)
|
||||
shouldRenew, err := e.shouldStartDomainRenewal(b, nm, cs, domain, now, previous, minValidity)
|
||||
if err != nil {
|
||||
logf("error checking for certificate renewal: %v", err)
|
||||
} else if !shouldRenew {
|
||||
@@ -378,7 +395,7 @@ var getCertPEM = func(ctx context.Context, e *extension, b *ipnlocal.LocalBacken
|
||||
defer e.setCertPending(b, domain, false)
|
||||
}
|
||||
|
||||
ac, err := e.acmeClient(cs)
|
||||
ac, err := e.acmeClient(nm, cs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -396,7 +413,7 @@ var getCertPEM = func(ctx context.Context, e *extension, b *ipnlocal.LocalBacken
|
||||
}
|
||||
|
||||
// If we have a previous cert, include it in the order via the ARI
|
||||
// "replaces" extension so LE classifies the new cert as a renewal
|
||||
// "replaces" extension so the CA classifies the new cert as a renewal
|
||||
// and exempts it from the per-registered-domain rate limit. Stores
|
||||
// that can tell the current ACME account did not issue the previous
|
||||
// cert opt out via [ARIReplacesAllower]; see #18251. If the CA
|
||||
@@ -755,13 +772,11 @@ func validLookingCertDomain(name string) bool {
|
||||
//
|
||||
// Subdomain requests like "app.node.ts.net" are rejected; callers should
|
||||
// request "*.node.ts.net" explicitly for subdomain coverage.
|
||||
func (e *extension) resolveCertDomain(b *ipnlocal.LocalBackend, domain string) (string, error) {
|
||||
func (e *extension) resolveCertDomain(b *ipnlocal.LocalBackend, nm *netmap.NetworkMap, domain string) (string, error) {
|
||||
if domain == "" {
|
||||
return "", errors.New("missing domain name")
|
||||
}
|
||||
|
||||
// Read the netmap once to get both CertDomains and capabilities atomically.
|
||||
nm := b.NetMapNoPeers()
|
||||
if nm == nil {
|
||||
return "", errors.New("no netmap available")
|
||||
}
|
||||
|
||||
+254
-7
@@ -20,6 +20,7 @@ import (
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"maps"
|
||||
"math/big"
|
||||
"net/http"
|
||||
@@ -27,6 +28,7 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -42,6 +44,7 @@ import (
|
||||
xacme "tailscale.com/tempfork/acme"
|
||||
"tailscale.com/tsconst"
|
||||
"tailscale.com/tstest"
|
||||
"tailscale.com/tstest/acmetest"
|
||||
"tailscale.com/types/logger"
|
||||
"tailscale.com/types/netmap"
|
||||
"tailscale.com/util/must"
|
||||
@@ -212,7 +215,7 @@ func TestResolveCertDomain(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
got, err := e.resolveCertDomain(b, tt.domain)
|
||||
got, err := e.resolveCertDomain(b, b.NetMapNoPeers(), tt.domain)
|
||||
if tt.wantErr != "" {
|
||||
if err == nil {
|
||||
t.Errorf("resolveCertDomain(%q) = %q, want error %q", tt.domain, got, tt.wantErr)
|
||||
@@ -453,7 +456,7 @@ func TestResolveCertDomainBYO(t *testing.T) {
|
||||
})
|
||||
|
||||
// Without a serve config, BYO is rejected.
|
||||
if _, err := e.resolveCertDomain(b, byoDomain); err == nil {
|
||||
if _, err := e.resolveCertDomain(b, b.NetMapNoPeers(), byoDomain); err == nil {
|
||||
t.Fatalf("resolveCertDomain(%q) without serve config: want error, got nil", byoDomain)
|
||||
}
|
||||
|
||||
@@ -463,7 +466,7 @@ func TestResolveCertDomainBYO(t *testing.T) {
|
||||
byoDomain + ":443": {Handlers: map[string]*ipn.HTTPHandler{"/": {Proxy: "http://127.0.0.1:8080"}}},
|
||||
},
|
||||
}).View())
|
||||
if _, err := e.resolveCertDomain(b, byoDomain); err == nil {
|
||||
if _, err := e.resolveCertDomain(b, b.NetMapNoPeers(), byoDomain); err == nil {
|
||||
t.Fatalf("resolveCertDomain(%q) with Web but no Funnel: want error, got nil", byoDomain)
|
||||
}
|
||||
|
||||
@@ -474,7 +477,7 @@ func TestResolveCertDomainBYO(t *testing.T) {
|
||||
},
|
||||
AllowFunnel: map[ipn.HostPort]bool{byoDomain + ":443": true},
|
||||
}).View())
|
||||
got, err := e.resolveCertDomain(b, byoDomain)
|
||||
got, err := e.resolveCertDomain(b, b.NetMapNoPeers(), byoDomain)
|
||||
if err != nil {
|
||||
t.Fatalf("resolveCertDomain(%q): %v", byoDomain, err)
|
||||
}
|
||||
@@ -483,7 +486,7 @@ func TestResolveCertDomainBYO(t *testing.T) {
|
||||
}
|
||||
|
||||
// The ts.net path still works alongside BYO entries.
|
||||
got, err = e.resolveCertDomain(b, tsNetDomain)
|
||||
got, err = e.resolveCertDomain(b, b.NetMapNoPeers(), tsNetDomain)
|
||||
if err != nil {
|
||||
t.Fatalf("resolveCertDomain(%q): %v", tsNetDomain, err)
|
||||
}
|
||||
@@ -658,7 +661,7 @@ func TestDebugACMEDirectoryURL(t *testing.T) {
|
||||
t.Run(tc, func(t *testing.T) {
|
||||
t.Setenv(setting, tc)
|
||||
e := &extension{}
|
||||
ac, err := e.acmeClient(certStateStore{StateStore: new(mem.Store)})
|
||||
ac, err := e.acmeClient(acmeDirNetmap(nil), certStateStore{StateStore: new(mem.Store)})
|
||||
if err != nil {
|
||||
t.Fatalf("acmeClient creation err: %v", err)
|
||||
}
|
||||
@@ -669,6 +672,211 @@ func TestDebugACMEDirectoryURL(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// acmeDirNetmap returns a netmap whose self node has capMap.
|
||||
func acmeDirNetmap(capMap tailcfg.NodeCapMap) *netmap.NetworkMap {
|
||||
return &netmap.NetworkMap{SelfNode: (&tailcfg.Node{CapMap: capMap}).View()}
|
||||
}
|
||||
|
||||
// acmeDirAttr returns a CapMap setting [nodecap.ACMEDirectoryURL] to u.
|
||||
func acmeDirAttr(u string) tailcfg.NodeCapMap {
|
||||
return tailcfg.NodeCapMap{nodecap.ACMEDirectoryURL: {tailcfg.RawMessage(`"` + u + `"`)}}
|
||||
}
|
||||
|
||||
func TestACMEDirectoryURL(t *testing.T) {
|
||||
const (
|
||||
ctrlURL = "https://ca.example.com/acme/acme/directory"
|
||||
debugURL = "https://acme-staging-v02.api.letsencrypt.org/directory"
|
||||
)
|
||||
attr := func(vals ...tailcfg.RawMessage) *netmap.NetworkMap {
|
||||
return acmeDirNetmap(tailcfg.NodeCapMap{nodecap.ACMEDirectoryURL: vals})
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
envknob string
|
||||
nm *netmap.NetworkMap
|
||||
want string
|
||||
wantAttr bool
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "absent", nm: acmeDirNetmap(nil), want: ""},
|
||||
{name: "valid", nm: attr(`"` + ctrlURL + `"`), want: ctrlURL, wantAttr: true},
|
||||
{name: "no_netmap", nm: nil, wantErr: true},
|
||||
{name: "invalid_self_node", nm: &netmap.NetworkMap{}, wantErr: true},
|
||||
{name: "envknob_wins_over_invalid", envknob: debugURL, nm: attr(`"http://ca.example.com"`), want: debugURL},
|
||||
{name: "envknob_without_netmap", envknob: debugURL, nm: nil, want: debugURL},
|
||||
{name: "no_values", nm: attr(), wantErr: true},
|
||||
{name: "multiple_values", nm: attr(`"`+ctrlURL+`"`, `"https://other.example.com/directory"`), wantErr: true},
|
||||
{name: "not_a_string", nm: attr(`42`), wantErr: true},
|
||||
{name: "malformed_json", nm: attr(`"https://ca.example.com`), wantErr: true},
|
||||
{name: "empty_string", nm: attr(`""`), wantErr: true},
|
||||
{name: "http", nm: attr(`"http://ca.example.com/directory"`), wantErr: true},
|
||||
{name: "relative", nm: attr(`"/acme/directory"`), wantErr: true},
|
||||
{name: "port_only", nm: attr(`"https://:443/acme/directory"`), wantErr: true},
|
||||
{name: "userinfo", nm: attr(`"https://user:pass@ca.example.com/directory"`), wantErr: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Setenv("TS_DEBUG_ACME_DIRECTORY_URL", tt.envknob)
|
||||
got, fromAttr, err := acmeDirectoryURL(tt.nm)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Fatalf("acmeDirectoryURL() = %q, %v; wantErr %v", got, err, tt.wantErr)
|
||||
}
|
||||
if got != tt.want || fromAttr != tt.wantAttr {
|
||||
t.Errorf("acmeDirectoryURL() = %q, %v; want %q, %v", got, fromAttr, tt.want, tt.wantAttr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestACMEClientHTTPSOnly checks that only a client for a directory named
|
||||
// by the node attribute refuses plaintext, keeping [http.DefaultClient]'s
|
||||
// policy, and that envknob and default clients use [http.DefaultClient].
|
||||
func TestACMEClientHTTPSOnly(t *testing.T) {
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
|
||||
t.Cleanup(ts.Close)
|
||||
rt := &http.Transport{}
|
||||
tstest.Replace(t, &http.DefaultClient, &http.Client{Transport: rt, Timeout: time.Minute})
|
||||
tests := []struct {
|
||||
name string
|
||||
envknob string
|
||||
nm *netmap.NetworkMap
|
||||
httpsOnly bool
|
||||
}{
|
||||
{name: "attr", nm: acmeDirNetmap(acmeDirAttr("https://ca.example.com/directory")), httpsOnly: true},
|
||||
{name: "attr_mixed_case", nm: acmeDirNetmap(acmeDirAttr("HTTPS://ca.example.com/directory")), httpsOnly: true},
|
||||
{name: "envknob", envknob: "https://ca.example.com/directory", nm: acmeDirNetmap(nil)},
|
||||
{name: "default", nm: acmeDirNetmap(nil)},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Setenv("TS_DEBUG_ACME_DIRECTORY_URL", tt.envknob)
|
||||
e := &extension{}
|
||||
ac, err := e.acmeClient(tt.nm, certStateStore{StateStore: new(mem.Store)})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !tt.httpsOnly {
|
||||
if ac.HTTPClient != nil {
|
||||
t.Errorf("HTTPClient = %v, want nil (http.DefaultClient)", ac.HTTPClient)
|
||||
}
|
||||
return
|
||||
}
|
||||
if hc := ac.HTTPClient; hc.Timeout != time.Minute || hc.Transport != (httpsOnlyTransport{rt}) {
|
||||
t.Errorf("HTTPClient = %+v, want http.DefaultClient's policy and transport", hc)
|
||||
}
|
||||
if _, err := ac.HTTPClient.Get(ts.URL); err == nil || !strings.Contains(err.Error(), "non-https") {
|
||||
t.Errorf("plaintext request: err = %v, want non-https refusal", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetCertPEMRechecksDomainAfterNetmapChange checks that a netmap
|
||||
// change between authorizing a domain and issuing for it (such as a
|
||||
// profile switch while a renewal is queued) stops the request before it
|
||||
// reaches a CA.
|
||||
func TestGetCertPEMRechecksDomainAfterNetmapChange(t *testing.T) {
|
||||
s := acmetest.Start(t)
|
||||
t.Setenv("TS_DEBUG_ACME_DIRECTORY_URL", s.DirectoryURL())
|
||||
const domain = "a.example.ts.net"
|
||||
b := ipnlocaltest.NewBackend(t)
|
||||
b.SetVarRoot(t.TempDir())
|
||||
|
||||
nmA := acmeDirNetmap(nil)
|
||||
nmA.DNS.CertDomains = []string{domain}
|
||||
nmB := acmeDirNetmap(nil)
|
||||
nmB.DNS.CertDomains = []string{"b.example.ts.net"}
|
||||
b.ForTest().SetNetMap(nmA)
|
||||
|
||||
orig := getCertPEM
|
||||
tstest.Replace(t, &getCertPEM, func(ctx context.Context, e *extension, b *ipnlocal.LocalBackend, cs certStore, logf logger.Logf, traceACME func(any), domain string, now time.Time, minValidity time.Duration) (*ipnlocal.TLSCertKeyPair, error) {
|
||||
b.ForTest().SetNetMap(nmB)
|
||||
return orig(ctx, e, b, cs, logf, traceACME, domain, now, minValidity)
|
||||
})
|
||||
|
||||
if _, err := b.GetCertPEMWithValidity(t.Context(), domain, 0); err == nil {
|
||||
t.Fatal("GetCertPEMWithValidity succeeded for a domain the current netmap doesn't authorize")
|
||||
}
|
||||
// The account lookup is the client's first request after discovery.
|
||||
if n := s.Requests("/new-account"); n != 0 {
|
||||
t.Errorf("CA got %d account requests, want 0", n)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetCertPEMTLSALPN01Fallback checks that a failed tls-alpn-01
|
||||
// challenge falls back to dns-01, but a failure after the CA accepted the
|
||||
// challenge doesn't, as that would place another order and hide the real
|
||||
// error.
|
||||
func TestGetCertPEMTLSALPN01Fallback(t *testing.T) {
|
||||
t.Setenv("TS_DEBUG_ACME_DIRECTORY_URL", "")
|
||||
const domain = "example.com"
|
||||
// The store trusts the cached cert's root, not the CA's.
|
||||
tstest.Replace(t, &testX509Roots, x509.NewCertPool())
|
||||
testX509Roots.AppendCertsFromPEM(must.Get(certTestFS.ReadFile("testdata/rootCA.pem")))
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
reject bool // reject the tls-alpn-01 challenge
|
||||
fail string // path prefix the CA rejects after the challenge passed
|
||||
wantErr string
|
||||
wantOrders int
|
||||
}{
|
||||
// The CA offers only tls-alpn-01, so the dns-01 retry's order fails.
|
||||
{name: "challenge_rejected", reject: true, wantErr: "dns-01 challenge not offered", wantOrders: 2},
|
||||
{name: "untrusted", wantErr: x509.UnknownAuthorityError{}.Error(), wantOrders: 1},
|
||||
{name: "order_poll_rejected", fail: "/order/", wantErr: "order poll rejected", wantOrders: 1},
|
||||
{name: "malformed_chain", fail: "/cert/", wantErr: "certificate chain is empty", wantOrders: 1},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var s *acmetest.Server
|
||||
ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case tt.fail == "/cert/" && strings.HasPrefix(r.URL.Path, "/cert/"):
|
||||
io.WriteString(w, "not a certificate")
|
||||
case tt.fail == "/order/" && strings.HasPrefix(r.URL.Path, "/order/"):
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
io.WriteString(w, `{"type":"urn:ietf:params:acme:error:unauthorized","detail":"order poll rejected"}`)
|
||||
default:
|
||||
s.ServeHTTP(w, r)
|
||||
}
|
||||
}))
|
||||
ts.StartTLS()
|
||||
t.Cleanup(ts.Close)
|
||||
s = acmetest.New(ts.URL)
|
||||
s.ChallengeType = "tls-alpn-01"
|
||||
if tt.reject {
|
||||
s.Validate = func(string, string) error { return errors.New("challenge rejected") }
|
||||
}
|
||||
tstest.Replace(t, &http.DefaultTransport, ts.Client().Transport)
|
||||
|
||||
b := ipnlocaltest.NewBackend(t)
|
||||
b.SetVarRoot(t.TempDir())
|
||||
nm := acmeDirNetmap(acmeDirAttr(s.DirectoryURL()))
|
||||
nm.DNS.CertDomains = []string{domain}
|
||||
b.ForTest().SetNetMap(nm)
|
||||
b.ForTest().SetServeConfig((&ipn.ServeConfig{AllowFunnel: map[ipn.HostPort]bool{domain + ":443": true}}).View())
|
||||
e := extOf(t, b)
|
||||
cs := must.Get(e.getCertStore(b))
|
||||
if err := cs.WriteTLSCertAndKey(domain, must.Get(certTestFS.ReadFile("testdata/example.com.pem")), must.Get(certTestFS.ReadFile("testdata/example.com-key.pem"))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// A cached cert, valid at now, makes Funnel renewals use
|
||||
// tls-alpn-01; the long min validity forces renewal.
|
||||
now := time.Date(2023, time.February, 20, 0, 0, 0, 0, time.UTC)
|
||||
_, err := getCertPEM(t.Context(), e, b, cs, t.Logf, func(any) {}, domain, now, 100*365*24*time.Hour)
|
||||
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Fatalf("getCertPEM err = %v, want it to contain %q", err, tt.wantErr)
|
||||
}
|
||||
if n := s.Requests("/new-order"); n != tt.wantOrders {
|
||||
t.Errorf("CA got %d orders, want %d", n, tt.wantOrders)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestDomainRenewalTimeByARIWindow checks that an empty or reversed ARI
|
||||
// window is an error, which makes the caller fall back to expiry, rather
|
||||
// than a panic.
|
||||
@@ -711,7 +919,7 @@ func TestDomainRenewalTimeByARIWindow(t *testing.T) {
|
||||
mu.Lock()
|
||||
start, end = tt.start, tt.end
|
||||
mu.Unlock()
|
||||
got, err := e.domainRenewalTimeByARI(b, cs, pair)
|
||||
got, err := e.domainRenewalTimeByARI(b, nil, cs, pair)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Fatalf("domainRenewalTimeByARI() = %v, %v; wantErr %v", got, err, tt.wantErr)
|
||||
}
|
||||
@@ -722,6 +930,45 @@ func TestDomainRenewalTimeByARIWindow(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestDomainRenewalTimeByARINodeAttr checks that ARI asks the CA named by
|
||||
// the netmap it's given, not the backend's, and that a CA that doesn't
|
||||
// advertise renewalInfo is an error.
|
||||
func TestDomainRenewalTimeByARINodeAttr(t *testing.T) {
|
||||
t.Setenv("TS_DEBUG_ACME_DIRECTORY_URL", "")
|
||||
var ts *httptest.Server
|
||||
ts = httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.URL.Path {
|
||||
case "/directory":
|
||||
fmt.Fprintf(w, `{"newNonce":%q,"newOrder":%q,"renewalInfo":%q}`, ts.URL+"/nonce", ts.URL+"/order", ts.URL+"/ari")
|
||||
case "/no-ari/directory":
|
||||
fmt.Fprintf(w, `{"newNonce":%q,"newOrder":%q}`, ts.URL+"/nonce", ts.URL+"/order")
|
||||
default:
|
||||
now := time.Now()
|
||||
json.NewEncoder(w).Encode(xacme.RenewalInfo{SuggestedWindow: xacme.RenewalInfoWindow{Start: now, End: now.Add(time.Hour)}})
|
||||
}
|
||||
}))
|
||||
t.Cleanup(ts.Close)
|
||||
tstest.Replace(t, &http.DefaultTransport, ts.Client().Transport)
|
||||
|
||||
b := ipnlocaltest.NewBackend(t) // has no netmap of its own
|
||||
e := extOf(t, b)
|
||||
cs := certStateStore{StateStore: new(mem.Store)}
|
||||
pair := &ipnlocal.TLSCertKeyPair{CertPEM: must.Get(certTestFS.ReadFile("testdata/example.com.pem"))}
|
||||
if _, err := e.domainRenewalTimeByARI(b, acmeDirNetmap(acmeDirAttr(ts.URL+"/directory")), cs, pair); err != nil {
|
||||
t.Errorf("domainRenewalTimeByARI: %v", err)
|
||||
}
|
||||
noARI := acmeDirNetmap(acmeDirAttr(ts.URL + "/no-ari/directory"))
|
||||
_, err := e.domainRenewalTimeByARI(b, noARI, cs, pair)
|
||||
if err == nil || !strings.Contains(err.Error(), "renewalInfo") {
|
||||
t.Errorf("domainRenewalTimeByARI without renewalInfo: err = %v, want a renewalInfo error", err)
|
||||
}
|
||||
// Without ARI, renewal falls back to expiry: not yet for a fresh cert.
|
||||
if renew, err := e.shouldStartDomainRenewal(b, noARI, cs, "example.com", time.Date(2023, time.February, 20, 0, 0, 0, 0, time.UTC), pair, 0); err != nil || renew {
|
||||
t.Errorf("shouldStartDomainRenewal without ARI = %v, %v; want false, nil", renew, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetCertPEMWithValidity(t *testing.T) {
|
||||
const testDomain = "example.com"
|
||||
b := ipnlocaltest.NewBackend(t)
|
||||
|
||||
@@ -5,6 +5,7 @@ package acme
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"cmp"
|
||||
"crypto"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
@@ -17,6 +18,8 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
@@ -32,7 +35,10 @@ import (
|
||||
"tailscale.com/ipn/store"
|
||||
"tailscale.com/ipn/store/mem"
|
||||
"tailscale.com/net/bakedroots"
|
||||
"tailscale.com/tailcfg"
|
||||
"tailscale.com/tailcfg/nodecap"
|
||||
xacme "tailscale.com/tempfork/acme"
|
||||
"tailscale.com/types/netmap"
|
||||
"tailscale.com/util/testenv"
|
||||
"tailscale.com/version"
|
||||
"tailscale.com/version/distro"
|
||||
@@ -394,19 +400,71 @@ func (e *extension) acmeKey(cs certStore) (crypto.Signer, error) {
|
||||
return privKey, nil
|
||||
}
|
||||
|
||||
func (e *extension) acmeClient(cs certStore) (*xacme.Client, error) {
|
||||
func (e *extension) acmeClient(nm *netmap.NetworkMap, cs certStore) (*xacme.Client, error) {
|
||||
dirURL, fromAttr, err := acmeDirectoryURL(nm)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
key, err := e.acmeKey(cs)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("acmeKey: %w", err)
|
||||
}
|
||||
// Note: if we add support for additional ACME providers (other than
|
||||
// LetsEncrypt), we should make sure that they support ARI extension (see
|
||||
// shouldStartDomainRenewalARI).
|
||||
return &xacme.Client{
|
||||
// CAs other than Let's Encrypt may not support ARI. Renewal then falls
|
||||
// back to expiry (see shouldStartDomainRenewal), and authorizeOrder
|
||||
// retries orders whose "replaces" field the CA rejects.
|
||||
ac := &xacme.Client{
|
||||
Key: key,
|
||||
UserAgent: "tailscaled/" + version.Long(),
|
||||
DirectoryURL: envknob.String("TS_DEBUG_ACME_DIRECTORY_URL"),
|
||||
}, nil
|
||||
DirectoryURL: dirURL,
|
||||
}
|
||||
if fromAttr {
|
||||
// Keep the default client's policy, such as an embedder's dialer.
|
||||
hc := *http.DefaultClient
|
||||
hc.Transport = httpsOnlyTransport{cmp.Or(hc.Transport, http.DefaultTransport)}
|
||||
ac.HTTPClient = &hc
|
||||
}
|
||||
return ac, nil
|
||||
}
|
||||
|
||||
// httpsOnlyTransport refuses non-https requests, so an https directory
|
||||
// can't steer the client to plaintext endpoints or redirects. RFC 8555
|
||||
// §6.1 requires https throughout.
|
||||
type httpsOnlyTransport struct{ http.RoundTripper }
|
||||
|
||||
func (t httpsOnlyTransport) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
if r.URL.Scheme != "https" {
|
||||
return nil, fmt.Errorf("refusing non-https ACME request to %s", r.URL.Redacted())
|
||||
}
|
||||
return t.RoundTripper.RoundTrip(r)
|
||||
}
|
||||
|
||||
// acmeDirectoryURL returns the ACME directory URL to use, or "" for the
|
||||
// default (Let's Encrypt), and whether it came from
|
||||
// [nodecap.ACMEDirectoryURL]. The debug envknob takes precedence over the
|
||||
// attribute so a local override is always possible. A present but invalid
|
||||
// attribute is an error, never a fallback to the default CA.
|
||||
func acmeDirectoryURL(nm *netmap.NetworkMap) (_ string, fromAttr bool, _ error) {
|
||||
if u := envknob.String("TS_DEBUG_ACME_DIRECTORY_URL"); u != "" {
|
||||
return u, false, nil
|
||||
}
|
||||
if nm == nil || !nm.SelfNode.Valid() {
|
||||
return "", false, errors.New("no netmap available")
|
||||
}
|
||||
cm := nm.SelfNode.CapMap()
|
||||
if !cm.Contains(nodecap.ACMEDirectoryURL) {
|
||||
return "", false, nil
|
||||
}
|
||||
vals, err := tailcfg.UnmarshalNodeCapViewJSON[string](cm, nodecap.ACMEDirectoryURL)
|
||||
if err != nil {
|
||||
return "", false, fmt.Errorf("invalid %q node attribute: %w", nodecap.ACMEDirectoryURL, err)
|
||||
}
|
||||
if len(vals) != 1 {
|
||||
return "", false, fmt.Errorf("invalid %q node attribute: got %d values, want 1", nodecap.ACMEDirectoryURL, len(vals))
|
||||
}
|
||||
if u, err := url.Parse(vals[0]); err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil {
|
||||
return "", false, fmt.Errorf("invalid %q node attribute: want an absolute https URL without userinfo", nodecap.ACMEDirectoryURL)
|
||||
}
|
||||
return vals[0], true, nil
|
||||
}
|
||||
|
||||
// validCertPEM checks whether the given certificate is valid for domain
|
||||
@@ -478,6 +536,8 @@ func validateLeaf(leaf *x509.Certificate, intermediates *x509.CertPool, domain s
|
||||
// after first checking the leaf cert's expiry, hostnames etc, so we know
|
||||
// that the only reason for an error is to do with constructing a full chain.
|
||||
// Allow this error so that cert caching still works in testing environments.
|
||||
// This is deliberately keyed on the debug envknob only: a CA selected by
|
||||
// [nodecap.ACMEDirectoryURL] must chain to the node's roots.
|
||||
if errors.As(err, &x509.UnknownAuthorityError{}) {
|
||||
acmeURL := envknob.String("TS_DEBUG_ACME_DIRECTORY_URL")
|
||||
if !isDefaultDirectoryURL(acmeURL) {
|
||||
|
||||
@@ -95,7 +95,7 @@ func (e *extension) refreshApplicableCerts(ctx context.Context, b *ipnlocal.Loca
|
||||
if host == "" {
|
||||
return
|
||||
}
|
||||
if _, err := e.resolveCertDomain(b, host); err != nil {
|
||||
if _, err := e.resolveCertDomain(b, b.NetMapNoPeers(), host); err != nil {
|
||||
return
|
||||
}
|
||||
want.Add(host)
|
||||
|
||||
@@ -457,6 +457,18 @@ const (
|
||||
// Presence of this field means that this client may try to use the peer as
|
||||
// a connector for the domains specified in the named app's configuration.
|
||||
Conn25Connector Cap = "conn25-connector-apps"
|
||||
|
||||
// ACMEDirectoryURL specifies the ACME directory URL the node uses to
|
||||
// obtain TLS certificates, in place of Let's Encrypt. The [NodeCapMap]
|
||||
// value is a single absolute https URL:
|
||||
//
|
||||
// "acme-directory-url": ["https://ca.example.com/directory"]
|
||||
//
|
||||
// The CA's root must be trusted by the node's system root store. An
|
||||
// invalid value fails issuance rather than falling back to Let's
|
||||
// Encrypt. Certs from a previous CA stay in use until due for renewal.
|
||||
// TS_DEBUG_ACME_DIRECTORY_URL on the node overrides it.
|
||||
ACMEDirectoryURL Cap = "acme-directory-url"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
+2
-1
@@ -201,7 +201,8 @@ type CapabilityVersion int
|
||||
// - 150: 2026-10-13: Client handles app connectors with "mode": "magicip" as conn25.
|
||||
// - 151: 2026-11-13: Client understands [nodecap.LogUploadAuth] for authenticated log uploads
|
||||
// - 152: 2026-11-17: Client supports hybrid post-quantum handshakes
|
||||
const CurrentCapabilityVersion CapabilityVersion = 152
|
||||
// - 153: 2026-11-30: Client understands [nodecap.ACMEDirectoryURL]
|
||||
const CurrentCapabilityVersion CapabilityVersion = 153
|
||||
|
||||
// ID is an integer ID for a user, node, or login allocated by the
|
||||
// control plane.
|
||||
|
||||
Reference in new issue
Block a user