You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

acme.go 35 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098
  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. dir, err := c.Discover(ctx)
  338. if err != nil {
  339. return nil, err
  340. }
  341. if dir.rfcCompliant() {
  342. return c.registerRFC(ctx, acct, prompt)
  343. }
  344. // Legacy ACME draft registration flow.
  345. a, err := c.doReg(ctx, dir.RegURL, "new-reg", acct)
  346. if err != nil {
  347. return nil, err
  348. }
  349. var accept bool
  350. if a.CurrentTerms != "" && a.CurrentTerms != a.AgreedTerms {
  351. accept = prompt(a.CurrentTerms)
  352. }
  353. if accept {
  354. a.AgreedTerms = a.CurrentTerms
  355. a, err = c.UpdateReg(ctx, a)
  356. }
  357. return a, err
  358. }
  359. // GetReg retrieves an existing account associated with c.Key.
  360. //
  361. // The url argument is an Account URI used with pre-RFC 8555 CAs.
  362. // It is ignored when interfacing with an RFC-compliant CA.
  363. func (c *Client) GetReg(ctx context.Context, url string) (*Account, error) {
  364. dir, err := c.Discover(ctx)
  365. if err != nil {
  366. return nil, err
  367. }
  368. if dir.rfcCompliant() {
  369. return c.getRegRFC(ctx)
  370. }
  371. // Legacy CA.
  372. a, err := c.doReg(ctx, url, "reg", nil)
  373. if err != nil {
  374. return nil, err
  375. }
  376. a.URI = url
  377. return a, nil
  378. }
  379. // UpdateReg updates an existing registration.
  380. // It returns an updated account copy. The provided account is not modified.
  381. //
  382. // When interfacing with RFC-compliant CAs, a.URI is ignored and the account URL
  383. // associated with c.Key is used instead.
  384. func (c *Client) UpdateReg(ctx context.Context, acct *Account) (*Account, error) {
  385. dir, err := c.Discover(ctx)
  386. if err != nil {
  387. return nil, err
  388. }
  389. if dir.rfcCompliant() {
  390. return c.updateRegRFC(ctx, acct)
  391. }
  392. // Legacy CA.
  393. uri := acct.URI
  394. a, err := c.doReg(ctx, uri, "reg", acct)
  395. if err != nil {
  396. return nil, err
  397. }
  398. a.URI = uri
  399. return a, nil
  400. }
  401. // Authorize performs the initial step in the pre-authorization flow,
  402. // as opposed to order-based flow.
  403. // The caller will then need to choose from and perform a set of returned
  404. // challenges using c.Accept in order to successfully complete authorization.
  405. //
  406. // Once complete, the caller can use AuthorizeOrder which the CA
  407. // should provision with the already satisfied authorization.
  408. // For pre-RFC CAs, the caller can proceed directly to requesting a certificate
  409. // using CreateCert method.
  410. //
  411. // If an authorization has been previously granted, the CA may return
  412. // a valid authorization which has its Status field set to StatusValid.
  413. //
  414. // More about pre-authorization can be found at
  415. // https://tools.ietf.org/html/rfc8555#section-7.4.1.
  416. func (c *Client) Authorize(ctx context.Context, domain string) (*Authorization, error) {
  417. return c.authorize(ctx, "dns", domain)
  418. }
  419. // AuthorizeIP is the same as Authorize but requests IP address authorization.
  420. // Clients which successfully obtain such authorization may request to issue
  421. // a certificate for IP addresses.
  422. //
  423. // See the ACME spec extension for more details about IP address identifiers:
  424. // https://tools.ietf.org/html/draft-ietf-acme-ip.
  425. func (c *Client) AuthorizeIP(ctx context.Context, ipaddr string) (*Authorization, error) {
  426. return c.authorize(ctx, "ip", ipaddr)
  427. }
  428. func (c *Client) authorize(ctx context.Context, typ, val string) (*Authorization, error) {
  429. if _, err := c.Discover(ctx); err != nil {
  430. return nil, err
  431. }
  432. type authzID struct {
  433. Type string `json:"type"`
  434. Value string `json:"value"`
  435. }
  436. req := struct {
  437. Resource string `json:"resource"`
  438. Identifier authzID `json:"identifier"`
  439. }{
  440. Resource: "new-authz",
  441. Identifier: authzID{Type: typ, Value: val},
  442. }
  443. res, err := c.post(ctx, nil, c.dir.AuthzURL, req, wantStatus(http.StatusCreated))
  444. if err != nil {
  445. return nil, err
  446. }
  447. defer res.Body.Close()
  448. var v wireAuthz
  449. if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
  450. return nil, fmt.Errorf("acme: invalid response: %v", err)
  451. }
  452. if v.Status != StatusPending && v.Status != StatusValid {
  453. return nil, fmt.Errorf("acme: unexpected status: %s", v.Status)
  454. }
  455. return v.authorization(res.Header.Get("Location")), nil
  456. }
  457. // GetAuthorization retrieves an authorization identified by the given URL.
  458. //
  459. // If a caller needs to poll an authorization until its status is final,
  460. // see the WaitAuthorization method.
  461. func (c *Client) GetAuthorization(ctx context.Context, url string) (*Authorization, error) {
  462. dir, err := c.Discover(ctx)
  463. if err != nil {
  464. return nil, err
  465. }
  466. var res *http.Response
  467. if dir.rfcCompliant() {
  468. res, err = c.postAsGet(ctx, url, wantStatus(http.StatusOK))
  469. } else {
  470. res, err = c.get(ctx, url, wantStatus(http.StatusOK, http.StatusAccepted))
  471. }
  472. if err != nil {
  473. return nil, err
  474. }
  475. defer res.Body.Close()
  476. var v wireAuthz
  477. if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
  478. return nil, fmt.Errorf("acme: invalid response: %v", err)
  479. }
  480. return v.authorization(url), nil
  481. }
  482. // RevokeAuthorization relinquishes an existing authorization identified
  483. // by the given URL.
  484. // The url argument is an Authorization.URI value.
  485. //
  486. // If successful, the caller will be required to obtain a new authorization
  487. // using the Authorize or AuthorizeOrder methods before being able to request
  488. // a new certificate for the domain associated with the authorization.
  489. //
  490. // It does not revoke existing certificates.
  491. func (c *Client) RevokeAuthorization(ctx context.Context, url string) error {
  492. // Required for c.accountKID() when in RFC mode.
  493. if _, err := c.Discover(ctx); err != nil {
  494. return err
  495. }
  496. req := struct {
  497. Resource string `json:"resource"`
  498. Status string `json:"status"`
  499. Delete bool `json:"delete"`
  500. }{
  501. Resource: "authz",
  502. Status: "deactivated",
  503. Delete: true,
  504. }
  505. res, err := c.post(ctx, nil, url, req, wantStatus(http.StatusOK))
  506. if err != nil {
  507. return err
  508. }
  509. defer res.Body.Close()
  510. return nil
  511. }
  512. // WaitAuthorization polls an authorization at the given URL
  513. // until it is in one of the final states, StatusValid or StatusInvalid,
  514. // the ACME CA responded with a 4xx error code, or the context is done.
  515. //
  516. // It returns a non-nil Authorization only if its Status is StatusValid.
  517. // In all other cases WaitAuthorization returns an error.
  518. // If the Status is StatusInvalid, the returned error is of type *AuthorizationError.
  519. func (c *Client) WaitAuthorization(ctx context.Context, url string) (*Authorization, error) {
  520. // Required for c.accountKID() when in RFC mode.
  521. dir, err := c.Discover(ctx)
  522. if err != nil {
  523. return nil, err
  524. }
  525. getfn := c.postAsGet
  526. if !dir.rfcCompliant() {
  527. getfn = c.get
  528. }
  529. for {
  530. res, err := getfn(ctx, url, wantStatus(http.StatusOK, http.StatusAccepted))
  531. if err != nil {
  532. return nil, err
  533. }
  534. var raw wireAuthz
  535. err = json.NewDecoder(res.Body).Decode(&raw)
  536. res.Body.Close()
  537. switch {
  538. case err != nil:
  539. // Skip and retry.
  540. case raw.Status == StatusValid:
  541. return raw.authorization(url), nil
  542. case raw.Status == StatusInvalid:
  543. return nil, raw.error(url)
  544. }
  545. // Exponential backoff is implemented in c.get above.
  546. // This is just to prevent continuously hitting the CA
  547. // while waiting for a final authorization status.
  548. d := retryAfter(res.Header.Get("Retry-After"))
  549. if d == 0 {
  550. // Given that the fastest challenges TLS-SNI and HTTP-01
  551. // require a CA to make at least 1 network round trip
  552. // and most likely persist a challenge state,
  553. // this default delay seems reasonable.
  554. d = time.Second
  555. }
  556. t := time.NewTimer(d)
  557. select {
  558. case <-ctx.Done():
  559. t.Stop()
  560. return nil, ctx.Err()
  561. case <-t.C:
  562. // Retry.
  563. }
  564. }
  565. }
  566. // GetChallenge retrieves the current status of an challenge.
  567. //
  568. // A client typically polls a challenge status using this method.
  569. func (c *Client) GetChallenge(ctx context.Context, url string) (*Challenge, error) {
  570. // Required for c.accountKID() when in RFC mode.
  571. dir, err := c.Discover(ctx)
  572. if err != nil {
  573. return nil, err
  574. }
  575. getfn := c.postAsGet
  576. if !dir.rfcCompliant() {
  577. getfn = c.get
  578. }
  579. res, err := getfn(ctx, url, wantStatus(http.StatusOK, http.StatusAccepted))
  580. if err != nil {
  581. return nil, err
  582. }
  583. defer res.Body.Close()
  584. v := wireChallenge{URI: url}
  585. if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
  586. return nil, fmt.Errorf("acme: invalid response: %v", err)
  587. }
  588. return v.challenge(), nil
  589. }
  590. // Accept informs the server that the client accepts one of its challenges
  591. // previously obtained with c.Authorize.
  592. //
  593. // The server will then perform the validation asynchronously.
  594. func (c *Client) Accept(ctx context.Context, chal *Challenge) (*Challenge, error) {
  595. // Required for c.accountKID() when in RFC mode.
  596. dir, err := c.Discover(ctx)
  597. if err != nil {
  598. return nil, err
  599. }
  600. var req interface{} = json.RawMessage("{}") // RFC-compliant CA
  601. if !dir.rfcCompliant() {
  602. auth, err := keyAuth(c.Key.Public(), chal.Token)
  603. if err != nil {
  604. return nil, err
  605. }
  606. req = struct {
  607. Resource string `json:"resource"`
  608. Type string `json:"type"`
  609. Auth string `json:"keyAuthorization"`
  610. }{
  611. Resource: "challenge",
  612. Type: chal.Type,
  613. Auth: auth,
  614. }
  615. }
  616. res, err := c.post(ctx, nil, chal.URI, req, wantStatus(
  617. http.StatusOK, // according to the spec
  618. http.StatusAccepted, // Let's Encrypt: see https://goo.gl/WsJ7VT (acme-divergences.md)
  619. ))
  620. if err != nil {
  621. return nil, err
  622. }
  623. defer res.Body.Close()
  624. var v wireChallenge
  625. if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
  626. return nil, fmt.Errorf("acme: invalid response: %v", err)
  627. }
  628. return v.challenge(), nil
  629. }
  630. // DNS01ChallengeRecord returns a DNS record value for a dns-01 challenge response.
  631. // A TXT record containing the returned value must be provisioned under
  632. // "_acme-challenge" name of the domain being validated.
  633. //
  634. // The token argument is a Challenge.Token value.
  635. func (c *Client) DNS01ChallengeRecord(token string) (string, error) {
  636. ka, err := keyAuth(c.Key.Public(), token)
  637. if err != nil {
  638. return "", err
  639. }
  640. b := sha256.Sum256([]byte(ka))
  641. return base64.RawURLEncoding.EncodeToString(b[:]), nil
  642. }
  643. // HTTP01ChallengeResponse returns the response for an http-01 challenge.
  644. // Servers should respond with the value to HTTP requests at the URL path
  645. // provided by HTTP01ChallengePath to validate the challenge and prove control
  646. // over a domain name.
  647. //
  648. // The token argument is a Challenge.Token value.
  649. func (c *Client) HTTP01ChallengeResponse(token string) (string, error) {
  650. return keyAuth(c.Key.Public(), token)
  651. }
  652. // HTTP01ChallengePath returns the URL path at which the response for an http-01 challenge
  653. // should be provided by the servers.
  654. // The response value can be obtained with HTTP01ChallengeResponse.
  655. //
  656. // The token argument is a Challenge.Token value.
  657. func (c *Client) HTTP01ChallengePath(token string) string {
  658. return "/.well-known/acme-challenge/" + token
  659. }
  660. // TLSSNI01ChallengeCert creates a certificate for TLS-SNI-01 challenge response.
  661. //
  662. // Deprecated: This challenge type is unused in both draft-02 and RFC versions of ACME spec.
  663. func (c *Client) TLSSNI01ChallengeCert(token string, opt ...CertOption) (cert tls.Certificate, name string, err error) {
  664. ka, err := keyAuth(c.Key.Public(), token)
  665. if err != nil {
  666. return tls.Certificate{}, "", err
  667. }
  668. b := sha256.Sum256([]byte(ka))
  669. h := hex.EncodeToString(b[:])
  670. name = fmt.Sprintf("%s.%s.acme.invalid", h[:32], h[32:])
  671. cert, err = tlsChallengeCert([]string{name}, opt)
  672. if err != nil {
  673. return tls.Certificate{}, "", err
  674. }
  675. return cert, name, nil
  676. }
  677. // TLSSNI02ChallengeCert creates a certificate for TLS-SNI-02 challenge response.
  678. //
  679. // Deprecated: This challenge type is unused in both draft-02 and RFC versions of ACME spec.
  680. func (c *Client) TLSSNI02ChallengeCert(token string, opt ...CertOption) (cert tls.Certificate, name string, err error) {
  681. b := sha256.Sum256([]byte(token))
  682. h := hex.EncodeToString(b[:])
  683. sanA := fmt.Sprintf("%s.%s.token.acme.invalid", h[:32], h[32:])
  684. ka, err := keyAuth(c.Key.Public(), token)
  685. if err != nil {
  686. return tls.Certificate{}, "", err
  687. }
  688. b = sha256.Sum256([]byte(ka))
  689. h = hex.EncodeToString(b[:])
  690. sanB := fmt.Sprintf("%s.%s.ka.acme.invalid", h[:32], h[32:])
  691. cert, err = tlsChallengeCert([]string{sanA, sanB}, opt)
  692. if err != nil {
  693. return tls.Certificate{}, "", err
  694. }
  695. return cert, sanA, nil
  696. }
  697. // TLSALPN01ChallengeCert creates a certificate for TLS-ALPN-01 challenge response.
  698. // Servers can present the certificate to validate the challenge and prove control
  699. // over a domain name. For more details on TLS-ALPN-01 see
  700. // https://tools.ietf.org/html/draft-shoemaker-acme-tls-alpn-00#section-3
  701. //
  702. // The token argument is a Challenge.Token value.
  703. // If a WithKey option is provided, its private part signs the returned cert,
  704. // and the public part is used to specify the signee.
  705. // If no WithKey option is provided, a new ECDSA key is generated using P-256 curve.
  706. //
  707. // The returned certificate is valid for the next 24 hours and must be presented only when
  708. // the server name in the TLS ClientHello matches the domain, and the special acme-tls/1 ALPN protocol
  709. // has been specified.
  710. func (c *Client) TLSALPN01ChallengeCert(token, domain string, opt ...CertOption) (cert tls.Certificate, err error) {
  711. ka, err := keyAuth(c.Key.Public(), token)
  712. if err != nil {
  713. return tls.Certificate{}, err
  714. }
  715. shasum := sha256.Sum256([]byte(ka))
  716. extValue, err := asn1.Marshal(shasum[:])
  717. if err != nil {
  718. return tls.Certificate{}, err
  719. }
  720. acmeExtension := pkix.Extension{
  721. Id: idPeACMEIdentifier,
  722. Critical: true,
  723. Value: extValue,
  724. }
  725. tmpl := defaultTLSChallengeCertTemplate()
  726. var newOpt []CertOption
  727. for _, o := range opt {
  728. switch o := o.(type) {
  729. case *certOptTemplate:
  730. t := *(*x509.Certificate)(o) // shallow copy is ok
  731. tmpl = &t
  732. default:
  733. newOpt = append(newOpt, o)
  734. }
  735. }
  736. tmpl.ExtraExtensions = append(tmpl.ExtraExtensions, acmeExtension)
  737. newOpt = append(newOpt, WithTemplate(tmpl))
  738. return tlsChallengeCert([]string{domain}, newOpt)
  739. }
  740. // doReg sends all types of registration requests the old way (pre-RFC world).
  741. // The type of request is identified by typ argument, which is a "resource"
  742. // in the ACME spec terms.
  743. //
  744. // A non-nil acct argument indicates whether the intention is to mutate data
  745. // of the Account. Only Contact and Agreement of its fields are used
  746. // in such cases.
  747. func (c *Client) doReg(ctx context.Context, url string, typ string, acct *Account) (*Account, error) {
  748. req := struct {
  749. Resource string `json:"resource"`
  750. Contact []string `json:"contact,omitempty"`
  751. Agreement string `json:"agreement,omitempty"`
  752. }{
  753. Resource: typ,
  754. }
  755. if acct != nil {
  756. req.Contact = acct.Contact
  757. req.Agreement = acct.AgreedTerms
  758. }
  759. res, err := c.post(ctx, nil, url, req, wantStatus(
  760. http.StatusOK, // updates and deletes
  761. http.StatusCreated, // new account creation
  762. http.StatusAccepted, // Let's Encrypt divergent implementation
  763. ))
  764. if err != nil {
  765. return nil, err
  766. }
  767. defer res.Body.Close()
  768. var v struct {
  769. Contact []string
  770. Agreement string
  771. Authorizations string
  772. Certificates string
  773. }
  774. if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
  775. return nil, fmt.Errorf("acme: invalid response: %v", err)
  776. }
  777. var tos string
  778. if v := linkHeader(res.Header, "terms-of-service"); len(v) > 0 {
  779. tos = v[0]
  780. }
  781. var authz string
  782. if v := linkHeader(res.Header, "next"); len(v) > 0 {
  783. authz = v[0]
  784. }
  785. return &Account{
  786. URI: res.Header.Get("Location"),
  787. Contact: v.Contact,
  788. AgreedTerms: v.Agreement,
  789. CurrentTerms: tos,
  790. Authz: authz,
  791. Authorizations: v.Authorizations,
  792. Certificates: v.Certificates,
  793. }, nil
  794. }
  795. // popNonce returns a nonce value previously stored with c.addNonce
  796. // or fetches a fresh one from c.dir.NonceURL.
  797. // If NonceURL is empty, it first tries c.directoryURL() and, failing that,
  798. // the provided url.
  799. func (c *Client) popNonce(ctx context.Context, url string) (string, error) {
  800. c.noncesMu.Lock()
  801. defer c.noncesMu.Unlock()
  802. if len(c.nonces) == 0 {
  803. if c.dir != nil && c.dir.NonceURL != "" {
  804. return c.fetchNonce(ctx, c.dir.NonceURL)
  805. }
  806. dirURL := c.directoryURL()
  807. v, err := c.fetchNonce(ctx, dirURL)
  808. if err != nil && url != dirURL {
  809. v, err = c.fetchNonce(ctx, url)
  810. }
  811. return v, err
  812. }
  813. var nonce string
  814. for nonce = range c.nonces {
  815. delete(c.nonces, nonce)
  816. break
  817. }
  818. return nonce, nil
  819. }
  820. // clearNonces clears any stored nonces
  821. func (c *Client) clearNonces() {
  822. c.noncesMu.Lock()
  823. defer c.noncesMu.Unlock()
  824. c.nonces = make(map[string]struct{})
  825. }
  826. // addNonce stores a nonce value found in h (if any) for future use.
  827. func (c *Client) addNonce(h http.Header) {
  828. v := nonceFromHeader(h)
  829. if v == "" {
  830. return
  831. }
  832. c.noncesMu.Lock()
  833. defer c.noncesMu.Unlock()
  834. if len(c.nonces) >= maxNonces {
  835. return
  836. }
  837. if c.nonces == nil {
  838. c.nonces = make(map[string]struct{})
  839. }
  840. c.nonces[v] = struct{}{}
  841. }
  842. func (c *Client) fetchNonce(ctx context.Context, url string) (string, error) {
  843. r, err := http.NewRequest("HEAD", url, nil)
  844. if err != nil {
  845. return "", err
  846. }
  847. resp, err := c.doNoRetry(ctx, r)
  848. if err != nil {
  849. return "", err
  850. }
  851. defer resp.Body.Close()
  852. nonce := nonceFromHeader(resp.Header)
  853. if nonce == "" {
  854. if resp.StatusCode > 299 {
  855. return "", responseError(resp)
  856. }
  857. return "", errors.New("acme: nonce not found")
  858. }
  859. return nonce, nil
  860. }
  861. func nonceFromHeader(h http.Header) string {
  862. return h.Get("Replay-Nonce")
  863. }
  864. func (c *Client) responseCert(ctx context.Context, res *http.Response, bundle bool) ([][]byte, error) {
  865. b, err := ioutil.ReadAll(io.LimitReader(res.Body, maxCertSize+1))
  866. if err != nil {
  867. return nil, fmt.Errorf("acme: response stream: %v", err)
  868. }
  869. if len(b) > maxCertSize {
  870. return nil, errors.New("acme: certificate is too big")
  871. }
  872. cert := [][]byte{b}
  873. if !bundle {
  874. return cert, nil
  875. }
  876. // Append CA chain cert(s).
  877. // At least one is required according to the spec:
  878. // https://tools.ietf.org/html/draft-ietf-acme-acme-03#section-6.3.1
  879. up := linkHeader(res.Header, "up")
  880. if len(up) == 0 {
  881. return nil, errors.New("acme: rel=up link not found")
  882. }
  883. if len(up) > maxChainLen {
  884. return nil, errors.New("acme: rel=up link is too large")
  885. }
  886. for _, url := range up {
  887. cc, err := c.chainCert(ctx, url, 0)
  888. if err != nil {
  889. return nil, err
  890. }
  891. cert = append(cert, cc...)
  892. }
  893. return cert, nil
  894. }
  895. // chainCert fetches CA certificate chain recursively by following "up" links.
  896. // Each recursive call increments the depth by 1, resulting in an error
  897. // if the recursion level reaches maxChainLen.
  898. //
  899. // First chainCert call starts with depth of 0.
  900. func (c *Client) chainCert(ctx context.Context, url string, depth int) ([][]byte, error) {
  901. if depth >= maxChainLen {
  902. return nil, errors.New("acme: certificate chain is too deep")
  903. }
  904. res, err := c.get(ctx, url, wantStatus(http.StatusOK))
  905. if err != nil {
  906. return nil, err
  907. }
  908. defer res.Body.Close()
  909. b, err := ioutil.ReadAll(io.LimitReader(res.Body, maxCertSize+1))
  910. if err != nil {
  911. return nil, err
  912. }
  913. if len(b) > maxCertSize {
  914. return nil, errors.New("acme: certificate is too big")
  915. }
  916. chain := [][]byte{b}
  917. uplink := linkHeader(res.Header, "up")
  918. if len(uplink) > maxChainLen {
  919. return nil, errors.New("acme: certificate chain is too large")
  920. }
  921. for _, up := range uplink {
  922. cc, err := c.chainCert(ctx, up, depth+1)
  923. if err != nil {
  924. return nil, err
  925. }
  926. chain = append(chain, cc...)
  927. }
  928. return chain, nil
  929. }
  930. // linkHeader returns URI-Reference values of all Link headers
  931. // with relation-type rel.
  932. // See https://tools.ietf.org/html/rfc5988#section-5 for details.
  933. func linkHeader(h http.Header, rel string) []string {
  934. var links []string
  935. for _, v := range h["Link"] {
  936. parts := strings.Split(v, ";")
  937. for _, p := range parts {
  938. p = strings.TrimSpace(p)
  939. if !strings.HasPrefix(p, "rel=") {
  940. continue
  941. }
  942. if v := strings.Trim(p[4:], `"`); v == rel {
  943. links = append(links, strings.Trim(parts[0], "<>"))
  944. }
  945. }
  946. }
  947. return links
  948. }
  949. // keyAuth generates a key authorization string for a given token.
  950. func keyAuth(pub crypto.PublicKey, token string) (string, error) {
  951. th, err := JWKThumbprint(pub)
  952. if err != nil {
  953. return "", err
  954. }
  955. return fmt.Sprintf("%s.%s", token, th), nil
  956. }
  957. // defaultTLSChallengeCertTemplate is a template used to create challenge certs for TLS challenges.
  958. func defaultTLSChallengeCertTemplate() *x509.Certificate {
  959. return &x509.Certificate{
  960. SerialNumber: big.NewInt(1),
  961. NotBefore: time.Now(),
  962. NotAfter: time.Now().Add(24 * time.Hour),
  963. BasicConstraintsValid: true,
  964. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
  965. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  966. }
  967. }
  968. // tlsChallengeCert creates a temporary certificate for TLS-SNI challenges
  969. // with the given SANs and auto-generated public/private key pair.
  970. // The Subject Common Name is set to the first SAN to aid debugging.
  971. // To create a cert with a custom key pair, specify WithKey option.
  972. func tlsChallengeCert(san []string, opt []CertOption) (tls.Certificate, error) {
  973. var key crypto.Signer
  974. tmpl := defaultTLSChallengeCertTemplate()
  975. for _, o := range opt {
  976. switch o := o.(type) {
  977. case *certOptKey:
  978. if key != nil {
  979. return tls.Certificate{}, errors.New("acme: duplicate key option")
  980. }
  981. key = o.key
  982. case *certOptTemplate:
  983. t := *(*x509.Certificate)(o) // shallow copy is ok
  984. tmpl = &t
  985. default:
  986. // package's fault, if we let this happen:
  987. panic(fmt.Sprintf("unsupported option type %T", o))
  988. }
  989. }
  990. if key == nil {
  991. var err error
  992. if key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader); err != nil {
  993. return tls.Certificate{}, err
  994. }
  995. }
  996. tmpl.DNSNames = san
  997. if len(san) > 0 {
  998. tmpl.Subject.CommonName = san[0]
  999. }
  1000. der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, key.Public(), key)
  1001. if err != nil {
  1002. return tls.Certificate{}, err
  1003. }
  1004. return tls.Certificate{
  1005. Certificate: [][]byte{der},
  1006. PrivateKey: key,
  1007. }, nil
  1008. }
  1009. // encodePEM returns b encoded as PEM with block of type typ.
  1010. func encodePEM(typ string, b []byte) []byte {
  1011. pb := &pem.Block{Type: typ, Bytes: b}
  1012. return pem.EncodeToMemory(pb)
  1013. }
  1014. // timeNow is useful for testing for fixed current time.
  1015. var timeNow = time.Now