You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

821 lines
23 KiB

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