1 // Copyright 2016 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package autocert provides automatic access to certificates from Let's Encrypt
6 // and any other ACME-based CA.
8 // This package is a work in progress and makes no API stability promises.
34 "golang.org/x/crypto/acme"
37 // createCertRetryAfter is how much time to wait before removing a failed state
38 // entry due to an unsuccessful createCert call.
39 // This is a variable instead of a const for testing.
40 // TODO: Consider making it configurable or an exp backoff?
41 var createCertRetryAfter = time.Minute
43 // pseudoRand is safe for concurrent use.
44 var pseudoRand *lockedMathRand
47 src := mathrand.NewSource(time.Now().UnixNano())
48 pseudoRand = &lockedMathRand{rnd: mathrand.New(src)}
51 // AcceptTOS is a Manager.Prompt function that always returns true to
52 // indicate acceptance of the CA's Terms of Service during account
54 func AcceptTOS(tosURL string) bool { return true }
56 // HostPolicy specifies which host names the Manager is allowed to respond to.
57 // It returns a non-nil error if the host should be rejected.
58 // The returned error is accessible via tls.Conn.Handshake and its callers.
59 // See Manager's HostPolicy field and GetCertificate method docs for more details.
60 type HostPolicy func(ctx context.Context, host string) error
62 // HostWhitelist returns a policy where only the specified host names are allowed.
63 // Only exact matches are currently supported. Subdomains, regexp or wildcard
65 func HostWhitelist(hosts ...string) HostPolicy {
66 whitelist := make(map[string]bool, len(hosts))
67 for _, h := range hosts {
70 return func(_ context.Context, host string) error {
72 return errors.New("acme/autocert: host not configured")
78 // defaultHostPolicy is used when Manager.HostPolicy is not set.
79 func defaultHostPolicy(context.Context, string) error {
83 // Manager is a stateful certificate manager built on top of acme.Client.
84 // It obtains and refreshes certificates automatically using "tls-alpn-01",
85 // "tls-sni-01", "tls-sni-02" and "http-01" challenge types,
86 // as well as providing them to a TLS server via tls.Config.
88 // You must specify a cache implementation, such as DirCache,
89 // to reuse obtained certificates across program restarts.
90 // Otherwise your server is very likely to exceed the certificate
91 // issuer's request rate limits.
93 // Prompt specifies a callback function to conditionally accept a CA's Terms of Service (TOS).
94 // The registration may require the caller to agree to the CA's TOS.
95 // If so, Manager calls Prompt with a TOS URL provided by the CA. Prompt should report
96 // whether the caller agrees to the terms.
98 // To always accept the terms, the callers can use AcceptTOS.
99 Prompt func(tosURL string) bool
101 // Cache optionally stores and retrieves previously-obtained certificates
102 // and other state. If nil, certs will only be cached for the lifetime of
103 // the Manager. Multiple Managers can share the same Cache.
105 // Using a persistent Cache, such as DirCache, is strongly recommended.
108 // HostPolicy controls which domains the Manager will attempt
109 // to retrieve new certificates for. It does not affect cached certs.
111 // If non-nil, HostPolicy is called before requesting a new cert.
112 // If nil, all hosts are currently allowed. This is not recommended,
113 // as it opens a potential attack where clients connect to a server
114 // by IP address and pretend to be asking for an incorrect host name.
115 // Manager will attempt to obtain a certificate for that host, incorrectly,
116 // eventually reaching the CA's rate limit for certificate requests
117 // and making it impossible to obtain actual certificates.
119 // See GetCertificate for more details.
120 HostPolicy HostPolicy
122 // RenewBefore optionally specifies how early certificates should
123 // be renewed before they expire.
125 // If zero, they're renewed 30 days before expiration.
126 RenewBefore time.Duration
128 // Client is used to perform low-level operations, such as account registration
129 // and requesting new certificates.
131 // If Client is nil, a zero-value acme.Client is used with acme.LetsEncryptURL
132 // as directory endpoint. If the Client.Key is nil, a new ECDSA P-256 key is
133 // generated and, if Cache is not nil, stored in cache.
135 // Mutating the field after the first call of GetCertificate method will have no effect.
138 // Email optionally specifies a contact email address.
139 // This is used by CAs, such as Let's Encrypt, to notify about problems
140 // with issued certificates.
142 // If the Client's account key is already registered, Email is not used.
145 // ForceRSA used to make the Manager generate RSA certificates. It is now ignored.
147 // Deprecated: the Manager will request the correct type of certificate based
148 // on what each client supports.
151 // ExtraExtensions are used when generating a new CSR (Certificate Request),
152 // thus allowing customization of the resulting certificate.
153 // For instance, TLS Feature Extension (RFC 7633) can be used
154 // to prevent an OCSP downgrade attack.
156 // The field value is passed to crypto/x509.CreateCertificateRequest
157 // in the template's ExtraExtensions field as is.
158 ExtraExtensions []pkix.Extension
161 client *acme.Client // initialized by acmeClient method
164 state map[certKey]*certState
166 // renewal tracks the set of domains currently running renewal timers.
168 renewal map[certKey]*domainRenewal
170 // tokensMu guards the rest of the fields: tryHTTP01, certTokens and httpTokens.
171 tokensMu sync.RWMutex
172 // tryHTTP01 indicates whether the Manager should try "http-01" challenge type
173 // during the authorization flow.
175 // httpTokens contains response body values for http-01 challenges
176 // and is keyed by the URL path at which a challenge response is expected
177 // to be provisioned.
178 // The entries are stored for the duration of the authorization flow.
179 httpTokens map[string][]byte
180 // certTokens contains temporary certificates for tls-sni and tls-alpn challenges
181 // and is keyed by token domain name, which matches server name of ClientHello.
182 // Keys always have ".acme.invalid" suffix for tls-sni. Otherwise, they are domain names
184 // The entries are stored for the duration of the authorization flow.
185 certTokens map[string]*tls.Certificate
186 // nowFunc, if not nil, returns the current time. This may be set for
188 nowFunc func() time.Time
191 // certKey is the key by which certificates are tracked in state, renewal and cache.
192 type certKey struct {
193 domain string // without trailing dot
194 isRSA bool // RSA cert for legacy clients (as opposed to default ECDSA)
195 isToken bool // tls-based challenge token cert; key type is undefined regardless of isRSA
198 func (c certKey) String() string {
200 return c.domain + "+token"
203 return c.domain + "+rsa"
208 // TLSConfig creates a new TLS config suitable for net/http.Server servers,
209 // supporting HTTP/2 and the tls-alpn-01 ACME challenge type.
210 func (m *Manager) TLSConfig() *tls.Config {
212 GetCertificate: m.GetCertificate,
213 NextProtos: []string{
214 "h2", "http/1.1", // enable HTTP/2
215 acme.ALPNProto, // enable tls-alpn ACME challenges
220 // GetCertificate implements the tls.Config.GetCertificate hook.
221 // It provides a TLS certificate for hello.ServerName host, including answering
222 // tls-alpn-01 and *.acme.invalid (tls-sni-01 and tls-sni-02) challenges.
223 // All other fields of hello are ignored.
225 // If m.HostPolicy is non-nil, GetCertificate calls the policy before requesting
226 // a new cert. A non-nil error returned from m.HostPolicy halts TLS negotiation.
227 // The error is propagated back to the caller of GetCertificate and is user-visible.
228 // This does not affect cached certs. See HostPolicy field description for more details.
230 // If GetCertificate is used directly, instead of via Manager.TLSConfig, package users will
231 // also have to add acme.ALPNProto to NextProtos for tls-alpn-01, or use HTTPHandler
232 // for http-01. (The tls-sni-* challenges have been deprecated by popular ACME providers
233 // due to security issues in the ecosystem.)
234 func (m *Manager) GetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
236 return nil, errors.New("acme/autocert: Manager.Prompt not set")
239 name := hello.ServerName
241 return nil, errors.New("acme/autocert: missing server name")
243 if !strings.Contains(strings.Trim(name, "."), ".") {
244 return nil, errors.New("acme/autocert: server name component count invalid")
246 if strings.ContainsAny(name, `+/\`) {
247 return nil, errors.New("acme/autocert: server name contains invalid character")
250 // In the worst-case scenario, the timeout needs to account for caching, host policy,
251 // domain ownership verification and certificate issuance.
252 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
255 // Check whether this is a token cert requested for TLS-SNI or TLS-ALPN challenge.
256 if wantsTokenCert(hello) {
258 defer m.tokensMu.RUnlock()
259 // It's ok to use the same token cert key for both tls-sni and tls-alpn
260 // because there's always at most 1 token cert per on-going domain authorization.
261 // See m.verify for details.
262 if cert := m.certTokens[name]; cert != nil {
265 if cert, err := m.cacheGet(ctx, certKey{domain: name, isToken: true}); err == nil {
268 // TODO: cache error results?
269 return nil, fmt.Errorf("acme/autocert: no token cert for %q", name)
274 domain: strings.TrimSuffix(name, "."), // golang.org/issue/18114
275 isRSA: !supportsECDSA(hello),
277 cert, err := m.cert(ctx, ck)
281 if err != ErrCacheMiss {
286 if err := m.hostPolicy()(ctx, name); err != nil {
289 cert, err = m.createCert(ctx, ck)
293 m.cachePut(ctx, ck, cert)
297 // wantsTokenCert reports whether a TLS request with SNI is made by a CA server
298 // for a challenge verification.
299 func wantsTokenCert(hello *tls.ClientHelloInfo) bool {
301 if len(hello.SupportedProtos) == 1 && hello.SupportedProtos[0] == acme.ALPNProto {
305 return strings.HasSuffix(hello.ServerName, ".acme.invalid")
308 func supportsECDSA(hello *tls.ClientHelloInfo) bool {
309 // The "signature_algorithms" extension, if present, limits the key exchange
310 // algorithms allowed by the cipher suites. See RFC 5246, section 7.4.1.4.1.
311 if hello.SignatureSchemes != nil {
314 for _, scheme := range hello.SignatureSchemes {
315 const tlsECDSAWithSHA1 tls.SignatureScheme = 0x0203 // constant added in Go 1.10
317 case tlsECDSAWithSHA1, tls.ECDSAWithP256AndSHA256,
318 tls.ECDSAWithP384AndSHA384, tls.ECDSAWithP521AndSHA512:
327 if hello.SupportedCurves != nil {
329 for _, curve := range hello.SupportedCurves {
330 if curve == tls.CurveP256 {
339 for _, suite := range hello.CipherSuites {
341 case tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
342 tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
343 tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
344 tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
345 tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
346 tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
347 tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305:
354 // HTTPHandler configures the Manager to provision ACME "http-01" challenge responses.
355 // It returns an http.Handler that responds to the challenges and must be
356 // running on port 80. If it receives a request that is not an ACME challenge,
357 // it delegates the request to the optional fallback handler.
359 // If fallback is nil, the returned handler redirects all GET and HEAD requests
360 // to the default TLS port 443 with 302 Found status code, preserving the original
361 // request path and query. It responds with 400 Bad Request to all other HTTP methods.
362 // The fallback is not protected by the optional HostPolicy.
364 // Because the fallback handler is run with unencrypted port 80 requests,
365 // the fallback should not serve TLS-only requests.
367 // If HTTPHandler is never called, the Manager will only use the "tls-alpn-01"
368 // challenge for domain verification.
369 func (m *Manager) HTTPHandler(fallback http.Handler) http.Handler {
371 defer m.tokensMu.Unlock()
375 fallback = http.HandlerFunc(handleHTTPRedirect)
377 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
378 if !strings.HasPrefix(r.URL.Path, "/.well-known/acme-challenge/") {
379 fallback.ServeHTTP(w, r)
382 // A reasonable context timeout for cache and host policy only,
383 // because we don't wait for a new certificate issuance here.
384 ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
386 if err := m.hostPolicy()(ctx, r.Host); err != nil {
387 http.Error(w, err.Error(), http.StatusForbidden)
390 data, err := m.httpToken(ctx, r.URL.Path)
392 http.Error(w, err.Error(), http.StatusNotFound)
399 func handleHTTPRedirect(w http.ResponseWriter, r *http.Request) {
400 if r.Method != "GET" && r.Method != "HEAD" {
401 http.Error(w, "Use HTTPS", http.StatusBadRequest)
404 target := "https://" + stripPort(r.Host) + r.URL.RequestURI()
405 http.Redirect(w, r, target, http.StatusFound)
408 func stripPort(hostport string) string {
409 host, _, err := net.SplitHostPort(hostport)
413 return net.JoinHostPort(host, "443")
416 // cert returns an existing certificate either from m.state or cache.
417 // If a certificate is found in cache but not in m.state, the latter will be filled
418 // with the cached value.
419 func (m *Manager) cert(ctx context.Context, ck certKey) (*tls.Certificate, error) {
421 if s, ok := m.state[ck]; ok {
427 defer m.stateMu.Unlock()
428 cert, err := m.cacheGet(ctx, ck)
432 signer, ok := cert.PrivateKey.(crypto.Signer)
434 return nil, errors.New("acme/autocert: private key cannot sign")
437 m.state = make(map[certKey]*certState)
441 cert: cert.Certificate,
445 go m.renew(ck, s.key, s.leaf.NotAfter)
449 // cacheGet always returns a valid certificate, or an error otherwise.
450 // If a cached certificate exists but is not valid, ErrCacheMiss is returned.
451 func (m *Manager) cacheGet(ctx context.Context, ck certKey) (*tls.Certificate, error) {
453 return nil, ErrCacheMiss
455 data, err := m.Cache.Get(ctx, ck.String())
461 priv, pub := pem.Decode(data)
462 if priv == nil || !strings.Contains(priv.Type, "PRIVATE") {
463 return nil, ErrCacheMiss
465 privKey, err := parsePrivateKey(priv.Bytes)
474 b, pub = pem.Decode(pub)
478 pubDER = append(pubDER, b.Bytes)
481 // Leftover content not consumed by pem.Decode. Corrupt. Ignore.
482 return nil, ErrCacheMiss
485 // verify and create TLS cert
486 leaf, err := validCert(ck, pubDER, privKey, m.now())
488 return nil, ErrCacheMiss
490 tlscert := &tls.Certificate{
498 func (m *Manager) cachePut(ctx context.Context, ck certKey, tlscert *tls.Certificate) error {
503 // contains PEM-encoded data
507 switch key := tlscert.PrivateKey.(type) {
508 case *ecdsa.PrivateKey:
509 if err := encodeECDSAKey(&buf, key); err != nil {
512 case *rsa.PrivateKey:
513 b := x509.MarshalPKCS1PrivateKey(key)
514 pb := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: b}
515 if err := pem.Encode(&buf, pb); err != nil {
519 return errors.New("acme/autocert: unknown private key type")
523 for _, b := range tlscert.Certificate {
524 pb := &pem.Block{Type: "CERTIFICATE", Bytes: b}
525 if err := pem.Encode(&buf, pb); err != nil {
530 return m.Cache.Put(ctx, ck.String(), buf.Bytes())
533 func encodeECDSAKey(w io.Writer, key *ecdsa.PrivateKey) error {
534 b, err := x509.MarshalECPrivateKey(key)
538 pb := &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}
539 return pem.Encode(w, pb)
542 // createCert starts the domain ownership verification and returns a certificate
543 // for that domain upon success.
545 // If the domain is already being verified, it waits for the existing verification to complete.
546 // Either way, createCert blocks for the duration of the whole process.
547 func (m *Manager) createCert(ctx context.Context, ck certKey) (*tls.Certificate, error) {
548 // TODO: maybe rewrite this whole piece using sync.Once
549 state, err := m.certState(ck)
553 // state may exist if another goroutine is already working on it
554 // in which case just wait for it to finish
557 defer state.RUnlock()
558 return state.tlscert()
561 // We are the first; state is locked.
562 // Unblock the readers when domain ownership is verified
563 // and we got the cert or the process failed.
567 der, leaf, err := m.authorizedCert(ctx, state.key, ck)
569 // Remove the failed state after some time,
570 // making the manager call createCert again on the following TLS hello.
571 time.AfterFunc(createCertRetryAfter, func() {
572 defer testDidRemoveState(ck)
574 defer m.stateMu.Unlock()
575 // Verify the state hasn't changed and it's still invalid
581 if _, err := validCert(ck, s.cert, s.key, m.now()); err == nil {
590 go m.renew(ck, state.key, state.leaf.NotAfter)
591 return state.tlscert()
594 // certState returns a new or existing certState.
595 // If a new certState is returned, state.exist is false and the state is locked.
596 // The returned error is non-nil only in the case where a new state could not be created.
597 func (m *Manager) certState(ck certKey) (*certState, error) {
599 defer m.stateMu.Unlock()
601 m.state = make(map[certKey]*certState)
604 if state, ok := m.state[ck]; ok {
614 key, err = rsa.GenerateKey(rand.Reader, 2048)
616 key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
626 state.Lock() // will be unlocked by m.certState caller
631 // authorizedCert starts the domain ownership verification process and requests a new cert upon success.
632 // The key argument is the certificate private key.
633 func (m *Manager) authorizedCert(ctx context.Context, key crypto.Signer, ck certKey) (der [][]byte, leaf *x509.Certificate, err error) {
634 client, err := m.acmeClient(ctx)
639 if err := m.verify(ctx, client, ck.domain); err != nil {
642 csr, err := certRequest(key, ck.domain, m.ExtraExtensions)
646 der, _, err = client.CreateCert(ctx, csr, 0, true)
650 leaf, err = validCert(ck, der, key, m.now())
654 return der, leaf, nil
657 // revokePendingAuthz revokes all authorizations idenfied by the elements of uri slice.
658 // It ignores revocation errors.
659 func (m *Manager) revokePendingAuthz(ctx context.Context, uri []string) {
660 client, err := m.acmeClient(ctx)
664 for _, u := range uri {
665 client.RevokeAuthorization(ctx, u)
669 // verify runs the identifier (domain) authorization flow
670 // using each applicable ACME challenge type.
671 func (m *Manager) verify(ctx context.Context, client *acme.Client, domain string) error {
672 // The list of challenge types we'll try to fulfill
673 // in this specific order.
674 challengeTypes := []string{"tls-alpn-01", "tls-sni-02", "tls-sni-01"}
677 challengeTypes = append(challengeTypes, "http-01")
681 // Keep track of pending authzs and revoke the ones that did not validate.
682 pendingAuthzs := make(map[string]bool)
685 for k, pending := range pendingAuthzs {
691 // Use "detached" background context.
692 // The revocations need not happen in the current verification flow.
693 go m.revokePendingAuthz(context.Background(), uri)
697 // errs accumulates challenge failure errors, printed if all fail
698 errs := make(map[*acme.Challenge]error)
699 var nextTyp int // challengeType index of the next challenge type to try
701 // Start domain authorization and get the challenge.
702 authz, err := client.Authorize(ctx, domain)
706 // No point in accepting challenges if the authorization status
707 // is in a final state.
708 switch authz.Status {
709 case acme.StatusValid:
710 return nil // already authorized
711 case acme.StatusInvalid:
712 return fmt.Errorf("acme/autocert: invalid authorization %q", authz.URI)
715 pendingAuthzs[authz.URI] = true
717 // Pick the next preferred challenge.
718 var chal *acme.Challenge
719 for chal == nil && nextTyp < len(challengeTypes) {
720 chal = pickChallenge(challengeTypes[nextTyp], authz.Challenges)
724 errorMsg := fmt.Sprintf("acme/autocert: unable to authorize %q", domain)
725 for chal, err := range errs {
726 errorMsg += fmt.Sprintf("; challenge %q failed with error: %v", chal.Type, err)
728 return errors.New(errorMsg)
730 cleanup, err := m.fulfill(ctx, client, chal, domain)
736 if _, err := client.Accept(ctx, chal); err != nil {
741 // A challenge is fulfilled and accepted: wait for the CA to validate.
742 if _, err := client.WaitAuthorization(ctx, authz.URI); err != nil {
746 delete(pendingAuthzs, authz.URI)
751 // fulfill provisions a response to the challenge chal.
752 // The cleanup is non-nil only if provisioning succeeded.
753 func (m *Manager) fulfill(ctx context.Context, client *acme.Client, chal *acme.Challenge, domain string) (cleanup func(), err error) {
756 cert, err := client.TLSALPN01ChallengeCert(chal.Token, domain)
760 m.putCertToken(ctx, domain, &cert)
761 return func() { go m.deleteCertToken(domain) }, nil
763 cert, name, err := client.TLSSNI01ChallengeCert(chal.Token)
767 m.putCertToken(ctx, name, &cert)
768 return func() { go m.deleteCertToken(name) }, nil
770 cert, name, err := client.TLSSNI02ChallengeCert(chal.Token)
774 m.putCertToken(ctx, name, &cert)
775 return func() { go m.deleteCertToken(name) }, nil
777 resp, err := client.HTTP01ChallengeResponse(chal.Token)
781 p := client.HTTP01ChallengePath(chal.Token)
782 m.putHTTPToken(ctx, p, resp)
783 return func() { go m.deleteHTTPToken(p) }, nil
785 return nil, fmt.Errorf("acme/autocert: unknown challenge type %q", chal.Type)
788 func pickChallenge(typ string, chal []*acme.Challenge) *acme.Challenge {
789 for _, c := range chal {
797 // putCertToken stores the token certificate with the specified name
798 // in both m.certTokens map and m.Cache.
799 func (m *Manager) putCertToken(ctx context.Context, name string, cert *tls.Certificate) {
801 defer m.tokensMu.Unlock()
802 if m.certTokens == nil {
803 m.certTokens = make(map[string]*tls.Certificate)
805 m.certTokens[name] = cert
806 m.cachePut(ctx, certKey{domain: name, isToken: true}, cert)
809 // deleteCertToken removes the token certificate with the specified name
810 // from both m.certTokens map and m.Cache.
811 func (m *Manager) deleteCertToken(name string) {
813 defer m.tokensMu.Unlock()
814 delete(m.certTokens, name)
816 ck := certKey{domain: name, isToken: true}
817 m.Cache.Delete(context.Background(), ck.String())
821 // httpToken retrieves an existing http-01 token value from an in-memory map
822 // or the optional cache.
823 func (m *Manager) httpToken(ctx context.Context, tokenPath string) ([]byte, error) {
825 defer m.tokensMu.RUnlock()
826 if v, ok := m.httpTokens[tokenPath]; ok {
830 return nil, fmt.Errorf("acme/autocert: no token at %q", tokenPath)
832 return m.Cache.Get(ctx, httpTokenCacheKey(tokenPath))
835 // putHTTPToken stores an http-01 token value using tokenPath as key
836 // in both in-memory map and the optional Cache.
838 // It ignores any error returned from Cache.Put.
839 func (m *Manager) putHTTPToken(ctx context.Context, tokenPath, val string) {
841 defer m.tokensMu.Unlock()
842 if m.httpTokens == nil {
843 m.httpTokens = make(map[string][]byte)
846 m.httpTokens[tokenPath] = b
848 m.Cache.Put(ctx, httpTokenCacheKey(tokenPath), b)
852 // deleteHTTPToken removes an http-01 token value from both in-memory map
853 // and the optional Cache, ignoring any error returned from the latter.
855 // If m.Cache is non-nil, it blocks until Cache.Delete returns without a timeout.
856 func (m *Manager) deleteHTTPToken(tokenPath string) {
858 defer m.tokensMu.Unlock()
859 delete(m.httpTokens, tokenPath)
861 m.Cache.Delete(context.Background(), httpTokenCacheKey(tokenPath))
865 // httpTokenCacheKey returns a key at which an http-01 token value may be stored
866 // in the Manager's optional Cache.
867 func httpTokenCacheKey(tokenPath string) string {
868 return path.Base(tokenPath) + "+http-01"
871 // renew starts a cert renewal timer loop, one per domain.
873 // The loop is scheduled in two cases:
874 // - a cert was fetched from cache for the first time (wasn't in m.state)
875 // - a new cert was created by m.createCert
877 // The key argument is a certificate private key.
878 // The exp argument is the cert expiration time (NotAfter).
879 func (m *Manager) renew(ck certKey, key crypto.Signer, exp time.Time) {
881 defer m.renewalMu.Unlock()
882 if m.renewal[ck] != nil {
883 // another goroutine is already on it
886 if m.renewal == nil {
887 m.renewal = make(map[certKey]*domainRenewal)
889 dr := &domainRenewal{m: m, ck: ck, key: key}
894 // stopRenew stops all currently running cert renewal timers.
895 // The timers are not restarted during the lifetime of the Manager.
896 func (m *Manager) stopRenew() {
898 defer m.renewalMu.Unlock()
899 for name, dr := range m.renewal {
900 delete(m.renewal, name)
905 func (m *Manager) accountKey(ctx context.Context) (crypto.Signer, error) {
906 const keyName = "acme_account+key"
908 // Previous versions of autocert stored the value under a different key.
909 const legacyKeyName = "acme_account.key"
911 genKey := func() (*ecdsa.PrivateKey, error) {
912 return ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
919 data, err := m.Cache.Get(ctx, keyName)
920 if err == ErrCacheMiss {
921 data, err = m.Cache.Get(ctx, legacyKeyName)
923 if err == ErrCacheMiss {
929 if err := encodeECDSAKey(&buf, key); err != nil {
932 if err := m.Cache.Put(ctx, keyName, buf.Bytes()); err != nil {
941 priv, _ := pem.Decode(data)
942 if priv == nil || !strings.Contains(priv.Type, "PRIVATE") {
943 return nil, errors.New("acme/autocert: invalid account key found in cache")
945 return parsePrivateKey(priv.Bytes)
948 func (m *Manager) acmeClient(ctx context.Context) (*acme.Client, error) {
950 defer m.clientMu.Unlock()
957 client = &acme.Client{DirectoryURL: acme.LetsEncryptURL}
959 if client.Key == nil {
961 client.Key, err = m.accountKey(ctx)
968 contact = []string{"mailto:" + m.Email}
970 a := &acme.Account{Contact: contact}
971 _, err := client.Register(ctx, a, m.Prompt)
972 if ae, ok := err.(*acme.Error); err == nil || ok && ae.StatusCode == http.StatusConflict {
973 // conflict indicates the key is already registered
980 func (m *Manager) hostPolicy() HostPolicy {
981 if m.HostPolicy != nil {
984 return defaultHostPolicy
987 func (m *Manager) renewBefore() time.Duration {
988 if m.RenewBefore > renewJitter {
991 return 720 * time.Hour // 30 days
994 func (m *Manager) now() time.Time {
995 if m.nowFunc != nil {
1001 // certState is ready when its mutex is unlocked for reading.
1002 type certState struct {
1004 locked bool // locked for read/write
1005 key crypto.Signer // private key for cert
1006 cert [][]byte // DER encoding
1007 leaf *x509.Certificate // parsed cert[0]; always non-nil if cert != nil
1010 // tlscert creates a tls.Certificate from s.key and s.cert.
1011 // Callers should wrap it in s.RLock() and s.RUnlock().
1012 func (s *certState) tlscert() (*tls.Certificate, error) {
1014 return nil, errors.New("acme/autocert: missing signer")
1016 if len(s.cert) == 0 {
1017 return nil, errors.New("acme/autocert: missing certificate")
1019 return &tls.Certificate{
1021 Certificate: s.cert,
1026 // certRequest generates a CSR for the given common name cn and optional SANs.
1027 func certRequest(key crypto.Signer, cn string, ext []pkix.Extension, san ...string) ([]byte, error) {
1028 req := &x509.CertificateRequest{
1029 Subject: pkix.Name{CommonName: cn},
1031 ExtraExtensions: ext,
1033 return x509.CreateCertificateRequest(rand.Reader, req, key)
1036 // Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates
1037 // PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys.
1038 // OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.
1040 // Inspired by parsePrivateKey in crypto/tls/tls.go.
1041 func parsePrivateKey(der []byte) (crypto.Signer, error) {
1042 if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
1045 if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
1046 switch key := key.(type) {
1047 case *rsa.PrivateKey:
1049 case *ecdsa.PrivateKey:
1052 return nil, errors.New("acme/autocert: unknown private key type in PKCS#8 wrapping")
1055 if key, err := x509.ParseECPrivateKey(der); err == nil {
1059 return nil, errors.New("acme/autocert: failed to parse private key")
1062 // validCert parses a cert chain provided as der argument and verifies the leaf and der[0]
1063 // correspond to the private key, the domain and key type match, and expiration dates
1064 // are valid. It doesn't do any revocation checking.
1066 // The returned value is the verified leaf cert.
1067 func validCert(ck certKey, der [][]byte, key crypto.Signer, now time.Time) (leaf *x509.Certificate, err error) {
1068 // parse public part(s)
1070 for _, b := range der {
1073 pub := make([]byte, n)
1075 for _, b := range der {
1076 n += copy(pub[n:], b)
1078 x509Cert, err := x509.ParseCertificates(pub)
1079 if err != nil || len(x509Cert) == 0 {
1080 return nil, errors.New("acme/autocert: no public key found")
1082 // verify the leaf is not expired and matches the domain name
1084 if now.Before(leaf.NotBefore) {
1085 return nil, errors.New("acme/autocert: certificate is not valid yet")
1087 if now.After(leaf.NotAfter) {
1088 return nil, errors.New("acme/autocert: expired certificate")
1090 if err := leaf.VerifyHostname(ck.domain); err != nil {
1093 // ensure the leaf corresponds to the private key and matches the certKey type
1094 switch pub := leaf.PublicKey.(type) {
1095 case *rsa.PublicKey:
1096 prv, ok := key.(*rsa.PrivateKey)
1098 return nil, errors.New("acme/autocert: private key type does not match public key type")
1100 if pub.N.Cmp(prv.N) != 0 {
1101 return nil, errors.New("acme/autocert: private key does not match public key")
1103 if !ck.isRSA && !ck.isToken {
1104 return nil, errors.New("acme/autocert: key type does not match expected value")
1106 case *ecdsa.PublicKey:
1107 prv, ok := key.(*ecdsa.PrivateKey)
1109 return nil, errors.New("acme/autocert: private key type does not match public key type")
1111 if pub.X.Cmp(prv.X) != 0 || pub.Y.Cmp(prv.Y) != 0 {
1112 return nil, errors.New("acme/autocert: private key does not match public key")
1114 if ck.isRSA && !ck.isToken {
1115 return nil, errors.New("acme/autocert: key type does not match expected value")
1118 return nil, errors.New("acme/autocert: unknown public key algorithm")
1123 type lockedMathRand struct {
1128 func (r *lockedMathRand) int63n(max int64) int64 {
1130 n := r.rnd.Int63n(max)
1135 // For easier testing.
1137 // Called when a state is removed.
1138 testDidRemoveState = func(certKey) {}