You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1131 lines
31 KiB

  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
  5. import (
  6. "bytes"
  7. "context"
  8. "crypto"
  9. "crypto/ecdsa"
  10. "crypto/elliptic"
  11. "crypto/rand"
  12. "crypto/rsa"
  13. "crypto/tls"
  14. "crypto/x509"
  15. "crypto/x509/pkix"
  16. "encoding/asn1"
  17. "encoding/base64"
  18. "encoding/json"
  19. "fmt"
  20. "html/template"
  21. "io"
  22. "math/big"
  23. "net/http"
  24. "net/http/httptest"
  25. "reflect"
  26. "strings"
  27. "sync"
  28. "testing"
  29. "time"
  30. "golang.org/x/crypto/acme"
  31. )
  32. var (
  33. exampleDomain = "example.org"
  34. exampleCertKey = certKey{domain: exampleDomain}
  35. exampleCertKeyRSA = certKey{domain: exampleDomain, isRSA: true}
  36. )
  37. var discoTmpl = template.Must(template.New("disco").Parse(`{
  38. "new-reg": "{{.}}/new-reg",
  39. "new-authz": "{{.}}/new-authz",
  40. "new-cert": "{{.}}/new-cert"
  41. }`))
  42. var authzTmpl = template.Must(template.New("authz").Parse(`{
  43. "status": "pending",
  44. "challenges": [
  45. {
  46. "uri": "{{.}}/challenge/1",
  47. "type": "tls-sni-01",
  48. "token": "token-01"
  49. },
  50. {
  51. "uri": "{{.}}/challenge/2",
  52. "type": "tls-sni-02",
  53. "token": "token-02"
  54. },
  55. {
  56. "uri": "{{.}}/challenge/dns-01",
  57. "type": "dns-01",
  58. "token": "token-dns-01"
  59. },
  60. {
  61. "uri": "{{.}}/challenge/http-01",
  62. "type": "http-01",
  63. "token": "token-http-01"
  64. }
  65. ]
  66. }`))
  67. type memCache struct {
  68. t *testing.T
  69. mu sync.Mutex
  70. keyData map[string][]byte
  71. }
  72. func (m *memCache) Get(ctx context.Context, key string) ([]byte, error) {
  73. m.mu.Lock()
  74. defer m.mu.Unlock()
  75. v, ok := m.keyData[key]
  76. if !ok {
  77. return nil, ErrCacheMiss
  78. }
  79. return v, nil
  80. }
  81. // filenameSafe returns whether all characters in s are printable ASCII
  82. // and safe to use in a filename on most filesystems.
  83. func filenameSafe(s string) bool {
  84. for _, c := range s {
  85. if c < 0x20 || c > 0x7E {
  86. return false
  87. }
  88. switch c {
  89. case '\\', '/', ':', '*', '?', '"', '<', '>', '|':
  90. return false
  91. }
  92. }
  93. return true
  94. }
  95. func (m *memCache) Put(ctx context.Context, key string, data []byte) error {
  96. if !filenameSafe(key) {
  97. m.t.Errorf("invalid characters in cache key %q", key)
  98. }
  99. m.mu.Lock()
  100. defer m.mu.Unlock()
  101. m.keyData[key] = data
  102. return nil
  103. }
  104. func (m *memCache) Delete(ctx context.Context, key string) error {
  105. m.mu.Lock()
  106. defer m.mu.Unlock()
  107. delete(m.keyData, key)
  108. return nil
  109. }
  110. func newMemCache(t *testing.T) *memCache {
  111. return &memCache{
  112. t: t,
  113. keyData: make(map[string][]byte),
  114. }
  115. }
  116. func (m *memCache) numCerts() int {
  117. m.mu.Lock()
  118. defer m.mu.Unlock()
  119. res := 0
  120. for key := range m.keyData {
  121. if strings.HasSuffix(key, "+token") ||
  122. strings.HasSuffix(key, "+key") ||
  123. strings.HasSuffix(key, "+http-01") {
  124. continue
  125. }
  126. res++
  127. }
  128. return res
  129. }
  130. func dummyCert(pub interface{}, san ...string) ([]byte, error) {
  131. return dateDummyCert(pub, time.Now(), time.Now().Add(90*24*time.Hour), san...)
  132. }
  133. func dateDummyCert(pub interface{}, start, end time.Time, san ...string) ([]byte, error) {
  134. // use EC key to run faster on 386
  135. key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  136. if err != nil {
  137. return nil, err
  138. }
  139. t := &x509.Certificate{
  140. SerialNumber: big.NewInt(1),
  141. NotBefore: start,
  142. NotAfter: end,
  143. BasicConstraintsValid: true,
  144. KeyUsage: x509.KeyUsageKeyEncipherment,
  145. DNSNames: san,
  146. }
  147. if pub == nil {
  148. pub = &key.PublicKey
  149. }
  150. return x509.CreateCertificate(rand.Reader, t, t, pub, key)
  151. }
  152. func decodePayload(v interface{}, r io.Reader) error {
  153. var req struct{ Payload string }
  154. if err := json.NewDecoder(r).Decode(&req); err != nil {
  155. return err
  156. }
  157. payload, err := base64.RawURLEncoding.DecodeString(req.Payload)
  158. if err != nil {
  159. return err
  160. }
  161. return json.Unmarshal(payload, v)
  162. }
  163. func clientHelloInfo(sni string, ecdsaSupport bool) *tls.ClientHelloInfo {
  164. hello := &tls.ClientHelloInfo{
  165. ServerName: sni,
  166. CipherSuites: []uint16{tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305},
  167. }
  168. if ecdsaSupport {
  169. hello.CipherSuites = append(hello.CipherSuites, tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305)
  170. }
  171. return hello
  172. }
  173. func TestGetCertificate(t *testing.T) {
  174. man := &Manager{Prompt: AcceptTOS}
  175. defer man.stopRenew()
  176. hello := clientHelloInfo("example.org", true)
  177. testGetCertificate(t, man, "example.org", hello)
  178. }
  179. func TestGetCertificate_trailingDot(t *testing.T) {
  180. man := &Manager{Prompt: AcceptTOS}
  181. defer man.stopRenew()
  182. hello := clientHelloInfo("example.org.", true)
  183. testGetCertificate(t, man, "example.org", hello)
  184. }
  185. func TestGetCertificate_ForceRSA(t *testing.T) {
  186. man := &Manager{
  187. Prompt: AcceptTOS,
  188. Cache: newMemCache(t),
  189. ForceRSA: true,
  190. }
  191. defer man.stopRenew()
  192. hello := clientHelloInfo(exampleDomain, true)
  193. testGetCertificate(t, man, exampleDomain, hello)
  194. // ForceRSA was deprecated and is now ignored.
  195. cert, err := man.cacheGet(context.Background(), exampleCertKey)
  196. if err != nil {
  197. t.Fatalf("man.cacheGet: %v", err)
  198. }
  199. if _, ok := cert.PrivateKey.(*ecdsa.PrivateKey); !ok {
  200. t.Errorf("cert.PrivateKey is %T; want *ecdsa.PrivateKey", cert.PrivateKey)
  201. }
  202. }
  203. func TestGetCertificate_nilPrompt(t *testing.T) {
  204. man := &Manager{}
  205. defer man.stopRenew()
  206. url, finish := startACMEServerStub(t, getCertificateFromManager(man, true), "example.org")
  207. defer finish()
  208. man.Client = &acme.Client{DirectoryURL: url}
  209. hello := clientHelloInfo("example.org", true)
  210. if _, err := man.GetCertificate(hello); err == nil {
  211. t.Error("got certificate for example.org; wanted error")
  212. }
  213. }
  214. func TestGetCertificate_expiredCache(t *testing.T) {
  215. // Make an expired cert and cache it.
  216. pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  217. if err != nil {
  218. t.Fatal(err)
  219. }
  220. tmpl := &x509.Certificate{
  221. SerialNumber: big.NewInt(1),
  222. Subject: pkix.Name{CommonName: exampleDomain},
  223. NotAfter: time.Now(),
  224. }
  225. pub, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &pk.PublicKey, pk)
  226. if err != nil {
  227. t.Fatal(err)
  228. }
  229. tlscert := &tls.Certificate{
  230. Certificate: [][]byte{pub},
  231. PrivateKey: pk,
  232. }
  233. man := &Manager{Prompt: AcceptTOS, Cache: newMemCache(t)}
  234. defer man.stopRenew()
  235. if err := man.cachePut(context.Background(), exampleCertKey, tlscert); err != nil {
  236. t.Fatalf("man.cachePut: %v", err)
  237. }
  238. // The expired cached cert should trigger a new cert issuance
  239. // and return without an error.
  240. hello := clientHelloInfo(exampleDomain, true)
  241. testGetCertificate(t, man, exampleDomain, hello)
  242. }
  243. func TestGetCertificate_failedAttempt(t *testing.T) {
  244. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  245. w.WriteHeader(http.StatusBadRequest)
  246. }))
  247. defer ts.Close()
  248. d := createCertRetryAfter
  249. f := testDidRemoveState
  250. defer func() {
  251. createCertRetryAfter = d
  252. testDidRemoveState = f
  253. }()
  254. createCertRetryAfter = 0
  255. done := make(chan struct{})
  256. testDidRemoveState = func(ck certKey) {
  257. if ck != exampleCertKey {
  258. t.Errorf("testDidRemoveState: domain = %v; want %v", ck, exampleCertKey)
  259. }
  260. close(done)
  261. }
  262. man := &Manager{
  263. Prompt: AcceptTOS,
  264. Client: &acme.Client{
  265. DirectoryURL: ts.URL,
  266. },
  267. }
  268. defer man.stopRenew()
  269. hello := clientHelloInfo(exampleDomain, true)
  270. if _, err := man.GetCertificate(hello); err == nil {
  271. t.Error("GetCertificate: err is nil")
  272. }
  273. select {
  274. case <-time.After(5 * time.Second):
  275. t.Errorf("took too long to remove the %q state", exampleCertKey)
  276. case <-done:
  277. man.stateMu.Lock()
  278. defer man.stateMu.Unlock()
  279. if v, exist := man.state[exampleCertKey]; exist {
  280. t.Errorf("state exists for %v: %+v", exampleCertKey, v)
  281. }
  282. }
  283. }
  284. // testGetCertificate_tokenCache tests the fallback of token certificate fetches
  285. // to cache when Manager.certTokens misses. ecdsaSupport refers to the CA when
  286. // verifying the certificate token.
  287. func testGetCertificate_tokenCache(t *testing.T, ecdsaSupport bool) {
  288. man1 := &Manager{
  289. Cache: newMemCache(t),
  290. Prompt: AcceptTOS,
  291. }
  292. defer man1.stopRenew()
  293. man2 := &Manager{
  294. Cache: man1.Cache,
  295. Prompt: AcceptTOS,
  296. }
  297. defer man2.stopRenew()
  298. // Send the verification request to a different Manager from the one that
  299. // initiated the authorization, when they share caches.
  300. url, finish := startACMEServerStub(t, getCertificateFromManager(man2, ecdsaSupport), "example.org")
  301. defer finish()
  302. man1.Client = &acme.Client{DirectoryURL: url}
  303. hello := clientHelloInfo("example.org", true)
  304. if _, err := man1.GetCertificate(hello); err != nil {
  305. t.Error(err)
  306. }
  307. if _, err := man2.GetCertificate(hello); err != nil {
  308. t.Error(err)
  309. }
  310. }
  311. func TestGetCertificate_tokenCache(t *testing.T) {
  312. t.Run("ecdsaSupport=true", func(t *testing.T) {
  313. testGetCertificate_tokenCache(t, true)
  314. })
  315. t.Run("ecdsaSupport=false", func(t *testing.T) {
  316. testGetCertificate_tokenCache(t, false)
  317. })
  318. }
  319. func TestGetCertificate_ecdsaVsRSA(t *testing.T) {
  320. cache := newMemCache(t)
  321. man := &Manager{Prompt: AcceptTOS, Cache: cache}
  322. defer man.stopRenew()
  323. url, finish := startACMEServerStub(t, getCertificateFromManager(man, true), "example.org")
  324. defer finish()
  325. man.Client = &acme.Client{DirectoryURL: url}
  326. cert, err := man.GetCertificate(clientHelloInfo("example.org", true))
  327. if err != nil {
  328. t.Error(err)
  329. }
  330. if _, ok := cert.Leaf.PublicKey.(*ecdsa.PublicKey); !ok {
  331. t.Error("an ECDSA client was served a non-ECDSA certificate")
  332. }
  333. cert, err = man.GetCertificate(clientHelloInfo("example.org", false))
  334. if err != nil {
  335. t.Error(err)
  336. }
  337. if _, ok := cert.Leaf.PublicKey.(*rsa.PublicKey); !ok {
  338. t.Error("a RSA client was served a non-RSA certificate")
  339. }
  340. if _, err := man.GetCertificate(clientHelloInfo("example.org", true)); err != nil {
  341. t.Error(err)
  342. }
  343. if _, err := man.GetCertificate(clientHelloInfo("example.org", false)); err != nil {
  344. t.Error(err)
  345. }
  346. if numCerts := cache.numCerts(); numCerts != 2 {
  347. t.Errorf("found %d certificates in cache; want %d", numCerts, 2)
  348. }
  349. }
  350. func TestGetCertificate_wrongCacheKeyType(t *testing.T) {
  351. cache := newMemCache(t)
  352. man := &Manager{Prompt: AcceptTOS, Cache: cache}
  353. defer man.stopRenew()
  354. url, finish := startACMEServerStub(t, getCertificateFromManager(man, true), exampleDomain)
  355. defer finish()
  356. man.Client = &acme.Client{DirectoryURL: url}
  357. // Make an RSA cert and cache it without suffix.
  358. pk, err := rsa.GenerateKey(rand.Reader, 512)
  359. if err != nil {
  360. t.Fatal(err)
  361. }
  362. tmpl := &x509.Certificate{
  363. SerialNumber: big.NewInt(1),
  364. Subject: pkix.Name{CommonName: exampleDomain},
  365. NotAfter: time.Now().Add(90 * 24 * time.Hour),
  366. }
  367. pub, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &pk.PublicKey, pk)
  368. if err != nil {
  369. t.Fatal(err)
  370. }
  371. rsaCert := &tls.Certificate{
  372. Certificate: [][]byte{pub},
  373. PrivateKey: pk,
  374. }
  375. if err := man.cachePut(context.Background(), exampleCertKey, rsaCert); err != nil {
  376. t.Fatalf("man.cachePut: %v", err)
  377. }
  378. // The RSA cached cert should be silently ignored and replaced.
  379. cert, err := man.GetCertificate(clientHelloInfo(exampleDomain, true))
  380. if err != nil {
  381. t.Error(err)
  382. }
  383. if _, ok := cert.Leaf.PublicKey.(*ecdsa.PublicKey); !ok {
  384. t.Error("an ECDSA client was served a non-ECDSA certificate")
  385. }
  386. if numCerts := cache.numCerts(); numCerts != 1 {
  387. t.Errorf("found %d certificates in cache; want %d", numCerts, 1)
  388. }
  389. }
  390. func getCertificateFromManager(man *Manager, ecdsaSupport bool) func(string) error {
  391. return func(sni string) error {
  392. _, err := man.GetCertificate(clientHelloInfo(sni, ecdsaSupport))
  393. return err
  394. }
  395. }
  396. // startACMEServerStub runs an ACME server
  397. // The domain argument is the expected domain name of a certificate request.
  398. func startACMEServerStub(t *testing.T, getCertificate func(string) error, domain string) (url string, finish func()) {
  399. // echo token-02 | shasum -a 256
  400. // then divide result in 2 parts separated by dot
  401. tokenCertName := "4e8eb87631187e9ff2153b56b13a4dec.13a35d002e485d60ff37354b32f665d9.token.acme.invalid"
  402. verifyTokenCert := func() {
  403. if err := getCertificate(tokenCertName); err != nil {
  404. t.Errorf("verifyTokenCert: GetCertificate(%q): %v", tokenCertName, err)
  405. return
  406. }
  407. }
  408. // ACME CA server stub
  409. var ca *httptest.Server
  410. ca = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  411. w.Header().Set("Replay-Nonce", "nonce")
  412. if r.Method == "HEAD" {
  413. // a nonce request
  414. return
  415. }
  416. switch r.URL.Path {
  417. // discovery
  418. case "/":
  419. if err := discoTmpl.Execute(w, ca.URL); err != nil {
  420. t.Errorf("discoTmpl: %v", err)
  421. }
  422. // client key registration
  423. case "/new-reg":
  424. w.Write([]byte("{}"))
  425. // domain authorization
  426. case "/new-authz":
  427. w.Header().Set("Location", ca.URL+"/authz/1")
  428. w.WriteHeader(http.StatusCreated)
  429. if err := authzTmpl.Execute(w, ca.URL); err != nil {
  430. t.Errorf("authzTmpl: %v", err)
  431. }
  432. // accept tls-sni-02 challenge
  433. case "/challenge/2":
  434. verifyTokenCert()
  435. w.Write([]byte("{}"))
  436. // authorization status
  437. case "/authz/1":
  438. w.Write([]byte(`{"status": "valid"}`))
  439. // cert request
  440. case "/new-cert":
  441. var req struct {
  442. CSR string `json:"csr"`
  443. }
  444. decodePayload(&req, r.Body)
  445. b, _ := base64.RawURLEncoding.DecodeString(req.CSR)
  446. csr, err := x509.ParseCertificateRequest(b)
  447. if err != nil {
  448. t.Errorf("new-cert: CSR: %v", err)
  449. }
  450. if csr.Subject.CommonName != domain {
  451. t.Errorf("CommonName in CSR = %q; want %q", csr.Subject.CommonName, domain)
  452. }
  453. der, err := dummyCert(csr.PublicKey, domain)
  454. if err != nil {
  455. t.Errorf("new-cert: dummyCert: %v", err)
  456. }
  457. chainUp := fmt.Sprintf("<%s/ca-cert>; rel=up", ca.URL)
  458. w.Header().Set("Link", chainUp)
  459. w.WriteHeader(http.StatusCreated)
  460. w.Write(der)
  461. // CA chain cert
  462. case "/ca-cert":
  463. der, err := dummyCert(nil, "ca")
  464. if err != nil {
  465. t.Errorf("ca-cert: dummyCert: %v", err)
  466. }
  467. w.Write(der)
  468. default:
  469. t.Errorf("unrecognized r.URL.Path: %s", r.URL.Path)
  470. }
  471. }))
  472. finish = func() {
  473. ca.Close()
  474. // make sure token cert was removed
  475. cancel := make(chan struct{})
  476. done := make(chan struct{})
  477. go func() {
  478. defer close(done)
  479. tick := time.NewTicker(100 * time.Millisecond)
  480. defer tick.Stop()
  481. for {
  482. if err := getCertificate(tokenCertName); err != nil {
  483. return
  484. }
  485. select {
  486. case <-tick.C:
  487. case <-cancel:
  488. return
  489. }
  490. }
  491. }()
  492. select {
  493. case <-done:
  494. case <-time.After(5 * time.Second):
  495. close(cancel)
  496. t.Error("token cert was not removed")
  497. <-done
  498. }
  499. }
  500. return ca.URL, finish
  501. }
  502. // tests man.GetCertificate flow using the provided hello argument.
  503. // The domain argument is the expected domain name of a certificate request.
  504. func testGetCertificate(t *testing.T, man *Manager, domain string, hello *tls.ClientHelloInfo) {
  505. url, finish := startACMEServerStub(t, getCertificateFromManager(man, true), domain)
  506. defer finish()
  507. man.Client = &acme.Client{DirectoryURL: url}
  508. // simulate tls.Config.GetCertificate
  509. var tlscert *tls.Certificate
  510. var err error
  511. done := make(chan struct{})
  512. go func() {
  513. tlscert, err = man.GetCertificate(hello)
  514. close(done)
  515. }()
  516. select {
  517. case <-time.After(time.Minute):
  518. t.Fatal("man.GetCertificate took too long to return")
  519. case <-done:
  520. }
  521. if err != nil {
  522. t.Fatalf("man.GetCertificate: %v", err)
  523. }
  524. // verify the tlscert is the same we responded with from the CA stub
  525. if len(tlscert.Certificate) == 0 {
  526. t.Fatal("len(tlscert.Certificate) is 0")
  527. }
  528. cert, err := x509.ParseCertificate(tlscert.Certificate[0])
  529. if err != nil {
  530. t.Fatalf("x509.ParseCertificate: %v", err)
  531. }
  532. if len(cert.DNSNames) == 0 || cert.DNSNames[0] != domain {
  533. t.Errorf("cert.DNSNames = %v; want %q", cert.DNSNames, domain)
  534. }
  535. }
  536. func TestVerifyHTTP01(t *testing.T) {
  537. var (
  538. http01 http.Handler
  539. authzCount int // num. of created authorizations
  540. didAcceptHTTP01 bool
  541. )
  542. verifyHTTPToken := func() {
  543. r := httptest.NewRequest("GET", "/.well-known/acme-challenge/token-http-01", nil)
  544. w := httptest.NewRecorder()
  545. http01.ServeHTTP(w, r)
  546. if w.Code != http.StatusOK {
  547. t.Errorf("http token: w.Code = %d; want %d", w.Code, http.StatusOK)
  548. }
  549. if v := w.Body.String(); !strings.HasPrefix(v, "token-http-01.") {
  550. t.Errorf("http token value = %q; want 'token-http-01.' prefix", v)
  551. }
  552. }
  553. // ACME CA server stub, only the needed bits.
  554. // TODO: Merge this with startACMEServerStub, making it a configurable CA for testing.
  555. var ca *httptest.Server
  556. ca = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  557. w.Header().Set("Replay-Nonce", "nonce")
  558. if r.Method == "HEAD" {
  559. // a nonce request
  560. return
  561. }
  562. switch r.URL.Path {
  563. // Discovery.
  564. case "/":
  565. if err := discoTmpl.Execute(w, ca.URL); err != nil {
  566. t.Errorf("discoTmpl: %v", err)
  567. }
  568. // Client key registration.
  569. case "/new-reg":
  570. w.Write([]byte("{}"))
  571. // New domain authorization.
  572. case "/new-authz":
  573. authzCount++
  574. w.Header().Set("Location", fmt.Sprintf("%s/authz/%d", ca.URL, authzCount))
  575. w.WriteHeader(http.StatusCreated)
  576. if err := authzTmpl.Execute(w, ca.URL); err != nil {
  577. t.Errorf("authzTmpl: %v", err)
  578. }
  579. // Accept tls-sni-02.
  580. case "/challenge/2":
  581. w.Write([]byte("{}"))
  582. // Reject tls-sni-01.
  583. case "/challenge/1":
  584. http.Error(w, "won't accept tls-sni-01", http.StatusBadRequest)
  585. // Should not accept dns-01.
  586. case "/challenge/dns-01":
  587. t.Errorf("dns-01 challenge was accepted")
  588. http.Error(w, "won't accept dns-01", http.StatusBadRequest)
  589. // Accept http-01.
  590. case "/challenge/http-01":
  591. didAcceptHTTP01 = true
  592. verifyHTTPToken()
  593. w.Write([]byte("{}"))
  594. // Authorization statuses.
  595. // Make tls-sni-xxx invalid.
  596. case "/authz/1", "/authz/2":
  597. w.Write([]byte(`{"status": "invalid"}`))
  598. case "/authz/3", "/authz/4":
  599. w.Write([]byte(`{"status": "valid"}`))
  600. default:
  601. http.NotFound(w, r)
  602. t.Errorf("unrecognized r.URL.Path: %s", r.URL.Path)
  603. }
  604. }))
  605. defer ca.Close()
  606. m := &Manager{
  607. Client: &acme.Client{
  608. DirectoryURL: ca.URL,
  609. },
  610. }
  611. http01 = m.HTTPHandler(nil)
  612. ctx := context.Background()
  613. client, err := m.acmeClient(ctx)
  614. if err != nil {
  615. t.Fatalf("m.acmeClient: %v", err)
  616. }
  617. if err := m.verify(ctx, client, "example.org"); err != nil {
  618. t.Errorf("m.verify: %v", err)
  619. }
  620. // Only tls-sni-01, tls-sni-02 and http-01 must be accepted
  621. // The dns-01 challenge is unsupported.
  622. if authzCount != 3 {
  623. t.Errorf("authzCount = %d; want 3", authzCount)
  624. }
  625. if !didAcceptHTTP01 {
  626. t.Error("did not accept http-01 challenge")
  627. }
  628. }
  629. func TestRevokeFailedAuthz(t *testing.T) {
  630. // Prefill authorization URIs expected to be revoked.
  631. // The challenges are selected in a specific order,
  632. // each tried within a newly created authorization.
  633. // This means each authorization URI corresponds to a different challenge type.
  634. revokedAuthz := map[string]bool{
  635. "/authz/0": false, // tls-sni-02
  636. "/authz/1": false, // tls-sni-01
  637. "/authz/2": false, // no viable challenge, but authz is created
  638. }
  639. var authzCount int // num. of created authorizations
  640. var revokeCount int // num. of revoked authorizations
  641. done := make(chan struct{}) // closed when revokeCount is 3
  642. // ACME CA server stub, only the needed bits.
  643. // TODO: Merge this with startACMEServerStub, making it a configurable CA for testing.
  644. var ca *httptest.Server
  645. ca = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  646. w.Header().Set("Replay-Nonce", "nonce")
  647. if r.Method == "HEAD" {
  648. // a nonce request
  649. return
  650. }
  651. switch r.URL.Path {
  652. // Discovery.
  653. case "/":
  654. if err := discoTmpl.Execute(w, ca.URL); err != nil {
  655. t.Errorf("discoTmpl: %v", err)
  656. }
  657. // Client key registration.
  658. case "/new-reg":
  659. w.Write([]byte("{}"))
  660. // New domain authorization.
  661. case "/new-authz":
  662. w.Header().Set("Location", fmt.Sprintf("%s/authz/%d", ca.URL, authzCount))
  663. w.WriteHeader(http.StatusCreated)
  664. if err := authzTmpl.Execute(w, ca.URL); err != nil {
  665. t.Errorf("authzTmpl: %v", err)
  666. }
  667. authzCount++
  668. // tls-sni-02 challenge "accept" request.
  669. case "/challenge/2":
  670. // Refuse.
  671. http.Error(w, "won't accept tls-sni-02 challenge", http.StatusBadRequest)
  672. // tls-sni-01 challenge "accept" request.
  673. case "/challenge/1":
  674. // Accept but the authorization will be "expired".
  675. w.Write([]byte("{}"))
  676. // Authorization requests.
  677. case "/authz/0", "/authz/1", "/authz/2":
  678. // Revocation requests.
  679. if r.Method == "POST" {
  680. var req struct{ Status string }
  681. if err := decodePayload(&req, r.Body); err != nil {
  682. t.Errorf("%s: decodePayload: %v", r.URL, err)
  683. }
  684. switch req.Status {
  685. case "deactivated":
  686. revokedAuthz[r.URL.Path] = true
  687. revokeCount++
  688. if revokeCount >= 3 {
  689. // Last authorization is revoked.
  690. defer close(done)
  691. }
  692. default:
  693. t.Errorf("%s: req.Status = %q; want 'deactivated'", r.URL, req.Status)
  694. }
  695. w.Write([]byte(`{"status": "invalid"}`))
  696. return
  697. }
  698. // Authorization status requests.
  699. // Simulate abandoned authorization, deleted by the CA.
  700. w.WriteHeader(http.StatusNotFound)
  701. default:
  702. http.NotFound(w, r)
  703. t.Errorf("unrecognized r.URL.Path: %s", r.URL.Path)
  704. }
  705. }))
  706. defer ca.Close()
  707. m := &Manager{
  708. Client: &acme.Client{DirectoryURL: ca.URL},
  709. }
  710. // Should fail and revoke 3 authorizations.
  711. // The first 2 are tsl-sni-02 and tls-sni-01 challenges.
  712. // The third time an authorization is created but no viable challenge is found.
  713. // See revokedAuthz above for more explanation.
  714. if _, err := m.createCert(context.Background(), exampleCertKey); err == nil {
  715. t.Errorf("m.createCert returned nil error")
  716. }
  717. select {
  718. case <-time.After(3 * time.Second):
  719. t.Error("revocations took too long")
  720. case <-done:
  721. // revokeCount is at least 3.
  722. }
  723. for uri, ok := range revokedAuthz {
  724. if !ok {
  725. t.Errorf("%q authorization was not revoked", uri)
  726. }
  727. }
  728. }
  729. func TestHTTPHandlerDefaultFallback(t *testing.T) {
  730. tt := []struct {
  731. method, url string
  732. wantCode int
  733. wantLocation string
  734. }{
  735. {"GET", "http://example.org", 302, "https://example.org/"},
  736. {"GET", "http://example.org/foo", 302, "https://example.org/foo"},
  737. {"GET", "http://example.org/foo/bar/", 302, "https://example.org/foo/bar/"},
  738. {"GET", "http://example.org/?a=b", 302, "https://example.org/?a=b"},
  739. {"GET", "http://example.org/foo?a=b", 302, "https://example.org/foo?a=b"},
  740. {"GET", "http://example.org:80/foo?a=b", 302, "https://example.org:443/foo?a=b"},
  741. {"GET", "http://example.org:80/foo%20bar", 302, "https://example.org:443/foo%20bar"},
  742. {"GET", "http://[2602:d1:xxxx::c60a]:1234", 302, "https://[2602:d1:xxxx::c60a]:443/"},
  743. {"GET", "http://[2602:d1:xxxx::c60a]", 302, "https://[2602:d1:xxxx::c60a]/"},
  744. {"GET", "http://[2602:d1:xxxx::c60a]/foo?a=b", 302, "https://[2602:d1:xxxx::c60a]/foo?a=b"},
  745. {"HEAD", "http://example.org", 302, "https://example.org/"},
  746. {"HEAD", "http://example.org/foo", 302, "https://example.org/foo"},
  747. {"HEAD", "http://example.org/foo/bar/", 302, "https://example.org/foo/bar/"},
  748. {"HEAD", "http://example.org/?a=b", 302, "https://example.org/?a=b"},
  749. {"HEAD", "http://example.org/foo?a=b", 302, "https://example.org/foo?a=b"},
  750. {"POST", "http://example.org", 400, ""},
  751. {"PUT", "http://example.org", 400, ""},
  752. {"GET", "http://example.org/.well-known/acme-challenge/x", 404, ""},
  753. }
  754. var m Manager
  755. h := m.HTTPHandler(nil)
  756. for i, test := range tt {
  757. r := httptest.NewRequest(test.method, test.url, nil)
  758. w := httptest.NewRecorder()
  759. h.ServeHTTP(w, r)
  760. if w.Code != test.wantCode {
  761. t.Errorf("%d: w.Code = %d; want %d", i, w.Code, test.wantCode)
  762. t.Errorf("%d: body: %s", i, w.Body.Bytes())
  763. }
  764. if v := w.Header().Get("Location"); v != test.wantLocation {
  765. t.Errorf("%d: Location = %q; want %q", i, v, test.wantLocation)
  766. }
  767. }
  768. }
  769. func TestAccountKeyCache(t *testing.T) {
  770. m := Manager{Cache: newMemCache(t)}
  771. ctx := context.Background()
  772. k1, err := m.accountKey(ctx)
  773. if err != nil {
  774. t.Fatal(err)
  775. }
  776. k2, err := m.accountKey(ctx)
  777. if err != nil {
  778. t.Fatal(err)
  779. }
  780. if !reflect.DeepEqual(k1, k2) {
  781. t.Errorf("account keys don't match: k1 = %#v; k2 = %#v", k1, k2)
  782. }
  783. }
  784. func TestCache(t *testing.T) {
  785. ecdsaKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  786. if err != nil {
  787. t.Fatal(err)
  788. }
  789. cert, err := dummyCert(ecdsaKey.Public(), exampleDomain)
  790. if err != nil {
  791. t.Fatal(err)
  792. }
  793. ecdsaCert := &tls.Certificate{
  794. Certificate: [][]byte{cert},
  795. PrivateKey: ecdsaKey,
  796. }
  797. rsaKey, err := rsa.GenerateKey(rand.Reader, 512)
  798. if err != nil {
  799. t.Fatal(err)
  800. }
  801. cert, err = dummyCert(rsaKey.Public(), exampleDomain)
  802. if err != nil {
  803. t.Fatal(err)
  804. }
  805. rsaCert := &tls.Certificate{
  806. Certificate: [][]byte{cert},
  807. PrivateKey: rsaKey,
  808. }
  809. man := &Manager{Cache: newMemCache(t)}
  810. defer man.stopRenew()
  811. ctx := context.Background()
  812. if err := man.cachePut(ctx, exampleCertKey, ecdsaCert); err != nil {
  813. t.Fatalf("man.cachePut: %v", err)
  814. }
  815. if err := man.cachePut(ctx, exampleCertKeyRSA, rsaCert); err != nil {
  816. t.Fatalf("man.cachePut: %v", err)
  817. }
  818. res, err := man.cacheGet(ctx, exampleCertKey)
  819. if err != nil {
  820. t.Fatalf("man.cacheGet: %v", err)
  821. }
  822. if res == nil || !bytes.Equal(res.Certificate[0], ecdsaCert.Certificate[0]) {
  823. t.Errorf("man.cacheGet = %+v; want %+v", res, ecdsaCert)
  824. }
  825. res, err = man.cacheGet(ctx, exampleCertKeyRSA)
  826. if err != nil {
  827. t.Fatalf("man.cacheGet: %v", err)
  828. }
  829. if res == nil || !bytes.Equal(res.Certificate[0], rsaCert.Certificate[0]) {
  830. t.Errorf("man.cacheGet = %+v; want %+v", res, rsaCert)
  831. }
  832. }
  833. func TestHostWhitelist(t *testing.T) {
  834. policy := HostWhitelist("example.com", "example.org", "*.example.net")
  835. tt := []struct {
  836. host string
  837. allow bool
  838. }{
  839. {"example.com", true},
  840. {"example.org", true},
  841. {"one.example.com", false},
  842. {"two.example.org", false},
  843. {"three.example.net", false},
  844. {"dummy", false},
  845. }
  846. for i, test := range tt {
  847. err := policy(nil, test.host)
  848. if err != nil && test.allow {
  849. t.Errorf("%d: policy(%q): %v; want nil", i, test.host, err)
  850. }
  851. if err == nil && !test.allow {
  852. t.Errorf("%d: policy(%q): nil; want an error", i, test.host)
  853. }
  854. }
  855. }
  856. func TestValidCert(t *testing.T) {
  857. key1, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  858. if err != nil {
  859. t.Fatal(err)
  860. }
  861. key2, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  862. if err != nil {
  863. t.Fatal(err)
  864. }
  865. key3, err := rsa.GenerateKey(rand.Reader, 512)
  866. if err != nil {
  867. t.Fatal(err)
  868. }
  869. cert1, err := dummyCert(key1.Public(), "example.org")
  870. if err != nil {
  871. t.Fatal(err)
  872. }
  873. cert2, err := dummyCert(key2.Public(), "example.org")
  874. if err != nil {
  875. t.Fatal(err)
  876. }
  877. cert3, err := dummyCert(key3.Public(), "example.org")
  878. if err != nil {
  879. t.Fatal(err)
  880. }
  881. now := time.Now()
  882. early, err := dateDummyCert(key1.Public(), now.Add(time.Hour), now.Add(2*time.Hour), "example.org")
  883. if err != nil {
  884. t.Fatal(err)
  885. }
  886. expired, err := dateDummyCert(key1.Public(), now.Add(-2*time.Hour), now.Add(-time.Hour), "example.org")
  887. if err != nil {
  888. t.Fatal(err)
  889. }
  890. tt := []struct {
  891. ck certKey
  892. key crypto.Signer
  893. cert [][]byte
  894. ok bool
  895. }{
  896. {certKey{domain: "example.org"}, key1, [][]byte{cert1}, true},
  897. {certKey{domain: "example.org", isRSA: true}, key3, [][]byte{cert3}, true},
  898. {certKey{domain: "example.org"}, key1, [][]byte{cert1, cert2, cert3}, true},
  899. {certKey{domain: "example.org"}, key1, [][]byte{cert1, {1}}, false},
  900. {certKey{domain: "example.org"}, key1, [][]byte{{1}}, false},
  901. {certKey{domain: "example.org"}, key1, [][]byte{cert2}, false},
  902. {certKey{domain: "example.org"}, key2, [][]byte{cert1}, false},
  903. {certKey{domain: "example.org"}, key1, [][]byte{cert3}, false},
  904. {certKey{domain: "example.org"}, key3, [][]byte{cert1}, false},
  905. {certKey{domain: "example.net"}, key1, [][]byte{cert1}, false},
  906. {certKey{domain: "example.org"}, key1, [][]byte{early}, false},
  907. {certKey{domain: "example.org"}, key1, [][]byte{expired}, false},
  908. {certKey{domain: "example.org", isRSA: true}, key1, [][]byte{cert1}, false},
  909. {certKey{domain: "example.org"}, key3, [][]byte{cert3}, false},
  910. }
  911. for i, test := range tt {
  912. leaf, err := validCert(test.ck, test.cert, test.key)
  913. if err != nil && test.ok {
  914. t.Errorf("%d: err = %v", i, err)
  915. }
  916. if err == nil && !test.ok {
  917. t.Errorf("%d: err is nil", i)
  918. }
  919. if err == nil && test.ok && leaf == nil {
  920. t.Errorf("%d: leaf is nil", i)
  921. }
  922. }
  923. }
  924. type cacheGetFunc func(ctx context.Context, key string) ([]byte, error)
  925. func (f cacheGetFunc) Get(ctx context.Context, key string) ([]byte, error) {
  926. return f(ctx, key)
  927. }
  928. func (f cacheGetFunc) Put(ctx context.Context, key string, data []byte) error {
  929. return fmt.Errorf("unsupported Put of %q = %q", key, data)
  930. }
  931. func (f cacheGetFunc) Delete(ctx context.Context, key string) error {
  932. return fmt.Errorf("unsupported Delete of %q", key)
  933. }
  934. func TestManagerGetCertificateBogusSNI(t *testing.T) {
  935. m := Manager{
  936. Prompt: AcceptTOS,
  937. Cache: cacheGetFunc(func(ctx context.Context, key string) ([]byte, error) {
  938. return nil, fmt.Errorf("cache.Get of %s", key)
  939. }),
  940. }
  941. tests := []struct {
  942. name string
  943. wantErr string
  944. }{
  945. {"foo.com", "cache.Get of foo.com"},
  946. {"foo.com.", "cache.Get of foo.com"},
  947. {`a\b.com`, "acme/autocert: server name contains invalid character"},
  948. {`a/b.com`, "acme/autocert: server name contains invalid character"},
  949. {"", "acme/autocert: missing server name"},
  950. {"foo", "acme/autocert: server name component count invalid"},
  951. {".foo", "acme/autocert: server name component count invalid"},
  952. {"foo.", "acme/autocert: server name component count invalid"},
  953. {"fo.o", "cache.Get of fo.o"},
  954. }
  955. for _, tt := range tests {
  956. _, err := m.GetCertificate(clientHelloInfo(tt.name, true))
  957. got := fmt.Sprint(err)
  958. if got != tt.wantErr {
  959. t.Errorf("GetCertificate(SNI = %q) = %q; want %q", tt.name, got, tt.wantErr)
  960. }
  961. }
  962. }
  963. func TestCertRequest(t *testing.T) {
  964. key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  965. if err != nil {
  966. t.Fatal(err)
  967. }
  968. // An extension from RFC7633. Any will do.
  969. ext := pkix.Extension{
  970. Id: asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1},
  971. Value: []byte("dummy"),
  972. }
  973. b, err := certRequest(key, "example.org", []pkix.Extension{ext}, "san.example.org")
  974. if err != nil {
  975. t.Fatalf("certRequest: %v", err)
  976. }
  977. r, err := x509.ParseCertificateRequest(b)
  978. if err != nil {
  979. t.Fatalf("ParseCertificateRequest: %v", err)
  980. }
  981. var found bool
  982. for _, v := range r.Extensions {
  983. if v.Id.Equal(ext.Id) {
  984. found = true
  985. break
  986. }
  987. }
  988. if !found {
  989. t.Errorf("want %v in Extensions: %v", ext, r.Extensions)
  990. }
  991. }
  992. func TestSupportsECDSA(t *testing.T) {
  993. tests := []struct {
  994. CipherSuites []uint16
  995. SignatureSchemes []tls.SignatureScheme
  996. SupportedCurves []tls.CurveID
  997. ecdsaOk bool
  998. }{
  999. {[]uint16{
  1000. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1001. }, nil, nil, false},
  1002. {[]uint16{
  1003. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  1004. }, nil, nil, true},
  1005. // SignatureSchemes limits, not extends, CipherSuites
  1006. {[]uint16{
  1007. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1008. }, []tls.SignatureScheme{
  1009. tls.PKCS1WithSHA256, tls.ECDSAWithP256AndSHA256,
  1010. }, nil, false},
  1011. {[]uint16{
  1012. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  1013. }, []tls.SignatureScheme{
  1014. tls.PKCS1WithSHA256,
  1015. }, nil, false},
  1016. {[]uint16{
  1017. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  1018. }, []tls.SignatureScheme{
  1019. tls.PKCS1WithSHA256, tls.ECDSAWithP256AndSHA256,
  1020. }, nil, true},
  1021. {[]uint16{
  1022. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  1023. }, []tls.SignatureScheme{
  1024. tls.PKCS1WithSHA256, tls.ECDSAWithP256AndSHA256,
  1025. }, []tls.CurveID{
  1026. tls.CurveP521,
  1027. }, false},
  1028. {[]uint16{
  1029. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  1030. }, []tls.SignatureScheme{
  1031. tls.PKCS1WithSHA256, tls.ECDSAWithP256AndSHA256,
  1032. }, []tls.CurveID{
  1033. tls.CurveP256,
  1034. tls.CurveP521,
  1035. }, true},
  1036. }
  1037. for i, tt := range tests {
  1038. result := supportsECDSA(&tls.ClientHelloInfo{
  1039. CipherSuites: tt.CipherSuites,
  1040. SignatureSchemes: tt.SignatureSchemes,
  1041. SupportedCurves: tt.SupportedCurves,
  1042. })
  1043. if result != tt.ecdsaOk {
  1044. t.Errorf("%d: supportsECDSA = %v; want %v", i, result, tt.ecdsaOk)
  1045. }
  1046. }
  1047. }