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

acme.go 31 kB

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