autocert.go 34 KB

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