firewall_test.go 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531
  1. package nebula
  2. import (
  3. "bytes"
  4. "fmt"
  5. "log/slog"
  6. "net/netip"
  7. "testing"
  8. "time"
  9. "github.com/gaissmai/bart"
  10. "github.com/slackhq/nebula/cert"
  11. "github.com/slackhq/nebula/config"
  12. "github.com/slackhq/nebula/firewall"
  13. "github.com/slackhq/nebula/iputil"
  14. "github.com/slackhq/nebula/test"
  15. "github.com/stretchr/testify/assert"
  16. "github.com/stretchr/testify/require"
  17. )
  18. func TestNewFirewall(t *testing.T) {
  19. l := test.NewLogger()
  20. c := &dummyCert{}
  21. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  22. conntrack := fw.Conntrack
  23. assert.NotNil(t, conntrack)
  24. assert.NotNil(t, conntrack.Conns)
  25. assert.NotNil(t, conntrack.TimerWheel)
  26. assert.NotNil(t, fw.rules.In)
  27. assert.NotNil(t, fw.rules.Out)
  28. // Nothing is allowed until there are rules
  29. assert.False(t, fw.rules.Match(&firewall.Packet{Protocol: iputil.IPProtocolTCP}, true, nil, nil))
  30. assert.False(t, fw.rules.Match(&firewall.Packet{Protocol: iputil.IPProtocolTCP}, false, nil, nil))
  31. assert.Equal(t, time.Second, fw.TCPTimeout)
  32. assert.Equal(t, time.Minute, fw.UDPTimeout)
  33. assert.Equal(t, time.Hour, fw.DefaultTimeout)
  34. assert.Equal(t, time.Second, fw.conntrackTimeout(iputil.IPProtocolTCP))
  35. assert.Equal(t, time.Second, fw.conntrackTimeout(iputil.IPProtocolSCTP))
  36. assert.Equal(t, time.Second, fw.conntrackTimeout(iputil.IPProtocolDCCP))
  37. assert.Equal(t, time.Minute, fw.conntrackTimeout(iputil.IPProtocolUDP))
  38. assert.Equal(t, time.Minute, fw.conntrackTimeout(iputil.IPProtocolUDPLite))
  39. assert.Equal(t, time.Hour, fw.conntrackTimeout(iputil.IPProtocolICMP))
  40. assert.Equal(t, time.Hour, fw.conntrackTimeout(47)) // GRE
  41. assert.Equal(t, time.Hour, conntrack.TimerWheel.wheelDuration)
  42. assert.Equal(t, time.Hour, conntrack.TimerWheel.wheelDuration)
  43. assert.Equal(t, 3602, conntrack.TimerWheel.wheelLen)
  44. fw = NewFirewall(l, time.Second, time.Hour, time.Minute, c)
  45. assert.Equal(t, time.Hour, conntrack.TimerWheel.wheelDuration)
  46. assert.Equal(t, 3602, conntrack.TimerWheel.wheelLen)
  47. fw = NewFirewall(l, time.Hour, time.Second, time.Minute, c)
  48. assert.Equal(t, time.Hour, conntrack.TimerWheel.wheelDuration)
  49. assert.Equal(t, 3602, conntrack.TimerWheel.wheelLen)
  50. fw = NewFirewall(l, time.Hour, time.Minute, time.Second, c)
  51. assert.Equal(t, time.Hour, conntrack.TimerWheel.wheelDuration)
  52. assert.Equal(t, 3602, conntrack.TimerWheel.wheelLen)
  53. fw = NewFirewall(l, time.Minute, time.Hour, time.Second, c)
  54. assert.Equal(t, time.Hour, conntrack.TimerWheel.wheelDuration)
  55. assert.Equal(t, 3602, conntrack.TimerWheel.wheelLen)
  56. fw = NewFirewall(l, time.Minute, time.Second, time.Hour, c)
  57. assert.Equal(t, time.Hour, conntrack.TimerWheel.wheelDuration)
  58. assert.Equal(t, 3602, conntrack.TimerWheel.wheelLen)
  59. }
  60. func TestFirewall_Drop(t *testing.T) {
  61. ob := &bytes.Buffer{}
  62. l := test.NewLoggerWithOutput(ob)
  63. myVpnNetworksTable := new(bart.Lite)
  64. myVpnNetworksTable.Insert(netip.MustParsePrefix("1.1.1.1/8"))
  65. p := firewall.Packet{
  66. LocalAddr: netip.MustParseAddr("1.2.3.4"),
  67. RemoteAddr: netip.MustParseAddr("1.2.3.4"),
  68. LocalPort: 10,
  69. RemotePort: 90,
  70. Protocol: iputil.IPProtocolUDP,
  71. Fragment: false,
  72. }
  73. c := dummyCert{
  74. name: "host1",
  75. networks: []netip.Prefix{netip.MustParsePrefix("1.2.3.4/24")},
  76. groups: []string{"default-group"},
  77. issuer: "signer-shasum",
  78. }
  79. h := HostInfo{
  80. ConnectionState: &ConnectionState{
  81. peerCert: &cert.CachedCertificate{
  82. Certificate: &c,
  83. InvertedGroups: map[string]struct{}{"default-group": {}},
  84. },
  85. },
  86. vpnAddrs: []netip.Addr{netip.MustParseAddr("1.2.3.4")},
  87. }
  88. h.buildNetworks(myVpnNetworksTable, &c)
  89. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  90. rb := firewall.NewRulesBuilder(l)
  91. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 0, 0, []string{"any"}, "", "", "", "", ""))
  92. fw.setRules(rb)
  93. cp := cert.NewCAPool()
  94. // Drop outbound
  95. assert.Equal(t, ErrNoMatchingRule, fw.Drop(p, false, &h, cp, nil))
  96. // Allow inbound
  97. resetConntrack(fw)
  98. require.NoError(t, fw.Drop(p, true, &h, cp, nil))
  99. // Allow outbound because conntrack
  100. require.NoError(t, fw.Drop(p, false, &h, cp, nil))
  101. // test remote mismatch
  102. oldRemote := p.RemoteAddr
  103. p.RemoteAddr = netip.MustParseAddr("1.2.3.10")
  104. assert.Equal(t, fw.Drop(p, false, &h, cp, nil), ErrInvalidRemoteIP)
  105. p.RemoteAddr = oldRemote
  106. // ensure signer doesn't get in the way of group checks
  107. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  108. rb = firewall.NewRulesBuilder(l)
  109. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "", "signer-shasum"))
  110. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "", "signer-shasum-bad"))
  111. fw.setRules(rb)
  112. assert.Equal(t, fw.Drop(p, true, &h, cp, nil), ErrNoMatchingRule)
  113. // test caSha doesn't drop on match
  114. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  115. rb = firewall.NewRulesBuilder(l)
  116. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "", "signer-shasum-bad"))
  117. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "", "signer-shasum"))
  118. fw.setRules(rb)
  119. require.NoError(t, fw.Drop(p, true, &h, cp, nil))
  120. // ensure ca name doesn't get in the way of group checks
  121. cp.CAs["signer-shasum"] = &cert.CachedCertificate{Certificate: &dummyCert{name: "ca-good"}}
  122. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  123. rb = firewall.NewRulesBuilder(l)
  124. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "ca-good", ""))
  125. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "ca-good-bad", ""))
  126. fw.setRules(rb)
  127. assert.Equal(t, fw.Drop(p, true, &h, cp, nil), ErrNoMatchingRule)
  128. // test caName doesn't drop on match
  129. cp.CAs["signer-shasum"] = &cert.CachedCertificate{Certificate: &dummyCert{name: "ca-good"}}
  130. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  131. rb = firewall.NewRulesBuilder(l)
  132. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "ca-good-bad", ""))
  133. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "ca-good", ""))
  134. fw.setRules(rb)
  135. require.NoError(t, fw.Drop(p, true, &h, cp, nil))
  136. }
  137. func TestFirewall_DropV6(t *testing.T) {
  138. ob := &bytes.Buffer{}
  139. l := test.NewLoggerWithOutput(ob)
  140. myVpnNetworksTable := new(bart.Lite)
  141. myVpnNetworksTable.Insert(netip.MustParsePrefix("fd00::/7"))
  142. p := firewall.Packet{
  143. LocalAddr: netip.MustParseAddr("fd12::34"),
  144. RemoteAddr: netip.MustParseAddr("fd12::34"),
  145. LocalPort: 10,
  146. RemotePort: 90,
  147. Protocol: iputil.IPProtocolUDP,
  148. Fragment: false,
  149. }
  150. c := dummyCert{
  151. name: "host1",
  152. networks: []netip.Prefix{netip.MustParsePrefix("fd12::34/120")},
  153. groups: []string{"default-group"},
  154. issuer: "signer-shasum",
  155. }
  156. h := HostInfo{
  157. ConnectionState: &ConnectionState{
  158. peerCert: &cert.CachedCertificate{
  159. Certificate: &c,
  160. InvertedGroups: map[string]struct{}{"default-group": {}},
  161. },
  162. },
  163. vpnAddrs: []netip.Addr{netip.MustParseAddr("fd12::34")},
  164. }
  165. h.buildNetworks(myVpnNetworksTable, &c)
  166. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  167. rb := firewall.NewRulesBuilder(l)
  168. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 0, 0, []string{"any"}, "", "", "", "", ""))
  169. fw.setRules(rb)
  170. cp := cert.NewCAPool()
  171. // Drop outbound
  172. assert.Equal(t, ErrNoMatchingRule, fw.Drop(p, false, &h, cp, nil))
  173. // Allow inbound
  174. resetConntrack(fw)
  175. require.NoError(t, fw.Drop(p, true, &h, cp, nil))
  176. // Allow outbound because conntrack
  177. require.NoError(t, fw.Drop(p, false, &h, cp, nil))
  178. // test remote mismatch
  179. oldRemote := p.RemoteAddr
  180. p.RemoteAddr = netip.MustParseAddr("fd12::56")
  181. assert.Equal(t, fw.Drop(p, false, &h, cp, nil), ErrInvalidRemoteIP)
  182. p.RemoteAddr = oldRemote
  183. // ensure signer doesn't get in the way of group checks
  184. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  185. rb = firewall.NewRulesBuilder(l)
  186. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "", "signer-shasum"))
  187. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "", "signer-shasum-bad"))
  188. fw.setRules(rb)
  189. assert.Equal(t, fw.Drop(p, true, &h, cp, nil), ErrNoMatchingRule)
  190. // test caSha doesn't drop on match
  191. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  192. rb = firewall.NewRulesBuilder(l)
  193. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "", "signer-shasum-bad"))
  194. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "", "signer-shasum"))
  195. fw.setRules(rb)
  196. require.NoError(t, fw.Drop(p, true, &h, cp, nil))
  197. // ensure ca name doesn't get in the way of group checks
  198. cp.CAs["signer-shasum"] = &cert.CachedCertificate{Certificate: &dummyCert{name: "ca-good"}}
  199. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  200. rb = firewall.NewRulesBuilder(l)
  201. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "ca-good", ""))
  202. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "ca-good-bad", ""))
  203. fw.setRules(rb)
  204. assert.Equal(t, fw.Drop(p, true, &h, cp, nil), ErrNoMatchingRule)
  205. // test caName doesn't drop on match
  206. cp.CAs["signer-shasum"] = &cert.CachedCertificate{Certificate: &dummyCert{name: "ca-good"}}
  207. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  208. rb = firewall.NewRulesBuilder(l)
  209. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "ca-good-bad", ""))
  210. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "ca-good", ""))
  211. fw.setRules(rb)
  212. require.NoError(t, fw.Drop(p, true, &h, cp, nil))
  213. }
  214. func BenchmarkFirewallTable_match(b *testing.B) {
  215. rb := firewall.NewRulesBuilder(test.NewLogger())
  216. pfix := netip.MustParsePrefix("172.1.1.1/32")
  217. require.NoError(b, rb.AddRule(true, iputil.IPProtocolTCP, 10, 10, []string{"good-group"}, "good-host", pfix.String(), "", "", ""))
  218. require.NoError(b, rb.AddRule(true, iputil.IPProtocolTCP, 100, 100, []string{"good-group"}, "good-host", "", pfix.String(), "", ""))
  219. pfix6 := netip.MustParsePrefix("fd11::11/128")
  220. require.NoError(b, rb.AddRule(true, iputil.IPProtocolTCP, 10, 10, []string{"good-group"}, "good-host", pfix6.String(), "", "", ""))
  221. require.NoError(b, rb.AddRule(true, iputil.IPProtocolTCP, 100, 100, []string{"good-group"}, "good-host", "", pfix6.String(), "", ""))
  222. ft := rb.Build(nil, nil).In
  223. cp := cert.NewCAPool()
  224. b.Run("fail on proto", func(b *testing.B) {
  225. // This benchmark is showing us the cost of failing to match the protocol
  226. c := &cert.CachedCertificate{
  227. Certificate: &dummyCert{},
  228. }
  229. for n := 0; n < b.N; n++ {
  230. assert.False(b, ft.Match(&firewall.Packet{Protocol: iputil.IPProtocolUDP}, true, c, cp))
  231. }
  232. })
  233. b.Run("pass proto, fail on port", func(b *testing.B) {
  234. // This benchmark is showing us the cost of matching a specific protocol but failing to match the port
  235. c := &cert.CachedCertificate{
  236. Certificate: &dummyCert{},
  237. }
  238. for n := 0; n < b.N; n++ {
  239. assert.False(b, ft.Match(&firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 1}, true, c, cp))
  240. }
  241. })
  242. b.Run("pass proto, port, fail on local CIDR", func(b *testing.B) {
  243. c := &cert.CachedCertificate{
  244. Certificate: &dummyCert{},
  245. }
  246. ip := netip.MustParsePrefix("9.254.254.254/32")
  247. for n := 0; n < b.N; n++ {
  248. assert.False(b, ft.Match(&firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 100, LocalAddr: ip.Addr()}, true, c, cp))
  249. }
  250. })
  251. b.Run("pass proto, port, fail on local CIDRv6", func(b *testing.B) {
  252. c := &cert.CachedCertificate{
  253. Certificate: &dummyCert{},
  254. }
  255. ip := netip.MustParsePrefix("fd99::99/128")
  256. for n := 0; n < b.N; n++ {
  257. assert.False(b, ft.Match(&firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 100, LocalAddr: ip.Addr()}, true, c, cp))
  258. }
  259. })
  260. b.Run("pass proto, port, any local CIDR, fail all group, name, and cidr", func(b *testing.B) {
  261. c := &cert.CachedCertificate{
  262. Certificate: &dummyCert{
  263. name: "nope",
  264. networks: []netip.Prefix{netip.MustParsePrefix("9.254.254.245/32")},
  265. },
  266. InvertedGroups: map[string]struct{}{"nope": {}},
  267. }
  268. for n := 0; n < b.N; n++ {
  269. assert.False(b, ft.Match(&firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 10}, true, c, cp))
  270. }
  271. })
  272. b.Run("pass proto, port, any local CIDRv6, fail all group, name, and cidr", func(b *testing.B) {
  273. c := &cert.CachedCertificate{
  274. Certificate: &dummyCert{
  275. name: "nope",
  276. networks: []netip.Prefix{netip.MustParsePrefix("fd99::99/128")},
  277. },
  278. InvertedGroups: map[string]struct{}{"nope": {}},
  279. }
  280. for n := 0; n < b.N; n++ {
  281. assert.False(b, ft.Match(&firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 10}, true, c, cp))
  282. }
  283. })
  284. b.Run("pass proto, port, specific local CIDR, fail all group, name, and cidr", func(b *testing.B) {
  285. c := &cert.CachedCertificate{
  286. Certificate: &dummyCert{
  287. name: "nope",
  288. networks: []netip.Prefix{netip.MustParsePrefix("9.254.254.245/32")},
  289. },
  290. InvertedGroups: map[string]struct{}{"nope": {}},
  291. }
  292. for n := 0; n < b.N; n++ {
  293. assert.False(b, ft.Match(&firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 100, LocalAddr: pfix.Addr()}, true, c, cp))
  294. }
  295. })
  296. b.Run("pass proto, port, specific local CIDRv6, fail all group, name, and cidr", func(b *testing.B) {
  297. c := &cert.CachedCertificate{
  298. Certificate: &dummyCert{
  299. name: "nope",
  300. networks: []netip.Prefix{netip.MustParsePrefix("fd99::99/128")},
  301. },
  302. InvertedGroups: map[string]struct{}{"nope": {}},
  303. }
  304. for n := 0; n < b.N; n++ {
  305. assert.False(b, ft.Match(&firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 100, LocalAddr: pfix6.Addr()}, true, c, cp))
  306. }
  307. })
  308. b.Run("pass on group on any local cidr", func(b *testing.B) {
  309. c := &cert.CachedCertificate{
  310. Certificate: &dummyCert{
  311. name: "nope",
  312. },
  313. InvertedGroups: map[string]struct{}{"good-group": {}},
  314. }
  315. for n := 0; n < b.N; n++ {
  316. assert.True(b, ft.Match(&firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 10}, true, c, cp))
  317. }
  318. })
  319. b.Run("pass on group on specific local cidr", func(b *testing.B) {
  320. c := &cert.CachedCertificate{
  321. Certificate: &dummyCert{
  322. name: "nope",
  323. },
  324. InvertedGroups: map[string]struct{}{"good-group": {}},
  325. }
  326. for n := 0; n < b.N; n++ {
  327. assert.True(b, ft.Match(&firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 100, LocalAddr: pfix.Addr()}, true, c, cp))
  328. }
  329. })
  330. b.Run("pass on group on specific local cidr6", func(b *testing.B) {
  331. c := &cert.CachedCertificate{
  332. Certificate: &dummyCert{
  333. name: "nope",
  334. },
  335. InvertedGroups: map[string]struct{}{"good-group": {}},
  336. }
  337. for n := 0; n < b.N; n++ {
  338. assert.True(b, ft.Match(&firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 100, LocalAddr: pfix6.Addr()}, true, c, cp))
  339. }
  340. })
  341. b.Run("pass on name", func(b *testing.B) {
  342. c := &cert.CachedCertificate{
  343. Certificate: &dummyCert{
  344. name: "good-host",
  345. },
  346. InvertedGroups: map[string]struct{}{"nope": {}},
  347. }
  348. for n := 0; n < b.N; n++ {
  349. ft.Match(&firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 10}, true, c, cp)
  350. }
  351. })
  352. // The port 10 rules have a cidr, this cert fails their group and host so only the cidr can pass them
  353. cidrCert := &cert.CachedCertificate{
  354. Certificate: &dummyCert{name: "nope"},
  355. InvertedGroups: map[string]struct{}{"nope": {}},
  356. }
  357. for _, tc := range []struct {
  358. name string
  359. addr netip.Addr
  360. want bool
  361. }{
  362. {"pass on cidr", pfix.Addr(), true},
  363. {"pass on cidr6", pfix6.Addr(), true},
  364. {"pass proto, port, fail group and name, fail on cidr", netip.MustParseAddr("9.254.254.245"), false},
  365. {"pass proto, port, fail group and name, fail on cidr6", netip.MustParseAddr("fd99::99"), false},
  366. } {
  367. p := &firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 10, RemoteAddr: tc.addr}
  368. b.Run(tc.name, func(b *testing.B) {
  369. if ft.Match(p, true, cidrCert, cp) != tc.want {
  370. b.Fatal("wrong verdict")
  371. }
  372. for b.Loop() {
  373. benchMatchSink = ft.Match(p, true, cidrCert, cp)
  374. }
  375. })
  376. }
  377. }
  378. var benchMatchSink bool
  379. // BenchmarkFirewallTable_matchManyRules measures a table with more rules than fit in one word of a rule set.
  380. // Rule 0 is a proto `any` rule that fails on host, and rules 1 through 130 are tcp ports 1 through 130 for hosts
  381. // h1 through h130, so the last rule id is the one that passes.
  382. func BenchmarkFirewallTable_matchManyRules(b *testing.B) {
  383. rb := firewall.NewRulesBuilder(test.NewLogger())
  384. require.NoError(b, rb.AddRule(true, firewall.ProtoAny, firewall.PortAny, firewall.PortAny, nil, "nope", "", "", "", ""))
  385. for i := 1; i <= 130; i++ {
  386. require.NoError(b, rb.AddRule(true, iputil.IPProtocolTCP, int32(i), int32(i), nil, fmt.Sprintf("h%d", i), "", "", "", ""))
  387. }
  388. ft := rb.Build(nil, nil).In
  389. cp := cert.NewCAPool()
  390. c := &cert.CachedCertificate{Certificate: &dummyCert{name: "h130"}, InvertedGroups: map[string]struct{}{}}
  391. for _, tc := range []struct {
  392. name string
  393. port uint16
  394. want bool
  395. }{
  396. {"fail on port", 5000, false},
  397. {"pass on name, last id", 130, true},
  398. {"fail on name, middle id", 65, false},
  399. } {
  400. p := &firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: tc.port}
  401. b.Run(tc.name, func(b *testing.B) {
  402. if ft.Match(p, true, c, cp) != tc.want {
  403. b.Fatal("wrong verdict")
  404. }
  405. for b.Loop() {
  406. benchMatchSink = ft.Match(p, true, c, cp)
  407. }
  408. })
  409. }
  410. }
  411. func TestFirewall_Drop2(t *testing.T) {
  412. ob := &bytes.Buffer{}
  413. l := test.NewLoggerWithOutput(ob)
  414. myVpnNetworksTable := new(bart.Lite)
  415. myVpnNetworksTable.Insert(netip.MustParsePrefix("1.1.1.1/8"))
  416. p := firewall.Packet{
  417. LocalAddr: netip.MustParseAddr("1.2.3.4"),
  418. RemoteAddr: netip.MustParseAddr("1.2.3.4"),
  419. LocalPort: 10,
  420. RemotePort: 90,
  421. Protocol: iputil.IPProtocolUDP,
  422. Fragment: false,
  423. }
  424. network := netip.MustParsePrefix("1.2.3.4/24")
  425. c := cert.CachedCertificate{
  426. Certificate: &dummyCert{
  427. name: "host1",
  428. networks: []netip.Prefix{network},
  429. },
  430. InvertedGroups: map[string]struct{}{"default-group": {}, "test-group": {}},
  431. }
  432. h := HostInfo{
  433. ConnectionState: &ConnectionState{
  434. peerCert: &c,
  435. },
  436. vpnAddrs: []netip.Addr{network.Addr()},
  437. }
  438. h.buildNetworks(myVpnNetworksTable, c.Certificate)
  439. c1 := cert.CachedCertificate{
  440. Certificate: &dummyCert{
  441. name: "host1",
  442. networks: []netip.Prefix{network},
  443. },
  444. InvertedGroups: map[string]struct{}{"default-group": {}, "test-group-not": {}},
  445. }
  446. h1 := HostInfo{
  447. vpnAddrs: []netip.Addr{network.Addr()},
  448. ConnectionState: &ConnectionState{
  449. peerCert: &c1,
  450. },
  451. }
  452. h1.buildNetworks(myVpnNetworksTable, c1.Certificate)
  453. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  454. rb := firewall.NewRulesBuilder(l)
  455. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group", "test-group"}, "", "", "", "", ""))
  456. fw.setRules(rb)
  457. cp := cert.NewCAPool()
  458. // h1/c1 lacks the proper groups
  459. require.ErrorIs(t, fw.Drop(p, true, &h1, cp, nil), ErrNoMatchingRule)
  460. // c has the proper groups
  461. resetConntrack(fw)
  462. require.NoError(t, fw.Drop(p, true, &h, cp, nil))
  463. }
  464. func TestFirewall_Drop3(t *testing.T) {
  465. ob := &bytes.Buffer{}
  466. l := test.NewLoggerWithOutput(ob)
  467. myVpnNetworksTable := new(bart.Lite)
  468. myVpnNetworksTable.Insert(netip.MustParsePrefix("1.1.1.1/8"))
  469. p := firewall.Packet{
  470. LocalAddr: netip.MustParseAddr("1.2.3.4"),
  471. RemoteAddr: netip.MustParseAddr("1.2.3.4"),
  472. LocalPort: 1,
  473. RemotePort: 1,
  474. Protocol: iputil.IPProtocolUDP,
  475. Fragment: false,
  476. }
  477. network := netip.MustParsePrefix("1.2.3.4/24")
  478. c := cert.CachedCertificate{
  479. Certificate: &dummyCert{
  480. name: "host-owner",
  481. networks: []netip.Prefix{network},
  482. },
  483. }
  484. c1 := cert.CachedCertificate{
  485. Certificate: &dummyCert{
  486. name: "host1",
  487. networks: []netip.Prefix{network},
  488. issuer: "signer-sha-bad",
  489. },
  490. }
  491. h1 := HostInfo{
  492. ConnectionState: &ConnectionState{
  493. peerCert: &c1,
  494. },
  495. vpnAddrs: []netip.Addr{network.Addr()},
  496. }
  497. h1.buildNetworks(myVpnNetworksTable, c1.Certificate)
  498. c2 := cert.CachedCertificate{
  499. Certificate: &dummyCert{
  500. name: "host2",
  501. networks: []netip.Prefix{network},
  502. issuer: "signer-sha",
  503. },
  504. }
  505. h2 := HostInfo{
  506. ConnectionState: &ConnectionState{
  507. peerCert: &c2,
  508. },
  509. vpnAddrs: []netip.Addr{network.Addr()},
  510. }
  511. h2.buildNetworks(myVpnNetworksTable, c2.Certificate)
  512. c3 := cert.CachedCertificate{
  513. Certificate: &dummyCert{
  514. name: "host3",
  515. networks: []netip.Prefix{network},
  516. issuer: "signer-sha-bad",
  517. },
  518. }
  519. h3 := HostInfo{
  520. ConnectionState: &ConnectionState{
  521. peerCert: &c3,
  522. },
  523. vpnAddrs: []netip.Addr{network.Addr()},
  524. }
  525. h3.buildNetworks(myVpnNetworksTable, c3.Certificate)
  526. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  527. rb := firewall.NewRulesBuilder(l)
  528. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 1, 1, []string{}, "host1", "", "", "", ""))
  529. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 1, 1, []string{}, "", "", "", "", "signer-sha"))
  530. fw.setRules(rb)
  531. cp := cert.NewCAPool()
  532. // c1 should pass because host match
  533. require.NoError(t, fw.Drop(p, true, &h1, cp, nil))
  534. // c2 should pass because ca sha match
  535. resetConntrack(fw)
  536. require.NoError(t, fw.Drop(p, true, &h2, cp, nil))
  537. // c3 should fail because no match
  538. resetConntrack(fw)
  539. assert.Equal(t, fw.Drop(p, true, &h3, cp, nil), ErrNoMatchingRule)
  540. // Test a remote address match
  541. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  542. rb = firewall.NewRulesBuilder(l)
  543. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 1, 1, []string{}, "", "1.2.3.4/24", "", "", ""))
  544. fw.setRules(rb)
  545. require.NoError(t, fw.Drop(p, true, &h1, cp, nil))
  546. }
  547. func TestFirewall_Drop3V6(t *testing.T) {
  548. ob := &bytes.Buffer{}
  549. l := test.NewLoggerWithOutput(ob)
  550. myVpnNetworksTable := new(bart.Lite)
  551. myVpnNetworksTable.Insert(netip.MustParsePrefix("fd00::/7"))
  552. p := firewall.Packet{
  553. LocalAddr: netip.MustParseAddr("fd12::34"),
  554. RemoteAddr: netip.MustParseAddr("fd12::34"),
  555. LocalPort: 1,
  556. RemotePort: 1,
  557. Protocol: iputil.IPProtocolUDP,
  558. Fragment: false,
  559. }
  560. network := netip.MustParsePrefix("fd12::34/120")
  561. c := cert.CachedCertificate{
  562. Certificate: &dummyCert{
  563. name: "host-owner",
  564. networks: []netip.Prefix{network},
  565. },
  566. }
  567. h := HostInfo{
  568. ConnectionState: &ConnectionState{
  569. peerCert: &c,
  570. },
  571. vpnAddrs: []netip.Addr{network.Addr()},
  572. }
  573. h.buildNetworks(myVpnNetworksTable, c.Certificate)
  574. // Test a remote address match
  575. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  576. rb := firewall.NewRulesBuilder(l)
  577. cp := cert.NewCAPool()
  578. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 1, 1, []string{}, "", "fd12::34/120", "", "", ""))
  579. fw.setRules(rb)
  580. require.NoError(t, fw.Drop(p, true, &h, cp, nil))
  581. }
  582. func TestFirewall_DropConntrackReload(t *testing.T) {
  583. ob := &bytes.Buffer{}
  584. l := test.NewLoggerWithOutput(ob)
  585. myVpnNetworksTable := new(bart.Lite)
  586. myVpnNetworksTable.Insert(netip.MustParsePrefix("1.1.1.1/8"))
  587. p := firewall.Packet{
  588. LocalAddr: netip.MustParseAddr("1.2.3.4"),
  589. RemoteAddr: netip.MustParseAddr("1.2.3.4"),
  590. LocalPort: 10,
  591. RemotePort: 90,
  592. Protocol: iputil.IPProtocolUDP,
  593. Fragment: false,
  594. }
  595. network := netip.MustParsePrefix("1.2.3.4/24")
  596. c := cert.CachedCertificate{
  597. Certificate: &dummyCert{
  598. name: "host1",
  599. networks: []netip.Prefix{network},
  600. groups: []string{"default-group"},
  601. issuer: "signer-shasum",
  602. },
  603. InvertedGroups: map[string]struct{}{"default-group": {}},
  604. }
  605. h := HostInfo{
  606. ConnectionState: &ConnectionState{
  607. peerCert: &c,
  608. },
  609. vpnAddrs: []netip.Addr{network.Addr()},
  610. }
  611. h.buildNetworks(myVpnNetworksTable, c.Certificate)
  612. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  613. rb := firewall.NewRulesBuilder(l)
  614. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 0, 0, []string{"any"}, "", "", "", "", ""))
  615. fw.setRules(rb)
  616. cp := cert.NewCAPool()
  617. // Drop outbound
  618. assert.Equal(t, fw.Drop(p, false, &h, cp, nil), ErrNoMatchingRule)
  619. // Allow inbound
  620. resetConntrack(fw)
  621. require.NoError(t, fw.Drop(p, true, &h, cp, nil))
  622. // Allow outbound because conntrack
  623. require.NoError(t, fw.Drop(p, false, &h, cp, nil))
  624. oldFw := fw
  625. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  626. rb = firewall.NewRulesBuilder(l)
  627. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 10, 10, []string{"any"}, "", "", "", "", ""))
  628. fw.setRules(rb)
  629. fw.Conntrack = oldFw.Conntrack
  630. fw.rulesVersion = oldFw.rulesVersion + 1
  631. // Allow outbound because conntrack and new rules allow port 10
  632. require.NoError(t, fw.Drop(p, false, &h, cp, nil))
  633. oldFw = fw
  634. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  635. rb = firewall.NewRulesBuilder(l)
  636. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 11, 11, []string{"any"}, "", "", "", "", ""))
  637. fw.setRules(rb)
  638. fw.Conntrack = oldFw.Conntrack
  639. fw.rulesVersion = oldFw.rulesVersion + 1
  640. // Drop outbound because conntrack doesn't match new ruleset
  641. assert.Equal(t, fw.Drop(p, false, &h, cp, nil), ErrNoMatchingRule)
  642. }
  643. func TestFirewall_ICMPPortBehavior(t *testing.T) {
  644. ob := &bytes.Buffer{}
  645. l := test.NewLoggerWithOutput(ob)
  646. myVpnNetworksTable := new(bart.Lite)
  647. myVpnNetworksTable.Insert(netip.MustParsePrefix("1.1.1.1/8"))
  648. network := netip.MustParsePrefix("1.2.3.4/24")
  649. c := cert.CachedCertificate{
  650. Certificate: &dummyCert{
  651. name: "host1",
  652. networks: []netip.Prefix{network},
  653. groups: []string{"default-group"},
  654. issuer: "signer-shasum",
  655. },
  656. InvertedGroups: map[string]struct{}{"default-group": {}},
  657. }
  658. h := HostInfo{
  659. ConnectionState: &ConnectionState{
  660. peerCert: &c,
  661. },
  662. vpnAddrs: []netip.Addr{network.Addr()},
  663. }
  664. h.buildNetworks(myVpnNetworksTable, c.Certificate)
  665. cp := cert.NewCAPool()
  666. templ := firewall.Packet{
  667. LocalAddr: netip.MustParseAddr("1.2.3.4"),
  668. RemoteAddr: netip.MustParseAddr("1.2.3.4"),
  669. Protocol: iputil.IPProtocolICMP,
  670. Fragment: false,
  671. }
  672. t.Run("ICMP allowed", func(t *testing.T) {
  673. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  674. rb := firewall.NewRulesBuilder(l)
  675. require.NoError(t, rb.AddRule(true, iputil.IPProtocolICMP, 0, 0, []string{"any"}, "", "", "", "", ""))
  676. fw.setRules(rb)
  677. t.Run("zero ports", func(t *testing.T) {
  678. p := templ.Copy()
  679. p.LocalPort = 0
  680. p.RemotePort = 0
  681. // Drop outbound
  682. assert.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
  683. // Allow inbound
  684. resetConntrack(fw)
  685. require.NoError(t, fw.Drop(*p, true, &h, cp, nil))
  686. //now also allow outbound
  687. require.NoError(t, fw.Drop(*p, false, &h, cp, nil))
  688. })
  689. t.Run("nonzero ports", func(t *testing.T) {
  690. p := templ.Copy()
  691. p.LocalPort = 0xabcd
  692. p.RemotePort = 0x1234
  693. // Drop outbound
  694. assert.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
  695. // Allow inbound
  696. resetConntrack(fw)
  697. require.NoError(t, fw.Drop(*p, true, &h, cp, nil))
  698. //now also allow outbound
  699. require.NoError(t, fw.Drop(*p, false, &h, cp, nil))
  700. })
  701. })
  702. t.Run("Any proto, some ports allowed", func(t *testing.T) {
  703. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  704. rb := firewall.NewRulesBuilder(l)
  705. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 80, 444, []string{"any"}, "", "", "", "", ""))
  706. fw.setRules(rb)
  707. t.Run("zero ports, still blocked", func(t *testing.T) {
  708. p := templ.Copy()
  709. p.LocalPort = 0
  710. p.RemotePort = 0
  711. // Drop outbound
  712. assert.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
  713. // Allow inbound
  714. resetConntrack(fw)
  715. assert.Equal(t, fw.Drop(*p, true, &h, cp, nil), ErrNoMatchingRule)
  716. //now also allow outbound
  717. assert.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
  718. })
  719. t.Run("nonzero ports, still blocked", func(t *testing.T) {
  720. p := templ.Copy()
  721. p.LocalPort = 0xabcd
  722. p.RemotePort = 0x1234
  723. // Drop outbound
  724. assert.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
  725. // Allow inbound
  726. resetConntrack(fw)
  727. assert.Equal(t, fw.Drop(*p, true, &h, cp, nil), ErrNoMatchingRule)
  728. //now also allow outbound
  729. assert.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
  730. })
  731. t.Run("nonzero, matching ports, still blocked", func(t *testing.T) {
  732. p := templ.Copy()
  733. p.LocalPort = 80
  734. p.RemotePort = 80
  735. // Drop outbound
  736. assert.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
  737. // Allow inbound
  738. resetConntrack(fw)
  739. assert.Equal(t, fw.Drop(*p, true, &h, cp, nil), ErrNoMatchingRule)
  740. //now also allow outbound
  741. assert.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
  742. })
  743. })
  744. t.Run("Any proto, any port", func(t *testing.T) {
  745. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  746. rb := firewall.NewRulesBuilder(l)
  747. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 0, 0, []string{"any"}, "", "", "", "", ""))
  748. fw.setRules(rb)
  749. t.Run("zero ports, allowed", func(t *testing.T) {
  750. resetConntrack(fw)
  751. p := templ.Copy()
  752. p.LocalPort = 0
  753. p.RemotePort = 0
  754. // Drop outbound
  755. assert.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
  756. // Allow inbound
  757. resetConntrack(fw)
  758. require.NoError(t, fw.Drop(*p, true, &h, cp, nil))
  759. //now also allow outbound
  760. require.NoError(t, fw.Drop(*p, false, &h, cp, nil))
  761. })
  762. t.Run("nonzero ports, allowed", func(t *testing.T) {
  763. resetConntrack(fw)
  764. p := templ.Copy()
  765. p.LocalPort = 0xabcd
  766. p.RemotePort = 0x1234
  767. // Drop outbound
  768. assert.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
  769. // Allow inbound
  770. resetConntrack(fw)
  771. require.NoError(t, fw.Drop(*p, true, &h, cp, nil))
  772. //now also allow outbound
  773. require.NoError(t, fw.Drop(*p, false, &h, cp, nil))
  774. //different ID is blocked
  775. p.RemotePort++
  776. require.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
  777. })
  778. })
  779. }
  780. func TestFirewall_ProtocolRules(t *testing.T) {
  781. l := test.NewLogger()
  782. myVpnNetworksTable := new(bart.Lite)
  783. myVpnNetworksTable.Insert(netip.MustParsePrefix("1.1.1.1/8"))
  784. network := netip.MustParsePrefix("1.2.3.4/24")
  785. c := cert.CachedCertificate{
  786. Certificate: &dummyCert{
  787. name: "host1",
  788. networks: []netip.Prefix{network},
  789. groups: []string{"default-group"},
  790. issuer: "signer-shasum",
  791. },
  792. InvertedGroups: map[string]struct{}{"default-group": {}},
  793. }
  794. h := HostInfo{
  795. ConnectionState: &ConnectionState{
  796. peerCert: &c,
  797. },
  798. vpnAddrs: []netip.Addr{network.Addr()},
  799. }
  800. h.buildNetworks(myVpnNetworksTable, c.Certificate)
  801. cp := cert.NewCAPool()
  802. protos := []uint8{iputil.IPProtocolTCP, iputil.IPProtocolUDP, iputil.IPProtocolUDPLite, iputil.IPProtocolDCCP, iputil.IPProtocolSCTP}
  803. for _, ruleProto := range protos {
  804. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  805. rb := firewall.NewRulesBuilder(l)
  806. require.NoError(t, rb.AddRule(true, ruleProto, 80, 80, []string{"any"}, "", "", "", "", ""))
  807. fw.setRules(rb)
  808. for _, pktProto := range protos {
  809. p := firewall.Packet{
  810. LocalAddr: netip.MustParseAddr("1.2.3.4"),
  811. RemoteAddr: netip.MustParseAddr("1.2.3.4"),
  812. LocalPort: 80,
  813. RemotePort: 5000,
  814. Protocol: pktProto,
  815. }
  816. if pktProto == ruleProto {
  817. require.NoError(t, fw.Drop(p, true, &h, cp, nil), "rule %d, packet %d", ruleProto, pktProto)
  818. p.LocalPort = 81
  819. assert.Equal(t, ErrNoMatchingRule, fw.Drop(p, true, &h, cp, nil), "rule %d, packet %d, wrong port", ruleProto, pktProto)
  820. } else {
  821. assert.Equal(t, ErrNoMatchingRule, fw.Drop(p, true, &h, cp, nil), "rule %d, packet %d", ruleProto, pktProto)
  822. }
  823. }
  824. }
  825. pkt := func(proto uint8) firewall.Packet {
  826. return firewall.Packet{
  827. LocalAddr: netip.MustParseAddr("1.2.3.4"),
  828. RemoteAddr: netip.MustParseAddr("1.2.3.4"),
  829. Protocol: proto,
  830. }
  831. }
  832. // A rule on any other protocol number only matches that protocol
  833. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  834. rb := firewall.NewRulesBuilder(l)
  835. require.NoError(t, rb.AddRule(true, 47, firewall.PortAny, firewall.PortAny, []string{"any"}, "", "", "", "", "")) // GRE
  836. fw.setRules(rb)
  837. require.NoError(t, fw.Drop(pkt(47), true, &h, cp, nil))
  838. assert.Equal(t, ErrNoMatchingRule, fw.Drop(pkt(50), true, &h, cp, nil)) // ESP
  839. assert.Equal(t, ErrNoMatchingRule, fw.Drop(pkt(iputil.IPProtocolTCP), true, &h, cp, nil))
  840. // A rule on either ICMP or ICMPv6 matches both
  841. for _, ruleProto := range []uint8{iputil.IPProtocolICMP, iputil.IPProtocolICMPv6} {
  842. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  843. rb := firewall.NewRulesBuilder(l)
  844. require.NoError(t, rb.AddRule(true, ruleProto, firewall.PortAny, firewall.PortAny, []string{"any"}, "", "", "", "", ""))
  845. fw.setRules(rb)
  846. require.NoError(t, fw.Drop(pkt(iputil.IPProtocolICMP), true, &h, cp, nil), "rule %d", ruleProto)
  847. require.NoError(t, fw.Drop(pkt(iputil.IPProtocolICMPv6), true, &h, cp, nil), "rule %d", ruleProto)
  848. assert.Equal(t, ErrNoMatchingRule, fw.Drop(pkt(47), true, &h, cp, nil), "rule %d", ruleProto)
  849. }
  850. // proto `any` rules apply to protocols with rules of their own, whichever rule was added first
  851. for _, anyFirst := range []bool{true, false} {
  852. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  853. rb := firewall.NewRulesBuilder(l)
  854. addAny := func() {
  855. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 80, 80, []string{"any"}, "", "", "", "", ""))
  856. }
  857. if anyFirst {
  858. addAny()
  859. }
  860. require.NoError(t, rb.AddRule(true, iputil.IPProtocolTCP, 22, 22, []string{"any"}, "", "", "", "", ""))
  861. if !anyFirst {
  862. addAny()
  863. }
  864. fw.setRules(rb)
  865. for _, tc := range []struct {
  866. proto uint8
  867. port uint16
  868. want error
  869. }{
  870. {iputil.IPProtocolTCP, 22, nil},
  871. {iputil.IPProtocolTCP, 80, nil},
  872. {iputil.IPProtocolTCP, 23, ErrNoMatchingRule},
  873. {iputil.IPProtocolUDP, 80, nil},
  874. {iputil.IPProtocolUDP, 22, ErrNoMatchingRule},
  875. } {
  876. p := pkt(tc.proto)
  877. p.LocalPort = tc.port
  878. assert.Equal(t, tc.want, fw.Drop(p, true, &h, cp, nil), "anyFirst %v, proto %d, port %d", anyFirst, tc.proto, tc.port)
  879. }
  880. }
  881. // ICMP and ICMPv6 share one copy of each proto `any` rule, whichever rule was added first
  882. for _, anyFirst := range []bool{true, false} {
  883. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  884. rb := firewall.NewRulesBuilder(l)
  885. addAny := func() {
  886. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, firewall.PortAny, firewall.PortAny, []string{"default-group"}, "", "", "", "", ""))
  887. }
  888. if anyFirst {
  889. addAny()
  890. }
  891. require.NoError(t, rb.AddRule(true, iputil.IPProtocolICMPv6, firewall.PortAny, firewall.PortAny, []string{"nope"}, "", "", "", "", ""))
  892. if !anyFirst {
  893. addAny()
  894. }
  895. fw.setRules(rb)
  896. require.NoError(t, fw.Drop(pkt(iputil.IPProtocolICMP), true, &h, cp, nil), "anyFirst %v", anyFirst)
  897. require.NoError(t, fw.Drop(pkt(iputil.IPProtocolICMPv6), true, &h, cp, nil), "anyFirst %v", anyFirst)
  898. }
  899. // Protocols without rules of their own have no rules to check until there is a proto `any` rule to share
  900. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  901. rb = firewall.NewRulesBuilder(l)
  902. require.NoError(t, rb.AddRule(true, iputil.IPProtocolTCP, 22, 22, []string{"any"}, "", "", "", "", ""))
  903. fw.setRules(rb)
  904. assert.Equal(t, ErrNoMatchingRule, fw.Drop(pkt(47), true, &h, cp, nil))
  905. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  906. rb = firewall.NewRulesBuilder(l)
  907. require.NoError(t, rb.AddRule(true, iputil.IPProtocolTCP, 22, 22, []string{"any"}, "", "", "", "", ""))
  908. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, firewall.PortAny, firewall.PortAny, []string{"any"}, "", "", "", "", ""))
  909. fw.setRules(rb)
  910. require.NoError(t, fw.Drop(pkt(47), true, &h, cp, nil))
  911. }
  912. func TestFirewall_DropIPSpoofing(t *testing.T) {
  913. ob := &bytes.Buffer{}
  914. l := test.NewLoggerWithOutput(ob)
  915. myVpnNetworksTable := new(bart.Lite)
  916. myVpnNetworksTable.Insert(netip.MustParsePrefix("192.0.2.1/24"))
  917. c := cert.CachedCertificate{
  918. Certificate: &dummyCert{
  919. name: "host-owner",
  920. networks: []netip.Prefix{netip.MustParsePrefix("192.0.2.1/24")},
  921. },
  922. }
  923. c1 := cert.CachedCertificate{
  924. Certificate: &dummyCert{
  925. name: "host",
  926. networks: []netip.Prefix{netip.MustParsePrefix("192.0.2.2/24")},
  927. unsafeNetworks: []netip.Prefix{netip.MustParsePrefix("198.51.100.0/24")},
  928. },
  929. }
  930. h1 := HostInfo{
  931. ConnectionState: &ConnectionState{
  932. peerCert: &c1,
  933. },
  934. vpnAddrs: []netip.Addr{c1.Certificate.Networks()[0].Addr()},
  935. }
  936. h1.buildNetworks(myVpnNetworksTable, c1.Certificate)
  937. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  938. rb := firewall.NewRulesBuilder(l)
  939. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 1, 1, []string{}, "", "", "", "", ""))
  940. fw.setRules(rb)
  941. cp := cert.NewCAPool()
  942. // Packet spoofed by `c1`. Note that the remote addr is not a valid one.
  943. p := firewall.Packet{
  944. LocalAddr: netip.MustParseAddr("192.0.2.1"),
  945. RemoteAddr: netip.MustParseAddr("192.0.2.3"),
  946. LocalPort: 1,
  947. RemotePort: 1,
  948. Protocol: iputil.IPProtocolUDP,
  949. Fragment: false,
  950. }
  951. assert.Equal(t, fw.Drop(p, true, &h1, cp, nil), ErrInvalidRemoteIP)
  952. }
  953. func TestFirewall_ConntrackSourceSpoofingAcrossPeers(t *testing.T) {
  954. l := test.NewLoggerWithOutput(&bytes.Buffer{})
  955. myVpnNetworksTable := new(bart.Lite)
  956. myVpnNetworksTable.Insert(netip.MustParsePrefix("192.0.2.1/24"))
  957. owner := &dummyCert{
  958. name: "owner",
  959. networks: []netip.Prefix{netip.MustParsePrefix("192.0.2.1/24")},
  960. }
  961. victim := &cert.CachedCertificate{
  962. Certificate: &dummyCert{
  963. name: "victim",
  964. networks: []netip.Prefix{netip.MustParsePrefix("192.0.2.2/24")},
  965. },
  966. }
  967. victimHI := HostInfo{
  968. ConnectionState: &ConnectionState{peerCert: victim},
  969. vpnAddrs: []netip.Addr{netip.MustParseAddr("192.0.2.2")},
  970. }
  971. victimHI.buildNetworks(myVpnNetworksTable, victim.Certificate)
  972. attacker := &cert.CachedCertificate{
  973. Certificate: &dummyCert{
  974. name: "attacker",
  975. networks: []netip.Prefix{netip.MustParsePrefix("192.0.2.3/24")},
  976. },
  977. }
  978. attackerHI := HostInfo{
  979. ConnectionState: &ConnectionState{peerCert: attacker},
  980. vpnAddrs: []netip.Addr{netip.MustParseAddr("192.0.2.3")},
  981. }
  982. attackerHI.buildNetworks(myVpnNetworksTable, attacker.Certificate)
  983. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, owner)
  984. rb := firewall.NewRulesBuilder(l)
  985. // Allow any inbound traffic that passes the cert / source-IP checks.
  986. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 0, 0, []string{"any"}, "", "", "", "", ""))
  987. fw.setRules(rb)
  988. cp := cert.NewCAPool()
  989. flow := firewall.Packet{
  990. LocalAddr: netip.MustParseAddr("192.0.2.1"),
  991. RemoteAddr: netip.MustParseAddr("192.0.2.2"),
  992. LocalPort: 443,
  993. RemotePort: 55000,
  994. Protocol: iputil.IPProtocolUDP,
  995. }
  996. require.NoError(t, fw.Drop(flow, true, &victimHI, cp, nil),
  997. "victim's own traffic from its own overlay IP must be allowed")
  998. unseen := flow
  999. unseen.RemotePort = 55001
  1000. assert.Equal(t, ErrInvalidRemoteIP, fw.Drop(unseen, true, &attackerHI, cp, nil),
  1001. "sanity: attacker forging victim's source IP must be rejected when no conntrack entry exists")
  1002. got := fw.Drop(flow, true, &attackerHI, cp, nil)
  1003. t.Logf("attacker replaying victim's 4-tuple: Drop returned %v (nil == packet ALLOWED == spoof succeeded)", got)
  1004. assert.Equal(t, ErrInvalidRemoteIP, got,
  1005. "SECURITY: attacker spoofed victim's overlay source IP (192.0.2.2) by reusing an existing conntrack 4-tuple; Drop returned %v instead of rejecting", got)
  1006. }
  1007. // BenchmarkFirewallDropConntrackHit measures Drop on an already-established flow
  1008. // (a conntrack hit). This is the fast path that the source-IP<->cert binding
  1009. // reordering adds work to, so it quantifies the cost of moving the address checks
  1010. // ahead of the conntrack lookup. Cases:
  1011. // - simple: peer cert has one address, no unsafe networks (h.networks == nil),
  1012. // so the remote-address check is a single netip.Addr compare.
  1013. // - complex: peer cert has unsafe networks (h.networks populated), so the
  1014. // remote-address check is a BART lookup.
  1015. // - noCache/localCache: whether a per-batch ConntrackCache is supplied, which in
  1016. // the original code let the fast path skip straight past the address checks.
  1017. func BenchmarkFirewallDropConntrackHit(b *testing.B) {
  1018. l := test.NewLoggerWithOutput(&bytes.Buffer{})
  1019. myVpnNetworksTable := new(bart.Lite)
  1020. myVpnNetworksTable.Insert(netip.MustParsePrefix("192.0.2.1/24"))
  1021. owner := &dummyCert{
  1022. name: "owner",
  1023. networks: []netip.Prefix{netip.MustParsePrefix("192.0.2.1/24")},
  1024. }
  1025. simpleCert := &cert.CachedCertificate{
  1026. Certificate: &dummyCert{
  1027. name: "simple",
  1028. networks: []netip.Prefix{netip.MustParsePrefix("192.0.2.2/24")},
  1029. },
  1030. }
  1031. simpleHost := &HostInfo{
  1032. ConnectionState: &ConnectionState{peerCert: simpleCert},
  1033. vpnAddrs: []netip.Addr{netip.MustParseAddr("192.0.2.2")},
  1034. }
  1035. simpleHost.buildNetworks(myVpnNetworksTable, simpleCert.Certificate)
  1036. complexCert := &cert.CachedCertificate{
  1037. Certificate: &dummyCert{
  1038. name: "complex",
  1039. networks: []netip.Prefix{netip.MustParsePrefix("192.0.2.2/24")},
  1040. unsafeNetworks: []netip.Prefix{netip.MustParsePrefix("198.51.100.0/24")},
  1041. },
  1042. }
  1043. complexHost := &HostInfo{
  1044. ConnectionState: &ConnectionState{peerCert: complexCert},
  1045. vpnAddrs: []netip.Addr{netip.MustParseAddr("192.0.2.2")},
  1046. }
  1047. complexHost.buildNetworks(myVpnNetworksTable, complexCert.Certificate)
  1048. cp := cert.NewCAPool()
  1049. flow := firewall.Packet{
  1050. LocalAddr: netip.MustParseAddr("192.0.2.1"),
  1051. RemoteAddr: netip.MustParseAddr("192.0.2.2"),
  1052. LocalPort: 443,
  1053. RemotePort: 55000,
  1054. Protocol: iputil.IPProtocolUDP,
  1055. }
  1056. cases := []struct {
  1057. name string
  1058. host *HostInfo
  1059. useCache bool
  1060. }{
  1061. {"simple/noCache", simpleHost, false},
  1062. {"simple/localCache", simpleHost, true},
  1063. {"complex/noCache", complexHost, false},
  1064. {"complex/localCache", complexHost, true},
  1065. }
  1066. for _, tc := range cases {
  1067. b.Run(tc.name, func(b *testing.B) {
  1068. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, owner)
  1069. rb := firewall.NewRulesBuilder(l)
  1070. require.NoError(b, rb.AddRule(true, firewall.ProtoAny, 0, 0, []string{"any"}, "", "", "", "", ""))
  1071. fw.setRules(rb)
  1072. // Establish the conntrack entry so every benchmarked Drop is a hit.
  1073. require.NoError(b, fw.Drop(flow, true, tc.host, cp, nil))
  1074. var cache firewall.ConntrackCache
  1075. if tc.useCache {
  1076. cache = firewall.ConntrackCache{}
  1077. }
  1078. b.ReportAllocs()
  1079. b.ResetTimer()
  1080. for i := 0; i < b.N; i++ {
  1081. if err := fw.Drop(flow, true, tc.host, cp, cache); err != nil {
  1082. b.Fatal(err)
  1083. }
  1084. }
  1085. })
  1086. }
  1087. }
  1088. func BenchmarkLookup(b *testing.B) {
  1089. ml := func(m map[string]struct{}, a [][]string) {
  1090. for n := 0; n < b.N; n++ {
  1091. for _, sg := range a {
  1092. found := false
  1093. for _, g := range sg {
  1094. if _, ok := m[g]; !ok {
  1095. found = false
  1096. break
  1097. }
  1098. found = true
  1099. }
  1100. if found {
  1101. return
  1102. }
  1103. }
  1104. }
  1105. }
  1106. b.Run("array to map best", func(b *testing.B) {
  1107. m := map[string]struct{}{
  1108. "1ne": {},
  1109. "2wo": {},
  1110. "3hr": {},
  1111. "4ou": {},
  1112. "5iv": {},
  1113. "6ix": {},
  1114. }
  1115. a := [][]string{
  1116. {"1ne", "2wo", "3hr", "4ou", "5iv", "6ix"},
  1117. {"one", "2wo", "3hr", "4ou", "5iv", "6ix"},
  1118. {"one", "two", "3hr", "4ou", "5iv", "6ix"},
  1119. {"one", "two", "thr", "4ou", "5iv", "6ix"},
  1120. {"one", "two", "thr", "fou", "5iv", "6ix"},
  1121. {"one", "two", "thr", "fou", "fiv", "6ix"},
  1122. {"one", "two", "thr", "fou", "fiv", "six"},
  1123. }
  1124. for n := 0; n < b.N; n++ {
  1125. ml(m, a)
  1126. }
  1127. })
  1128. b.Run("array to map worst", func(b *testing.B) {
  1129. m := map[string]struct{}{
  1130. "one": {},
  1131. "two": {},
  1132. "thr": {},
  1133. "fou": {},
  1134. "fiv": {},
  1135. "six": {},
  1136. }
  1137. a := [][]string{
  1138. {"1ne", "2wo", "3hr", "4ou", "5iv", "6ix"},
  1139. {"one", "2wo", "3hr", "4ou", "5iv", "6ix"},
  1140. {"one", "two", "3hr", "4ou", "5iv", "6ix"},
  1141. {"one", "two", "thr", "4ou", "5iv", "6ix"},
  1142. {"one", "two", "thr", "fou", "5iv", "6ix"},
  1143. {"one", "two", "thr", "fou", "fiv", "6ix"},
  1144. {"one", "two", "thr", "fou", "fiv", "six"},
  1145. }
  1146. for n := 0; n < b.N; n++ {
  1147. ml(m, a)
  1148. }
  1149. })
  1150. }
  1151. func TestNewFirewallFromConfig(t *testing.T) {
  1152. l := test.NewLogger()
  1153. // Test a bad rule definition
  1154. c := &dummyCert{}
  1155. cs, err := newCertState(cert.Version2, nil, c, false, cert.Curve_CURVE25519, nil, "aes")
  1156. require.NoError(t, err)
  1157. conf := config.NewC(test.NewLogger())
  1158. conf.Settings["firewall"] = map[string]any{"outbound": "asdf"}
  1159. _, err = NewFirewallFromConfig(l, cs, conf)
  1160. require.EqualError(t, err, "firewall.outbound failed to parse, should be an array of rules")
  1161. // Test both port and code
  1162. conf = config.NewC(test.NewLogger())
  1163. conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"port": "1", "code": "2"}}}
  1164. _, err = NewFirewallFromConfig(l, cs, conf)
  1165. require.EqualError(t, err, "firewall.outbound rule #0; only one of port or code should be provided")
  1166. // Test missing host, group, cidr, ca_name and ca_sha
  1167. conf = config.NewC(test.NewLogger())
  1168. conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{}}}
  1169. _, err = NewFirewallFromConfig(l, cs, conf)
  1170. require.EqualError(t, err, "firewall.outbound rule #0; at least one of host, group, cidr, local_cidr, ca_name, or ca_sha must be provided")
  1171. // Test code/port error
  1172. conf = config.NewC(test.NewLogger())
  1173. conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"code": "a", "host": "testh", "proto": "any"}}}
  1174. _, err = NewFirewallFromConfig(l, cs, conf)
  1175. require.EqualError(t, err, "firewall.outbound rule #0; code was not a number; `a`")
  1176. conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"port": "a", "host": "testh", "proto": "any"}}}
  1177. _, err = NewFirewallFromConfig(l, cs, conf)
  1178. require.EqualError(t, err, "firewall.outbound rule #0; port was not a number; `a`")
  1179. // Test proto error
  1180. conf = config.NewC(test.NewLogger())
  1181. conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"code": "1", "host": "testh"}}}
  1182. _, err = NewFirewallFromConfig(l, cs, conf)
  1183. require.EqualError(t, err, "firewall.outbound rule #0; proto was not understood; ``")
  1184. // Test cidr parse error
  1185. conf = config.NewC(test.NewLogger())
  1186. conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"code": "1", "cidr": "testh", "proto": "any"}}}
  1187. _, err = NewFirewallFromConfig(l, cs, conf)
  1188. require.EqualError(t, err, "firewall.outbound rule #0; cidr did not parse; netip.ParsePrefix(\"testh\"): no '/'")
  1189. // Test local_cidr parse error
  1190. conf = config.NewC(test.NewLogger())
  1191. conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"code": "1", "local_cidr": "testh", "proto": "any"}}}
  1192. _, err = NewFirewallFromConfig(l, cs, conf)
  1193. require.EqualError(t, err, "firewall.outbound rule #0; local_cidr did not parse; netip.ParsePrefix(\"testh\"): no '/'")
  1194. // Test both group and groups
  1195. conf = config.NewC(test.NewLogger())
  1196. conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "group": "a", "groups": []string{"b", "c"}}}}
  1197. _, err = NewFirewallFromConfig(l, cs, conf)
  1198. require.EqualError(t, err, "firewall.inbound rule #0; only one of group or groups should be defined, both provided")
  1199. }
  1200. type testcase struct {
  1201. h *HostInfo
  1202. p firewall.Packet
  1203. c cert.Certificate
  1204. err error
  1205. }
  1206. func (c *testcase) Test(t *testing.T, fw *Firewall) {
  1207. t.Helper()
  1208. cp := cert.NewCAPool()
  1209. resetConntrack(fw)
  1210. err := fw.Drop(c.p, true, c.h, cp, nil)
  1211. if c.err == nil {
  1212. require.NoError(t, err, "failed to not drop remote address %s", c.p.RemoteAddr)
  1213. } else {
  1214. require.ErrorIs(t, c.err, err, "failed to drop remote address %s", c.p.RemoteAddr)
  1215. }
  1216. }
  1217. func buildTestCase(setup testsetup, err error, theirPrefixes ...netip.Prefix) testcase {
  1218. c1 := dummyCert{
  1219. name: "host1",
  1220. networks: theirPrefixes,
  1221. groups: []string{"default-group"},
  1222. issuer: "signer-shasum",
  1223. }
  1224. h := HostInfo{
  1225. ConnectionState: &ConnectionState{
  1226. peerCert: &cert.CachedCertificate{
  1227. Certificate: &c1,
  1228. InvertedGroups: map[string]struct{}{"default-group": {}},
  1229. },
  1230. },
  1231. vpnAddrs: make([]netip.Addr, len(theirPrefixes)),
  1232. }
  1233. for i := range theirPrefixes {
  1234. h.vpnAddrs[i] = theirPrefixes[i].Addr()
  1235. }
  1236. h.buildNetworks(setup.myVpnNetworksTable, &c1)
  1237. p := firewall.Packet{
  1238. LocalAddr: setup.c.Networks()[0].Addr(), //todo?
  1239. RemoteAddr: theirPrefixes[0].Addr(),
  1240. LocalPort: 10,
  1241. RemotePort: 90,
  1242. Protocol: iputil.IPProtocolUDP,
  1243. Fragment: false,
  1244. }
  1245. return testcase{
  1246. h: &h,
  1247. p: p,
  1248. c: &c1,
  1249. err: err,
  1250. }
  1251. }
  1252. type testsetup struct {
  1253. c dummyCert
  1254. myVpnNetworksTable *bart.Lite
  1255. fw *Firewall
  1256. }
  1257. func newSetup(t *testing.T, l *slog.Logger, myPrefixes ...netip.Prefix) testsetup {
  1258. c := dummyCert{
  1259. name: "me",
  1260. networks: myPrefixes,
  1261. groups: []string{"default-group"},
  1262. issuer: "signer-shasum",
  1263. }
  1264. return newSetupFromCert(t, l, c)
  1265. }
  1266. func newSetupFromCert(t *testing.T, l *slog.Logger, c dummyCert) testsetup {
  1267. myVpnNetworksTable := new(bart.Lite)
  1268. for _, prefix := range c.Networks() {
  1269. myVpnNetworksTable.Insert(prefix)
  1270. }
  1271. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  1272. rb := firewall.NewRulesBuilder(l)
  1273. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 0, 0, []string{"any"}, "", "", "", "", ""))
  1274. fw.setRules(rb)
  1275. return testsetup{
  1276. c: c,
  1277. fw: fw,
  1278. myVpnNetworksTable: myVpnNetworksTable,
  1279. }
  1280. }
  1281. func TestFirewall_Drop_EnforceIPMatch(t *testing.T) {
  1282. t.Parallel()
  1283. ob := &bytes.Buffer{}
  1284. l := test.NewLoggerWithOutput(ob)
  1285. myPrefix := netip.MustParsePrefix("1.1.1.1/8")
  1286. // for now, it's okay that these are all "incoming", the logic this test tries to check doesn't care about in/out
  1287. t.Run("allow inbound all matching", func(t *testing.T) {
  1288. t.Parallel()
  1289. setup := newSetup(t, l, myPrefix)
  1290. tc := buildTestCase(setup, nil, netip.MustParsePrefix("1.2.3.4/24"))
  1291. tc.Test(t, setup.fw)
  1292. })
  1293. t.Run("allow inbound local matching", func(t *testing.T) {
  1294. t.Parallel()
  1295. setup := newSetup(t, l, myPrefix)
  1296. tc := buildTestCase(setup, ErrInvalidLocalIP, netip.MustParsePrefix("1.2.3.4/24"))
  1297. tc.p.LocalAddr = netip.MustParseAddr("1.2.3.8")
  1298. tc.Test(t, setup.fw)
  1299. })
  1300. t.Run("block inbound remote mismatched", func(t *testing.T) {
  1301. t.Parallel()
  1302. setup := newSetup(t, l, myPrefix)
  1303. tc := buildTestCase(setup, ErrInvalidRemoteIP, netip.MustParsePrefix("1.2.3.4/24"))
  1304. tc.p.RemoteAddr = netip.MustParseAddr("9.9.9.9")
  1305. tc.Test(t, setup.fw)
  1306. })
  1307. t.Run("Block a vpn peer packet", func(t *testing.T) {
  1308. t.Parallel()
  1309. setup := newSetup(t, l, myPrefix)
  1310. tc := buildTestCase(setup, ErrPeerRejected, netip.MustParsePrefix("2.2.2.2/24"))
  1311. tc.Test(t, setup.fw)
  1312. })
  1313. twoPrefixes := []netip.Prefix{
  1314. netip.MustParsePrefix("1.2.3.4/24"), netip.MustParsePrefix("2.2.2.2/24"),
  1315. }
  1316. t.Run("allow inbound one matching", func(t *testing.T) {
  1317. t.Parallel()
  1318. setup := newSetup(t, l, myPrefix)
  1319. tc := buildTestCase(setup, nil, twoPrefixes...)
  1320. tc.Test(t, setup.fw)
  1321. })
  1322. t.Run("block inbound multimismatch", func(t *testing.T) {
  1323. t.Parallel()
  1324. setup := newSetup(t, l, myPrefix)
  1325. tc := buildTestCase(setup, ErrInvalidRemoteIP, twoPrefixes...)
  1326. tc.p.RemoteAddr = netip.MustParseAddr("9.9.9.9")
  1327. tc.Test(t, setup.fw)
  1328. })
  1329. t.Run("allow inbound 2nd one matching", func(t *testing.T) {
  1330. t.Parallel()
  1331. setup2 := newSetup(t, l, netip.MustParsePrefix("2.2.2.1/24"))
  1332. tc := buildTestCase(setup2, nil, twoPrefixes...)
  1333. tc.p.RemoteAddr = twoPrefixes[1].Addr()
  1334. tc.Test(t, setup2.fw)
  1335. })
  1336. t.Run("allow inbound unsafe route", func(t *testing.T) {
  1337. t.Parallel()
  1338. unsafePrefix := netip.MustParsePrefix("192.168.0.0/24")
  1339. c := dummyCert{
  1340. name: "me",
  1341. networks: []netip.Prefix{myPrefix},
  1342. unsafeNetworks: []netip.Prefix{unsafePrefix},
  1343. groups: []string{"default-group"},
  1344. issuer: "signer-shasum",
  1345. }
  1346. unsafeSetup := newSetupFromCert(t, l, c)
  1347. tc := buildTestCase(unsafeSetup, nil, twoPrefixes...)
  1348. tc.p.LocalAddr = netip.MustParseAddr("192.168.0.3")
  1349. tc.err = ErrNoMatchingRule
  1350. tc.Test(t, unsafeSetup.fw) //should hit firewall and bounce off
  1351. // The same rules plus one for the unsafe route
  1352. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  1353. rb := firewall.NewRulesBuilder(l)
  1354. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 0, 0, []string{"any"}, "", "", "", "", ""))
  1355. require.NoError(t, rb.AddRule(true, firewall.ProtoAny, 0, 0, []string{"any"}, "", "", unsafePrefix.String(), "", ""))
  1356. fw.setRules(rb)
  1357. tc.err = nil
  1358. tc.Test(t, fw) //should pass
  1359. })
  1360. }
  1361. // setRules builds rb for fw's networks and makes them its rules
  1362. func (f *Firewall) setRules(rb *firewall.RulesBuilder) {
  1363. f.rules = rb.Build(f.assignedNetworks, f.unsafeNetworks)
  1364. }
  1365. func resetConntrack(fw *Firewall) {
  1366. fw.Conntrack.Lock()
  1367. fw.Conntrack.Conns = map[firewall.Packet]*conn{}
  1368. fw.Conntrack.Unlock()
  1369. }