You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

acme.go 30KB

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