acme.go 25 KB

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