src: Add DMA localagent
[barometer.git] / src / dma / vendor / golang.org / x / crypto / acme / autocert / autocert.go
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.
4
5 // Package autocert provides automatic access to certificates from Let's Encrypt
6 // and any other ACME-based CA.
7 //
8 // This package is a work in progress and makes no API stability promises.
9 package autocert
10
11 import (
12         "bytes"
13         "context"
14         "crypto"
15         "crypto/ecdsa"
16         "crypto/elliptic"
17         "crypto/rand"
18         "crypto/rsa"
19         "crypto/tls"
20         "crypto/x509"
21         "crypto/x509/pkix"
22         "encoding/pem"
23         "errors"
24         "fmt"
25         "io"
26         mathrand "math/rand"
27         "net"
28         "net/http"
29         "path"
30         "strings"
31         "sync"
32         "time"
33
34         "golang.org/x/crypto/acme"
35 )
36
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
42
43 // pseudoRand is safe for concurrent use.
44 var pseudoRand *lockedMathRand
45
46 func init() {
47         src := mathrand.NewSource(time.Now().UnixNano())
48         pseudoRand = &lockedMathRand{rnd: mathrand.New(src)}
49 }
50
51 // AcceptTOS is a Manager.Prompt function that always returns true to
52 // indicate acceptance of the CA's Terms of Service during account
53 // registration.
54 func AcceptTOS(tosURL string) bool { return true }
55
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
61
62 // HostWhitelist returns a policy where only the specified host names are allowed.
63 // Only exact matches are currently supported. Subdomains, regexp or wildcard
64 // will not match.
65 func HostWhitelist(hosts ...string) HostPolicy {
66         whitelist := make(map[string]bool, len(hosts))
67         for _, h := range hosts {
68                 whitelist[h] = true
69         }
70         return func(_ context.Context, host string) error {
71                 if !whitelist[host] {
72                         return errors.New("acme/autocert: host not configured")
73                 }
74                 return nil
75         }
76 }
77
78 // defaultHostPolicy is used when Manager.HostPolicy is not set.
79 func defaultHostPolicy(context.Context, string) error {
80         return nil
81 }
82
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.
87 //
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.
92 type Manager struct {
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.
97         //
98         // To always accept the terms, the callers can use AcceptTOS.
99         Prompt func(tosURL string) bool
100
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.
104         //
105         // Using a persistent Cache, such as DirCache, is strongly recommended.
106         Cache Cache
107
108         // HostPolicy controls which domains the Manager will attempt
109         // to retrieve new certificates for. It does not affect cached certs.
110         //
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.
118         //
119         // See GetCertificate for more details.
120         HostPolicy HostPolicy
121
122         // RenewBefore optionally specifies how early certificates should
123         // be renewed before they expire.
124         //
125         // If zero, they're renewed 30 days before expiration.
126         RenewBefore time.Duration
127
128         // Client is used to perform low-level operations, such as account registration
129         // and requesting new certificates.
130         //
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.
134         //
135         // Mutating the field after the first call of GetCertificate method will have no effect.
136         Client *acme.Client
137
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.
141         //
142         // If the Client's account key is already registered, Email is not used.
143         Email string
144
145         // ForceRSA used to make the Manager generate RSA certificates. It is now ignored.
146         //
147         // Deprecated: the Manager will request the correct type of certificate based
148         // on what each client supports.
149         ForceRSA bool
150
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.
155         //
156         // The field value is passed to crypto/x509.CreateCertificateRequest
157         // in the template's ExtraExtensions field as is.
158         ExtraExtensions []pkix.Extension
159
160         clientMu sync.Mutex
161         client   *acme.Client // initialized by acmeClient method
162
163         stateMu sync.Mutex
164         state   map[certKey]*certState
165
166         // renewal tracks the set of domains currently running renewal timers.
167         renewalMu sync.Mutex
168         renewal   map[certKey]*domainRenewal
169
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.
174         tryHTTP01 bool
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
183         // for tls-alpn.
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
187         // testing purposes.
188         nowFunc func() time.Time
189 }
190
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
196 }
197
198 func (c certKey) String() string {
199         if c.isToken {
200                 return c.domain + "+token"
201         }
202         if c.isRSA {
203                 return c.domain + "+rsa"
204         }
205         return c.domain
206 }
207
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 {
211         return &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
216                 },
217         }
218 }
219
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.
224 //
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.
229 //
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) {
235         if m.Prompt == nil {
236                 return nil, errors.New("acme/autocert: Manager.Prompt not set")
237         }
238
239         name := hello.ServerName
240         if name == "" {
241                 return nil, errors.New("acme/autocert: missing server name")
242         }
243         if !strings.Contains(strings.Trim(name, "."), ".") {
244                 return nil, errors.New("acme/autocert: server name component count invalid")
245         }
246         if strings.ContainsAny(name, `+/\`) {
247                 return nil, errors.New("acme/autocert: server name contains invalid character")
248         }
249
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)
253         defer cancel()
254
255         // Check whether this is a token cert requested for TLS-SNI or TLS-ALPN challenge.
256         if wantsTokenCert(hello) {
257                 m.tokensMu.RLock()
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 {
263                         return cert, nil
264                 }
265                 if cert, err := m.cacheGet(ctx, certKey{domain: name, isToken: true}); err == nil {
266                         return cert, nil
267                 }
268                 // TODO: cache error results?
269                 return nil, fmt.Errorf("acme/autocert: no token cert for %q", name)
270         }
271
272         // regular domain
273         ck := certKey{
274                 domain: strings.TrimSuffix(name, "."), // golang.org/issue/18114
275                 isRSA:  !supportsECDSA(hello),
276         }
277         cert, err := m.cert(ctx, ck)
278         if err == nil {
279                 return cert, nil
280         }
281         if err != ErrCacheMiss {
282                 return nil, err
283         }
284
285         // first-time
286         if err := m.hostPolicy()(ctx, name); err != nil {
287                 return nil, err
288         }
289         cert, err = m.createCert(ctx, ck)
290         if err != nil {
291                 return nil, err
292         }
293         m.cachePut(ctx, ck, cert)
294         return cert, nil
295 }
296
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 {
300         // tls-alpn-01
301         if len(hello.SupportedProtos) == 1 && hello.SupportedProtos[0] == acme.ALPNProto {
302                 return true
303         }
304         // tls-sni-xx
305         return strings.HasSuffix(hello.ServerName, ".acme.invalid")
306 }
307
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 {
312                 ecdsaOK := false
313         schemeLoop:
314                 for _, scheme := range hello.SignatureSchemes {
315                         const tlsECDSAWithSHA1 tls.SignatureScheme = 0x0203 // constant added in Go 1.10
316                         switch scheme {
317                         case tlsECDSAWithSHA1, tls.ECDSAWithP256AndSHA256,
318                                 tls.ECDSAWithP384AndSHA384, tls.ECDSAWithP521AndSHA512:
319                                 ecdsaOK = true
320                                 break schemeLoop
321                         }
322                 }
323                 if !ecdsaOK {
324                         return false
325                 }
326         }
327         if hello.SupportedCurves != nil {
328                 ecdsaOK := false
329                 for _, curve := range hello.SupportedCurves {
330                         if curve == tls.CurveP256 {
331                                 ecdsaOK = true
332                                 break
333                         }
334                 }
335                 if !ecdsaOK {
336                         return false
337                 }
338         }
339         for _, suite := range hello.CipherSuites {
340                 switch suite {
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:
348                         return true
349                 }
350         }
351         return false
352 }
353
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.
358 //
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.
363 //
364 // Because the fallback handler is run with unencrypted port 80 requests,
365 // the fallback should not serve TLS-only requests.
366 //
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 {
370         m.tokensMu.Lock()
371         defer m.tokensMu.Unlock()
372         m.tryHTTP01 = true
373
374         if fallback == nil {
375                 fallback = http.HandlerFunc(handleHTTPRedirect)
376         }
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)
380                         return
381                 }
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)
385                 defer cancel()
386                 if err := m.hostPolicy()(ctx, r.Host); err != nil {
387                         http.Error(w, err.Error(), http.StatusForbidden)
388                         return
389                 }
390                 data, err := m.httpToken(ctx, r.URL.Path)
391                 if err != nil {
392                         http.Error(w, err.Error(), http.StatusNotFound)
393                         return
394                 }
395                 w.Write(data)
396         })
397 }
398
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)
402                 return
403         }
404         target := "https://" + stripPort(r.Host) + r.URL.RequestURI()
405         http.Redirect(w, r, target, http.StatusFound)
406 }
407
408 func stripPort(hostport string) string {
409         host, _, err := net.SplitHostPort(hostport)
410         if err != nil {
411                 return hostport
412         }
413         return net.JoinHostPort(host, "443")
414 }
415
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) {
420         m.stateMu.Lock()
421         if s, ok := m.state[ck]; ok {
422                 m.stateMu.Unlock()
423                 s.RLock()
424                 defer s.RUnlock()
425                 return s.tlscert()
426         }
427         defer m.stateMu.Unlock()
428         cert, err := m.cacheGet(ctx, ck)
429         if err != nil {
430                 return nil, err
431         }
432         signer, ok := cert.PrivateKey.(crypto.Signer)
433         if !ok {
434                 return nil, errors.New("acme/autocert: private key cannot sign")
435         }
436         if m.state == nil {
437                 m.state = make(map[certKey]*certState)
438         }
439         s := &certState{
440                 key:  signer,
441                 cert: cert.Certificate,
442                 leaf: cert.Leaf,
443         }
444         m.state[ck] = s
445         go m.renew(ck, s.key, s.leaf.NotAfter)
446         return cert, nil
447 }
448
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) {
452         if m.Cache == nil {
453                 return nil, ErrCacheMiss
454         }
455         data, err := m.Cache.Get(ctx, ck.String())
456         if err != nil {
457                 return nil, err
458         }
459
460         // private
461         priv, pub := pem.Decode(data)
462         if priv == nil || !strings.Contains(priv.Type, "PRIVATE") {
463                 return nil, ErrCacheMiss
464         }
465         privKey, err := parsePrivateKey(priv.Bytes)
466         if err != nil {
467                 return nil, err
468         }
469
470         // public
471         var pubDER [][]byte
472         for len(pub) > 0 {
473                 var b *pem.Block
474                 b, pub = pem.Decode(pub)
475                 if b == nil {
476                         break
477                 }
478                 pubDER = append(pubDER, b.Bytes)
479         }
480         if len(pub) > 0 {
481                 // Leftover content not consumed by pem.Decode. Corrupt. Ignore.
482                 return nil, ErrCacheMiss
483         }
484
485         // verify and create TLS cert
486         leaf, err := validCert(ck, pubDER, privKey, m.now())
487         if err != nil {
488                 return nil, ErrCacheMiss
489         }
490         tlscert := &tls.Certificate{
491                 Certificate: pubDER,
492                 PrivateKey:  privKey,
493                 Leaf:        leaf,
494         }
495         return tlscert, nil
496 }
497
498 func (m *Manager) cachePut(ctx context.Context, ck certKey, tlscert *tls.Certificate) error {
499         if m.Cache == nil {
500                 return nil
501         }
502
503         // contains PEM-encoded data
504         var buf bytes.Buffer
505
506         // private
507         switch key := tlscert.PrivateKey.(type) {
508         case *ecdsa.PrivateKey:
509                 if err := encodeECDSAKey(&buf, key); err != nil {
510                         return err
511                 }
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 {
516                         return err
517                 }
518         default:
519                 return errors.New("acme/autocert: unknown private key type")
520         }
521
522         // public
523         for _, b := range tlscert.Certificate {
524                 pb := &pem.Block{Type: "CERTIFICATE", Bytes: b}
525                 if err := pem.Encode(&buf, pb); err != nil {
526                         return err
527                 }
528         }
529
530         return m.Cache.Put(ctx, ck.String(), buf.Bytes())
531 }
532
533 func encodeECDSAKey(w io.Writer, key *ecdsa.PrivateKey) error {
534         b, err := x509.MarshalECPrivateKey(key)
535         if err != nil {
536                 return err
537         }
538         pb := &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}
539         return pem.Encode(w, pb)
540 }
541
542 // createCert starts the domain ownership verification and returns a certificate
543 // for that domain upon success.
544 //
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)
550         if err != nil {
551                 return nil, err
552         }
553         // state may exist if another goroutine is already working on it
554         // in which case just wait for it to finish
555         if !state.locked {
556                 state.RLock()
557                 defer state.RUnlock()
558                 return state.tlscert()
559         }
560
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.
564         defer state.Unlock()
565         state.locked = false
566
567         der, leaf, err := m.authorizedCert(ctx, state.key, ck)
568         if err != nil {
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)
573                         m.stateMu.Lock()
574                         defer m.stateMu.Unlock()
575                         // Verify the state hasn't changed and it's still invalid
576                         // before deleting.
577                         s, ok := m.state[ck]
578                         if !ok {
579                                 return
580                         }
581                         if _, err := validCert(ck, s.cert, s.key, m.now()); err == nil {
582                                 return
583                         }
584                         delete(m.state, ck)
585                 })
586                 return nil, err
587         }
588         state.cert = der
589         state.leaf = leaf
590         go m.renew(ck, state.key, state.leaf.NotAfter)
591         return state.tlscert()
592 }
593
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) {
598         m.stateMu.Lock()
599         defer m.stateMu.Unlock()
600         if m.state == nil {
601                 m.state = make(map[certKey]*certState)
602         }
603         // existing state
604         if state, ok := m.state[ck]; ok {
605                 return state, nil
606         }
607
608         // new locked state
609         var (
610                 err error
611                 key crypto.Signer
612         )
613         if ck.isRSA {
614                 key, err = rsa.GenerateKey(rand.Reader, 2048)
615         } else {
616                 key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
617         }
618         if err != nil {
619                 return nil, err
620         }
621
622         state := &certState{
623                 key:    key,
624                 locked: true,
625         }
626         state.Lock() // will be unlocked by m.certState caller
627         m.state[ck] = state
628         return state, nil
629 }
630
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)
635         if err != nil {
636                 return nil, nil, err
637         }
638
639         if err := m.verify(ctx, client, ck.domain); err != nil {
640                 return nil, nil, err
641         }
642         csr, err := certRequest(key, ck.domain, m.ExtraExtensions)
643         if err != nil {
644                 return nil, nil, err
645         }
646         der, _, err = client.CreateCert(ctx, csr, 0, true)
647         if err != nil {
648                 return nil, nil, err
649         }
650         leaf, err = validCert(ck, der, key, m.now())
651         if err != nil {
652                 return nil, nil, err
653         }
654         return der, leaf, nil
655 }
656
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)
661         if err != nil {
662                 return
663         }
664         for _, u := range uri {
665                 client.RevokeAuthorization(ctx, u)
666         }
667 }
668
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"}
675         m.tokensMu.RLock()
676         if m.tryHTTP01 {
677                 challengeTypes = append(challengeTypes, "http-01")
678         }
679         m.tokensMu.RUnlock()
680
681         // Keep track of pending authzs and revoke the ones that did not validate.
682         pendingAuthzs := make(map[string]bool)
683         defer func() {
684                 var uri []string
685                 for k, pending := range pendingAuthzs {
686                         if pending {
687                                 uri = append(uri, k)
688                         }
689                 }
690                 if len(uri) > 0 {
691                         // Use "detached" background context.
692                         // The revocations need not happen in the current verification flow.
693                         go m.revokePendingAuthz(context.Background(), uri)
694                 }
695         }()
696
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
700         for {
701                 // Start domain authorization and get the challenge.
702                 authz, err := client.Authorize(ctx, domain)
703                 if err != nil {
704                         return err
705                 }
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)
713                 }
714
715                 pendingAuthzs[authz.URI] = true
716
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)
721                         nextTyp++
722                 }
723                 if chal == nil {
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)
727                         }
728                         return errors.New(errorMsg)
729                 }
730                 cleanup, err := m.fulfill(ctx, client, chal, domain)
731                 if err != nil {
732                         errs[chal] = err
733                         continue
734                 }
735                 defer cleanup()
736                 if _, err := client.Accept(ctx, chal); err != nil {
737                         errs[chal] = err
738                         continue
739                 }
740
741                 // A challenge is fulfilled and accepted: wait for the CA to validate.
742                 if _, err := client.WaitAuthorization(ctx, authz.URI); err != nil {
743                         errs[chal] = err
744                         continue
745                 }
746                 delete(pendingAuthzs, authz.URI)
747                 return nil
748         }
749 }
750
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) {
754         switch chal.Type {
755         case "tls-alpn-01":
756                 cert, err := client.TLSALPN01ChallengeCert(chal.Token, domain)
757                 if err != nil {
758                         return nil, err
759                 }
760                 m.putCertToken(ctx, domain, &cert)
761                 return func() { go m.deleteCertToken(domain) }, nil
762         case "tls-sni-01":
763                 cert, name, err := client.TLSSNI01ChallengeCert(chal.Token)
764                 if err != nil {
765                         return nil, err
766                 }
767                 m.putCertToken(ctx, name, &cert)
768                 return func() { go m.deleteCertToken(name) }, nil
769         case "tls-sni-02":
770                 cert, name, err := client.TLSSNI02ChallengeCert(chal.Token)
771                 if err != nil {
772                         return nil, err
773                 }
774                 m.putCertToken(ctx, name, &cert)
775                 return func() { go m.deleteCertToken(name) }, nil
776         case "http-01":
777                 resp, err := client.HTTP01ChallengeResponse(chal.Token)
778                 if err != nil {
779                         return nil, err
780                 }
781                 p := client.HTTP01ChallengePath(chal.Token)
782                 m.putHTTPToken(ctx, p, resp)
783                 return func() { go m.deleteHTTPToken(p) }, nil
784         }
785         return nil, fmt.Errorf("acme/autocert: unknown challenge type %q", chal.Type)
786 }
787
788 func pickChallenge(typ string, chal []*acme.Challenge) *acme.Challenge {
789         for _, c := range chal {
790                 if c.Type == typ {
791                         return c
792                 }
793         }
794         return nil
795 }
796
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) {
800         m.tokensMu.Lock()
801         defer m.tokensMu.Unlock()
802         if m.certTokens == nil {
803                 m.certTokens = make(map[string]*tls.Certificate)
804         }
805         m.certTokens[name] = cert
806         m.cachePut(ctx, certKey{domain: name, isToken: true}, cert)
807 }
808
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) {
812         m.tokensMu.Lock()
813         defer m.tokensMu.Unlock()
814         delete(m.certTokens, name)
815         if m.Cache != nil {
816                 ck := certKey{domain: name, isToken: true}
817                 m.Cache.Delete(context.Background(), ck.String())
818         }
819 }
820
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) {
824         m.tokensMu.RLock()
825         defer m.tokensMu.RUnlock()
826         if v, ok := m.httpTokens[tokenPath]; ok {
827                 return v, nil
828         }
829         if m.Cache == nil {
830                 return nil, fmt.Errorf("acme/autocert: no token at %q", tokenPath)
831         }
832         return m.Cache.Get(ctx, httpTokenCacheKey(tokenPath))
833 }
834
835 // putHTTPToken stores an http-01 token value using tokenPath as key
836 // in both in-memory map and the optional Cache.
837 //
838 // It ignores any error returned from Cache.Put.
839 func (m *Manager) putHTTPToken(ctx context.Context, tokenPath, val string) {
840         m.tokensMu.Lock()
841         defer m.tokensMu.Unlock()
842         if m.httpTokens == nil {
843                 m.httpTokens = make(map[string][]byte)
844         }
845         b := []byte(val)
846         m.httpTokens[tokenPath] = b
847         if m.Cache != nil {
848                 m.Cache.Put(ctx, httpTokenCacheKey(tokenPath), b)
849         }
850 }
851
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.
854 //
855 // If m.Cache is non-nil, it blocks until Cache.Delete returns without a timeout.
856 func (m *Manager) deleteHTTPToken(tokenPath string) {
857         m.tokensMu.Lock()
858         defer m.tokensMu.Unlock()
859         delete(m.httpTokens, tokenPath)
860         if m.Cache != nil {
861                 m.Cache.Delete(context.Background(), httpTokenCacheKey(tokenPath))
862         }
863 }
864
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"
869 }
870
871 // renew starts a cert renewal timer loop, one per domain.
872 //
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
876 //
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) {
880         m.renewalMu.Lock()
881         defer m.renewalMu.Unlock()
882         if m.renewal[ck] != nil {
883                 // another goroutine is already on it
884                 return
885         }
886         if m.renewal == nil {
887                 m.renewal = make(map[certKey]*domainRenewal)
888         }
889         dr := &domainRenewal{m: m, ck: ck, key: key}
890         m.renewal[ck] = dr
891         dr.start(exp)
892 }
893
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() {
897         m.renewalMu.Lock()
898         defer m.renewalMu.Unlock()
899         for name, dr := range m.renewal {
900                 delete(m.renewal, name)
901                 dr.stop()
902         }
903 }
904
905 func (m *Manager) accountKey(ctx context.Context) (crypto.Signer, error) {
906         const keyName = "acme_account+key"
907
908         // Previous versions of autocert stored the value under a different key.
909         const legacyKeyName = "acme_account.key"
910
911         genKey := func() (*ecdsa.PrivateKey, error) {
912                 return ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
913         }
914
915         if m.Cache == nil {
916                 return genKey()
917         }
918
919         data, err := m.Cache.Get(ctx, keyName)
920         if err == ErrCacheMiss {
921                 data, err = m.Cache.Get(ctx, legacyKeyName)
922         }
923         if err == ErrCacheMiss {
924                 key, err := genKey()
925                 if err != nil {
926                         return nil, err
927                 }
928                 var buf bytes.Buffer
929                 if err := encodeECDSAKey(&buf, key); err != nil {
930                         return nil, err
931                 }
932                 if err := m.Cache.Put(ctx, keyName, buf.Bytes()); err != nil {
933                         return nil, err
934                 }
935                 return key, nil
936         }
937         if err != nil {
938                 return nil, err
939         }
940
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")
944         }
945         return parsePrivateKey(priv.Bytes)
946 }
947
948 func (m *Manager) acmeClient(ctx context.Context) (*acme.Client, error) {
949         m.clientMu.Lock()
950         defer m.clientMu.Unlock()
951         if m.client != nil {
952                 return m.client, nil
953         }
954
955         client := m.Client
956         if client == nil {
957                 client = &acme.Client{DirectoryURL: acme.LetsEncryptURL}
958         }
959         if client.Key == nil {
960                 var err error
961                 client.Key, err = m.accountKey(ctx)
962                 if err != nil {
963                         return nil, err
964                 }
965         }
966         var contact []string
967         if m.Email != "" {
968                 contact = []string{"mailto:" + m.Email}
969         }
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
974                 m.client = client
975                 err = nil
976         }
977         return m.client, err
978 }
979
980 func (m *Manager) hostPolicy() HostPolicy {
981         if m.HostPolicy != nil {
982                 return m.HostPolicy
983         }
984         return defaultHostPolicy
985 }
986
987 func (m *Manager) renewBefore() time.Duration {
988         if m.RenewBefore > renewJitter {
989                 return m.RenewBefore
990         }
991         return 720 * time.Hour // 30 days
992 }
993
994 func (m *Manager) now() time.Time {
995         if m.nowFunc != nil {
996                 return m.nowFunc()
997         }
998         return time.Now()
999 }
1000
1001 // certState is ready when its mutex is unlocked for reading.
1002 type certState struct {
1003         sync.RWMutex
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
1008 }
1009
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) {
1013         if s.key == nil {
1014                 return nil, errors.New("acme/autocert: missing signer")
1015         }
1016         if len(s.cert) == 0 {
1017                 return nil, errors.New("acme/autocert: missing certificate")
1018         }
1019         return &tls.Certificate{
1020                 PrivateKey:  s.key,
1021                 Certificate: s.cert,
1022                 Leaf:        s.leaf,
1023         }, nil
1024 }
1025
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},
1030                 DNSNames:        san,
1031                 ExtraExtensions: ext,
1032         }
1033         return x509.CreateCertificateRequest(rand.Reader, req, key)
1034 }
1035
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.
1039 //
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 {
1043                 return key, nil
1044         }
1045         if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
1046                 switch key := key.(type) {
1047                 case *rsa.PrivateKey:
1048                         return key, nil
1049                 case *ecdsa.PrivateKey:
1050                         return key, nil
1051                 default:
1052                         return nil, errors.New("acme/autocert: unknown private key type in PKCS#8 wrapping")
1053                 }
1054         }
1055         if key, err := x509.ParseECPrivateKey(der); err == nil {
1056                 return key, nil
1057         }
1058
1059         return nil, errors.New("acme/autocert: failed to parse private key")
1060 }
1061
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.
1065 //
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)
1069         var n int
1070         for _, b := range der {
1071                 n += len(b)
1072         }
1073         pub := make([]byte, n)
1074         n = 0
1075         for _, b := range der {
1076                 n += copy(pub[n:], b)
1077         }
1078         x509Cert, err := x509.ParseCertificates(pub)
1079         if err != nil || len(x509Cert) == 0 {
1080                 return nil, errors.New("acme/autocert: no public key found")
1081         }
1082         // verify the leaf is not expired and matches the domain name
1083         leaf = x509Cert[0]
1084         if now.Before(leaf.NotBefore) {
1085                 return nil, errors.New("acme/autocert: certificate is not valid yet")
1086         }
1087         if now.After(leaf.NotAfter) {
1088                 return nil, errors.New("acme/autocert: expired certificate")
1089         }
1090         if err := leaf.VerifyHostname(ck.domain); err != nil {
1091                 return nil, err
1092         }
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)
1097                 if !ok {
1098                         return nil, errors.New("acme/autocert: private key type does not match public key type")
1099                 }
1100                 if pub.N.Cmp(prv.N) != 0 {
1101                         return nil, errors.New("acme/autocert: private key does not match public key")
1102                 }
1103                 if !ck.isRSA && !ck.isToken {
1104                         return nil, errors.New("acme/autocert: key type does not match expected value")
1105                 }
1106         case *ecdsa.PublicKey:
1107                 prv, ok := key.(*ecdsa.PrivateKey)
1108                 if !ok {
1109                         return nil, errors.New("acme/autocert: private key type does not match public key type")
1110                 }
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")
1113                 }
1114                 if ck.isRSA && !ck.isToken {
1115                         return nil, errors.New("acme/autocert: key type does not match expected value")
1116                 }
1117         default:
1118                 return nil, errors.New("acme/autocert: unknown public key algorithm")
1119         }
1120         return leaf, nil
1121 }
1122
1123 type lockedMathRand struct {
1124         sync.Mutex
1125         rnd *mathrand.Rand
1126 }
1127
1128 func (r *lockedMathRand) int63n(max int64) int64 {
1129         r.Lock()
1130         n := r.rnd.Int63n(max)
1131         r.Unlock()
1132         return n
1133 }
1134
1135 // For easier testing.
1136 var (
1137         // Called when a state is removed.
1138         testDidRemoveState = func(certKey) {}
1139 )