firewall_test.go 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047
  1. package nebula
  2. import (
  3. "bytes"
  4. "errors"
  5. "math"
  6. "net/netip"
  7. "testing"
  8. "time"
  9. "github.com/slackhq/nebula/cert"
  10. "github.com/slackhq/nebula/config"
  11. "github.com/slackhq/nebula/firewall"
  12. "github.com/slackhq/nebula/test"
  13. "github.com/stretchr/testify/assert"
  14. "github.com/stretchr/testify/require"
  15. )
  16. func TestNewFirewall(t *testing.T) {
  17. l := test.NewLogger()
  18. c := &dummyCert{}
  19. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  20. conntrack := fw.Conntrack
  21. assert.NotNil(t, conntrack)
  22. assert.NotNil(t, conntrack.Conns)
  23. assert.NotNil(t, conntrack.TimerWheel)
  24. assert.NotNil(t, fw.InRules)
  25. assert.NotNil(t, fw.OutRules)
  26. assert.Equal(t, time.Second, fw.TCPTimeout)
  27. assert.Equal(t, time.Minute, fw.UDPTimeout)
  28. assert.Equal(t, time.Hour, fw.DefaultTimeout)
  29. assert.Equal(t, time.Hour, conntrack.TimerWheel.wheelDuration)
  30. assert.Equal(t, time.Hour, conntrack.TimerWheel.wheelDuration)
  31. assert.Equal(t, 3602, conntrack.TimerWheel.wheelLen)
  32. fw = NewFirewall(l, time.Second, time.Hour, time.Minute, c)
  33. assert.Equal(t, time.Hour, conntrack.TimerWheel.wheelDuration)
  34. assert.Equal(t, 3602, conntrack.TimerWheel.wheelLen)
  35. fw = NewFirewall(l, time.Hour, time.Second, time.Minute, c)
  36. assert.Equal(t, time.Hour, conntrack.TimerWheel.wheelDuration)
  37. assert.Equal(t, 3602, conntrack.TimerWheel.wheelLen)
  38. fw = NewFirewall(l, time.Hour, time.Minute, time.Second, c)
  39. assert.Equal(t, time.Hour, conntrack.TimerWheel.wheelDuration)
  40. assert.Equal(t, 3602, conntrack.TimerWheel.wheelLen)
  41. fw = NewFirewall(l, time.Minute, time.Hour, time.Second, c)
  42. assert.Equal(t, time.Hour, conntrack.TimerWheel.wheelDuration)
  43. assert.Equal(t, 3602, conntrack.TimerWheel.wheelLen)
  44. fw = NewFirewall(l, time.Minute, time.Second, time.Hour, c)
  45. assert.Equal(t, time.Hour, conntrack.TimerWheel.wheelDuration)
  46. assert.Equal(t, 3602, conntrack.TimerWheel.wheelLen)
  47. }
  48. func TestFirewall_AddRule(t *testing.T) {
  49. l := test.NewLogger()
  50. ob := &bytes.Buffer{}
  51. l.SetOutput(ob)
  52. c := &dummyCert{}
  53. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  54. assert.NotNil(t, fw.InRules)
  55. assert.NotNil(t, fw.OutRules)
  56. ti, err := netip.ParsePrefix("1.2.3.4/32")
  57. require.NoError(t, err)
  58. ti6, err := netip.ParsePrefix("fd12::34/128")
  59. require.NoError(t, err)
  60. require.NoError(t, fw.AddRule(true, firewall.ProtoTCP, 1, 1, []string{}, "", netip.Prefix{}, netip.Prefix{}, "", ""))
  61. // An empty rule is any
  62. assert.True(t, fw.InRules.TCP[1].Any.Any.Any)
  63. assert.Empty(t, fw.InRules.TCP[1].Any.Groups)
  64. assert.Empty(t, fw.InRules.TCP[1].Any.Hosts)
  65. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  66. require.NoError(t, fw.AddRule(true, firewall.ProtoUDP, 1, 1, []string{"g1"}, "", netip.Prefix{}, netip.Prefix{}, "", ""))
  67. assert.Nil(t, fw.InRules.UDP[1].Any.Any)
  68. assert.Contains(t, fw.InRules.UDP[1].Any.Groups[0].Groups, "g1")
  69. assert.Empty(t, fw.InRules.UDP[1].Any.Hosts)
  70. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  71. require.NoError(t, fw.AddRule(true, firewall.ProtoICMP, 1, 1, []string{}, "h1", netip.Prefix{}, netip.Prefix{}, "", ""))
  72. assert.Nil(t, fw.InRules.ICMP[1].Any.Any)
  73. assert.Empty(t, fw.InRules.ICMP[1].Any.Groups)
  74. assert.Contains(t, fw.InRules.ICMP[1].Any.Hosts, "h1")
  75. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  76. require.NoError(t, fw.AddRule(false, firewall.ProtoAny, 1, 1, []string{}, "", ti, netip.Prefix{}, "", ""))
  77. assert.Nil(t, fw.OutRules.AnyProto[1].Any.Any)
  78. _, ok := fw.OutRules.AnyProto[1].Any.CIDR.Get(ti)
  79. assert.True(t, ok)
  80. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  81. require.NoError(t, fw.AddRule(false, firewall.ProtoAny, 1, 1, []string{}, "", ti6, netip.Prefix{}, "", ""))
  82. assert.Nil(t, fw.OutRules.AnyProto[1].Any.Any)
  83. _, ok = fw.OutRules.AnyProto[1].Any.CIDR.Get(ti6)
  84. assert.True(t, ok)
  85. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  86. require.NoError(t, fw.AddRule(false, firewall.ProtoAny, 1, 1, []string{}, "", netip.Prefix{}, ti, "", ""))
  87. assert.NotNil(t, fw.OutRules.AnyProto[1].Any.Any)
  88. _, ok = fw.OutRules.AnyProto[1].Any.Any.LocalCIDR.Get(ti)
  89. assert.True(t, ok)
  90. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  91. require.NoError(t, fw.AddRule(false, firewall.ProtoAny, 1, 1, []string{}, "", netip.Prefix{}, ti6, "", ""))
  92. assert.NotNil(t, fw.OutRules.AnyProto[1].Any.Any)
  93. _, ok = fw.OutRules.AnyProto[1].Any.Any.LocalCIDR.Get(ti6)
  94. assert.True(t, ok)
  95. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  96. require.NoError(t, fw.AddRule(true, firewall.ProtoUDP, 1, 1, []string{"g1"}, "", netip.Prefix{}, netip.Prefix{}, "ca-name", ""))
  97. assert.Contains(t, fw.InRules.UDP[1].CANames, "ca-name")
  98. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  99. require.NoError(t, fw.AddRule(true, firewall.ProtoUDP, 1, 1, []string{"g1"}, "", netip.Prefix{}, netip.Prefix{}, "", "ca-sha"))
  100. assert.Contains(t, fw.InRules.UDP[1].CAShas, "ca-sha")
  101. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  102. require.NoError(t, fw.AddRule(false, firewall.ProtoAny, 0, 0, []string{}, "any", netip.Prefix{}, netip.Prefix{}, "", ""))
  103. assert.True(t, fw.OutRules.AnyProto[0].Any.Any.Any)
  104. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  105. anyIp, err := netip.ParsePrefix("0.0.0.0/0")
  106. require.NoError(t, err)
  107. require.NoError(t, fw.AddRule(false, firewall.ProtoAny, 0, 0, []string{}, "", anyIp, netip.Prefix{}, "", ""))
  108. assert.True(t, fw.OutRules.AnyProto[0].Any.Any.Any)
  109. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  110. anyIp6, err := netip.ParsePrefix("::/0")
  111. require.NoError(t, err)
  112. require.NoError(t, fw.AddRule(false, firewall.ProtoAny, 0, 0, []string{}, "", anyIp6, netip.Prefix{}, "", ""))
  113. assert.True(t, fw.OutRules.AnyProto[0].Any.Any.Any)
  114. // Test error conditions
  115. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  116. require.Error(t, fw.AddRule(true, math.MaxUint8, 0, 0, []string{}, "", netip.Prefix{}, netip.Prefix{}, "", ""))
  117. require.Error(t, fw.AddRule(true, firewall.ProtoAny, 10, 0, []string{}, "", netip.Prefix{}, netip.Prefix{}, "", ""))
  118. }
  119. func TestFirewall_Drop(t *testing.T) {
  120. l := test.NewLogger()
  121. ob := &bytes.Buffer{}
  122. l.SetOutput(ob)
  123. p := firewall.Packet{
  124. LocalAddr: netip.MustParseAddr("1.2.3.4"),
  125. RemoteAddr: netip.MustParseAddr("1.2.3.4"),
  126. LocalPort: 10,
  127. RemotePort: 90,
  128. Protocol: firewall.ProtoUDP,
  129. Fragment: false,
  130. }
  131. c := dummyCert{
  132. name: "host1",
  133. networks: []netip.Prefix{netip.MustParsePrefix("1.2.3.4/24")},
  134. groups: []string{"default-group"},
  135. issuer: "signer-shasum",
  136. }
  137. h := HostInfo{
  138. ConnectionState: &ConnectionState{
  139. peerCert: &cert.CachedCertificate{
  140. Certificate: &c,
  141. InvertedGroups: map[string]struct{}{"default-group": {}},
  142. },
  143. },
  144. vpnAddrs: []netip.Addr{netip.MustParseAddr("1.2.3.4")},
  145. }
  146. h.buildNetworks(c.networks, c.unsafeNetworks)
  147. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  148. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"any"}, "", netip.Prefix{}, netip.Prefix{}, "", ""))
  149. cp := cert.NewCAPool()
  150. // Drop outbound
  151. assert.Equal(t, ErrNoMatchingRule, fw.Drop(p, false, &h, cp, nil))
  152. // Allow inbound
  153. resetConntrack(fw)
  154. require.NoError(t, fw.Drop(p, true, &h, cp, nil))
  155. // Allow outbound because conntrack
  156. require.NoError(t, fw.Drop(p, false, &h, cp, nil))
  157. // test remote mismatch
  158. oldRemote := p.RemoteAddr
  159. p.RemoteAddr = netip.MustParseAddr("1.2.3.10")
  160. assert.Equal(t, fw.Drop(p, false, &h, cp, nil), ErrInvalidRemoteIP)
  161. p.RemoteAddr = oldRemote
  162. // ensure signer doesn't get in the way of group checks
  163. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  164. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", netip.Prefix{}, netip.Prefix{}, "", "signer-shasum"))
  165. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", netip.Prefix{}, netip.Prefix{}, "", "signer-shasum-bad"))
  166. assert.Equal(t, fw.Drop(p, true, &h, cp, nil), ErrNoMatchingRule)
  167. // test caSha doesn't drop on match
  168. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  169. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", netip.Prefix{}, netip.Prefix{}, "", "signer-shasum-bad"))
  170. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", netip.Prefix{}, netip.Prefix{}, "", "signer-shasum"))
  171. require.NoError(t, fw.Drop(p, true, &h, cp, nil))
  172. // ensure ca name doesn't get in the way of group checks
  173. cp.CAs["signer-shasum"] = &cert.CachedCertificate{Certificate: &dummyCert{name: "ca-good"}}
  174. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  175. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", netip.Prefix{}, netip.Prefix{}, "ca-good", ""))
  176. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", netip.Prefix{}, netip.Prefix{}, "ca-good-bad", ""))
  177. assert.Equal(t, fw.Drop(p, true, &h, cp, nil), ErrNoMatchingRule)
  178. // test caName doesn't drop on match
  179. cp.CAs["signer-shasum"] = &cert.CachedCertificate{Certificate: &dummyCert{name: "ca-good"}}
  180. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  181. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", netip.Prefix{}, netip.Prefix{}, "ca-good-bad", ""))
  182. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", netip.Prefix{}, netip.Prefix{}, "ca-good", ""))
  183. require.NoError(t, fw.Drop(p, true, &h, cp, nil))
  184. }
  185. func TestFirewall_DropV6(t *testing.T) {
  186. l := test.NewLogger()
  187. ob := &bytes.Buffer{}
  188. l.SetOutput(ob)
  189. p := firewall.Packet{
  190. LocalAddr: netip.MustParseAddr("fd12::34"),
  191. RemoteAddr: netip.MustParseAddr("fd12::34"),
  192. LocalPort: 10,
  193. RemotePort: 90,
  194. Protocol: firewall.ProtoUDP,
  195. Fragment: false,
  196. }
  197. c := dummyCert{
  198. name: "host1",
  199. networks: []netip.Prefix{netip.MustParsePrefix("fd12::34/120")},
  200. groups: []string{"default-group"},
  201. issuer: "signer-shasum",
  202. }
  203. h := HostInfo{
  204. ConnectionState: &ConnectionState{
  205. peerCert: &cert.CachedCertificate{
  206. Certificate: &c,
  207. InvertedGroups: map[string]struct{}{"default-group": {}},
  208. },
  209. },
  210. vpnAddrs: []netip.Addr{netip.MustParseAddr("fd12::34")},
  211. }
  212. h.buildNetworks(c.networks, c.unsafeNetworks)
  213. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  214. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"any"}, "", netip.Prefix{}, netip.Prefix{}, "", ""))
  215. cp := cert.NewCAPool()
  216. // Drop outbound
  217. assert.Equal(t, ErrNoMatchingRule, fw.Drop(p, false, &h, cp, nil))
  218. // Allow inbound
  219. resetConntrack(fw)
  220. require.NoError(t, fw.Drop(p, true, &h, cp, nil))
  221. // Allow outbound because conntrack
  222. require.NoError(t, fw.Drop(p, false, &h, cp, nil))
  223. // test remote mismatch
  224. oldRemote := p.RemoteAddr
  225. p.RemoteAddr = netip.MustParseAddr("fd12::56")
  226. assert.Equal(t, fw.Drop(p, false, &h, cp, nil), ErrInvalidRemoteIP)
  227. p.RemoteAddr = oldRemote
  228. // ensure signer doesn't get in the way of group checks
  229. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  230. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", netip.Prefix{}, netip.Prefix{}, "", "signer-shasum"))
  231. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", netip.Prefix{}, netip.Prefix{}, "", "signer-shasum-bad"))
  232. assert.Equal(t, fw.Drop(p, true, &h, cp, nil), ErrNoMatchingRule)
  233. // test caSha doesn't drop on match
  234. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  235. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", netip.Prefix{}, netip.Prefix{}, "", "signer-shasum-bad"))
  236. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", netip.Prefix{}, netip.Prefix{}, "", "signer-shasum"))
  237. require.NoError(t, fw.Drop(p, true, &h, cp, nil))
  238. // ensure ca name doesn't get in the way of group checks
  239. cp.CAs["signer-shasum"] = &cert.CachedCertificate{Certificate: &dummyCert{name: "ca-good"}}
  240. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  241. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", netip.Prefix{}, netip.Prefix{}, "ca-good", ""))
  242. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", netip.Prefix{}, netip.Prefix{}, "ca-good-bad", ""))
  243. assert.Equal(t, fw.Drop(p, true, &h, cp, nil), ErrNoMatchingRule)
  244. // test caName doesn't drop on match
  245. cp.CAs["signer-shasum"] = &cert.CachedCertificate{Certificate: &dummyCert{name: "ca-good"}}
  246. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  247. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", netip.Prefix{}, netip.Prefix{}, "ca-good-bad", ""))
  248. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", netip.Prefix{}, netip.Prefix{}, "ca-good", ""))
  249. require.NoError(t, fw.Drop(p, true, &h, cp, nil))
  250. }
  251. func BenchmarkFirewallTable_match(b *testing.B) {
  252. f := &Firewall{}
  253. ft := FirewallTable{
  254. TCP: firewallPort{},
  255. }
  256. pfix := netip.MustParsePrefix("172.1.1.1/32")
  257. _ = ft.TCP.addRule(f, 10, 10, []string{"good-group"}, "good-host", pfix, netip.Prefix{}, "", "")
  258. _ = ft.TCP.addRule(f, 100, 100, []string{"good-group"}, "good-host", netip.Prefix{}, pfix, "", "")
  259. pfix6 := netip.MustParsePrefix("fd11::11/128")
  260. _ = ft.TCP.addRule(f, 10, 10, []string{"good-group"}, "good-host", pfix6, netip.Prefix{}, "", "")
  261. _ = ft.TCP.addRule(f, 100, 100, []string{"good-group"}, "good-host", netip.Prefix{}, pfix6, "", "")
  262. cp := cert.NewCAPool()
  263. b.Run("fail on proto", func(b *testing.B) {
  264. // This benchmark is showing us the cost of failing to match the protocol
  265. c := &cert.CachedCertificate{
  266. Certificate: &dummyCert{},
  267. }
  268. for n := 0; n < b.N; n++ {
  269. assert.False(b, ft.match(firewall.Packet{Protocol: firewall.ProtoUDP}, true, c, cp))
  270. }
  271. })
  272. b.Run("pass proto, fail on port", func(b *testing.B) {
  273. // This benchmark is showing us the cost of matching a specific protocol but failing to match the port
  274. c := &cert.CachedCertificate{
  275. Certificate: &dummyCert{},
  276. }
  277. for n := 0; n < b.N; n++ {
  278. assert.False(b, ft.match(firewall.Packet{Protocol: firewall.ProtoTCP, LocalPort: 1}, true, c, cp))
  279. }
  280. })
  281. b.Run("pass proto, port, fail on local CIDR", func(b *testing.B) {
  282. c := &cert.CachedCertificate{
  283. Certificate: &dummyCert{},
  284. }
  285. ip := netip.MustParsePrefix("9.254.254.254/32")
  286. for n := 0; n < b.N; n++ {
  287. assert.False(b, ft.match(firewall.Packet{Protocol: firewall.ProtoTCP, LocalPort: 100, LocalAddr: ip.Addr()}, true, c, cp))
  288. }
  289. })
  290. b.Run("pass proto, port, fail on local CIDRv6", func(b *testing.B) {
  291. c := &cert.CachedCertificate{
  292. Certificate: &dummyCert{},
  293. }
  294. ip := netip.MustParsePrefix("fd99::99/128")
  295. for n := 0; n < b.N; n++ {
  296. assert.False(b, ft.match(firewall.Packet{Protocol: firewall.ProtoTCP, LocalPort: 100, LocalAddr: ip.Addr()}, true, c, cp))
  297. }
  298. })
  299. b.Run("pass proto, port, any local CIDR, fail all group, name, and cidr", func(b *testing.B) {
  300. c := &cert.CachedCertificate{
  301. Certificate: &dummyCert{
  302. name: "nope",
  303. networks: []netip.Prefix{netip.MustParsePrefix("9.254.254.245/32")},
  304. },
  305. InvertedGroups: map[string]struct{}{"nope": {}},
  306. }
  307. for n := 0; n < b.N; n++ {
  308. assert.False(b, ft.match(firewall.Packet{Protocol: firewall.ProtoTCP, LocalPort: 10}, true, c, cp))
  309. }
  310. })
  311. b.Run("pass proto, port, any local CIDRv6, fail all group, name, and cidr", func(b *testing.B) {
  312. c := &cert.CachedCertificate{
  313. Certificate: &dummyCert{
  314. name: "nope",
  315. networks: []netip.Prefix{netip.MustParsePrefix("fd99::99/128")},
  316. },
  317. InvertedGroups: map[string]struct{}{"nope": {}},
  318. }
  319. for n := 0; n < b.N; n++ {
  320. assert.False(b, ft.match(firewall.Packet{Protocol: firewall.ProtoTCP, LocalPort: 10}, true, c, cp))
  321. }
  322. })
  323. b.Run("pass proto, port, specific local CIDR, fail all group, name, and cidr", func(b *testing.B) {
  324. c := &cert.CachedCertificate{
  325. Certificate: &dummyCert{
  326. name: "nope",
  327. networks: []netip.Prefix{netip.MustParsePrefix("9.254.254.245/32")},
  328. },
  329. InvertedGroups: map[string]struct{}{"nope": {}},
  330. }
  331. for n := 0; n < b.N; n++ {
  332. assert.False(b, ft.match(firewall.Packet{Protocol: firewall.ProtoTCP, LocalPort: 100, LocalAddr: pfix.Addr()}, true, c, cp))
  333. }
  334. })
  335. b.Run("pass proto, port, specific local CIDRv6, fail all group, name, and cidr", func(b *testing.B) {
  336. c := &cert.CachedCertificate{
  337. Certificate: &dummyCert{
  338. name: "nope",
  339. networks: []netip.Prefix{netip.MustParsePrefix("fd99:99/128")},
  340. },
  341. InvertedGroups: map[string]struct{}{"nope": {}},
  342. }
  343. for n := 0; n < b.N; n++ {
  344. assert.False(b, ft.match(firewall.Packet{Protocol: firewall.ProtoTCP, LocalPort: 100, LocalAddr: pfix6.Addr()}, true, c, cp))
  345. }
  346. })
  347. b.Run("pass on group on any local cidr", func(b *testing.B) {
  348. c := &cert.CachedCertificate{
  349. Certificate: &dummyCert{
  350. name: "nope",
  351. },
  352. InvertedGroups: map[string]struct{}{"good-group": {}},
  353. }
  354. for n := 0; n < b.N; n++ {
  355. assert.True(b, ft.match(firewall.Packet{Protocol: firewall.ProtoTCP, LocalPort: 10}, true, c, cp))
  356. }
  357. })
  358. b.Run("pass on group on specific local cidr", func(b *testing.B) {
  359. c := &cert.CachedCertificate{
  360. Certificate: &dummyCert{
  361. name: "nope",
  362. },
  363. InvertedGroups: map[string]struct{}{"good-group": {}},
  364. }
  365. for n := 0; n < b.N; n++ {
  366. assert.True(b, ft.match(firewall.Packet{Protocol: firewall.ProtoTCP, LocalPort: 100, LocalAddr: pfix.Addr()}, true, c, cp))
  367. }
  368. })
  369. b.Run("pass on group on specific local cidr6", func(b *testing.B) {
  370. c := &cert.CachedCertificate{
  371. Certificate: &dummyCert{
  372. name: "nope",
  373. },
  374. InvertedGroups: map[string]struct{}{"good-group": {}},
  375. }
  376. for n := 0; n < b.N; n++ {
  377. assert.True(b, ft.match(firewall.Packet{Protocol: firewall.ProtoTCP, LocalPort: 100, LocalAddr: pfix6.Addr()}, true, c, cp))
  378. }
  379. })
  380. b.Run("pass on name", func(b *testing.B) {
  381. c := &cert.CachedCertificate{
  382. Certificate: &dummyCert{
  383. name: "good-host",
  384. },
  385. InvertedGroups: map[string]struct{}{"nope": {}},
  386. }
  387. for n := 0; n < b.N; n++ {
  388. ft.match(firewall.Packet{Protocol: firewall.ProtoTCP, LocalPort: 10}, true, c, cp)
  389. }
  390. })
  391. }
  392. func TestFirewall_Drop2(t *testing.T) {
  393. l := test.NewLogger()
  394. ob := &bytes.Buffer{}
  395. l.SetOutput(ob)
  396. p := firewall.Packet{
  397. LocalAddr: netip.MustParseAddr("1.2.3.4"),
  398. RemoteAddr: netip.MustParseAddr("1.2.3.4"),
  399. LocalPort: 10,
  400. RemotePort: 90,
  401. Protocol: firewall.ProtoUDP,
  402. Fragment: false,
  403. }
  404. network := netip.MustParsePrefix("1.2.3.4/24")
  405. c := cert.CachedCertificate{
  406. Certificate: &dummyCert{
  407. name: "host1",
  408. networks: []netip.Prefix{network},
  409. },
  410. InvertedGroups: map[string]struct{}{"default-group": {}, "test-group": {}},
  411. }
  412. h := HostInfo{
  413. ConnectionState: &ConnectionState{
  414. peerCert: &c,
  415. },
  416. vpnAddrs: []netip.Addr{network.Addr()},
  417. }
  418. h.buildNetworks(c.Certificate.Networks(), c.Certificate.UnsafeNetworks())
  419. c1 := cert.CachedCertificate{
  420. Certificate: &dummyCert{
  421. name: "host1",
  422. networks: []netip.Prefix{network},
  423. },
  424. InvertedGroups: map[string]struct{}{"default-group": {}, "test-group-not": {}},
  425. }
  426. h1 := HostInfo{
  427. vpnAddrs: []netip.Addr{network.Addr()},
  428. ConnectionState: &ConnectionState{
  429. peerCert: &c1,
  430. },
  431. }
  432. h1.buildNetworks(c1.Certificate.Networks(), c1.Certificate.UnsafeNetworks())
  433. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  434. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group", "test-group"}, "", netip.Prefix{}, netip.Prefix{}, "", ""))
  435. cp := cert.NewCAPool()
  436. // h1/c1 lacks the proper groups
  437. require.ErrorIs(t, fw.Drop(p, true, &h1, cp, nil), ErrNoMatchingRule)
  438. // c has the proper groups
  439. resetConntrack(fw)
  440. require.NoError(t, fw.Drop(p, true, &h, cp, nil))
  441. }
  442. func TestFirewall_Drop3(t *testing.T) {
  443. l := test.NewLogger()
  444. ob := &bytes.Buffer{}
  445. l.SetOutput(ob)
  446. p := firewall.Packet{
  447. LocalAddr: netip.MustParseAddr("1.2.3.4"),
  448. RemoteAddr: netip.MustParseAddr("1.2.3.4"),
  449. LocalPort: 1,
  450. RemotePort: 1,
  451. Protocol: firewall.ProtoUDP,
  452. Fragment: false,
  453. }
  454. network := netip.MustParsePrefix("1.2.3.4/24")
  455. c := cert.CachedCertificate{
  456. Certificate: &dummyCert{
  457. name: "host-owner",
  458. networks: []netip.Prefix{network},
  459. },
  460. }
  461. c1 := cert.CachedCertificate{
  462. Certificate: &dummyCert{
  463. name: "host1",
  464. networks: []netip.Prefix{network},
  465. issuer: "signer-sha-bad",
  466. },
  467. }
  468. h1 := HostInfo{
  469. ConnectionState: &ConnectionState{
  470. peerCert: &c1,
  471. },
  472. vpnAddrs: []netip.Addr{network.Addr()},
  473. }
  474. h1.buildNetworks(c1.Certificate.Networks(), c1.Certificate.UnsafeNetworks())
  475. c2 := cert.CachedCertificate{
  476. Certificate: &dummyCert{
  477. name: "host2",
  478. networks: []netip.Prefix{network},
  479. issuer: "signer-sha",
  480. },
  481. }
  482. h2 := HostInfo{
  483. ConnectionState: &ConnectionState{
  484. peerCert: &c2,
  485. },
  486. vpnAddrs: []netip.Addr{network.Addr()},
  487. }
  488. h2.buildNetworks(c2.Certificate.Networks(), c2.Certificate.UnsafeNetworks())
  489. c3 := cert.CachedCertificate{
  490. Certificate: &dummyCert{
  491. name: "host3",
  492. networks: []netip.Prefix{network},
  493. issuer: "signer-sha-bad",
  494. },
  495. }
  496. h3 := HostInfo{
  497. ConnectionState: &ConnectionState{
  498. peerCert: &c3,
  499. },
  500. vpnAddrs: []netip.Addr{network.Addr()},
  501. }
  502. h3.buildNetworks(c3.Certificate.Networks(), c3.Certificate.UnsafeNetworks())
  503. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  504. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 1, 1, []string{}, "host1", netip.Prefix{}, netip.Prefix{}, "", ""))
  505. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 1, 1, []string{}, "", netip.Prefix{}, netip.Prefix{}, "", "signer-sha"))
  506. cp := cert.NewCAPool()
  507. // c1 should pass because host match
  508. require.NoError(t, fw.Drop(p, true, &h1, cp, nil))
  509. // c2 should pass because ca sha match
  510. resetConntrack(fw)
  511. require.NoError(t, fw.Drop(p, true, &h2, cp, nil))
  512. // c3 should fail because no match
  513. resetConntrack(fw)
  514. assert.Equal(t, fw.Drop(p, true, &h3, cp, nil), ErrNoMatchingRule)
  515. // Test a remote address match
  516. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  517. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 1, 1, []string{}, "", netip.MustParsePrefix("1.2.3.4/24"), netip.Prefix{}, "", ""))
  518. require.NoError(t, fw.Drop(p, true, &h1, cp, nil))
  519. }
  520. func TestFirewall_Drop3V6(t *testing.T) {
  521. l := test.NewLogger()
  522. ob := &bytes.Buffer{}
  523. l.SetOutput(ob)
  524. p := firewall.Packet{
  525. LocalAddr: netip.MustParseAddr("fd12::34"),
  526. RemoteAddr: netip.MustParseAddr("fd12::34"),
  527. LocalPort: 1,
  528. RemotePort: 1,
  529. Protocol: firewall.ProtoUDP,
  530. Fragment: false,
  531. }
  532. network := netip.MustParsePrefix("fd12::34/120")
  533. c := cert.CachedCertificate{
  534. Certificate: &dummyCert{
  535. name: "host-owner",
  536. networks: []netip.Prefix{network},
  537. },
  538. }
  539. h := HostInfo{
  540. ConnectionState: &ConnectionState{
  541. peerCert: &c,
  542. },
  543. vpnAddrs: []netip.Addr{network.Addr()},
  544. }
  545. h.buildNetworks(c.Certificate.Networks(), c.Certificate.UnsafeNetworks())
  546. // Test a remote address match
  547. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  548. cp := cert.NewCAPool()
  549. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 1, 1, []string{}, "", netip.MustParsePrefix("fd12::34/120"), netip.Prefix{}, "", ""))
  550. require.NoError(t, fw.Drop(p, true, &h, cp, nil))
  551. }
  552. func TestFirewall_DropConntrackReload(t *testing.T) {
  553. l := test.NewLogger()
  554. ob := &bytes.Buffer{}
  555. l.SetOutput(ob)
  556. p := firewall.Packet{
  557. LocalAddr: netip.MustParseAddr("1.2.3.4"),
  558. RemoteAddr: netip.MustParseAddr("1.2.3.4"),
  559. LocalPort: 10,
  560. RemotePort: 90,
  561. Protocol: firewall.ProtoUDP,
  562. Fragment: false,
  563. }
  564. network := netip.MustParsePrefix("1.2.3.4/24")
  565. c := cert.CachedCertificate{
  566. Certificate: &dummyCert{
  567. name: "host1",
  568. networks: []netip.Prefix{network},
  569. groups: []string{"default-group"},
  570. issuer: "signer-shasum",
  571. },
  572. InvertedGroups: map[string]struct{}{"default-group": {}},
  573. }
  574. h := HostInfo{
  575. ConnectionState: &ConnectionState{
  576. peerCert: &c,
  577. },
  578. vpnAddrs: []netip.Addr{network.Addr()},
  579. }
  580. h.buildNetworks(c.Certificate.Networks(), c.Certificate.UnsafeNetworks())
  581. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  582. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"any"}, "", netip.Prefix{}, netip.Prefix{}, "", ""))
  583. cp := cert.NewCAPool()
  584. // Drop outbound
  585. assert.Equal(t, fw.Drop(p, false, &h, cp, nil), ErrNoMatchingRule)
  586. // Allow inbound
  587. resetConntrack(fw)
  588. require.NoError(t, fw.Drop(p, true, &h, cp, nil))
  589. // Allow outbound because conntrack
  590. require.NoError(t, fw.Drop(p, false, &h, cp, nil))
  591. oldFw := fw
  592. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  593. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 10, 10, []string{"any"}, "", netip.Prefix{}, netip.Prefix{}, "", ""))
  594. fw.Conntrack = oldFw.Conntrack
  595. fw.rulesVersion = oldFw.rulesVersion + 1
  596. // Allow outbound because conntrack and new rules allow port 10
  597. require.NoError(t, fw.Drop(p, false, &h, cp, nil))
  598. oldFw = fw
  599. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  600. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 11, 11, []string{"any"}, "", netip.Prefix{}, netip.Prefix{}, "", ""))
  601. fw.Conntrack = oldFw.Conntrack
  602. fw.rulesVersion = oldFw.rulesVersion + 1
  603. // Drop outbound because conntrack doesn't match new ruleset
  604. assert.Equal(t, fw.Drop(p, false, &h, cp, nil), ErrNoMatchingRule)
  605. }
  606. func BenchmarkLookup(b *testing.B) {
  607. ml := func(m map[string]struct{}, a [][]string) {
  608. for n := 0; n < b.N; n++ {
  609. for _, sg := range a {
  610. found := false
  611. for _, g := range sg {
  612. if _, ok := m[g]; !ok {
  613. found = false
  614. break
  615. }
  616. found = true
  617. }
  618. if found {
  619. return
  620. }
  621. }
  622. }
  623. }
  624. b.Run("array to map best", func(b *testing.B) {
  625. m := map[string]struct{}{
  626. "1ne": {},
  627. "2wo": {},
  628. "3hr": {},
  629. "4ou": {},
  630. "5iv": {},
  631. "6ix": {},
  632. }
  633. a := [][]string{
  634. {"1ne", "2wo", "3hr", "4ou", "5iv", "6ix"},
  635. {"one", "2wo", "3hr", "4ou", "5iv", "6ix"},
  636. {"one", "two", "3hr", "4ou", "5iv", "6ix"},
  637. {"one", "two", "thr", "4ou", "5iv", "6ix"},
  638. {"one", "two", "thr", "fou", "5iv", "6ix"},
  639. {"one", "two", "thr", "fou", "fiv", "6ix"},
  640. {"one", "two", "thr", "fou", "fiv", "six"},
  641. }
  642. for n := 0; n < b.N; n++ {
  643. ml(m, a)
  644. }
  645. })
  646. b.Run("array to map worst", func(b *testing.B) {
  647. m := map[string]struct{}{
  648. "one": {},
  649. "two": {},
  650. "thr": {},
  651. "fou": {},
  652. "fiv": {},
  653. "six": {},
  654. }
  655. a := [][]string{
  656. {"1ne", "2wo", "3hr", "4ou", "5iv", "6ix"},
  657. {"one", "2wo", "3hr", "4ou", "5iv", "6ix"},
  658. {"one", "two", "3hr", "4ou", "5iv", "6ix"},
  659. {"one", "two", "thr", "4ou", "5iv", "6ix"},
  660. {"one", "two", "thr", "fou", "5iv", "6ix"},
  661. {"one", "two", "thr", "fou", "fiv", "6ix"},
  662. {"one", "two", "thr", "fou", "fiv", "six"},
  663. }
  664. for n := 0; n < b.N; n++ {
  665. ml(m, a)
  666. }
  667. })
  668. }
  669. func Test_parsePort(t *testing.T) {
  670. _, _, err := parsePort("")
  671. require.EqualError(t, err, "was not a number; ``")
  672. _, _, err = parsePort(" ")
  673. require.EqualError(t, err, "was not a number; ` `")
  674. _, _, err = parsePort("-")
  675. require.EqualError(t, err, "appears to be a range but could not be parsed; `-`")
  676. _, _, err = parsePort(" - ")
  677. require.EqualError(t, err, "appears to be a range but could not be parsed; ` - `")
  678. _, _, err = parsePort("a-b")
  679. require.EqualError(t, err, "beginning range was not a number; `a`")
  680. _, _, err = parsePort("1-b")
  681. require.EqualError(t, err, "ending range was not a number; `b`")
  682. s, e, err := parsePort(" 1 - 2 ")
  683. assert.Equal(t, int32(1), s)
  684. assert.Equal(t, int32(2), e)
  685. require.NoError(t, err)
  686. s, e, err = parsePort("0-1")
  687. assert.Equal(t, int32(0), s)
  688. assert.Equal(t, int32(0), e)
  689. require.NoError(t, err)
  690. s, e, err = parsePort("9919")
  691. assert.Equal(t, int32(9919), s)
  692. assert.Equal(t, int32(9919), e)
  693. require.NoError(t, err)
  694. s, e, err = parsePort("any")
  695. assert.Equal(t, int32(0), s)
  696. assert.Equal(t, int32(0), e)
  697. require.NoError(t, err)
  698. }
  699. func TestNewFirewallFromConfig(t *testing.T) {
  700. l := test.NewLogger()
  701. // Test a bad rule definition
  702. c := &dummyCert{}
  703. cs, err := newCertState(cert.Version2, nil, c, false, cert.Curve_CURVE25519, nil)
  704. require.NoError(t, err)
  705. conf := config.NewC(l)
  706. conf.Settings["firewall"] = map[string]any{"outbound": "asdf"}
  707. _, err = NewFirewallFromConfig(l, cs, conf)
  708. require.EqualError(t, err, "firewall.outbound failed to parse, should be an array of rules")
  709. // Test both port and code
  710. conf = config.NewC(l)
  711. conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"port": "1", "code": "2"}}}
  712. _, err = NewFirewallFromConfig(l, cs, conf)
  713. require.EqualError(t, err, "firewall.outbound rule #0; only one of port or code should be provided")
  714. // Test missing host, group, cidr, ca_name and ca_sha
  715. conf = config.NewC(l)
  716. conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{}}}
  717. _, err = NewFirewallFromConfig(l, cs, conf)
  718. 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")
  719. // Test code/port error
  720. conf = config.NewC(l)
  721. conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"code": "a", "host": "testh"}}}
  722. _, err = NewFirewallFromConfig(l, cs, conf)
  723. require.EqualError(t, err, "firewall.outbound rule #0; code was not a number; `a`")
  724. conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"port": "a", "host": "testh"}}}
  725. _, err = NewFirewallFromConfig(l, cs, conf)
  726. require.EqualError(t, err, "firewall.outbound rule #0; port was not a number; `a`")
  727. // Test proto error
  728. conf = config.NewC(l)
  729. conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"code": "1", "host": "testh"}}}
  730. _, err = NewFirewallFromConfig(l, cs, conf)
  731. require.EqualError(t, err, "firewall.outbound rule #0; proto was not understood; ``")
  732. // Test cidr parse error
  733. conf = config.NewC(l)
  734. conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"code": "1", "cidr": "testh", "proto": "any"}}}
  735. _, err = NewFirewallFromConfig(l, cs, conf)
  736. require.EqualError(t, err, "firewall.outbound rule #0; cidr did not parse; netip.ParsePrefix(\"testh\"): no '/'")
  737. // Test local_cidr parse error
  738. conf = config.NewC(l)
  739. conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"code": "1", "local_cidr": "testh", "proto": "any"}}}
  740. _, err = NewFirewallFromConfig(l, cs, conf)
  741. require.EqualError(t, err, "firewall.outbound rule #0; local_cidr did not parse; netip.ParsePrefix(\"testh\"): no '/'")
  742. // Test both group and groups
  743. conf = config.NewC(l)
  744. conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "group": "a", "groups": []string{"b", "c"}}}}
  745. _, err = NewFirewallFromConfig(l, cs, conf)
  746. require.EqualError(t, err, "firewall.inbound rule #0; only one of group or groups should be defined, both provided")
  747. }
  748. func TestAddFirewallRulesFromConfig(t *testing.T) {
  749. l := test.NewLogger()
  750. // Test adding tcp rule
  751. conf := config.NewC(l)
  752. mf := &mockFirewall{}
  753. conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"port": "1", "proto": "tcp", "host": "a"}}}
  754. require.NoError(t, AddFirewallRulesFromConfig(l, false, conf, mf))
  755. assert.Equal(t, addRuleCall{incoming: false, proto: firewall.ProtoTCP, startPort: 1, endPort: 1, groups: nil, host: "a", ip: netip.Prefix{}, localIp: netip.Prefix{}}, mf.lastCall)
  756. // Test adding udp rule
  757. conf = config.NewC(l)
  758. mf = &mockFirewall{}
  759. conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"port": "1", "proto": "udp", "host": "a"}}}
  760. require.NoError(t, AddFirewallRulesFromConfig(l, false, conf, mf))
  761. assert.Equal(t, addRuleCall{incoming: false, proto: firewall.ProtoUDP, startPort: 1, endPort: 1, groups: nil, host: "a", ip: netip.Prefix{}, localIp: netip.Prefix{}}, mf.lastCall)
  762. // Test adding icmp rule
  763. conf = config.NewC(l)
  764. mf = &mockFirewall{}
  765. conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"port": "1", "proto": "icmp", "host": "a"}}}
  766. require.NoError(t, AddFirewallRulesFromConfig(l, false, conf, mf))
  767. assert.Equal(t, addRuleCall{incoming: false, proto: firewall.ProtoICMP, startPort: 1, endPort: 1, groups: nil, host: "a", ip: netip.Prefix{}, localIp: netip.Prefix{}}, mf.lastCall)
  768. // Test adding any rule
  769. conf = config.NewC(l)
  770. mf = &mockFirewall{}
  771. conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "host": "a"}}}
  772. require.NoError(t, AddFirewallRulesFromConfig(l, true, conf, mf))
  773. assert.Equal(t, addRuleCall{incoming: true, proto: firewall.ProtoAny, startPort: 1, endPort: 1, groups: nil, host: "a", ip: netip.Prefix{}, localIp: netip.Prefix{}}, mf.lastCall)
  774. // Test adding rule with cidr
  775. cidr := netip.MustParsePrefix("10.0.0.0/8")
  776. conf = config.NewC(l)
  777. mf = &mockFirewall{}
  778. conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "cidr": cidr.String()}}}
  779. require.NoError(t, AddFirewallRulesFromConfig(l, true, conf, mf))
  780. assert.Equal(t, addRuleCall{incoming: true, proto: firewall.ProtoAny, startPort: 1, endPort: 1, groups: nil, ip: cidr, localIp: netip.Prefix{}}, mf.lastCall)
  781. // Test adding rule with local_cidr
  782. conf = config.NewC(l)
  783. mf = &mockFirewall{}
  784. conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "local_cidr": cidr.String()}}}
  785. require.NoError(t, AddFirewallRulesFromConfig(l, true, conf, mf))
  786. assert.Equal(t, addRuleCall{incoming: true, proto: firewall.ProtoAny, startPort: 1, endPort: 1, groups: nil, ip: netip.Prefix{}, localIp: cidr}, mf.lastCall)
  787. // Test adding rule with cidr ipv6
  788. cidr6 := netip.MustParsePrefix("fd00::/8")
  789. conf = config.NewC(l)
  790. mf = &mockFirewall{}
  791. conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "cidr": cidr6.String()}}}
  792. require.NoError(t, AddFirewallRulesFromConfig(l, true, conf, mf))
  793. assert.Equal(t, addRuleCall{incoming: true, proto: firewall.ProtoAny, startPort: 1, endPort: 1, groups: nil, ip: cidr6, localIp: netip.Prefix{}}, mf.lastCall)
  794. // Test adding rule with local_cidr ipv6
  795. conf = config.NewC(l)
  796. mf = &mockFirewall{}
  797. conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "local_cidr": cidr6.String()}}}
  798. require.NoError(t, AddFirewallRulesFromConfig(l, true, conf, mf))
  799. assert.Equal(t, addRuleCall{incoming: true, proto: firewall.ProtoAny, startPort: 1, endPort: 1, groups: nil, ip: netip.Prefix{}, localIp: cidr6}, mf.lastCall)
  800. // Test adding rule with ca_sha
  801. conf = config.NewC(l)
  802. mf = &mockFirewall{}
  803. conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "ca_sha": "12312313123"}}}
  804. require.NoError(t, AddFirewallRulesFromConfig(l, true, conf, mf))
  805. assert.Equal(t, addRuleCall{incoming: true, proto: firewall.ProtoAny, startPort: 1, endPort: 1, groups: nil, ip: netip.Prefix{}, localIp: netip.Prefix{}, caSha: "12312313123"}, mf.lastCall)
  806. // Test adding rule with ca_name
  807. conf = config.NewC(l)
  808. mf = &mockFirewall{}
  809. conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "ca_name": "root01"}}}
  810. require.NoError(t, AddFirewallRulesFromConfig(l, true, conf, mf))
  811. assert.Equal(t, addRuleCall{incoming: true, proto: firewall.ProtoAny, startPort: 1, endPort: 1, groups: nil, ip: netip.Prefix{}, localIp: netip.Prefix{}, caName: "root01"}, mf.lastCall)
  812. // Test single group
  813. conf = config.NewC(l)
  814. mf = &mockFirewall{}
  815. conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "group": "a"}}}
  816. require.NoError(t, AddFirewallRulesFromConfig(l, true, conf, mf))
  817. assert.Equal(t, addRuleCall{incoming: true, proto: firewall.ProtoAny, startPort: 1, endPort: 1, groups: []string{"a"}, ip: netip.Prefix{}, localIp: netip.Prefix{}}, mf.lastCall)
  818. // Test single groups
  819. conf = config.NewC(l)
  820. mf = &mockFirewall{}
  821. conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "groups": "a"}}}
  822. require.NoError(t, AddFirewallRulesFromConfig(l, true, conf, mf))
  823. assert.Equal(t, addRuleCall{incoming: true, proto: firewall.ProtoAny, startPort: 1, endPort: 1, groups: []string{"a"}, ip: netip.Prefix{}, localIp: netip.Prefix{}}, mf.lastCall)
  824. // Test multiple AND groups
  825. conf = config.NewC(l)
  826. mf = &mockFirewall{}
  827. conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "groups": []string{"a", "b"}}}}
  828. require.NoError(t, AddFirewallRulesFromConfig(l, true, conf, mf))
  829. assert.Equal(t, addRuleCall{incoming: true, proto: firewall.ProtoAny, startPort: 1, endPort: 1, groups: []string{"a", "b"}, ip: netip.Prefix{}, localIp: netip.Prefix{}}, mf.lastCall)
  830. // Test Add error
  831. conf = config.NewC(l)
  832. mf = &mockFirewall{}
  833. mf.nextCallReturn = errors.New("test error")
  834. conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "host": "a"}}}
  835. require.EqualError(t, AddFirewallRulesFromConfig(l, true, conf, mf), "firewall.inbound rule #0; `test error`")
  836. }
  837. func TestFirewall_convertRule(t *testing.T) {
  838. l := test.NewLogger()
  839. ob := &bytes.Buffer{}
  840. l.SetOutput(ob)
  841. // Ensure group array of 1 is converted and a warning is printed
  842. c := map[string]any{
  843. "group": []any{"group1"},
  844. }
  845. r, err := convertRule(l, c, "test", 1)
  846. assert.Contains(t, ob.String(), "test rule #1; group was an array with a single value, converting to simple value")
  847. require.NoError(t, err)
  848. assert.Equal(t, "group1", r.Group)
  849. // Ensure group array of > 1 is errord
  850. ob.Reset()
  851. c = map[string]any{
  852. "group": []any{"group1", "group2"},
  853. }
  854. r, err = convertRule(l, c, "test", 1)
  855. assert.Empty(t, ob.String())
  856. require.Error(t, err, "group should contain a single value, an array with more than one entry was provided")
  857. // Make sure a well formed group is alright
  858. ob.Reset()
  859. c = map[string]any{
  860. "group": "group1",
  861. }
  862. r, err = convertRule(l, c, "test", 1)
  863. require.NoError(t, err)
  864. assert.Equal(t, "group1", r.Group)
  865. }
  866. type addRuleCall struct {
  867. incoming bool
  868. proto uint8
  869. startPort int32
  870. endPort int32
  871. groups []string
  872. host string
  873. ip netip.Prefix
  874. localIp netip.Prefix
  875. caName string
  876. caSha string
  877. }
  878. type mockFirewall struct {
  879. lastCall addRuleCall
  880. nextCallReturn error
  881. }
  882. func (mf *mockFirewall) AddRule(incoming bool, proto uint8, startPort int32, endPort int32, groups []string, host string, ip netip.Prefix, localIp netip.Prefix, caName string, caSha string) error {
  883. mf.lastCall = addRuleCall{
  884. incoming: incoming,
  885. proto: proto,
  886. startPort: startPort,
  887. endPort: endPort,
  888. groups: groups,
  889. host: host,
  890. ip: ip,
  891. localIp: localIp,
  892. caName: caName,
  893. caSha: caSha,
  894. }
  895. err := mf.nextCallReturn
  896. mf.nextCallReturn = nil
  897. return err
  898. }
  899. func resetConntrack(fw *Firewall) {
  900. fw.Conntrack.Lock()
  901. fw.Conntrack.Conns = map[firewall.Packet]*conn{}
  902. fw.Conntrack.Unlock()
  903. }