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

1093 lines
32 KiB

  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. // and other state. If nil, certs will only be cached for the lifetime of
  91. // the Manager. Multiple Managers can share the same Cache.
  92. //
  93. // Using a persistent Cache, such as DirCache, is strongly recommended.
  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. //
  116. // If Client is nil, a zero-value acme.Client is used with acme.LetsEncryptURL
  117. // as directory endpoint. If the Client.Key is nil, a new ECDSA P-256 key is
  118. // generated and, if Cache is not nil, stored in cache.
  119. //
  120. // Mutating the field after the first call of GetCertificate method will have no effect.
  121. Client *acme.Client
  122. // Email optionally specifies a contact email address.
  123. // This is used by CAs, such as Let's Encrypt, to notify about problems
  124. // with issued certificates.
  125. //
  126. // If the Client's account key is already registered, Email is not used.
  127. Email string
  128. // ForceRSA used to make the Manager generate RSA certificates. It is now ignored.
  129. //
  130. // Deprecated: the Manager will request the correct type of certificate based
  131. // on what each client supports.
  132. ForceRSA bool
  133. // ExtraExtensions are used when generating a new CSR (Certificate Request),
  134. // thus allowing customization of the resulting certificate.
  135. // For instance, TLS Feature Extension (RFC 7633) can be used
  136. // to prevent an OCSP downgrade attack.
  137. //
  138. // The field value is passed to crypto/x509.CreateCertificateRequest
  139. // in the template's ExtraExtensions field as is.
  140. ExtraExtensions []pkix.Extension
  141. clientMu sync.Mutex
  142. client *acme.Client // initialized by acmeClient method
  143. stateMu sync.Mutex
  144. state map[certKey]*certState
  145. // renewal tracks the set of domains currently running renewal timers.
  146. renewalMu sync.Mutex
  147. renewal map[certKey]*domainRenewal
  148. // tokensMu guards the rest of the fields: tryHTTP01, certTokens and httpTokens.
  149. tokensMu sync.RWMutex
  150. // tryHTTP01 indicates whether the Manager should try "http-01" challenge type
  151. // during the authorization flow.
  152. tryHTTP01 bool
  153. // httpTokens contains response body values for http-01 challenges
  154. // and is keyed by the URL path at which a challenge response is expected
  155. // to be provisioned.
  156. // The entries are stored for the duration of the authorization flow.
  157. httpTokens map[string][]byte
  158. // certTokens contains temporary certificates for tls-sni challenges
  159. // and is keyed by token domain name, which matches server name of ClientHello.
  160. // Keys always have ".acme.invalid" suffix.
  161. // The entries are stored for the duration of the authorization flow.
  162. certTokens map[string]*tls.Certificate
  163. }
  164. // certKey is the key by which certificates are tracked in state, renewal and cache.
  165. type certKey struct {
  166. domain string // without trailing dot
  167. isRSA bool // RSA cert for legacy clients (as opposed to default ECDSA)
  168. isToken bool // tls-sni challenge token cert; key type is undefined regardless of isRSA
  169. }
  170. func (c certKey) String() string {
  171. if c.isToken {
  172. return c.domain + "+token"
  173. }
  174. if c.isRSA {
  175. return c.domain + "+rsa"
  176. }
  177. return c.domain
  178. }
  179. // GetCertificate implements the tls.Config.GetCertificate hook.
  180. // It provides a TLS certificate for hello.ServerName host, including answering
  181. // *.acme.invalid (TLS-SNI) challenges. All other fields of hello are ignored.
  182. //
  183. // If m.HostPolicy is non-nil, GetCertificate calls the policy before requesting
  184. // a new cert. A non-nil error returned from m.HostPolicy halts TLS negotiation.
  185. // The error is propagated back to the caller of GetCertificate and is user-visible.
  186. // This does not affect cached certs. See HostPolicy field description for more details.
  187. func (m *Manager) GetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
  188. if m.Prompt == nil {
  189. return nil, errors.New("acme/autocert: Manager.Prompt not set")
  190. }
  191. name := hello.ServerName
  192. if name == "" {
  193. return nil, errors.New("acme/autocert: missing server name")
  194. }
  195. if !strings.Contains(strings.Trim(name, "."), ".") {
  196. return nil, errors.New("acme/autocert: server name component count invalid")
  197. }
  198. if strings.ContainsAny(name, `+/\`) {
  199. return nil, errors.New("acme/autocert: server name contains invalid character")
  200. }
  201. // In the worst-case scenario, the timeout needs to account for caching, host policy,
  202. // domain ownership verification and certificate issuance.
  203. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
  204. defer cancel()
  205. // check whether this is a token cert requested for TLS-SNI challenge
  206. if strings.HasSuffix(name, ".acme.invalid") {
  207. m.tokensMu.RLock()
  208. defer m.tokensMu.RUnlock()
  209. if cert := m.certTokens[name]; cert != nil {
  210. return cert, nil
  211. }
  212. if cert, err := m.cacheGet(ctx, certKey{domain: name, isToken: true}); err == nil {
  213. return cert, nil
  214. }
  215. // TODO: cache error results?
  216. return nil, fmt.Errorf("acme/autocert: no token cert for %q", name)
  217. }
  218. // regular domain
  219. ck := certKey{
  220. domain: strings.TrimSuffix(name, "."), // golang.org/issue/18114
  221. isRSA: !supportsECDSA(hello),
  222. }
  223. cert, err := m.cert(ctx, ck)
  224. if err == nil {
  225. return cert, nil
  226. }
  227. if err != ErrCacheMiss {
  228. return nil, err
  229. }
  230. // first-time
  231. if err := m.hostPolicy()(ctx, name); err != nil {
  232. return nil, err
  233. }
  234. cert, err = m.createCert(ctx, ck)
  235. if err != nil {
  236. return nil, err
  237. }
  238. m.cachePut(ctx, ck, cert)
  239. return cert, nil
  240. }
  241. func supportsECDSA(hello *tls.ClientHelloInfo) bool {
  242. // The "signature_algorithms" extension, if present, limits the key exchange
  243. // algorithms allowed by the cipher suites. See RFC 5246, section 7.4.1.4.1.
  244. if hello.SignatureSchemes != nil {
  245. ecdsaOK := false
  246. schemeLoop:
  247. for _, scheme := range hello.SignatureSchemes {
  248. const tlsECDSAWithSHA1 tls.SignatureScheme = 0x0203 // constant added in Go 1.10
  249. switch scheme {
  250. case tlsECDSAWithSHA1, tls.ECDSAWithP256AndSHA256,
  251. tls.ECDSAWithP384AndSHA384, tls.ECDSAWithP521AndSHA512:
  252. ecdsaOK = true
  253. break schemeLoop
  254. }
  255. }
  256. if !ecdsaOK {
  257. return false
  258. }
  259. }
  260. if hello.SupportedCurves != nil {
  261. ecdsaOK := false
  262. for _, curve := range hello.SupportedCurves {
  263. if curve == tls.CurveP256 {
  264. ecdsaOK = true
  265. break
  266. }
  267. }
  268. if !ecdsaOK {
  269. return false
  270. }
  271. }
  272. for _, suite := range hello.CipherSuites {
  273. switch suite {
  274. case tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
  275. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  276. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  277. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
  278. tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  279. tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  280. tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305:
  281. return true
  282. }
  283. }
  284. return false
  285. }
  286. // HTTPHandler configures the Manager to provision ACME "http-01" challenge responses.
  287. // It returns an http.Handler that responds to the challenges and must be
  288. // running on port 80. If it receives a request that is not an ACME challenge,
  289. // it delegates the request to the optional fallback handler.
  290. //
  291. // If fallback is nil, the returned handler redirects all GET and HEAD requests
  292. // to the default TLS port 443 with 302 Found status code, preserving the original
  293. // request path and query. It responds with 400 Bad Request to all other HTTP methods.
  294. // The fallback is not protected by the optional HostPolicy.
  295. //
  296. // Because the fallback handler is run with unencrypted port 80 requests,
  297. // the fallback should not serve TLS-only requests.
  298. //
  299. // If HTTPHandler is never called, the Manager will only use TLS SNI
  300. // challenges for domain verification.
  301. func (m *Manager) HTTPHandler(fallback http.Handler) http.Handler {
  302. m.tokensMu.Lock()
  303. defer m.tokensMu.Unlock()
  304. m.tryHTTP01 = true
  305. if fallback == nil {
  306. fallback = http.HandlerFunc(handleHTTPRedirect)
  307. }
  308. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  309. if !strings.HasPrefix(r.URL.Path, "/.well-known/acme-challenge/") {
  310. fallback.ServeHTTP(w, r)
  311. return
  312. }
  313. // A reasonable context timeout for cache and host policy only,
  314. // because we don't wait for a new certificate issuance here.
  315. ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
  316. defer cancel()
  317. if err := m.hostPolicy()(ctx, r.Host); err != nil {
  318. http.Error(w, err.Error(), http.StatusForbidden)
  319. return
  320. }
  321. data, err := m.httpToken(ctx, r.URL.Path)
  322. if err != nil {
  323. http.Error(w, err.Error(), http.StatusNotFound)
  324. return
  325. }
  326. w.Write(data)
  327. })
  328. }
  329. func handleHTTPRedirect(w http.ResponseWriter, r *http.Request) {
  330. if r.Method != "GET" && r.Method != "HEAD" {
  331. http.Error(w, "Use HTTPS", http.StatusBadRequest)
  332. return
  333. }
  334. target := "https://" + stripPort(r.Host) + r.URL.RequestURI()
  335. http.Redirect(w, r, target, http.StatusFound)
  336. }
  337. func stripPort(hostport string) string {
  338. host, _, err := net.SplitHostPort(hostport)
  339. if err != nil {
  340. return hostport
  341. }
  342. return net.JoinHostPort(host, "443")
  343. }
  344. // cert returns an existing certificate either from m.state or cache.
  345. // If a certificate is found in cache but not in m.state, the latter will be filled
  346. // with the cached value.
  347. func (m *Manager) cert(ctx context.Context, ck certKey) (*tls.Certificate, error) {
  348. m.stateMu.Lock()
  349. if s, ok := m.state[ck]; ok {
  350. m.stateMu.Unlock()
  351. s.RLock()
  352. defer s.RUnlock()
  353. return s.tlscert()
  354. }
  355. defer m.stateMu.Unlock()
  356. cert, err := m.cacheGet(ctx, ck)
  357. if err != nil {
  358. return nil, err
  359. }
  360. signer, ok := cert.PrivateKey.(crypto.Signer)
  361. if !ok {
  362. return nil, errors.New("acme/autocert: private key cannot sign")
  363. }
  364. if m.state == nil {
  365. m.state = make(map[certKey]*certState)
  366. }
  367. s := &certState{
  368. key: signer,
  369. cert: cert.Certificate,
  370. leaf: cert.Leaf,
  371. }
  372. m.state[ck] = s
  373. go m.renew(ck, s.key, s.leaf.NotAfter)
  374. return cert, nil
  375. }
  376. // cacheGet always returns a valid certificate, or an error otherwise.
  377. // If a cached certificate exists but is not valid, ErrCacheMiss is returned.
  378. func (m *Manager) cacheGet(ctx context.Context, ck certKey) (*tls.Certificate, error) {
  379. if m.Cache == nil {
  380. return nil, ErrCacheMiss
  381. }
  382. data, err := m.Cache.Get(ctx, ck.String())
  383. if err != nil {
  384. return nil, err
  385. }
  386. // private
  387. priv, pub := pem.Decode(data)
  388. if priv == nil || !strings.Contains(priv.Type, "PRIVATE") {
  389. return nil, ErrCacheMiss
  390. }
  391. privKey, err := parsePrivateKey(priv.Bytes)
  392. if err != nil {
  393. return nil, err
  394. }
  395. // public
  396. var pubDER [][]byte
  397. for len(pub) > 0 {
  398. var b *pem.Block
  399. b, pub = pem.Decode(pub)
  400. if b == nil {
  401. break
  402. }
  403. pubDER = append(pubDER, b.Bytes)
  404. }
  405. if len(pub) > 0 {
  406. // Leftover content not consumed by pem.Decode. Corrupt. Ignore.
  407. return nil, ErrCacheMiss
  408. }
  409. // verify and create TLS cert
  410. leaf, err := validCert(ck, pubDER, privKey)
  411. if err != nil {
  412. return nil, ErrCacheMiss
  413. }
  414. tlscert := &tls.Certificate{
  415. Certificate: pubDER,
  416. PrivateKey: privKey,
  417. Leaf: leaf,
  418. }
  419. return tlscert, nil
  420. }
  421. func (m *Manager) cachePut(ctx context.Context, ck certKey, tlscert *tls.Certificate) error {
  422. if m.Cache == nil {
  423. return nil
  424. }
  425. // contains PEM-encoded data
  426. var buf bytes.Buffer
  427. // private
  428. switch key := tlscert.PrivateKey.(type) {
  429. case *ecdsa.PrivateKey:
  430. if err := encodeECDSAKey(&buf, key); err != nil {
  431. return err
  432. }
  433. case *rsa.PrivateKey:
  434. b := x509.MarshalPKCS1PrivateKey(key)
  435. pb := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: b}
  436. if err := pem.Encode(&buf, pb); err != nil {
  437. return err
  438. }
  439. default:
  440. return errors.New("acme/autocert: unknown private key type")
  441. }
  442. // public
  443. for _, b := range tlscert.Certificate {
  444. pb := &pem.Block{Type: "CERTIFICATE", Bytes: b}
  445. if err := pem.Encode(&buf, pb); err != nil {
  446. return err
  447. }
  448. }
  449. return m.Cache.Put(ctx, ck.String(), buf.Bytes())
  450. }
  451. func encodeECDSAKey(w io.Writer, key *ecdsa.PrivateKey) error {
  452. b, err := x509.MarshalECPrivateKey(key)
  453. if err != nil {
  454. return err
  455. }
  456. pb := &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}
  457. return pem.Encode(w, pb)
  458. }
  459. // createCert starts the domain ownership verification and returns a certificate
  460. // for that domain upon success.
  461. //
  462. // If the domain is already being verified, it waits for the existing verification to complete.
  463. // Either way, createCert blocks for the duration of the whole process.
  464. func (m *Manager) createCert(ctx context.Context, ck certKey) (*tls.Certificate, error) {
  465. // TODO: maybe rewrite this whole piece using sync.Once
  466. state, err := m.certState(ck)
  467. if err != nil {
  468. return nil, err
  469. }
  470. // state may exist if another goroutine is already working on it
  471. // in which case just wait for it to finish
  472. if !state.locked {
  473. state.RLock()
  474. defer state.RUnlock()
  475. return state.tlscert()
  476. }
  477. // We are the first; state is locked.
  478. // Unblock the readers when domain ownership is verified
  479. // and we got the cert or the process failed.
  480. defer state.Unlock()
  481. state.locked = false
  482. der, leaf, err := m.authorizedCert(ctx, state.key, ck)
  483. if err != nil {
  484. // Remove the failed state after some time,
  485. // making the manager call createCert again on the following TLS hello.
  486. time.AfterFunc(createCertRetryAfter, func() {
  487. defer testDidRemoveState(ck)
  488. m.stateMu.Lock()
  489. defer m.stateMu.Unlock()
  490. // Verify the state hasn't changed and it's still invalid
  491. // before deleting.
  492. s, ok := m.state[ck]
  493. if !ok {
  494. return
  495. }
  496. if _, err := validCert(ck, s.cert, s.key); err == nil {
  497. return
  498. }
  499. delete(m.state, ck)
  500. })
  501. return nil, err
  502. }
  503. state.cert = der
  504. state.leaf = leaf
  505. go m.renew(ck, state.key, state.leaf.NotAfter)
  506. return state.tlscert()
  507. }
  508. // certState returns a new or existing certState.
  509. // If a new certState is returned, state.exist is false and the state is locked.
  510. // The returned error is non-nil only in the case where a new state could not be created.
  511. func (m *Manager) certState(ck certKey) (*certState, error) {
  512. m.stateMu.Lock()
  513. defer m.stateMu.Unlock()
  514. if m.state == nil {
  515. m.state = make(map[certKey]*certState)
  516. }
  517. // existing state
  518. if state, ok := m.state[ck]; ok {
  519. return state, nil
  520. }
  521. // new locked state
  522. var (
  523. err error
  524. key crypto.Signer
  525. )
  526. if ck.isRSA {
  527. key, err = rsa.GenerateKey(rand.Reader, 2048)
  528. } else {
  529. key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  530. }
  531. if err != nil {
  532. return nil, err
  533. }
  534. state := &certState{
  535. key: key,
  536. locked: true,
  537. }
  538. state.Lock() // will be unlocked by m.certState caller
  539. m.state[ck] = state
  540. return state, nil
  541. }
  542. // authorizedCert starts the domain ownership verification process and requests a new cert upon success.
  543. // The key argument is the certificate private key.
  544. func (m *Manager) authorizedCert(ctx context.Context, key crypto.Signer, ck certKey) (der [][]byte, leaf *x509.Certificate, err error) {
  545. client, err := m.acmeClient(ctx)
  546. if err != nil {
  547. return nil, nil, err
  548. }
  549. if err := m.verify(ctx, client, ck.domain); err != nil {
  550. return nil, nil, err
  551. }
  552. csr, err := certRequest(key, ck.domain, m.ExtraExtensions)
  553. if err != nil {
  554. return nil, nil, err
  555. }
  556. der, _, err = client.CreateCert(ctx, csr, 0, true)
  557. if err != nil {
  558. return nil, nil, err
  559. }
  560. leaf, err = validCert(ck, der, key)
  561. if err != nil {
  562. return nil, nil, err
  563. }
  564. return der, leaf, nil
  565. }
  566. // revokePendingAuthz revokes all authorizations idenfied by the elements of uri slice.
  567. // It ignores revocation errors.
  568. func (m *Manager) revokePendingAuthz(ctx context.Context, uri []string) {
  569. client, err := m.acmeClient(ctx)
  570. if err != nil {
  571. return
  572. }
  573. for _, u := range uri {
  574. client.RevokeAuthorization(ctx, u)
  575. }
  576. }
  577. // verify runs the identifier (domain) authorization flow
  578. // using each applicable ACME challenge type.
  579. func (m *Manager) verify(ctx context.Context, client *acme.Client, domain string) error {
  580. // The list of challenge types we'll try to fulfill
  581. // in this specific order.
  582. challengeTypes := []string{"tls-sni-02", "tls-sni-01"}
  583. m.tokensMu.RLock()
  584. if m.tryHTTP01 {
  585. challengeTypes = append(challengeTypes, "http-01")
  586. }
  587. m.tokensMu.RUnlock()
  588. // Keep track of pending authzs and revoke the ones that did not validate.
  589. pendingAuthzs := make(map[string]bool)
  590. defer func() {
  591. var uri []string
  592. for k, pending := range pendingAuthzs {
  593. if pending {
  594. uri = append(uri, k)
  595. }
  596. }
  597. if len(uri) > 0 {
  598. // Use "detached" background context.
  599. // The revocations need not happen in the current verification flow.
  600. go m.revokePendingAuthz(context.Background(), uri)
  601. }
  602. }()
  603. // errs accumulates challenge failure errors, printed if all fail
  604. errs := make(map[*acme.Challenge]error)
  605. var nextTyp int // challengeType index of the next challenge type to try
  606. for {
  607. // Start domain authorization and get the challenge.
  608. authz, err := client.Authorize(ctx, domain)
  609. if err != nil {
  610. return err
  611. }
  612. // No point in accepting challenges if the authorization status
  613. // is in a final state.
  614. switch authz.Status {
  615. case acme.StatusValid:
  616. return nil // already authorized
  617. case acme.StatusInvalid:
  618. return fmt.Errorf("acme/autocert: invalid authorization %q", authz.URI)
  619. }
  620. pendingAuthzs[authz.URI] = true
  621. // Pick the next preferred challenge.
  622. var chal *acme.Challenge
  623. for chal == nil && nextTyp < len(challengeTypes) {
  624. chal = pickChallenge(challengeTypes[nextTyp], authz.Challenges)
  625. nextTyp++
  626. }
  627. if chal == nil {
  628. errorMsg := fmt.Sprintf("acme/autocert: unable to authorize %q", domain)
  629. for chal, err := range errs {
  630. errorMsg += fmt.Sprintf("; challenge %q failed with error: %v", chal.Type, err)
  631. }
  632. return errors.New(errorMsg)
  633. }
  634. cleanup, err := m.fulfill(ctx, client, chal)
  635. if err != nil {
  636. errs[chal] = err
  637. continue
  638. }
  639. defer cleanup()
  640. if _, err := client.Accept(ctx, chal); err != nil {
  641. errs[chal] = err
  642. continue
  643. }
  644. // A challenge is fulfilled and accepted: wait for the CA to validate.
  645. if _, err := client.WaitAuthorization(ctx, authz.URI); err != nil {
  646. errs[chal] = err
  647. continue
  648. }
  649. delete(pendingAuthzs, authz.URI)
  650. return nil
  651. }
  652. }
  653. // fulfill provisions a response to the challenge chal.
  654. // The cleanup is non-nil only if provisioning succeeded.
  655. func (m *Manager) fulfill(ctx context.Context, client *acme.Client, chal *acme.Challenge) (cleanup func(), err error) {
  656. switch chal.Type {
  657. case "tls-sni-01":
  658. cert, name, err := client.TLSSNI01ChallengeCert(chal.Token)
  659. if err != nil {
  660. return nil, err
  661. }
  662. m.putCertToken(ctx, name, &cert)
  663. return func() { go m.deleteCertToken(name) }, nil
  664. case "tls-sni-02":
  665. cert, name, err := client.TLSSNI02ChallengeCert(chal.Token)
  666. if err != nil {
  667. return nil, err
  668. }
  669. m.putCertToken(ctx, name, &cert)
  670. return func() { go m.deleteCertToken(name) }, nil
  671. case "http-01":
  672. resp, err := client.HTTP01ChallengeResponse(chal.Token)
  673. if err != nil {
  674. return nil, err
  675. }
  676. p := client.HTTP01ChallengePath(chal.Token)
  677. m.putHTTPToken(ctx, p, resp)
  678. return func() { go m.deleteHTTPToken(p) }, nil
  679. }
  680. return nil, fmt.Errorf("acme/autocert: unknown challenge type %q", chal.Type)
  681. }
  682. func pickChallenge(typ string, chal []*acme.Challenge) *acme.Challenge {
  683. for _, c := range chal {
  684. if c.Type == typ {
  685. return c
  686. }
  687. }
  688. return nil
  689. }
  690. // putCertToken stores the token certificate with the specified name
  691. // in both m.certTokens map and m.Cache.
  692. func (m *Manager) putCertToken(ctx context.Context, name string, cert *tls.Certificate) {
  693. m.tokensMu.Lock()
  694. defer m.tokensMu.Unlock()
  695. if m.certTokens == nil {
  696. m.certTokens = make(map[string]*tls.Certificate)
  697. }
  698. m.certTokens[name] = cert
  699. m.cachePut(ctx, certKey{domain: name, isToken: true}, cert)
  700. }
  701. // deleteCertToken removes the token certificate with the specified name
  702. // from both m.certTokens map and m.Cache.
  703. func (m *Manager) deleteCertToken(name string) {
  704. m.tokensMu.Lock()
  705. defer m.tokensMu.Unlock()
  706. delete(m.certTokens, name)
  707. if m.Cache != nil {
  708. ck := certKey{domain: name, isToken: true}
  709. m.Cache.Delete(context.Background(), ck.String())
  710. }
  711. }
  712. // httpToken retrieves an existing http-01 token value from an in-memory map
  713. // or the optional cache.
  714. func (m *Manager) httpToken(ctx context.Context, tokenPath string) ([]byte, error) {
  715. m.tokensMu.RLock()
  716. defer m.tokensMu.RUnlock()
  717. if v, ok := m.httpTokens[tokenPath]; ok {
  718. return v, nil
  719. }
  720. if m.Cache == nil {
  721. return nil, fmt.Errorf("acme/autocert: no token at %q", tokenPath)
  722. }
  723. return m.Cache.Get(ctx, httpTokenCacheKey(tokenPath))
  724. }
  725. // putHTTPToken stores an http-01 token value using tokenPath as key
  726. // in both in-memory map and the optional Cache.
  727. //
  728. // It ignores any error returned from Cache.Put.
  729. func (m *Manager) putHTTPToken(ctx context.Context, tokenPath, val string) {
  730. m.tokensMu.Lock()
  731. defer m.tokensMu.Unlock()
  732. if m.httpTokens == nil {
  733. m.httpTokens = make(map[string][]byte)
  734. }
  735. b := []byte(val)
  736. m.httpTokens[tokenPath] = b
  737. if m.Cache != nil {
  738. m.Cache.Put(ctx, httpTokenCacheKey(tokenPath), b)
  739. }
  740. }
  741. // deleteHTTPToken removes an http-01 token value from both in-memory map
  742. // and the optional Cache, ignoring any error returned from the latter.
  743. //
  744. // If m.Cache is non-nil, it blocks until Cache.Delete returns without a timeout.
  745. func (m *Manager) deleteHTTPToken(tokenPath string) {
  746. m.tokensMu.Lock()
  747. defer m.tokensMu.Unlock()
  748. delete(m.httpTokens, tokenPath)
  749. if m.Cache != nil {
  750. m.Cache.Delete(context.Background(), httpTokenCacheKey(tokenPath))
  751. }
  752. }
  753. // httpTokenCacheKey returns a key at which an http-01 token value may be stored
  754. // in the Manager's optional Cache.
  755. func httpTokenCacheKey(tokenPath string) string {
  756. return path.Base(tokenPath) + "+http-01"
  757. }
  758. // renew starts a cert renewal timer loop, one per domain.
  759. //
  760. // The loop is scheduled in two cases:
  761. // - a cert was fetched from cache for the first time (wasn't in m.state)
  762. // - a new cert was created by m.createCert
  763. //
  764. // The key argument is a certificate private key.
  765. // The exp argument is the cert expiration time (NotAfter).
  766. func (m *Manager) renew(ck certKey, key crypto.Signer, exp time.Time) {
  767. m.renewalMu.Lock()
  768. defer m.renewalMu.Unlock()
  769. if m.renewal[ck] != nil {
  770. // another goroutine is already on it
  771. return
  772. }
  773. if m.renewal == nil {
  774. m.renewal = make(map[certKey]*domainRenewal)
  775. }
  776. dr := &domainRenewal{m: m, ck: ck, key: key}
  777. m.renewal[ck] = dr
  778. dr.start(exp)
  779. }
  780. // stopRenew stops all currently running cert renewal timers.
  781. // The timers are not restarted during the lifetime of the Manager.
  782. func (m *Manager) stopRenew() {
  783. m.renewalMu.Lock()
  784. defer m.renewalMu.Unlock()
  785. for name, dr := range m.renewal {
  786. delete(m.renewal, name)
  787. dr.stop()
  788. }
  789. }
  790. func (m *Manager) accountKey(ctx context.Context) (crypto.Signer, error) {
  791. const keyName = "acme_account+key"
  792. // Previous versions of autocert stored the value under a different key.
  793. const legacyKeyName = "acme_account.key"
  794. genKey := func() (*ecdsa.PrivateKey, error) {
  795. return ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  796. }
  797. if m.Cache == nil {
  798. return genKey()
  799. }
  800. data, err := m.Cache.Get(ctx, keyName)
  801. if err == ErrCacheMiss {
  802. data, err = m.Cache.Get(ctx, legacyKeyName)
  803. }
  804. if err == ErrCacheMiss {
  805. key, err := genKey()
  806. if err != nil {
  807. return nil, err
  808. }
  809. var buf bytes.Buffer
  810. if err := encodeECDSAKey(&buf, key); err != nil {
  811. return nil, err
  812. }
  813. if err := m.Cache.Put(ctx, keyName, buf.Bytes()); err != nil {
  814. return nil, err
  815. }
  816. return key, nil
  817. }
  818. if err != nil {
  819. return nil, err
  820. }
  821. priv, _ := pem.Decode(data)
  822. if priv == nil || !strings.Contains(priv.Type, "PRIVATE") {
  823. return nil, errors.New("acme/autocert: invalid account key found in cache")
  824. }
  825. return parsePrivateKey(priv.Bytes)
  826. }
  827. func (m *Manager) acmeClient(ctx context.Context) (*acme.Client, error) {
  828. m.clientMu.Lock()
  829. defer m.clientMu.Unlock()
  830. if m.client != nil {
  831. return m.client, nil
  832. }
  833. client := m.Client
  834. if client == nil {
  835. client = &acme.Client{DirectoryURL: acme.LetsEncryptURL}
  836. }
  837. if client.Key == nil {
  838. var err error
  839. client.Key, err = m.accountKey(ctx)
  840. if err != nil {
  841. return nil, err
  842. }
  843. }
  844. var contact []string
  845. if m.Email != "" {
  846. contact = []string{"mailto:" + m.Email}
  847. }
  848. a := &acme.Account{Contact: contact}
  849. _, err := client.Register(ctx, a, m.Prompt)
  850. if ae, ok := err.(*acme.Error); err == nil || ok && ae.StatusCode == http.StatusConflict {
  851. // conflict indicates the key is already registered
  852. m.client = client
  853. err = nil
  854. }
  855. return m.client, err
  856. }
  857. func (m *Manager) hostPolicy() HostPolicy {
  858. if m.HostPolicy != nil {
  859. return m.HostPolicy
  860. }
  861. return defaultHostPolicy
  862. }
  863. func (m *Manager) renewBefore() time.Duration {
  864. if m.RenewBefore > renewJitter {
  865. return m.RenewBefore
  866. }
  867. return 720 * time.Hour // 30 days
  868. }
  869. // certState is ready when its mutex is unlocked for reading.
  870. type certState struct {
  871. sync.RWMutex
  872. locked bool // locked for read/write
  873. key crypto.Signer // private key for cert
  874. cert [][]byte // DER encoding
  875. leaf *x509.Certificate // parsed cert[0]; always non-nil if cert != nil
  876. }
  877. // tlscert creates a tls.Certificate from s.key and s.cert.
  878. // Callers should wrap it in s.RLock() and s.RUnlock().
  879. func (s *certState) tlscert() (*tls.Certificate, error) {
  880. if s.key == nil {
  881. return nil, errors.New("acme/autocert: missing signer")
  882. }
  883. if len(s.cert) == 0 {
  884. return nil, errors.New("acme/autocert: missing certificate")
  885. }
  886. return &tls.Certificate{
  887. PrivateKey: s.key,
  888. Certificate: s.cert,
  889. Leaf: s.leaf,
  890. }, nil
  891. }
  892. // certRequest generates a CSR for the given common name cn and optional SANs.
  893. func certRequest(key crypto.Signer, cn string, ext []pkix.Extension, san ...string) ([]byte, error) {
  894. req := &x509.CertificateRequest{
  895. Subject: pkix.Name{CommonName: cn},
  896. DNSNames: san,
  897. ExtraExtensions: ext,
  898. }
  899. return x509.CreateCertificateRequest(rand.Reader, req, key)
  900. }
  901. // Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates
  902. // PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys.
  903. // OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.
  904. //
  905. // Inspired by parsePrivateKey in crypto/tls/tls.go.
  906. func parsePrivateKey(der []byte) (crypto.Signer, error) {
  907. if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
  908. return key, nil
  909. }
  910. if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
  911. switch key := key.(type) {
  912. case *rsa.PrivateKey:
  913. return key, nil
  914. case *ecdsa.PrivateKey:
  915. return key, nil
  916. default:
  917. return nil, errors.New("acme/autocert: unknown private key type in PKCS#8 wrapping")
  918. }
  919. }
  920. if key, err := x509.ParseECPrivateKey(der); err == nil {
  921. return key, nil
  922. }
  923. return nil, errors.New("acme/autocert: failed to parse private key")
  924. }
  925. // validCert parses a cert chain provided as der argument and verifies the leaf and der[0]
  926. // correspond to the private key, the domain and key type match, and expiration dates
  927. // are valid. It doesn't do any revocation checking.
  928. //
  929. // The returned value is the verified leaf cert.
  930. func validCert(ck certKey, der [][]byte, key crypto.Signer) (leaf *x509.Certificate, err error) {
  931. // parse public part(s)
  932. var n int
  933. for _, b := range der {
  934. n += len(b)
  935. }
  936. pub := make([]byte, n)
  937. n = 0
  938. for _, b := range der {
  939. n += copy(pub[n:], b)
  940. }
  941. x509Cert, err := x509.ParseCertificates(pub)
  942. if err != nil || len(x509Cert) == 0 {
  943. return nil, errors.New("acme/autocert: no public key found")
  944. }
  945. // verify the leaf is not expired and matches the domain name
  946. leaf = x509Cert[0]
  947. now := timeNow()
  948. if now.Before(leaf.NotBefore) {
  949. return nil, errors.New("acme/autocert: certificate is not valid yet")
  950. }
  951. if now.After(leaf.NotAfter) {
  952. return nil, errors.New("acme/autocert: expired certificate")
  953. }
  954. if err := leaf.VerifyHostname(ck.domain); err != nil {
  955. return nil, err
  956. }
  957. // ensure the leaf corresponds to the private key and matches the certKey type
  958. switch pub := leaf.PublicKey.(type) {
  959. case *rsa.PublicKey:
  960. prv, ok := key.(*rsa.PrivateKey)
  961. if !ok {
  962. return nil, errors.New("acme/autocert: private key type does not match public key type")
  963. }
  964. if pub.N.Cmp(prv.N) != 0 {
  965. return nil, errors.New("acme/autocert: private key does not match public key")
  966. }
  967. if !ck.isRSA && !ck.isToken {
  968. return nil, errors.New("acme/autocert: key type does not match expected value")
  969. }
  970. case *ecdsa.PublicKey:
  971. prv, ok := key.(*ecdsa.PrivateKey)
  972. if !ok {
  973. return nil, errors.New("acme/autocert: private key type does not match public key type")
  974. }
  975. if pub.X.Cmp(prv.X) != 0 || pub.Y.Cmp(prv.Y) != 0 {
  976. return nil, errors.New("acme/autocert: private key does not match public key")
  977. }
  978. if ck.isRSA && !ck.isToken {
  979. return nil, errors.New("acme/autocert: key type does not match expected value")
  980. }
  981. default:
  982. return nil, errors.New("acme/autocert: unknown public key algorithm")
  983. }
  984. return leaf, nil
  985. }
  986. type lockedMathRand struct {
  987. sync.Mutex
  988. rnd *mathrand.Rand
  989. }
  990. func (r *lockedMathRand) int63n(max int64) int64 {
  991. r.Lock()
  992. n := r.rnd.Int63n(max)
  993. r.Unlock()
  994. return n
  995. }
  996. // For easier testing.
  997. var (
  998. timeNow = time.Now
  999. // Called when a state is removed.
  1000. testDidRemoveState = func(certKey) {}
  1001. )