autocert.go 38 KB

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