autocert.go 23 KB

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