acme.go 29 KB

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