firewall_test.go 50 KB

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