autocert.go 28 KB

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