aboutsummaryrefslogtreecommitdiff
path: root/vendor/golang.org/x/crypto/acme/autocert
diff options
context:
space:
mode:
authorNiall Sheridan <nsheridan@gmail.com>2018-06-20 22:39:07 +0100
committerNiall Sheridan <nsheridan@gmail.com>2018-06-20 22:39:07 +0100
commitde6d2c524430287c699aaa898c1325da6afea539 (patch)
treef78eb841208d667668a7bc92a9290d693cc7103b /vendor/golang.org/x/crypto/acme/autocert
parenteb99016e1629e690e55633de6fc63a14c53e7ea2 (diff)
Update dependencies
Diffstat (limited to 'vendor/golang.org/x/crypto/acme/autocert')
-rw-r--r--vendor/golang.org/x/crypto/acme/autocert/autocert.go583
-rw-r--r--vendor/golang.org/x/crypto/acme/autocert/cache.go6
-rw-r--r--vendor/golang.org/x/crypto/acme/autocert/renewal.go43
3 files changed, 460 insertions, 172 deletions
diff --git a/vendor/golang.org/x/crypto/acme/autocert/autocert.go b/vendor/golang.org/x/crypto/acme/autocert/autocert.go
index b101020..c8fa4e6 100644
--- a/vendor/golang.org/x/crypto/acme/autocert/autocert.go
+++ b/vendor/golang.org/x/crypto/acme/autocert/autocert.go
@@ -24,8 +24,9 @@ import (
"fmt"
"io"
mathrand "math/rand"
+ "net"
"net/http"
- "strconv"
+ "path"
"strings"
"sync"
"time"
@@ -80,8 +81,9 @@ func defaultHostPolicy(context.Context, string) error {
}
// Manager is a stateful certificate manager built on top of acme.Client.
-// It obtains and refreshes certificates automatically,
-// as well as providing them to a TLS server via tls.Config.
+// It obtains and refreshes certificates automatically using "tls-sni-01",
+// "tls-sni-02" and "http-01" challenge types, as well as providing them
+// to a TLS server via tls.Config.
//
// You must specify a cache implementation, such as DirCache,
// to reuse obtained certificates across program restarts.
@@ -96,11 +98,11 @@ type Manager struct {
// To always accept the terms, the callers can use AcceptTOS.
Prompt func(tosURL string) bool
- // Cache optionally stores and retrieves previously-obtained certificates.
- // If nil, certs will only be cached for the lifetime of the Manager.
+ // Cache optionally stores and retrieves previously-obtained certificates
+ // and other state. If nil, certs will only be cached for the lifetime of
+ // the Manager. Multiple Managers can share the same Cache.
//
- // Manager passes the Cache certificates data encoded in PEM, with private/public
- // parts combined in a single Cache.Put call, private key first.
+ // Using a persistent Cache, such as DirCache, is strongly recommended.
Cache Cache
// HostPolicy controls which domains the Manager will attempt
@@ -125,8 +127,10 @@ type Manager struct {
// Client is used to perform low-level operations, such as account registration
// and requesting new certificates.
+ //
// If Client is nil, a zero-value acme.Client is used with acme.LetsEncryptURL
- // directory endpoint and a newly-generated ECDSA P-256 key.
+ // as directory endpoint. If the Client.Key is nil, a new ECDSA P-256 key is
+ // generated and, if Cache is not nil, stored in cache.
//
// Mutating the field after the first call of GetCertificate method will have no effect.
Client *acme.Client
@@ -138,27 +142,63 @@ type Manager struct {
// If the Client's account key is already registered, Email is not used.
Email string
- // ForceRSA makes the Manager generate certificates with 2048-bit RSA keys.
+ // ForceRSA used to make the Manager generate RSA certificates. It is now ignored.
//
- // If false, a default is used. Currently the default
- // is EC-based keys using the P-256 curve.
+ // Deprecated: the Manager will request the correct type of certificate based
+ // on what each client supports.
ForceRSA bool
+ // ExtraExtensions are used when generating a new CSR (Certificate Request),
+ // thus allowing customization of the resulting certificate.
+ // For instance, TLS Feature Extension (RFC 7633) can be used
+ // to prevent an OCSP downgrade attack.
+ //
+ // The field value is passed to crypto/x509.CreateCertificateRequest
+ // in the template's ExtraExtensions field as is.
+ ExtraExtensions []pkix.Extension
+
clientMu sync.Mutex
client *acme.Client // initialized by acmeClient method
stateMu sync.Mutex
- state map[string]*certState // keyed by domain name
-
- // tokenCert is keyed by token domain name, which matches server name
- // of ClientHello. Keys always have ".acme.invalid" suffix.
- tokenCertMu sync.RWMutex
- tokenCert map[string]*tls.Certificate
+ state map[certKey]*certState
// renewal tracks the set of domains currently running renewal timers.
- // It is keyed by domain name.
renewalMu sync.Mutex
- renewal map[string]*domainRenewal
+ renewal map[certKey]*domainRenewal
+
+ // tokensMu guards the rest of the fields: tryHTTP01, certTokens and httpTokens.
+ tokensMu sync.RWMutex
+ // tryHTTP01 indicates whether the Manager should try "http-01" challenge type
+ // during the authorization flow.
+ tryHTTP01 bool
+ // httpTokens contains response body values for http-01 challenges
+ // and is keyed by the URL path at which a challenge response is expected
+ // to be provisioned.
+ // The entries are stored for the duration of the authorization flow.
+ httpTokens map[string][]byte
+ // certTokens contains temporary certificates for tls-sni challenges
+ // and is keyed by token domain name, which matches server name of ClientHello.
+ // Keys always have ".acme.invalid" suffix.
+ // The entries are stored for the duration of the authorization flow.
+ certTokens map[string]*tls.Certificate
+}
+
+// certKey is the key by which certificates are tracked in state, renewal and cache.
+type certKey struct {
+ domain string // without trailing dot
+ isRSA bool // RSA cert for legacy clients (as opposed to default ECDSA)
+ isToken bool // tls-sni challenge token cert; key type is undefined regardless of isRSA
+}
+
+func (c certKey) String() string {
+ if c.isToken {
+ return c.domain + "+token"
+ }
+ if c.isRSA {
+ return c.domain + "+rsa"
+ }
+ return c.domain
}
// GetCertificate implements the tls.Config.GetCertificate hook.
@@ -181,21 +221,23 @@ func (m *Manager) GetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate,
if !strings.Contains(strings.Trim(name, "."), ".") {
return nil, errors.New("acme/autocert: server name component count invalid")
}
- if strings.ContainsAny(name, `/\`) {
+ if strings.ContainsAny(name, `+/\`) {
return nil, errors.New("acme/autocert: server name contains invalid character")
}
+ // In the worst-case scenario, the timeout needs to account for caching, host policy,
+ // domain ownership verification and certificate issuance.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
// check whether this is a token cert requested for TLS-SNI challenge
if strings.HasSuffix(name, ".acme.invalid") {
- m.tokenCertMu.RLock()
- defer m.tokenCertMu.RUnlock()
- if cert := m.tokenCert[name]; cert != nil {
+ m.tokensMu.RLock()
+ defer m.tokensMu.RUnlock()
+ if cert := m.certTokens[name]; cert != nil {
return cert, nil
}
- if cert, err := m.cacheGet(ctx, name); err == nil {
+ if cert, err := m.cacheGet(ctx, certKey{domain: name, isToken: true}); err == nil {
return cert, nil
}
// TODO: cache error results?
@@ -203,8 +245,11 @@ func (m *Manager) GetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate,
}
// regular domain
- name = strings.TrimSuffix(name, ".") // golang.org/issue/18114
- cert, err := m.cert(ctx, name)
+ ck := certKey{
+ domain: strings.TrimSuffix(name, "."), // golang.org/issue/18114
+ isRSA: !supportsECDSA(hello),
+ }
+ cert, err := m.cert(ctx, ck)
if err == nil {
return cert, nil
}
@@ -216,27 +261,135 @@ func (m *Manager) GetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate,
if err := m.hostPolicy()(ctx, name); err != nil {
return nil, err
}
- cert, err = m.createCert(ctx, name)
+ cert, err = m.createCert(ctx, ck)
if err != nil {
return nil, err
}
- m.cachePut(ctx, name, cert)
+ m.cachePut(ctx, ck, cert)
return cert, nil
}
+func supportsECDSA(hello *tls.ClientHelloInfo) bool {
+ // The "signature_algorithms" extension, if present, limits the key exchange
+ // algorithms allowed by the cipher suites. See RFC 5246, section 7.4.1.4.1.
+ if hello.SignatureSchemes != nil {
+ ecdsaOK := false
+ schemeLoop:
+ for _, scheme := range hello.SignatureSchemes {
+ const tlsECDSAWithSHA1 tls.SignatureScheme = 0x0203 // constant added in Go 1.10
+ switch scheme {
+ case tlsECDSAWithSHA1, tls.ECDSAWithP256AndSHA256,
+ tls.ECDSAWithP384AndSHA384, tls.ECDSAWithP521AndSHA512:
+ ecdsaOK = true
+ break schemeLoop
+ }
+ }
+ if !ecdsaOK {
+ return false
+ }
+ }
+ if hello.SupportedCurves != nil {
+ ecdsaOK := false
+ for _, curve := range hello.SupportedCurves {
+ if curve == tls.CurveP256 {
+ ecdsaOK = true
+ break
+ }
+ }
+ if !ecdsaOK {
+ return false
+ }
+ }
+ for _, suite := range hello.CipherSuites {
+ switch suite {
+ case tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
+ tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
+ tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
+ tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
+ tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
+ tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
+ tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305:
+ return true
+ }
+ }
+ return false
+}
+
+// HTTPHandler configures the Manager to provision ACME "http-01" challenge responses.
+// It returns an http.Handler that responds to the challenges and must be
+// running on port 80. If it receives a request that is not an ACME challenge,
+// it delegates the request to the optional fallback handler.
+//
+// If fallback is nil, the returned handler redirects all GET and HEAD requests
+// to the default TLS port 443 with 302 Found status code, preserving the original
+// request path and query. It responds with 400 Bad Request to all other HTTP methods.
+// The fallback is not protected by the optional HostPolicy.
+//
+// Because the fallback handler is run with unencrypted port 80 requests,
+// the fallback should not serve TLS-only requests.
+//
+// If HTTPHandler is never called, the Manager will only use TLS SNI
+// challenges for domain verification.
+func (m *Manager) HTTPHandler(fallback http.Handler) http.Handler {
+ m.tokensMu.Lock()
+ defer m.tokensMu.Unlock()
+ m.tryHTTP01 = true
+
+ if fallback == nil {
+ fallback = http.HandlerFunc(handleHTTPRedirect)
+ }
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if !strings.HasPrefix(r.URL.Path, "/.well-known/acme-challenge/") {
+ fallback.ServeHTTP(w, r)
+ return
+ }
+ // A reasonable context timeout for cache and host policy only,
+ // because we don't wait for a new certificate issuance here.
+ ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
+ defer cancel()
+ if err := m.hostPolicy()(ctx, r.Host); err != nil {
+ http.Error(w, err.Error(), http.StatusForbidden)
+ return
+ }
+ data, err := m.httpToken(ctx, r.URL.Path)
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusNotFound)
+ return
+ }
+ w.Write(data)
+ })
+}
+
+func handleHTTPRedirect(w http.ResponseWriter, r *http.Request) {
+ if r.Method != "GET" && r.Method != "HEAD" {
+ http.Error(w, "Use HTTPS", http.StatusBadRequest)
+ return
+ }
+ target := "https://" + stripPort(r.Host) + r.URL.RequestURI()
+ http.Redirect(w, r, target, http.StatusFound)
+}
+
+func stripPort(hostport string) string {
+ host, _, err := net.SplitHostPort(hostport)
+ if err != nil {
+ return hostport
+ }
+ return net.JoinHostPort(host, "443")
+}
+
// cert returns an existing certificate either from m.state or cache.
// If a certificate is found in cache but not in m.state, the latter will be filled
// with the cached value.
-func (m *Manager) cert(ctx context.Context, name string) (*tls.Certificate, error) {
+func (m *Manager) cert(ctx context.Context, ck certKey) (*tls.Certificate, error) {
m.stateMu.Lock()
- if s, ok := m.state[name]; ok {
+ if s, ok := m.state[ck]; ok {
m.stateMu.Unlock()
s.RLock()
defer s.RUnlock()
return s.tlscert()
}
defer m.stateMu.Unlock()
- cert, err := m.cacheGet(ctx, name)
+ cert, err := m.cacheGet(ctx, ck)
if err != nil {
return nil, err
}
@@ -245,25 +398,25 @@ func (m *Manager) cert(ctx context.Context, name string) (*tls.Certificate, erro
return nil, errors.New("acme/autocert: private key cannot sign")
}
if m.state == nil {
- m.state = make(map[string]*certState)
+ m.state = make(map[certKey]*certState)
}
s := &certState{
key: signer,
cert: cert.Certificate,
leaf: cert.Leaf,
}
- m.state[name] = s
- go m.renew(name, s.key, s.leaf.NotAfter)
+ m.state[ck] = s
+ go m.renew(ck, s.key, s.leaf.NotAfter)
return cert, nil
}
// cacheGet always returns a valid certificate, or an error otherwise.
-// If a cached certficate exists but is not valid, ErrCacheMiss is returned.
-func (m *Manager) cacheGet(ctx context.Context, domain string) (*tls.Certificate, error) {
+// If a cached certificate exists but is not valid, ErrCacheMiss is returned.
+func (m *Manager) cacheGet(ctx context.Context, ck certKey) (*tls.Certificate, error) {
if m.Cache == nil {
return nil, ErrCacheMiss
}
- data, err := m.Cache.Get(ctx, domain)
+ data, err := m.Cache.Get(ctx, ck.String())
if err != nil {
return nil, err
}
@@ -294,7 +447,7 @@ func (m *Manager) cacheGet(ctx context.Context, domain string) (*tls.Certificate
}
// verify and create TLS cert
- leaf, err := validCert(domain, pubDER, privKey)
+ leaf, err := validCert(ck, pubDER, privKey)
if err != nil {
return nil, ErrCacheMiss
}
@@ -306,7 +459,7 @@ func (m *Manager) cacheGet(ctx context.Context, domain string) (*tls.Certificate
return tlscert, nil
}
-func (m *Manager) cachePut(ctx context.Context, domain string, tlscert *tls.Certificate) error {
+func (m *Manager) cachePut(ctx context.Context, ck certKey, tlscert *tls.Certificate) error {
if m.Cache == nil {
return nil
}
@@ -338,7 +491,7 @@ func (m *Manager) cachePut(ctx context.Context, domain string, tlscert *tls.Cert
}
}
- return m.Cache.Put(ctx, domain, buf.Bytes())
+ return m.Cache.Put(ctx, ck.String(), buf.Bytes())
}
func encodeECDSAKey(w io.Writer, key *ecdsa.PrivateKey) error {
@@ -355,9 +508,9 @@ func encodeECDSAKey(w io.Writer, key *ecdsa.PrivateKey) error {
//
// If the domain is already being verified, it waits for the existing verification to complete.
// Either way, createCert blocks for the duration of the whole process.
-func (m *Manager) createCert(ctx context.Context, domain string) (*tls.Certificate, error) {
+func (m *Manager) createCert(ctx context.Context, ck certKey) (*tls.Certificate, error) {
// TODO: maybe rewrite this whole piece using sync.Once
- state, err := m.certState(domain)
+ state, err := m.certState(ck)
if err != nil {
return nil, err
}
@@ -371,48 +524,48 @@ func (m *Manager) createCert(ctx context.Context, domain string) (*tls.Certifica
// We are the first; state is locked.
// Unblock the readers when domain ownership is verified
- // and the we got the cert or the process failed.
+ // and we got the cert or the process failed.
defer state.Unlock()
state.locked = false
- der, leaf, err := m.authorizedCert(ctx, state.key, domain)
+ der, leaf, err := m.authorizedCert(ctx, state.key, ck)
if err != nil {
// Remove the failed state after some time,
// making the manager call createCert again on the following TLS hello.
time.AfterFunc(createCertRetryAfter, func() {
- defer testDidRemoveState(domain)
+ defer testDidRemoveState(ck)
m.stateMu.Lock()
defer m.stateMu.Unlock()
// Verify the state hasn't changed and it's still invalid
// before deleting.
- s, ok := m.state[domain]
+ s, ok := m.state[ck]
if !ok {
return
}
- if _, err := validCert(domain, s.cert, s.key); err == nil {
+ if _, err := validCert(ck, s.cert, s.key); err == nil {
return
}
- delete(m.state, domain)
+ delete(m.state, ck)
})
return nil, err
}
state.cert = der
state.leaf = leaf
- go m.renew(domain, state.key, state.leaf.NotAfter)
+ go m.renew(ck, state.key, state.leaf.NotAfter)
return state.tlscert()
}
// certState returns a new or existing certState.
// If a new certState is returned, state.exist is false and the state is locked.
// The returned error is non-nil only in the case where a new state could not be created.
-func (m *Manager) certState(domain string) (*certState, error) {
+func (m *Manager) certState(ck certKey) (*certState, error) {
m.stateMu.Lock()
defer m.stateMu.Unlock()
if m.state == nil {
- m.state = make(map[string]*certState)
+ m.state = make(map[certKey]*certState)
}
// existing state
- if state, ok := m.state[domain]; ok {
+ if state, ok := m.state[ck]; ok {
return state, nil
}
@@ -421,7 +574,7 @@ func (m *Manager) certState(domain string) (*certState, error) {
err error
key crypto.Signer
)
- if m.ForceRSA {
+ if ck.isRSA {
key, err = rsa.GenerateKey(rand.Reader, 2048)
} else {
key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
@@ -435,21 +588,22 @@ func (m *Manager) certState(domain string) (*certState, error) {
locked: true,
}
state.Lock() // will be unlocked by m.certState caller
- m.state[domain] = state
+ m.state[ck] = state
return state, nil
}
-// authorizedCert starts domain ownership verification process and requests a new cert upon success.
+// authorizedCert starts the domain ownership verification process and requests a new cert upon success.
// The key argument is the certificate private key.
-func (m *Manager) authorizedCert(ctx context.Context, key crypto.Signer, domain string) (der [][]byte, leaf *x509.Certificate, err error) {
- if err := m.verify(ctx, domain); err != nil {
- return nil, nil, err
- }
+func (m *Manager) authorizedCert(ctx context.Context, key crypto.Signer, ck certKey) (der [][]byte, leaf *x509.Certificate, err error) {
client, err := m.acmeClient(ctx)
if err != nil {
return nil, nil, err
}
- csr, err := certRequest(key, domain)
+
+ if err := m.verify(ctx, client, ck.domain); err != nil {
+ return nil, nil, err
+ }
+ csr, err := certRequest(key, ck.domain, m.ExtraExtensions)
if err != nil {
return nil, nil, err
}
@@ -457,105 +611,220 @@ func (m *Manager) authorizedCert(ctx context.Context, key crypto.Signer, domain
if err != nil {
return nil, nil, err
}
- leaf, err = validCert(domain, der, key)
+ leaf, err = validCert(ck, der, key)
if err != nil {
return nil, nil, err
}
return der, leaf, nil
}
-// verify starts a new identifier (domain) authorization flow.
-// It prepares a challenge response and then blocks until the authorization
-// is marked as "completed" by the CA (either succeeded or failed).
-//
-// verify returns nil iff the verification was successful.
-func (m *Manager) verify(ctx context.Context, domain string) error {
+// revokePendingAuthz revokes all authorizations idenfied by the elements of uri slice.
+// It ignores revocation errors.
+func (m *Manager) revokePendingAuthz(ctx context.Context, uri []string) {
client, err := m.acmeClient(ctx)
if err != nil {
- return err
+ return
}
-
- // start domain authorization and get the challenge
- authz, err := client.Authorize(ctx, domain)
- if err != nil {
- return err
+ for _, u := range uri {
+ client.RevokeAuthorization(ctx, u)
}
- // maybe don't need to at all
- if authz.Status == acme.StatusValid {
- return nil
+}
+
+// verify runs the identifier (domain) authorization flow
+// using each applicable ACME challenge type.
+func (m *Manager) verify(ctx context.Context, client *acme.Client, domain string) error {
+ // The list of challenge types we'll try to fulfill
+ // in this specific order.
+ challengeTypes := []string{"tls-sni-02", "tls-sni-01"}
+ m.tokensMu.RLock()
+ if m.tryHTTP01 {
+ challengeTypes = append(challengeTypes, "http-01")
}
+ m.tokensMu.RUnlock()
- // pick a challenge: prefer tls-sni-02 over tls-sni-01
- // TODO: consider authz.Combinations
- var chal *acme.Challenge
- for _, c := range authz.Challenges {
- if c.Type == "tls-sni-02" {
- chal = c
- break
+ // Keep track of pending authzs and revoke the ones that did not validate.
+ pendingAuthzs := make(map[string]bool)
+ defer func() {
+ var uri []string
+ for k, pending := range pendingAuthzs {
+ if pending {
+ uri = append(uri, k)
+ }
}
- if c.Type == "tls-sni-01" {
- chal = c
+ if len(uri) > 0 {
+ // Use "detached" background context.
+ // The revocations need not happen in the current verification flow.
+ go m.revokePendingAuthz(context.Background(), uri)
}
+ }()
+
+ // errs accumulates challenge failure errors, printed if all fail
+ errs := make(map[*acme.Challenge]error)
+ var nextTyp int // challengeType index of the next challenge type to try
+ for {
+ // Start domain authorization and get the challenge.
+ authz, err := client.Authorize(ctx, domain)
+ if err != nil {
+ return err
+ }
+ // No point in accepting challenges if the authorization status
+ // is in a final state.
+ switch authz.Status {
+ case acme.StatusValid:
+ return nil // already authorized
+ case acme.StatusInvalid:
+ return fmt.Errorf("acme/autocert: invalid authorization %q", authz.URI)
+ }
+
+ pendingAuthzs[authz.URI] = true
+
+ // Pick the next preferred challenge.
+ var chal *acme.Challenge
+ for chal == nil && nextTyp < len(challengeTypes) {
+ chal = pickChallenge(challengeTypes[nextTyp], authz.Challenges)
+ nextTyp++
+ }
+ if chal == nil {
+ errorMsg := fmt.Sprintf("acme/autocert: unable to authorize %q", domain)
+ for chal, err := range errs {
+ errorMsg += fmt.Sprintf("; challenge %q failed with error: %v", chal.Type, err)
+ }
+ return errors.New(errorMsg)
+ }
+ cleanup, err := m.fulfill(ctx, client, chal)
+ if err != nil {
+ errs[chal] = err
+ continue
+ }
+ defer cleanup()
+ if _, err := client.Accept(ctx, chal); err != nil {
+ errs[chal] = err
+ continue
+ }
+
+ // A challenge is fulfilled and accepted: wait for the CA to validate.
+ if _, err := client.WaitAuthorization(ctx, authz.URI); err != nil {
+ errs[chal] = err
+ continue
+ }
+ delete(pendingAuthzs, authz.URI)
+ return nil
}
- if chal == nil {
- return errors.New("acme/autocert: no supported challenge type found")
- }
+}
- // create a token cert for the challenge response
- var (
- cert tls.Certificate
- name string
- )
+// fulfill provisions a response to the challenge chal.
+// The cleanup is non-nil only if provisioning succeeded.
+func (m *Manager) fulfill(ctx context.Context, client *acme.Client, chal *acme.Challenge) (cleanup func(), err error) {
switch chal.Type {
case "tls-sni-01":
- cert, name, err = client.TLSSNI01ChallengeCert(chal.Token)
+ cert, name, err := client.TLSSNI01ChallengeCert(chal.Token)
+ if err != nil {
+ return nil, err
+ }
+ m.putCertToken(ctx, name, &cert)
+ return func() { go m.deleteCertToken(name) }, nil
case "tls-sni-02":
- cert, name, err = client.TLSSNI02ChallengeCert(chal.Token)
- default:
- err = fmt.Errorf("acme/autocert: unknown challenge type %q", chal.Type)
+ cert, name, err := client.TLSSNI02ChallengeCert(chal.Token)
+ if err != nil {
+ return nil, err
+ }
+ m.putCertToken(ctx, name, &cert)
+ return func() { go m.deleteCertToken(name) }, nil
+ case "http-01":
+ resp, err := client.HTTP01ChallengeResponse(chal.Token)
+ if err != nil {
+ return nil, err
+ }
+ p := client.HTTP01ChallengePath(chal.Token)
+ m.putHTTPToken(ctx, p, resp)
+ return func() { go m.deleteHTTPToken(p) }, nil
}
- if err != nil {
- return err
+ return nil, fmt.Errorf("acme/autocert: unknown challenge type %q", chal.Type)
+}
+
+func pickChallenge(typ string, chal []*acme.Challenge) *acme.Challenge {
+ for _, c := range chal {
+ if c.Type == typ {
+ return c
+ }
}
- m.putTokenCert(ctx, name, &cert)
- defer func() {
- // verification has ended at this point
- // don't need token cert anymore
- go m.deleteTokenCert(name)
- }()
+ return nil
+}
- // ready to fulfill the challenge
- if _, err := client.Accept(ctx, chal); err != nil {
- return err
+// putCertToken stores the token certificate with the specified name
+// in both m.certTokens map and m.Cache.
+func (m *Manager) putCertToken(ctx context.Context, name string, cert *tls.Certificate) {
+ m.tokensMu.Lock()
+ defer m.tokensMu.Unlock()
+ if m.certTokens == nil {
+ m.certTokens = make(map[string]*tls.Certificate)
+ }
+ m.certTokens[name] = cert
+ m.cachePut(ctx, certKey{domain: name, isToken: true}, cert)
+}
+
+// deleteCertToken removes the token certificate with the specified name
+// from both m.certTokens map and m.Cache.
+func (m *Manager) deleteCertToken(name string) {
+ m.tokensMu.Lock()
+ defer m.tokensMu.Unlock()
+ delete(m.certTokens, name)
+ if m.Cache != nil {
+ ck := certKey{domain: name, isToken: true}
+ m.Cache.Delete(context.Background(), ck.String())
+ }
+}
+
+// httpToken retrieves an existing http-01 token value from an in-memory map
+// or the optional cache.
+func (m *Manager) httpToken(ctx context.Context, tokenPath string) ([]byte, error) {
+ m.tokensMu.RLock()
+ defer m.tokensMu.RUnlock()
+ if v, ok := m.httpTokens[tokenPath]; ok {
+ return v, nil
+ }
+ if m.Cache == nil {
+ return nil, fmt.Errorf("acme/autocert: no token at %q", tokenPath)
}
- // wait for the CA to validate
- _, err = client.WaitAuthorization(ctx, authz.URI)
- return err
+ return m.Cache.Get(ctx, httpTokenCacheKey(tokenPath))
}
-// putTokenCert stores the cert under the named key in both m.tokenCert map
-// and m.Cache.
-func (m *Manager) putTokenCert(ctx context.Context, name string, cert *tls.Certificate) {
- m.tokenCertMu.Lock()
- defer m.tokenCertMu.Unlock()
- if m.tokenCert == nil {
- m.tokenCert = make(map[string]*tls.Certificate)
+// putHTTPToken stores an http-01 token value using tokenPath as key
+// in both in-memory map and the optional Cache.
+//
+// It ignores any error returned from Cache.Put.
+func (m *Manager) putHTTPToken(ctx context.Context, tokenPath, val string) {
+ m.tokensMu.Lock()
+ defer m.tokensMu.Unlock()
+ if m.httpTokens == nil {
+ m.httpTokens = make(map[string][]byte)
+ }
+ b := []byte(val)
+ m.httpTokens[tokenPath] = b
+ if m.Cache != nil {
+ m.Cache.Put(ctx, httpTokenCacheKey(tokenPath), b)
}
- m.tokenCert[name] = cert
- m.cachePut(ctx, name, cert)
}
-// deleteTokenCert removes the token certificate for the specified domain name
-// from both m.tokenCert map and m.Cache.
-func (m *Manager) deleteTokenCert(name string) {
- m.tokenCertMu.Lock()
- defer m.tokenCertMu.Unlock()
- delete(m.tokenCert, name)
+// deleteHTTPToken removes an http-01 token value from both in-memory map
+// and the optional Cache, ignoring any error returned from the latter.
+//
+// If m.Cache is non-nil, it blocks until Cache.Delete returns without a timeout.
+func (m *Manager) deleteHTTPToken(tokenPath string) {
+ m.tokensMu.Lock()
+ defer m.tokensMu.Unlock()
+ delete(m.httpTokens, tokenPath)
if m.Cache != nil {
- m.Cache.Delete(context.Background(), name)
+ m.Cache.Delete(context.Background(), httpTokenCacheKey(tokenPath))
}
}
+// httpTokenCacheKey returns a key at which an http-01 token value may be stored
+// in the Manager's optional Cache.
+func httpTokenCacheKey(tokenPath string) string {
+ return path.Base(tokenPath) + "+http-01"
+}
+
// renew starts a cert renewal timer loop, one per domain.
//
// The loop is scheduled in two cases:
@@ -564,18 +833,18 @@ func (m *Manager) deleteTokenCert(name string) {
//
// The key argument is a certificate private key.
// The exp argument is the cert expiration time (NotAfter).
-func (m *Manager) renew(domain string, key crypto.Signer, exp time.Time) {
+func (m *Manager) renew(ck certKey, key crypto.Signer, exp time.Time) {
m.renewalMu.Lock()
defer m.renewalMu.Unlock()
- if m.renewal[domain] != nil {
+ if m.renewal[ck] != nil {
// another goroutine is already on it
return
}
if m.renewal == nil {
- m.renewal = make(map[string]*domainRenewal)
+ m.renewal = make(map[certKey]*domainRenewal)
}
- dr := &domainRenewal{m: m, domain: domain, key: key}
- m.renewal[domain] = dr
+ dr := &domainRenewal{m: m, ck: ck, key: key}
+ m.renewal[ck] = dr
dr.start(exp)
}
@@ -591,7 +860,10 @@ func (m *Manager) stopRenew() {
}
func (m *Manager) accountKey(ctx context.Context) (crypto.Signer, error) {
- const keyName = "acme_account.key"
+ const keyName = "acme_account+key"
+
+ // Previous versions of autocert stored the value under a different key.
+ const legacyKeyName = "acme_account.key"
genKey := func() (*ecdsa.PrivateKey, error) {
return ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
@@ -603,6 +875,9 @@ func (m *Manager) accountKey(ctx context.Context) (crypto.Signer, error) {
data, err := m.Cache.Get(ctx, keyName)
if err == ErrCacheMiss {
+ data, err = m.Cache.Get(ctx, legacyKeyName)
+ }
+ if err == ErrCacheMiss {
key, err := genKey()
if err != nil {
return nil, err
@@ -698,12 +973,12 @@ func (s *certState) tlscert() (*tls.Certificate, error) {
}, nil
}
-// certRequest creates a certificate request for the given common name cn
-// and optional SANs.
-func certRequest(key crypto.Signer, cn string, san ...string) ([]byte, error) {
+// certRequest generates a CSR for the given common name cn and optional SANs.
+func certRequest(key crypto.Signer, cn string, ext []pkix.Extension, san ...string) ([]byte, error) {
req := &x509.CertificateRequest{
- Subject: pkix.Name{CommonName: cn},
- DNSNames: san,
+ Subject: pkix.Name{CommonName: cn},
+ DNSNames: san,
+ ExtraExtensions: ext,
}
return x509.CreateCertificateRequest(rand.Reader, req, key)
}
@@ -734,12 +1009,12 @@ func parsePrivateKey(der []byte) (crypto.Signer, error) {
return nil, errors.New("acme/autocert: failed to parse private key")
}
-// validCert parses a cert chain provided as der argument and verifies the leaf, der[0],
-// corresponds to the private key, as well as the domain match and expiration dates.
-// It doesn't do any revocation checking.
+// validCert parses a cert chain provided as der argument and verifies the leaf and der[0]
+// correspond to the private key, the domain and key type match, and expiration dates
+// are valid. It doesn't do any revocation checking.
//
// The returned value is the verified leaf cert.
-func validCert(domain string, der [][]byte, key crypto.Signer) (leaf *x509.Certificate, err error) {
+func validCert(ck certKey, der [][]byte, key crypto.Signer) (leaf *x509.Certificate, err error) {
// parse public part(s)
var n int
for _, b := range der {
@@ -751,7 +1026,7 @@ func validCert(domain string, der [][]byte, key crypto.Signer) (leaf *x509.Certi
n += copy(pub[n:], b)
}
x509Cert, err := x509.ParseCertificates(pub)
- if len(x509Cert) == 0 {
+ if err != nil || len(x509Cert) == 0 {
return nil, errors.New("acme/autocert: no public key found")
}
// verify the leaf is not expired and matches the domain name
@@ -763,10 +1038,10 @@ func validCert(domain string, der [][]byte, key crypto.Signer) (leaf *x509.Certi
if now.After(leaf.NotAfter) {
return nil, errors.New("acme/autocert: expired certificate")
}
- if err := leaf.VerifyHostname(domain); err != nil {
+ if err := leaf.VerifyHostname(ck.domain); err != nil {
return nil, err
}
- // ensure the leaf corresponds to the private key
+ // ensure the leaf corresponds to the private key and matches the certKey type
switch pub := leaf.PublicKey.(type) {
case *rsa.PublicKey:
prv, ok := key.(*rsa.PrivateKey)
@@ -776,6 +1051,9 @@ func validCert(domain string, der [][]byte, key crypto.Signer) (leaf *x509.Certi
if pub.N.Cmp(prv.N) != 0 {
return nil, errors.New("acme/autocert: private key does not match public key")
}
+ if !ck.isRSA && !ck.isToken {
+ return nil, errors.New("acme/autocert: key type does not match expected value")
+ }
case *ecdsa.PublicKey:
prv, ok := key.(*ecdsa.PrivateKey)
if !ok {
@@ -784,22 +1062,15 @@ func validCert(domain string, der [][]byte, key crypto.Signer) (leaf *x509.Certi
if pub.X.Cmp(prv.X) != 0 || pub.Y.Cmp(prv.Y) != 0 {
return nil, errors.New("acme/autocert: private key does not match public key")
}
+ if ck.isRSA && !ck.isToken {
+ return nil, errors.New("acme/autocert: key type does not match expected value")
+ }
default:
return nil, errors.New("acme/autocert: unknown public key algorithm")
}
return leaf, nil
}
-func retryAfter(v string) time.Duration {
- if i, err := strconv.Atoi(v); err == nil {
- return time.Duration(i) * time.Second
- }
- if t, err := http.ParseTime(v); err == nil {
- return t.Sub(timeNow())
- }
- return time.Second
-}
-
type lockedMathRand struct {
sync.Mutex
rnd *mathrand.Rand
@@ -817,5 +1088,5 @@ var (
timeNow = time.Now
// Called when a state is removed.
- testDidRemoveState = func(domain string) {}
+ testDidRemoveState = func(certKey) {}
)
diff --git a/vendor/golang.org/x/crypto/acme/autocert/cache.go b/vendor/golang.org/x/crypto/acme/autocert/cache.go
index 61a5fd2..aa9aa84 100644
--- a/vendor/golang.org/x/crypto/acme/autocert/cache.go
+++ b/vendor/golang.org/x/crypto/acme/autocert/cache.go
@@ -16,10 +16,10 @@ import (
var ErrCacheMiss = errors.New("acme/autocert: certificate cache miss")
// Cache is used by Manager to store and retrieve previously obtained certificates
-// as opaque data.
+// and other account data as opaque blobs.
//
-// The key argument of the methods refers to a domain name but need not be an FQDN.
-// Cache implementations should not rely on the key naming pattern.
+// Cache implementations should not rely on the key naming pattern. Keys can
+// include any printable ASCII characters, except the following: \/:*?"<>|
type Cache interface {
// Get returns a certificate data for the specified key.
// If there's no such key, Get returns ErrCacheMiss.
diff --git a/vendor/golang.org/x/crypto/acme/autocert/renewal.go b/vendor/golang.org/x/crypto/acme/autocert/renewal.go
index 6c5da2b..ef3e44e 100644
--- a/vendor/golang.org/x/crypto/acme/autocert/renewal.go
+++ b/vendor/golang.org/x/crypto/acme/autocert/renewal.go
@@ -17,9 +17,9 @@ const renewJitter = time.Hour
// domainRenewal tracks the state used by the periodic timers
// renewing a single domain's cert.
type domainRenewal struct {
- m *Manager
- domain string
- key crypto.Signer
+ m *Manager
+ ck certKey
+ key crypto.Signer
timerMu sync.Mutex
timer *time.Timer
@@ -71,25 +71,43 @@ func (dr *domainRenewal) renew() {
testDidRenewLoop(next, err)
}
+// updateState locks and replaces the relevant Manager.state item with the given
+// state. It additionally updates dr.key with the given state's key.
+func (dr *domainRenewal) updateState(state *certState) {
+ dr.m.stateMu.Lock()
+ defer dr.m.stateMu.Unlock()
+ dr.key = state.key
+ dr.m.state[dr.ck] = state
+}
+
// do is similar to Manager.createCert but it doesn't lock a Manager.state item.
// Instead, it requests a new certificate independently and, upon success,
// replaces dr.m.state item with a new one and updates cache for the given domain.
//
-// It may return immediately if the expiration date of the currently cached cert
-// is far enough in the future.
+// It may lock and update the Manager.state if the expiration date of the currently
+// cached cert is far enough in the future.
//
// The returned value is a time interval after which the renewal should occur again.
func (dr *domainRenewal) do(ctx context.Context) (time.Duration, error) {
// a race is likely unavoidable in a distributed environment
// but we try nonetheless
- if tlscert, err := dr.m.cacheGet(ctx, dr.domain); err == nil {
+ if tlscert, err := dr.m.cacheGet(ctx, dr.ck); err == nil {
next := dr.next(tlscert.Leaf.NotAfter)
if next > dr.m.renewBefore()+renewJitter {
- return next, nil
+ signer, ok := tlscert.PrivateKey.(crypto.Signer)
+ if ok {
+ state := &certState{
+ key: signer,
+ cert: tlscert.Certificate,
+ leaf: tlscert.Leaf,
+ }
+ dr.updateState(state)
+ return next, nil
+ }
}
}
- der, leaf, err := dr.m.authorizedCert(ctx, dr.key, dr.domain)
+ der, leaf, err := dr.m.authorizedCert(ctx, dr.key, dr.ck)
if err != nil {
return 0, err
}
@@ -102,11 +120,10 @@ func (dr *domainRenewal) do(ctx context.Context) (time.Duration, error) {
if err != nil {
return 0, err
}
- dr.m.cachePut(ctx, dr.domain, tlscert)
- dr.m.stateMu.Lock()
- defer dr.m.stateMu.Unlock()
- // m.state is guaranteed to be non-nil at this point
- dr.m.state[dr.domain] = state
+ if err := dr.m.cachePut(ctx, dr.ck, tlscert); err != nil {
+ return 0, err
+ }
+ dr.updateState(state)
return dr.next(leaf.NotAfter), nil
}