autocert.go 35 KB

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