acme.go 32 KB

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