autocert.go 34 KB

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