autocert.go 21 KB

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