acme.go 27 KB

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