autocert.go 32 KB

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