acme.go 28 KB

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