package tsbridge // Self-contained ts.net certificate provisioning. Upstream tsnet cannot // serve HTTPS on Android: the localapi cert endpoint it relies on is // compiled out there (ipn/localapi/disabled_stubs.go returns 404 // "disabled on android"; upstream issue tailscale#18245). The ACME feature // itself IS linked into tsnet, and the local client's SetDNS endpoint is // documented as the escape hatch for answering ACME dns-01 challenges for // ts.net names. So we run the order ourselves: // // xacme (tailscale's ACME client) → Let's Encrypt, dns-01 // lc.SetDNS → publishes the _acme-challenge TXT via control // // This works on every platform tsbridge supports, so it replaces // tsnet's ListenTLS everywhere (one code path). import ( "bytes" "context" "crypto" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/tls" "crypto/x509" "crypto/x509/pkix" "encoding/pem" "errors" "fmt" "os" "path/filepath" "strings" "sync" "time" "tailscale.com/client/local" xacme "tailscale.com/tempfork/acme" ) const ( certDirName = "certs" acmeAccountFile = "acme-account.key" // minRenewRemaining is how much validity a cached cert must have left // before we re-issue instead of using it. Expressed as a fraction of // the total lifetime so it works for both 90-day and short-lived certs. renewRemainingFraction = 3 minRenewRemaining = time.Hour ) // certManager caches and renews a TLS certificate for one ts.net domain, // storing PEMs under /certs (survives restarts; same property the // upstream cert store relies on to stay under ACME rate limits). type certManager struct { domain string dir string lc *local.Client mu sync.Mutex cert *tls.Certificate leaf *x509.Certificate } func newCertManager(lc *local.Client, domain, stateDir string) (*certManager, error) { dir := filepath.Join(stateDir, certDirName) if err := os.MkdirAll(dir, 0o700); err != nil { return nil, fmt.Errorf("create cert dir: %w", err) } return &certManager{domain: domain, dir: dir, lc: lc}, nil } // TLSConfig returns the TLS config for serving. GetCertificate is consulted // per handshake, so renewals swap in without dropping the listener. func (m *certManager) TLSConfig() *tls.Config { return &tls.Config{ // HTTP/1.1 only: the webapp's WebSocket proxy relies on the classic // upgrade path, and the page is tiny, so h2 buys nothing. NextProtos: []string{"http/1.1"}, GetCertificate: func(hi *tls.ClientHelloInfo) (*tls.Certificate, error) { return m.forSNI(hi.ServerName) }, } } func (m *certManager) forSNI(serverName string) (*tls.Certificate, error) { m.mu.Lock() defer m.mu.Unlock() if m.cert == nil { return nil, errors.New("no certificate provisioned yet") } if !strings.EqualFold(strings.TrimSuffix(serverName, "."), m.domain) { return nil, fmt.Errorf("no certificate for SNI %q", serverName) } return m.cert, nil } // ensure loads a cached cert or provisions a new one. func (m *certManager) ensure(ctx context.Context) error { m.mu.Lock() defer m.mu.Unlock() if cert, leaf, err := m.loadCached(); err == nil && certUsable(leaf, time.Now()) { m.cert, m.leaf = cert, leaf return nil } return m.issue(ctx) } func (m *certManager) loadCached() (*tls.Certificate, *x509.Certificate, error) { certPEM, err := os.ReadFile(filepath.Join(m.dir, m.domain+".crt")) if err != nil { return nil, nil, err } keyPEM, err := os.ReadFile(filepath.Join(m.dir, m.domain+".key")) if err != nil { return nil, nil, err } cert, err := tls.X509KeyPair(certPEM, keyPEM) if err != nil { return nil, nil, err } leaf, err := x509.ParseCertificate(cert.Certificate[0]) if err != nil { return nil, nil, err } if err := leaf.VerifyHostname(m.domain); err != nil { return nil, nil, fmt.Errorf("cached cert is not for %s: %w", m.domain, err) } return &cert, leaf, nil } func certUsable(leaf *x509.Certificate, now time.Time) bool { lifetime := leaf.NotAfter.Sub(leaf.NotBefore) remaining := leaf.NotAfter.Sub(now) return remaining > max(minRenewRemaining, lifetime/renewRemainingFraction) } // runRenewals re-issues the cert as it approaches expiry until ctx ends. // Failures retry with capped backoff; the serving listener keeps using the // previous cert until a new one lands. func (m *certManager) runRenewals(ctx context.Context, logf func(string, ...any)) { for { m.mu.Lock() var delay time.Duration if m.leaf == nil { delay = time.Minute } else { lifetime := m.leaf.NotAfter.Sub(m.leaf.NotBefore) renewAt := m.leaf.NotAfter.Add(-lifetime / renewRemainingFraction) delay = time.Until(renewAt) if delay < 0 { delay = 0 } } m.mu.Unlock() timer := time.NewTimer(min(delay, 24*time.Hour)) select { case <-ctx.Done(): timer.Stop() return case <-timer.C: } if err := m.ensure(ctx); err != nil { if ctx.Err() != nil { return } logf("cert renewal failed: %v (retrying in 5 min)", err) select { case <-ctx.Done(): return case <-time.After(5 * time.Minute): } } else { logf("certificate for %s renewed", m.domain) } } } // issue runs one full ACME dns-01 order for m.domain. func (m *certManager) issue(ctx context.Context) error { accountKey, err := m.accountKey() if err != nil { return err } cl := &xacme.Client{Key: accountKey} a, err := ensureACMEAccount(ctx, cl) if err != nil { return err } _ = a order, err := cl.AuthorizeOrder(ctx, []xacme.AuthzID{{Type: "dns", Value: m.domain}}) if err != nil { return fmt.Errorf("AuthorizeOrder: %w", err) } for _, authzURL := range order.AuthzURLs { az, err := cl.GetAuthorization(ctx, authzURL) if err != nil { return fmt.Errorf("GetAuthorization: %w", err) } if az.Status == xacme.StatusValid { continue } var chal *xacme.Challenge for _, c := range az.Challenges { if c.Type == "dns-01" { chal = c break } } if chal == nil { return errors.New("dns-01 challenge not offered") } record, err := cl.DNS01ChallengeRecord(chal.Token) if err != nil { return fmt.Errorf("DNS01ChallengeRecord: %w", err) } name := "_acme-challenge." + strings.TrimPrefix(az.Identifier.Value, "*.") // Control rate-limits and connections can drop mid-flight (phones // switch networks; Go never auto-retries POSTs), so retry the // idempotent TXT publish a few times before giving up. if err := retryBackoff(ctx, 3, 3*time.Second, func() error { err := m.lc.SetDNS(ctx, name, record) if err != nil { return fmt.Errorf("SetDNS %q: %w", name, err) } return nil }); err != nil { return err } if _, err := cl.Accept(ctx, chal); err != nil { return fmt.Errorf("Accept challenge: %w", err) } } order, err = cl.WaitOrder(ctx, order.URI) if err != nil { if oe, ok := err.(*xacme.OrderError); ok { return fmt.Errorf("WaitOrder: order status %q", oe.Status) } return fmt.Errorf("WaitOrder: %w", err) } certKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { return err } csrDER, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{ Subject: pkix.Name{CommonName: m.domain}, DNSNames: []string{m.domain}, }, certKey) if err != nil { return fmt.Errorf("CreateCertificateRequest: %w", err) } derChain, _, err := cl.CreateOrderCert(ctx, order.FinalizeURL, csrDER, true) if err != nil { return fmt.Errorf("CreateOrderCert: %w", err) } var certPEM bytes.Buffer for _, der := range derChain { if err := pem.Encode(&certPEM, &pem.Block{Type: "CERTIFICATE", Bytes: der}); err != nil { return err } } keyDER, err := x509.MarshalECPrivateKey(certKey) if err != nil { return err } var keyPEM bytes.Buffer if err := pem.Encode(&keyPEM, &pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER}); err != nil { return err } certFile := filepath.Join(m.dir, m.domain+".crt") keyFile := filepath.Join(m.dir, m.domain+".key") if err := os.WriteFile(certFile, certPEM.Bytes(), 0o600); err != nil { return err } if err := os.WriteFile(keyFile, keyPEM.Bytes(), 0o600); err != nil { return err } cert, leaf, err := m.loadCached() if err != nil { return fmt.Errorf("verify freshly issued cert: %w", err) } m.cert, m.leaf = cert, leaf return nil } // ensureACMEAccount registers an ACME account with Let's Encrypt for the // stored key, mirroring tailscale's flow. func ensureACMEAccount(ctx context.Context, cl *xacme.Client) (*xacme.Account, error) { a, err := cl.GetReg(ctx, "" /* pre-RFC param */) switch { case err == nil: return a, nil case err == xacme.ErrNoAccount: a, err = cl.Register(ctx, new(xacme.Account), xacme.AcceptTOS) if err == xacme.ErrAccountAlreadyExists { a, err = cl.GetReg(ctx, "" /* pre-RFC param */) } if err != nil { return nil, fmt.Errorf("acme.Register: %w", err) } return a, nil default: return nil, fmt.Errorf("acme.GetReg: %w", err) } } // retryBackoff runs fn up to attempts times with linear backoff between // tries (base, 2*base, …). Returns the last error, or ctx's error. func retryBackoff(ctx context.Context, attempts int, base time.Duration, fn func() error) error { var err error for i := 0; i < attempts; i++ { if i > 0 { select { case <-ctx.Done(): return ctx.Err() case <-time.After(base * time.Duration(i)): } } if err = fn(); err == nil { return nil } } return err } // accountKey loads or creates the PEM-encoded ECDSA ACME account key. func (m *certManager) accountKey() (crypto.Signer, error) { path := filepath.Join(m.dir, acmeAccountFile) if data, err := os.ReadFile(path); err == nil { block, _ := pem.Decode(data) if block == nil { return nil, errors.New("malformed ACME account key") } return x509.ParseECPrivateKey(block.Bytes) } key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { return nil, err } der, err := x509.MarshalECPrivateKey(key) if err != nil { return nil, err } var buf bytes.Buffer if err := pem.Encode(&buf, &pem.Block{Type: "EC PRIVATE KEY", Bytes: der}); err != nil { return nil, err } if err := os.WriteFile(path, buf.Bytes(), 0o600); err != nil { return nil, err } return key, nil }