acme.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  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 err := 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.retryPostJWS(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.retryPostJWS(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.retryPostJWS(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.retryPostJWS(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 of type *AuthorizationError.
  402. func (c *Client) WaitAuthorization(ctx context.Context, url string) (*Authorization, error) {
  403. sleep := sleeper(ctx)
  404. for {
  405. res, err := c.get(ctx, url)
  406. if err != nil {
  407. return nil, err
  408. }
  409. retry := res.Header.Get("retry-after")
  410. if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusAccepted {
  411. res.Body.Close()
  412. if err := sleep(retry, 1); err != nil {
  413. return nil, err
  414. }
  415. continue
  416. }
  417. var raw wireAuthz
  418. err = json.NewDecoder(res.Body).Decode(&raw)
  419. res.Body.Close()
  420. if err != nil {
  421. if err := sleep(retry, 0); err != nil {
  422. return nil, err
  423. }
  424. continue
  425. }
  426. if raw.Status == StatusValid {
  427. return raw.authorization(url), nil
  428. }
  429. if raw.Status == StatusInvalid {
  430. return nil, raw.error(url)
  431. }
  432. if err := sleep(retry, 0); err != nil {
  433. return nil, err
  434. }
  435. }
  436. }
  437. // GetChallenge retrieves the current status of an challenge.
  438. //
  439. // A client typically polls a challenge status using this method.
  440. func (c *Client) GetChallenge(ctx context.Context, url string) (*Challenge, error) {
  441. res, err := c.get(ctx, url)
  442. if err != nil {
  443. return nil, err
  444. }
  445. defer res.Body.Close()
  446. if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusAccepted {
  447. return nil, responseError(res)
  448. }
  449. v := wireChallenge{URI: url}
  450. if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
  451. return nil, fmt.Errorf("acme: invalid response: %v", err)
  452. }
  453. return v.challenge(), nil
  454. }
  455. // Accept informs the server that the client accepts one of its challenges
  456. // previously obtained with c.Authorize.
  457. //
  458. // The server will then perform the validation asynchronously.
  459. func (c *Client) Accept(ctx context.Context, chal *Challenge) (*Challenge, error) {
  460. auth, err := keyAuth(c.Key.Public(), chal.Token)
  461. if err != nil {
  462. return nil, err
  463. }
  464. req := struct {
  465. Resource string `json:"resource"`
  466. Type string `json:"type"`
  467. Auth string `json:"keyAuthorization"`
  468. }{
  469. Resource: "challenge",
  470. Type: chal.Type,
  471. Auth: auth,
  472. }
  473. res, err := c.retryPostJWS(ctx, c.Key, chal.URI, req)
  474. if err != nil {
  475. return nil, err
  476. }
  477. defer res.Body.Close()
  478. // Note: the protocol specifies 200 as the expected response code, but
  479. // letsencrypt seems to be returning 202.
  480. if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusAccepted {
  481. return nil, responseError(res)
  482. }
  483. var v wireChallenge
  484. if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
  485. return nil, fmt.Errorf("acme: invalid response: %v", err)
  486. }
  487. return v.challenge(), nil
  488. }
  489. // DNS01ChallengeRecord returns a DNS record value for a dns-01 challenge response.
  490. // A TXT record containing the returned value must be provisioned under
  491. // "_acme-challenge" name of the domain being validated.
  492. //
  493. // The token argument is a Challenge.Token value.
  494. func (c *Client) DNS01ChallengeRecord(token string) (string, error) {
  495. ka, err := keyAuth(c.Key.Public(), token)
  496. if err != nil {
  497. return "", err
  498. }
  499. b := sha256.Sum256([]byte(ka))
  500. return base64.RawURLEncoding.EncodeToString(b[:]), nil
  501. }
  502. // HTTP01ChallengeResponse returns the response for an http-01 challenge.
  503. // Servers should respond with the value to HTTP requests at the URL path
  504. // provided by HTTP01ChallengePath to validate the challenge and prove control
  505. // over a domain name.
  506. //
  507. // The token argument is a Challenge.Token value.
  508. func (c *Client) HTTP01ChallengeResponse(token string) (string, error) {
  509. return keyAuth(c.Key.Public(), token)
  510. }
  511. // HTTP01ChallengePath returns the URL path at which the response for an http-01 challenge
  512. // should be provided by the servers.
  513. // The response value can be obtained with HTTP01ChallengeResponse.
  514. //
  515. // The token argument is a Challenge.Token value.
  516. func (c *Client) HTTP01ChallengePath(token string) string {
  517. return "/.well-known/acme-challenge/" + token
  518. }
  519. // TLSSNI01ChallengeCert creates a certificate for TLS-SNI-01 challenge response.
  520. // Servers can present the certificate to validate the challenge and prove control
  521. // over a domain name.
  522. //
  523. // The implementation is incomplete in that the returned value is a single certificate,
  524. // computed only for Z0 of the key authorization. ACME CAs are expected to update
  525. // their implementations to use the newer version, TLS-SNI-02.
  526. // For more details on TLS-SNI-01 see https://tools.ietf.org/html/draft-ietf-acme-acme-01#section-7.3.
  527. //
  528. // The token argument is a Challenge.Token value.
  529. // If a WithKey option is provided, its private part signs the returned cert,
  530. // and the public part is used to specify the signee.
  531. // If no WithKey option is provided, a new ECDSA key is generated using P-256 curve.
  532. //
  533. // The returned certificate is valid for the next 24 hours and must be presented only when
  534. // the server name of the client hello matches exactly the returned name value.
  535. func (c *Client) TLSSNI01ChallengeCert(token string, opt ...CertOption) (cert tls.Certificate, name string, err error) {
  536. ka, err := keyAuth(c.Key.Public(), token)
  537. if err != nil {
  538. return tls.Certificate{}, "", err
  539. }
  540. b := sha256.Sum256([]byte(ka))
  541. h := hex.EncodeToString(b[:])
  542. name = fmt.Sprintf("%s.%s.acme.invalid", h[:32], h[32:])
  543. cert, err = tlsChallengeCert([]string{name}, opt)
  544. if err != nil {
  545. return tls.Certificate{}, "", err
  546. }
  547. return cert, name, nil
  548. }
  549. // TLSSNI02ChallengeCert creates a certificate for TLS-SNI-02 challenge response.
  550. // Servers can present the certificate to validate the challenge and prove control
  551. // over a domain name. For more details on TLS-SNI-02 see
  552. // https://tools.ietf.org/html/draft-ietf-acme-acme-03#section-7.3.
  553. //
  554. // The token argument is a Challenge.Token value.
  555. // If a WithKey option is provided, its private part signs the returned cert,
  556. // and the public part is used to specify the signee.
  557. // If no WithKey option is provided, a new ECDSA key is generated using P-256 curve.
  558. //
  559. // The returned certificate is valid for the next 24 hours and must be presented only when
  560. // the server name in the client hello matches exactly the returned name value.
  561. func (c *Client) TLSSNI02ChallengeCert(token string, opt ...CertOption) (cert tls.Certificate, name string, err error) {
  562. b := sha256.Sum256([]byte(token))
  563. h := hex.EncodeToString(b[:])
  564. sanA := fmt.Sprintf("%s.%s.token.acme.invalid", h[:32], h[32:])
  565. ka, err := keyAuth(c.Key.Public(), token)
  566. if err != nil {
  567. return tls.Certificate{}, "", err
  568. }
  569. b = sha256.Sum256([]byte(ka))
  570. h = hex.EncodeToString(b[:])
  571. sanB := fmt.Sprintf("%s.%s.ka.acme.invalid", h[:32], h[32:])
  572. cert, err = tlsChallengeCert([]string{sanA, sanB}, opt)
  573. if err != nil {
  574. return tls.Certificate{}, "", err
  575. }
  576. return cert, sanA, nil
  577. }
  578. // doReg sends all types of registration requests.
  579. // The type of request is identified by typ argument, which is a "resource"
  580. // in the ACME spec terms.
  581. //
  582. // A non-nil acct argument indicates whether the intention is to mutate data
  583. // of the Account. Only Contact and Agreement of its fields are used
  584. // in such cases.
  585. func (c *Client) doReg(ctx context.Context, url string, typ string, acct *Account) (*Account, error) {
  586. req := struct {
  587. Resource string `json:"resource"`
  588. Contact []string `json:"contact,omitempty"`
  589. Agreement string `json:"agreement,omitempty"`
  590. }{
  591. Resource: typ,
  592. }
  593. if acct != nil {
  594. req.Contact = acct.Contact
  595. req.Agreement = acct.AgreedTerms
  596. }
  597. res, err := c.retryPostJWS(ctx, c.Key, url, req)
  598. if err != nil {
  599. return nil, err
  600. }
  601. defer res.Body.Close()
  602. if res.StatusCode < 200 || res.StatusCode > 299 {
  603. return nil, responseError(res)
  604. }
  605. var v struct {
  606. Contact []string
  607. Agreement string
  608. Authorizations string
  609. Certificates string
  610. }
  611. if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
  612. return nil, fmt.Errorf("acme: invalid response: %v", err)
  613. }
  614. var tos string
  615. if v := linkHeader(res.Header, "terms-of-service"); len(v) > 0 {
  616. tos = v[0]
  617. }
  618. var authz string
  619. if v := linkHeader(res.Header, "next"); len(v) > 0 {
  620. authz = v[0]
  621. }
  622. return &Account{
  623. URI: res.Header.Get("Location"),
  624. Contact: v.Contact,
  625. AgreedTerms: v.Agreement,
  626. CurrentTerms: tos,
  627. Authz: authz,
  628. Authorizations: v.Authorizations,
  629. Certificates: v.Certificates,
  630. }, nil
  631. }
  632. // retryPostJWS will retry calls to postJWS if there is a badNonce error,
  633. // clearing the stored nonces after each error.
  634. // If the response was 4XX-5XX, then responseError is called on the body,
  635. // the body is closed, and the error returned.
  636. func (c *Client) retryPostJWS(ctx context.Context, key crypto.Signer, url string, body interface{}) (*http.Response, error) {
  637. sleep := sleeper(ctx)
  638. for {
  639. res, err := c.postJWS(ctx, key, url, body)
  640. if err != nil {
  641. return nil, err
  642. }
  643. // handle errors 4XX-5XX with responseError
  644. if res.StatusCode >= 400 && res.StatusCode <= 599 {
  645. err := responseError(res)
  646. res.Body.Close()
  647. // according to spec badNonce is urn:ietf:params:acme:error:badNonce
  648. // however, acme servers in the wild return their version of the error
  649. // https://tools.ietf.org/html/draft-ietf-acme-acme-02#section-5.4
  650. if ae, ok := err.(*Error); ok && strings.HasSuffix(strings.ToLower(ae.ProblemType), ":badnonce") {
  651. // clear any nonces that we might've stored that might now be
  652. // considered bad
  653. c.clearNonces()
  654. retry := res.Header.Get("retry-after")
  655. if err := sleep(retry, 1); err != nil {
  656. return nil, err
  657. }
  658. continue
  659. }
  660. return nil, err
  661. }
  662. return res, nil
  663. }
  664. }
  665. // postJWS signs the body with the given key and POSTs it to the provided url.
  666. // The body argument must be JSON-serializable.
  667. func (c *Client) postJWS(ctx context.Context, key crypto.Signer, url string, body interface{}) (*http.Response, error) {
  668. nonce, err := c.popNonce(ctx, url)
  669. if err != nil {
  670. return nil, err
  671. }
  672. b, err := jwsEncodeJSON(body, key, nonce)
  673. if err != nil {
  674. return nil, err
  675. }
  676. res, err := c.post(ctx, url, "application/jose+json", bytes.NewReader(b))
  677. if err != nil {
  678. return nil, err
  679. }
  680. c.addNonce(res.Header)
  681. return res, nil
  682. }
  683. // popNonce returns a nonce value previously stored with c.addNonce
  684. // or fetches a fresh one from the given URL.
  685. func (c *Client) popNonce(ctx context.Context, url string) (string, error) {
  686. c.noncesMu.Lock()
  687. defer c.noncesMu.Unlock()
  688. if len(c.nonces) == 0 {
  689. return c.fetchNonce(ctx, url)
  690. }
  691. var nonce string
  692. for nonce = range c.nonces {
  693. delete(c.nonces, nonce)
  694. break
  695. }
  696. return nonce, nil
  697. }
  698. // clearNonces clears any stored nonces
  699. func (c *Client) clearNonces() {
  700. c.noncesMu.Lock()
  701. defer c.noncesMu.Unlock()
  702. c.nonces = make(map[string]struct{})
  703. }
  704. // addNonce stores a nonce value found in h (if any) for future use.
  705. func (c *Client) addNonce(h http.Header) {
  706. v := nonceFromHeader(h)
  707. if v == "" {
  708. return
  709. }
  710. c.noncesMu.Lock()
  711. defer c.noncesMu.Unlock()
  712. if len(c.nonces) >= maxNonces {
  713. return
  714. }
  715. if c.nonces == nil {
  716. c.nonces = make(map[string]struct{})
  717. }
  718. c.nonces[v] = struct{}{}
  719. }
  720. func (c *Client) httpClient() *http.Client {
  721. if c.HTTPClient != nil {
  722. return c.HTTPClient
  723. }
  724. return http.DefaultClient
  725. }
  726. func (c *Client) get(ctx context.Context, urlStr string) (*http.Response, error) {
  727. req, err := http.NewRequest("GET", urlStr, nil)
  728. if err != nil {
  729. return nil, err
  730. }
  731. return c.do(ctx, req)
  732. }
  733. func (c *Client) head(ctx context.Context, urlStr string) (*http.Response, error) {
  734. req, err := http.NewRequest("HEAD", urlStr, nil)
  735. if err != nil {
  736. return nil, err
  737. }
  738. return c.do(ctx, req)
  739. }
  740. func (c *Client) post(ctx context.Context, urlStr, contentType string, body io.Reader) (*http.Response, error) {
  741. req, err := http.NewRequest("POST", urlStr, body)
  742. if err != nil {
  743. return nil, err
  744. }
  745. req.Header.Set("Content-Type", contentType)
  746. return c.do(ctx, req)
  747. }
  748. func (c *Client) do(ctx context.Context, req *http.Request) (*http.Response, error) {
  749. res, err := c.httpClient().Do(req.WithContext(ctx))
  750. if err != nil {
  751. select {
  752. case <-ctx.Done():
  753. // Prefer the unadorned context error.
  754. // (The acme package had tests assuming this, previously from ctxhttp's
  755. // behavior, predating net/http supporting contexts natively)
  756. // TODO(bradfitz): reconsider this in the future. But for now this
  757. // requires no test updates.
  758. return nil, ctx.Err()
  759. default:
  760. return nil, err
  761. }
  762. }
  763. return res, nil
  764. }
  765. func (c *Client) fetchNonce(ctx context.Context, url string) (string, error) {
  766. resp, err := c.head(ctx, url)
  767. if err != nil {
  768. return "", err
  769. }
  770. defer resp.Body.Close()
  771. nonce := nonceFromHeader(resp.Header)
  772. if nonce == "" {
  773. if resp.StatusCode > 299 {
  774. return "", responseError(resp)
  775. }
  776. return "", errors.New("acme: nonce not found")
  777. }
  778. return nonce, nil
  779. }
  780. func nonceFromHeader(h http.Header) string {
  781. return h.Get("Replay-Nonce")
  782. }
  783. func (c *Client) responseCert(ctx context.Context, res *http.Response, bundle bool) ([][]byte, error) {
  784. b, err := ioutil.ReadAll(io.LimitReader(res.Body, maxCertSize+1))
  785. if err != nil {
  786. return nil, fmt.Errorf("acme: response stream: %v", err)
  787. }
  788. if len(b) > maxCertSize {
  789. return nil, errors.New("acme: certificate is too big")
  790. }
  791. cert := [][]byte{b}
  792. if !bundle {
  793. return cert, nil
  794. }
  795. // Append CA chain cert(s).
  796. // At least one is required according to the spec:
  797. // https://tools.ietf.org/html/draft-ietf-acme-acme-03#section-6.3.1
  798. up := linkHeader(res.Header, "up")
  799. if len(up) == 0 {
  800. return nil, errors.New("acme: rel=up link not found")
  801. }
  802. if len(up) > maxChainLen {
  803. return nil, errors.New("acme: rel=up link is too large")
  804. }
  805. for _, url := range up {
  806. cc, err := c.chainCert(ctx, url, 0)
  807. if err != nil {
  808. return nil, err
  809. }
  810. cert = append(cert, cc...)
  811. }
  812. return cert, nil
  813. }
  814. // responseError creates an error of Error type from resp.
  815. func responseError(resp *http.Response) error {
  816. // don't care if ReadAll returns an error:
  817. // json.Unmarshal will fail in that case anyway
  818. b, _ := ioutil.ReadAll(resp.Body)
  819. e := &wireError{Status: resp.StatusCode}
  820. if err := json.Unmarshal(b, e); err != nil {
  821. // this is not a regular error response:
  822. // populate detail with anything we received,
  823. // e.Status will already contain HTTP response code value
  824. e.Detail = string(b)
  825. if e.Detail == "" {
  826. e.Detail = resp.Status
  827. }
  828. }
  829. return e.error(resp.Header)
  830. }
  831. // chainCert fetches CA certificate chain recursively by following "up" links.
  832. // Each recursive call increments the depth by 1, resulting in an error
  833. // if the recursion level reaches maxChainLen.
  834. //
  835. // First chainCert call starts with depth of 0.
  836. func (c *Client) chainCert(ctx context.Context, url string, depth int) ([][]byte, error) {
  837. if depth >= maxChainLen {
  838. return nil, errors.New("acme: certificate chain is too deep")
  839. }
  840. res, err := c.get(ctx, url)
  841. if err != nil {
  842. return nil, err
  843. }
  844. defer res.Body.Close()
  845. if res.StatusCode != http.StatusOK {
  846. return nil, responseError(res)
  847. }
  848. b, err := ioutil.ReadAll(io.LimitReader(res.Body, maxCertSize+1))
  849. if err != nil {
  850. return nil, err
  851. }
  852. if len(b) > maxCertSize {
  853. return nil, errors.New("acme: certificate is too big")
  854. }
  855. chain := [][]byte{b}
  856. uplink := linkHeader(res.Header, "up")
  857. if len(uplink) > maxChainLen {
  858. return nil, errors.New("acme: certificate chain is too large")
  859. }
  860. for _, up := range uplink {
  861. cc, err := c.chainCert(ctx, up, depth+1)
  862. if err != nil {
  863. return nil, err
  864. }
  865. chain = append(chain, cc...)
  866. }
  867. return chain, nil
  868. }
  869. // linkHeader returns URI-Reference values of all Link headers
  870. // with relation-type rel.
  871. // See https://tools.ietf.org/html/rfc5988#section-5 for details.
  872. func linkHeader(h http.Header, rel string) []string {
  873. var links []string
  874. for _, v := range h["Link"] {
  875. parts := strings.Split(v, ";")
  876. for _, p := range parts {
  877. p = strings.TrimSpace(p)
  878. if !strings.HasPrefix(p, "rel=") {
  879. continue
  880. }
  881. if v := strings.Trim(p[4:], `"`); v == rel {
  882. links = append(links, strings.Trim(parts[0], "<>"))
  883. }
  884. }
  885. }
  886. return links
  887. }
  888. // sleeper returns a function that accepts the Retry-After HTTP header value
  889. // and an increment that's used with backoff to increasingly sleep on
  890. // consecutive calls until the context is done. If the Retry-After header
  891. // cannot be parsed, then backoff is used with a maximum sleep time of 10
  892. // seconds.
  893. func sleeper(ctx context.Context) func(ra string, inc int) error {
  894. var count int
  895. return func(ra string, inc int) error {
  896. count += inc
  897. d := backoff(count, 10*time.Second)
  898. d = retryAfter(ra, d)
  899. wakeup := time.NewTimer(d)
  900. defer wakeup.Stop()
  901. select {
  902. case <-ctx.Done():
  903. return ctx.Err()
  904. case <-wakeup.C:
  905. return nil
  906. }
  907. }
  908. }
  909. // retryAfter parses a Retry-After HTTP header value,
  910. // trying to convert v into an int (seconds) or use http.ParseTime otherwise.
  911. // It returns d if v cannot be parsed.
  912. func retryAfter(v string, d time.Duration) time.Duration {
  913. if i, err := strconv.Atoi(v); err == nil {
  914. return time.Duration(i) * time.Second
  915. }
  916. t, err := http.ParseTime(v)
  917. if err != nil {
  918. return d
  919. }
  920. return t.Sub(timeNow())
  921. }
  922. // backoff computes a duration after which an n+1 retry iteration should occur
  923. // using truncated exponential backoff algorithm.
  924. //
  925. // The n argument is always bounded between 0 and 30.
  926. // The max argument defines upper bound for the returned value.
  927. func backoff(n int, max time.Duration) time.Duration {
  928. if n < 0 {
  929. n = 0
  930. }
  931. if n > 30 {
  932. n = 30
  933. }
  934. var d time.Duration
  935. if x, err := rand.Int(rand.Reader, big.NewInt(1000)); err == nil {
  936. d = time.Duration(x.Int64()) * time.Millisecond
  937. }
  938. d += time.Duration(1<<uint(n)) * time.Second
  939. if d > max {
  940. return max
  941. }
  942. return d
  943. }
  944. // keyAuth generates a key authorization string for a given token.
  945. func keyAuth(pub crypto.PublicKey, token string) (string, error) {
  946. th, err := JWKThumbprint(pub)
  947. if err != nil {
  948. return "", err
  949. }
  950. return fmt.Sprintf("%s.%s", token, th), nil
  951. }
  952. // tlsChallengeCert creates a temporary certificate for TLS-SNI challenges
  953. // with the given SANs and auto-generated public/private key pair.
  954. // To create a cert with a custom key pair, specify WithKey option.
  955. func tlsChallengeCert(san []string, opt []CertOption) (tls.Certificate, error) {
  956. var (
  957. key crypto.Signer
  958. tmpl *x509.Certificate
  959. )
  960. for _, o := range opt {
  961. switch o := o.(type) {
  962. case *certOptKey:
  963. if key != nil {
  964. return tls.Certificate{}, errors.New("acme: duplicate key option")
  965. }
  966. key = o.key
  967. case *certOptTemplate:
  968. var t = *(*x509.Certificate)(o) // shallow copy is ok
  969. tmpl = &t
  970. default:
  971. // package's fault, if we let this happen:
  972. panic(fmt.Sprintf("unsupported option type %T", o))
  973. }
  974. }
  975. if key == nil {
  976. var err error
  977. if key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader); err != nil {
  978. return tls.Certificate{}, err
  979. }
  980. }
  981. if tmpl == nil {
  982. tmpl = &x509.Certificate{
  983. SerialNumber: big.NewInt(1),
  984. NotBefore: time.Now(),
  985. NotAfter: time.Now().Add(24 * time.Hour),
  986. BasicConstraintsValid: true,
  987. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
  988. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  989. }
  990. }
  991. tmpl.DNSNames = san
  992. der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, key.Public(), key)
  993. if err != nil {
  994. return tls.Certificate{}, err
  995. }
  996. return tls.Certificate{
  997. Certificate: [][]byte{der},
  998. PrivateKey: key,
  999. }, nil
  1000. }
  1001. // encodePEM returns b encoded as PEM with block of type typ.
  1002. func encodePEM(typ string, b []byte) []byte {
  1003. pb := &pem.Block{Type: typ, Bytes: b}
  1004. return pem.EncodeToMemory(pb)
  1005. }
  1006. // timeNow is useful for testing for fixed current time.
  1007. var timeNow = time.Now