acme.go 29 KB

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