acme.go 27 KB

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