acme.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  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. // most famously used by Let's Encrypt.
  7. //
  8. // The initial implementation of this package was based on an early version
  9. // of the spec. The current implementation supports only the modern
  10. // RFC 8555 but some of the old API surface remains for compatibility.
  11. // While code using the old API will still compile, it will return an error.
  12. // Note the deprecation comments to update your code.
  13. //
  14. // See https://tools.ietf.org/html/rfc8555 for the spec.
  15. //
  16. // Most common scenarios will want to use autocert subdirectory instead,
  17. // which provides automatic access to certificates from Let's Encrypt
  18. // and any other ACME-based CA.
  19. package acme
  20. import (
  21. "context"
  22. "crypto"
  23. "crypto/ecdsa"
  24. "crypto/elliptic"
  25. "crypto/rand"
  26. "crypto/sha256"
  27. "crypto/tls"
  28. "crypto/x509"
  29. "crypto/x509/pkix"
  30. "encoding/asn1"
  31. "encoding/base64"
  32. "encoding/hex"
  33. "encoding/json"
  34. "encoding/pem"
  35. "errors"
  36. "fmt"
  37. "math/big"
  38. "net/http"
  39. "strings"
  40. "sync"
  41. "time"
  42. )
  43. const (
  44. // LetsEncryptURL is the Directory endpoint of Let's Encrypt CA.
  45. LetsEncryptURL = "https://acme-v02.api.letsencrypt.org/directory"
  46. // ALPNProto is the ALPN protocol name used by a CA server when validating
  47. // tls-alpn-01 challenges.
  48. //
  49. // Package users must ensure their servers can negotiate the ACME ALPN in
  50. // order for tls-alpn-01 challenge verifications to succeed.
  51. // See the crypto/tls package's Config.NextProtos field.
  52. ALPNProto = "acme-tls/1"
  53. )
  54. // idPeACMEIdentifier is the OID for the ACME extension for the TLS-ALPN challenge.
  55. // https://tools.ietf.org/html/draft-ietf-acme-tls-alpn-05#section-5.1
  56. var idPeACMEIdentifier = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 31}
  57. const (
  58. maxChainLen = 5 // max depth and breadth of a certificate chain
  59. maxCertSize = 1 << 20 // max size of a certificate, in DER bytes
  60. // Used for decoding certs from application/pem-certificate-chain response,
  61. // the default when in RFC mode.
  62. maxCertChainSize = maxCertSize * maxChainLen
  63. // Max number of collected nonces kept in memory.
  64. // Expect usual peak of 1 or 2.
  65. maxNonces = 100
  66. )
  67. // Client is an ACME client.
  68. //
  69. // The only required field is Key. An example of creating a client with a new key
  70. // is as follows:
  71. //
  72. // key, err := rsa.GenerateKey(rand.Reader, 2048)
  73. // if err != nil {
  74. // log.Fatal(err)
  75. // }
  76. // client := &Client{Key: key}
  77. type Client struct {
  78. // Key is the account key used to register with a CA and sign requests.
  79. // Key.Public() must return a *rsa.PublicKey or *ecdsa.PublicKey.
  80. //
  81. // The following algorithms are supported:
  82. // RS256, ES256, ES384 and ES512.
  83. // See RFC 7518 for more details about the algorithms.
  84. Key crypto.Signer
  85. // HTTPClient optionally specifies an HTTP client to use
  86. // instead of http.DefaultClient.
  87. HTTPClient *http.Client
  88. // DirectoryURL points to the CA directory endpoint.
  89. // If empty, LetsEncryptURL is used.
  90. // Mutating this value after a successful call of Client's Discover method
  91. // will have no effect.
  92. DirectoryURL string
  93. // RetryBackoff computes the duration after which the nth retry of a failed request
  94. // should occur. The value of n for the first call on failure is 1.
  95. // The values of r and resp are the request and response of the last failed attempt.
  96. // If the returned value is negative or zero, no more retries are done and an error
  97. // is returned to the caller of the original method.
  98. //
  99. // Requests which result in a 4xx client error are not retried,
  100. // except for 400 Bad Request due to "bad nonce" errors and 429 Too Many Requests.
  101. //
  102. // If RetryBackoff is nil, a truncated exponential backoff algorithm
  103. // with the ceiling of 10 seconds is used, where each subsequent retry n
  104. // is done after either ("Retry-After" + jitter) or (2^n seconds + jitter),
  105. // preferring the former if "Retry-After" header is found in the resp.
  106. // The jitter is a random value up to 1 second.
  107. RetryBackoff func(n int, r *http.Request, resp *http.Response) time.Duration
  108. // UserAgent is prepended to the User-Agent header sent to the ACME server,
  109. // which by default is this package's name and version.
  110. //
  111. // Reusable libraries and tools in particular should set this value to be
  112. // identifiable by the server, in case they are causing issues.
  113. UserAgent string
  114. cacheMu sync.Mutex
  115. dir *Directory // cached result of Client's Discover method
  116. // KID is the key identifier provided by the CA. If not provided it will be
  117. // retrieved from the CA by making a call to the registration endpoint.
  118. KID KeyID
  119. noncesMu sync.Mutex
  120. nonces map[string]struct{} // nonces collected from previous responses
  121. }
  122. // accountKID returns a key ID associated with c.Key, the account identity
  123. // provided by the CA during RFC based registration.
  124. // It assumes c.Discover has already been called.
  125. //
  126. // accountKID requires at most one network roundtrip.
  127. // It caches only successful result.
  128. //
  129. // When in pre-RFC mode or when c.getRegRFC responds with an error, accountKID
  130. // returns noKeyID.
  131. func (c *Client) accountKID(ctx context.Context) KeyID {
  132. c.cacheMu.Lock()
  133. defer c.cacheMu.Unlock()
  134. if c.KID != noKeyID {
  135. return c.KID
  136. }
  137. a, err := c.getRegRFC(ctx)
  138. if err != nil {
  139. return noKeyID
  140. }
  141. c.KID = KeyID(a.URI)
  142. return c.KID
  143. }
  144. var errPreRFC = errors.New("acme: server does not support the RFC 8555 version of ACME")
  145. // Discover performs ACME server discovery using c.DirectoryURL.
  146. //
  147. // It caches successful result. So, subsequent calls will not result in
  148. // a network round-trip. This also means mutating c.DirectoryURL after successful call
  149. // of this method will have no effect.
  150. func (c *Client) Discover(ctx context.Context) (Directory, error) {
  151. c.cacheMu.Lock()
  152. defer c.cacheMu.Unlock()
  153. if c.dir != nil {
  154. return *c.dir, nil
  155. }
  156. res, err := c.get(ctx, c.directoryURL(), wantStatus(http.StatusOK))
  157. if err != nil {
  158. return Directory{}, err
  159. }
  160. defer res.Body.Close()
  161. c.addNonce(res.Header)
  162. var v struct {
  163. Reg string `json:"newAccount"`
  164. Authz string `json:"newAuthz"`
  165. Order string `json:"newOrder"`
  166. Revoke string `json:"revokeCert"`
  167. Nonce string `json:"newNonce"`
  168. KeyChange string `json:"keyChange"`
  169. Meta struct {
  170. Terms string `json:"termsOfService"`
  171. Website string `json:"website"`
  172. CAA []string `json:"caaIdentities"`
  173. ExternalAcct bool `json:"externalAccountRequired"`
  174. }
  175. }
  176. if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
  177. return Directory{}, err
  178. }
  179. if v.Order == "" {
  180. return Directory{}, errPreRFC
  181. }
  182. c.dir = &Directory{
  183. RegURL: v.Reg,
  184. AuthzURL: v.Authz,
  185. OrderURL: v.Order,
  186. RevokeURL: v.Revoke,
  187. NonceURL: v.Nonce,
  188. KeyChangeURL: v.KeyChange,
  189. Terms: v.Meta.Terms,
  190. Website: v.Meta.Website,
  191. CAA: v.Meta.CAA,
  192. ExternalAccountRequired: v.Meta.ExternalAcct,
  193. }
  194. return *c.dir, nil
  195. }
  196. func (c *Client) directoryURL() string {
  197. if c.DirectoryURL != "" {
  198. return c.DirectoryURL
  199. }
  200. return LetsEncryptURL
  201. }
  202. // CreateCert was part of the old version of ACME. It is incompatible with RFC 8555.
  203. //
  204. // Deprecated: this was for the pre-RFC 8555 version of ACME. Callers should use CreateOrderCert.
  205. func (c *Client) CreateCert(ctx context.Context, csr []byte, exp time.Duration, bundle bool) (der [][]byte, certURL string, err error) {
  206. return nil, "", errPreRFC
  207. }
  208. // FetchCert retrieves already issued certificate from the given url, in DER format.
  209. // It retries the request until the certificate is successfully retrieved,
  210. // context is cancelled by the caller or an error response is received.
  211. //
  212. // If the bundle argument is true, the returned value also contains the CA (issuer)
  213. // certificate chain.
  214. //
  215. // FetchCert returns an error if the CA's response or chain was unreasonably large.
  216. // Callers are encouraged to parse the returned value to ensure the certificate is valid
  217. // and has expected features.
  218. func (c *Client) FetchCert(ctx context.Context, url string, bundle bool) ([][]byte, error) {
  219. if _, err := c.Discover(ctx); err != nil {
  220. return nil, err
  221. }
  222. return c.fetchCertRFC(ctx, url, bundle)
  223. }
  224. // RevokeCert revokes a previously issued certificate cert, provided in DER format.
  225. //
  226. // The key argument, used to sign the request, must be authorized
  227. // to revoke the certificate. It's up to the CA to decide which keys are authorized.
  228. // For instance, the key pair of the certificate may be authorized.
  229. // If the key is nil, c.Key is used instead.
  230. func (c *Client) RevokeCert(ctx context.Context, key crypto.Signer, cert []byte, reason CRLReasonCode) error {
  231. if _, err := c.Discover(ctx); err != nil {
  232. return err
  233. }
  234. return c.revokeCertRFC(ctx, key, cert, reason)
  235. }
  236. // AcceptTOS always returns true to indicate the acceptance of a CA's Terms of Service
  237. // during account registration. See Register method of Client for more details.
  238. func AcceptTOS(tosURL string) bool { return true }
  239. // Register creates a new account with the CA using c.Key.
  240. // It returns the registered account. The account acct is not modified.
  241. //
  242. // The registration may require the caller to agree to the CA's Terms of Service (TOS).
  243. // If so, and the account has not indicated the acceptance of the terms (see Account for details),
  244. // Register calls prompt with a TOS URL provided by the CA. Prompt should report
  245. // whether the caller agrees to the terms. To always accept the terms, the caller can use AcceptTOS.
  246. //
  247. // When interfacing with an RFC-compliant CA, non-RFC 8555 fields of acct are ignored
  248. // and prompt is called if Directory's Terms field is non-zero.
  249. // Also see Error's Instance field for when a CA requires already registered accounts to agree
  250. // to an updated Terms of Service.
  251. func (c *Client) Register(ctx context.Context, acct *Account, prompt func(tosURL string) bool) (*Account, error) {
  252. if c.Key == nil {
  253. return nil, errors.New("acme: client.Key must be set to Register")
  254. }
  255. if _, err := c.Discover(ctx); err != nil {
  256. return nil, err
  257. }
  258. return c.registerRFC(ctx, acct, prompt)
  259. }
  260. // GetReg retrieves an existing account associated with c.Key.
  261. //
  262. // The url argument is a legacy artifact of the pre-RFC 8555 API
  263. // and is ignored.
  264. func (c *Client) GetReg(ctx context.Context, url string) (*Account, error) {
  265. if _, err := c.Discover(ctx); err != nil {
  266. return nil, err
  267. }
  268. return c.getRegRFC(ctx)
  269. }
  270. // UpdateReg updates an existing registration.
  271. // It returns an updated account copy. The provided account is not modified.
  272. //
  273. // The account's URI is ignored and the account URL associated with
  274. // c.Key is used instead.
  275. func (c *Client) UpdateReg(ctx context.Context, acct *Account) (*Account, error) {
  276. if _, err := c.Discover(ctx); err != nil {
  277. return nil, err
  278. }
  279. return c.updateRegRFC(ctx, acct)
  280. }
  281. // AccountKeyRollover attempts to transition a client's account key to a new key.
  282. // On success client's Key is updated which is not concurrency safe.
  283. // On failure an error will be returned.
  284. // The new key is already registered with the ACME provider if the following is true:
  285. // - error is of type acme.Error
  286. // - StatusCode should be 409 (Conflict)
  287. // - Location header will have the KID of the associated account
  288. //
  289. // More about account key rollover can be found at
  290. // https://tools.ietf.org/html/rfc8555#section-7.3.5.
  291. func (c *Client) AccountKeyRollover(ctx context.Context, newKey crypto.Signer) error {
  292. return c.accountKeyRollover(ctx, newKey)
  293. }
  294. // Authorize performs the initial step in the pre-authorization flow,
  295. // as opposed to order-based flow.
  296. // The caller will then need to choose from and perform a set of returned
  297. // challenges using c.Accept in order to successfully complete authorization.
  298. //
  299. // Once complete, the caller can use AuthorizeOrder which the CA
  300. // should provision with the already satisfied authorization.
  301. // For pre-RFC CAs, the caller can proceed directly to requesting a certificate
  302. // using CreateCert method.
  303. //
  304. // If an authorization has been previously granted, the CA may return
  305. // a valid authorization which has its Status field set to StatusValid.
  306. //
  307. // More about pre-authorization can be found at
  308. // https://tools.ietf.org/html/rfc8555#section-7.4.1.
  309. func (c *Client) Authorize(ctx context.Context, domain string) (*Authorization, error) {
  310. return c.authorize(ctx, "dns", domain)
  311. }
  312. // AuthorizeIP is the same as Authorize but requests IP address authorization.
  313. // Clients which successfully obtain such authorization may request to issue
  314. // a certificate for IP addresses.
  315. //
  316. // See the ACME spec extension for more details about IP address identifiers:
  317. // https://tools.ietf.org/html/draft-ietf-acme-ip.
  318. func (c *Client) AuthorizeIP(ctx context.Context, ipaddr string) (*Authorization, error) {
  319. return c.authorize(ctx, "ip", ipaddr)
  320. }
  321. func (c *Client) authorize(ctx context.Context, typ, val string) (*Authorization, error) {
  322. if _, err := c.Discover(ctx); err != nil {
  323. return nil, err
  324. }
  325. type authzID struct {
  326. Type string `json:"type"`
  327. Value string `json:"value"`
  328. }
  329. req := struct {
  330. Resource string `json:"resource"`
  331. Identifier authzID `json:"identifier"`
  332. }{
  333. Resource: "new-authz",
  334. Identifier: authzID{Type: typ, Value: val},
  335. }
  336. res, err := c.post(ctx, nil, c.dir.AuthzURL, req, wantStatus(http.StatusCreated))
  337. if err != nil {
  338. return nil, err
  339. }
  340. defer res.Body.Close()
  341. var v wireAuthz
  342. if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
  343. return nil, fmt.Errorf("acme: invalid response: %v", err)
  344. }
  345. if v.Status != StatusPending && v.Status != StatusValid {
  346. return nil, fmt.Errorf("acme: unexpected status: %s", v.Status)
  347. }
  348. return v.authorization(res.Header.Get("Location")), nil
  349. }
  350. // GetAuthorization retrieves an authorization identified by the given URL.
  351. //
  352. // If a caller needs to poll an authorization until its status is final,
  353. // see the WaitAuthorization method.
  354. func (c *Client) GetAuthorization(ctx context.Context, url string) (*Authorization, error) {
  355. if _, err := c.Discover(ctx); err != nil {
  356. return nil, err
  357. }
  358. res, err := c.postAsGet(ctx, url, wantStatus(http.StatusOK))
  359. if err != nil {
  360. return nil, err
  361. }
  362. defer res.Body.Close()
  363. var v wireAuthz
  364. if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
  365. return nil, fmt.Errorf("acme: invalid response: %v", err)
  366. }
  367. return v.authorization(url), nil
  368. }
  369. // RevokeAuthorization relinquishes an existing authorization identified
  370. // by the given URL.
  371. // The url argument is an Authorization.URI value.
  372. //
  373. // If successful, the caller will be required to obtain a new authorization
  374. // using the Authorize or AuthorizeOrder methods before being able to request
  375. // a new certificate for the domain associated with the authorization.
  376. //
  377. // It does not revoke existing certificates.
  378. func (c *Client) RevokeAuthorization(ctx context.Context, url string) error {
  379. if _, err := c.Discover(ctx); err != nil {
  380. return err
  381. }
  382. req := struct {
  383. Resource string `json:"resource"`
  384. Status string `json:"status"`
  385. Delete bool `json:"delete"`
  386. }{
  387. Resource: "authz",
  388. Status: "deactivated",
  389. Delete: true,
  390. }
  391. res, err := c.post(ctx, nil, url, req, wantStatus(http.StatusOK))
  392. if err != nil {
  393. return err
  394. }
  395. defer res.Body.Close()
  396. return nil
  397. }
  398. // WaitAuthorization polls an authorization at the given URL
  399. // until it is in one of the final states, StatusValid or StatusInvalid,
  400. // the ACME CA responded with a 4xx error code, or the context is done.
  401. //
  402. // It returns a non-nil Authorization only if its Status is StatusValid.
  403. // In all other cases WaitAuthorization returns an error.
  404. // If the Status is StatusInvalid, the returned error is of type *AuthorizationError.
  405. func (c *Client) WaitAuthorization(ctx context.Context, url string) (*Authorization, error) {
  406. if _, err := c.Discover(ctx); err != nil {
  407. return nil, err
  408. }
  409. for {
  410. res, err := c.postAsGet(ctx, url, wantStatus(http.StatusOK, http.StatusAccepted))
  411. if err != nil {
  412. return nil, err
  413. }
  414. var raw wireAuthz
  415. err = json.NewDecoder(res.Body).Decode(&raw)
  416. res.Body.Close()
  417. switch {
  418. case err != nil:
  419. // Skip and retry.
  420. case raw.Status == StatusValid:
  421. return raw.authorization(url), nil
  422. case raw.Status == StatusInvalid:
  423. return nil, raw.error(url)
  424. }
  425. // Exponential backoff is implemented in c.get above.
  426. // This is just to prevent continuously hitting the CA
  427. // while waiting for a final authorization status.
  428. d := retryAfter(res.Header.Get("Retry-After"))
  429. if d == 0 {
  430. // Given that the fastest challenges TLS-SNI and HTTP-01
  431. // require a CA to make at least 1 network round trip
  432. // and most likely persist a challenge state,
  433. // this default delay seems reasonable.
  434. d = time.Second
  435. }
  436. t := time.NewTimer(d)
  437. select {
  438. case <-ctx.Done():
  439. t.Stop()
  440. return nil, ctx.Err()
  441. case <-t.C:
  442. // Retry.
  443. }
  444. }
  445. }
  446. // GetChallenge retrieves the current status of an challenge.
  447. //
  448. // A client typically polls a challenge status using this method.
  449. func (c *Client) GetChallenge(ctx context.Context, url string) (*Challenge, error) {
  450. if _, err := c.Discover(ctx); err != nil {
  451. return nil, err
  452. }
  453. res, err := c.postAsGet(ctx, url, wantStatus(http.StatusOK, http.StatusAccepted))
  454. if err != nil {
  455. return nil, err
  456. }
  457. defer res.Body.Close()
  458. v := wireChallenge{URI: url}
  459. if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
  460. return nil, fmt.Errorf("acme: invalid response: %v", err)
  461. }
  462. return v.challenge(), nil
  463. }
  464. // Accept informs the server that the client accepts one of its challenges
  465. // previously obtained with c.Authorize.
  466. //
  467. // The server will then perform the validation asynchronously.
  468. func (c *Client) Accept(ctx context.Context, chal *Challenge) (*Challenge, error) {
  469. if _, err := c.Discover(ctx); err != nil {
  470. return nil, err
  471. }
  472. res, err := c.post(ctx, nil, chal.URI, json.RawMessage("{}"), wantStatus(
  473. http.StatusOK, // according to the spec
  474. http.StatusAccepted, // Let's Encrypt: see https://goo.gl/WsJ7VT (acme-divergences.md)
  475. ))
  476. if err != nil {
  477. return nil, err
  478. }
  479. defer res.Body.Close()
  480. var v wireChallenge
  481. if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
  482. return nil, fmt.Errorf("acme: invalid response: %v", err)
  483. }
  484. return v.challenge(), nil
  485. }
  486. // DNS01ChallengeRecord returns a DNS record value for a dns-01 challenge response.
  487. // A TXT record containing the returned value must be provisioned under
  488. // "_acme-challenge" name of the domain being validated.
  489. //
  490. // The token argument is a Challenge.Token value.
  491. func (c *Client) DNS01ChallengeRecord(token string) (string, error) {
  492. ka, err := keyAuth(c.Key.Public(), token)
  493. if err != nil {
  494. return "", err
  495. }
  496. b := sha256.Sum256([]byte(ka))
  497. return base64.RawURLEncoding.EncodeToString(b[:]), nil
  498. }
  499. // HTTP01ChallengeResponse returns the response for an http-01 challenge.
  500. // Servers should respond with the value to HTTP requests at the URL path
  501. // provided by HTTP01ChallengePath to validate the challenge and prove control
  502. // over a domain name.
  503. //
  504. // The token argument is a Challenge.Token value.
  505. func (c *Client) HTTP01ChallengeResponse(token string) (string, error) {
  506. return keyAuth(c.Key.Public(), token)
  507. }
  508. // HTTP01ChallengePath returns the URL path at which the response for an http-01 challenge
  509. // should be provided by the servers.
  510. // The response value can be obtained with HTTP01ChallengeResponse.
  511. //
  512. // The token argument is a Challenge.Token value.
  513. func (c *Client) HTTP01ChallengePath(token string) string {
  514. return "/.well-known/acme-challenge/" + token
  515. }
  516. // TLSSNI01ChallengeCert creates a certificate for TLS-SNI-01 challenge response.
  517. //
  518. // Deprecated: This challenge type is unused in both draft-02 and RFC versions of the ACME spec.
  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. //
  535. // Deprecated: This challenge type is unused in both draft-02 and RFC versions of the ACME spec.
  536. func (c *Client) TLSSNI02ChallengeCert(token string, opt ...CertOption) (cert tls.Certificate, name string, err error) {
  537. b := sha256.Sum256([]byte(token))
  538. h := hex.EncodeToString(b[:])
  539. sanA := fmt.Sprintf("%s.%s.token.acme.invalid", h[:32], h[32:])
  540. ka, err := keyAuth(c.Key.Public(), token)
  541. if err != nil {
  542. return tls.Certificate{}, "", err
  543. }
  544. b = sha256.Sum256([]byte(ka))
  545. h = hex.EncodeToString(b[:])
  546. sanB := fmt.Sprintf("%s.%s.ka.acme.invalid", h[:32], h[32:])
  547. cert, err = tlsChallengeCert([]string{sanA, sanB}, opt)
  548. if err != nil {
  549. return tls.Certificate{}, "", err
  550. }
  551. return cert, sanA, nil
  552. }
  553. // TLSALPN01ChallengeCert creates a certificate for TLS-ALPN-01 challenge response.
  554. // Servers can present the certificate to validate the challenge and prove control
  555. // over a domain name. For more details on TLS-ALPN-01 see
  556. // https://tools.ietf.org/html/draft-shoemaker-acme-tls-alpn-00#section-3
  557. //
  558. // The token argument is a Challenge.Token value.
  559. // If a WithKey option is provided, its private part signs the returned cert,
  560. // and the public part is used to specify the signee.
  561. // If no WithKey option is provided, a new ECDSA key is generated using P-256 curve.
  562. //
  563. // The returned certificate is valid for the next 24 hours and must be presented only when
  564. // the server name in the TLS ClientHello matches the domain, and the special acme-tls/1 ALPN protocol
  565. // has been specified.
  566. func (c *Client) TLSALPN01ChallengeCert(token, domain string, opt ...CertOption) (cert tls.Certificate, err error) {
  567. ka, err := keyAuth(c.Key.Public(), token)
  568. if err != nil {
  569. return tls.Certificate{}, err
  570. }
  571. shasum := sha256.Sum256([]byte(ka))
  572. extValue, err := asn1.Marshal(shasum[:])
  573. if err != nil {
  574. return tls.Certificate{}, err
  575. }
  576. acmeExtension := pkix.Extension{
  577. Id: idPeACMEIdentifier,
  578. Critical: true,
  579. Value: extValue,
  580. }
  581. tmpl := defaultTLSChallengeCertTemplate()
  582. var newOpt []CertOption
  583. for _, o := range opt {
  584. switch o := o.(type) {
  585. case *certOptTemplate:
  586. t := *(*x509.Certificate)(o) // shallow copy is ok
  587. tmpl = &t
  588. default:
  589. newOpt = append(newOpt, o)
  590. }
  591. }
  592. tmpl.ExtraExtensions = append(tmpl.ExtraExtensions, acmeExtension)
  593. newOpt = append(newOpt, WithTemplate(tmpl))
  594. return tlsChallengeCert([]string{domain}, newOpt)
  595. }
  596. // popNonce returns a nonce value previously stored with c.addNonce
  597. // or fetches a fresh one from c.dir.NonceURL.
  598. // If NonceURL is empty, it first tries c.directoryURL() and, failing that,
  599. // the provided url.
  600. func (c *Client) popNonce(ctx context.Context, url string) (string, error) {
  601. c.noncesMu.Lock()
  602. defer c.noncesMu.Unlock()
  603. if len(c.nonces) == 0 {
  604. if c.dir != nil && c.dir.NonceURL != "" {
  605. return c.fetchNonce(ctx, c.dir.NonceURL)
  606. }
  607. dirURL := c.directoryURL()
  608. v, err := c.fetchNonce(ctx, dirURL)
  609. if err != nil && url != dirURL {
  610. v, err = c.fetchNonce(ctx, url)
  611. }
  612. return v, err
  613. }
  614. var nonce string
  615. for nonce = range c.nonces {
  616. delete(c.nonces, nonce)
  617. break
  618. }
  619. return nonce, nil
  620. }
  621. // clearNonces clears any stored nonces
  622. func (c *Client) clearNonces() {
  623. c.noncesMu.Lock()
  624. defer c.noncesMu.Unlock()
  625. c.nonces = make(map[string]struct{})
  626. }
  627. // addNonce stores a nonce value found in h (if any) for future use.
  628. func (c *Client) addNonce(h http.Header) {
  629. v := nonceFromHeader(h)
  630. if v == "" {
  631. return
  632. }
  633. c.noncesMu.Lock()
  634. defer c.noncesMu.Unlock()
  635. if len(c.nonces) >= maxNonces {
  636. return
  637. }
  638. if c.nonces == nil {
  639. c.nonces = make(map[string]struct{})
  640. }
  641. c.nonces[v] = struct{}{}
  642. }
  643. func (c *Client) fetchNonce(ctx context.Context, url string) (string, error) {
  644. r, err := http.NewRequest("HEAD", url, nil)
  645. if err != nil {
  646. return "", err
  647. }
  648. resp, err := c.doNoRetry(ctx, r)
  649. if err != nil {
  650. return "", err
  651. }
  652. defer resp.Body.Close()
  653. nonce := nonceFromHeader(resp.Header)
  654. if nonce == "" {
  655. if resp.StatusCode > 299 {
  656. return "", responseError(resp)
  657. }
  658. return "", errors.New("acme: nonce not found")
  659. }
  660. return nonce, nil
  661. }
  662. func nonceFromHeader(h http.Header) string {
  663. return h.Get("Replay-Nonce")
  664. }
  665. // linkHeader returns URI-Reference values of all Link headers
  666. // with relation-type rel.
  667. // See https://tools.ietf.org/html/rfc5988#section-5 for details.
  668. func linkHeader(h http.Header, rel string) []string {
  669. var links []string
  670. for _, v := range h["Link"] {
  671. parts := strings.Split(v, ";")
  672. for _, p := range parts {
  673. p = strings.TrimSpace(p)
  674. if !strings.HasPrefix(p, "rel=") {
  675. continue
  676. }
  677. if v := strings.Trim(p[4:], `"`); v == rel {
  678. links = append(links, strings.Trim(parts[0], "<>"))
  679. }
  680. }
  681. }
  682. return links
  683. }
  684. // keyAuth generates a key authorization string for a given token.
  685. func keyAuth(pub crypto.PublicKey, token string) (string, error) {
  686. th, err := JWKThumbprint(pub)
  687. if err != nil {
  688. return "", err
  689. }
  690. return fmt.Sprintf("%s.%s", token, th), nil
  691. }
  692. // defaultTLSChallengeCertTemplate is a template used to create challenge certs for TLS challenges.
  693. func defaultTLSChallengeCertTemplate() *x509.Certificate {
  694. return &x509.Certificate{
  695. SerialNumber: big.NewInt(1),
  696. NotBefore: time.Now(),
  697. NotAfter: time.Now().Add(24 * time.Hour),
  698. BasicConstraintsValid: true,
  699. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
  700. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  701. }
  702. }
  703. // tlsChallengeCert creates a temporary certificate for TLS-SNI challenges
  704. // with the given SANs and auto-generated public/private key pair.
  705. // The Subject Common Name is set to the first SAN to aid debugging.
  706. // To create a cert with a custom key pair, specify WithKey option.
  707. func tlsChallengeCert(san []string, opt []CertOption) (tls.Certificate, error) {
  708. var key crypto.Signer
  709. tmpl := defaultTLSChallengeCertTemplate()
  710. for _, o := range opt {
  711. switch o := o.(type) {
  712. case *certOptKey:
  713. if key != nil {
  714. return tls.Certificate{}, errors.New("acme: duplicate key option")
  715. }
  716. key = o.key
  717. case *certOptTemplate:
  718. t := *(*x509.Certificate)(o) // shallow copy is ok
  719. tmpl = &t
  720. default:
  721. // package's fault, if we let this happen:
  722. panic(fmt.Sprintf("unsupported option type %T", o))
  723. }
  724. }
  725. if key == nil {
  726. var err error
  727. if key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader); err != nil {
  728. return tls.Certificate{}, err
  729. }
  730. }
  731. tmpl.DNSNames = san
  732. if len(san) > 0 {
  733. tmpl.Subject.CommonName = san[0]
  734. }
  735. der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, key.Public(), key)
  736. if err != nil {
  737. return tls.Certificate{}, err
  738. }
  739. return tls.Certificate{
  740. Certificate: [][]byte{der},
  741. PrivateKey: key,
  742. }, nil
  743. }
  744. // encodePEM returns b encoded as PEM with block of type typ.
  745. func encodePEM(typ string, b []byte) []byte {
  746. pb := &pem.Block{Type: typ, Bytes: b}
  747. return pem.EncodeToMemory(pb)
  748. }
  749. // timeNow is time.Now, except in tests which can mess with it.
  750. var timeNow = time.Now