1 // Copyright 2015 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 acme provides an implementation of the
6 // Automatic Certificate Management Environment (ACME) spec.
7 // See https://tools.ietf.org/html/draft-ietf-acme-acme-02 for details.
9 // Most common scenarios will want to use autocert subdirectory instead,
10 // which provides automatic access to certificates from Let's Encrypt
11 // and any other ACME-based CA.
13 // This package is a work in progress and makes no API stability promises.
43 // LetsEncryptURL is the Directory endpoint of Let's Encrypt CA.
44 LetsEncryptURL = "https://acme-v01.api.letsencrypt.org/directory"
46 // ALPNProto is the ALPN protocol name used by a CA server when validating
47 // tls-alpn-01 challenges.
49 // Package users must ensure their servers can negotiate the ACME ALPN in
50 // order for tls-alpn-01 challenge verifications to succeed.
51 // See the crypto/tls package's Config.NextProtos field.
52 ALPNProto = "acme-tls/1"
55 // idPeACMEIdentifierV1 is the OID for the ACME extension for the TLS-ALPN challenge.
56 var idPeACMEIdentifierV1 = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 30, 1}
59 maxChainLen = 5 // max depth and breadth of a certificate chain
60 maxCertSize = 1 << 20 // max size of a certificate, in bytes
62 // Max number of collected nonces kept in memory.
63 // Expect usual peak of 1 or 2.
67 // Client is an ACME client.
68 // The only required field is Key. An example of creating a client with a new key
71 // key, err := rsa.GenerateKey(rand.Reader, 2048)
75 // client := &Client{Key: key}
78 // Key is the account key used to register with a CA and sign requests.
79 // Key.Public() must return a *rsa.PublicKey or *ecdsa.PublicKey.
81 // The following algorithms are supported:
82 // RS256, ES256, ES384 and ES512.
83 // See RFC7518 for more details about the algorithms.
86 // HTTPClient optionally specifies an HTTP client to use
87 // instead of http.DefaultClient.
88 HTTPClient *http.Client
90 // DirectoryURL points to the CA directory endpoint.
91 // If empty, LetsEncryptURL is used.
92 // Mutating this value after a successful call of Client's Discover method
93 // will have no effect.
96 // RetryBackoff computes the duration after which the nth retry of a failed request
97 // should occur. The value of n for the first call on failure is 1.
98 // The values of r and resp are the request and response of the last failed attempt.
99 // If the returned value is negative or zero, no more retries are done and an error
100 // is returned to the caller of the original method.
102 // Requests which result in a 4xx client error are not retried,
103 // except for 400 Bad Request due to "bad nonce" errors and 429 Too Many Requests.
105 // If RetryBackoff is nil, a truncated exponential backoff algorithm
106 // with the ceiling of 10 seconds is used, where each subsequent retry n
107 // is done after either ("Retry-After" + jitter) or (2^n seconds + jitter),
108 // preferring the former if "Retry-After" header is found in the resp.
109 // The jitter is a random value up to 1 second.
110 RetryBackoff func(n int, r *http.Request, resp *http.Response) time.Duration
112 dirMu sync.Mutex // guards writes to dir
113 dir *Directory // cached result of Client's Discover method
116 nonces map[string]struct{} // nonces collected from previous responses
119 // Discover performs ACME server discovery using c.DirectoryURL.
121 // It caches successful result. So, subsequent calls will not result in
122 // a network round-trip. This also means mutating c.DirectoryURL after successful call
123 // of this method will have no effect.
124 func (c *Client) Discover(ctx context.Context) (Directory, error) {
126 defer c.dirMu.Unlock()
131 res, err := c.get(ctx, c.directoryURL(), wantStatus(http.StatusOK))
133 return Directory{}, err
135 defer res.Body.Close()
136 c.addNonce(res.Header)
139 Reg string `json:"new-reg"`
140 Authz string `json:"new-authz"`
141 Cert string `json:"new-cert"`
142 Revoke string `json:"revoke-cert"`
144 Terms string `json:"terms-of-service"`
145 Website string `json:"website"`
146 CAA []string `json:"caa-identities"`
149 if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
150 return Directory{}, err
158 Website: v.Meta.Website,
164 func (c *Client) directoryURL() string {
165 if c.DirectoryURL != "" {
166 return c.DirectoryURL
168 return LetsEncryptURL
171 // CreateCert requests a new certificate using the Certificate Signing Request csr encoded in DER format.
172 // The exp argument indicates the desired certificate validity duration. CA may issue a certificate
173 // with a different duration.
174 // If the bundle argument is true, the returned value will also contain the CA (issuer) certificate chain.
176 // In the case where CA server does not provide the issued certificate in the response,
177 // CreateCert will poll certURL using c.FetchCert, which will result in additional round-trips.
178 // In such a scenario, the caller can cancel the polling with ctx.
180 // CreateCert returns an error if the CA's response or chain was unreasonably large.
181 // Callers are encouraged to parse the returned value to ensure the certificate is valid and has the expected features.
182 func (c *Client) CreateCert(ctx context.Context, csr []byte, exp time.Duration, bundle bool) (der [][]byte, certURL string, err error) {
183 if _, err := c.Discover(ctx); err != nil {
188 Resource string `json:"resource"`
189 CSR string `json:"csr"`
190 NotBefore string `json:"notBefore,omitempty"`
191 NotAfter string `json:"notAfter,omitempty"`
193 Resource: "new-cert",
194 CSR: base64.RawURLEncoding.EncodeToString(csr),
197 req.NotBefore = now.Format(time.RFC3339)
199 req.NotAfter = now.Add(exp).Format(time.RFC3339)
202 res, err := c.post(ctx, c.Key, c.dir.CertURL, req, wantStatus(http.StatusCreated))
206 defer res.Body.Close()
208 curl := res.Header.Get("Location") // cert permanent URL
209 if res.ContentLength == 0 {
210 // no cert in the body; poll until we get it
211 cert, err := c.FetchCert(ctx, curl, bundle)
212 return cert, curl, err
214 // slurp issued cert and CA chain, if requested
215 cert, err := c.responseCert(ctx, res, bundle)
216 return cert, curl, err
219 // FetchCert retrieves already issued certificate from the given url, in DER format.
220 // It retries the request until the certificate is successfully retrieved,
221 // context is cancelled by the caller or an error response is received.
223 // The returned value will also contain the CA (issuer) certificate if the bundle argument is true.
225 // FetchCert returns an error if the CA's response or chain was unreasonably large.
226 // Callers are encouraged to parse the returned value to ensure the certificate is valid
227 // and has expected features.
228 func (c *Client) FetchCert(ctx context.Context, url string, bundle bool) ([][]byte, error) {
229 res, err := c.get(ctx, url, wantStatus(http.StatusOK))
233 return c.responseCert(ctx, res, bundle)
236 // RevokeCert revokes a previously issued certificate cert, provided in DER format.
238 // The key argument, used to sign the request, must be authorized
239 // to revoke the certificate. It's up to the CA to decide which keys are authorized.
240 // For instance, the key pair of the certificate may be authorized.
241 // If the key is nil, c.Key is used instead.
242 func (c *Client) RevokeCert(ctx context.Context, key crypto.Signer, cert []byte, reason CRLReasonCode) error {
243 if _, err := c.Discover(ctx); err != nil {
248 Resource string `json:"resource"`
249 Cert string `json:"certificate"`
250 Reason int `json:"reason"`
252 Resource: "revoke-cert",
253 Cert: base64.RawURLEncoding.EncodeToString(cert),
259 res, err := c.post(ctx, key, c.dir.RevokeURL, body, wantStatus(http.StatusOK))
263 defer res.Body.Close()
267 // AcceptTOS always returns true to indicate the acceptance of a CA's Terms of Service
268 // during account registration. See Register method of Client for more details.
269 func AcceptTOS(tosURL string) bool { return true }
271 // Register creates a new account registration by following the "new-reg" flow.
272 // It returns the registered account. The account is not modified.
274 // The registration may require the caller to agree to the CA's Terms of Service (TOS).
275 // If so, and the account has not indicated the acceptance of the terms (see Account for details),
276 // Register calls prompt with a TOS URL provided by the CA. Prompt should report
277 // whether the caller agrees to the terms. To always accept the terms, the caller can use AcceptTOS.
278 func (c *Client) Register(ctx context.Context, a *Account, prompt func(tosURL string) bool) (*Account, error) {
279 if _, err := c.Discover(ctx); err != nil {
284 if a, err = c.doReg(ctx, c.dir.RegURL, "new-reg", a); err != nil {
288 if a.CurrentTerms != "" && a.CurrentTerms != a.AgreedTerms {
289 accept = prompt(a.CurrentTerms)
292 a.AgreedTerms = a.CurrentTerms
293 a, err = c.UpdateReg(ctx, a)
298 // GetReg retrieves an existing registration.
299 // The url argument is an Account URI.
300 func (c *Client) GetReg(ctx context.Context, url string) (*Account, error) {
301 a, err := c.doReg(ctx, url, "reg", nil)
309 // UpdateReg updates an existing registration.
310 // It returns an updated account copy. The provided account is not modified.
311 func (c *Client) UpdateReg(ctx context.Context, a *Account) (*Account, error) {
313 a, err := c.doReg(ctx, uri, "reg", a)
321 // Authorize performs the initial step in an authorization flow.
322 // The caller will then need to choose from and perform a set of returned
323 // challenges using c.Accept in order to successfully complete authorization.
325 // If an authorization has been previously granted, the CA may return
326 // a valid authorization (Authorization.Status is StatusValid). If so, the caller
327 // need not fulfill any challenge and can proceed to requesting a certificate.
328 func (c *Client) Authorize(ctx context.Context, domain string) (*Authorization, error) {
329 return c.authorize(ctx, "dns", domain)
332 // AuthorizeIP is the same as Authorize but requests IP address authorization.
333 // Clients which successfully obtain such authorization may request to issue
334 // a certificate for IP addresses.
336 // See the ACME spec extension for more details about IP address identifiers:
337 // https://tools.ietf.org/html/draft-ietf-acme-ip.
338 func (c *Client) AuthorizeIP(ctx context.Context, ipaddr string) (*Authorization, error) {
339 return c.authorize(ctx, "ip", ipaddr)
342 func (c *Client) authorize(ctx context.Context, typ, val string) (*Authorization, error) {
343 if _, err := c.Discover(ctx); err != nil {
347 type authzID struct {
348 Type string `json:"type"`
349 Value string `json:"value"`
352 Resource string `json:"resource"`
353 Identifier authzID `json:"identifier"`
355 Resource: "new-authz",
356 Identifier: authzID{Type: typ, Value: val},
358 res, err := c.post(ctx, c.Key, c.dir.AuthzURL, req, wantStatus(http.StatusCreated))
362 defer res.Body.Close()
365 if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
366 return nil, fmt.Errorf("acme: invalid response: %v", err)
368 if v.Status != StatusPending && v.Status != StatusValid {
369 return nil, fmt.Errorf("acme: unexpected status: %s", v.Status)
371 return v.authorization(res.Header.Get("Location")), nil
374 // GetAuthorization retrieves an authorization identified by the given URL.
376 // If a caller needs to poll an authorization until its status is final,
377 // see the WaitAuthorization method.
378 func (c *Client) GetAuthorization(ctx context.Context, url string) (*Authorization, error) {
379 res, err := c.get(ctx, url, wantStatus(http.StatusOK, http.StatusAccepted))
383 defer res.Body.Close()
385 if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
386 return nil, fmt.Errorf("acme: invalid response: %v", err)
388 return v.authorization(url), nil
391 // RevokeAuthorization relinquishes an existing authorization identified
393 // The url argument is an Authorization.URI value.
395 // If successful, the caller will be required to obtain a new authorization
396 // using the Authorize method before being able to request a new certificate
397 // for the domain associated with the authorization.
399 // It does not revoke existing certificates.
400 func (c *Client) RevokeAuthorization(ctx context.Context, url string) error {
402 Resource string `json:"resource"`
403 Status string `json:"status"`
404 Delete bool `json:"delete"`
407 Status: "deactivated",
410 res, err := c.post(ctx, c.Key, url, req, wantStatus(http.StatusOK))
414 defer res.Body.Close()
418 // WaitAuthorization polls an authorization at the given URL
419 // until it is in one of the final states, StatusValid or StatusInvalid,
420 // the ACME CA responded with a 4xx error code, or the context is done.
422 // It returns a non-nil Authorization only if its Status is StatusValid.
423 // In all other cases WaitAuthorization returns an error.
424 // If the Status is StatusInvalid, the returned error is of type *AuthorizationError.
425 func (c *Client) WaitAuthorization(ctx context.Context, url string) (*Authorization, error) {
427 res, err := c.get(ctx, url, wantStatus(http.StatusOK, http.StatusAccepted))
433 err = json.NewDecoder(res.Body).Decode(&raw)
438 case raw.Status == StatusValid:
439 return raw.authorization(url), nil
440 case raw.Status == StatusInvalid:
441 return nil, raw.error(url)
444 // Exponential backoff is implemented in c.get above.
445 // This is just to prevent continuously hitting the CA
446 // while waiting for a final authorization status.
447 d := retryAfter(res.Header.Get("Retry-After"))
449 // Given that the fastest challenges TLS-SNI and HTTP-01
450 // require a CA to make at least 1 network round trip
451 // and most likely persist a challenge state,
452 // this default delay seems reasonable.
455 t := time.NewTimer(d)
459 return nil, ctx.Err()
466 // GetChallenge retrieves the current status of an challenge.
468 // A client typically polls a challenge status using this method.
469 func (c *Client) GetChallenge(ctx context.Context, url string) (*Challenge, error) {
470 res, err := c.get(ctx, url, wantStatus(http.StatusOK, http.StatusAccepted))
474 defer res.Body.Close()
475 v := wireChallenge{URI: url}
476 if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
477 return nil, fmt.Errorf("acme: invalid response: %v", err)
479 return v.challenge(), nil
482 // Accept informs the server that the client accepts one of its challenges
483 // previously obtained with c.Authorize.
485 // The server will then perform the validation asynchronously.
486 func (c *Client) Accept(ctx context.Context, chal *Challenge) (*Challenge, error) {
487 auth, err := keyAuth(c.Key.Public(), chal.Token)
493 Resource string `json:"resource"`
494 Type string `json:"type"`
495 Auth string `json:"keyAuthorization"`
497 Resource: "challenge",
501 res, err := c.post(ctx, c.Key, chal.URI, req, wantStatus(
502 http.StatusOK, // according to the spec
503 http.StatusAccepted, // Let's Encrypt: see https://goo.gl/WsJ7VT (acme-divergences.md)
508 defer res.Body.Close()
511 if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
512 return nil, fmt.Errorf("acme: invalid response: %v", err)
514 return v.challenge(), nil
517 // DNS01ChallengeRecord returns a DNS record value for a dns-01 challenge response.
518 // A TXT record containing the returned value must be provisioned under
519 // "_acme-challenge" name of the domain being validated.
521 // The token argument is a Challenge.Token value.
522 func (c *Client) DNS01ChallengeRecord(token string) (string, error) {
523 ka, err := keyAuth(c.Key.Public(), token)
527 b := sha256.Sum256([]byte(ka))
528 return base64.RawURLEncoding.EncodeToString(b[:]), nil
531 // HTTP01ChallengeResponse returns the response for an http-01 challenge.
532 // Servers should respond with the value to HTTP requests at the URL path
533 // provided by HTTP01ChallengePath to validate the challenge and prove control
534 // over a domain name.
536 // The token argument is a Challenge.Token value.
537 func (c *Client) HTTP01ChallengeResponse(token string) (string, error) {
538 return keyAuth(c.Key.Public(), token)
541 // HTTP01ChallengePath returns the URL path at which the response for an http-01 challenge
542 // should be provided by the servers.
543 // The response value can be obtained with HTTP01ChallengeResponse.
545 // The token argument is a Challenge.Token value.
546 func (c *Client) HTTP01ChallengePath(token string) string {
547 return "/.well-known/acme-challenge/" + token
550 // TLSSNI01ChallengeCert creates a certificate for TLS-SNI-01 challenge response.
551 // Servers can present the certificate to validate the challenge and prove control
552 // over a domain name.
554 // The implementation is incomplete in that the returned value is a single certificate,
555 // computed only for Z0 of the key authorization. ACME CAs are expected to update
556 // their implementations to use the newer version, TLS-SNI-02.
557 // For more details on TLS-SNI-01 see https://tools.ietf.org/html/draft-ietf-acme-acme-01#section-7.3.
559 // The token argument is a Challenge.Token value.
560 // If a WithKey option is provided, its private part signs the returned cert,
561 // and the public part is used to specify the signee.
562 // If no WithKey option is provided, a new ECDSA key is generated using P-256 curve.
564 // The returned certificate is valid for the next 24 hours and must be presented only when
565 // the server name of the TLS ClientHello matches exactly the returned name value.
566 func (c *Client) TLSSNI01ChallengeCert(token string, opt ...CertOption) (cert tls.Certificate, name string, err error) {
567 ka, err := keyAuth(c.Key.Public(), token)
569 return tls.Certificate{}, "", err
571 b := sha256.Sum256([]byte(ka))
572 h := hex.EncodeToString(b[:])
573 name = fmt.Sprintf("%s.%s.acme.invalid", h[:32], h[32:])
574 cert, err = tlsChallengeCert([]string{name}, opt)
576 return tls.Certificate{}, "", err
578 return cert, name, nil
581 // TLSSNI02ChallengeCert creates a certificate for TLS-SNI-02 challenge response.
582 // Servers can present the certificate to validate the challenge and prove control
583 // over a domain name. For more details on TLS-SNI-02 see
584 // https://tools.ietf.org/html/draft-ietf-acme-acme-03#section-7.3.
586 // The token argument is a Challenge.Token value.
587 // If a WithKey option is provided, its private part signs the returned cert,
588 // and the public part is used to specify the signee.
589 // If no WithKey option is provided, a new ECDSA key is generated using P-256 curve.
591 // The returned certificate is valid for the next 24 hours and must be presented only when
592 // the server name in the TLS ClientHello matches exactly the returned name value.
593 func (c *Client) TLSSNI02ChallengeCert(token string, opt ...CertOption) (cert tls.Certificate, name string, err error) {
594 b := sha256.Sum256([]byte(token))
595 h := hex.EncodeToString(b[:])
596 sanA := fmt.Sprintf("%s.%s.token.acme.invalid", h[:32], h[32:])
598 ka, err := keyAuth(c.Key.Public(), token)
600 return tls.Certificate{}, "", err
602 b = sha256.Sum256([]byte(ka))
603 h = hex.EncodeToString(b[:])
604 sanB := fmt.Sprintf("%s.%s.ka.acme.invalid", h[:32], h[32:])
606 cert, err = tlsChallengeCert([]string{sanA, sanB}, opt)
608 return tls.Certificate{}, "", err
610 return cert, sanA, nil
613 // TLSALPN01ChallengeCert creates a certificate for TLS-ALPN-01 challenge response.
614 // Servers can present the certificate to validate the challenge and prove control
615 // over a domain name. For more details on TLS-ALPN-01 see
616 // https://tools.ietf.org/html/draft-shoemaker-acme-tls-alpn-00#section-3
618 // The token argument is a Challenge.Token value.
619 // If a WithKey option is provided, its private part signs the returned cert,
620 // and the public part is used to specify the signee.
621 // If no WithKey option is provided, a new ECDSA key is generated using P-256 curve.
623 // The returned certificate is valid for the next 24 hours and must be presented only when
624 // the server name in the TLS ClientHello matches the domain, and the special acme-tls/1 ALPN protocol
625 // has been specified.
626 func (c *Client) TLSALPN01ChallengeCert(token, domain string, opt ...CertOption) (cert tls.Certificate, err error) {
627 ka, err := keyAuth(c.Key.Public(), token)
629 return tls.Certificate{}, err
631 shasum := sha256.Sum256([]byte(ka))
632 extValue, err := asn1.Marshal(shasum[:])
634 return tls.Certificate{}, err
636 acmeExtension := pkix.Extension{
637 Id: idPeACMEIdentifierV1,
642 tmpl := defaultTLSChallengeCertTemplate()
644 var newOpt []CertOption
645 for _, o := range opt {
646 switch o := o.(type) {
647 case *certOptTemplate:
648 t := *(*x509.Certificate)(o) // shallow copy is ok
651 newOpt = append(newOpt, o)
654 tmpl.ExtraExtensions = append(tmpl.ExtraExtensions, acmeExtension)
655 newOpt = append(newOpt, WithTemplate(tmpl))
656 return tlsChallengeCert([]string{domain}, newOpt)
659 // doReg sends all types of registration requests.
660 // The type of request is identified by typ argument, which is a "resource"
661 // in the ACME spec terms.
663 // A non-nil acct argument indicates whether the intention is to mutate data
664 // of the Account. Only Contact and Agreement of its fields are used
666 func (c *Client) doReg(ctx context.Context, url string, typ string, acct *Account) (*Account, error) {
668 Resource string `json:"resource"`
669 Contact []string `json:"contact,omitempty"`
670 Agreement string `json:"agreement,omitempty"`
675 req.Contact = acct.Contact
676 req.Agreement = acct.AgreedTerms
678 res, err := c.post(ctx, c.Key, url, req, wantStatus(
679 http.StatusOK, // updates and deletes
680 http.StatusCreated, // new account creation
681 http.StatusAccepted, // Let's Encrypt divergent implementation
686 defer res.Body.Close()
691 Authorizations string
694 if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
695 return nil, fmt.Errorf("acme: invalid response: %v", err)
698 if v := linkHeader(res.Header, "terms-of-service"); len(v) > 0 {
702 if v := linkHeader(res.Header, "next"); len(v) > 0 {
706 URI: res.Header.Get("Location"),
708 AgreedTerms: v.Agreement,
711 Authorizations: v.Authorizations,
712 Certificates: v.Certificates,
716 // popNonce returns a nonce value previously stored with c.addNonce
717 // or fetches a fresh one from a URL by issuing a HEAD request.
718 // It first tries c.directoryURL() and then the provided url if the former fails.
719 func (c *Client) popNonce(ctx context.Context, url string) (string, error) {
721 defer c.noncesMu.Unlock()
722 if len(c.nonces) == 0 {
723 dirURL := c.directoryURL()
724 v, err := c.fetchNonce(ctx, dirURL)
725 if err != nil && url != dirURL {
726 v, err = c.fetchNonce(ctx, url)
731 for nonce = range c.nonces {
732 delete(c.nonces, nonce)
738 // clearNonces clears any stored nonces
739 func (c *Client) clearNonces() {
741 defer c.noncesMu.Unlock()
742 c.nonces = make(map[string]struct{})
745 // addNonce stores a nonce value found in h (if any) for future use.
746 func (c *Client) addNonce(h http.Header) {
747 v := nonceFromHeader(h)
752 defer c.noncesMu.Unlock()
753 if len(c.nonces) >= maxNonces {
757 c.nonces = make(map[string]struct{})
759 c.nonces[v] = struct{}{}
762 func (c *Client) fetchNonce(ctx context.Context, url string) (string, error) {
763 r, err := http.NewRequest("HEAD", url, nil)
767 resp, err := c.doNoRetry(ctx, r)
771 defer resp.Body.Close()
772 nonce := nonceFromHeader(resp.Header)
774 if resp.StatusCode > 299 {
775 return "", responseError(resp)
777 return "", errors.New("acme: nonce not found")
782 func nonceFromHeader(h http.Header) string {
783 return h.Get("Replay-Nonce")
786 func (c *Client) responseCert(ctx context.Context, res *http.Response, bundle bool) ([][]byte, error) {
787 b, err := ioutil.ReadAll(io.LimitReader(res.Body, maxCertSize+1))
789 return nil, fmt.Errorf("acme: response stream: %v", err)
791 if len(b) > maxCertSize {
792 return nil, errors.New("acme: certificate is too big")
799 // Append CA chain cert(s).
800 // At least one is required according to the spec:
801 // https://tools.ietf.org/html/draft-ietf-acme-acme-03#section-6.3.1
802 up := linkHeader(res.Header, "up")
804 return nil, errors.New("acme: rel=up link not found")
806 if len(up) > maxChainLen {
807 return nil, errors.New("acme: rel=up link is too large")
809 for _, url := range up {
810 cc, err := c.chainCert(ctx, url, 0)
814 cert = append(cert, cc...)
819 // chainCert fetches CA certificate chain recursively by following "up" links.
820 // Each recursive call increments the depth by 1, resulting in an error
821 // if the recursion level reaches maxChainLen.
823 // First chainCert call starts with depth of 0.
824 func (c *Client) chainCert(ctx context.Context, url string, depth int) ([][]byte, error) {
825 if depth >= maxChainLen {
826 return nil, errors.New("acme: certificate chain is too deep")
829 res, err := c.get(ctx, url, wantStatus(http.StatusOK))
833 defer res.Body.Close()
834 b, err := ioutil.ReadAll(io.LimitReader(res.Body, maxCertSize+1))
838 if len(b) > maxCertSize {
839 return nil, errors.New("acme: certificate is too big")
843 uplink := linkHeader(res.Header, "up")
844 if len(uplink) > maxChainLen {
845 return nil, errors.New("acme: certificate chain is too large")
847 for _, up := range uplink {
848 cc, err := c.chainCert(ctx, up, depth+1)
852 chain = append(chain, cc...)
858 // linkHeader returns URI-Reference values of all Link headers
859 // with relation-type rel.
860 // See https://tools.ietf.org/html/rfc5988#section-5 for details.
861 func linkHeader(h http.Header, rel string) []string {
863 for _, v := range h["Link"] {
864 parts := strings.Split(v, ";")
865 for _, p := range parts {
866 p = strings.TrimSpace(p)
867 if !strings.HasPrefix(p, "rel=") {
870 if v := strings.Trim(p[4:], `"`); v == rel {
871 links = append(links, strings.Trim(parts[0], "<>"))
878 // keyAuth generates a key authorization string for a given token.
879 func keyAuth(pub crypto.PublicKey, token string) (string, error) {
880 th, err := JWKThumbprint(pub)
884 return fmt.Sprintf("%s.%s", token, th), nil
887 // defaultTLSChallengeCertTemplate is a template used to create challenge certs for TLS challenges.
888 func defaultTLSChallengeCertTemplate() *x509.Certificate {
889 return &x509.Certificate{
890 SerialNumber: big.NewInt(1),
891 NotBefore: time.Now(),
892 NotAfter: time.Now().Add(24 * time.Hour),
893 BasicConstraintsValid: true,
894 KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
895 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
899 // tlsChallengeCert creates a temporary certificate for TLS-SNI challenges
900 // with the given SANs and auto-generated public/private key pair.
901 // The Subject Common Name is set to the first SAN to aid debugging.
902 // To create a cert with a custom key pair, specify WithKey option.
903 func tlsChallengeCert(san []string, opt []CertOption) (tls.Certificate, error) {
904 var key crypto.Signer
905 tmpl := defaultTLSChallengeCertTemplate()
906 for _, o := range opt {
907 switch o := o.(type) {
910 return tls.Certificate{}, errors.New("acme: duplicate key option")
913 case *certOptTemplate:
914 t := *(*x509.Certificate)(o) // shallow copy is ok
917 // package's fault, if we let this happen:
918 panic(fmt.Sprintf("unsupported option type %T", o))
923 if key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader); err != nil {
924 return tls.Certificate{}, err
929 tmpl.Subject.CommonName = san[0]
932 der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, key.Public(), key)
934 return tls.Certificate{}, err
936 return tls.Certificate{
937 Certificate: [][]byte{der},
942 // encodePEM returns b encoded as PEM with block of type typ.
943 func encodePEM(typ string, b []byte) []byte {
944 pb := &pem.Block{Type: typ, Bytes: b}
945 return pem.EncodeToMemory(pb)
948 // timeNow is useful for testing for fixed current time.
949 var timeNow = time.Now