本站源代码
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.

1138 lines
34KB

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