autocert.go 22 KB

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