autocert.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  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. "crypto"
  12. "crypto/ecdsa"
  13. "crypto/rand"
  14. "crypto/rsa"
  15. "crypto/tls"
  16. "crypto/x509"
  17. "crypto/x509/pkix"
  18. "encoding/pem"
  19. "errors"
  20. "fmt"
  21. "net/http"
  22. "sort"
  23. "strconv"
  24. "strings"
  25. "sync"
  26. "time"
  27. "golang.org/x/crypto/acme/internal/acme"
  28. "golang.org/x/net/context"
  29. )
  30. // AcceptTOS always returns true to indicate the acceptance of a CA Terms of Service
  31. // during account registration.
  32. func AcceptTOS(tosURL string) bool { return true }
  33. // HostPolicy specifies which host names the Manager is allowed to respond to.
  34. // It returns a non-nil error if the host should be rejected.
  35. // The returned error is accessible via tls.Conn.Handshake and its callers.
  36. // See Manager's HostPolicy field and GetCertificate method docs for more details.
  37. type HostPolicy func(ctx context.Context, host string) error
  38. // HostWhitelist returns a policy where only the specified host names are allowed.
  39. // Only exact matches are currently supported. Subdomains, regexp or wildcard
  40. // will not match.
  41. func HostWhitelist(hosts ...string) HostPolicy {
  42. whitelist := make(map[string]bool, len(hosts))
  43. for _, h := range hosts {
  44. whitelist[h] = true
  45. }
  46. return func(_ context.Context, host string) error {
  47. if !whitelist[host] {
  48. return errors.New("acme/autocert: host not configured")
  49. }
  50. return nil
  51. }
  52. }
  53. // defaultHostPolicy is used when Manager.HostPolicy is not set.
  54. func defaultHostPolicy(context.Context, string) error {
  55. return nil
  56. }
  57. // Manager is a stateful certificate manager built on top of acme.Client.
  58. // It obtains and refreshes certificates automatically,
  59. // as well as providing them to a TLS server via tls.Config.
  60. //
  61. // A simple usage example:
  62. //
  63. // m := autocert.Manager{
  64. // Prompt: autocert.AcceptTOS,
  65. // HostPolicy: autocert.HostWhitelist("example.org"),
  66. // }
  67. // s := &http.Server{
  68. // Addr: ":https",
  69. // TLSConfig: &tls.Config{GetCertificate: m.GetCertificate},
  70. // }
  71. // s.ListenAndServeTLS("", "")
  72. //
  73. // To preserve issued certificates and improve overall performance,
  74. // use a cache implementation of Cache. For instance, DirCache.
  75. type Manager struct {
  76. // Prompt specifies a callback function to conditionally accept a CA's Terms of Service (TOS).
  77. // The registration may require the caller to agree to the CA's TOS.
  78. // If so, Manager calls Prompt with a TOS URL provided by the CA. Prompt should report
  79. // whether the caller agrees to the terms.
  80. //
  81. // To always accept the terms, the callers can use AcceptTOS.
  82. Prompt func(tosURL string) bool
  83. // Cache optionally stores and retrieves previously-obtained certificates.
  84. // If nil, certs will only be cached for the lifetime of the Manager.
  85. //
  86. // Manager passes the Cache certificates data encoded in PEM, with private/public
  87. // parts combined in a single Cache.Put call, private key first.
  88. Cache Cache
  89. // HostPolicy controls which domains the Manager will attempt
  90. // to retrieve new certificates for. It does not affect cached certs.
  91. //
  92. // If non-nil, HostPolicy is called before requesting a new cert.
  93. // If nil, all hosts are currently allowed. This is not recommended,
  94. // as it opens a potential attack where clients connect to a server
  95. // by IP address and pretend to be asking for an incorrect host name.
  96. // Manager will attempt to obtain a certificate for that host, incorrectly,
  97. // eventually reaching the CA's rate limit for certificate requests
  98. // and making it impossible to obtain actual certificates.
  99. //
  100. // See GetCertificate for more details.
  101. HostPolicy HostPolicy
  102. // Client is used to perform low-level operations, such as account registration
  103. // and requesting new certificates.
  104. // If Client is nil, a zero-value acme.Client is used with acme.LetsEncryptURL
  105. // directory endpoint and a newly-generated 2048-bit RSA key.
  106. //
  107. // Mutating the field after the first call of GetCertificate method will have no effect.
  108. Client *acme.Client
  109. // Email optionally specifies a contact email address.
  110. // This is used by CAs, such as Let's Encrypt, to notify about problems
  111. // with issued certificates.
  112. //
  113. // If the Client's account key is already registered, Email is not used.
  114. Email string
  115. clientMu sync.Mutex
  116. client *acme.Client // initialized by acmeClient method
  117. stateMu sync.Mutex
  118. state map[string]*certState // keyed by domain name
  119. // tokenCert is keyed by token domain name, which matches server name
  120. // of ClientHello. Keys always have ".acme.invalid" suffix.
  121. tokenCertMu sync.RWMutex
  122. tokenCert map[string]*tls.Certificate
  123. }
  124. // GetCertificate implements the tls.Config.GetCertificate hook.
  125. // It provides a TLS certificate for hello.ServerName host, including answering
  126. // *.acme.invalid (TLS-SNI) challenges. All other fields of hello are ignored.
  127. //
  128. // If m.HostPolicy is non-nil, GetCertificate calls the policy before requesting
  129. // a new cert. A non-nil error returned from m.HostPolicy halts TLS negotiation.
  130. // The error is propagated back to the caller of GetCertificate and is user-visible.
  131. // This does not affect cached certs. See HostPolicy field description for more details.
  132. func (m *Manager) GetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
  133. name := hello.ServerName
  134. if name == "" {
  135. return nil, errors.New("acme/autocert: missing server name")
  136. }
  137. // check whether this is a token cert requested for TLS-SNI challenge
  138. if strings.HasSuffix(name, ".acme.invalid") {
  139. m.tokenCertMu.RLock()
  140. defer m.tokenCertMu.RUnlock()
  141. if cert := m.tokenCert[name]; cert != nil {
  142. return cert, nil
  143. }
  144. if cert, err := m.cacheGet(name); err == nil {
  145. return cert, nil
  146. }
  147. // TODO: cache error results?
  148. return nil, fmt.Errorf("acme/autocert: no token cert for %q", name)
  149. }
  150. // regular domain
  151. cert, err := m.cert(name)
  152. if err == nil {
  153. return cert, nil
  154. }
  155. if err != ErrCacheMiss {
  156. return nil, err
  157. }
  158. // first-time
  159. ctx := context.Background() // TODO: use a deadline?
  160. if err := m.hostPolicy()(ctx, name); err != nil {
  161. return nil, err
  162. }
  163. cert, err = m.createCert(ctx, name)
  164. if err != nil {
  165. return nil, err
  166. }
  167. m.cachePut(name, cert)
  168. return cert, nil
  169. }
  170. // cert returns an existing certificate either from m.state or cache.
  171. // If a certificate is found in cache but not in m.state, the latter will be filled
  172. // with the cached value.
  173. func (m *Manager) cert(name string) (*tls.Certificate, error) {
  174. m.stateMu.Lock()
  175. s, ok := m.state[name]
  176. if ok {
  177. m.stateMu.Unlock()
  178. s.RLock()
  179. defer s.RUnlock()
  180. return s.tlscert()
  181. }
  182. defer m.stateMu.Unlock()
  183. cert, err := m.cacheGet(name)
  184. if err != nil {
  185. return nil, err
  186. }
  187. signer, ok := cert.PrivateKey.(crypto.Signer)
  188. if !ok {
  189. return nil, errors.New("acme/autocert: private key cannot sign")
  190. }
  191. if m.state == nil {
  192. m.state = make(map[string]*certState)
  193. }
  194. m.state[name] = &certState{
  195. key: signer,
  196. cert: cert.Certificate,
  197. leaf: cert.Leaf,
  198. }
  199. return cert, nil
  200. }
  201. // cacheGet always returns a valid certificate, or an error otherwise.
  202. func (m *Manager) cacheGet(domain string) (*tls.Certificate, error) {
  203. if m.Cache == nil {
  204. return nil, ErrCacheMiss
  205. }
  206. // TODO: might want to define a cache timeout on m
  207. ctx := context.Background()
  208. data, err := m.Cache.Get(ctx, domain)
  209. if err != nil {
  210. return nil, err
  211. }
  212. // private
  213. priv, pub := pem.Decode(data)
  214. if priv == nil || !strings.Contains(priv.Type, "PRIVATE") {
  215. return nil, errors.New("acme/autocert: no private key found in cache")
  216. }
  217. privKey, err := parsePrivateKey(priv.Bytes)
  218. if err != nil {
  219. return nil, err
  220. }
  221. // public
  222. var pubDER []byte
  223. for len(pub) > 0 {
  224. var b *pem.Block
  225. b, pub = pem.Decode(pub)
  226. if b == nil {
  227. break
  228. }
  229. pubDER = append(pubDER, b.Bytes...)
  230. }
  231. if len(pub) > 0 {
  232. return nil, errors.New("acme/autocert: invalid public key")
  233. }
  234. // parse public part(s) and verify the leaf is not expired
  235. // and corresponds to the private key
  236. x509Cert, err := x509.ParseCertificates(pubDER)
  237. if len(x509Cert) == 0 {
  238. return nil, errors.New("acme/autocert: no public key found in cache")
  239. }
  240. leaf := x509Cert[0]
  241. now := time.Now()
  242. if now.Before(leaf.NotBefore) {
  243. return nil, errors.New("acme/autocert: certificate is not valid yet")
  244. }
  245. if now.After(leaf.NotAfter) {
  246. return nil, errors.New("acme/autocert: expired certificate")
  247. }
  248. if !domainMatch(leaf, domain) {
  249. return nil, errors.New("acme/autocert: certificate does not match domain name")
  250. }
  251. switch pub := leaf.PublicKey.(type) {
  252. case *rsa.PublicKey:
  253. prv, ok := privKey.(*rsa.PrivateKey)
  254. if !ok {
  255. return nil, errors.New("acme/autocert: private key type does not match public key type")
  256. }
  257. if pub.N.Cmp(prv.N) != 0 {
  258. return nil, errors.New("acme/autocert: private key does not match public key")
  259. }
  260. case *ecdsa.PublicKey:
  261. prv, ok := privKey.(*ecdsa.PrivateKey)
  262. if !ok {
  263. return nil, errors.New("acme/autocert: private key type does not match public key type")
  264. }
  265. if pub.X.Cmp(prv.X) != 0 || pub.Y.Cmp(prv.Y) != 0 {
  266. return nil, errors.New("acme/autocert: private key does not match public key")
  267. }
  268. default:
  269. return nil, errors.New("acme/autocert: unknown public key algorithm")
  270. }
  271. tlscert := &tls.Certificate{
  272. Certificate: make([][]byte, len(x509Cert)),
  273. PrivateKey: privKey,
  274. Leaf: leaf,
  275. }
  276. for i, crt := range x509Cert {
  277. tlscert.Certificate[i] = crt.Raw
  278. }
  279. return tlscert, nil
  280. }
  281. func (m *Manager) cachePut(domain string, tlscert *tls.Certificate) error {
  282. if m.Cache == nil {
  283. return nil
  284. }
  285. // contains PEM-encoded data
  286. var buf bytes.Buffer
  287. // private
  288. switch key := tlscert.PrivateKey.(type) {
  289. case *ecdsa.PrivateKey:
  290. b, err := x509.MarshalECPrivateKey(key)
  291. if err != nil {
  292. return err
  293. }
  294. pb := &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}
  295. if err := pem.Encode(&buf, pb); err != nil {
  296. return err
  297. }
  298. case *rsa.PrivateKey:
  299. b := x509.MarshalPKCS1PrivateKey(key)
  300. pb := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: b}
  301. if err := pem.Encode(&buf, pb); err != nil {
  302. return err
  303. }
  304. default:
  305. return errors.New("acme/autocert: unknown private key type")
  306. }
  307. // public
  308. for _, b := range tlscert.Certificate {
  309. pb := &pem.Block{Type: "CERTIFICATE", Bytes: b}
  310. if err := pem.Encode(&buf, pb); err != nil {
  311. return err
  312. }
  313. }
  314. // TODO: might want to define a cache timeout on m
  315. ctx := context.Background()
  316. return m.Cache.Put(ctx, domain, buf.Bytes())
  317. }
  318. // createCert starts domain ownership verification and returns a certificate for that domain
  319. // upon success.
  320. //
  321. // If the domain is already being verified, it waits for the existing verification to complete.
  322. // Either way, createCert blocks for the duration of the whole process.
  323. func (m *Manager) createCert(ctx context.Context, domain string) (*tls.Certificate, error) {
  324. state, ok, err := m.certState(domain)
  325. if err != nil {
  326. return nil, err
  327. }
  328. // state may exist if another goroutine is already working on it
  329. // in which case just wait for it to finish
  330. if ok {
  331. state.RLock()
  332. defer state.RUnlock()
  333. return state.tlscert()
  334. }
  335. // We are the first.
  336. // Unblock the readers when domain ownership is verified
  337. // and the we got the cert or the process failed.
  338. defer state.Unlock()
  339. // TODO: make m.verify retry or retry m.verify calls here
  340. if err := m.verify(ctx, domain); err != nil {
  341. return nil, err
  342. }
  343. client, err := m.acmeClient(ctx)
  344. if err != nil {
  345. return nil, err
  346. }
  347. csr, err := certRequest(state.key, domain)
  348. if err != nil {
  349. return nil, err
  350. }
  351. der, _, err := client.CreateCert(ctx, csr, 0, true)
  352. if err != nil {
  353. return nil, err
  354. }
  355. state.cert = der
  356. return state.tlscert()
  357. }
  358. // verify starts a new identifier (domain) authorization flow.
  359. // It prepares a challenge response and then blocks until the authorization
  360. // is marked as "completed" by the CA (either succeeded or failed).
  361. //
  362. // verify returns nil iff the verification was successful.
  363. func (m *Manager) verify(ctx context.Context, domain string) error {
  364. client, err := m.acmeClient(ctx)
  365. if err != nil {
  366. return err
  367. }
  368. // start domain authorization and get the challenge
  369. authz, err := client.Authorize(ctx, domain)
  370. if err != nil {
  371. return err
  372. }
  373. // maybe don't need to at all
  374. if authz.Status == acme.StatusValid {
  375. return nil
  376. }
  377. // pick a challenge: prefer tls-sni-02 over tls-sni-01
  378. // TODO: consider authz.Combinations
  379. var chal *acme.Challenge
  380. for _, c := range authz.Challenges {
  381. if c.Type == "tls-sni-02" {
  382. chal = c
  383. break
  384. }
  385. if c.Type == "tls-sni-01" {
  386. chal = c
  387. }
  388. }
  389. if chal == nil {
  390. return errors.New("acme/autocert: no supported challenge type found")
  391. }
  392. // create a token cert for the challenge response
  393. var (
  394. cert tls.Certificate
  395. name string
  396. )
  397. switch chal.Type {
  398. case "tls-sni-01":
  399. cert, name, err = client.TLSSNI01ChallengeCert(chal.Token)
  400. case "tls-sni-02":
  401. cert, name, err = client.TLSSNI02ChallengeCert(chal.Token)
  402. default:
  403. err = fmt.Errorf("acme/autocert: unknown challenge type %q", chal.Type)
  404. }
  405. if err != nil {
  406. return err
  407. }
  408. m.putTokenCert(name, &cert)
  409. defer func() {
  410. // verification has ended at this point
  411. // don't need token cert anymore
  412. go m.deleteTokenCert(name)
  413. }()
  414. // ready to fulfill the challenge
  415. if _, err := client.Accept(ctx, chal); err != nil {
  416. return err
  417. }
  418. // wait for the CA to validate
  419. _, err = client.WaitAuthorization(ctx, authz.URI)
  420. return err
  421. }
  422. // certState returns existing state or creates a new one locked for read/write.
  423. // The boolean return value indicates whether the state was found in m.state.
  424. func (m *Manager) certState(domain string) (*certState, bool, error) {
  425. m.stateMu.Lock()
  426. defer m.stateMu.Unlock()
  427. if m.state == nil {
  428. m.state = make(map[string]*certState)
  429. }
  430. // existing state
  431. if state, ok := m.state[domain]; ok {
  432. return state, true, nil
  433. }
  434. // new locked state
  435. key, err := rsa.GenerateKey(rand.Reader, 2048)
  436. if err != nil {
  437. return nil, false, err
  438. }
  439. state := &certState{key: key}
  440. state.Lock()
  441. m.state[domain] = state
  442. return state, false, nil
  443. }
  444. // putTokenCert stores the cert under the named key in both m.tokenCert map
  445. // and m.Cache.
  446. func (m *Manager) putTokenCert(name string, cert *tls.Certificate) {
  447. m.tokenCertMu.Lock()
  448. defer m.tokenCertMu.Unlock()
  449. if m.tokenCert == nil {
  450. m.tokenCert = make(map[string]*tls.Certificate)
  451. }
  452. m.tokenCert[name] = cert
  453. m.cachePut(name, cert)
  454. }
  455. // deleteTokenCert removes the token certificate for the specified domain name
  456. // from both m.tokenCert map and m.Cache.
  457. func (m *Manager) deleteTokenCert(name string) {
  458. m.tokenCertMu.Lock()
  459. defer m.tokenCertMu.Unlock()
  460. delete(m.tokenCert, name)
  461. if m.Cache != nil {
  462. m.Cache.Delete(context.Background(), name)
  463. }
  464. }
  465. func (m *Manager) acmeClient(ctx context.Context) (*acme.Client, error) {
  466. m.clientMu.Lock()
  467. defer m.clientMu.Unlock()
  468. if m.client != nil {
  469. return m.client, nil
  470. }
  471. client := m.Client
  472. if client == nil {
  473. client = &acme.Client{DirectoryURL: acme.LetsEncryptURL}
  474. }
  475. if client.Key == nil {
  476. var err error
  477. client.Key, err = rsa.GenerateKey(rand.Reader, 2048)
  478. if err != nil {
  479. return nil, err
  480. }
  481. }
  482. var contact []string
  483. if m.Email != "" {
  484. contact = []string{"mailto:" + m.Email}
  485. }
  486. a := &acme.Account{Contact: contact}
  487. _, err := client.Register(ctx, a, m.Prompt)
  488. if ae, ok := err.(*acme.Error); err == nil || ok && ae.StatusCode == http.StatusConflict {
  489. // conflict indicates the key is already registered
  490. m.client = client
  491. err = nil
  492. }
  493. return m.client, err
  494. }
  495. func (m *Manager) hostPolicy() HostPolicy {
  496. if m.HostPolicy != nil {
  497. return m.HostPolicy
  498. }
  499. return defaultHostPolicy
  500. }
  501. // certState is ready when its mutex is unlocked for reading.
  502. type certState struct {
  503. sync.RWMutex
  504. key crypto.Signer
  505. cert [][]byte // DER encoding
  506. leaf *x509.Certificate // parsed cert[0]; may be nil
  507. }
  508. // tlscert creates a tls.Certificate from s.key and s.cert.
  509. // Callers should wrap it in s.RLock() and s.RUnlock().
  510. func (s *certState) tlscert() (*tls.Certificate, error) {
  511. if s.key == nil {
  512. return nil, errors.New("acme/autocert: missing signer")
  513. }
  514. if len(s.cert) == 0 {
  515. return nil, errors.New("acme/autocert: missing certificate")
  516. }
  517. // TODO: compare pub.N with key.N or pub.{X,Y} for ECDSA?
  518. return &tls.Certificate{
  519. PrivateKey: s.key,
  520. Certificate: s.cert,
  521. Leaf: s.leaf,
  522. }, nil
  523. }
  524. // certRequest creates a certificate request for the given common name cn
  525. // and optional SANs.
  526. func certRequest(key crypto.Signer, cn string, san ...string) ([]byte, error) {
  527. req := &x509.CertificateRequest{
  528. Subject: pkix.Name{CommonName: cn},
  529. DNSNames: san,
  530. }
  531. return x509.CreateCertificateRequest(rand.Reader, req, key)
  532. }
  533. // Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates
  534. // PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys.
  535. // OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.
  536. //
  537. // Copied from crypto/tls/tls.go.
  538. func parsePrivateKey(der []byte) (crypto.PrivateKey, error) {
  539. if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
  540. return key, nil
  541. }
  542. if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
  543. switch key := key.(type) {
  544. case *rsa.PrivateKey, *ecdsa.PrivateKey:
  545. return key, nil
  546. default:
  547. return nil, errors.New("acme/autocert: found unknown private key type in PKCS#8 wrapping")
  548. }
  549. }
  550. if key, err := x509.ParseECPrivateKey(der); err == nil {
  551. return key, nil
  552. }
  553. return nil, errors.New("acme/autocert: failed to parse private key")
  554. }
  555. // domainMatch matches cert against the specified domain name.
  556. // It doesn't support wildcard.
  557. func domainMatch(cert *x509.Certificate, name string) bool {
  558. if cert.Subject.CommonName == name {
  559. return true
  560. }
  561. sort.Strings(cert.DNSNames)
  562. i := sort.SearchStrings(cert.DNSNames, name)
  563. return i < len(cert.DNSNames) && cert.DNSNames[i] == name
  564. }
  565. func retryAfter(v string) time.Duration {
  566. if i, err := strconv.Atoi(v); err == nil {
  567. return time.Duration(i) * time.Second
  568. }
  569. if t, err := http.ParseTime(v); err == nil {
  570. return t.Sub(time.Now())
  571. }
  572. return time.Second
  573. }