autocert.go 17 KB

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