customcert_test.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. package tlsmode
  2. // FORK: #1756 - a certificate from disk replaces the private CA. Names and
  3. // paths are invented.
  4. import (
  5. "crypto/ecdsa"
  6. "crypto/elliptic"
  7. "crypto/rand"
  8. "crypto/x509"
  9. "crypto/x509/pkix"
  10. "encoding/pem"
  11. "math/big"
  12. "net"
  13. "net/http"
  14. "os"
  15. "path/filepath"
  16. "strings"
  17. "testing"
  18. "time"
  19. )
  20. // writePair leaves a self-signed certificate and its key in dir.
  21. func writePair(t *testing.T, dir, name string) (string, string) {
  22. t.Helper()
  23. key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  24. if err != nil {
  25. t.Fatal(err)
  26. }
  27. tmpl := &x509.Certificate{
  28. SerialNumber: big.NewInt(7),
  29. Subject: pkix.Name{CommonName: name},
  30. DNSNames: []string{name},
  31. IPAddresses: []net.IP{net.ParseIP("192.168.50.2")},
  32. NotBefore: time.Now().Add(-time.Hour),
  33. NotAfter: time.Now().Add(24 * time.Hour),
  34. KeyUsage: x509.KeyUsageDigitalSignature,
  35. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  36. BasicConstraintsValid: true,
  37. }
  38. der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
  39. if err != nil {
  40. t.Fatal(err)
  41. }
  42. kb, err := x509.MarshalECPrivateKey(key)
  43. if err != nil {
  44. t.Fatal(err)
  45. }
  46. certPath := filepath.Join(dir, name+".crt")
  47. keyPath := filepath.Join(dir, name+".key")
  48. if err := os.WriteFile(certPath, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0o600); err != nil {
  49. t.Fatal(err)
  50. }
  51. if err := os.WriteFile(keyPath, pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: kb}), 0o600); err != nil {
  52. t.Fatal(err)
  53. }
  54. return certPath, keyPath
  55. }
  56. func TestACertificateFromDiskReplacesTheCA(t *testing.T) {
  57. r := newRig(t, nil)
  58. if err := r.m.SetEnabled(true, "test"); err != nil {
  59. t.Fatal(err)
  60. }
  61. certPath, keyPath := writePair(t, t.TempDir(), "monitor-box")
  62. if err := r.m.SetCertificate(certPath, keyPath, "test"); err != nil {
  63. t.Fatal(err)
  64. }
  65. st := r.m.Status()
  66. if st.CertSource != "custom" || st.CertPath != certPath || st.KeyPath != keyPath {
  67. t.Fatalf("status does not point at the pair: %+v", st)
  68. }
  69. if st.RootSHA256 != "" || len(st.Uncovered) != 0 {
  70. t.Errorf("a certificate from disk has no root of ours to hand out: %+v", st)
  71. }
  72. if len(st.Names) != 2 || st.Names[0] != "monitor-box" || st.Names[1] != "192.168.50.2" {
  73. t.Errorf("names of the served leaf: %v", st.Names)
  74. }
  75. if st.Fingerprint == "" || st.Fingerprint != r.m.Fingerprint() {
  76. t.Errorf("pin: status %q, manager %q", st.Fingerprint, r.m.Fingerprint())
  77. }
  78. // The listener serves it: the rig pins whatever the manager reports, so
  79. // a handshake only succeeds if the served leaf is the one on disk.
  80. if body, err := r.getTLS("/"); err != nil {
  81. t.Fatalf("the listener does not serve the new pair: %v", err)
  82. } else if body != "tls=true" {
  83. t.Fatalf("body %q", body)
  84. }
  85. // Going back to the CA brings its root back.
  86. if err := r.m.SetCertificate("", "", "test"); err != nil {
  87. t.Fatal(err)
  88. }
  89. if st := r.m.Status(); st.CertSource != "ca" || st.RootSHA256 == "" {
  90. t.Fatalf("back to the CA: %+v", st)
  91. }
  92. if _, err := r.getTLS("/"); err != nil {
  93. t.Fatalf("the CA listener did not come back: %v", err)
  94. }
  95. }
  96. func TestABadPairLeavesTheListenerAlone(t *testing.T) {
  97. r := newRig(t, nil)
  98. if err := r.m.SetEnabled(true, "test"); err != nil {
  99. t.Fatal(err)
  100. }
  101. before, beforeStatus := r.m.Fingerprint(), r.m.Status()
  102. for name, err := range map[string]error{
  103. "missing file": r.m.SetCertificate(filepath.Join(t.TempDir(), "nope.crt"), filepath.Join(t.TempDir(), "nope.key"), "test"),
  104. "relative path": r.m.SetCertificate("cert.pem", "key.pem", "test"),
  105. "only one of two": r.m.SetCertificate(filepath.Join(t.TempDir(), "nope.crt"), "", "test"),
  106. } {
  107. if err == nil {
  108. t.Errorf("%s: no error", name)
  109. }
  110. }
  111. if got := r.m.Fingerprint(); got != before {
  112. t.Errorf("the pin changed after a rejected pair: %q -> %q", before, got)
  113. }
  114. if st := r.m.Status(); st.CertSource != beforeStatus.CertSource {
  115. t.Errorf("the source changed after a rejected pair: %q", st.CertSource)
  116. }
  117. if _, err := r.getTLS("/"); err != nil {
  118. t.Fatalf("the listener stopped serving: %v", err)
  119. }
  120. }
  121. func TestAgentTrustWithACertificateFromDisk(t *testing.T) {
  122. r := newRig(t, nil)
  123. if err := r.m.SetEnabled(true, "test"); err != nil {
  124. t.Fatal(err)
  125. }
  126. certPath, keyPath := writePair(t, t.TempDir(), "monitor-box")
  127. if err := r.m.SetCertificate(certPath, keyPath, "test"); err != nil {
  128. t.Fatal(err)
  129. }
  130. tr := AgentTrust(r.m, func() string { return "legacy-pin" }, "http://192.168.50.2:3000")
  131. if tr.ServerURL == "" {
  132. t.Fatal("no HTTPS URL with a certificate from disk")
  133. }
  134. if tr.ServerFP != r.m.Fingerprint() {
  135. t.Errorf("pin %q, want the served leaf %q", tr.ServerFP, r.m.Fingerprint())
  136. }
  137. if len(tr.CAPEM) != 0 {
  138. t.Errorf("there is no root to hand out, got %d bytes", len(tr.CAPEM))
  139. }
  140. }
  141. func TestRenewRefusesACertificateFromDisk(t *testing.T) {
  142. r := newRig(t, nil)
  143. if err := r.m.SetEnabled(true, "test"); err != nil {
  144. t.Fatal(err)
  145. }
  146. certPath, keyPath := writePair(t, t.TempDir(), "monitor-box")
  147. if err := r.m.SetCertificate(certPath, keyPath, "test"); err != nil {
  148. t.Fatal(err)
  149. }
  150. if _, err := r.m.Renew("test"); err == nil || !strings.Contains(err.Error(), "file") {
  151. t.Fatalf("renew: %v", err)
  152. }
  153. }
  154. // The pair survives a restart: a new manager on the same database serves it
  155. // without going through the UI again.
  156. func TestACertificateFromDiskSurvivesARestart(t *testing.T) {
  157. r := newRig(t, nil)
  158. if err := r.m.SetEnabled(true, "test"); err != nil {
  159. t.Fatal(err)
  160. }
  161. certPath, keyPath := writePair(t, t.TempDir(), "monitor-box")
  162. if err := r.m.SetCertificate(certPath, keyPath, "test"); err != nil {
  163. t.Fatal(err)
  164. }
  165. want := r.m.Fingerprint()
  166. r.m.Close()
  167. opts := Options{
  168. DB: r.db, DataDir: r.dir, Port: r.port,
  169. NewServer: func(addr string, h http.Handler) *http.Server {
  170. return &http.Server{Addr: addr, Handler: h, ReadHeaderTimeout: 5 * time.Second}
  171. },
  172. Now: func() time.Time { return r.now },
  173. }
  174. m := New(opts)
  175. if err := m.Start(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) })); err != nil {
  176. t.Fatal(err)
  177. }
  178. t.Cleanup(m.Close)
  179. if st := m.Status(); st.CertSource != "custom" || st.CertPath != certPath {
  180. t.Fatalf("after a restart: %+v", st)
  181. }
  182. if got := m.Fingerprint(); got != want {
  183. t.Errorf("pin after a restart: %q, want %q", got, want)
  184. }
  185. }