acme.go 34 KB

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