You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

912 lines
29 KiB

  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. // Package acme provides an implementation of the
  5. // Automatic Certificate Management Environment (ACME) spec.
  6. // See https://tools.ietf.org/html/draft-ietf-acme-acme-02 for details.
  7. //
  8. // Most common scenarios will want to use autocert subdirectory instead,
  9. // which provides automatic access to certificates from Let's Encrypt
  10. // and any other ACME-based CA.
  11. //
  12. // This package is a work in progress and makes no API stability promises.
  13. package acme
  14. import (
  15. "context"
  16. "crypto"
  17. "crypto/ecdsa"
  18. "crypto/elliptic"
  19. "crypto/rand"
  20. "crypto/sha256"
  21. "crypto/tls"
  22. "crypto/x509"
  23. "crypto/x509/pkix"
  24. "encoding/asn1"
  25. "encoding/base64"
  26. "encoding/hex"
  27. "encoding/json"
  28. "encoding/pem"
  29. "errors"
  30. "fmt"
  31. "io"
  32. "io/ioutil"
  33. "math/big"
  34. "net/http"
  35. "strings"
  36. "sync"
  37. "time"
  38. )
  39. // LetsEncryptURL is the Directory endpoint of Let's Encrypt CA.
  40. const LetsEncryptURL = "https://acme-v01.api.letsencrypt.org/directory"
  41. // idPeACMEIdentifierV1 is the OID for the ACME extension for the TLS-ALPN challenge.
  42. var idPeACMEIdentifierV1 = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 30, 1}
  43. const (
  44. maxChainLen = 5 // max depth and breadth of a certificate chain
  45. maxCertSize = 1 << 20 // max size of a certificate, in bytes
  46. // Max number of collected nonces kept in memory.
  47. // Expect usual peak of 1 or 2.
  48. maxNonces = 100
  49. )
  50. // Client is an ACME client.
  51. // The only required field is Key. An example of creating a client with a new key
  52. // is as follows:
  53. //
  54. // key, err := rsa.GenerateKey(rand.Reader, 2048)
  55. // if err != nil {
  56. // log.Fatal(err)
  57. // }
  58. // client := &Client{Key: key}
  59. //
  60. type Client struct {
  61. // Key is the account key used to register with a CA and sign requests.
  62. // Key.Public() must return a *rsa.PublicKey or *ecdsa.PublicKey.
  63. Key crypto.Signer
  64. // HTTPClient optionally specifies an HTTP client to use
  65. // instead of http.DefaultClient.
  66. HTTPClient *http.Client
  67. // DirectoryURL points to the CA directory endpoint.
  68. // If empty, LetsEncryptURL is used.
  69. // Mutating this value after a successful call of Client's Discover method
  70. // will have no effect.
  71. DirectoryURL string
  72. // RetryBackoff computes the duration after which the nth retry of a failed request
  73. // should occur. The value of n for the first call on failure is 1.
  74. // The values of r and resp are the request and response of the last failed attempt.
  75. // If the returned value is negative or zero, no more retries are done and an error
  76. // is returned to the caller of the original method.
  77. //
  78. // Requests which result in a 4xx client error are not retried,
  79. // except for 400 Bad Request due to "bad nonce" errors and 429 Too Many Requests.
  80. //
  81. // If RetryBackoff is nil, a truncated exponential backoff algorithm
  82. // with the ceiling of 10 seconds is used, where each subsequent retry n
  83. // is done after either ("Retry-After" + jitter) or (2^n seconds + jitter),
  84. // preferring the former if "Retry-After" header is found in the resp.
  85. // The jitter is a random value up to 1 second.
  86. RetryBackoff func(n int, r *http.Request, resp *http.Response) time.Duration
  87. dirMu sync.Mutex // guards writes to dir
  88. dir *Directory // cached result of Client's Discover method
  89. noncesMu sync.Mutex
  90. nonces map[string]struct{} // nonces collected from previous responses
  91. }
  92. // Discover performs ACME server discovery using c.DirectoryURL.
  93. //
  94. // It caches successful result. So, subsequent calls will not result in
  95. // a network round-trip. This also means mutating c.DirectoryURL after successful call
  96. // of this method will have no effect.
  97. func (c *Client) Discover(ctx context.Context) (Directory, error) {
  98. c.dirMu.Lock()
  99. defer c.dirMu.Unlock()
  100. if c.dir != nil {
  101. return *c.dir, nil
  102. }
  103. dirURL := c.DirectoryURL
  104. if dirURL == "" {
  105. dirURL = LetsEncryptURL
  106. }
  107. res, err := c.get(ctx, dirURL, wantStatus(http.StatusOK))
  108. if err != nil {
  109. return Directory{}, err
  110. }
  111. defer res.Body.Close()
  112. c.addNonce(res.Header)
  113. var v struct {
  114. Reg string `json:"new-reg"`
  115. Authz string `json:"new-authz"`
  116. Cert string `json:"new-cert"`
  117. Revoke string `json:"revoke-cert"`
  118. Meta struct {
  119. Terms string `json:"terms-of-service"`
  120. Website string `json:"website"`
  121. CAA []string `json:"caa-identities"`
  122. }
  123. }
  124. if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
  125. return Directory{}, err
  126. }
  127. c.dir = &Directory{
  128. RegURL: v.Reg,
  129. AuthzURL: v.Authz,
  130. CertURL: v.Cert,
  131. RevokeURL: v.Revoke,
  132. Terms: v.Meta.Terms,
  133. Website: v.Meta.Website,
  134. CAA: v.Meta.CAA,
  135. }
  136. return *c.dir, nil
  137. }
  138. // CreateCert requests a new certificate using the Certificate Signing Request csr encoded in DER format.
  139. // The exp argument indicates the desired certificate validity duration. CA may issue a certificate
  140. // with a different duration.
  141. // If the bundle argument is true, the returned value will also contain the CA (issuer) certificate chain.
  142. //
  143. // In the case where CA server does not provide the issued certificate in the response,
  144. // CreateCert will poll certURL using c.FetchCert, which will result in additional round-trips.
  145. // In such a scenario, the caller can cancel the polling with ctx.
  146. //
  147. // CreateCert returns an error if the CA's response or chain was unreasonably large.
  148. // Callers are encouraged to parse the returned value to ensure the certificate is valid and has the expected features.
  149. func (c *Client) CreateCert(ctx context.Context, csr []byte, exp time.Duration, bundle bool) (der [][]byte, certURL string, err error) {
  150. if _, err := c.Discover(ctx); err != nil {
  151. return nil, "", err
  152. }
  153. req := struct {
  154. Resource string `json:"resource"`
  155. CSR string `json:"csr"`
  156. NotBefore string `json:"notBefore,omitempty"`
  157. NotAfter string `json:"notAfter,omitempty"`
  158. }{
  159. Resource: "new-cert",
  160. CSR: base64.RawURLEncoding.EncodeToString(csr),
  161. }
  162. now := timeNow()
  163. req.NotBefore = now.Format(time.RFC3339)
  164. if exp > 0 {
  165. req.NotAfter = now.Add(exp).Format(time.RFC3339)
  166. }
  167. res, err := c.post(ctx, c.Key, c.dir.CertURL, req, wantStatus(http.StatusCreated))
  168. if err != nil {
  169. return nil, "", err
  170. }
  171. defer res.Body.Close()
  172. curl := res.Header.Get("Location") // cert permanent URL
  173. if res.ContentLength == 0 {
  174. // no cert in the body; poll until we get it
  175. cert, err := c.FetchCert(ctx, curl, bundle)
  176. return cert, curl, err
  177. }
  178. // slurp issued cert and CA chain, if requested
  179. cert, err := c.responseCert(ctx, res, bundle)
  180. return cert, curl, err
  181. }
  182. // FetchCert retrieves already issued certificate from the given url, in DER format.
  183. // It retries the request until the certificate is successfully retrieved,
  184. // context is cancelled by the caller or an error response is received.
  185. //
  186. // The returned value will also contain the CA (issuer) certificate if the bundle argument is true.
  187. //
  188. // FetchCert returns an error if the CA's response or chain was unreasonably large.
  189. // Callers are encouraged to parse the returned value to ensure the certificate is valid
  190. // and has expected features.
  191. func (c *Client) FetchCert(ctx context.Context, url string, bundle bool) ([][]byte, error) {
  192. res, err := c.get(ctx, url, wantStatus(http.StatusOK))
  193. if err != nil {
  194. return nil, err
  195. }
  196. return c.responseCert(ctx, res, bundle)
  197. }
  198. // RevokeCert revokes a previously issued certificate cert, provided in DER format.
  199. //
  200. // The key argument, used to sign the request, must be authorized
  201. // to revoke the certificate. It's up to the CA to decide which keys are authorized.
  202. // For instance, the key pair of the certificate may be authorized.
  203. // If the key is nil, c.Key is used instead.
  204. func (c *Client) RevokeCert(ctx context.Context, key crypto.Signer, cert []byte, reason CRLReasonCode) error {
  205. if _, err := c.Discover(ctx); err != nil {
  206. return err
  207. }
  208. body := &struct {
  209. Resource string `json:"resource"`
  210. Cert string `json:"certificate"`
  211. Reason int `json:"reason"`
  212. }{
  213. Resource: "revoke-cert",
  214. Cert: base64.RawURLEncoding.EncodeToString(cert),
  215. Reason: int(reason),
  216. }
  217. if key == nil {
  218. key = c.Key
  219. }
  220. res, err := c.post(ctx, key, c.dir.RevokeURL, body, wantStatus(http.StatusOK))
  221. if err != nil {
  222. return err
  223. }
  224. defer res.Body.Close()
  225. return nil
  226. }
  227. // AcceptTOS always returns true to indicate the acceptance of a CA's Terms of Service
  228. // during account registration. See Register method of Client for more details.
  229. func AcceptTOS(tosURL string) bool { return true }
  230. // Register creates a new account registration by following the "new-reg" flow.
  231. // It returns the registered account. The account is not modified.
  232. //
  233. // The registration may require the caller to agree to the CA's Terms of Service (TOS).
  234. // If so, and the account has not indicated the acceptance of the terms (see Account for details),
  235. // Register calls prompt with a TOS URL provided by the CA. Prompt should report
  236. // whether the caller agrees to the terms. To always accept the terms, the caller can use AcceptTOS.
  237. func (c *Client) Register(ctx context.Context, a *Account, prompt func(tosURL string) bool) (*Account, error) {
  238. if _, err := c.Discover(ctx); err != nil {
  239. return nil, err
  240. }
  241. var err error
  242. if a, err = c.doReg(ctx, c.dir.RegURL, "new-reg", a); err != nil {
  243. return nil, err
  244. }
  245. var accept bool
  246. if a.CurrentTerms != "" && a.CurrentTerms != a.AgreedTerms {
  247. accept = prompt(a.CurrentTerms)
  248. }
  249. if accept {
  250. a.AgreedTerms = a.CurrentTerms
  251. a, err = c.UpdateReg(ctx, a)
  252. }
  253. return a, err
  254. }
  255. // GetReg retrieves an existing registration.
  256. // The url argument is an Account URI.
  257. func (c *Client) GetReg(ctx context.Context, url string) (*Account, error) {
  258. a, err := c.doReg(ctx, url, "reg", nil)
  259. if err != nil {
  260. return nil, err
  261. }
  262. a.URI = url
  263. return a, nil
  264. }
  265. // UpdateReg updates an existing registration.
  266. // It returns an updated account copy. The provided account is not modified.
  267. func (c *Client) UpdateReg(ctx context.Context, a *Account) (*Account, error) {
  268. uri := a.URI
  269. a, err := c.doReg(ctx, uri, "reg", a)
  270. if err != nil {
  271. return nil, err
  272. }
  273. a.URI = uri
  274. return a, nil
  275. }
  276. // Authorize performs the initial step in an authorization flow.
  277. // The caller will then need to choose from and perform a set of returned
  278. // challenges using c.Accept in order to successfully complete authorization.
  279. //
  280. // If an authorization has been previously granted, the CA may return
  281. // a valid authorization (Authorization.Status is StatusValid). If so, the caller
  282. // need not fulfill any challenge and can proceed to requesting a certificate.
  283. func (c *Client) Authorize(ctx context.Context, domain string) (*Authorization, error) {
  284. if _, err := c.Discover(ctx); err != nil {
  285. return nil, err
  286. }
  287. type authzID struct {
  288. Type string `json:"type"`
  289. Value string `json:"value"`
  290. }
  291. req := struct {
  292. Resource string `json:"resource"`
  293. Identifier authzID `json:"identifier"`
  294. }{
  295. Resource: "new-authz",
  296. Identifier: authzID{Type: "dns", Value: domain},
  297. }
  298. res, err := c.post(ctx, c.Key, c.dir.AuthzURL, req, wantStatus(http.StatusCreated))
  299. if err != nil {
  300. return nil, err
  301. }
  302. defer res.Body.Close()
  303. var v wireAuthz
  304. if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
  305. return nil, fmt.Errorf("acme: invalid response: %v", err)
  306. }
  307. if v.Status != StatusPending && v.Status != StatusValid {
  308. return nil, fmt.Errorf("acme: unexpected status: %s", v.Status)
  309. }
  310. return v.authorization(res.Header.Get("Location")), nil
  311. }
  312. // GetAuthorization retrieves an authorization identified by the given URL.
  313. //
  314. // If a caller needs to poll an authorization until its status is final,
  315. // see the WaitAuthorization method.
  316. func (c *Client) GetAuthorization(ctx context.Context, url string) (*Authorization, error) {
  317. res, err := c.get(ctx, url, wantStatus(http.StatusOK, http.StatusAccepted))
  318. if err != nil {
  319. return nil, err
  320. }
  321. defer res.Body.Close()
  322. var v wireAuthz
  323. if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
  324. return nil, fmt.Errorf("acme: invalid response: %v", err)
  325. }
  326. return v.authorization(url), nil
  327. }
  328. // RevokeAuthorization relinquishes an existing authorization identified
  329. // by the given URL.
  330. // The url argument is an Authorization.URI value.
  331. //
  332. // If successful, the caller will be required to obtain a new authorization
  333. // using the Authorize method before being able to request a new certificate
  334. // for the domain associated with the authorization.
  335. //
  336. // It does not revoke existing certificates.
  337. func (c *Client) RevokeAuthorization(ctx context.Context, url string) error {
  338. req := struct {
  339. Resource string `json:"resource"`
  340. Status string `json:"status"`
  341. Delete bool `json:"delete"`
  342. }{
  343. Resource: "authz",
  344. Status: "deactivated",
  345. Delete: true,
  346. }
  347. res, err := c.post(ctx, c.Key, url, req, wantStatus(http.StatusOK))
  348. if err != nil {
  349. return err
  350. }
  351. defer res.Body.Close()
  352. return nil
  353. }
  354. // WaitAuthorization polls an authorization at the given URL
  355. // until it is in one of the final states, StatusValid or StatusInvalid,
  356. // the ACME CA responded with a 4xx error code, or the context is done.
  357. //
  358. // It returns a non-nil Authorization only if its Status is StatusValid.
  359. // In all other cases WaitAuthorization returns an error.
  360. // If the Status is StatusInvalid, the returned error is of type *AuthorizationError.
  361. func (c *Client) WaitAuthorization(ctx context.Context, url string) (*Authorization, error) {
  362. for {
  363. res, err := c.get(ctx, url, wantStatus(http.StatusOK, http.StatusAccepted))
  364. if err != nil {
  365. return nil, err
  366. }
  367. var raw wireAuthz
  368. err = json.NewDecoder(res.Body).Decode(&raw)
  369. res.Body.Close()
  370. switch {
  371. case err != nil:
  372. // Skip and retry.
  373. case raw.Status == StatusValid:
  374. return raw.authorization(url), nil
  375. case raw.Status == StatusInvalid:
  376. return nil, raw.error(url)
  377. }
  378. // Exponential backoff is implemented in c.get above.
  379. // This is just to prevent continuously hitting the CA
  380. // while waiting for a final authorization status.
  381. d := retryAfter(res.Header.Get("Retry-After"))
  382. if d == 0 {
  383. // Given that the fastest challenges TLS-SNI and HTTP-01
  384. // require a CA to make at least 1 network round trip
  385. // and most likely persist a challenge state,
  386. // this default delay seems reasonable.
  387. d = time.Second
  388. }
  389. t := time.NewTimer(d)
  390. select {
  391. case <-ctx.Done():
  392. t.Stop()
  393. return nil, ctx.Err()
  394. case <-t.C:
  395. // Retry.
  396. }
  397. }
  398. }
  399. // GetChallenge retrieves the current status of an challenge.
  400. //
  401. // A client typically polls a challenge status using this method.
  402. func (c *Client) GetChallenge(ctx context.Context, url string) (*Challenge, error) {
  403. res, err := c.get(ctx, url, wantStatus(http.StatusOK, http.StatusAccepted))
  404. if err != nil {
  405. return nil, err
  406. }
  407. defer res.Body.Close()
  408. v := wireChallenge{URI: url}
  409. if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
  410. return nil, fmt.Errorf("acme: invalid response: %v", err)
  411. }
  412. return v.challenge(), nil
  413. }
  414. // Accept informs the server that the client accepts one of its challenges
  415. // previously obtained with c.Authorize.
  416. //
  417. // The server will then perform the validation asynchronously.
  418. func (c *Client) Accept(ctx context.Context, chal *Challenge) (*Challenge, error) {
  419. auth, err := keyAuth(c.Key.Public(), chal.Token)
  420. if err != nil {
  421. return nil, err
  422. }
  423. req := struct {
  424. Resource string `json:"resource"`
  425. Type string `json:"type"`
  426. Auth string `json:"keyAuthorization"`
  427. }{
  428. Resource: "challenge",
  429. Type: chal.Type,
  430. Auth: auth,
  431. }
  432. res, err := c.post(ctx, c.Key, chal.URI, req, wantStatus(
  433. http.StatusOK, // according to the spec
  434. http.StatusAccepted, // Let's Encrypt: see https://goo.gl/WsJ7VT (acme-divergences.md)
  435. ))
  436. if err != nil {
  437. return nil, err
  438. }
  439. defer res.Body.Close()
  440. var v wireChallenge
  441. if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
  442. return nil, fmt.Errorf("acme: invalid response: %v", err)
  443. }
  444. return v.challenge(), nil
  445. }
  446. // DNS01ChallengeRecord returns a DNS record value for a dns-01 challenge response.
  447. // A TXT record containing the returned value must be provisioned under
  448. // "_acme-challenge" name of the domain being validated.
  449. //
  450. // The token argument is a Challenge.Token value.
  451. func (c *Client) DNS01ChallengeRecord(token string) (string, error) {
  452. ka, err := keyAuth(c.Key.Public(), token)
  453. if err != nil {
  454. return "", err
  455. }
  456. b := sha256.Sum256([]byte(ka))
  457. return base64.RawURLEncoding.EncodeToString(b[:]), nil
  458. }
  459. // HTTP01ChallengeResponse returns the response for an http-01 challenge.
  460. // Servers should respond with the value to HTTP requests at the URL path
  461. // provided by HTTP01ChallengePath to validate the challenge and prove control
  462. // over a domain name.
  463. //
  464. // The token argument is a Challenge.Token value.
  465. func (c *Client) HTTP01ChallengeResponse(token string) (string, error) {
  466. return keyAuth(c.Key.Public(), token)
  467. }
  468. // HTTP01ChallengePath returns the URL path at which the response for an http-01 challenge
  469. // should be provided by the servers.
  470. // The response value can be obtained with HTTP01ChallengeResponse.
  471. //
  472. // The token argument is a Challenge.Token value.
  473. func (c *Client) HTTP01ChallengePath(token string) string {
  474. return "/.well-known/acme-challenge/" + token
  475. }
  476. // TLSSNI01ChallengeCert creates a certificate for TLS-SNI-01 challenge response.
  477. // Servers can present the certificate to validate the challenge and prove control
  478. // over a domain name.
  479. //
  480. // The implementation is incomplete in that the returned value is a single certificate,
  481. // computed only for Z0 of the key authorization. ACME CAs are expected to update
  482. // their implementations to use the newer version, TLS-SNI-02.
  483. // For more details on TLS-SNI-01 see https://tools.ietf.org/html/draft-ietf-acme-acme-01#section-7.3.
  484. //
  485. // The token argument is a Challenge.Token value.
  486. // If a WithKey option is provided, its private part signs the returned cert,
  487. // and the public part is used to specify the signee.
  488. // If no WithKey option is provided, a new ECDSA key is generated using P-256 curve.
  489. //
  490. // The returned certificate is valid for the next 24 hours and must be presented only when
  491. // the server name of the TLS ClientHello matches exactly the returned name value.
  492. func (c *Client) TLSSNI01ChallengeCert(token string, opt ...CertOption) (cert tls.Certificate, name string, err error) {
  493. ka, err := keyAuth(c.Key.Public(), token)
  494. if err != nil {
  495. return tls.Certificate{}, "", err
  496. }
  497. b := sha256.Sum256([]byte(ka))
  498. h := hex.EncodeToString(b[:])
  499. name = fmt.Sprintf("%s.%s.acme.invalid", h[:32], h[32:])
  500. cert, err = tlsChallengeCert([]string{name}, opt)
  501. if err != nil {
  502. return tls.Certificate{}, "", err
  503. }
  504. return cert, name, nil
  505. }
  506. // TLSSNI02ChallengeCert creates a certificate for TLS-SNI-02 challenge response.
  507. // Servers can present the certificate to validate the challenge and prove control
  508. // over a domain name. For more details on TLS-SNI-02 see
  509. // https://tools.ietf.org/html/draft-ietf-acme-acme-03#section-7.3.
  510. //
  511. // The token argument is a Challenge.Token value.
  512. // If a WithKey option is provided, its private part signs the returned cert,
  513. // and the public part is used to specify the signee.
  514. // If no WithKey option is provided, a new ECDSA key is generated using P-256 curve.
  515. //
  516. // The returned certificate is valid for the next 24 hours and must be presented only when
  517. // the server name in the TLS ClientHello matches exactly the returned name value.
  518. func (c *Client) TLSSNI02ChallengeCert(token string, opt ...CertOption) (cert tls.Certificate, name string, err error) {
  519. b := sha256.Sum256([]byte(token))
  520. h := hex.EncodeToString(b[:])
  521. sanA := fmt.Sprintf("%s.%s.token.acme.invalid", h[:32], h[32:])
  522. ka, err := keyAuth(c.Key.Public(), token)
  523. if err != nil {
  524. return tls.Certificate{}, "", err
  525. }
  526. b = sha256.Sum256([]byte(ka))
  527. h = hex.EncodeToString(b[:])
  528. sanB := fmt.Sprintf("%s.%s.ka.acme.invalid", h[:32], h[32:])
  529. cert, err = tlsChallengeCert([]string{sanA, sanB}, opt)
  530. if err != nil {
  531. return tls.Certificate{}, "", err
  532. }
  533. return cert, sanA, nil
  534. }
  535. // TLSALPN01ChallengeCert creates a certificate for TLS-ALPN-01 challenge response.
  536. // Servers can present the certificate to validate the challenge and prove control
  537. // over a domain name. For more details on TLS-ALPN-01 see
  538. // https://tools.ietf.org/html/draft-shoemaker-acme-tls-alpn-00#section-3
  539. //
  540. // The token argument is a Challenge.Token value.
  541. // If a WithKey option is provided, its private part signs the returned cert,
  542. // and the public part is used to specify the signee.
  543. // If no WithKey option is provided, a new ECDSA key is generated using P-256 curve.
  544. //
  545. // The returned certificate is valid for the next 24 hours and must be presented only when
  546. // the server name in the TLS ClientHello matches the domain, and the special acme-tls/1 ALPN protocol
  547. // has been specified.
  548. func (c *Client) TLSALPN01ChallengeCert(token, domain string, opt ...CertOption) (cert tls.Certificate, err error) {
  549. ka, err := keyAuth(c.Key.Public(), token)
  550. if err != nil {
  551. return tls.Certificate{}, err
  552. }
  553. shasum := sha256.Sum256([]byte(ka))
  554. extValue, err := asn1.Marshal(shasum[:])
  555. if err != nil {
  556. return tls.Certificate{}, err
  557. }
  558. acmeExtension := pkix.Extension{
  559. Id: idPeACMEIdentifierV1,
  560. Critical: true,
  561. Value: extValue,
  562. }
  563. tmpl := defaultTLSChallengeCertTemplate()
  564. var newOpt []CertOption
  565. for _, o := range opt {
  566. switch o := o.(type) {
  567. case *certOptTemplate:
  568. t := *(*x509.Certificate)(o) // shallow copy is ok
  569. tmpl = &t
  570. default:
  571. newOpt = append(newOpt, o)
  572. }
  573. }
  574. tmpl.ExtraExtensions = append(tmpl.ExtraExtensions, acmeExtension)
  575. newOpt = append(newOpt, WithTemplate(tmpl))
  576. return tlsChallengeCert([]string{domain}, newOpt)
  577. }
  578. // doReg sends all types of registration requests.
  579. // The type of request is identified by typ argument, which is a "resource"
  580. // in the ACME spec terms.
  581. //
  582. // A non-nil acct argument indicates whether the intention is to mutate data
  583. // of the Account. Only Contact and Agreement of its fields are used
  584. // in such cases.
  585. func (c *Client) doReg(ctx context.Context, url string, typ string, acct *Account) (*Account, error) {
  586. req := struct {
  587. Resource string `json:"resource"`
  588. Contact []string `json:"contact,omitempty"`
  589. Agreement string `json:"agreement,omitempty"`
  590. }{
  591. Resource: typ,
  592. }
  593. if acct != nil {
  594. req.Contact = acct.Contact
  595. req.Agreement = acct.AgreedTerms
  596. }
  597. res, err := c.post(ctx, c.Key, url, req, wantStatus(
  598. http.StatusOK, // updates and deletes
  599. http.StatusCreated, // new account creation
  600. ))
  601. if err != nil {
  602. return nil, err
  603. }
  604. defer res.Body.Close()
  605. var v struct {
  606. Contact []string
  607. Agreement string
  608. Authorizations string
  609. Certificates string
  610. }
  611. if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
  612. return nil, fmt.Errorf("acme: invalid response: %v", err)
  613. }
  614. var tos string
  615. if v := linkHeader(res.Header, "terms-of-service"); len(v) > 0 {
  616. tos = v[0]
  617. }
  618. var authz string
  619. if v := linkHeader(res.Header, "next"); len(v) > 0 {
  620. authz = v[0]
  621. }
  622. return &Account{
  623. URI: res.Header.Get("Location"),
  624. Contact: v.Contact,
  625. AgreedTerms: v.Agreement,
  626. CurrentTerms: tos,
  627. Authz: authz,
  628. Authorizations: v.Authorizations,
  629. Certificates: v.Certificates,
  630. }, nil
  631. }
  632. // popNonce returns a nonce value previously stored with c.addNonce
  633. // or fetches a fresh one from the given URL.
  634. func (c *Client) popNonce(ctx context.Context, url string) (string, error) {
  635. c.noncesMu.Lock()
  636. defer c.noncesMu.Unlock()
  637. if len(c.nonces) == 0 {
  638. return c.fetchNonce(ctx, url)
  639. }
  640. var nonce string
  641. for nonce = range c.nonces {
  642. delete(c.nonces, nonce)
  643. break
  644. }
  645. return nonce, nil
  646. }
  647. // clearNonces clears any stored nonces
  648. func (c *Client) clearNonces() {
  649. c.noncesMu.Lock()
  650. defer c.noncesMu.Unlock()
  651. c.nonces = make(map[string]struct{})
  652. }
  653. // addNonce stores a nonce value found in h (if any) for future use.
  654. func (c *Client) addNonce(h http.Header) {
  655. v := nonceFromHeader(h)
  656. if v == "" {
  657. return
  658. }
  659. c.noncesMu.Lock()
  660. defer c.noncesMu.Unlock()
  661. if len(c.nonces) >= maxNonces {
  662. return
  663. }
  664. if c.nonces == nil {
  665. c.nonces = make(map[string]struct{})
  666. }
  667. c.nonces[v] = struct{}{}
  668. }
  669. func (c *Client) fetchNonce(ctx context.Context, url string) (string, error) {
  670. r, err := http.NewRequest("HEAD", url, nil)
  671. if err != nil {
  672. return "", err
  673. }
  674. resp, err := c.doNoRetry(ctx, r)
  675. if err != nil {
  676. return "", err
  677. }
  678. defer resp.Body.Close()
  679. nonce := nonceFromHeader(resp.Header)
  680. if nonce == "" {
  681. if resp.StatusCode > 299 {
  682. return "", responseError(resp)
  683. }
  684. return "", errors.New("acme: nonce not found")
  685. }
  686. return nonce, nil
  687. }
  688. func nonceFromHeader(h http.Header) string {
  689. return h.Get("Replay-Nonce")
  690. }
  691. func (c *Client) responseCert(ctx context.Context, res *http.Response, bundle bool) ([][]byte, error) {
  692. b, err := ioutil.ReadAll(io.LimitReader(res.Body, maxCertSize+1))
  693. if err != nil {
  694. return nil, fmt.Errorf("acme: response stream: %v", err)
  695. }
  696. if len(b) > maxCertSize {
  697. return nil, errors.New("acme: certificate is too big")
  698. }
  699. cert := [][]byte{b}
  700. if !bundle {
  701. return cert, nil
  702. }
  703. // Append CA chain cert(s).
  704. // At least one is required according to the spec:
  705. // https://tools.ietf.org/html/draft-ietf-acme-acme-03#section-6.3.1
  706. up := linkHeader(res.Header, "up")
  707. if len(up) == 0 {
  708. return nil, errors.New("acme: rel=up link not found")
  709. }
  710. if len(up) > maxChainLen {
  711. return nil, errors.New("acme: rel=up link is too large")
  712. }
  713. for _, url := range up {
  714. cc, err := c.chainCert(ctx, url, 0)
  715. if err != nil {
  716. return nil, err
  717. }
  718. cert = append(cert, cc...)
  719. }
  720. return cert, nil
  721. }
  722. // chainCert fetches CA certificate chain recursively by following "up" links.
  723. // Each recursive call increments the depth by 1, resulting in an error
  724. // if the recursion level reaches maxChainLen.
  725. //
  726. // First chainCert call starts with depth of 0.
  727. func (c *Client) chainCert(ctx context.Context, url string, depth int) ([][]byte, error) {
  728. if depth >= maxChainLen {
  729. return nil, errors.New("acme: certificate chain is too deep")
  730. }
  731. res, err := c.get(ctx, url, wantStatus(http.StatusOK))
  732. if err != nil {
  733. return nil, err
  734. }
  735. defer res.Body.Close()
  736. b, err := ioutil.ReadAll(io.LimitReader(res.Body, maxCertSize+1))
  737. if err != nil {
  738. return nil, err
  739. }
  740. if len(b) > maxCertSize {
  741. return nil, errors.New("acme: certificate is too big")
  742. }
  743. chain := [][]byte{b}
  744. uplink := linkHeader(res.Header, "up")
  745. if len(uplink) > maxChainLen {
  746. return nil, errors.New("acme: certificate chain is too large")
  747. }
  748. for _, up := range uplink {
  749. cc, err := c.chainCert(ctx, up, depth+1)
  750. if err != nil {
  751. return nil, err
  752. }
  753. chain = append(chain, cc...)
  754. }
  755. return chain, nil
  756. }
  757. // linkHeader returns URI-Reference values of all Link headers
  758. // with relation-type rel.
  759. // See https://tools.ietf.org/html/rfc5988#section-5 for details.
  760. func linkHeader(h http.Header, rel string) []string {
  761. var links []string
  762. for _, v := range h["Link"] {
  763. parts := strings.Split(v, ";")
  764. for _, p := range parts {
  765. p = strings.TrimSpace(p)
  766. if !strings.HasPrefix(p, "rel=") {
  767. continue
  768. }
  769. if v := strings.Trim(p[4:], `"`); v == rel {
  770. links = append(links, strings.Trim(parts[0], "<>"))
  771. }
  772. }
  773. }
  774. return links
  775. }
  776. // keyAuth generates a key authorization string for a given token.
  777. func keyAuth(pub crypto.PublicKey, token string) (string, error) {
  778. th, err := JWKThumbprint(pub)
  779. if err != nil {
  780. return "", err
  781. }
  782. return fmt.Sprintf("%s.%s", token, th), nil
  783. }
  784. // defaultTLSChallengeCertTemplate is a template used to create challenge certs for TLS challenges.
  785. func defaultTLSChallengeCertTemplate() *x509.Certificate {
  786. return &x509.Certificate{
  787. SerialNumber: big.NewInt(1),
  788. NotBefore: time.Now(),
  789. NotAfter: time.Now().Add(24 * time.Hour),
  790. BasicConstraintsValid: true,
  791. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
  792. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  793. }
  794. }
  795. // tlsChallengeCert creates a temporary certificate for TLS-SNI challenges
  796. // with the given SANs and auto-generated public/private key pair.
  797. // The Subject Common Name is set to the first SAN to aid debugging.
  798. // To create a cert with a custom key pair, specify WithKey option.
  799. func tlsChallengeCert(san []string, opt []CertOption) (tls.Certificate, error) {
  800. var key crypto.Signer
  801. tmpl := defaultTLSChallengeCertTemplate()
  802. for _, o := range opt {
  803. switch o := o.(type) {
  804. case *certOptKey:
  805. if key != nil {
  806. return tls.Certificate{}, errors.New("acme: duplicate key option")
  807. }
  808. key = o.key
  809. case *certOptTemplate:
  810. t := *(*x509.Certificate)(o) // shallow copy is ok
  811. tmpl = &t
  812. default:
  813. // package's fault, if we let this happen:
  814. panic(fmt.Sprintf("unsupported option type %T", o))
  815. }
  816. }
  817. if key == nil {
  818. var err error
  819. if key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader); err != nil {
  820. return tls.Certificate{}, err
  821. }
  822. }
  823. tmpl.DNSNames = san
  824. if len(san) > 0 {
  825. tmpl.Subject.CommonName = san[0]
  826. }
  827. der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, key.Public(), key)
  828. if err != nil {
  829. return tls.Certificate{}, err
  830. }
  831. return tls.Certificate{
  832. Certificate: [][]byte{der},
  833. PrivateKey: key,
  834. }, nil
  835. }
  836. // encodePEM returns b encoded as PEM with block of type typ.
  837. func encodePEM(typ string, b []byte) []byte {
  838. pb := &pem.Block{Type: typ, Bytes: b}
  839. return pem.EncodeToMemory(pb)
  840. }
  841. // timeNow is useful for testing for fixed current time.
  842. var timeNow = time.Now