acme.go 29 KB

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