autocert.go 21 KB

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