acme.go 31 KB

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