acme.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  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. // WaitAuthorization polls an authorization at the given URL
  351. // until it is in one of the final states, StatusValid or StatusInvalid,
  352. // 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 ErrAuthorizationFailed.
  357. func (c *Client) WaitAuthorization(ctx context.Context, url string) (*Authorization, error) {
  358. var count int
  359. sleep := func(v string, inc int) error {
  360. count += inc
  361. d := backoff(count, 10*time.Second)
  362. d = retryAfter(v, d)
  363. wakeup := time.NewTimer(d)
  364. defer wakeup.Stop()
  365. select {
  366. case <-ctx.Done():
  367. return ctx.Err()
  368. case <-wakeup.C:
  369. return nil
  370. }
  371. }
  372. for {
  373. res, err := ctxhttp.Get(ctx, c.HTTPClient, url)
  374. if err != nil {
  375. return nil, err
  376. }
  377. retry := res.Header.Get("retry-after")
  378. if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusAccepted {
  379. res.Body.Close()
  380. if err := sleep(retry, 1); err != nil {
  381. return nil, err
  382. }
  383. continue
  384. }
  385. var raw wireAuthz
  386. err = json.NewDecoder(res.Body).Decode(&raw)
  387. res.Body.Close()
  388. if err != nil {
  389. if err := sleep(retry, 0); err != nil {
  390. return nil, err
  391. }
  392. continue
  393. }
  394. if raw.Status == StatusValid {
  395. return raw.authorization(url), nil
  396. }
  397. if raw.Status == StatusInvalid {
  398. return nil, ErrAuthorizationFailed
  399. }
  400. if err := sleep(retry, 0); err != nil {
  401. return nil, err
  402. }
  403. }
  404. }
  405. // GetChallenge retrieves the current status of an challenge.
  406. //
  407. // A client typically polls a challenge status using this method.
  408. func (c *Client) GetChallenge(ctx context.Context, url string) (*Challenge, error) {
  409. res, err := ctxhttp.Get(ctx, c.HTTPClient, url)
  410. if err != nil {
  411. return nil, err
  412. }
  413. defer res.Body.Close()
  414. if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusAccepted {
  415. return nil, responseError(res)
  416. }
  417. v := wireChallenge{URI: url}
  418. if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
  419. return nil, fmt.Errorf("acme: invalid response: %v", err)
  420. }
  421. return v.challenge(), nil
  422. }
  423. // Accept informs the server that the client accepts one of its challenges
  424. // previously obtained with c.Authorize.
  425. //
  426. // The server will then perform the validation asynchronously.
  427. func (c *Client) Accept(ctx context.Context, chal *Challenge) (*Challenge, error) {
  428. auth, err := keyAuth(c.Key.Public(), chal.Token)
  429. if err != nil {
  430. return nil, err
  431. }
  432. req := struct {
  433. Resource string `json:"resource"`
  434. Type string `json:"type"`
  435. Auth string `json:"keyAuthorization"`
  436. }{
  437. Resource: "challenge",
  438. Type: chal.Type,
  439. Auth: auth,
  440. }
  441. res, err := postJWS(ctx, c.HTTPClient, c.Key, chal.URI, req)
  442. if err != nil {
  443. return nil, err
  444. }
  445. defer res.Body.Close()
  446. // Note: the protocol specifies 200 as the expected response code, but
  447. // letsencrypt seems to be returning 202.
  448. if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusAccepted {
  449. return nil, responseError(res)
  450. }
  451. var v wireChallenge
  452. if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
  453. return nil, fmt.Errorf("acme: invalid response: %v", err)
  454. }
  455. return v.challenge(), nil
  456. }
  457. // DNS01ChallengeRecord returns a DNS record value for a dns-01 challenge response.
  458. // A TXT record containing the returned value must be provisioned under
  459. // "_acme-challenge" name of the domain being validated.
  460. //
  461. // The token argument is a Challenge.Token value.
  462. func (c *Client) DNS01ChallengeRecord(token string) (string, error) {
  463. ka, err := keyAuth(c.Key.Public(), token)
  464. if err != nil {
  465. return "", err
  466. }
  467. b := sha256.Sum256([]byte(ka))
  468. return base64.RawURLEncoding.EncodeToString(b[:]), nil
  469. }
  470. // HTTP01ChallengeResponse returns the response for an http-01 challenge.
  471. // Servers should respond with the value to HTTP requests at the URL path
  472. // provided by HTTP01ChallengePath to validate the challenge and prove control
  473. // over a domain name.
  474. //
  475. // The token argument is a Challenge.Token value.
  476. func (c *Client) HTTP01ChallengeResponse(token string) (string, error) {
  477. return keyAuth(c.Key.Public(), token)
  478. }
  479. // HTTP01ChallengePath returns the URL path at which the response for an http-01 challenge
  480. // should be provided by the servers.
  481. // The response value can be obtained with HTTP01ChallengeResponse.
  482. //
  483. // The token argument is a Challenge.Token value.
  484. func (c *Client) HTTP01ChallengePath(token string) string {
  485. return "/.well-known/acme-challenge/" + token
  486. }
  487. // TLSSNI01ChallengeCert creates a certificate for TLS-SNI-01 challenge response.
  488. // Servers can present the certificate to validate the challenge and prove control
  489. // over a domain name.
  490. //
  491. // The implementation is incomplete in that the returned value is a single certificate,
  492. // computed only for Z0 of the key authorization. ACME CAs are expected to update
  493. // their implementations to use the newer version, TLS-SNI-02.
  494. // For more details on TLS-SNI-01 see https://tools.ietf.org/html/draft-ietf-acme-acme-01#section-7.3.
  495. //
  496. // The token argument is a Challenge.Token value.
  497. // If a WithKey option is provided, its private part signs the returned cert,
  498. // and the public part is used to specify the signee.
  499. // If no WithKey option is provided, a new ECDSA key is generated using P-256 curve.
  500. //
  501. // The returned certificate is valid for the next 24 hours and must be presented only when
  502. // the server name of the client hello matches exactly the returned name value.
  503. func (c *Client) TLSSNI01ChallengeCert(token string, opt ...CertOption) (cert tls.Certificate, name string, err error) {
  504. ka, err := keyAuth(c.Key.Public(), token)
  505. if err != nil {
  506. return tls.Certificate{}, "", err
  507. }
  508. b := sha256.Sum256([]byte(ka))
  509. h := hex.EncodeToString(b[:])
  510. name = fmt.Sprintf("%s.%s.acme.invalid", h[:32], h[32:])
  511. cert, err = tlsChallengeCert([]string{name}, opt)
  512. if err != nil {
  513. return tls.Certificate{}, "", err
  514. }
  515. return cert, name, nil
  516. }
  517. // TLSSNI02ChallengeCert creates a certificate for TLS-SNI-02 challenge response.
  518. // Servers can present the certificate to validate the challenge and prove control
  519. // over a domain name. For more details on TLS-SNI-02 see
  520. // https://tools.ietf.org/html/draft-ietf-acme-acme-03#section-7.3.
  521. //
  522. // The token argument is a Challenge.Token value.
  523. // If a WithKey option is provided, its private part signs the returned cert,
  524. // and the public part is used to specify the signee.
  525. // If no WithKey option is provided, a new ECDSA key is generated using P-256 curve.
  526. //
  527. // The returned certificate is valid for the next 24 hours and must be presented only when
  528. // the server name in the client hello matches exactly the returned name value.
  529. func (c *Client) TLSSNI02ChallengeCert(token string, opt ...CertOption) (cert tls.Certificate, name string, err error) {
  530. b := sha256.Sum256([]byte(token))
  531. h := hex.EncodeToString(b[:])
  532. sanA := fmt.Sprintf("%s.%s.token.acme.invalid", h[:32], h[32:])
  533. ka, err := keyAuth(c.Key.Public(), token)
  534. if err != nil {
  535. return tls.Certificate{}, "", err
  536. }
  537. b = sha256.Sum256([]byte(ka))
  538. h = hex.EncodeToString(b[:])
  539. sanB := fmt.Sprintf("%s.%s.ka.acme.invalid", h[:32], h[32:])
  540. cert, err = tlsChallengeCert([]string{sanA, sanB}, opt)
  541. if err != nil {
  542. return tls.Certificate{}, "", err
  543. }
  544. return cert, sanA, nil
  545. }
  546. // doReg sends all types of registration requests.
  547. // The type of request is identified by typ argument, which is a "resource"
  548. // in the ACME spec terms.
  549. //
  550. // A non-nil acct argument indicates whether the intention is to mutate data
  551. // of the Account. Only Contact and Agreement of its fields are used
  552. // in such cases.
  553. func (c *Client) doReg(ctx context.Context, url string, typ string, acct *Account) (*Account, error) {
  554. req := struct {
  555. Resource string `json:"resource"`
  556. Contact []string `json:"contact,omitempty"`
  557. Agreement string `json:"agreement,omitempty"`
  558. }{
  559. Resource: typ,
  560. }
  561. if acct != nil {
  562. req.Contact = acct.Contact
  563. req.Agreement = acct.AgreedTerms
  564. }
  565. res, err := postJWS(ctx, c.HTTPClient, c.Key, url, req)
  566. if err != nil {
  567. return nil, err
  568. }
  569. defer res.Body.Close()
  570. if res.StatusCode < 200 || res.StatusCode > 299 {
  571. return nil, responseError(res)
  572. }
  573. var v struct {
  574. Contact []string
  575. Agreement string
  576. Authorizations string
  577. Certificates string
  578. }
  579. if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
  580. return nil, fmt.Errorf("acme: invalid response: %v", err)
  581. }
  582. var tos string
  583. if v := linkHeader(res.Header, "terms-of-service"); len(v) > 0 {
  584. tos = v[0]
  585. }
  586. var authz string
  587. if v := linkHeader(res.Header, "next"); len(v) > 0 {
  588. authz = v[0]
  589. }
  590. return &Account{
  591. URI: res.Header.Get("Location"),
  592. Contact: v.Contact,
  593. AgreedTerms: v.Agreement,
  594. CurrentTerms: tos,
  595. Authz: authz,
  596. Authorizations: v.Authorizations,
  597. Certificates: v.Certificates,
  598. }, nil
  599. }
  600. func responseCert(ctx context.Context, client *http.Client, res *http.Response, bundle bool) ([][]byte, error) {
  601. b, err := ioutil.ReadAll(io.LimitReader(res.Body, maxCertSize+1))
  602. if err != nil {
  603. return nil, fmt.Errorf("acme: response stream: %v", err)
  604. }
  605. if len(b) > maxCertSize {
  606. return nil, errors.New("acme: certificate is too big")
  607. }
  608. cert := [][]byte{b}
  609. if !bundle {
  610. return cert, nil
  611. }
  612. // Append CA chain cert(s).
  613. // At least one is required according to the spec:
  614. // https://tools.ietf.org/html/draft-ietf-acme-acme-03#section-6.3.1
  615. up := linkHeader(res.Header, "up")
  616. if len(up) == 0 {
  617. return nil, errors.New("acme: rel=up link not found")
  618. }
  619. if len(up) > maxChainLen {
  620. return nil, errors.New("acme: rel=up link is too large")
  621. }
  622. for _, url := range up {
  623. cc, err := chainCert(ctx, client, url, 0)
  624. if err != nil {
  625. return nil, err
  626. }
  627. cert = append(cert, cc...)
  628. }
  629. return cert, nil
  630. }
  631. // responseError creates an error of Error type from resp.
  632. func responseError(resp *http.Response) error {
  633. // don't care if ReadAll returns an error:
  634. // json.Unmarshal will fail in that case anyway
  635. b, _ := ioutil.ReadAll(resp.Body)
  636. e := struct {
  637. Status int
  638. Type string
  639. Detail string
  640. }{
  641. Status: resp.StatusCode,
  642. }
  643. if err := json.Unmarshal(b, &e); err != nil {
  644. // this is not a regular error response:
  645. // populate detail with anything we received,
  646. // e.Status will already contain HTTP response code value
  647. e.Detail = string(b)
  648. if e.Detail == "" {
  649. e.Detail = resp.Status
  650. }
  651. }
  652. return &Error{
  653. StatusCode: e.Status,
  654. ProblemType: e.Type,
  655. Detail: e.Detail,
  656. Header: resp.Header,
  657. }
  658. }
  659. // chainCert fetches CA certificate chain recursively by following "up" links.
  660. // Each recursive call increments the depth by 1, resulting in an error
  661. // if the recursion level reaches maxChainLen.
  662. //
  663. // First chainCert call starts with depth of 0.
  664. func chainCert(ctx context.Context, client *http.Client, url string, depth int) ([][]byte, error) {
  665. if depth >= maxChainLen {
  666. return nil, errors.New("acme: certificate chain is too deep")
  667. }
  668. res, err := ctxhttp.Get(ctx, client, url)
  669. if err != nil {
  670. return nil, err
  671. }
  672. defer res.Body.Close()
  673. if res.StatusCode != http.StatusOK {
  674. return nil, responseError(res)
  675. }
  676. b, err := ioutil.ReadAll(io.LimitReader(res.Body, maxCertSize+1))
  677. if err != nil {
  678. return nil, err
  679. }
  680. if len(b) > maxCertSize {
  681. return nil, errors.New("acme: certificate is too big")
  682. }
  683. chain := [][]byte{b}
  684. uplink := linkHeader(res.Header, "up")
  685. if len(uplink) > maxChainLen {
  686. return nil, errors.New("acme: certificate chain is too large")
  687. }
  688. for _, up := range uplink {
  689. cc, err := chainCert(ctx, client, up, depth+1)
  690. if err != nil {
  691. return nil, err
  692. }
  693. chain = append(chain, cc...)
  694. }
  695. return chain, nil
  696. }
  697. // postJWS signs the body with the given key and POSTs it to the provided url.
  698. // The body argument must be JSON-serializable.
  699. func postJWS(ctx context.Context, client *http.Client, key crypto.Signer, url string, body interface{}) (*http.Response, error) {
  700. nonce, err := fetchNonce(ctx, client, url)
  701. if err != nil {
  702. return nil, err
  703. }
  704. b, err := jwsEncodeJSON(body, key, nonce)
  705. if err != nil {
  706. return nil, err
  707. }
  708. return ctxhttp.Post(ctx, client, url, "application/jose+json", bytes.NewReader(b))
  709. }
  710. func fetchNonce(ctx context.Context, client *http.Client, url string) (string, error) {
  711. resp, err := ctxhttp.Head(ctx, client, url)
  712. if err != nil {
  713. return "", nil
  714. }
  715. defer resp.Body.Close()
  716. enc := resp.Header.Get("replay-nonce")
  717. if enc == "" {
  718. return "", errors.New("acme: nonce not found")
  719. }
  720. return enc, nil
  721. }
  722. // linkHeader returns URI-Reference values of all Link headers
  723. // with relation-type rel.
  724. // See https://tools.ietf.org/html/rfc5988#section-5 for details.
  725. func linkHeader(h http.Header, rel string) []string {
  726. var links []string
  727. for _, v := range h["Link"] {
  728. parts := strings.Split(v, ";")
  729. for _, p := range parts {
  730. p = strings.TrimSpace(p)
  731. if !strings.HasPrefix(p, "rel=") {
  732. continue
  733. }
  734. if v := strings.Trim(p[4:], `"`); v == rel {
  735. links = append(links, strings.Trim(parts[0], "<>"))
  736. }
  737. }
  738. }
  739. return links
  740. }
  741. // retryAfter parses a Retry-After HTTP header value,
  742. // trying to convert v into an int (seconds) or use http.ParseTime otherwise.
  743. // It returns d if v cannot be parsed.
  744. func retryAfter(v string, d time.Duration) time.Duration {
  745. if i, err := strconv.Atoi(v); err == nil {
  746. return time.Duration(i) * time.Second
  747. }
  748. t, err := http.ParseTime(v)
  749. if err != nil {
  750. return d
  751. }
  752. return t.Sub(timeNow())
  753. }
  754. // backoff computes a duration after which an n+1 retry iteration should occur
  755. // using truncated exponential backoff algorithm.
  756. //
  757. // The n argument is always bounded between 0 and 30.
  758. // The max argument defines upper bound for the returned value.
  759. func backoff(n int, max time.Duration) time.Duration {
  760. if n < 0 {
  761. n = 0
  762. }
  763. if n > 30 {
  764. n = 30
  765. }
  766. var d time.Duration
  767. if x, err := rand.Int(rand.Reader, big.NewInt(1000)); err == nil {
  768. d = time.Duration(x.Int64()) * time.Millisecond
  769. }
  770. d += time.Duration(1<<uint(n)) * time.Second
  771. if d > max {
  772. return max
  773. }
  774. return d
  775. }
  776. // keyAuth generates a key authorization string for a given token.
  777. func keyAuth(pub crypto.PublicKey, token string) (string, error) {
  778. th, err := JWKThumbprint(pub)
  779. if err != nil {
  780. return "", err
  781. }
  782. return fmt.Sprintf("%s.%s", token, th), nil
  783. }
  784. // tlsChallengeCert creates a temporary certificate for TLS-SNI challenges
  785. // with the given SANs and auto-generated public/private key pair.
  786. // To create a cert with a custom key pair, specify WithKey option.
  787. func tlsChallengeCert(san []string, opt []CertOption) (tls.Certificate, error) {
  788. var key crypto.Signer
  789. for _, o := range opt {
  790. switch o := o.(type) {
  791. case *certOptKey:
  792. if key != nil {
  793. return tls.Certificate{}, errors.New("acme: duplicate key option")
  794. }
  795. key = o.key
  796. default:
  797. // package's fault, if we let this happen:
  798. panic(fmt.Sprintf("unsupported option type %T", o))
  799. }
  800. }
  801. if key == nil {
  802. var err error
  803. if key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader); err != nil {
  804. return tls.Certificate{}, err
  805. }
  806. }
  807. t := x509.Certificate{
  808. SerialNumber: big.NewInt(1),
  809. NotBefore: time.Now(),
  810. NotAfter: time.Now().Add(24 * time.Hour),
  811. BasicConstraintsValid: true,
  812. KeyUsage: x509.KeyUsageKeyEncipherment,
  813. DNSNames: san,
  814. }
  815. der, err := x509.CreateCertificate(rand.Reader, &t, &t, key.Public(), key)
  816. if err != nil {
  817. return tls.Certificate{}, err
  818. }
  819. return tls.Certificate{
  820. Certificate: [][]byte{der},
  821. PrivateKey: key,
  822. }, nil
  823. }
  824. // encodePEM returns b encoded as PEM with block of type typ.
  825. func encodePEM(typ string, b []byte) []byte {
  826. pb := &pem.Block{Type: typ, Bytes: b}
  827. return pem.EncodeToMemory(pb)
  828. }
  829. // timeNow is useful for testing for fixed current time.
  830. var timeNow = time.Now