acme.go 28 KB

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