firewall_test.go 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799
  1. package nebula
  2. import (
  3. "bytes"
  4. "errors"
  5. "log/slog"
  6. "math"
  7. "net/netip"
  8. "testing"
  9. "time"
  10. "github.com/gaissmai/bart"
  11. "github.com/slackhq/nebula/cert"
  12. "github.com/slackhq/nebula/config"
  13. "github.com/slackhq/nebula/firewall"
  14. "github.com/slackhq/nebula/iputil"
  15. "github.com/slackhq/nebula/test"
  16. "github.com/stretchr/testify/assert"
  17. "github.com/stretchr/testify/require"
  18. )
  19. func TestNewFirewall(t *testing.T) {
  20. l := test.NewLogger()
  21. c := &dummyCert{}
  22. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  23. conntrack := fw.Conntrack
  24. assert.NotNil(t, conntrack)
  25. assert.NotNil(t, conntrack.Conns)
  26. assert.NotNil(t, conntrack.TimerWheel)
  27. assert.NotNil(t, fw.InRules)
  28. assert.NotNil(t, fw.OutRules)
  29. assert.Equal(t, time.Second, fw.TCPTimeout)
  30. assert.Equal(t, time.Minute, fw.UDPTimeout)
  31. assert.Equal(t, time.Hour, fw.DefaultTimeout)
  32. assert.Equal(t, time.Hour, conntrack.TimerWheel.wheelDuration)
  33. assert.Equal(t, time.Hour, conntrack.TimerWheel.wheelDuration)
  34. assert.Equal(t, 3602, conntrack.TimerWheel.wheelLen)
  35. fw = NewFirewall(l, time.Second, time.Hour, 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.Second, time.Minute, c)
  39. assert.Equal(t, time.Hour, conntrack.TimerWheel.wheelDuration)
  40. assert.Equal(t, 3602, conntrack.TimerWheel.wheelLen)
  41. fw = NewFirewall(l, time.Hour, time.Minute, 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.Hour, time.Second, c)
  45. assert.Equal(t, time.Hour, conntrack.TimerWheel.wheelDuration)
  46. assert.Equal(t, 3602, conntrack.TimerWheel.wheelLen)
  47. fw = NewFirewall(l, time.Minute, time.Second, time.Hour, c)
  48. assert.Equal(t, time.Hour, conntrack.TimerWheel.wheelDuration)
  49. assert.Equal(t, 3602, conntrack.TimerWheel.wheelLen)
  50. }
  51. func TestFirewall_AddRule(t *testing.T) {
  52. ob := &bytes.Buffer{}
  53. l := test.NewLoggerWithOutput(ob)
  54. c := &dummyCert{}
  55. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  56. assert.NotNil(t, fw.InRules)
  57. assert.NotNil(t, fw.OutRules)
  58. ti, err := netip.ParsePrefix("1.2.3.4/32")
  59. require.NoError(t, err)
  60. ti6, err := netip.ParsePrefix("fd12::34/128")
  61. require.NoError(t, err)
  62. require.NoError(t, fw.AddRule(true, iputil.IPProtocolTCP, 1, 1, []string{}, "", "", "", "", ""))
  63. // An empty rule is any
  64. assert.True(t, fw.InRules.TCP[1].Any.Any.Any)
  65. assert.Empty(t, fw.InRules.TCP[1].Any.Groups)
  66. assert.Empty(t, fw.InRules.TCP[1].Any.Hosts)
  67. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  68. require.NoError(t, fw.AddRule(true, iputil.IPProtocolUDP, 1, 1, []string{"g1"}, "", "", "", "", ""))
  69. assert.Nil(t, fw.InRules.UDP[1].Any.Any)
  70. assert.Contains(t, fw.InRules.UDP[1].Any.Groups[0].Groups, "g1")
  71. assert.Empty(t, fw.InRules.UDP[1].Any.Hosts)
  72. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  73. require.NoError(t, fw.AddRule(true, iputil.IPProtocolICMP, 1, 1, []string{}, "h1", "", "", "", ""))
  74. //no matter what port is given for icmp, it should end up as "any"
  75. assert.Nil(t, fw.InRules.ICMP[firewall.PortAny].Any.Any)
  76. assert.Empty(t, fw.InRules.ICMP[firewall.PortAny].Any.Groups)
  77. assert.Contains(t, fw.InRules.ICMP[firewall.PortAny].Any.Hosts, "h1")
  78. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  79. require.NoError(t, fw.AddRule(false, firewall.ProtoAny, 1, 1, []string{}, "", ti.String(), "", "", ""))
  80. assert.Nil(t, fw.OutRules.AnyProto[1].Any.Any)
  81. _, ok := fw.OutRules.AnyProto[1].Any.CIDR.Get(ti)
  82. assert.True(t, ok)
  83. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  84. require.NoError(t, fw.AddRule(false, firewall.ProtoAny, 1, 1, []string{}, "", ti6.String(), "", "", ""))
  85. assert.Nil(t, fw.OutRules.AnyProto[1].Any.Any)
  86. _, ok = fw.OutRules.AnyProto[1].Any.CIDR.Get(ti6)
  87. assert.True(t, ok)
  88. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  89. require.NoError(t, fw.AddRule(false, firewall.ProtoAny, 1, 1, []string{}, "", "", ti.String(), "", ""))
  90. assert.NotNil(t, fw.OutRules.AnyProto[1].Any.Any)
  91. ok = fw.OutRules.AnyProto[1].Any.Any.LocalCIDR.Get(ti)
  92. assert.True(t, ok)
  93. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  94. require.NoError(t, fw.AddRule(false, firewall.ProtoAny, 1, 1, []string{}, "", "", ti6.String(), "", ""))
  95. assert.NotNil(t, fw.OutRules.AnyProto[1].Any.Any)
  96. ok = fw.OutRules.AnyProto[1].Any.Any.LocalCIDR.Get(ti6)
  97. assert.True(t, ok)
  98. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  99. require.NoError(t, fw.AddRule(true, iputil.IPProtocolUDP, 1, 1, []string{"g1"}, "", "", "", "ca-name", ""))
  100. assert.Contains(t, fw.InRules.UDP[1].CANames, "ca-name")
  101. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  102. require.NoError(t, fw.AddRule(true, iputil.IPProtocolUDP, 1, 1, []string{"g1"}, "", "", "", "", "ca-sha"))
  103. assert.Contains(t, fw.InRules.UDP[1].CAShas, "ca-sha")
  104. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  105. require.NoError(t, fw.AddRule(false, firewall.ProtoAny, 0, 0, []string{}, "any", "", "", "", ""))
  106. assert.True(t, fw.OutRules.AnyProto[0].Any.Any.Any)
  107. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  108. anyIp, err := netip.ParsePrefix("0.0.0.0/0")
  109. require.NoError(t, err)
  110. require.NoError(t, fw.AddRule(false, firewall.ProtoAny, 0, 0, []string{}, "", anyIp.String(), "", "", ""))
  111. assert.Nil(t, fw.OutRules.AnyProto[0].Any.Any)
  112. table, ok := fw.OutRules.AnyProto[0].Any.CIDR.Lookup(netip.MustParseAddr("1.1.1.1"))
  113. assert.True(t, table.Any)
  114. table, ok = fw.OutRules.AnyProto[0].Any.CIDR.Lookup(netip.MustParseAddr("9::9"))
  115. assert.False(t, ok)
  116. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  117. anyIp6, err := netip.ParsePrefix("::/0")
  118. require.NoError(t, err)
  119. require.NoError(t, fw.AddRule(false, firewall.ProtoAny, 0, 0, []string{}, "", anyIp6.String(), "", "", ""))
  120. assert.Nil(t, fw.OutRules.AnyProto[0].Any.Any)
  121. table, ok = fw.OutRules.AnyProto[0].Any.CIDR.Lookup(netip.MustParseAddr("9::9"))
  122. assert.True(t, table.Any)
  123. table, ok = fw.OutRules.AnyProto[0].Any.CIDR.Lookup(netip.MustParseAddr("1.1.1.1"))
  124. assert.False(t, ok)
  125. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  126. require.NoError(t, fw.AddRule(false, firewall.ProtoAny, 0, 0, []string{}, "", "any", "", "", ""))
  127. assert.True(t, fw.OutRules.AnyProto[0].Any.Any.Any)
  128. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  129. require.NoError(t, fw.AddRule(false, firewall.ProtoAny, 0, 0, []string{}, "", "", anyIp.String(), "", ""))
  130. assert.False(t, fw.OutRules.AnyProto[0].Any.Any.Any)
  131. assert.True(t, fw.OutRules.AnyProto[0].Any.Any.LocalCIDR.Lookup(netip.MustParseAddr("1.1.1.1")))
  132. assert.False(t, fw.OutRules.AnyProto[0].Any.Any.LocalCIDR.Lookup(netip.MustParseAddr("9::9")))
  133. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  134. require.NoError(t, fw.AddRule(false, firewall.ProtoAny, 0, 0, []string{}, "", "", anyIp6.String(), "", ""))
  135. assert.False(t, fw.OutRules.AnyProto[0].Any.Any.Any)
  136. assert.True(t, fw.OutRules.AnyProto[0].Any.Any.LocalCIDR.Lookup(netip.MustParseAddr("9::9")))
  137. assert.False(t, fw.OutRules.AnyProto[0].Any.Any.LocalCIDR.Lookup(netip.MustParseAddr("1.1.1.1")))
  138. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  139. require.NoError(t, fw.AddRule(false, firewall.ProtoAny, 0, 0, []string{}, "", "", "any", "", ""))
  140. assert.True(t, fw.OutRules.AnyProto[0].Any.Any.Any)
  141. // Test error conditions
  142. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
  143. require.Error(t, fw.AddRule(true, math.MaxUint8, 0, 0, []string{}, "", "", "", "", ""))
  144. require.Error(t, fw.AddRule(true, firewall.ProtoAny, 10, 0, []string{}, "", "", "", "", ""))
  145. }
  146. func TestFirewall_Drop(t *testing.T) {
  147. ob := &bytes.Buffer{}
  148. l := test.NewLoggerWithOutput(ob)
  149. myVpnNetworksTable := new(bart.Lite)
  150. myVpnNetworksTable.Insert(netip.MustParsePrefix("1.1.1.1/8"))
  151. p := firewall.Packet{
  152. LocalAddr: netip.MustParseAddr("1.2.3.4"),
  153. RemoteAddr: netip.MustParseAddr("1.2.3.4"),
  154. LocalPort: 10,
  155. RemotePort: 90,
  156. Protocol: iputil.IPProtocolUDP,
  157. Fragment: false,
  158. }
  159. c := dummyCert{
  160. name: "host1",
  161. networks: []netip.Prefix{netip.MustParsePrefix("1.2.3.4/24")},
  162. groups: []string{"default-group"},
  163. issuer: "signer-shasum",
  164. }
  165. h := HostInfo{
  166. ConnectionState: &ConnectionState{
  167. peerCert: &cert.CachedCertificate{
  168. Certificate: &c,
  169. InvertedGroups: map[string]struct{}{"default-group": {}},
  170. },
  171. },
  172. vpnAddrs: []netip.Addr{netip.MustParseAddr("1.2.3.4")},
  173. }
  174. h.buildNetworks(myVpnNetworksTable, &c)
  175. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  176. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"any"}, "", "", "", "", ""))
  177. cp := cert.NewCAPool()
  178. // Drop outbound
  179. assert.Equal(t, ErrNoMatchingRule, fw.Drop(p, false, &h, cp, nil))
  180. // Allow inbound
  181. resetConntrack(fw)
  182. require.NoError(t, fw.Drop(p, true, &h, cp, nil))
  183. // Allow outbound because conntrack
  184. require.NoError(t, fw.Drop(p, false, &h, cp, nil))
  185. // test remote mismatch
  186. oldRemote := p.RemoteAddr
  187. p.RemoteAddr = netip.MustParseAddr("1.2.3.10")
  188. assert.Equal(t, fw.Drop(p, false, &h, cp, nil), ErrInvalidRemoteIP)
  189. p.RemoteAddr = oldRemote
  190. // ensure signer doesn't get in the way of group checks
  191. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  192. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "", "signer-shasum"))
  193. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "", "signer-shasum-bad"))
  194. assert.Equal(t, fw.Drop(p, true, &h, cp, nil), ErrNoMatchingRule)
  195. // test caSha doesn't drop on match
  196. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  197. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "", "signer-shasum-bad"))
  198. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "", "signer-shasum"))
  199. require.NoError(t, fw.Drop(p, true, &h, cp, nil))
  200. // ensure ca name doesn't get in the way of group checks
  201. cp.CAs["signer-shasum"] = &cert.CachedCertificate{Certificate: &dummyCert{name: "ca-good"}}
  202. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  203. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "ca-good", ""))
  204. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "ca-good-bad", ""))
  205. assert.Equal(t, fw.Drop(p, true, &h, cp, nil), ErrNoMatchingRule)
  206. // test caName doesn't drop on match
  207. cp.CAs["signer-shasum"] = &cert.CachedCertificate{Certificate: &dummyCert{name: "ca-good"}}
  208. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  209. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "ca-good-bad", ""))
  210. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "ca-good", ""))
  211. require.NoError(t, fw.Drop(p, true, &h, cp, nil))
  212. }
  213. // TestFirewall_DropOverlaySourceThroughUnsafeNetwork: a peer whose unsafe network
  214. // overlaps our overlay may not send as another node of it. Its own address and sources
  215. // outside the overlay still pass through the unsafe network, and outbound to such an
  216. // address, where the address is a destination, is not the firewall's to refuse here.
  217. func TestFirewall_DropOverlaySourceThroughUnsafeNetwork(t *testing.T) {
  218. l := test.NewLogger()
  219. myVpnNetworksTable := new(bart.Lite)
  220. myVpnNetworksTable.Insert(netip.MustParsePrefix("1.2.3.0/24"))
  221. me := dummyCert{name: "me", networks: []netip.Prefix{netip.MustParsePrefix("1.2.3.4/24")}}
  222. // A router for 1.2.0.0/16, which contains the whole overlay.
  223. peer := dummyCert{
  224. name: "router",
  225. networks: []netip.Prefix{netip.MustParsePrefix("1.2.3.9/24")},
  226. unsafeNetworks: []netip.Prefix{netip.MustParsePrefix("1.2.0.0/16")},
  227. groups: []string{"default-group"},
  228. }
  229. h := HostInfo{
  230. ConnectionState: &ConnectionState{
  231. peerCert: &cert.CachedCertificate{Certificate: &peer, InvertedGroups: map[string]struct{}{"default-group": {}}},
  232. },
  233. vpnAddrs: []netip.Addr{netip.MustParseAddr("1.2.3.9")},
  234. }
  235. h.buildNetworks(myVpnNetworksTable, &peer)
  236. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, &me)
  237. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"any"}, "", "", "", "", ""))
  238. cp := cert.NewCAPool()
  239. packet := func(remote string) firewall.Packet {
  240. return firewall.Packet{
  241. LocalAddr: netip.MustParseAddr("1.2.3.4"),
  242. RemoteAddr: netip.MustParseAddr(remote),
  243. LocalPort: 10,
  244. RemotePort: 90,
  245. Protocol: iputil.IPProtocolUDP,
  246. }
  247. }
  248. // Another node's overlay address, through the unsafe network: refused.
  249. assert.Equal(t, ErrInvalidRemoteIP, fw.Drop(packet("1.2.3.10"), true, &h, cp, nil))
  250. assert.Equal(t, int64(1), fw.incomingMetrics.droppedRemoteAddr.Count())
  251. // The peer's own address, and an address outside the overlay it routes for: served.
  252. require.NoError(t, fw.Drop(packet("1.2.3.9"), true, &h, cp, nil))
  253. require.NoError(t, fw.Drop(packet("1.2.5.5"), true, &h, cp, nil))
  254. // Outbound to the overlay address via the router is not refused here; it meets the
  255. // outbound rules as before.
  256. resetConntrack(fw)
  257. assert.Equal(t, ErrNoMatchingRule, fw.Drop(packet("1.2.3.10"), false, &h, cp, nil))
  258. }
  259. func TestFirewall_DropV6(t *testing.T) {
  260. ob := &bytes.Buffer{}
  261. l := test.NewLoggerWithOutput(ob)
  262. myVpnNetworksTable := new(bart.Lite)
  263. myVpnNetworksTable.Insert(netip.MustParsePrefix("fd00::/7"))
  264. p := firewall.Packet{
  265. LocalAddr: netip.MustParseAddr("fd12::34"),
  266. RemoteAddr: netip.MustParseAddr("fd12::34"),
  267. LocalPort: 10,
  268. RemotePort: 90,
  269. Protocol: iputil.IPProtocolUDP,
  270. Fragment: false,
  271. }
  272. c := dummyCert{
  273. name: "host1",
  274. networks: []netip.Prefix{netip.MustParsePrefix("fd12::34/120")},
  275. groups: []string{"default-group"},
  276. issuer: "signer-shasum",
  277. }
  278. h := HostInfo{
  279. ConnectionState: &ConnectionState{
  280. peerCert: &cert.CachedCertificate{
  281. Certificate: &c,
  282. InvertedGroups: map[string]struct{}{"default-group": {}},
  283. },
  284. },
  285. vpnAddrs: []netip.Addr{netip.MustParseAddr("fd12::34")},
  286. }
  287. h.buildNetworks(myVpnNetworksTable, &c)
  288. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  289. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"any"}, "", "", "", "", ""))
  290. cp := cert.NewCAPool()
  291. // Drop outbound
  292. assert.Equal(t, ErrNoMatchingRule, fw.Drop(p, false, &h, cp, nil))
  293. // Allow inbound
  294. resetConntrack(fw)
  295. require.NoError(t, fw.Drop(p, true, &h, cp, nil))
  296. // Allow outbound because conntrack
  297. require.NoError(t, fw.Drop(p, false, &h, cp, nil))
  298. // test remote mismatch
  299. oldRemote := p.RemoteAddr
  300. p.RemoteAddr = netip.MustParseAddr("fd12::56")
  301. assert.Equal(t, fw.Drop(p, false, &h, cp, nil), ErrInvalidRemoteIP)
  302. p.RemoteAddr = oldRemote
  303. // ensure signer doesn't get in the way of group checks
  304. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  305. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "", "signer-shasum"))
  306. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "", "signer-shasum-bad"))
  307. assert.Equal(t, fw.Drop(p, true, &h, cp, nil), ErrNoMatchingRule)
  308. // test caSha doesn't drop on match
  309. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  310. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "", "signer-shasum-bad"))
  311. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "", "signer-shasum"))
  312. require.NoError(t, fw.Drop(p, true, &h, cp, nil))
  313. // ensure ca name doesn't get in the way of group checks
  314. cp.CAs["signer-shasum"] = &cert.CachedCertificate{Certificate: &dummyCert{name: "ca-good"}}
  315. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  316. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "ca-good", ""))
  317. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "ca-good-bad", ""))
  318. assert.Equal(t, fw.Drop(p, true, &h, cp, nil), ErrNoMatchingRule)
  319. // test caName doesn't drop on match
  320. cp.CAs["signer-shasum"] = &cert.CachedCertificate{Certificate: &dummyCert{name: "ca-good"}}
  321. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  322. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "ca-good-bad", ""))
  323. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "ca-good", ""))
  324. require.NoError(t, fw.Drop(p, true, &h, cp, nil))
  325. }
  326. func BenchmarkFirewallTable_match(b *testing.B) {
  327. f := &Firewall{}
  328. ft := FirewallTable{
  329. TCP: firewallPort{},
  330. }
  331. pfix := netip.MustParsePrefix("172.1.1.1/32")
  332. _ = ft.TCP.addRule(f, 10, 10, []string{"good-group"}, "good-host", pfix.String(), "", "", "")
  333. _ = ft.TCP.addRule(f, 100, 100, []string{"good-group"}, "good-host", "", pfix.String(), "", "")
  334. pfix6 := netip.MustParsePrefix("fd11::11/128")
  335. _ = ft.TCP.addRule(f, 10, 10, []string{"good-group"}, "good-host", pfix6.String(), "", "", "")
  336. _ = ft.TCP.addRule(f, 100, 100, []string{"good-group"}, "good-host", "", pfix6.String(), "", "")
  337. cp := cert.NewCAPool()
  338. b.Run("fail on proto", func(b *testing.B) {
  339. // This benchmark is showing us the cost of failing to match the protocol
  340. c := &cert.CachedCertificate{
  341. Certificate: &dummyCert{},
  342. }
  343. for n := 0; n < b.N; n++ {
  344. assert.False(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolUDP}, true, c, cp))
  345. }
  346. })
  347. b.Run("pass proto, fail on port", func(b *testing.B) {
  348. // This benchmark is showing us the cost of matching a specific protocol but failing to match the port
  349. c := &cert.CachedCertificate{
  350. Certificate: &dummyCert{},
  351. }
  352. for n := 0; n < b.N; n++ {
  353. assert.False(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 1}, true, c, cp))
  354. }
  355. })
  356. b.Run("pass proto, port, fail on local CIDR", func(b *testing.B) {
  357. c := &cert.CachedCertificate{
  358. Certificate: &dummyCert{},
  359. }
  360. ip := netip.MustParsePrefix("9.254.254.254/32")
  361. for n := 0; n < b.N; n++ {
  362. assert.False(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 100, LocalAddr: ip.Addr()}, true, c, cp))
  363. }
  364. })
  365. b.Run("pass proto, port, fail on local CIDRv6", func(b *testing.B) {
  366. c := &cert.CachedCertificate{
  367. Certificate: &dummyCert{},
  368. }
  369. ip := netip.MustParsePrefix("fd99::99/128")
  370. for n := 0; n < b.N; n++ {
  371. assert.False(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 100, LocalAddr: ip.Addr()}, true, c, cp))
  372. }
  373. })
  374. b.Run("pass proto, port, any local CIDR, fail all group, name, and cidr", func(b *testing.B) {
  375. c := &cert.CachedCertificate{
  376. Certificate: &dummyCert{
  377. name: "nope",
  378. networks: []netip.Prefix{netip.MustParsePrefix("9.254.254.245/32")},
  379. },
  380. InvertedGroups: map[string]struct{}{"nope": {}},
  381. }
  382. for n := 0; n < b.N; n++ {
  383. assert.False(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 10}, true, c, cp))
  384. }
  385. })
  386. b.Run("pass proto, port, any local CIDRv6, fail all group, name, and cidr", func(b *testing.B) {
  387. c := &cert.CachedCertificate{
  388. Certificate: &dummyCert{
  389. name: "nope",
  390. networks: []netip.Prefix{netip.MustParsePrefix("fd99::99/128")},
  391. },
  392. InvertedGroups: map[string]struct{}{"nope": {}},
  393. }
  394. for n := 0; n < b.N; n++ {
  395. assert.False(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 10}, true, c, cp))
  396. }
  397. })
  398. b.Run("pass proto, port, specific local CIDR, fail all group, name, and cidr", func(b *testing.B) {
  399. c := &cert.CachedCertificate{
  400. Certificate: &dummyCert{
  401. name: "nope",
  402. networks: []netip.Prefix{netip.MustParsePrefix("9.254.254.245/32")},
  403. },
  404. InvertedGroups: map[string]struct{}{"nope": {}},
  405. }
  406. for n := 0; n < b.N; n++ {
  407. assert.False(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 100, LocalAddr: pfix.Addr()}, true, c, cp))
  408. }
  409. })
  410. b.Run("pass proto, port, specific local CIDRv6, fail all group, name, and cidr", func(b *testing.B) {
  411. c := &cert.CachedCertificate{
  412. Certificate: &dummyCert{
  413. name: "nope",
  414. networks: []netip.Prefix{netip.MustParsePrefix("fd99::99/128")},
  415. },
  416. InvertedGroups: map[string]struct{}{"nope": {}},
  417. }
  418. for n := 0; n < b.N; n++ {
  419. assert.False(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 100, LocalAddr: pfix6.Addr()}, true, c, cp))
  420. }
  421. })
  422. b.Run("pass on group on any local cidr", func(b *testing.B) {
  423. c := &cert.CachedCertificate{
  424. Certificate: &dummyCert{
  425. name: "nope",
  426. },
  427. InvertedGroups: map[string]struct{}{"good-group": {}},
  428. }
  429. for n := 0; n < b.N; n++ {
  430. assert.True(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 10}, true, c, cp))
  431. }
  432. })
  433. b.Run("pass on group on specific local cidr", func(b *testing.B) {
  434. c := &cert.CachedCertificate{
  435. Certificate: &dummyCert{
  436. name: "nope",
  437. },
  438. InvertedGroups: map[string]struct{}{"good-group": {}},
  439. }
  440. for n := 0; n < b.N; n++ {
  441. assert.True(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 100, LocalAddr: pfix.Addr()}, true, c, cp))
  442. }
  443. })
  444. b.Run("pass on group on specific local cidr6", func(b *testing.B) {
  445. c := &cert.CachedCertificate{
  446. Certificate: &dummyCert{
  447. name: "nope",
  448. },
  449. InvertedGroups: map[string]struct{}{"good-group": {}},
  450. }
  451. for n := 0; n < b.N; n++ {
  452. assert.True(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 100, LocalAddr: pfix6.Addr()}, true, c, cp))
  453. }
  454. })
  455. b.Run("pass on name", func(b *testing.B) {
  456. c := &cert.CachedCertificate{
  457. Certificate: &dummyCert{
  458. name: "good-host",
  459. },
  460. InvertedGroups: map[string]struct{}{"nope": {}},
  461. }
  462. for n := 0; n < b.N; n++ {
  463. ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 10}, true, c, cp)
  464. }
  465. })
  466. }
  467. func TestFirewall_Drop2(t *testing.T) {
  468. ob := &bytes.Buffer{}
  469. l := test.NewLoggerWithOutput(ob)
  470. myVpnNetworksTable := new(bart.Lite)
  471. myVpnNetworksTable.Insert(netip.MustParsePrefix("1.1.1.1/8"))
  472. p := firewall.Packet{
  473. LocalAddr: netip.MustParseAddr("1.2.3.4"),
  474. RemoteAddr: netip.MustParseAddr("1.2.3.4"),
  475. LocalPort: 10,
  476. RemotePort: 90,
  477. Protocol: iputil.IPProtocolUDP,
  478. Fragment: false,
  479. }
  480. network := netip.MustParsePrefix("1.2.3.4/24")
  481. c := cert.CachedCertificate{
  482. Certificate: &dummyCert{
  483. name: "host1",
  484. networks: []netip.Prefix{network},
  485. },
  486. InvertedGroups: map[string]struct{}{"default-group": {}, "test-group": {}},
  487. }
  488. h := HostInfo{
  489. ConnectionState: &ConnectionState{
  490. peerCert: &c,
  491. },
  492. vpnAddrs: []netip.Addr{network.Addr()},
  493. }
  494. h.buildNetworks(myVpnNetworksTable, c.Certificate)
  495. c1 := cert.CachedCertificate{
  496. Certificate: &dummyCert{
  497. name: "host1",
  498. networks: []netip.Prefix{network},
  499. },
  500. InvertedGroups: map[string]struct{}{"default-group": {}, "test-group-not": {}},
  501. }
  502. h1 := HostInfo{
  503. vpnAddrs: []netip.Addr{network.Addr()},
  504. ConnectionState: &ConnectionState{
  505. peerCert: &c1,
  506. },
  507. }
  508. h1.buildNetworks(myVpnNetworksTable, c1.Certificate)
  509. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  510. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group", "test-group"}, "", "", "", "", ""))
  511. cp := cert.NewCAPool()
  512. // h1/c1 lacks the proper groups
  513. require.ErrorIs(t, fw.Drop(p, true, &h1, cp, nil), ErrNoMatchingRule)
  514. // c has the proper groups
  515. resetConntrack(fw)
  516. require.NoError(t, fw.Drop(p, true, &h, cp, nil))
  517. }
  518. func TestFirewall_Drop3(t *testing.T) {
  519. ob := &bytes.Buffer{}
  520. l := test.NewLoggerWithOutput(ob)
  521. myVpnNetworksTable := new(bart.Lite)
  522. myVpnNetworksTable.Insert(netip.MustParsePrefix("1.1.1.1/8"))
  523. p := firewall.Packet{
  524. LocalAddr: netip.MustParseAddr("1.2.3.4"),
  525. RemoteAddr: netip.MustParseAddr("1.2.3.4"),
  526. LocalPort: 1,
  527. RemotePort: 1,
  528. Protocol: iputil.IPProtocolUDP,
  529. Fragment: false,
  530. }
  531. network := netip.MustParsePrefix("1.2.3.4/24")
  532. c := cert.CachedCertificate{
  533. Certificate: &dummyCert{
  534. name: "host-owner",
  535. networks: []netip.Prefix{network},
  536. },
  537. }
  538. c1 := cert.CachedCertificate{
  539. Certificate: &dummyCert{
  540. name: "host1",
  541. networks: []netip.Prefix{network},
  542. issuer: "signer-sha-bad",
  543. },
  544. }
  545. h1 := HostInfo{
  546. ConnectionState: &ConnectionState{
  547. peerCert: &c1,
  548. },
  549. vpnAddrs: []netip.Addr{network.Addr()},
  550. }
  551. h1.buildNetworks(myVpnNetworksTable, c1.Certificate)
  552. c2 := cert.CachedCertificate{
  553. Certificate: &dummyCert{
  554. name: "host2",
  555. networks: []netip.Prefix{network},
  556. issuer: "signer-sha",
  557. },
  558. }
  559. h2 := HostInfo{
  560. ConnectionState: &ConnectionState{
  561. peerCert: &c2,
  562. },
  563. vpnAddrs: []netip.Addr{network.Addr()},
  564. }
  565. h2.buildNetworks(myVpnNetworksTable, c2.Certificate)
  566. c3 := cert.CachedCertificate{
  567. Certificate: &dummyCert{
  568. name: "host3",
  569. networks: []netip.Prefix{network},
  570. issuer: "signer-sha-bad",
  571. },
  572. }
  573. h3 := HostInfo{
  574. ConnectionState: &ConnectionState{
  575. peerCert: &c3,
  576. },
  577. vpnAddrs: []netip.Addr{network.Addr()},
  578. }
  579. h3.buildNetworks(myVpnNetworksTable, c3.Certificate)
  580. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  581. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 1, 1, []string{}, "host1", "", "", "", ""))
  582. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 1, 1, []string{}, "", "", "", "", "signer-sha"))
  583. cp := cert.NewCAPool()
  584. // c1 should pass because host match
  585. require.NoError(t, fw.Drop(p, true, &h1, cp, nil))
  586. // c2 should pass because ca sha match
  587. resetConntrack(fw)
  588. require.NoError(t, fw.Drop(p, true, &h2, cp, nil))
  589. // c3 should fail because no match
  590. resetConntrack(fw)
  591. assert.Equal(t, fw.Drop(p, true, &h3, cp, nil), ErrNoMatchingRule)
  592. // Test a remote address match
  593. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  594. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 1, 1, []string{}, "", "1.2.3.4/24", "", "", ""))
  595. require.NoError(t, fw.Drop(p, true, &h1, cp, nil))
  596. }
  597. func TestFirewall_Drop3V6(t *testing.T) {
  598. ob := &bytes.Buffer{}
  599. l := test.NewLoggerWithOutput(ob)
  600. myVpnNetworksTable := new(bart.Lite)
  601. myVpnNetworksTable.Insert(netip.MustParsePrefix("fd00::/7"))
  602. p := firewall.Packet{
  603. LocalAddr: netip.MustParseAddr("fd12::34"),
  604. RemoteAddr: netip.MustParseAddr("fd12::34"),
  605. LocalPort: 1,
  606. RemotePort: 1,
  607. Protocol: iputil.IPProtocolUDP,
  608. Fragment: false,
  609. }
  610. network := netip.MustParsePrefix("fd12::34/120")
  611. c := cert.CachedCertificate{
  612. Certificate: &dummyCert{
  613. name: "host-owner",
  614. networks: []netip.Prefix{network},
  615. },
  616. }
  617. h := HostInfo{
  618. ConnectionState: &ConnectionState{
  619. peerCert: &c,
  620. },
  621. vpnAddrs: []netip.Addr{network.Addr()},
  622. }
  623. h.buildNetworks(myVpnNetworksTable, c.Certificate)
  624. // Test a remote address match
  625. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  626. cp := cert.NewCAPool()
  627. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 1, 1, []string{}, "", "fd12::34/120", "", "", ""))
  628. require.NoError(t, fw.Drop(p, true, &h, cp, nil))
  629. }
  630. func TestFirewall_DropConntrackReload(t *testing.T) {
  631. ob := &bytes.Buffer{}
  632. l := test.NewLoggerWithOutput(ob)
  633. myVpnNetworksTable := new(bart.Lite)
  634. myVpnNetworksTable.Insert(netip.MustParsePrefix("1.1.1.1/8"))
  635. p := firewall.Packet{
  636. LocalAddr: netip.MustParseAddr("1.2.3.4"),
  637. RemoteAddr: netip.MustParseAddr("1.2.3.4"),
  638. LocalPort: 10,
  639. RemotePort: 90,
  640. Protocol: iputil.IPProtocolUDP,
  641. Fragment: false,
  642. }
  643. network := netip.MustParsePrefix("1.2.3.4/24")
  644. c := cert.CachedCertificate{
  645. Certificate: &dummyCert{
  646. name: "host1",
  647. networks: []netip.Prefix{network},
  648. groups: []string{"default-group"},
  649. issuer: "signer-shasum",
  650. },
  651. InvertedGroups: map[string]struct{}{"default-group": {}},
  652. }
  653. h := HostInfo{
  654. ConnectionState: &ConnectionState{
  655. peerCert: &c,
  656. },
  657. vpnAddrs: []netip.Addr{network.Addr()},
  658. }
  659. h.buildNetworks(myVpnNetworksTable, c.Certificate)
  660. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  661. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"any"}, "", "", "", "", ""))
  662. cp := cert.NewCAPool()
  663. // Drop outbound
  664. assert.Equal(t, fw.Drop(p, false, &h, cp, nil), ErrNoMatchingRule)
  665. // Allow inbound
  666. resetConntrack(fw)
  667. require.NoError(t, fw.Drop(p, true, &h, cp, nil))
  668. // Allow outbound because conntrack
  669. require.NoError(t, fw.Drop(p, false, &h, cp, nil))
  670. oldFw := fw
  671. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  672. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 10, 10, []string{"any"}, "", "", "", "", ""))
  673. fw.Conntrack = oldFw.Conntrack
  674. fw.rulesVersion = oldFw.rulesVersion + 1
  675. // Allow outbound because conntrack and new rules allow port 10
  676. require.NoError(t, fw.Drop(p, false, &h, cp, nil))
  677. oldFw = fw
  678. fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  679. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 11, 11, []string{"any"}, "", "", "", "", ""))
  680. fw.Conntrack = oldFw.Conntrack
  681. fw.rulesVersion = oldFw.rulesVersion + 1
  682. // Drop outbound because conntrack doesn't match new ruleset
  683. assert.Equal(t, fw.Drop(p, false, &h, cp, nil), ErrNoMatchingRule)
  684. }
  685. func TestFirewall_ICMPPortBehavior(t *testing.T) {
  686. ob := &bytes.Buffer{}
  687. l := test.NewLoggerWithOutput(ob)
  688. myVpnNetworksTable := new(bart.Lite)
  689. myVpnNetworksTable.Insert(netip.MustParsePrefix("1.1.1.1/8"))
  690. network := netip.MustParsePrefix("1.2.3.4/24")
  691. c := cert.CachedCertificate{
  692. Certificate: &dummyCert{
  693. name: "host1",
  694. networks: []netip.Prefix{network},
  695. groups: []string{"default-group"},
  696. issuer: "signer-shasum",
  697. },
  698. InvertedGroups: map[string]struct{}{"default-group": {}},
  699. }
  700. h := HostInfo{
  701. ConnectionState: &ConnectionState{
  702. peerCert: &c,
  703. },
  704. vpnAddrs: []netip.Addr{network.Addr()},
  705. }
  706. h.buildNetworks(myVpnNetworksTable, c.Certificate)
  707. cp := cert.NewCAPool()
  708. templ := firewall.Packet{
  709. LocalAddr: netip.MustParseAddr("1.2.3.4"),
  710. RemoteAddr: netip.MustParseAddr("1.2.3.4"),
  711. Protocol: iputil.IPProtocolICMP,
  712. Fragment: false,
  713. }
  714. t.Run("ICMP allowed", func(t *testing.T) {
  715. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  716. require.NoError(t, fw.AddRule(true, iputil.IPProtocolICMP, 0, 0, []string{"any"}, "", "", "", "", ""))
  717. t.Run("zero ports", func(t *testing.T) {
  718. p := templ.Copy()
  719. p.LocalPort = 0
  720. p.RemotePort = 0
  721. // Drop outbound
  722. assert.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
  723. // Allow inbound
  724. resetConntrack(fw)
  725. require.NoError(t, fw.Drop(*p, true, &h, cp, nil))
  726. //now also allow outbound
  727. require.NoError(t, fw.Drop(*p, false, &h, cp, nil))
  728. })
  729. t.Run("nonzero ports", func(t *testing.T) {
  730. p := templ.Copy()
  731. p.LocalPort = 0xabcd
  732. p.RemotePort = 0x1234
  733. // Drop outbound
  734. assert.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
  735. // Allow inbound
  736. resetConntrack(fw)
  737. require.NoError(t, fw.Drop(*p, true, &h, cp, nil))
  738. //now also allow outbound
  739. require.NoError(t, fw.Drop(*p, false, &h, cp, nil))
  740. })
  741. })
  742. t.Run("Any proto, some ports allowed", func(t *testing.T) {
  743. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  744. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 80, 444, []string{"any"}, "", "", "", "", ""))
  745. t.Run("zero ports, still blocked", func(t *testing.T) {
  746. p := templ.Copy()
  747. p.LocalPort = 0
  748. p.RemotePort = 0
  749. // Drop outbound
  750. assert.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
  751. // Allow inbound
  752. resetConntrack(fw)
  753. assert.Equal(t, fw.Drop(*p, true, &h, cp, nil), ErrNoMatchingRule)
  754. //now also allow outbound
  755. assert.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
  756. })
  757. t.Run("nonzero ports, still blocked", func(t *testing.T) {
  758. p := templ.Copy()
  759. p.LocalPort = 0xabcd
  760. p.RemotePort = 0x1234
  761. // Drop outbound
  762. assert.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
  763. // Allow inbound
  764. resetConntrack(fw)
  765. assert.Equal(t, fw.Drop(*p, true, &h, cp, nil), ErrNoMatchingRule)
  766. //now also allow outbound
  767. assert.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
  768. })
  769. t.Run("nonzero, matching ports, still blocked", func(t *testing.T) {
  770. p := templ.Copy()
  771. p.LocalPort = 80
  772. p.RemotePort = 80
  773. // Drop outbound
  774. assert.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
  775. // Allow inbound
  776. resetConntrack(fw)
  777. assert.Equal(t, fw.Drop(*p, true, &h, cp, nil), ErrNoMatchingRule)
  778. //now also allow outbound
  779. assert.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
  780. })
  781. })
  782. t.Run("Any proto, any port", func(t *testing.T) {
  783. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  784. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"any"}, "", "", "", "", ""))
  785. t.Run("zero ports, allowed", func(t *testing.T) {
  786. resetConntrack(fw)
  787. p := templ.Copy()
  788. p.LocalPort = 0
  789. p.RemotePort = 0
  790. // Drop outbound
  791. assert.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
  792. // Allow inbound
  793. resetConntrack(fw)
  794. require.NoError(t, fw.Drop(*p, true, &h, cp, nil))
  795. //now also allow outbound
  796. require.NoError(t, fw.Drop(*p, false, &h, cp, nil))
  797. })
  798. t.Run("nonzero ports, allowed", func(t *testing.T) {
  799. resetConntrack(fw)
  800. p := templ.Copy()
  801. p.LocalPort = 0xabcd
  802. p.RemotePort = 0x1234
  803. // Drop outbound
  804. assert.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
  805. // Allow inbound
  806. resetConntrack(fw)
  807. require.NoError(t, fw.Drop(*p, true, &h, cp, nil))
  808. //now also allow outbound
  809. require.NoError(t, fw.Drop(*p, false, &h, cp, nil))
  810. //different ID is blocked
  811. p.RemotePort++
  812. require.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
  813. })
  814. })
  815. }
  816. func TestFirewall_DropIPSpoofing(t *testing.T) {
  817. ob := &bytes.Buffer{}
  818. l := test.NewLoggerWithOutput(ob)
  819. myVpnNetworksTable := new(bart.Lite)
  820. myVpnNetworksTable.Insert(netip.MustParsePrefix("192.0.2.1/24"))
  821. c := cert.CachedCertificate{
  822. Certificate: &dummyCert{
  823. name: "host-owner",
  824. networks: []netip.Prefix{netip.MustParsePrefix("192.0.2.1/24")},
  825. },
  826. }
  827. c1 := cert.CachedCertificate{
  828. Certificate: &dummyCert{
  829. name: "host",
  830. networks: []netip.Prefix{netip.MustParsePrefix("192.0.2.2/24")},
  831. unsafeNetworks: []netip.Prefix{netip.MustParsePrefix("198.51.100.0/24")},
  832. },
  833. }
  834. h1 := HostInfo{
  835. ConnectionState: &ConnectionState{
  836. peerCert: &c1,
  837. },
  838. vpnAddrs: []netip.Addr{c1.Certificate.Networks()[0].Addr()},
  839. }
  840. h1.buildNetworks(myVpnNetworksTable, c1.Certificate)
  841. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
  842. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 1, 1, []string{}, "", "", "", "", ""))
  843. cp := cert.NewCAPool()
  844. // Packet spoofed by `c1`. Note that the remote addr is not a valid one.
  845. p := firewall.Packet{
  846. LocalAddr: netip.MustParseAddr("192.0.2.1"),
  847. RemoteAddr: netip.MustParseAddr("192.0.2.3"),
  848. LocalPort: 1,
  849. RemotePort: 1,
  850. Protocol: iputil.IPProtocolUDP,
  851. Fragment: false,
  852. }
  853. assert.Equal(t, fw.Drop(p, true, &h1, cp, nil), ErrInvalidRemoteIP)
  854. }
  855. func TestFirewall_ConntrackSourceSpoofingAcrossPeers(t *testing.T) {
  856. l := test.NewLoggerWithOutput(&bytes.Buffer{})
  857. myVpnNetworksTable := new(bart.Lite)
  858. myVpnNetworksTable.Insert(netip.MustParsePrefix("192.0.2.1/24"))
  859. owner := &dummyCert{
  860. name: "owner",
  861. networks: []netip.Prefix{netip.MustParsePrefix("192.0.2.1/24")},
  862. }
  863. victim := &cert.CachedCertificate{
  864. Certificate: &dummyCert{
  865. name: "victim",
  866. networks: []netip.Prefix{netip.MustParsePrefix("192.0.2.2/24")},
  867. },
  868. }
  869. victimHI := HostInfo{
  870. ConnectionState: &ConnectionState{peerCert: victim},
  871. vpnAddrs: []netip.Addr{netip.MustParseAddr("192.0.2.2")},
  872. }
  873. victimHI.buildNetworks(myVpnNetworksTable, victim.Certificate)
  874. attacker := &cert.CachedCertificate{
  875. Certificate: &dummyCert{
  876. name: "attacker",
  877. networks: []netip.Prefix{netip.MustParsePrefix("192.0.2.3/24")},
  878. },
  879. }
  880. attackerHI := HostInfo{
  881. ConnectionState: &ConnectionState{peerCert: attacker},
  882. vpnAddrs: []netip.Addr{netip.MustParseAddr("192.0.2.3")},
  883. }
  884. attackerHI.buildNetworks(myVpnNetworksTable, attacker.Certificate)
  885. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, owner)
  886. // Allow any inbound traffic that passes the cert / source-IP checks.
  887. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"any"}, "", "", "", "", ""))
  888. cp := cert.NewCAPool()
  889. flow := firewall.Packet{
  890. LocalAddr: netip.MustParseAddr("192.0.2.1"),
  891. RemoteAddr: netip.MustParseAddr("192.0.2.2"),
  892. LocalPort: 443,
  893. RemotePort: 55000,
  894. Protocol: iputil.IPProtocolUDP,
  895. }
  896. require.NoError(t, fw.Drop(flow, true, &victimHI, cp, nil),
  897. "victim's own traffic from its own overlay IP must be allowed")
  898. unseen := flow
  899. unseen.RemotePort = 55001
  900. assert.Equal(t, ErrInvalidRemoteIP, fw.Drop(unseen, true, &attackerHI, cp, nil),
  901. "sanity: attacker forging victim's source IP must be rejected when no conntrack entry exists")
  902. got := fw.Drop(flow, true, &attackerHI, cp, nil)
  903. t.Logf("attacker replaying victim's 4-tuple: Drop returned %v (nil == packet ALLOWED == spoof succeeded)", got)
  904. assert.Equal(t, ErrInvalidRemoteIP, got,
  905. "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)
  906. }
  907. // BenchmarkFirewallDropConntrackHit measures Drop on an already-established flow
  908. // (a conntrack hit). This is the fast path that the source-IP<->cert binding
  909. // reordering adds work to, so it quantifies the cost of moving the address checks
  910. // ahead of the conntrack lookup. Cases:
  911. // - simple: peer cert has one address, no unsafe networks (h.networks == nil),
  912. // so the remote-address check is a single netip.Addr compare.
  913. // - complex: peer cert has unsafe networks (h.networks populated), so the
  914. // remote-address check is a BART lookup.
  915. // - noCache/localCache: whether a per-batch ConntrackCache is supplied, which in
  916. // the original code let the fast path skip straight past the address checks.
  917. func BenchmarkFirewallDropConntrackHit(b *testing.B) {
  918. l := test.NewLoggerWithOutput(&bytes.Buffer{})
  919. myVpnNetworksTable := new(bart.Lite)
  920. myVpnNetworksTable.Insert(netip.MustParsePrefix("192.0.2.1/24"))
  921. owner := &dummyCert{
  922. name: "owner",
  923. networks: []netip.Prefix{netip.MustParsePrefix("192.0.2.1/24")},
  924. }
  925. simpleCert := &cert.CachedCertificate{
  926. Certificate: &dummyCert{
  927. name: "simple",
  928. networks: []netip.Prefix{netip.MustParsePrefix("192.0.2.2/24")},
  929. },
  930. }
  931. simpleHost := &HostInfo{
  932. ConnectionState: &ConnectionState{peerCert: simpleCert},
  933. vpnAddrs: []netip.Addr{netip.MustParseAddr("192.0.2.2")},
  934. }
  935. simpleHost.buildNetworks(myVpnNetworksTable, simpleCert.Certificate)
  936. complexCert := &cert.CachedCertificate{
  937. Certificate: &dummyCert{
  938. name: "complex",
  939. networks: []netip.Prefix{netip.MustParsePrefix("192.0.2.2/24")},
  940. unsafeNetworks: []netip.Prefix{netip.MustParsePrefix("198.51.100.0/24")},
  941. },
  942. }
  943. complexHost := &HostInfo{
  944. ConnectionState: &ConnectionState{peerCert: complexCert},
  945. vpnAddrs: []netip.Addr{netip.MustParseAddr("192.0.2.2")},
  946. }
  947. complexHost.buildNetworks(myVpnNetworksTable, complexCert.Certificate)
  948. cp := cert.NewCAPool()
  949. flow := firewall.Packet{
  950. LocalAddr: netip.MustParseAddr("192.0.2.1"),
  951. RemoteAddr: netip.MustParseAddr("192.0.2.2"),
  952. LocalPort: 443,
  953. RemotePort: 55000,
  954. Protocol: iputil.IPProtocolUDP,
  955. }
  956. cases := []struct {
  957. name string
  958. host *HostInfo
  959. useCache bool
  960. }{
  961. {"simple/noCache", simpleHost, false},
  962. {"simple/localCache", simpleHost, true},
  963. {"complex/noCache", complexHost, false},
  964. {"complex/localCache", complexHost, true},
  965. }
  966. for _, tc := range cases {
  967. b.Run(tc.name, func(b *testing.B) {
  968. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, owner)
  969. require.NoError(b, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"any"}, "", "", "", "", ""))
  970. // Establish the conntrack entry so every benchmarked Drop is a hit.
  971. require.NoError(b, fw.Drop(flow, true, tc.host, cp, nil))
  972. var cache firewall.ConntrackCache
  973. if tc.useCache {
  974. cache = firewall.ConntrackCache{}
  975. }
  976. b.ReportAllocs()
  977. b.ResetTimer()
  978. for i := 0; i < b.N; i++ {
  979. if err := fw.Drop(flow, true, tc.host, cp, cache); err != nil {
  980. b.Fatal(err)
  981. }
  982. }
  983. })
  984. }
  985. }
  986. func BenchmarkLookup(b *testing.B) {
  987. ml := func(m map[string]struct{}, a [][]string) {
  988. for n := 0; n < b.N; n++ {
  989. for _, sg := range a {
  990. found := false
  991. for _, g := range sg {
  992. if _, ok := m[g]; !ok {
  993. found = false
  994. break
  995. }
  996. found = true
  997. }
  998. if found {
  999. return
  1000. }
  1001. }
  1002. }
  1003. }
  1004. b.Run("array to map best", func(b *testing.B) {
  1005. m := map[string]struct{}{
  1006. "1ne": {},
  1007. "2wo": {},
  1008. "3hr": {},
  1009. "4ou": {},
  1010. "5iv": {},
  1011. "6ix": {},
  1012. }
  1013. a := [][]string{
  1014. {"1ne", "2wo", "3hr", "4ou", "5iv", "6ix"},
  1015. {"one", "2wo", "3hr", "4ou", "5iv", "6ix"},
  1016. {"one", "two", "3hr", "4ou", "5iv", "6ix"},
  1017. {"one", "two", "thr", "4ou", "5iv", "6ix"},
  1018. {"one", "two", "thr", "fou", "5iv", "6ix"},
  1019. {"one", "two", "thr", "fou", "fiv", "6ix"},
  1020. {"one", "two", "thr", "fou", "fiv", "six"},
  1021. }
  1022. for n := 0; n < b.N; n++ {
  1023. ml(m, a)
  1024. }
  1025. })
  1026. b.Run("array to map worst", func(b *testing.B) {
  1027. m := map[string]struct{}{
  1028. "one": {},
  1029. "two": {},
  1030. "thr": {},
  1031. "fou": {},
  1032. "fiv": {},
  1033. "six": {},
  1034. }
  1035. a := [][]string{
  1036. {"1ne", "2wo", "3hr", "4ou", "5iv", "6ix"},
  1037. {"one", "2wo", "3hr", "4ou", "5iv", "6ix"},
  1038. {"one", "two", "3hr", "4ou", "5iv", "6ix"},
  1039. {"one", "two", "thr", "4ou", "5iv", "6ix"},
  1040. {"one", "two", "thr", "fou", "5iv", "6ix"},
  1041. {"one", "two", "thr", "fou", "fiv", "6ix"},
  1042. {"one", "two", "thr", "fou", "fiv", "six"},
  1043. }
  1044. for n := 0; n < b.N; n++ {
  1045. ml(m, a)
  1046. }
  1047. })
  1048. }
  1049. func Test_parsePort(t *testing.T) {
  1050. _, _, err := parsePort("")
  1051. require.EqualError(t, err, "was not a number; ``")
  1052. _, _, err = parsePort(" ")
  1053. require.EqualError(t, err, "was not a number; ` `")
  1054. _, _, err = parsePort("-")
  1055. require.EqualError(t, err, "appears to be a range but could not be parsed; `-`")
  1056. _, _, err = parsePort(" - ")
  1057. require.EqualError(t, err, "appears to be a range but could not be parsed; ` - `")
  1058. _, _, err = parsePort("a-b")
  1059. require.EqualError(t, err, "beginning range was not a number; `a`")
  1060. _, _, err = parsePort("1-b")
  1061. require.EqualError(t, err, "ending range was not a number; `b`")
  1062. s, e, err := parsePort(" 1 - 2 ")
  1063. assert.Equal(t, int32(1), s)
  1064. assert.Equal(t, int32(2), e)
  1065. require.NoError(t, err)
  1066. s, e, err = parsePort("0-1")
  1067. assert.Equal(t, int32(0), s)
  1068. assert.Equal(t, int32(0), e)
  1069. require.NoError(t, err)
  1070. s, e, err = parsePort("9919")
  1071. assert.Equal(t, int32(9919), s)
  1072. assert.Equal(t, int32(9919), e)
  1073. require.NoError(t, err)
  1074. s, e, err = parsePort("any")
  1075. assert.Equal(t, int32(0), s)
  1076. assert.Equal(t, int32(0), e)
  1077. require.NoError(t, err)
  1078. }
  1079. // Test_parsePort_invalid covers inputs that must error. The named bug is
  1080. // that int32(strconv.Atoi("4294967296")) truncates to 0 == firewall.PortAny,
  1081. // silently turning a typo into a match-all-ports rule; the rest are
  1082. // representative syntax/range probes.
  1083. func Test_parsePort_invalid(t *testing.T) {
  1084. tests := []struct {
  1085. name string
  1086. input string
  1087. wantErrContains string
  1088. }{
  1089. // Numeric overflow (the named bug + boundary).
  1090. {"named bug: 2^32 truncates to PortAny", "4294967296", "out of range"},
  1091. {"just above max real port", "65536", "out of range"},
  1092. // Negatives route through the range branch and hit the empty-half
  1093. // guard; included as defense in depth so a future refactor cannot
  1094. // accidentally reach the int32 cast.
  1095. {"negative", "-1", "could not be parsed"},
  1096. // Syntax probes.
  1097. {"NUL between digits", "4\x002", "was not a number"},
  1098. {"hex notation", "0x10", "was not a number"},
  1099. {"scientific notation", "1e3", "was not a number"},
  1100. {"leading whitespace", " 42", "was not a number"},
  1101. {"fullwidth digits", "42", "was not a number"},
  1102. // Range branch.
  1103. {"range upper out of range", "1-65536", "ending range out of range"},
  1104. {"range lower out of range", "65536-65537", "beginning range out of range"},
  1105. {"range with negative upper", "1--1", "ending range was not a number"},
  1106. }
  1107. for _, tc := range tests {
  1108. t.Run(tc.name, func(t *testing.T) {
  1109. _, _, err := parsePort(tc.input)
  1110. require.Error(t, err, "input %q must error", tc.input)
  1111. require.ErrorContains(t, err, tc.wantErrContains)
  1112. })
  1113. }
  1114. }
  1115. // Test_parsePort_valid_boundaries locks in success cases at 0, 1, and 65535
  1116. // so a future refactor cannot regress the boundaries.
  1117. func Test_parsePort_valid_boundaries(t *testing.T) {
  1118. tests := []struct {
  1119. name string
  1120. input string
  1121. wantStart int32
  1122. wantEnd int32
  1123. }{
  1124. {"zero is PortAny", "0", 0, 0},
  1125. {"min real port", "1", 1, 1},
  1126. {"max real port", "65535", 65535, 65535},
  1127. {"range zero to max forces end to zero", "0-65535", 0, 0},
  1128. {"range max to max", "65535-65535", 65535, 65535},
  1129. {"range one to max", "1-65535", 1, 65535},
  1130. {"range with whitespace inside", " 1 - 2 ", 1, 2},
  1131. }
  1132. for _, tc := range tests {
  1133. t.Run(tc.name, func(t *testing.T) {
  1134. s, e, err := parsePort(tc.input)
  1135. require.NoError(t, err)
  1136. assert.Equal(t, tc.wantStart, s, "start port")
  1137. assert.Equal(t, tc.wantEnd, e, "end port")
  1138. })
  1139. }
  1140. }
  1141. func TestNewFirewallFromConfig(t *testing.T) {
  1142. l := test.NewLogger()
  1143. // Test a bad rule definition
  1144. c := &dummyCert{}
  1145. cs, err := newCertState(cert.Version2, nil, c, false, cert.Curve_CURVE25519, nil, "aes")
  1146. require.NoError(t, err)
  1147. conf := config.NewC(test.NewLogger())
  1148. conf.Settings["firewall"] = map[string]any{"outbound": "asdf"}
  1149. _, err = NewFirewallFromConfig(l, cs, conf)
  1150. require.EqualError(t, err, "firewall.outbound failed to parse, should be an array of rules")
  1151. // Test both port and code
  1152. conf = config.NewC(test.NewLogger())
  1153. conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"port": "1", "code": "2"}}}
  1154. _, err = NewFirewallFromConfig(l, cs, conf)
  1155. require.EqualError(t, err, "firewall.outbound rule #0; only one of port or code should be provided")
  1156. // Test missing host, group, cidr, ca_name and ca_sha
  1157. conf = config.NewC(test.NewLogger())
  1158. conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{}}}
  1159. _, err = NewFirewallFromConfig(l, cs, conf)
  1160. 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")
  1161. // Test code/port error
  1162. conf = config.NewC(test.NewLogger())
  1163. conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"code": "a", "host": "testh", "proto": "any"}}}
  1164. _, err = NewFirewallFromConfig(l, cs, conf)
  1165. require.EqualError(t, err, "firewall.outbound rule #0; code was not a number; `a`")
  1166. conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"port": "a", "host": "testh", "proto": "any"}}}
  1167. _, err = NewFirewallFromConfig(l, cs, conf)
  1168. require.EqualError(t, err, "firewall.outbound rule #0; port was not a number; `a`")
  1169. // Test proto error
  1170. conf = config.NewC(test.NewLogger())
  1171. conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"code": "1", "host": "testh"}}}
  1172. _, err = NewFirewallFromConfig(l, cs, conf)
  1173. require.EqualError(t, err, "firewall.outbound rule #0; proto was not understood; ``")
  1174. // Test cidr parse error
  1175. conf = config.NewC(test.NewLogger())
  1176. conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"code": "1", "cidr": "testh", "proto": "any"}}}
  1177. _, err = NewFirewallFromConfig(l, cs, conf)
  1178. require.EqualError(t, err, "firewall.outbound rule #0; cidr did not parse; netip.ParsePrefix(\"testh\"): no '/'")
  1179. // Test local_cidr parse error
  1180. conf = config.NewC(test.NewLogger())
  1181. conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"code": "1", "local_cidr": "testh", "proto": "any"}}}
  1182. _, err = NewFirewallFromConfig(l, cs, conf)
  1183. require.EqualError(t, err, "firewall.outbound rule #0; local_cidr did not parse; netip.ParsePrefix(\"testh\"): no '/'")
  1184. // Test both group and groups
  1185. conf = config.NewC(test.NewLogger())
  1186. conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "group": "a", "groups": []string{"b", "c"}}}}
  1187. _, err = NewFirewallFromConfig(l, cs, conf)
  1188. require.EqualError(t, err, "firewall.inbound rule #0; only one of group or groups should be defined, both provided")
  1189. }
  1190. func TestAddFirewallRulesFromConfig(t *testing.T) {
  1191. l := test.NewLogger()
  1192. // Test adding tcp rule
  1193. conf := config.NewC(test.NewLogger())
  1194. mf := &mockFirewall{}
  1195. conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"port": "1", "proto": "tcp", "host": "a"}}}
  1196. require.NoError(t, AddFirewallRulesFromConfig(l, false, conf, mf))
  1197. assert.Equal(t, addRuleCall{incoming: false, proto: iputil.IPProtocolTCP, startPort: 1, endPort: 1, groups: nil, host: "a", ip: "", localIp: ""}, mf.lastCall)
  1198. // Test adding udp rule
  1199. conf = config.NewC(test.NewLogger())
  1200. mf = &mockFirewall{}
  1201. conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"port": "1", "proto": "udp", "host": "a"}}}
  1202. require.NoError(t, AddFirewallRulesFromConfig(l, false, conf, mf))
  1203. assert.Equal(t, addRuleCall{incoming: false, proto: iputil.IPProtocolUDP, startPort: 1, endPort: 1, groups: nil, host: "a", ip: "", localIp: ""}, mf.lastCall)
  1204. // Test adding icmp rule
  1205. conf = config.NewC(test.NewLogger())
  1206. mf = &mockFirewall{}
  1207. conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"port": "1", "proto": "icmp", "host": "a"}}}
  1208. require.NoError(t, AddFirewallRulesFromConfig(l, false, conf, mf))
  1209. assert.Equal(t, addRuleCall{incoming: false, proto: iputil.IPProtocolICMP, startPort: firewall.PortAny, endPort: firewall.PortAny, groups: nil, host: "a", ip: "", localIp: ""}, mf.lastCall)
  1210. // Test adding icmp rule no port
  1211. conf = config.NewC(test.NewLogger())
  1212. mf = &mockFirewall{}
  1213. conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"proto": "icmp", "host": "a"}}}
  1214. require.NoError(t, AddFirewallRulesFromConfig(l, false, conf, mf))
  1215. assert.Equal(t, addRuleCall{incoming: false, proto: iputil.IPProtocolICMP, startPort: firewall.PortAny, endPort: firewall.PortAny, groups: nil, host: "a", ip: "", localIp: ""}, mf.lastCall)
  1216. // Test adding any rule
  1217. conf = config.NewC(test.NewLogger())
  1218. mf = &mockFirewall{}
  1219. conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "host": "a"}}}
  1220. require.NoError(t, AddFirewallRulesFromConfig(l, true, conf, mf))
  1221. assert.Equal(t, addRuleCall{incoming: true, proto: firewall.ProtoAny, startPort: 1, endPort: 1, groups: nil, host: "a", ip: "", localIp: ""}, mf.lastCall)
  1222. // Test adding rule with cidr
  1223. cidr := netip.MustParsePrefix("10.0.0.0/8")
  1224. conf = config.NewC(test.NewLogger())
  1225. mf = &mockFirewall{}
  1226. conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "cidr": cidr.String()}}}
  1227. require.NoError(t, AddFirewallRulesFromConfig(l, true, conf, mf))
  1228. assert.Equal(t, addRuleCall{incoming: true, proto: firewall.ProtoAny, startPort: 1, endPort: 1, groups: nil, ip: cidr.String(), localIp: ""}, mf.lastCall)
  1229. // Test adding rule with local_cidr
  1230. conf = config.NewC(test.NewLogger())
  1231. mf = &mockFirewall{}
  1232. conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "local_cidr": cidr.String()}}}
  1233. require.NoError(t, AddFirewallRulesFromConfig(l, true, conf, mf))
  1234. assert.Equal(t, addRuleCall{incoming: true, proto: firewall.ProtoAny, startPort: 1, endPort: 1, groups: nil, ip: "", localIp: cidr.String()}, mf.lastCall)
  1235. // Test adding rule with cidr ipv6
  1236. cidr6 := netip.MustParsePrefix("fd00::/8")
  1237. conf = config.NewC(test.NewLogger())
  1238. mf = &mockFirewall{}
  1239. conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "cidr": cidr6.String()}}}
  1240. require.NoError(t, AddFirewallRulesFromConfig(l, true, conf, mf))
  1241. assert.Equal(t, addRuleCall{incoming: true, proto: firewall.ProtoAny, startPort: 1, endPort: 1, groups: nil, ip: cidr6.String(), localIp: ""}, mf.lastCall)
  1242. // Test adding rule with any cidr
  1243. conf = config.NewC(test.NewLogger())
  1244. mf = &mockFirewall{}
  1245. conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "cidr": "any"}}}
  1246. require.NoError(t, AddFirewallRulesFromConfig(l, true, conf, mf))
  1247. assert.Equal(t, addRuleCall{incoming: true, proto: firewall.ProtoAny, startPort: 1, endPort: 1, groups: nil, ip: "any", localIp: ""}, mf.lastCall)
  1248. // Test adding rule with junk cidr
  1249. conf = config.NewC(test.NewLogger())
  1250. mf = &mockFirewall{}
  1251. conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "cidr": "junk/junk"}}}
  1252. require.EqualError(t, AddFirewallRulesFromConfig(l, true, conf, mf), "firewall.inbound rule #0; cidr did not parse; netip.ParsePrefix(\"junk/junk\"): ParseAddr(\"junk\"): unable to parse IP")
  1253. // Test adding rule with local_cidr ipv6
  1254. conf = config.NewC(test.NewLogger())
  1255. mf = &mockFirewall{}
  1256. conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "local_cidr": cidr6.String()}}}
  1257. require.NoError(t, AddFirewallRulesFromConfig(l, true, conf, mf))
  1258. assert.Equal(t, addRuleCall{incoming: true, proto: firewall.ProtoAny, startPort: 1, endPort: 1, groups: nil, ip: "", localIp: cidr6.String()}, mf.lastCall)
  1259. // Test adding rule with any local_cidr
  1260. conf = config.NewC(test.NewLogger())
  1261. mf = &mockFirewall{}
  1262. conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "local_cidr": "any"}}}
  1263. require.NoError(t, AddFirewallRulesFromConfig(l, true, conf, mf))
  1264. assert.Equal(t, addRuleCall{incoming: true, proto: firewall.ProtoAny, startPort: 1, endPort: 1, groups: nil, localIp: "any"}, mf.lastCall)
  1265. // Test adding rule with junk local_cidr
  1266. conf = config.NewC(test.NewLogger())
  1267. mf = &mockFirewall{}
  1268. conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "local_cidr": "junk/junk"}}}
  1269. require.EqualError(t, AddFirewallRulesFromConfig(l, true, conf, mf), "firewall.inbound rule #0; local_cidr did not parse; netip.ParsePrefix(\"junk/junk\"): ParseAddr(\"junk\"): unable to parse IP")
  1270. // Test adding rule with ca_sha
  1271. conf = config.NewC(test.NewLogger())
  1272. mf = &mockFirewall{}
  1273. conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "ca_sha": "12312313123"}}}
  1274. require.NoError(t, AddFirewallRulesFromConfig(l, true, conf, mf))
  1275. assert.Equal(t, addRuleCall{incoming: true, proto: firewall.ProtoAny, startPort: 1, endPort: 1, groups: nil, ip: "", localIp: "", caSha: "12312313123"}, mf.lastCall)
  1276. // Test adding rule with ca_name
  1277. conf = config.NewC(test.NewLogger())
  1278. mf = &mockFirewall{}
  1279. conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "ca_name": "root01"}}}
  1280. require.NoError(t, AddFirewallRulesFromConfig(l, true, conf, mf))
  1281. assert.Equal(t, addRuleCall{incoming: true, proto: firewall.ProtoAny, startPort: 1, endPort: 1, groups: nil, ip: "", localIp: "", caName: "root01"}, mf.lastCall)
  1282. // Test single group
  1283. conf = config.NewC(test.NewLogger())
  1284. mf = &mockFirewall{}
  1285. conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "group": "a"}}}
  1286. require.NoError(t, AddFirewallRulesFromConfig(l, true, conf, mf))
  1287. assert.Equal(t, addRuleCall{incoming: true, proto: firewall.ProtoAny, startPort: 1, endPort: 1, groups: []string{"a"}, ip: "", localIp: ""}, mf.lastCall)
  1288. // Test single groups
  1289. conf = config.NewC(test.NewLogger())
  1290. mf = &mockFirewall{}
  1291. conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "groups": "a"}}}
  1292. require.NoError(t, AddFirewallRulesFromConfig(l, true, conf, mf))
  1293. assert.Equal(t, addRuleCall{incoming: true, proto: firewall.ProtoAny, startPort: 1, endPort: 1, groups: []string{"a"}, ip: "", localIp: ""}, mf.lastCall)
  1294. // Test multiple AND groups
  1295. conf = config.NewC(test.NewLogger())
  1296. mf = &mockFirewall{}
  1297. conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "groups": []string{"a", "b"}}}}
  1298. require.NoError(t, AddFirewallRulesFromConfig(l, true, conf, mf))
  1299. assert.Equal(t, addRuleCall{incoming: true, proto: firewall.ProtoAny, startPort: 1, endPort: 1, groups: []string{"a", "b"}, ip: "", localIp: ""}, mf.lastCall)
  1300. // Test Add error
  1301. conf = config.NewC(test.NewLogger())
  1302. mf = &mockFirewall{}
  1303. mf.nextCallReturn = errors.New("test error")
  1304. conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "host": "a"}}}
  1305. require.EqualError(t, AddFirewallRulesFromConfig(l, true, conf, mf), "firewall.inbound rule #0; `test error`")
  1306. }
  1307. func TestFirewall_convertRule(t *testing.T) {
  1308. ob := &bytes.Buffer{}
  1309. l := test.NewLoggerWithOutput(ob)
  1310. // Ensure group array of 1 is converted and a warning is printed
  1311. c := map[string]any{
  1312. "group": []any{"group1"},
  1313. }
  1314. r, err := convertRule(l, c, "test", 1)
  1315. assert.Contains(t, ob.String(), "group was an array with a single value, converting to simple value")
  1316. assert.Contains(t, ob.String(), "table=test")
  1317. assert.Contains(t, ob.String(), "rule=1")
  1318. require.NoError(t, err)
  1319. assert.Equal(t, []string{"group1"}, r.Groups)
  1320. // Ensure group array of > 1 is errord
  1321. ob.Reset()
  1322. c = map[string]any{
  1323. "group": []any{"group1", "group2"},
  1324. }
  1325. r, err = convertRule(l, c, "test", 1)
  1326. assert.Empty(t, ob.String())
  1327. require.Error(t, err, "group should contain a single value, an array with more than one entry was provided")
  1328. // Make sure a well formed group is alright
  1329. ob.Reset()
  1330. c = map[string]any{
  1331. "group": "group1",
  1332. }
  1333. r, err = convertRule(l, c, "test", 1)
  1334. require.NoError(t, err)
  1335. assert.Equal(t, []string{"group1"}, r.Groups)
  1336. }
  1337. func TestFirewall_convertRuleSanity(t *testing.T) {
  1338. ob := &bytes.Buffer{}
  1339. l := test.NewLoggerWithOutput(ob)
  1340. noWarningPlease := []map[string]any{
  1341. {"group": "group1"},
  1342. {"groups": []any{"group2"}},
  1343. {"host": "bob"},
  1344. {"cidr": "1.1.1.1/1"},
  1345. {"groups": []any{"group2"}, "host": "bob"},
  1346. {"cidr": "1.1.1.1/1", "host": "bob"},
  1347. {"groups": []any{"group2"}, "cidr": "1.1.1.1/1"},
  1348. {"groups": []any{"group2"}, "cidr": "1.1.1.1/1", "host": "bob"},
  1349. }
  1350. for _, c := range noWarningPlease {
  1351. r, err := convertRule(l, c, "test", 1)
  1352. require.NoError(t, err)
  1353. require.NoError(t, r.sanity(), "should not generate a sanity warning, %+v", c)
  1354. }
  1355. yesWarningPlease := []map[string]any{
  1356. {"group": "group1"},
  1357. {"groups": []any{"group2"}},
  1358. {"cidr": "1.1.1.1/1"},
  1359. {"groups": []any{"group2"}, "host": "bob"},
  1360. {"cidr": "1.1.1.1/1", "host": "bob"},
  1361. {"groups": []any{"group2"}, "cidr": "1.1.1.1/1"},
  1362. {"groups": []any{"group2"}, "cidr": "1.1.1.1/1", "host": "bob"},
  1363. }
  1364. for _, c := range yesWarningPlease {
  1365. c["host"] = "any"
  1366. r, err := convertRule(l, c, "test", 1)
  1367. require.NoError(t, err)
  1368. err = r.sanity()
  1369. require.Error(t, err, "I wanted a warning: %+v", c)
  1370. }
  1371. //reset the list
  1372. yesWarningPlease = []map[string]any{
  1373. {"group": "group1"},
  1374. {"groups": []any{"group2"}},
  1375. {"cidr": "1.1.1.1/1"},
  1376. {"groups": []any{"group2"}, "host": "bob"},
  1377. {"cidr": "1.1.1.1/1", "host": "bob"},
  1378. {"groups": []any{"group2"}, "cidr": "1.1.1.1/1"},
  1379. {"groups": []any{"group2"}, "cidr": "1.1.1.1/1", "host": "bob"},
  1380. }
  1381. for _, c := range yesWarningPlease {
  1382. r, err := convertRule(l, c, "test", 1)
  1383. require.NoError(t, err)
  1384. r.Groups = append(r.Groups, "any")
  1385. err = r.sanity()
  1386. require.Error(t, err, "I wanted a warning: %+v", c)
  1387. }
  1388. }
  1389. type testcase struct {
  1390. h *HostInfo
  1391. p firewall.Packet
  1392. c cert.Certificate
  1393. err error
  1394. }
  1395. func (c *testcase) Test(t *testing.T, fw *Firewall) {
  1396. t.Helper()
  1397. cp := cert.NewCAPool()
  1398. resetConntrack(fw)
  1399. err := fw.Drop(c.p, true, c.h, cp, nil)
  1400. if c.err == nil {
  1401. require.NoError(t, err, "failed to not drop remote address %s", c.p.RemoteAddr)
  1402. } else {
  1403. require.ErrorIs(t, c.err, err, "failed to drop remote address %s", c.p.RemoteAddr)
  1404. }
  1405. }
  1406. func buildTestCase(setup testsetup, err error, theirPrefixes ...netip.Prefix) testcase {
  1407. c1 := dummyCert{
  1408. name: "host1",
  1409. networks: theirPrefixes,
  1410. groups: []string{"default-group"},
  1411. issuer: "signer-shasum",
  1412. }
  1413. h := HostInfo{
  1414. ConnectionState: &ConnectionState{
  1415. peerCert: &cert.CachedCertificate{
  1416. Certificate: &c1,
  1417. InvertedGroups: map[string]struct{}{"default-group": {}},
  1418. },
  1419. },
  1420. vpnAddrs: make([]netip.Addr, len(theirPrefixes)),
  1421. }
  1422. for i := range theirPrefixes {
  1423. h.vpnAddrs[i] = theirPrefixes[i].Addr()
  1424. }
  1425. h.buildNetworks(setup.myVpnNetworksTable, &c1)
  1426. p := firewall.Packet{
  1427. LocalAddr: setup.c.Networks()[0].Addr(), //todo?
  1428. RemoteAddr: theirPrefixes[0].Addr(),
  1429. LocalPort: 10,
  1430. RemotePort: 90,
  1431. Protocol: iputil.IPProtocolUDP,
  1432. Fragment: false,
  1433. }
  1434. return testcase{
  1435. h: &h,
  1436. p: p,
  1437. c: &c1,
  1438. err: err,
  1439. }
  1440. }
  1441. type testsetup struct {
  1442. c dummyCert
  1443. myVpnNetworksTable *bart.Lite
  1444. fw *Firewall
  1445. }
  1446. func newSetup(t *testing.T, l *slog.Logger, myPrefixes ...netip.Prefix) testsetup {
  1447. c := dummyCert{
  1448. name: "me",
  1449. networks: myPrefixes,
  1450. groups: []string{"default-group"},
  1451. issuer: "signer-shasum",
  1452. }
  1453. return newSetupFromCert(t, l, c)
  1454. }
  1455. func newSetupFromCert(t *testing.T, l *slog.Logger, c dummyCert) testsetup {
  1456. myVpnNetworksTable := new(bart.Lite)
  1457. for _, prefix := range c.Networks() {
  1458. myVpnNetworksTable.Insert(prefix)
  1459. }
  1460. fw := NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
  1461. require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"any"}, "", "", "", "", ""))
  1462. return testsetup{
  1463. c: c,
  1464. fw: fw,
  1465. myVpnNetworksTable: myVpnNetworksTable,
  1466. }
  1467. }
  1468. func TestFirewall_Drop_EnforceIPMatch(t *testing.T) {
  1469. t.Parallel()
  1470. ob := &bytes.Buffer{}
  1471. l := test.NewLoggerWithOutput(ob)
  1472. myPrefix := netip.MustParsePrefix("1.1.1.1/8")
  1473. // for now, it's okay that these are all "incoming", the logic this test tries to check doesn't care about in/out
  1474. t.Run("allow inbound all matching", func(t *testing.T) {
  1475. t.Parallel()
  1476. setup := newSetup(t, l, myPrefix)
  1477. tc := buildTestCase(setup, nil, netip.MustParsePrefix("1.2.3.4/24"))
  1478. tc.Test(t, setup.fw)
  1479. })
  1480. t.Run("allow inbound local matching", func(t *testing.T) {
  1481. t.Parallel()
  1482. setup := newSetup(t, l, myPrefix)
  1483. tc := buildTestCase(setup, ErrInvalidLocalIP, netip.MustParsePrefix("1.2.3.4/24"))
  1484. tc.p.LocalAddr = netip.MustParseAddr("1.2.3.8")
  1485. tc.Test(t, setup.fw)
  1486. })
  1487. t.Run("block inbound remote mismatched", func(t *testing.T) {
  1488. t.Parallel()
  1489. setup := newSetup(t, l, myPrefix)
  1490. tc := buildTestCase(setup, ErrInvalidRemoteIP, netip.MustParsePrefix("1.2.3.4/24"))
  1491. tc.p.RemoteAddr = netip.MustParseAddr("9.9.9.9")
  1492. tc.Test(t, setup.fw)
  1493. })
  1494. t.Run("Block a vpn peer packet", func(t *testing.T) {
  1495. t.Parallel()
  1496. setup := newSetup(t, l, myPrefix)
  1497. tc := buildTestCase(setup, ErrPeerRejected, netip.MustParsePrefix("2.2.2.2/24"))
  1498. tc.Test(t, setup.fw)
  1499. })
  1500. twoPrefixes := []netip.Prefix{
  1501. netip.MustParsePrefix("1.2.3.4/24"), netip.MustParsePrefix("2.2.2.2/24"),
  1502. }
  1503. t.Run("allow inbound one matching", func(t *testing.T) {
  1504. t.Parallel()
  1505. setup := newSetup(t, l, myPrefix)
  1506. tc := buildTestCase(setup, nil, twoPrefixes...)
  1507. tc.Test(t, setup.fw)
  1508. })
  1509. t.Run("block inbound multimismatch", func(t *testing.T) {
  1510. t.Parallel()
  1511. setup := newSetup(t, l, myPrefix)
  1512. tc := buildTestCase(setup, ErrInvalidRemoteIP, twoPrefixes...)
  1513. tc.p.RemoteAddr = netip.MustParseAddr("9.9.9.9")
  1514. tc.Test(t, setup.fw)
  1515. })
  1516. t.Run("allow inbound 2nd one matching", func(t *testing.T) {
  1517. t.Parallel()
  1518. setup2 := newSetup(t, l, netip.MustParsePrefix("2.2.2.1/24"))
  1519. tc := buildTestCase(setup2, nil, twoPrefixes...)
  1520. tc.p.RemoteAddr = twoPrefixes[1].Addr()
  1521. tc.Test(t, setup2.fw)
  1522. })
  1523. t.Run("allow inbound unsafe route", func(t *testing.T) {
  1524. t.Parallel()
  1525. unsafePrefix := netip.MustParsePrefix("192.168.0.0/24")
  1526. c := dummyCert{
  1527. name: "me",
  1528. networks: []netip.Prefix{myPrefix},
  1529. unsafeNetworks: []netip.Prefix{unsafePrefix},
  1530. groups: []string{"default-group"},
  1531. issuer: "signer-shasum",
  1532. }
  1533. unsafeSetup := newSetupFromCert(t, l, c)
  1534. tc := buildTestCase(unsafeSetup, nil, twoPrefixes...)
  1535. tc.p.LocalAddr = netip.MustParseAddr("192.168.0.3")
  1536. tc.err = ErrNoMatchingRule
  1537. tc.Test(t, unsafeSetup.fw) //should hit firewall and bounce off
  1538. require.NoError(t, unsafeSetup.fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"any"}, "", "", unsafePrefix.String(), "", ""))
  1539. tc.err = nil
  1540. tc.Test(t, unsafeSetup.fw) //should pass
  1541. })
  1542. }
  1543. type addRuleCall struct {
  1544. incoming bool
  1545. proto uint8
  1546. startPort int32
  1547. endPort int32
  1548. groups []string
  1549. host string
  1550. ip string
  1551. localIp string
  1552. caName string
  1553. caSha string
  1554. }
  1555. type mockFirewall struct {
  1556. lastCall addRuleCall
  1557. nextCallReturn error
  1558. }
  1559. func (mf *mockFirewall) AddRule(incoming bool, proto uint8, startPort int32, endPort int32, groups []string, host string, ip, localIp, caName string, caSha string) error {
  1560. mf.lastCall = addRuleCall{
  1561. incoming: incoming,
  1562. proto: proto,
  1563. startPort: startPort,
  1564. endPort: endPort,
  1565. groups: groups,
  1566. host: host,
  1567. ip: ip,
  1568. localIp: localIp,
  1569. caName: caName,
  1570. caSha: caSha,
  1571. }
  1572. err := mf.nextCallReturn
  1573. mf.nextCallReturn = nil
  1574. return err
  1575. }
  1576. func resetConntrack(fw *Firewall) {
  1577. fw.Conntrack.Lock()
  1578. fw.Conntrack.Conns = map[firewall.Packet]*conn{}
  1579. fw.Conntrack.Unlock()
  1580. }