acme.go 29 KB

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