autocert.go 22 KB

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