autocert.go 23 KB

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