autocert.go 23 KB

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