autocert.go 22 KB

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