acme.go 34 KB

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