autocert.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973
  1. // Copyright 2016 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 autocert provides automatic access to certificates from Let's Encrypt
  5. // and any other ACME-based CA.
  6. //
  7. // This package is a work in progress and makes no API stability promises.
  8. package autocert
  9. import (
  10. "bytes"
  11. "context"
  12. "crypto"
  13. "crypto/ecdsa"
  14. "crypto/elliptic"
  15. "crypto/rand"
  16. "crypto/rsa"
  17. "crypto/tls"
  18. "crypto/x509"
  19. "crypto/x509/pkix"
  20. "encoding/pem"
  21. "errors"
  22. "fmt"
  23. "io"
  24. mathrand "math/rand"
  25. "net"
  26. "net/http"
  27. "path"
  28. "strconv"
  29. "strings"
  30. "sync"
  31. "time"
  32. "golang.org/x/crypto/acme"
  33. )
  34. // createCertRetryAfter is how much time to wait before removing a failed state
  35. // entry due to an unsuccessful createCert call.
  36. // This is a variable instead of a const for testing.
  37. // TODO: Consider making it configurable or an exp backoff?
  38. var createCertRetryAfter = time.Minute
  39. // pseudoRand is safe for concurrent use.
  40. var pseudoRand *lockedMathRand
  41. func init() {
  42. src := mathrand.NewSource(timeNow().UnixNano())
  43. pseudoRand = &lockedMathRand{rnd: mathrand.New(src)}
  44. }
  45. // AcceptTOS is a Manager.Prompt function that always returns true to
  46. // indicate acceptance of the CA's Terms of Service during account
  47. // registration.
  48. func AcceptTOS(tosURL string) bool { return true }
  49. // HostPolicy specifies which host names the Manager is allowed to respond to.
  50. // It returns a non-nil error if the host should be rejected.
  51. // The returned error is accessible via tls.Conn.Handshake and its callers.
  52. // See Manager's HostPolicy field and GetCertificate method docs for more details.
  53. type HostPolicy func(ctx context.Context, host string) error
  54. // HostWhitelist returns a policy where only the specified host names are allowed.
  55. // Only exact matches are currently supported. Subdomains, regexp or wildcard
  56. // will not match.
  57. func HostWhitelist(hosts ...string) HostPolicy {
  58. whitelist := make(map[string]bool, len(hosts))
  59. for _, h := range hosts {
  60. whitelist[h] = true
  61. }
  62. return func(_ context.Context, host string) error {
  63. if !whitelist[host] {
  64. return errors.New("acme/autocert: host not configured")
  65. }
  66. return nil
  67. }
  68. }
  69. // defaultHostPolicy is used when Manager.HostPolicy is not set.
  70. func defaultHostPolicy(context.Context, string) error {
  71. return nil
  72. }
  73. // Manager is a stateful certificate manager built on top of acme.Client.
  74. // It obtains and refreshes certificates automatically using "tls-sni-01",
  75. // "tls-sni-02" and "http-01" challenge types, as well as providing them
  76. // to a TLS server via tls.Config.
  77. //
  78. // You must specify a cache implementation, such as DirCache,
  79. // to reuse obtained certificates across program restarts.
  80. // Otherwise your server is very likely to exceed the certificate
  81. // issuer's request rate limits.
  82. type Manager struct {
  83. // Prompt specifies a callback function to conditionally accept a CA's Terms of Service (TOS).
  84. // The registration may require the caller to agree to the CA's TOS.
  85. // If so, Manager calls Prompt with a TOS URL provided by the CA. Prompt should report
  86. // whether the caller agrees to the terms.
  87. //
  88. // To always accept the terms, the callers can use AcceptTOS.
  89. Prompt func(tosURL string) bool
  90. // Cache optionally stores and retrieves previously-obtained certificates.
  91. // If nil, certs will only be cached for the lifetime of the Manager.
  92. //
  93. // Manager passes the Cache certificates data encoded in PEM, with private/public
  94. // parts combined in a single Cache.Put call, private key first.
  95. Cache Cache
  96. // HostPolicy controls which domains the Manager will attempt
  97. // to retrieve new certificates for. It does not affect cached certs.
  98. //
  99. // If non-nil, HostPolicy is called before requesting a new cert.
  100. // If nil, all hosts are currently allowed. This is not recommended,
  101. // as it opens a potential attack where clients connect to a server
  102. // by IP address and pretend to be asking for an incorrect host name.
  103. // Manager will attempt to obtain a certificate for that host, incorrectly,
  104. // eventually reaching the CA's rate limit for certificate requests
  105. // and making it impossible to obtain actual certificates.
  106. //
  107. // See GetCertificate for more details.
  108. HostPolicy HostPolicy
  109. // RenewBefore optionally specifies how early certificates should
  110. // be renewed before they expire.
  111. //
  112. // If zero, they're renewed 30 days before expiration.
  113. RenewBefore time.Duration
  114. // Client is used to perform low-level operations, such as account registration
  115. // and requesting new certificates.
  116. // If Client is nil, a zero-value acme.Client is used with acme.LetsEncryptURL
  117. // directory endpoint and a newly-generated ECDSA P-256 key.
  118. //
  119. // Mutating the field after the first call of GetCertificate method will have no effect.
  120. Client *acme.Client
  121. // Email optionally specifies a contact email address.
  122. // This is used by CAs, such as Let's Encrypt, to notify about problems
  123. // with issued certificates.
  124. //
  125. // If the Client's account key is already registered, Email is not used.
  126. Email string
  127. // ForceRSA makes the Manager generate certificates with 2048-bit RSA keys.
  128. //
  129. // If false, a default is used. Currently the default
  130. // is EC-based keys using the P-256 curve.
  131. ForceRSA bool
  132. clientMu sync.Mutex
  133. client *acme.Client // initialized by acmeClient method
  134. stateMu sync.Mutex
  135. state map[string]*certState // keyed by domain name
  136. // renewal tracks the set of domains currently running renewal timers.
  137. // It is keyed by domain name.
  138. renewalMu sync.Mutex
  139. renewal map[string]*domainRenewal
  140. // tokensMu guards the rest of the fields: tryHTTP01, certTokens and httpTokens.
  141. tokensMu sync.RWMutex
  142. // tryHTTP01 indicates whether the Manager should try "http-01" challenge type
  143. // during the authorization flow.
  144. tryHTTP01 bool
  145. // httpTokens contains response body values for http-01 challenges
  146. // and is keyed by the URL path at which a challenge response is expected
  147. // to be provisioned.
  148. // The entries are stored for the duration of the authorization flow.
  149. httpTokens map[string][]byte
  150. // certTokens contains temporary certificates for tls-sni challenges
  151. // and is keyed by token domain name, which matches server name of ClientHello.
  152. // Keys always have ".acme.invalid" suffix.
  153. // The entries are stored for the duration of the authorization flow.
  154. certTokens map[string]*tls.Certificate
  155. }
  156. // GetCertificate implements the tls.Config.GetCertificate hook.
  157. // It provides a TLS certificate for hello.ServerName host, including answering
  158. // *.acme.invalid (TLS-SNI) challenges. All other fields of hello are ignored.
  159. //
  160. // If m.HostPolicy is non-nil, GetCertificate calls the policy before requesting
  161. // a new cert. A non-nil error returned from m.HostPolicy halts TLS negotiation.
  162. // The error is propagated back to the caller of GetCertificate and is user-visible.
  163. // This does not affect cached certs. See HostPolicy field description for more details.
  164. func (m *Manager) GetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
  165. if m.Prompt == nil {
  166. return nil, errors.New("acme/autocert: Manager.Prompt not set")
  167. }
  168. name := hello.ServerName
  169. if name == "" {
  170. return nil, errors.New("acme/autocert: missing server name")
  171. }
  172. if !strings.Contains(strings.Trim(name, "."), ".") {
  173. return nil, errors.New("acme/autocert: server name component count invalid")
  174. }
  175. if strings.ContainsAny(name, `/\`) {
  176. return nil, errors.New("acme/autocert: server name contains invalid character")
  177. }
  178. // In the worst-case scenario, the timeout needs to account for caching, host policy,
  179. // domain ownership verification and certificate issuance.
  180. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
  181. defer cancel()
  182. // check whether this is a token cert requested for TLS-SNI challenge
  183. if strings.HasSuffix(name, ".acme.invalid") {
  184. m.tokensMu.RLock()
  185. defer m.tokensMu.RUnlock()
  186. if cert := m.certTokens[name]; cert != nil {
  187. return cert, nil
  188. }
  189. if cert, err := m.cacheGet(ctx, name); err == nil {
  190. return cert, nil
  191. }
  192. // TODO: cache error results?
  193. return nil, fmt.Errorf("acme/autocert: no token cert for %q", name)
  194. }
  195. // regular domain
  196. name = strings.TrimSuffix(name, ".") // golang.org/issue/18114
  197. cert, err := m.cert(ctx, name)
  198. if err == nil {
  199. return cert, nil
  200. }
  201. if err != ErrCacheMiss {
  202. return nil, err
  203. }
  204. // first-time
  205. if err := m.hostPolicy()(ctx, name); err != nil {
  206. return nil, err
  207. }
  208. cert, err = m.createCert(ctx, name)
  209. if err != nil {
  210. return nil, err
  211. }
  212. m.cachePut(ctx, name, cert)
  213. return cert, nil
  214. }
  215. // HTTPHandler configures the Manager to provision ACME "http-01" challenge responses.
  216. // It returns an http.Handler that responds to the challenges and must be
  217. // running on port 80. If it receives a request that is not an ACME challenge,
  218. // it delegates the request to the optional fallback handler.
  219. //
  220. // If fallback is nil, the returned handler redirects all GET and HEAD requests
  221. // to the default TLS port 443 with 302 Found status code, preserving the original
  222. // request path and query. It responds with 400 Bad Request to all other HTTP methods.
  223. // The fallback is not protected by the optional HostPolicy.
  224. //
  225. // Because the fallback handler is run with unencrypted port 80 requests,
  226. // the fallback should not serve TLS-only requests.
  227. //
  228. // If HTTPHandler is never called, the Manager will only use TLS SNI
  229. // challenges for domain verification.
  230. func (m *Manager) HTTPHandler(fallback http.Handler) http.Handler {
  231. m.tokensMu.Lock()
  232. defer m.tokensMu.Unlock()
  233. m.tryHTTP01 = true
  234. if fallback == nil {
  235. fallback = http.HandlerFunc(handleHTTPRedirect)
  236. }
  237. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  238. if !strings.HasPrefix(r.URL.Path, "/.well-known/acme-challenge/") {
  239. fallback.ServeHTTP(w, r)
  240. return
  241. }
  242. // A reasonable context timeout for cache and host policy only,
  243. // because we don't wait for a new certificate issuance here.
  244. ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
  245. defer cancel()
  246. if err := m.hostPolicy()(ctx, r.Host); err != nil {
  247. http.Error(w, err.Error(), http.StatusForbidden)
  248. return
  249. }
  250. data, err := m.httpToken(ctx, r.URL.Path)
  251. if err != nil {
  252. http.Error(w, err.Error(), http.StatusNotFound)
  253. return
  254. }
  255. w.Write(data)
  256. })
  257. }
  258. func handleHTTPRedirect(w http.ResponseWriter, r *http.Request) {
  259. if r.Method != "GET" && r.Method != "HEAD" {
  260. http.Error(w, "Use HTTPS", http.StatusBadRequest)
  261. return
  262. }
  263. target := "https://" + stripPort(r.Host) + r.URL.RequestURI()
  264. http.Redirect(w, r, target, http.StatusFound)
  265. }
  266. func stripPort(hostport string) string {
  267. host, _, err := net.SplitHostPort(hostport)
  268. if err != nil {
  269. return hostport
  270. }
  271. return net.JoinHostPort(host, "443")
  272. }
  273. // cert returns an existing certificate either from m.state or cache.
  274. // If a certificate is found in cache but not in m.state, the latter will be filled
  275. // with the cached value.
  276. func (m *Manager) cert(ctx context.Context, name string) (*tls.Certificate, error) {
  277. m.stateMu.Lock()
  278. if s, ok := m.state[name]; ok {
  279. m.stateMu.Unlock()
  280. s.RLock()
  281. defer s.RUnlock()
  282. return s.tlscert()
  283. }
  284. defer m.stateMu.Unlock()
  285. cert, err := m.cacheGet(ctx, name)
  286. if err != nil {
  287. return nil, err
  288. }
  289. signer, ok := cert.PrivateKey.(crypto.Signer)
  290. if !ok {
  291. return nil, errors.New("acme/autocert: private key cannot sign")
  292. }
  293. if m.state == nil {
  294. m.state = make(map[string]*certState)
  295. }
  296. s := &certState{
  297. key: signer,
  298. cert: cert.Certificate,
  299. leaf: cert.Leaf,
  300. }
  301. m.state[name] = s
  302. go m.renew(name, s.key, s.leaf.NotAfter)
  303. return cert, nil
  304. }
  305. // cacheGet always returns a valid certificate, or an error otherwise.
  306. // If a cached certficate exists but is not valid, ErrCacheMiss is returned.
  307. func (m *Manager) cacheGet(ctx context.Context, domain string) (*tls.Certificate, error) {
  308. if m.Cache == nil {
  309. return nil, ErrCacheMiss
  310. }
  311. data, err := m.Cache.Get(ctx, domain)
  312. if err != nil {
  313. return nil, err
  314. }
  315. // private
  316. priv, pub := pem.Decode(data)
  317. if priv == nil || !strings.Contains(priv.Type, "PRIVATE") {
  318. return nil, ErrCacheMiss
  319. }
  320. privKey, err := parsePrivateKey(priv.Bytes)
  321. if err != nil {
  322. return nil, err
  323. }
  324. // public
  325. var pubDER [][]byte
  326. for len(pub) > 0 {
  327. var b *pem.Block
  328. b, pub = pem.Decode(pub)
  329. if b == nil {
  330. break
  331. }
  332. pubDER = append(pubDER, b.Bytes)
  333. }
  334. if len(pub) > 0 {
  335. // Leftover content not consumed by pem.Decode. Corrupt. Ignore.
  336. return nil, ErrCacheMiss
  337. }
  338. // verify and create TLS cert
  339. leaf, err := validCert(domain, pubDER, privKey)
  340. if err != nil {
  341. return nil, ErrCacheMiss
  342. }
  343. tlscert := &tls.Certificate{
  344. Certificate: pubDER,
  345. PrivateKey: privKey,
  346. Leaf: leaf,
  347. }
  348. return tlscert, nil
  349. }
  350. func (m *Manager) cachePut(ctx context.Context, domain string, tlscert *tls.Certificate) error {
  351. if m.Cache == nil {
  352. return nil
  353. }
  354. // contains PEM-encoded data
  355. var buf bytes.Buffer
  356. // private
  357. switch key := tlscert.PrivateKey.(type) {
  358. case *ecdsa.PrivateKey:
  359. if err := encodeECDSAKey(&buf, key); err != nil {
  360. return err
  361. }
  362. case *rsa.PrivateKey:
  363. b := x509.MarshalPKCS1PrivateKey(key)
  364. pb := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: b}
  365. if err := pem.Encode(&buf, pb); err != nil {
  366. return err
  367. }
  368. default:
  369. return errors.New("acme/autocert: unknown private key type")
  370. }
  371. // public
  372. for _, b := range tlscert.Certificate {
  373. pb := &pem.Block{Type: "CERTIFICATE", Bytes: b}
  374. if err := pem.Encode(&buf, pb); err != nil {
  375. return err
  376. }
  377. }
  378. return m.Cache.Put(ctx, domain, buf.Bytes())
  379. }
  380. func encodeECDSAKey(w io.Writer, key *ecdsa.PrivateKey) error {
  381. b, err := x509.MarshalECPrivateKey(key)
  382. if err != nil {
  383. return err
  384. }
  385. pb := &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}
  386. return pem.Encode(w, pb)
  387. }
  388. // createCert starts the domain ownership verification and returns a certificate
  389. // for that domain upon success.
  390. //
  391. // If the domain is already being verified, it waits for the existing verification to complete.
  392. // Either way, createCert blocks for the duration of the whole process.
  393. func (m *Manager) createCert(ctx context.Context, domain string) (*tls.Certificate, error) {
  394. // TODO: maybe rewrite this whole piece using sync.Once
  395. state, err := m.certState(domain)
  396. if err != nil {
  397. return nil, err
  398. }
  399. // state may exist if another goroutine is already working on it
  400. // in which case just wait for it to finish
  401. if !state.locked {
  402. state.RLock()
  403. defer state.RUnlock()
  404. return state.tlscert()
  405. }
  406. // We are the first; state is locked.
  407. // Unblock the readers when domain ownership is verified
  408. // and we got the cert or the process failed.
  409. defer state.Unlock()
  410. state.locked = false
  411. der, leaf, err := m.authorizedCert(ctx, state.key, domain)
  412. if err != nil {
  413. // Remove the failed state after some time,
  414. // making the manager call createCert again on the following TLS hello.
  415. time.AfterFunc(createCertRetryAfter, func() {
  416. defer testDidRemoveState(domain)
  417. m.stateMu.Lock()
  418. defer m.stateMu.Unlock()
  419. // Verify the state hasn't changed and it's still invalid
  420. // before deleting.
  421. s, ok := m.state[domain]
  422. if !ok {
  423. return
  424. }
  425. if _, err := validCert(domain, s.cert, s.key); err == nil {
  426. return
  427. }
  428. delete(m.state, domain)
  429. })
  430. return nil, err
  431. }
  432. state.cert = der
  433. state.leaf = leaf
  434. go m.renew(domain, state.key, state.leaf.NotAfter)
  435. return state.tlscert()
  436. }
  437. // certState returns a new or existing certState.
  438. // If a new certState is returned, state.exist is false and the state is locked.
  439. // The returned error is non-nil only in the case where a new state could not be created.
  440. func (m *Manager) certState(domain string) (*certState, error) {
  441. m.stateMu.Lock()
  442. defer m.stateMu.Unlock()
  443. if m.state == nil {
  444. m.state = make(map[string]*certState)
  445. }
  446. // existing state
  447. if state, ok := m.state[domain]; ok {
  448. return state, nil
  449. }
  450. // new locked state
  451. var (
  452. err error
  453. key crypto.Signer
  454. )
  455. if m.ForceRSA {
  456. key, err = rsa.GenerateKey(rand.Reader, 2048)
  457. } else {
  458. key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  459. }
  460. if err != nil {
  461. return nil, err
  462. }
  463. state := &certState{
  464. key: key,
  465. locked: true,
  466. }
  467. state.Lock() // will be unlocked by m.certState caller
  468. m.state[domain] = state
  469. return state, nil
  470. }
  471. // authorizedCert starts the domain ownership verification process and requests a new cert upon success.
  472. // The key argument is the certificate private key.
  473. func (m *Manager) authorizedCert(ctx context.Context, key crypto.Signer, domain string) (der [][]byte, leaf *x509.Certificate, err error) {
  474. client, err := m.acmeClient(ctx)
  475. if err != nil {
  476. return nil, nil, err
  477. }
  478. if err := m.verify(ctx, client, domain); err != nil {
  479. return nil, nil, err
  480. }
  481. csr, err := certRequest(key, domain)
  482. if err != nil {
  483. return nil, nil, err
  484. }
  485. der, _, err = client.CreateCert(ctx, csr, 0, true)
  486. if err != nil {
  487. return nil, nil, err
  488. }
  489. leaf, err = validCert(domain, der, key)
  490. if err != nil {
  491. return nil, nil, err
  492. }
  493. return der, leaf, nil
  494. }
  495. // verify runs the identifier (domain) authorization flow
  496. // using each applicable ACME challenge type.
  497. func (m *Manager) verify(ctx context.Context, client *acme.Client, domain string) error {
  498. // The list of challenge types we'll try to fulfill
  499. // in this specific order.
  500. challengeTypes := []string{"tls-sni-02", "tls-sni-01"}
  501. m.tokensMu.RLock()
  502. if m.tryHTTP01 {
  503. challengeTypes = append(challengeTypes, "http-01")
  504. }
  505. m.tokensMu.RUnlock()
  506. var nextTyp int // challengeType index of the next challenge type to try
  507. for {
  508. // Start domain authorization and get the challenge.
  509. authz, err := client.Authorize(ctx, domain)
  510. if err != nil {
  511. return err
  512. }
  513. // No point in accepting challenges if the authorization status
  514. // is in a final state.
  515. switch authz.Status {
  516. case acme.StatusValid:
  517. return nil // already authorized
  518. case acme.StatusInvalid:
  519. return fmt.Errorf("acme/autocert: invalid authorization %q", authz.URI)
  520. }
  521. // Pick the next preferred challenge.
  522. var chal *acme.Challenge
  523. for chal == nil && nextTyp < len(challengeTypes) {
  524. chal = pickChallenge(challengeTypes[nextTyp], authz.Challenges)
  525. nextTyp++
  526. }
  527. if chal == nil {
  528. return fmt.Errorf("acme/autocert: unable to authorize %q; tried %q", domain, challengeTypes)
  529. }
  530. cleanup, err := m.fulfill(ctx, client, chal)
  531. if err != nil {
  532. continue
  533. }
  534. defer cleanup()
  535. if _, err := client.Accept(ctx, chal); err != nil {
  536. continue
  537. }
  538. // A challenge is fulfilled and accepted: wait for the CA to validate.
  539. if _, err := client.WaitAuthorization(ctx, authz.URI); err == nil {
  540. return nil
  541. }
  542. }
  543. }
  544. // fulfill provisions a response to the challenge chal.
  545. // The cleanup is non-nil only if provisioning succeeded.
  546. func (m *Manager) fulfill(ctx context.Context, client *acme.Client, chal *acme.Challenge) (cleanup func(), err error) {
  547. switch chal.Type {
  548. case "tls-sni-01":
  549. cert, name, err := client.TLSSNI01ChallengeCert(chal.Token)
  550. if err != nil {
  551. return nil, err
  552. }
  553. m.putCertToken(ctx, name, &cert)
  554. return func() { go m.deleteCertToken(name) }, nil
  555. case "tls-sni-02":
  556. cert, name, err := client.TLSSNI02ChallengeCert(chal.Token)
  557. if err != nil {
  558. return nil, err
  559. }
  560. m.putCertToken(ctx, name, &cert)
  561. return func() { go m.deleteCertToken(name) }, nil
  562. case "http-01":
  563. resp, err := client.HTTP01ChallengeResponse(chal.Token)
  564. if err != nil {
  565. return nil, err
  566. }
  567. p := client.HTTP01ChallengePath(chal.Token)
  568. m.putHTTPToken(ctx, p, resp)
  569. return func() { go m.deleteHTTPToken(p) }, nil
  570. }
  571. return nil, fmt.Errorf("acme/autocert: unknown challenge type %q", chal.Type)
  572. }
  573. func pickChallenge(typ string, chal []*acme.Challenge) *acme.Challenge {
  574. for _, c := range chal {
  575. if c.Type == typ {
  576. return c
  577. }
  578. }
  579. return nil
  580. }
  581. // putCertToken stores the cert under the named key in both m.certTokens map
  582. // and m.Cache.
  583. func (m *Manager) putCertToken(ctx context.Context, name string, cert *tls.Certificate) {
  584. m.tokensMu.Lock()
  585. defer m.tokensMu.Unlock()
  586. if m.certTokens == nil {
  587. m.certTokens = make(map[string]*tls.Certificate)
  588. }
  589. m.certTokens[name] = cert
  590. m.cachePut(ctx, name, cert)
  591. }
  592. // deleteCertToken removes the token certificate for the specified domain name
  593. // from both m.certTokens map and m.Cache.
  594. func (m *Manager) deleteCertToken(name string) {
  595. m.tokensMu.Lock()
  596. defer m.tokensMu.Unlock()
  597. delete(m.certTokens, name)
  598. if m.Cache != nil {
  599. m.Cache.Delete(context.Background(), name)
  600. }
  601. }
  602. // httpToken retrieves an existing http-01 token value from an in-memory map
  603. // or the optional cache.
  604. func (m *Manager) httpToken(ctx context.Context, tokenPath string) ([]byte, error) {
  605. m.tokensMu.RLock()
  606. defer m.tokensMu.RUnlock()
  607. if v, ok := m.httpTokens[tokenPath]; ok {
  608. return v, nil
  609. }
  610. if m.Cache == nil {
  611. return nil, fmt.Errorf("acme/autocert: no token at %q", tokenPath)
  612. }
  613. return m.Cache.Get(ctx, httpTokenCacheKey(tokenPath))
  614. }
  615. // putHTTPToken stores an http-01 token value using tokenPath as key
  616. // in both in-memory map and the optional Cache.
  617. //
  618. // It ignores any error returned from Cache.Put.
  619. func (m *Manager) putHTTPToken(ctx context.Context, tokenPath, val string) {
  620. m.tokensMu.Lock()
  621. defer m.tokensMu.Unlock()
  622. if m.httpTokens == nil {
  623. m.httpTokens = make(map[string][]byte)
  624. }
  625. b := []byte(val)
  626. m.httpTokens[tokenPath] = b
  627. if m.Cache != nil {
  628. m.Cache.Put(ctx, httpTokenCacheKey(tokenPath), b)
  629. }
  630. }
  631. // deleteHTTPToken removes an http-01 token value from both in-memory map
  632. // and the optional Cache, ignoring any error returned from the latter.
  633. //
  634. // If m.Cache is non-nil, it blocks until Cache.Delete returns without a timeout.
  635. func (m *Manager) deleteHTTPToken(tokenPath string) {
  636. m.tokensMu.Lock()
  637. defer m.tokensMu.Unlock()
  638. delete(m.httpTokens, tokenPath)
  639. if m.Cache != nil {
  640. m.Cache.Delete(context.Background(), httpTokenCacheKey(tokenPath))
  641. }
  642. }
  643. // httpTokenCacheKey returns a key at which an http-01 token value may be stored
  644. // in the Manager's optional Cache.
  645. func httpTokenCacheKey(tokenPath string) string {
  646. return "http-01-" + path.Base(tokenPath)
  647. }
  648. // renew starts a cert renewal timer loop, one per domain.
  649. //
  650. // The loop is scheduled in two cases:
  651. // - a cert was fetched from cache for the first time (wasn't in m.state)
  652. // - a new cert was created by m.createCert
  653. //
  654. // The key argument is a certificate private key.
  655. // The exp argument is the cert expiration time (NotAfter).
  656. func (m *Manager) renew(domain string, key crypto.Signer, exp time.Time) {
  657. m.renewalMu.Lock()
  658. defer m.renewalMu.Unlock()
  659. if m.renewal[domain] != nil {
  660. // another goroutine is already on it
  661. return
  662. }
  663. if m.renewal == nil {
  664. m.renewal = make(map[string]*domainRenewal)
  665. }
  666. dr := &domainRenewal{m: m, domain: domain, key: key}
  667. m.renewal[domain] = dr
  668. dr.start(exp)
  669. }
  670. // stopRenew stops all currently running cert renewal timers.
  671. // The timers are not restarted during the lifetime of the Manager.
  672. func (m *Manager) stopRenew() {
  673. m.renewalMu.Lock()
  674. defer m.renewalMu.Unlock()
  675. for name, dr := range m.renewal {
  676. delete(m.renewal, name)
  677. dr.stop()
  678. }
  679. }
  680. func (m *Manager) accountKey(ctx context.Context) (crypto.Signer, error) {
  681. const keyName = "acme_account.key"
  682. genKey := func() (*ecdsa.PrivateKey, error) {
  683. return ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  684. }
  685. if m.Cache == nil {
  686. return genKey()
  687. }
  688. data, err := m.Cache.Get(ctx, keyName)
  689. if err == ErrCacheMiss {
  690. key, err := genKey()
  691. if err != nil {
  692. return nil, err
  693. }
  694. var buf bytes.Buffer
  695. if err := encodeECDSAKey(&buf, key); err != nil {
  696. return nil, err
  697. }
  698. if err := m.Cache.Put(ctx, keyName, buf.Bytes()); err != nil {
  699. return nil, err
  700. }
  701. return key, nil
  702. }
  703. if err != nil {
  704. return nil, err
  705. }
  706. priv, _ := pem.Decode(data)
  707. if priv == nil || !strings.Contains(priv.Type, "PRIVATE") {
  708. return nil, errors.New("acme/autocert: invalid account key found in cache")
  709. }
  710. return parsePrivateKey(priv.Bytes)
  711. }
  712. func (m *Manager) acmeClient(ctx context.Context) (*acme.Client, error) {
  713. m.clientMu.Lock()
  714. defer m.clientMu.Unlock()
  715. if m.client != nil {
  716. return m.client, nil
  717. }
  718. client := m.Client
  719. if client == nil {
  720. client = &acme.Client{DirectoryURL: acme.LetsEncryptURL}
  721. }
  722. if client.Key == nil {
  723. var err error
  724. client.Key, err = m.accountKey(ctx)
  725. if err != nil {
  726. return nil, err
  727. }
  728. }
  729. var contact []string
  730. if m.Email != "" {
  731. contact = []string{"mailto:" + m.Email}
  732. }
  733. a := &acme.Account{Contact: contact}
  734. _, err := client.Register(ctx, a, m.Prompt)
  735. if ae, ok := err.(*acme.Error); err == nil || ok && ae.StatusCode == http.StatusConflict {
  736. // conflict indicates the key is already registered
  737. m.client = client
  738. err = nil
  739. }
  740. return m.client, err
  741. }
  742. func (m *Manager) hostPolicy() HostPolicy {
  743. if m.HostPolicy != nil {
  744. return m.HostPolicy
  745. }
  746. return defaultHostPolicy
  747. }
  748. func (m *Manager) renewBefore() time.Duration {
  749. if m.RenewBefore > renewJitter {
  750. return m.RenewBefore
  751. }
  752. return 720 * time.Hour // 30 days
  753. }
  754. // certState is ready when its mutex is unlocked for reading.
  755. type certState struct {
  756. sync.RWMutex
  757. locked bool // locked for read/write
  758. key crypto.Signer // private key for cert
  759. cert [][]byte // DER encoding
  760. leaf *x509.Certificate // parsed cert[0]; always non-nil if cert != nil
  761. }
  762. // tlscert creates a tls.Certificate from s.key and s.cert.
  763. // Callers should wrap it in s.RLock() and s.RUnlock().
  764. func (s *certState) tlscert() (*tls.Certificate, error) {
  765. if s.key == nil {
  766. return nil, errors.New("acme/autocert: missing signer")
  767. }
  768. if len(s.cert) == 0 {
  769. return nil, errors.New("acme/autocert: missing certificate")
  770. }
  771. return &tls.Certificate{
  772. PrivateKey: s.key,
  773. Certificate: s.cert,
  774. Leaf: s.leaf,
  775. }, nil
  776. }
  777. // certRequest creates a certificate request for the given common name cn
  778. // and optional SANs.
  779. func certRequest(key crypto.Signer, cn string, san ...string) ([]byte, error) {
  780. req := &x509.CertificateRequest{
  781. Subject: pkix.Name{CommonName: cn},
  782. DNSNames: san,
  783. }
  784. return x509.CreateCertificateRequest(rand.Reader, req, key)
  785. }
  786. // Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates
  787. // PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys.
  788. // OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.
  789. //
  790. // Inspired by parsePrivateKey in crypto/tls/tls.go.
  791. func parsePrivateKey(der []byte) (crypto.Signer, error) {
  792. if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
  793. return key, nil
  794. }
  795. if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
  796. switch key := key.(type) {
  797. case *rsa.PrivateKey:
  798. return key, nil
  799. case *ecdsa.PrivateKey:
  800. return key, nil
  801. default:
  802. return nil, errors.New("acme/autocert: unknown private key type in PKCS#8 wrapping")
  803. }
  804. }
  805. if key, err := x509.ParseECPrivateKey(der); err == nil {
  806. return key, nil
  807. }
  808. return nil, errors.New("acme/autocert: failed to parse private key")
  809. }
  810. // validCert parses a cert chain provided as der argument and verifies the leaf, der[0],
  811. // corresponds to the private key, as well as the domain match and expiration dates.
  812. // It doesn't do any revocation checking.
  813. //
  814. // The returned value is the verified leaf cert.
  815. func validCert(domain string, der [][]byte, key crypto.Signer) (leaf *x509.Certificate, err error) {
  816. // parse public part(s)
  817. var n int
  818. for _, b := range der {
  819. n += len(b)
  820. }
  821. pub := make([]byte, n)
  822. n = 0
  823. for _, b := range der {
  824. n += copy(pub[n:], b)
  825. }
  826. x509Cert, err := x509.ParseCertificates(pub)
  827. if len(x509Cert) == 0 {
  828. return nil, errors.New("acme/autocert: no public key found")
  829. }
  830. // verify the leaf is not expired and matches the domain name
  831. leaf = x509Cert[0]
  832. now := timeNow()
  833. if now.Before(leaf.NotBefore) {
  834. return nil, errors.New("acme/autocert: certificate is not valid yet")
  835. }
  836. if now.After(leaf.NotAfter) {
  837. return nil, errors.New("acme/autocert: expired certificate")
  838. }
  839. if err := leaf.VerifyHostname(domain); err != nil {
  840. return nil, err
  841. }
  842. // ensure the leaf corresponds to the private key
  843. switch pub := leaf.PublicKey.(type) {
  844. case *rsa.PublicKey:
  845. prv, ok := key.(*rsa.PrivateKey)
  846. if !ok {
  847. return nil, errors.New("acme/autocert: private key type does not match public key type")
  848. }
  849. if pub.N.Cmp(prv.N) != 0 {
  850. return nil, errors.New("acme/autocert: private key does not match public key")
  851. }
  852. case *ecdsa.PublicKey:
  853. prv, ok := key.(*ecdsa.PrivateKey)
  854. if !ok {
  855. return nil, errors.New("acme/autocert: private key type does not match public key type")
  856. }
  857. if pub.X.Cmp(prv.X) != 0 || pub.Y.Cmp(prv.Y) != 0 {
  858. return nil, errors.New("acme/autocert: private key does not match public key")
  859. }
  860. default:
  861. return nil, errors.New("acme/autocert: unknown public key algorithm")
  862. }
  863. return leaf, nil
  864. }
  865. func retryAfter(v string) time.Duration {
  866. if i, err := strconv.Atoi(v); err == nil {
  867. return time.Duration(i) * time.Second
  868. }
  869. if t, err := http.ParseTime(v); err == nil {
  870. return t.Sub(timeNow())
  871. }
  872. return time.Second
  873. }
  874. type lockedMathRand struct {
  875. sync.Mutex
  876. rnd *mathrand.Rand
  877. }
  878. func (r *lockedMathRand) int63n(max int64) int64 {
  879. r.Lock()
  880. n := r.rnd.Int63n(max)
  881. r.Unlock()
  882. return n
  883. }
  884. // For easier testing.
  885. var (
  886. timeNow = time.Now
  887. // Called when a state is removed.
  888. testDidRemoveState = func(domain string) {}
  889. )