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.
82 // HTTPClient optionally specifies an HTTP client to use
83 // instead of http.DefaultClient.
84 HTTPClient *http.Client
86 // DirectoryURL points to the CA directory endpoint.
87 // If empty, LetsEncryptURL is used.
88 // Mutating this value after a successful call of Client's Discover method
89 // will have no effect.
92 // RetryBackoff computes the duration after which the nth retry of a failed request
93 // should occur. The value of n for the first call on failure is 1.
94 // The values of r and resp are the request and response of the last failed attempt.
95 // If the returned value is negative or zero, no more retries are done and an error
96 // is returned to the caller of the original method.
98 // Requests which result in a 4xx client error are not retried,
99 // except for 400 Bad Request due to "bad nonce" errors and 429 Too Many Requests.
101 // If RetryBackoff is nil, a truncated exponential backoff algorithm
102 // with the ceiling of 10 seconds is used, where each subsequent retry n
103 // is done after either ("Retry-After" + jitter) or (2^n seconds + jitter),
104 // preferring the former if "Retry-After" header is found in the resp.
105 // The jitter is a random value up to 1 second.
106 RetryBackoff func(n int, r *http.Request, resp *http.Response) time.Duration
108 dirMu sync.Mutex // guards writes to dir
109 dir *Directory // cached result of Client's Discover method
112 nonces map[string]struct{} // nonces collected from previous responses
115 // Discover performs ACME server discovery using c.DirectoryURL.
117 // It caches successful result. So, subsequent calls will not result in
118 // a network round-trip. This also means mutating c.DirectoryURL after successful call
119 // of this method will have no effect.
120 func (c *Client) Discover(ctx context.Context) (Directory, error) {
122 defer c.dirMu.Unlock()
127 dirURL := c.DirectoryURL
129 dirURL = LetsEncryptURL
131 res, err := c.get(ctx, dirURL, 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 // CreateCert requests a new certificate using the Certificate Signing Request csr encoded in DER format.
165 // The exp argument indicates the desired certificate validity duration. CA may issue a certificate
166 // with a different duration.
167 // If the bundle argument is true, the returned value will also contain the CA (issuer) certificate chain.
169 // In the case where CA server does not provide the issued certificate in the response,
170 // CreateCert will poll certURL using c.FetchCert, which will result in additional round-trips.
171 // In such a scenario, the caller can cancel the polling with ctx.
173 // CreateCert returns an error if the CA's response or chain was unreasonably large.
174 // Callers are encouraged to parse the returned value to ensure the certificate is valid and has the expected features.
175 func (c *Client) CreateCert(ctx context.Context, csr []byte, exp time.Duration, bundle bool) (der [][]byte, certURL string, err error) {
176 if _, err := c.Discover(ctx); err != nil {
181 Resource string `json:"resource"`
182 CSR string `json:"csr"`
183 NotBefore string `json:"notBefore,omitempty"`
184 NotAfter string `json:"notAfter,omitempty"`
186 Resource: "new-cert",
187 CSR: base64.RawURLEncoding.EncodeToString(csr),
190 req.NotBefore = now.Format(time.RFC3339)
192 req.NotAfter = now.Add(exp).Format(time.RFC3339)
195 res, err := c.post(ctx, c.Key, c.dir.CertURL, req, wantStatus(http.StatusCreated))
199 defer res.Body.Close()
201 curl := res.Header.Get("Location") // cert permanent URL
202 if res.ContentLength == 0 {
203 // no cert in the body; poll until we get it
204 cert, err := c.FetchCert(ctx, curl, bundle)
205 return cert, curl, err
207 // slurp issued cert and CA chain, if requested
208 cert, err := c.responseCert(ctx, res, bundle)
209 return cert, curl, err
212 // FetchCert retrieves already issued certificate from the given url, in DER format.
213 // It retries the request until the certificate is successfully retrieved,
214 // context is cancelled by the caller or an error response is received.
216 // The returned value will also contain the CA (issuer) certificate if the bundle argument is true.
218 // FetchCert returns an error if the CA's response or chain was unreasonably large.
219 // Callers are encouraged to parse the returned value to ensure the certificate is valid
220 // and has expected features.
221 func (c *Client) FetchCert(ctx context.Context, url string, bundle bool) ([][]byte, error) {
222 res, err := c.get(ctx, url, wantStatus(http.StatusOK))
226 return c.responseCert(ctx, res, bundle)
229 // RevokeCert revokes a previously issued certificate cert, provided in DER format.
231 // The key argument, used to sign the request, must be authorized
232 // to revoke the certificate. It's up to the CA to decide which keys are authorized.
233 // For instance, the key pair of the certificate may be authorized.
234 // If the key is nil, c.Key is used instead.
235 func (c *Client) RevokeCert(ctx context.Context, key crypto.Signer, cert []byte, reason CRLReasonCode) error {
236 if _, err := c.Discover(ctx); err != nil {
241 Resource string `json:"resource"`
242 Cert string `json:"certificate"`
243 Reason int `json:"reason"`
245 Resource: "revoke-cert",
246 Cert: base64.RawURLEncoding.EncodeToString(cert),
252 res, err := c.post(ctx, key, c.dir.RevokeURL, body, wantStatus(http.StatusOK))
256 defer res.Body.Close()
260 // AcceptTOS always returns true to indicate the acceptance of a CA's Terms of Service
261 // during account registration. See Register method of Client for more details.
262 func AcceptTOS(tosURL string) bool { return true }
264 // Register creates a new account registration by following the "new-reg" flow.
265 // It returns the registered account. The account is not modified.
267 // The registration may require the caller to agree to the CA's Terms of Service (TOS).
268 // If so, and the account has not indicated the acceptance of the terms (see Account for details),
269 // Register calls prompt with a TOS URL provided by the CA. Prompt should report
270 // whether the caller agrees to the terms. To always accept the terms, the caller can use AcceptTOS.
271 func (c *Client) Register(ctx context.Context, a *Account, prompt func(tosURL string) bool) (*Account, error) {
272 if _, err := c.Discover(ctx); err != nil {
277 if a, err = c.doReg(ctx, c.dir.RegURL, "new-reg", a); err != nil {
281 if a.CurrentTerms != "" && a.CurrentTerms != a.AgreedTerms {
282 accept = prompt(a.CurrentTerms)
285 a.AgreedTerms = a.CurrentTerms
286 a, err = c.UpdateReg(ctx, a)
291 // GetReg retrieves an existing registration.
292 // The url argument is an Account URI.
293 func (c *Client) GetReg(ctx context.Context, url string) (*Account, error) {
294 a, err := c.doReg(ctx, url, "reg", nil)
302 // UpdateReg updates an existing registration.
303 // It returns an updated account copy. The provided account is not modified.
304 func (c *Client) UpdateReg(ctx context.Context, a *Account) (*Account, error) {
306 a, err := c.doReg(ctx, uri, "reg", a)
314 // Authorize performs the initial step in an authorization flow.
315 // The caller will then need to choose from and perform a set of returned
316 // challenges using c.Accept in order to successfully complete authorization.
318 // If an authorization has been previously granted, the CA may return
319 // a valid authorization (Authorization.Status is StatusValid). If so, the caller
320 // need not fulfill any challenge and can proceed to requesting a certificate.
321 func (c *Client) Authorize(ctx context.Context, domain string) (*Authorization, error) {
322 if _, err := c.Discover(ctx); err != nil {
326 type authzID struct {
327 Type string `json:"type"`
328 Value string `json:"value"`
331 Resource string `json:"resource"`
332 Identifier authzID `json:"identifier"`
334 Resource: "new-authz",
335 Identifier: authzID{Type: "dns", Value: domain},
337 res, err := c.post(ctx, c.Key, c.dir.AuthzURL, req, wantStatus(http.StatusCreated))
341 defer res.Body.Close()
344 if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
345 return nil, fmt.Errorf("acme: invalid response: %v", err)
347 if v.Status != StatusPending && v.Status != StatusValid {
348 return nil, fmt.Errorf("acme: unexpected status: %s", v.Status)
350 return v.authorization(res.Header.Get("Location")), nil
353 // GetAuthorization retrieves an authorization identified by the given URL.
355 // If a caller needs to poll an authorization until its status is final,
356 // see the WaitAuthorization method.
357 func (c *Client) GetAuthorization(ctx context.Context, url string) (*Authorization, error) {
358 res, err := c.get(ctx, url, wantStatus(http.StatusOK, http.StatusAccepted))
362 defer res.Body.Close()
364 if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
365 return nil, fmt.Errorf("acme: invalid response: %v", err)
367 return v.authorization(url), nil
370 // RevokeAuthorization relinquishes an existing authorization identified
372 // The url argument is an Authorization.URI value.
374 // If successful, the caller will be required to obtain a new authorization
375 // using the Authorize method before being able to request a new certificate
376 // for the domain associated with the authorization.
378 // It does not revoke existing certificates.
379 func (c *Client) RevokeAuthorization(ctx context.Context, url string) error {
381 Resource string `json:"resource"`
382 Status string `json:"status"`
383 Delete bool `json:"delete"`
386 Status: "deactivated",
389 res, err := c.post(ctx, c.Key, url, req, wantStatus(http.StatusOK))
393 defer res.Body.Close()
397 // WaitAuthorization polls an authorization at the given URL
398 // until it is in one of the final states, StatusValid or StatusInvalid,
399 // the ACME CA responded with a 4xx error code, or the context is done.
401 // It returns a non-nil Authorization only if its Status is StatusValid.
402 // In all other cases WaitAuthorization returns an error.
403 // If the Status is StatusInvalid, the returned error is of type *AuthorizationError.
404 func (c *Client) WaitAuthorization(ctx context.Context, url string) (*Authorization, error) {
406 res, err := c.get(ctx, url, wantStatus(http.StatusOK, http.StatusAccepted))
412 err = json.NewDecoder(res.Body).Decode(&raw)
417 case raw.Status == StatusValid:
418 return raw.authorization(url), nil
419 case raw.Status == StatusInvalid:
420 return nil, raw.error(url)
423 // Exponential backoff is implemented in c.get above.
424 // This is just to prevent continuously hitting the CA
425 // while waiting for a final authorization status.
426 d := retryAfter(res.Header.Get("Retry-After"))
428 // Given that the fastest challenges TLS-SNI and HTTP-01
429 // require a CA to make at least 1 network round trip
430 // and most likely persist a challenge state,
431 // this default delay seems reasonable.
434 t := time.NewTimer(d)
438 return nil, ctx.Err()
445 // GetChallenge retrieves the current status of an challenge.
447 // A client typically polls a challenge status using this method.
448 func (c *Client) GetChallenge(ctx context.Context, url string) (*Challenge, error) {
449 res, err := c.get(ctx, url, wantStatus(http.StatusOK, http.StatusAccepted))
453 defer res.Body.Close()
454 v := wireChallenge{URI: url}
455 if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
456 return nil, fmt.Errorf("acme: invalid response: %v", err)
458 return v.challenge(), nil
461 // Accept informs the server that the client accepts one of its challenges
462 // previously obtained with c.Authorize.
464 // The server will then perform the validation asynchronously.
465 func (c *Client) Accept(ctx context.Context, chal *Challenge) (*Challenge, error) {
466 auth, err := keyAuth(c.Key.Public(), chal.Token)
472 Resource string `json:"resource"`
473 Type string `json:"type"`
474 Auth string `json:"keyAuthorization"`
476 Resource: "challenge",
480 res, err := c.post(ctx, c.Key, chal.URI, req, wantStatus(
481 http.StatusOK, // according to the spec
482 http.StatusAccepted, // Let's Encrypt: see https://goo.gl/WsJ7VT (acme-divergences.md)
487 defer res.Body.Close()
490 if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
491 return nil, fmt.Errorf("acme: invalid response: %v", err)
493 return v.challenge(), nil
496 // DNS01ChallengeRecord returns a DNS record value for a dns-01 challenge response.
497 // A TXT record containing the returned value must be provisioned under
498 // "_acme-challenge" name of the domain being validated.
500 // The token argument is a Challenge.Token value.
501 func (c *Client) DNS01ChallengeRecord(token string) (string, error) {
502 ka, err := keyAuth(c.Key.Public(), token)
506 b := sha256.Sum256([]byte(ka))
507 return base64.RawURLEncoding.EncodeToString(b[:]), nil
510 // HTTP01ChallengeResponse returns the response for an http-01 challenge.
511 // Servers should respond with the value to HTTP requests at the URL path
512 // provided by HTTP01ChallengePath to validate the challenge and prove control
513 // over a domain name.
515 // The token argument is a Challenge.Token value.
516 func (c *Client) HTTP01ChallengeResponse(token string) (string, error) {
517 return keyAuth(c.Key.Public(), token)
520 // HTTP01ChallengePath returns the URL path at which the response for an http-01 challenge
521 // should be provided by the servers.
522 // The response value can be obtained with HTTP01ChallengeResponse.
524 // The token argument is a Challenge.Token value.
525 func (c *Client) HTTP01ChallengePath(token string) string {
526 return "/.well-known/acme-challenge/" + token
529 // TLSSNI01ChallengeCert creates a certificate for TLS-SNI-01 challenge response.
530 // Servers can present the certificate to validate the challenge and prove control
531 // over a domain name.
533 // The implementation is incomplete in that the returned value is a single certificate,
534 // computed only for Z0 of the key authorization. ACME CAs are expected to update
535 // their implementations to use the newer version, TLS-SNI-02.
536 // For more details on TLS-SNI-01 see https://tools.ietf.org/html/draft-ietf-acme-acme-01#section-7.3.
538 // The token argument is a Challenge.Token value.
539 // If a WithKey option is provided, its private part signs the returned cert,
540 // and the public part is used to specify the signee.
541 // If no WithKey option is provided, a new ECDSA key is generated using P-256 curve.
543 // The returned certificate is valid for the next 24 hours and must be presented only when
544 // the server name of the TLS ClientHello matches exactly the returned name value.
545 func (c *Client) TLSSNI01ChallengeCert(token string, opt ...CertOption) (cert tls.Certificate, name string, err error) {
546 ka, err := keyAuth(c.Key.Public(), token)
548 return tls.Certificate{}, "", err
550 b := sha256.Sum256([]byte(ka))
551 h := hex.EncodeToString(b[:])
552 name = fmt.Sprintf("%s.%s.acme.invalid", h[:32], h[32:])
553 cert, err = tlsChallengeCert([]string{name}, opt)
555 return tls.Certificate{}, "", err
557 return cert, name, nil
560 // TLSSNI02ChallengeCert creates a certificate for TLS-SNI-02 challenge response.
561 // Servers can present the certificate to validate the challenge and prove control
562 // over a domain name. For more details on TLS-SNI-02 see
563 // https://tools.ietf.org/html/draft-ietf-acme-acme-03#section-7.3.
565 // The token argument is a Challenge.Token value.
566 // If a WithKey option is provided, its private part signs the returned cert,
567 // and the public part is used to specify the signee.
568 // If no WithKey option is provided, a new ECDSA key is generated using P-256 curve.
570 // The returned certificate is valid for the next 24 hours and must be presented only when
571 // the server name in the TLS ClientHello matches exactly the returned name value.
572 func (c *Client) TLSSNI02ChallengeCert(token string, opt ...CertOption) (cert tls.Certificate, name string, err error) {
573 b := sha256.Sum256([]byte(token))
574 h := hex.EncodeToString(b[:])
575 sanA := fmt.Sprintf("%s.%s.token.acme.invalid", h[:32], h[32:])
577 ka, err := keyAuth(c.Key.Public(), token)
579 return tls.Certificate{}, "", err
581 b = sha256.Sum256([]byte(ka))
582 h = hex.EncodeToString(b[:])
583 sanB := fmt.Sprintf("%s.%s.ka.acme.invalid", h[:32], h[32:])
585 cert, err = tlsChallengeCert([]string{sanA, sanB}, opt)
587 return tls.Certificate{}, "", err
589 return cert, sanA, nil
592 // TLSALPN01ChallengeCert creates a certificate for TLS-ALPN-01 challenge response.
593 // Servers can present the certificate to validate the challenge and prove control
594 // over a domain name. For more details on TLS-ALPN-01 see
595 // https://tools.ietf.org/html/draft-shoemaker-acme-tls-alpn-00#section-3
597 // The token argument is a Challenge.Token value.
598 // If a WithKey option is provided, its private part signs the returned cert,
599 // and the public part is used to specify the signee.
600 // If no WithKey option is provided, a new ECDSA key is generated using P-256 curve.
602 // The returned certificate is valid for the next 24 hours and must be presented only when
603 // the server name in the TLS ClientHello matches the domain, and the special acme-tls/1 ALPN protocol
604 // has been specified.
605 func (c *Client) TLSALPN01ChallengeCert(token, domain string, opt ...CertOption) (cert tls.Certificate, err error) {
606 ka, err := keyAuth(c.Key.Public(), token)
608 return tls.Certificate{}, err
610 shasum := sha256.Sum256([]byte(ka))
611 extValue, err := asn1.Marshal(shasum[:])
613 return tls.Certificate{}, err
615 acmeExtension := pkix.Extension{
616 Id: idPeACMEIdentifierV1,
621 tmpl := defaultTLSChallengeCertTemplate()
623 var newOpt []CertOption
624 for _, o := range opt {
625 switch o := o.(type) {
626 case *certOptTemplate:
627 t := *(*x509.Certificate)(o) // shallow copy is ok
630 newOpt = append(newOpt, o)
633 tmpl.ExtraExtensions = append(tmpl.ExtraExtensions, acmeExtension)
634 newOpt = append(newOpt, WithTemplate(tmpl))
635 return tlsChallengeCert([]string{domain}, newOpt)
638 // doReg sends all types of registration requests.
639 // The type of request is identified by typ argument, which is a "resource"
640 // in the ACME spec terms.
642 // A non-nil acct argument indicates whether the intention is to mutate data
643 // of the Account. Only Contact and Agreement of its fields are used
645 func (c *Client) doReg(ctx context.Context, url string, typ string, acct *Account) (*Account, error) {
647 Resource string `json:"resource"`
648 Contact []string `json:"contact,omitempty"`
649 Agreement string `json:"agreement,omitempty"`
654 req.Contact = acct.Contact
655 req.Agreement = acct.AgreedTerms
657 res, err := c.post(ctx, c.Key, url, req, wantStatus(
658 http.StatusOK, // updates and deletes
659 http.StatusCreated, // new account creation
660 http.StatusAccepted, // Let's Encrypt divergent implementation
665 defer res.Body.Close()
670 Authorizations string
673 if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
674 return nil, fmt.Errorf("acme: invalid response: %v", err)
677 if v := linkHeader(res.Header, "terms-of-service"); len(v) > 0 {
681 if v := linkHeader(res.Header, "next"); len(v) > 0 {
685 URI: res.Header.Get("Location"),
687 AgreedTerms: v.Agreement,
690 Authorizations: v.Authorizations,
691 Certificates: v.Certificates,
695 // popNonce returns a nonce value previously stored with c.addNonce
696 // or fetches a fresh one from the given URL.
697 func (c *Client) popNonce(ctx context.Context, url string) (string, error) {
699 defer c.noncesMu.Unlock()
700 if len(c.nonces) == 0 {
701 return c.fetchNonce(ctx, url)
704 for nonce = range c.nonces {
705 delete(c.nonces, nonce)
711 // clearNonces clears any stored nonces
712 func (c *Client) clearNonces() {
714 defer c.noncesMu.Unlock()
715 c.nonces = make(map[string]struct{})
718 // addNonce stores a nonce value found in h (if any) for future use.
719 func (c *Client) addNonce(h http.Header) {
720 v := nonceFromHeader(h)
725 defer c.noncesMu.Unlock()
726 if len(c.nonces) >= maxNonces {
730 c.nonces = make(map[string]struct{})
732 c.nonces[v] = struct{}{}
735 func (c *Client) fetchNonce(ctx context.Context, url string) (string, error) {
736 r, err := http.NewRequest("HEAD", url, nil)
740 resp, err := c.doNoRetry(ctx, r)
744 defer resp.Body.Close()
745 nonce := nonceFromHeader(resp.Header)
747 if resp.StatusCode > 299 {
748 return "", responseError(resp)
750 return "", errors.New("acme: nonce not found")
755 func nonceFromHeader(h http.Header) string {
756 return h.Get("Replay-Nonce")
759 func (c *Client) responseCert(ctx context.Context, res *http.Response, bundle bool) ([][]byte, error) {
760 b, err := ioutil.ReadAll(io.LimitReader(res.Body, maxCertSize+1))
762 return nil, fmt.Errorf("acme: response stream: %v", err)
764 if len(b) > maxCertSize {
765 return nil, errors.New("acme: certificate is too big")
772 // Append CA chain cert(s).
773 // At least one is required according to the spec:
774 // https://tools.ietf.org/html/draft-ietf-acme-acme-03#section-6.3.1
775 up := linkHeader(res.Header, "up")
777 return nil, errors.New("acme: rel=up link not found")
779 if len(up) > maxChainLen {
780 return nil, errors.New("acme: rel=up link is too large")
782 for _, url := range up {
783 cc, err := c.chainCert(ctx, url, 0)
787 cert = append(cert, cc...)
792 // chainCert fetches CA certificate chain recursively by following "up" links.
793 // Each recursive call increments the depth by 1, resulting in an error
794 // if the recursion level reaches maxChainLen.
796 // First chainCert call starts with depth of 0.
797 func (c *Client) chainCert(ctx context.Context, url string, depth int) ([][]byte, error) {
798 if depth >= maxChainLen {
799 return nil, errors.New("acme: certificate chain is too deep")
802 res, err := c.get(ctx, url, wantStatus(http.StatusOK))
806 defer res.Body.Close()
807 b, err := ioutil.ReadAll(io.LimitReader(res.Body, maxCertSize+1))
811 if len(b) > maxCertSize {
812 return nil, errors.New("acme: certificate is too big")
816 uplink := linkHeader(res.Header, "up")
817 if len(uplink) > maxChainLen {
818 return nil, errors.New("acme: certificate chain is too large")
820 for _, up := range uplink {
821 cc, err := c.chainCert(ctx, up, depth+1)
825 chain = append(chain, cc...)
831 // linkHeader returns URI-Reference values of all Link headers
832 // with relation-type rel.
833 // See https://tools.ietf.org/html/rfc5988#section-5 for details.
834 func linkHeader(h http.Header, rel string) []string {
836 for _, v := range h["Link"] {
837 parts := strings.Split(v, ";")
838 for _, p := range parts {
839 p = strings.TrimSpace(p)
840 if !strings.HasPrefix(p, "rel=") {
843 if v := strings.Trim(p[4:], `"`); v == rel {
844 links = append(links, strings.Trim(parts[0], "<>"))
851 // keyAuth generates a key authorization string for a given token.
852 func keyAuth(pub crypto.PublicKey, token string) (string, error) {
853 th, err := JWKThumbprint(pub)
857 return fmt.Sprintf("%s.%s", token, th), nil
860 // defaultTLSChallengeCertTemplate is a template used to create challenge certs for TLS challenges.
861 func defaultTLSChallengeCertTemplate() *x509.Certificate {
862 return &x509.Certificate{
863 SerialNumber: big.NewInt(1),
864 NotBefore: time.Now(),
865 NotAfter: time.Now().Add(24 * time.Hour),
866 BasicConstraintsValid: true,
867 KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
868 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
872 // tlsChallengeCert creates a temporary certificate for TLS-SNI challenges
873 // with the given SANs and auto-generated public/private key pair.
874 // The Subject Common Name is set to the first SAN to aid debugging.
875 // To create a cert with a custom key pair, specify WithKey option.
876 func tlsChallengeCert(san []string, opt []CertOption) (tls.Certificate, error) {
877 var key crypto.Signer
878 tmpl := defaultTLSChallengeCertTemplate()
879 for _, o := range opt {
880 switch o := o.(type) {
883 return tls.Certificate{}, errors.New("acme: duplicate key option")
886 case *certOptTemplate:
887 t := *(*x509.Certificate)(o) // shallow copy is ok
890 // package's fault, if we let this happen:
891 panic(fmt.Sprintf("unsupported option type %T", o))
896 if key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader); err != nil {
897 return tls.Certificate{}, err
902 tmpl.Subject.CommonName = san[0]
905 der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, key.Public(), key)
907 return tls.Certificate{}, err
909 return tls.Certificate{
910 Certificate: [][]byte{der},
915 // encodePEM returns b encoded as PEM with block of type typ.
916 func encodePEM(typ string, b []byte) []byte {
917 pb := &pem.Block{Type: typ, Bytes: b}
918 return pem.EncodeToMemory(pb)
921 // timeNow is useful for testing for fixed current time.
922 var timeNow = time.Now