ca_test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. package tlscert
  2. // FORK: tests for the private CA. Addresses are from the documentation and
  3. // private ranges, names invented.
  4. import (
  5. "crypto/ecdsa"
  6. "crypto/elliptic"
  7. "crypto/rand"
  8. "crypto/tls"
  9. "crypto/x509"
  10. "crypto/x509/pkix"
  11. "fmt"
  12. "net"
  13. "net/http"
  14. "os"
  15. "path/filepath"
  16. "strings"
  17. "testing"
  18. "time"
  19. agentruntime "github.com/gnacho/netpulse/agent/runtime"
  20. )
  21. // fakeHost is the system as the CA sees it.
  22. type fakeHost struct {
  23. addrs []net.IP
  24. now time.Time
  25. logs []string
  26. }
  27. func (h *fakeHost) opts(dir string) CAOptions {
  28. return CAOptions{
  29. Dir: dir,
  30. Addrs: func() ([]net.IP, error) { return h.addrs, nil },
  31. Hostname: func() (string, error) { return "monitor-box", nil },
  32. SearchDomains: func() []string { return []string{"example.lan"} },
  33. Now: func() time.Time { return h.now },
  34. Logf: func(f string, a ...any) { h.logs = append(h.logs, fmt.Sprintf(f, a...)) },
  35. }
  36. }
  37. func newHost() *fakeHost {
  38. return &fakeHost{
  39. addrs: []net.IP{net.ParseIP("192.168.50.2"), net.ParseIP("fe80::1")},
  40. now: time.Now(),
  41. }
  42. }
  43. func openTestCA(t *testing.T, h *fakeHost, dir string) *CA {
  44. t.Helper()
  45. ca, err := OpenCA(h.opts(dir))
  46. if err != nil {
  47. t.Fatalf("OpenCA: %v", err)
  48. }
  49. return ca
  50. }
  51. func verifyFor(t *testing.T, ca *CA, leaf *x509.Certificate, name string) error {
  52. t.Helper()
  53. roots := x509.NewCertPool()
  54. roots.AddCert(ca.root)
  55. _, err := leaf.Verify(x509.VerifyOptions{
  56. DNSName: name, Roots: roots, CurrentTime: time.Now(),
  57. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  58. })
  59. return err
  60. }
  61. func TestTheRootIsConstrainedAndPrivate(t *testing.T) {
  62. dir := filepath.Join(t.TempDir(), "tls")
  63. ca := openTestCA(t, newHost(), dir)
  64. r := ca.root
  65. if !r.IsCA || !r.MaxPathLenZero || r.MaxPathLen != 0 || r.KeyUsage&x509.KeyUsageCertSign == 0 {
  66. t.Fatalf("root is not a path-length-0 CA: isCA=%v pathlen=%d", r.IsCA, r.MaxPathLen)
  67. }
  68. // Non-critical on purpose: mbedTLS (OpenWrt) refuses a critical one.
  69. if r.PermittedDNSDomainsCritical || len(r.PermittedIPRanges) == 0 || len(r.PermittedDNSDomains) == 0 {
  70. t.Fatal("root lacks its name constraints, or marks them critical")
  71. }
  72. for _, want := range []string{"lan", "home.arpa", "monitor-box", "example.lan"} {
  73. if !ca.permitsName(want) {
  74. t.Errorf("root does not permit %q", want)
  75. }
  76. }
  77. for path, want := range map[string]os.FileMode{
  78. dir: 0o700,
  79. filepath.Join(dir, caKeyFile): 0o600,
  80. filepath.Join(dir, leafKeyFile): 0o600,
  81. } {
  82. fi, err := os.Stat(path)
  83. if err != nil {
  84. t.Fatal(err)
  85. }
  86. if fi.Mode().Perm() != want {
  87. t.Errorf("%s mode %04o, want %04o", filepath.Base(path), fi.Mode().Perm(), want)
  88. }
  89. }
  90. }
  91. func TestTheLeafNamesTheHostAndVerifies(t *testing.T) {
  92. ca := openTestCA(t, newHost(), tlsDir(t))
  93. leaf := ca.Leaf()
  94. for _, name := range []string{"192.168.50.2", "127.0.0.1", "monitor-box", "monitor-box.example.lan"} {
  95. if err := verifyFor(t, ca, leaf, name); err != nil {
  96. t.Errorf("%s: %v", name, err)
  97. }
  98. }
  99. for _, ip := range leaf.IPAddresses {
  100. if ip.IsLinkLocalUnicast() {
  101. t.Errorf("leaf names link-local %s", ip)
  102. }
  103. }
  104. }
  105. // The point of the constraints: even a certificate signed with the CA's own
  106. // key is refused for a public name or address.
  107. func TestTheRootCannotVouchForPublicNames(t *testing.T) {
  108. ca := openTestCA(t, newHost(), tlsDir(t))
  109. for _, tc := range []struct {
  110. dns string
  111. ip string
  112. }{
  113. {dns: "bank.example.com"},
  114. {ip: "203.0.113.7"},
  115. } {
  116. k, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  117. serial, _ := randomSerial()
  118. tmpl := &x509.Certificate{
  119. SerialNumber: serial, Subject: pkix.Name{CommonName: "forged"},
  120. NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour),
  121. KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  122. }
  123. name := tc.dns
  124. if tc.dns != "" {
  125. tmpl.DNSNames = []string{tc.dns}
  126. } else {
  127. tmpl.IPAddresses = []net.IP{net.ParseIP(tc.ip)}
  128. name = tc.ip
  129. }
  130. der, err := x509.CreateCertificate(rand.Reader, tmpl, ca.root, &k.PublicKey, ca.rootKey)
  131. if err != nil {
  132. t.Fatal(err)
  133. }
  134. forged, _ := x509.ParseCertificate(der)
  135. if err := verifyFor(t, ca, forged, name); err == nil {
  136. t.Errorf("a certificate for %s signed by the CA verified", name)
  137. }
  138. }
  139. }
  140. // A public address the host has is left out of the leaf, and said so once.
  141. func TestAddressesOutsideTheConstraintsAreLeftOut(t *testing.T) {
  142. h := newHost()
  143. h.addrs = append(h.addrs, net.ParseIP("203.0.113.7"))
  144. ca := openTestCA(t, h, tlsDir(t))
  145. for _, ip := range ca.Leaf().IPAddresses {
  146. if ip.Equal(net.ParseIP("203.0.113.7")) {
  147. t.Fatal("the leaf names a public address")
  148. }
  149. }
  150. if _, err := ca.Refresh(); err != nil {
  151. t.Fatal(err)
  152. }
  153. n := 0
  154. for _, l := range h.logs {
  155. if strings.Contains(l, "203.0.113.7") {
  156. n++
  157. }
  158. }
  159. if n != 1 {
  160. t.Fatalf("the dropped address was logged %d times, want once", n)
  161. }
  162. }
  163. func TestReopeningKeepsTheRootAndTheLeaf(t *testing.T) {
  164. h := newHost()
  165. dir := tlsDir(t)
  166. first := openTestCA(t, h, dir)
  167. second := openTestCA(t, h, dir)
  168. if first.Fingerprint() != second.Fingerprint() {
  169. t.Fatal("reopening created a new root")
  170. }
  171. if first.Leaf().SerialNumber.Cmp(second.Leaf().SerialNumber) != 0 {
  172. t.Fatal("reopening re-issued a leaf that was still good")
  173. }
  174. }
  175. func TestTheLeafFollowsTheHostsAddressesWithTheSameKey(t *testing.T) {
  176. h := newHost()
  177. ca := openTestCA(t, h, tlsDir(t))
  178. before := ca.Leaf()
  179. h.addrs = []net.IP{net.ParseIP("10.20.30.40")}
  180. issued, err := ca.Refresh()
  181. if err != nil || !issued {
  182. t.Fatalf("an address change did not re-issue the leaf (issued=%v, err=%v)", issued, err)
  183. }
  184. after := ca.Leaf()
  185. if err := verifyFor(t, ca, after, "10.20.30.40"); err != nil {
  186. t.Fatalf("new leaf does not name the new address: %v", err)
  187. }
  188. if !after.PublicKey.(*ecdsa.PublicKey).Equal(before.PublicKey) {
  189. t.Fatal("re-issuing changed the leaf key")
  190. }
  191. if issued, _ := ca.Refresh(); issued {
  192. t.Fatal("an unchanged host re-issued the leaf again")
  193. }
  194. }
  195. func TestTheLeafIsRenewedBeforeItExpires(t *testing.T) {
  196. h := newHost()
  197. ca := openTestCA(t, h, tlsDir(t))
  198. h.now = h.now.Add(leafValidity - leafRenewBefore + time.Hour)
  199. if issued, err := ca.Refresh(); err != nil || !issued {
  200. t.Fatalf("a leaf inside the renewal window was not renewed (issued=%v, err=%v)", issued, err)
  201. }
  202. if !ca.Leaf().NotAfter.After(h.now.Add(leafRenewBefore)) {
  203. t.Fatal("the renewed leaf is not valid for long enough")
  204. }
  205. }
  206. func TestAFailedWriteKeepsServingThePreviousLeaf(t *testing.T) {
  207. if os.Geteuid() == 0 {
  208. t.Skip("root ignores directory permissions")
  209. }
  210. h := newHost()
  211. dir := tlsDir(t)
  212. ca := openTestCA(t, h, dir)
  213. before := ca.Leaf()
  214. if err := os.Chmod(dir, 0o500); err != nil {
  215. t.Fatal(err)
  216. }
  217. defer os.Chmod(dir, 0o700)
  218. h.addrs = []net.IP{net.ParseIP("10.20.30.40")}
  219. if _, err := ca.Refresh(); err == nil {
  220. t.Fatal("writing into a read-only directory succeeded")
  221. }
  222. if ca.Leaf() != before {
  223. t.Fatal("a failed re-issue replaced the served leaf")
  224. }
  225. }
  226. func TestOpenKeyFilesAreRefused(t *testing.T) {
  227. for _, tc := range []struct {
  228. name string
  229. mess func(dir string) error
  230. want string
  231. }{
  232. {"a readable CA key", func(dir string) error { return os.Chmod(filepath.Join(dir, caKeyFile), 0o644) }, "chmod 600"},
  233. {"a readable directory", func(dir string) error { return os.Chmod(dir, 0o755) }, "chmod 700"},
  234. {"a CA certificate without its key", func(dir string) error { return os.Remove(filepath.Join(dir, caKeyFile)) }, "only one of"},
  235. {"a CA key without its certificate", func(dir string) error { return os.Remove(filepath.Join(dir, caCertFile)) }, "only one of"},
  236. } {
  237. t.Run(tc.name, func(t *testing.T) {
  238. h := newHost()
  239. dir := filepath.Join(t.TempDir(), "tls")
  240. openTestCA(t, h, dir)
  241. if err := tc.mess(dir); err != nil {
  242. t.Fatal(err)
  243. }
  244. _, err := OpenCA(h.opts(dir))
  245. if err == nil || !strings.Contains(err.Error(), tc.want) {
  246. t.Fatalf("OpenCA error %v, want one saying %q", err, tc.want)
  247. }
  248. })
  249. }
  250. }
  251. // End to end: an agent that pins the root reaches the server over TLS.
  252. func TestAnAgentPinningTheRootConnects(t *testing.T) {
  253. ca := openTestCA(t, newHost(), tlsDir(t))
  254. // A listener with exactly the CA's config: httptest would add its own
  255. // certificate, which Go serves instead of GetCertificate's to a client
  256. // that sends no SNI - as one dialling an address does.
  257. ln, err := net.Listen("tcp", "127.0.0.1:0")
  258. if err != nil {
  259. t.Fatal(err)
  260. }
  261. srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
  262. fmt.Fprint(w, "ok")
  263. })}
  264. go srv.Serve(tls.NewListener(ln, ca.TLSConfig()))
  265. defer srv.Close()
  266. url := "https://" + ln.Addr().String()
  267. tr, err := agentruntime.ServerTransport(url, ca.Fingerprint())
  268. if err != nil {
  269. t.Fatal(err)
  270. }
  271. res, err := (&http.Client{Transport: tr, Timeout: 5 * time.Second}).Get(url)
  272. if err != nil {
  273. t.Fatalf("an agent pinning the root could not connect: %v", err)
  274. }
  275. res.Body.Close()
  276. if res.TLS == nil || res.TLS.Version < tls.VersionTLS12 {
  277. t.Fatal("not a TLS 1.2+ connection")
  278. }
  279. }
  280. func TestRootSHA256IsWhatDevicesShow(t *testing.T) {
  281. ca := openTestCA(t, newHost(), tlsDir(t))
  282. fp := ca.RootSHA256()
  283. if len(fp) != 32*3-1 || strings.Count(fp, ":") != 31 || strings.ToUpper(fp) != fp {
  284. t.Fatalf("RootSHA256 = %q, want 32 upper-case hex pairs joined by colons", fp)
  285. }
  286. }
  287. // tlsDir is a directory the CA creates itself, as DATA_DIR/tls is.
  288. func tlsDir(t *testing.T) string {
  289. t.Helper()
  290. return filepath.Join(t.TempDir(), "tls")
  291. }
  292. // A search domain lets the root vouch for this host under it, never for the
  293. // whole domain, which can be a company's or a public one.
  294. func TestASearchDomainOnlyCoversThisHost(t *testing.T) {
  295. h := newHost()
  296. opts := h.opts(tlsDir(t))
  297. opts.SearchDomains = func() []string { return []string{"corp.example"} }
  298. ca, err := OpenCA(opts)
  299. if err != nil {
  300. t.Fatal(err)
  301. }
  302. if !ca.permitsName("monitor-box.corp.example") {
  303. t.Fatal("the host under its search domain is not covered")
  304. }
  305. for _, n := range []string{"corp.example", "mail.corp.example"} {
  306. if ca.permitsName(n) {
  307. t.Errorf("the root may vouch for %s", n)
  308. }
  309. }
  310. }
  311. // Created with a clock running fast, the root is still valid once the clock
  312. // is corrected.
  313. func TestTheRootToleratesAFastClockAtCreation(t *testing.T) {
  314. h := newHost()
  315. h.now = time.Now().Add(90 * 24 * time.Hour)
  316. ca := openTestCA(t, h, tlsDir(t))
  317. if !ca.root.NotBefore.Before(time.Now()) {
  318. t.Fatalf("root not valid before %v", ca.root.NotBefore)
  319. }
  320. }