Merge "Add support for 'collectd-master' container"
[barometer.git] / src / dma / vendor / golang.org / x / crypto / acme / acme.go
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.
4
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.
8 //
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.
12 //
13 // This package is a work in progress and makes no API stability promises.
14 package acme
15
16 import (
17         "context"
18         "crypto"
19         "crypto/ecdsa"
20         "crypto/elliptic"
21         "crypto/rand"
22         "crypto/sha256"
23         "crypto/tls"
24         "crypto/x509"
25         "crypto/x509/pkix"
26         "encoding/asn1"
27         "encoding/base64"
28         "encoding/hex"
29         "encoding/json"
30         "encoding/pem"
31         "errors"
32         "fmt"
33         "io"
34         "io/ioutil"
35         "math/big"
36         "net/http"
37         "strings"
38         "sync"
39         "time"
40 )
41
42 const (
43         // LetsEncryptURL is the Directory endpoint of Let's Encrypt CA.
44         LetsEncryptURL = "https://acme-v01.api.letsencrypt.org/directory"
45
46         // ALPNProto is the ALPN protocol name used by a CA server when validating
47         // tls-alpn-01 challenges.
48         //
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"
53 )
54
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}
57
58 const (
59         maxChainLen = 5       // max depth and breadth of a certificate chain
60         maxCertSize = 1 << 20 // max size of a certificate, in bytes
61
62         // Max number of collected nonces kept in memory.
63         // Expect usual peak of 1 or 2.
64         maxNonces = 100
65 )
66
67 // Client is an ACME client.
68 // The only required field is Key. An example of creating a client with a new key
69 // is as follows:
70 //
71 //      key, err := rsa.GenerateKey(rand.Reader, 2048)
72 //      if err != nil {
73 //              log.Fatal(err)
74 //      }
75 //      client := &Client{Key: key}
76 //
77 type Client struct {
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.
80         Key crypto.Signer
81
82         // HTTPClient optionally specifies an HTTP client to use
83         // instead of http.DefaultClient.
84         HTTPClient *http.Client
85
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.
90         DirectoryURL string
91
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.
97         //
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.
100         //
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
107
108         dirMu sync.Mutex // guards writes to dir
109         dir   *Directory // cached result of Client's Discover method
110
111         noncesMu sync.Mutex
112         nonces   map[string]struct{} // nonces collected from previous responses
113 }
114
115 // Discover performs ACME server discovery using c.DirectoryURL.
116 //
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) {
121         c.dirMu.Lock()
122         defer c.dirMu.Unlock()
123         if c.dir != nil {
124                 return *c.dir, nil
125         }
126
127         dirURL := c.DirectoryURL
128         if dirURL == "" {
129                 dirURL = LetsEncryptURL
130         }
131         res, err := c.get(ctx, dirURL, wantStatus(http.StatusOK))
132         if err != nil {
133                 return Directory{}, err
134         }
135         defer res.Body.Close()
136         c.addNonce(res.Header)
137
138         var v struct {
139                 Reg    string `json:"new-reg"`
140                 Authz  string `json:"new-authz"`
141                 Cert   string `json:"new-cert"`
142                 Revoke string `json:"revoke-cert"`
143                 Meta   struct {
144                         Terms   string   `json:"terms-of-service"`
145                         Website string   `json:"website"`
146                         CAA     []string `json:"caa-identities"`
147                 }
148         }
149         if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
150                 return Directory{}, err
151         }
152         c.dir = &Directory{
153                 RegURL:    v.Reg,
154                 AuthzURL:  v.Authz,
155                 CertURL:   v.Cert,
156                 RevokeURL: v.Revoke,
157                 Terms:     v.Meta.Terms,
158                 Website:   v.Meta.Website,
159                 CAA:       v.Meta.CAA,
160         }
161         return *c.dir, nil
162 }
163
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.
168 //
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.
172 //
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 {
177                 return nil, "", err
178         }
179
180         req := struct {
181                 Resource  string `json:"resource"`
182                 CSR       string `json:"csr"`
183                 NotBefore string `json:"notBefore,omitempty"`
184                 NotAfter  string `json:"notAfter,omitempty"`
185         }{
186                 Resource: "new-cert",
187                 CSR:      base64.RawURLEncoding.EncodeToString(csr),
188         }
189         now := timeNow()
190         req.NotBefore = now.Format(time.RFC3339)
191         if exp > 0 {
192                 req.NotAfter = now.Add(exp).Format(time.RFC3339)
193         }
194
195         res, err := c.post(ctx, c.Key, c.dir.CertURL, req, wantStatus(http.StatusCreated))
196         if err != nil {
197                 return nil, "", err
198         }
199         defer res.Body.Close()
200
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
206         }
207         // slurp issued cert and CA chain, if requested
208         cert, err := c.responseCert(ctx, res, bundle)
209         return cert, curl, err
210 }
211
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.
215 //
216 // The returned value will also contain the CA (issuer) certificate if the bundle argument is true.
217 //
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))
223         if err != nil {
224                 return nil, err
225         }
226         return c.responseCert(ctx, res, bundle)
227 }
228
229 // RevokeCert revokes a previously issued certificate cert, provided in DER format.
230 //
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 {
237                 return err
238         }
239
240         body := &struct {
241                 Resource string `json:"resource"`
242                 Cert     string `json:"certificate"`
243                 Reason   int    `json:"reason"`
244         }{
245                 Resource: "revoke-cert",
246                 Cert:     base64.RawURLEncoding.EncodeToString(cert),
247                 Reason:   int(reason),
248         }
249         if key == nil {
250                 key = c.Key
251         }
252         res, err := c.post(ctx, key, c.dir.RevokeURL, body, wantStatus(http.StatusOK))
253         if err != nil {
254                 return err
255         }
256         defer res.Body.Close()
257         return nil
258 }
259
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 }
263
264 // Register creates a new account registration by following the "new-reg" flow.
265 // It returns the registered account. The account is not modified.
266 //
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 {
273                 return nil, err
274         }
275
276         var err error
277         if a, err = c.doReg(ctx, c.dir.RegURL, "new-reg", a); err != nil {
278                 return nil, err
279         }
280         var accept bool
281         if a.CurrentTerms != "" && a.CurrentTerms != a.AgreedTerms {
282                 accept = prompt(a.CurrentTerms)
283         }
284         if accept {
285                 a.AgreedTerms = a.CurrentTerms
286                 a, err = c.UpdateReg(ctx, a)
287         }
288         return a, err
289 }
290
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)
295         if err != nil {
296                 return nil, err
297         }
298         a.URI = url
299         return a, nil
300 }
301
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) {
305         uri := a.URI
306         a, err := c.doReg(ctx, uri, "reg", a)
307         if err != nil {
308                 return nil, err
309         }
310         a.URI = uri
311         return a, nil
312 }
313
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.
317 //
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 {
323                 return nil, err
324         }
325
326         type authzID struct {
327                 Type  string `json:"type"`
328                 Value string `json:"value"`
329         }
330         req := struct {
331                 Resource   string  `json:"resource"`
332                 Identifier authzID `json:"identifier"`
333         }{
334                 Resource:   "new-authz",
335                 Identifier: authzID{Type: "dns", Value: domain},
336         }
337         res, err := c.post(ctx, c.Key, c.dir.AuthzURL, req, wantStatus(http.StatusCreated))
338         if err != nil {
339                 return nil, err
340         }
341         defer res.Body.Close()
342
343         var v wireAuthz
344         if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
345                 return nil, fmt.Errorf("acme: invalid response: %v", err)
346         }
347         if v.Status != StatusPending && v.Status != StatusValid {
348                 return nil, fmt.Errorf("acme: unexpected status: %s", v.Status)
349         }
350         return v.authorization(res.Header.Get("Location")), nil
351 }
352
353 // GetAuthorization retrieves an authorization identified by the given URL.
354 //
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))
359         if err != nil {
360                 return nil, err
361         }
362         defer res.Body.Close()
363         var v wireAuthz
364         if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
365                 return nil, fmt.Errorf("acme: invalid response: %v", err)
366         }
367         return v.authorization(url), nil
368 }
369
370 // RevokeAuthorization relinquishes an existing authorization identified
371 // by the given URL.
372 // The url argument is an Authorization.URI value.
373 //
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.
377 //
378 // It does not revoke existing certificates.
379 func (c *Client) RevokeAuthorization(ctx context.Context, url string) error {
380         req := struct {
381                 Resource string `json:"resource"`
382                 Status   string `json:"status"`
383                 Delete   bool   `json:"delete"`
384         }{
385                 Resource: "authz",
386                 Status:   "deactivated",
387                 Delete:   true,
388         }
389         res, err := c.post(ctx, c.Key, url, req, wantStatus(http.StatusOK))
390         if err != nil {
391                 return err
392         }
393         defer res.Body.Close()
394         return nil
395 }
396
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.
400 //
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) {
405         for {
406                 res, err := c.get(ctx, url, wantStatus(http.StatusOK, http.StatusAccepted))
407                 if err != nil {
408                         return nil, err
409                 }
410
411                 var raw wireAuthz
412                 err = json.NewDecoder(res.Body).Decode(&raw)
413                 res.Body.Close()
414                 switch {
415                 case err != nil:
416                         // Skip and retry.
417                 case raw.Status == StatusValid:
418                         return raw.authorization(url), nil
419                 case raw.Status == StatusInvalid:
420                         return nil, raw.error(url)
421                 }
422
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"))
427                 if d == 0 {
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.
432                         d = time.Second
433                 }
434                 t := time.NewTimer(d)
435                 select {
436                 case <-ctx.Done():
437                         t.Stop()
438                         return nil, ctx.Err()
439                 case <-t.C:
440                         // Retry.
441                 }
442         }
443 }
444
445 // GetChallenge retrieves the current status of an challenge.
446 //
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))
450         if err != nil {
451                 return nil, err
452         }
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)
457         }
458         return v.challenge(), nil
459 }
460
461 // Accept informs the server that the client accepts one of its challenges
462 // previously obtained with c.Authorize.
463 //
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)
467         if err != nil {
468                 return nil, err
469         }
470
471         req := struct {
472                 Resource string `json:"resource"`
473                 Type     string `json:"type"`
474                 Auth     string `json:"keyAuthorization"`
475         }{
476                 Resource: "challenge",
477                 Type:     chal.Type,
478                 Auth:     auth,
479         }
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)
483         ))
484         if err != nil {
485                 return nil, err
486         }
487         defer res.Body.Close()
488
489         var v wireChallenge
490         if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
491                 return nil, fmt.Errorf("acme: invalid response: %v", err)
492         }
493         return v.challenge(), nil
494 }
495
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.
499 //
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)
503         if err != nil {
504                 return "", err
505         }
506         b := sha256.Sum256([]byte(ka))
507         return base64.RawURLEncoding.EncodeToString(b[:]), nil
508 }
509
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.
514 //
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)
518 }
519
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.
523 //
524 // The token argument is a Challenge.Token value.
525 func (c *Client) HTTP01ChallengePath(token string) string {
526         return "/.well-known/acme-challenge/" + token
527 }
528
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.
532 //
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.
537 //
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.
542 //
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)
547         if err != nil {
548                 return tls.Certificate{}, "", err
549         }
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)
554         if err != nil {
555                 return tls.Certificate{}, "", err
556         }
557         return cert, name, nil
558 }
559
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.
564 //
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.
569 //
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:])
576
577         ka, err := keyAuth(c.Key.Public(), token)
578         if err != nil {
579                 return tls.Certificate{}, "", err
580         }
581         b = sha256.Sum256([]byte(ka))
582         h = hex.EncodeToString(b[:])
583         sanB := fmt.Sprintf("%s.%s.ka.acme.invalid", h[:32], h[32:])
584
585         cert, err = tlsChallengeCert([]string{sanA, sanB}, opt)
586         if err != nil {
587                 return tls.Certificate{}, "", err
588         }
589         return cert, sanA, nil
590 }
591
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
596 //
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.
601 //
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)
607         if err != nil {
608                 return tls.Certificate{}, err
609         }
610         shasum := sha256.Sum256([]byte(ka))
611         extValue, err := asn1.Marshal(shasum[:])
612         if err != nil {
613                 return tls.Certificate{}, err
614         }
615         acmeExtension := pkix.Extension{
616                 Id:       idPeACMEIdentifierV1,
617                 Critical: true,
618                 Value:    extValue,
619         }
620
621         tmpl := defaultTLSChallengeCertTemplate()
622
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
628                         tmpl = &t
629                 default:
630                         newOpt = append(newOpt, o)
631                 }
632         }
633         tmpl.ExtraExtensions = append(tmpl.ExtraExtensions, acmeExtension)
634         newOpt = append(newOpt, WithTemplate(tmpl))
635         return tlsChallengeCert([]string{domain}, newOpt)
636 }
637
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.
641 //
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
644 // in such cases.
645 func (c *Client) doReg(ctx context.Context, url string, typ string, acct *Account) (*Account, error) {
646         req := struct {
647                 Resource  string   `json:"resource"`
648                 Contact   []string `json:"contact,omitempty"`
649                 Agreement string   `json:"agreement,omitempty"`
650         }{
651                 Resource: typ,
652         }
653         if acct != nil {
654                 req.Contact = acct.Contact
655                 req.Agreement = acct.AgreedTerms
656         }
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
661         ))
662         if err != nil {
663                 return nil, err
664         }
665         defer res.Body.Close()
666
667         var v struct {
668                 Contact        []string
669                 Agreement      string
670                 Authorizations string
671                 Certificates   string
672         }
673         if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
674                 return nil, fmt.Errorf("acme: invalid response: %v", err)
675         }
676         var tos string
677         if v := linkHeader(res.Header, "terms-of-service"); len(v) > 0 {
678                 tos = v[0]
679         }
680         var authz string
681         if v := linkHeader(res.Header, "next"); len(v) > 0 {
682                 authz = v[0]
683         }
684         return &Account{
685                 URI:            res.Header.Get("Location"),
686                 Contact:        v.Contact,
687                 AgreedTerms:    v.Agreement,
688                 CurrentTerms:   tos,
689                 Authz:          authz,
690                 Authorizations: v.Authorizations,
691                 Certificates:   v.Certificates,
692         }, nil
693 }
694
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) {
698         c.noncesMu.Lock()
699         defer c.noncesMu.Unlock()
700         if len(c.nonces) == 0 {
701                 return c.fetchNonce(ctx, url)
702         }
703         var nonce string
704         for nonce = range c.nonces {
705                 delete(c.nonces, nonce)
706                 break
707         }
708         return nonce, nil
709 }
710
711 // clearNonces clears any stored nonces
712 func (c *Client) clearNonces() {
713         c.noncesMu.Lock()
714         defer c.noncesMu.Unlock()
715         c.nonces = make(map[string]struct{})
716 }
717
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)
721         if v == "" {
722                 return
723         }
724         c.noncesMu.Lock()
725         defer c.noncesMu.Unlock()
726         if len(c.nonces) >= maxNonces {
727                 return
728         }
729         if c.nonces == nil {
730                 c.nonces = make(map[string]struct{})
731         }
732         c.nonces[v] = struct{}{}
733 }
734
735 func (c *Client) fetchNonce(ctx context.Context, url string) (string, error) {
736         r, err := http.NewRequest("HEAD", url, nil)
737         if err != nil {
738                 return "", err
739         }
740         resp, err := c.doNoRetry(ctx, r)
741         if err != nil {
742                 return "", err
743         }
744         defer resp.Body.Close()
745         nonce := nonceFromHeader(resp.Header)
746         if nonce == "" {
747                 if resp.StatusCode > 299 {
748                         return "", responseError(resp)
749                 }
750                 return "", errors.New("acme: nonce not found")
751         }
752         return nonce, nil
753 }
754
755 func nonceFromHeader(h http.Header) string {
756         return h.Get("Replay-Nonce")
757 }
758
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))
761         if err != nil {
762                 return nil, fmt.Errorf("acme: response stream: %v", err)
763         }
764         if len(b) > maxCertSize {
765                 return nil, errors.New("acme: certificate is too big")
766         }
767         cert := [][]byte{b}
768         if !bundle {
769                 return cert, nil
770         }
771
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")
776         if len(up) == 0 {
777                 return nil, errors.New("acme: rel=up link not found")
778         }
779         if len(up) > maxChainLen {
780                 return nil, errors.New("acme: rel=up link is too large")
781         }
782         for _, url := range up {
783                 cc, err := c.chainCert(ctx, url, 0)
784                 if err != nil {
785                         return nil, err
786                 }
787                 cert = append(cert, cc...)
788         }
789         return cert, nil
790 }
791
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.
795 //
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")
800         }
801
802         res, err := c.get(ctx, url, wantStatus(http.StatusOK))
803         if err != nil {
804                 return nil, err
805         }
806         defer res.Body.Close()
807         b, err := ioutil.ReadAll(io.LimitReader(res.Body, maxCertSize+1))
808         if err != nil {
809                 return nil, err
810         }
811         if len(b) > maxCertSize {
812                 return nil, errors.New("acme: certificate is too big")
813         }
814         chain := [][]byte{b}
815
816         uplink := linkHeader(res.Header, "up")
817         if len(uplink) > maxChainLen {
818                 return nil, errors.New("acme: certificate chain is too large")
819         }
820         for _, up := range uplink {
821                 cc, err := c.chainCert(ctx, up, depth+1)
822                 if err != nil {
823                         return nil, err
824                 }
825                 chain = append(chain, cc...)
826         }
827
828         return chain, nil
829 }
830
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 {
835         var links []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=") {
841                                 continue
842                         }
843                         if v := strings.Trim(p[4:], `"`); v == rel {
844                                 links = append(links, strings.Trim(parts[0], "<>"))
845                         }
846                 }
847         }
848         return links
849 }
850
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)
854         if err != nil {
855                 return "", err
856         }
857         return fmt.Sprintf("%s.%s", token, th), nil
858 }
859
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},
869         }
870 }
871
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) {
881                 case *certOptKey:
882                         if key != nil {
883                                 return tls.Certificate{}, errors.New("acme: duplicate key option")
884                         }
885                         key = o.key
886                 case *certOptTemplate:
887                         t := *(*x509.Certificate)(o) // shallow copy is ok
888                         tmpl = &t
889                 default:
890                         // package's fault, if we let this happen:
891                         panic(fmt.Sprintf("unsupported option type %T", o))
892                 }
893         }
894         if key == nil {
895                 var err error
896                 if key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader); err != nil {
897                         return tls.Certificate{}, err
898                 }
899         }
900         tmpl.DNSNames = san
901         if len(san) > 0 {
902                 tmpl.Subject.CommonName = san[0]
903         }
904
905         der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, key.Public(), key)
906         if err != nil {
907                 return tls.Certificate{}, err
908         }
909         return tls.Certificate{
910                 Certificate: [][]byte{der},
911                 PrivateKey:  key,
912         }, nil
913 }
914
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)
919 }
920
921 // timeNow is useful for testing for fixed current time.
922 var timeNow = time.Now