firewall_test.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  1. package nebula
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "errors"
  6. "math"
  7. "net"
  8. "testing"
  9. "time"
  10. "github.com/rcrowley/go-metrics"
  11. "github.com/slackhq/nebula/cert"
  12. "github.com/stretchr/testify/assert"
  13. )
  14. func TestNewFirewall(t *testing.T) {
  15. c := &cert.NebulaCertificate{}
  16. fw := NewFirewall(time.Second, time.Minute, time.Hour, c)
  17. assert.NotNil(t, fw.Conns)
  18. assert.NotNil(t, fw.InRules)
  19. assert.NotNil(t, fw.OutRules)
  20. assert.NotNil(t, fw.TimerWheel)
  21. assert.Equal(t, time.Second, fw.TCPTimeout)
  22. assert.Equal(t, time.Minute, fw.UDPTimeout)
  23. assert.Equal(t, time.Hour, fw.DefaultTimeout)
  24. assert.Equal(t, time.Hour, fw.TimerWheel.wheelDuration)
  25. assert.Equal(t, time.Hour, fw.TimerWheel.wheelDuration)
  26. assert.Equal(t, 3601, fw.TimerWheel.wheelLen)
  27. fw = NewFirewall(time.Second, time.Hour, time.Minute, c)
  28. assert.Equal(t, time.Hour, fw.TimerWheel.wheelDuration)
  29. assert.Equal(t, 3601, fw.TimerWheel.wheelLen)
  30. fw = NewFirewall(time.Hour, time.Second, time.Minute, c)
  31. assert.Equal(t, time.Hour, fw.TimerWheel.wheelDuration)
  32. assert.Equal(t, 3601, fw.TimerWheel.wheelLen)
  33. fw = NewFirewall(time.Hour, time.Minute, time.Second, c)
  34. assert.Equal(t, time.Hour, fw.TimerWheel.wheelDuration)
  35. assert.Equal(t, 3601, fw.TimerWheel.wheelLen)
  36. fw = NewFirewall(time.Minute, time.Hour, time.Second, c)
  37. assert.Equal(t, time.Hour, fw.TimerWheel.wheelDuration)
  38. assert.Equal(t, 3601, fw.TimerWheel.wheelLen)
  39. fw = NewFirewall(time.Minute, time.Second, time.Hour, c)
  40. assert.Equal(t, time.Hour, fw.TimerWheel.wheelDuration)
  41. assert.Equal(t, 3601, fw.TimerWheel.wheelLen)
  42. }
  43. func TestFirewall_AddRule(t *testing.T) {
  44. ob := &bytes.Buffer{}
  45. out := l.Out
  46. l.SetOutput(ob)
  47. defer l.SetOutput(out)
  48. c := &cert.NebulaCertificate{}
  49. fw := NewFirewall(time.Second, time.Minute, time.Hour, c)
  50. assert.NotNil(t, fw.InRules)
  51. assert.NotNil(t, fw.OutRules)
  52. _, ti, _ := net.ParseCIDR("1.2.3.4/32")
  53. assert.Nil(t, fw.AddRule(true, fwProtoTCP, 1, 1, []string{}, "", nil, "", ""))
  54. // An empty rule is any
  55. assert.True(t, fw.InRules.TCP[1].Any.Any)
  56. assert.Empty(t, fw.InRules.TCP[1].Any.Groups)
  57. assert.Empty(t, fw.InRules.TCP[1].Any.Hosts)
  58. assert.Nil(t, fw.InRules.TCP[1].Any.CIDR.root.left)
  59. assert.Nil(t, fw.InRules.TCP[1].Any.CIDR.root.right)
  60. assert.Nil(t, fw.InRules.TCP[1].Any.CIDR.root.value)
  61. fw = NewFirewall(time.Second, time.Minute, time.Hour, c)
  62. assert.Nil(t, fw.AddRule(true, fwProtoUDP, 1, 1, []string{"g1"}, "", nil, "", ""))
  63. assert.False(t, fw.InRules.UDP[1].Any.Any)
  64. assert.Contains(t, fw.InRules.UDP[1].Any.Groups[0], "g1")
  65. assert.Empty(t, fw.InRules.UDP[1].Any.Hosts)
  66. assert.Nil(t, fw.InRules.UDP[1].Any.CIDR.root.left)
  67. assert.Nil(t, fw.InRules.UDP[1].Any.CIDR.root.right)
  68. assert.Nil(t, fw.InRules.UDP[1].Any.CIDR.root.value)
  69. fw = NewFirewall(time.Second, time.Minute, time.Hour, c)
  70. assert.Nil(t, fw.AddRule(true, fwProtoICMP, 1, 1, []string{}, "h1", nil, "", ""))
  71. assert.False(t, fw.InRules.ICMP[1].Any.Any)
  72. assert.Empty(t, fw.InRules.ICMP[1].Any.Groups)
  73. assert.Contains(t, fw.InRules.ICMP[1].Any.Hosts, "h1")
  74. assert.Nil(t, fw.InRules.ICMP[1].Any.CIDR.root.left)
  75. assert.Nil(t, fw.InRules.ICMP[1].Any.CIDR.root.right)
  76. assert.Nil(t, fw.InRules.ICMP[1].Any.CIDR.root.value)
  77. fw = NewFirewall(time.Second, time.Minute, time.Hour, c)
  78. assert.Nil(t, fw.AddRule(false, fwProtoAny, 1, 1, []string{}, "", ti, "", ""))
  79. assert.False(t, fw.OutRules.AnyProto[1].Any.Any)
  80. assert.Empty(t, fw.OutRules.AnyProto[1].Any.Groups)
  81. assert.Empty(t, fw.OutRules.AnyProto[1].Any.Hosts)
  82. assert.NotNil(t, fw.OutRules.AnyProto[1].Any.CIDR.Match(ip2int(ti.IP)))
  83. fw = NewFirewall(time.Second, time.Minute, time.Hour, c)
  84. assert.Nil(t, fw.AddRule(true, fwProtoUDP, 1, 1, []string{"g1"}, "", nil, "ca-name", ""))
  85. assert.Contains(t, fw.InRules.UDP[1].CANames, "ca-name")
  86. fw = NewFirewall(time.Second, time.Minute, time.Hour, c)
  87. assert.Nil(t, fw.AddRule(true, fwProtoUDP, 1, 1, []string{"g1"}, "", nil, "", "ca-sha"))
  88. assert.Contains(t, fw.InRules.UDP[1].CAShas, "ca-sha")
  89. // Set any and clear fields
  90. fw = NewFirewall(time.Second, time.Minute, time.Hour, c)
  91. assert.Nil(t, fw.AddRule(false, fwProtoAny, 0, 0, []string{"g1", "g2"}, "h1", ti, "", ""))
  92. assert.Equal(t, []string{"g1", "g2"}, fw.OutRules.AnyProto[0].Any.Groups[0])
  93. assert.Contains(t, fw.OutRules.AnyProto[0].Any.Hosts, "h1")
  94. assert.NotNil(t, fw.OutRules.AnyProto[0].Any.CIDR.Match(ip2int(ti.IP)))
  95. // run twice just to make sure
  96. //TODO: these ANY rules should clear the CA firewall portion
  97. assert.Nil(t, fw.AddRule(false, fwProtoAny, 0, 0, []string{"any"}, "", nil, "", ""))
  98. assert.Nil(t, fw.AddRule(false, fwProtoAny, 0, 0, []string{}, "any", nil, "", ""))
  99. assert.True(t, fw.OutRules.AnyProto[0].Any.Any)
  100. assert.Empty(t, fw.OutRules.AnyProto[0].Any.Groups)
  101. assert.Empty(t, fw.OutRules.AnyProto[0].Any.Hosts)
  102. assert.Nil(t, fw.OutRules.AnyProto[0].Any.CIDR.root.left)
  103. assert.Nil(t, fw.OutRules.AnyProto[0].Any.CIDR.root.right)
  104. assert.Nil(t, fw.OutRules.AnyProto[0].Any.CIDR.root.value)
  105. fw = NewFirewall(time.Second, time.Minute, time.Hour, c)
  106. assert.Nil(t, fw.AddRule(false, fwProtoAny, 0, 0, []string{}, "any", nil, "", ""))
  107. assert.True(t, fw.OutRules.AnyProto[0].Any.Any)
  108. fw = NewFirewall(time.Second, time.Minute, time.Hour, c)
  109. _, anyIp, _ := net.ParseCIDR("0.0.0.0/0")
  110. assert.Nil(t, fw.AddRule(false, fwProtoAny, 0, 0, []string{}, "", anyIp, "", ""))
  111. assert.True(t, fw.OutRules.AnyProto[0].Any.Any)
  112. // Test error conditions
  113. fw = NewFirewall(time.Second, time.Minute, time.Hour, c)
  114. assert.Error(t, fw.AddRule(true, math.MaxUint8, 0, 0, []string{}, "", nil, "", ""))
  115. assert.Error(t, fw.AddRule(true, fwProtoAny, 10, 0, []string{}, "", nil, "", ""))
  116. }
  117. func TestFirewall_Drop(t *testing.T) {
  118. ob := &bytes.Buffer{}
  119. out := l.Out
  120. l.SetOutput(ob)
  121. defer l.SetOutput(out)
  122. p := FirewallPacket{
  123. ip2int(net.IPv4(1, 2, 3, 4)),
  124. ip2int(net.IPv4(1, 2, 3, 4)),
  125. 10,
  126. 90,
  127. fwProtoUDP,
  128. false,
  129. }
  130. ipNet := net.IPNet{
  131. IP: net.IPv4(1, 2, 3, 4),
  132. Mask: net.IPMask{255, 255, 255, 0},
  133. }
  134. c := cert.NebulaCertificate{
  135. Details: cert.NebulaCertificateDetails{
  136. Name: "host1",
  137. Ips: []*net.IPNet{&ipNet},
  138. Groups: []string{"default-group"},
  139. InvertedGroups: map[string]struct{}{"default-group": {}},
  140. Issuer: "signer-shasum",
  141. },
  142. }
  143. h := HostInfo{
  144. ConnectionState: &ConnectionState{
  145. peerCert: &c,
  146. },
  147. }
  148. h.CreateRemoteCIDR(&c)
  149. fw := NewFirewall(time.Second, time.Minute, time.Hour, &c)
  150. assert.Nil(t, fw.AddRule(true, fwProtoAny, 0, 0, []string{"any"}, "", nil, "", ""))
  151. cp := cert.NewCAPool()
  152. // Drop outbound
  153. assert.True(t, fw.Drop([]byte{}, p, false, &h, cp))
  154. // Allow inbound
  155. resetConntrack(fw)
  156. assert.False(t, fw.Drop([]byte{}, p, true, &h, cp))
  157. // Allow outbound because conntrack
  158. assert.False(t, fw.Drop([]byte{}, p, false, &h, cp))
  159. // test remote mismatch
  160. oldRemote := p.RemoteIP
  161. p.RemoteIP = ip2int(net.IPv4(1, 2, 3, 10))
  162. assert.True(t, fw.Drop([]byte{}, p, false, &h, cp))
  163. p.RemoteIP = oldRemote
  164. // ensure signer doesn't get in the way of group checks
  165. fw = NewFirewall(time.Second, time.Minute, time.Hour, &c)
  166. assert.Nil(t, fw.AddRule(true, fwProtoAny, 0, 0, []string{"nope"}, "", nil, "", "signer-shasum"))
  167. assert.Nil(t, fw.AddRule(true, fwProtoAny, 0, 0, []string{"default-group"}, "", nil, "", "signer-shasum-bad"))
  168. assert.True(t, fw.Drop([]byte{}, p, true, &h, cp))
  169. // test caSha doesn't drop on match
  170. fw = NewFirewall(time.Second, time.Minute, time.Hour, &c)
  171. assert.Nil(t, fw.AddRule(true, fwProtoAny, 0, 0, []string{"nope"}, "", nil, "", "signer-shasum-bad"))
  172. assert.Nil(t, fw.AddRule(true, fwProtoAny, 0, 0, []string{"default-group"}, "", nil, "", "signer-shasum"))
  173. assert.False(t, fw.Drop([]byte{}, p, true, &h, cp))
  174. // ensure ca name doesn't get in the way of group checks
  175. cp.CAs["signer-shasum"] = &cert.NebulaCertificate{Details: cert.NebulaCertificateDetails{Name: "ca-good"}}
  176. fw = NewFirewall(time.Second, time.Minute, time.Hour, &c)
  177. assert.Nil(t, fw.AddRule(true, fwProtoAny, 0, 0, []string{"nope"}, "", nil, "ca-good", ""))
  178. assert.Nil(t, fw.AddRule(true, fwProtoAny, 0, 0, []string{"default-group"}, "", nil, "ca-good-bad", ""))
  179. assert.True(t, fw.Drop([]byte{}, p, true, &h, cp))
  180. // test caName doesn't drop on match
  181. cp.CAs["signer-shasum"] = &cert.NebulaCertificate{Details: cert.NebulaCertificateDetails{Name: "ca-good"}}
  182. fw = NewFirewall(time.Second, time.Minute, time.Hour, &c)
  183. assert.Nil(t, fw.AddRule(true, fwProtoAny, 0, 0, []string{"nope"}, "", nil, "ca-good-bad", ""))
  184. assert.Nil(t, fw.AddRule(true, fwProtoAny, 0, 0, []string{"default-group"}, "", nil, "ca-good", ""))
  185. assert.False(t, fw.Drop([]byte{}, p, true, &h, cp))
  186. }
  187. func BenchmarkFirewallTable_match(b *testing.B) {
  188. ft := FirewallTable{
  189. TCP: firewallPort{},
  190. }
  191. _, n, _ := net.ParseCIDR("172.1.1.1/32")
  192. _ = ft.TCP.addRule(10, 10, []string{"good-group"}, "good-host", n, "", "")
  193. _ = ft.TCP.addRule(10, 10, []string{"good-group2"}, "good-host", n, "", "")
  194. _ = ft.TCP.addRule(10, 10, []string{"good-group3"}, "good-host", n, "", "")
  195. _ = ft.TCP.addRule(10, 10, []string{"good-group4"}, "good-host", n, "", "")
  196. _ = ft.TCP.addRule(10, 10, []string{"good-group, good-group1"}, "good-host", n, "", "")
  197. cp := cert.NewCAPool()
  198. b.Run("fail on proto", func(b *testing.B) {
  199. c := &cert.NebulaCertificate{}
  200. for n := 0; n < b.N; n++ {
  201. ft.match(FirewallPacket{Protocol: fwProtoUDP}, true, c, cp)
  202. }
  203. })
  204. b.Run("fail on port", func(b *testing.B) {
  205. c := &cert.NebulaCertificate{}
  206. for n := 0; n < b.N; n++ {
  207. ft.match(FirewallPacket{Protocol: fwProtoTCP, LocalPort: 1}, true, c, cp)
  208. }
  209. })
  210. b.Run("fail all group, name, and cidr", func(b *testing.B) {
  211. _, ip, _ := net.ParseCIDR("9.254.254.254/32")
  212. c := &cert.NebulaCertificate{
  213. Details: cert.NebulaCertificateDetails{
  214. InvertedGroups: map[string]struct{}{"nope": {}},
  215. Name: "nope",
  216. Ips: []*net.IPNet{ip},
  217. },
  218. }
  219. for n := 0; n < b.N; n++ {
  220. ft.match(FirewallPacket{Protocol: fwProtoTCP, LocalPort: 10}, true, c, cp)
  221. }
  222. })
  223. b.Run("pass on group", func(b *testing.B) {
  224. c := &cert.NebulaCertificate{
  225. Details: cert.NebulaCertificateDetails{
  226. InvertedGroups: map[string]struct{}{"good-group": {}},
  227. Name: "nope",
  228. },
  229. }
  230. for n := 0; n < b.N; n++ {
  231. ft.match(FirewallPacket{Protocol: fwProtoTCP, LocalPort: 10}, true, c, cp)
  232. }
  233. })
  234. b.Run("pass on name", func(b *testing.B) {
  235. c := &cert.NebulaCertificate{
  236. Details: cert.NebulaCertificateDetails{
  237. InvertedGroups: map[string]struct{}{"nope": {}},
  238. Name: "good-host",
  239. },
  240. }
  241. for n := 0; n < b.N; n++ {
  242. ft.match(FirewallPacket{Protocol: fwProtoTCP, LocalPort: 10}, true, c, cp)
  243. }
  244. })
  245. b.Run("pass on ip", func(b *testing.B) {
  246. ip := ip2int(net.IPv4(172, 1, 1, 1))
  247. c := &cert.NebulaCertificate{
  248. Details: cert.NebulaCertificateDetails{
  249. InvertedGroups: map[string]struct{}{"nope": {}},
  250. Name: "good-host",
  251. },
  252. }
  253. for n := 0; n < b.N; n++ {
  254. ft.match(FirewallPacket{Protocol: fwProtoTCP, LocalPort: 10, RemoteIP: ip}, true, c, cp)
  255. }
  256. })
  257. _ = ft.TCP.addRule(0, 0, []string{"good-group"}, "good-host", n, "", "")
  258. b.Run("pass on ip with any port", func(b *testing.B) {
  259. ip := ip2int(net.IPv4(172, 1, 1, 1))
  260. c := &cert.NebulaCertificate{
  261. Details: cert.NebulaCertificateDetails{
  262. InvertedGroups: map[string]struct{}{"nope": {}},
  263. Name: "good-host",
  264. },
  265. }
  266. for n := 0; n < b.N; n++ {
  267. ft.match(FirewallPacket{Protocol: fwProtoTCP, LocalPort: 100, RemoteIP: ip}, true, c, cp)
  268. }
  269. })
  270. }
  271. func TestFirewall_Drop2(t *testing.T) {
  272. ob := &bytes.Buffer{}
  273. out := l.Out
  274. l.SetOutput(ob)
  275. defer l.SetOutput(out)
  276. p := FirewallPacket{
  277. ip2int(net.IPv4(1, 2, 3, 4)),
  278. ip2int(net.IPv4(1, 2, 3, 4)),
  279. 10,
  280. 90,
  281. fwProtoUDP,
  282. false,
  283. }
  284. ipNet := net.IPNet{
  285. IP: net.IPv4(1, 2, 3, 4),
  286. Mask: net.IPMask{255, 255, 255, 0},
  287. }
  288. c := cert.NebulaCertificate{
  289. Details: cert.NebulaCertificateDetails{
  290. Name: "host1",
  291. Ips: []*net.IPNet{&ipNet},
  292. InvertedGroups: map[string]struct{}{"default-group": {}, "test-group": {}},
  293. },
  294. }
  295. h := HostInfo{
  296. ConnectionState: &ConnectionState{
  297. peerCert: &c,
  298. },
  299. }
  300. h.CreateRemoteCIDR(&c)
  301. c1 := cert.NebulaCertificate{
  302. Details: cert.NebulaCertificateDetails{
  303. Name: "host1",
  304. Ips: []*net.IPNet{&ipNet},
  305. InvertedGroups: map[string]struct{}{"default-group": {}, "test-group-not": {}},
  306. },
  307. }
  308. h1 := HostInfo{
  309. ConnectionState: &ConnectionState{
  310. peerCert: &c1,
  311. },
  312. }
  313. h1.CreateRemoteCIDR(&c1)
  314. fw := NewFirewall(time.Second, time.Minute, time.Hour, &c)
  315. assert.Nil(t, fw.AddRule(true, fwProtoAny, 0, 0, []string{"default-group", "test-group"}, "", nil, "", ""))
  316. cp := cert.NewCAPool()
  317. // h1/c1 lacks the proper groups
  318. assert.True(t, fw.Drop([]byte{}, p, true, &h1, cp))
  319. // c has the proper groups
  320. resetConntrack(fw)
  321. assert.False(t, fw.Drop([]byte{}, p, true, &h, cp))
  322. }
  323. func TestFirewall_Drop3(t *testing.T) {
  324. ob := &bytes.Buffer{}
  325. out := l.Out
  326. l.SetOutput(ob)
  327. defer l.SetOutput(out)
  328. p := FirewallPacket{
  329. ip2int(net.IPv4(1, 2, 3, 4)),
  330. ip2int(net.IPv4(1, 2, 3, 4)),
  331. 1,
  332. 1,
  333. fwProtoUDP,
  334. false,
  335. }
  336. ipNet := net.IPNet{
  337. IP: net.IPv4(1, 2, 3, 4),
  338. Mask: net.IPMask{255, 255, 255, 0},
  339. }
  340. c := cert.NebulaCertificate{
  341. Details: cert.NebulaCertificateDetails{
  342. Name: "host-owner",
  343. Ips: []*net.IPNet{&ipNet},
  344. },
  345. }
  346. c1 := cert.NebulaCertificate{
  347. Details: cert.NebulaCertificateDetails{
  348. Name: "host1",
  349. Ips: []*net.IPNet{&ipNet},
  350. Issuer: "signer-sha-bad",
  351. },
  352. }
  353. h1 := HostInfo{
  354. ConnectionState: &ConnectionState{
  355. peerCert: &c1,
  356. },
  357. }
  358. h1.CreateRemoteCIDR(&c1)
  359. c2 := cert.NebulaCertificate{
  360. Details: cert.NebulaCertificateDetails{
  361. Name: "host2",
  362. Ips: []*net.IPNet{&ipNet},
  363. Issuer: "signer-sha",
  364. },
  365. }
  366. h2 := HostInfo{
  367. ConnectionState: &ConnectionState{
  368. peerCert: &c2,
  369. },
  370. }
  371. h2.CreateRemoteCIDR(&c2)
  372. c3 := cert.NebulaCertificate{
  373. Details: cert.NebulaCertificateDetails{
  374. Name: "host3",
  375. Ips: []*net.IPNet{&ipNet},
  376. Issuer: "signer-sha-bad",
  377. },
  378. }
  379. h3 := HostInfo{
  380. ConnectionState: &ConnectionState{
  381. peerCert: &c3,
  382. },
  383. }
  384. h3.CreateRemoteCIDR(&c3)
  385. fw := NewFirewall(time.Second, time.Minute, time.Hour, &c)
  386. assert.Nil(t, fw.AddRule(true, fwProtoAny, 1, 1, []string{}, "host1", nil, "", ""))
  387. assert.Nil(t, fw.AddRule(true, fwProtoAny, 1, 1, []string{}, "", nil, "", "signer-sha"))
  388. cp := cert.NewCAPool()
  389. // c1 should pass because host match
  390. assert.False(t, fw.Drop([]byte{}, p, true, &h1, cp))
  391. // c2 should pass because ca sha match
  392. resetConntrack(fw)
  393. assert.False(t, fw.Drop([]byte{}, p, true, &h2, cp))
  394. // c3 should fail because no match
  395. resetConntrack(fw)
  396. assert.True(t, fw.Drop([]byte{}, p, true, &h3, cp))
  397. }
  398. func BenchmarkLookup(b *testing.B) {
  399. ml := func(m map[string]struct{}, a [][]string) {
  400. for n := 0; n < b.N; n++ {
  401. for _, sg := range a {
  402. found := false
  403. for _, g := range sg {
  404. if _, ok := m[g]; !ok {
  405. found = false
  406. break
  407. }
  408. found = true
  409. }
  410. if found {
  411. return
  412. }
  413. }
  414. }
  415. }
  416. b.Run("array to map best", func(b *testing.B) {
  417. m := map[string]struct{}{
  418. "1ne": {},
  419. "2wo": {},
  420. "3hr": {},
  421. "4ou": {},
  422. "5iv": {},
  423. "6ix": {},
  424. }
  425. a := [][]string{
  426. {"1ne", "2wo", "3hr", "4ou", "5iv", "6ix"},
  427. {"one", "2wo", "3hr", "4ou", "5iv", "6ix"},
  428. {"one", "two", "3hr", "4ou", "5iv", "6ix"},
  429. {"one", "two", "thr", "4ou", "5iv", "6ix"},
  430. {"one", "two", "thr", "fou", "5iv", "6ix"},
  431. {"one", "two", "thr", "fou", "fiv", "6ix"},
  432. {"one", "two", "thr", "fou", "fiv", "six"},
  433. }
  434. for n := 0; n < b.N; n++ {
  435. ml(m, a)
  436. }
  437. })
  438. b.Run("array to map worst", func(b *testing.B) {
  439. m := map[string]struct{}{
  440. "one": {},
  441. "two": {},
  442. "thr": {},
  443. "fou": {},
  444. "fiv": {},
  445. "six": {},
  446. }
  447. a := [][]string{
  448. {"1ne", "2wo", "3hr", "4ou", "5iv", "6ix"},
  449. {"one", "2wo", "3hr", "4ou", "5iv", "6ix"},
  450. {"one", "two", "3hr", "4ou", "5iv", "6ix"},
  451. {"one", "two", "thr", "4ou", "5iv", "6ix"},
  452. {"one", "two", "thr", "fou", "5iv", "6ix"},
  453. {"one", "two", "thr", "fou", "fiv", "6ix"},
  454. {"one", "two", "thr", "fou", "fiv", "six"},
  455. }
  456. for n := 0; n < b.N; n++ {
  457. ml(m, a)
  458. }
  459. })
  460. //TODO: only way array lookup in array will help is if both are sorted, then maybe it's faster
  461. }
  462. func Test_parsePort(t *testing.T) {
  463. _, _, err := parsePort("")
  464. assert.EqualError(t, err, "was not a number; ``")
  465. _, _, err = parsePort(" ")
  466. assert.EqualError(t, err, "was not a number; ` `")
  467. _, _, err = parsePort("-")
  468. assert.EqualError(t, err, "appears to be a range but could not be parsed; `-`")
  469. _, _, err = parsePort(" - ")
  470. assert.EqualError(t, err, "appears to be a range but could not be parsed; ` - `")
  471. _, _, err = parsePort("a-b")
  472. assert.EqualError(t, err, "beginning range was not a number; `a`")
  473. _, _, err = parsePort("1-b")
  474. assert.EqualError(t, err, "ending range was not a number; `b`")
  475. s, e, err := parsePort(" 1 - 2 ")
  476. assert.Equal(t, int32(1), s)
  477. assert.Equal(t, int32(2), e)
  478. assert.Nil(t, err)
  479. s, e, err = parsePort("0-1")
  480. assert.Equal(t, int32(0), s)
  481. assert.Equal(t, int32(0), e)
  482. assert.Nil(t, err)
  483. s, e, err = parsePort("9919")
  484. assert.Equal(t, int32(9919), s)
  485. assert.Equal(t, int32(9919), e)
  486. assert.Nil(t, err)
  487. s, e, err = parsePort("any")
  488. assert.Equal(t, int32(0), s)
  489. assert.Equal(t, int32(0), e)
  490. assert.Nil(t, err)
  491. }
  492. func TestNewFirewallFromConfig(t *testing.T) {
  493. // Test a bad rule definition
  494. c := &cert.NebulaCertificate{}
  495. conf := NewConfig()
  496. conf.Settings["firewall"] = map[interface{}]interface{}{"outbound": "asdf"}
  497. _, err := NewFirewallFromConfig(c, conf)
  498. assert.EqualError(t, err, "firewall.outbound failed to parse, should be an array of rules")
  499. // Test both port and code
  500. conf = NewConfig()
  501. conf.Settings["firewall"] = map[interface{}]interface{}{"outbound": []interface{}{map[interface{}]interface{}{"port": "1", "code": "2"}}}
  502. _, err = NewFirewallFromConfig(c, conf)
  503. assert.EqualError(t, err, "firewall.outbound rule #0; only one of port or code should be provided")
  504. // Test missing host, group, cidr, ca_name and ca_sha
  505. conf = NewConfig()
  506. conf.Settings["firewall"] = map[interface{}]interface{}{"outbound": []interface{}{map[interface{}]interface{}{}}}
  507. _, err = NewFirewallFromConfig(c, conf)
  508. assert.EqualError(t, err, "firewall.outbound rule #0; at least one of host, group, cidr, ca_name, or ca_sha must be provided")
  509. // Test code/port error
  510. conf = NewConfig()
  511. conf.Settings["firewall"] = map[interface{}]interface{}{"outbound": []interface{}{map[interface{}]interface{}{"code": "a", "host": "testh"}}}
  512. _, err = NewFirewallFromConfig(c, conf)
  513. assert.EqualError(t, err, "firewall.outbound rule #0; code was not a number; `a`")
  514. conf.Settings["firewall"] = map[interface{}]interface{}{"outbound": []interface{}{map[interface{}]interface{}{"port": "a", "host": "testh"}}}
  515. _, err = NewFirewallFromConfig(c, conf)
  516. assert.EqualError(t, err, "firewall.outbound rule #0; port was not a number; `a`")
  517. // Test proto error
  518. conf = NewConfig()
  519. conf.Settings["firewall"] = map[interface{}]interface{}{"outbound": []interface{}{map[interface{}]interface{}{"code": "1", "host": "testh"}}}
  520. _, err = NewFirewallFromConfig(c, conf)
  521. assert.EqualError(t, err, "firewall.outbound rule #0; proto was not understood; ``")
  522. // Test cidr parse error
  523. conf = NewConfig()
  524. conf.Settings["firewall"] = map[interface{}]interface{}{"outbound": []interface{}{map[interface{}]interface{}{"code": "1", "cidr": "testh", "proto": "any"}}}
  525. _, err = NewFirewallFromConfig(c, conf)
  526. assert.EqualError(t, err, "firewall.outbound rule #0; cidr did not parse; invalid CIDR address: testh")
  527. // Test both group and groups
  528. conf = NewConfig()
  529. conf.Settings["firewall"] = map[interface{}]interface{}{"inbound": []interface{}{map[interface{}]interface{}{"port": "1", "proto": "any", "group": "a", "groups": []string{"b", "c"}}}}
  530. _, err = NewFirewallFromConfig(c, conf)
  531. assert.EqualError(t, err, "firewall.inbound rule #0; only one of group or groups should be defined, both provided")
  532. }
  533. func TestAddFirewallRulesFromConfig(t *testing.T) {
  534. // Test adding tcp rule
  535. conf := NewConfig()
  536. mf := &mockFirewall{}
  537. conf.Settings["firewall"] = map[interface{}]interface{}{"outbound": []interface{}{map[interface{}]interface{}{"port": "1", "proto": "tcp", "host": "a"}}}
  538. assert.Nil(t, AddFirewallRulesFromConfig(false, conf, mf))
  539. assert.Equal(t, addRuleCall{incoming: false, proto: fwProtoTCP, startPort: 1, endPort: 1, groups: nil, host: "a", ip: nil}, mf.lastCall)
  540. // Test adding udp rule
  541. conf = NewConfig()
  542. mf = &mockFirewall{}
  543. conf.Settings["firewall"] = map[interface{}]interface{}{"outbound": []interface{}{map[interface{}]interface{}{"port": "1", "proto": "udp", "host": "a"}}}
  544. assert.Nil(t, AddFirewallRulesFromConfig(false, conf, mf))
  545. assert.Equal(t, addRuleCall{incoming: false, proto: fwProtoUDP, startPort: 1, endPort: 1, groups: nil, host: "a", ip: nil}, mf.lastCall)
  546. // Test adding icmp rule
  547. conf = NewConfig()
  548. mf = &mockFirewall{}
  549. conf.Settings["firewall"] = map[interface{}]interface{}{"outbound": []interface{}{map[interface{}]interface{}{"port": "1", "proto": "icmp", "host": "a"}}}
  550. assert.Nil(t, AddFirewallRulesFromConfig(false, conf, mf))
  551. assert.Equal(t, addRuleCall{incoming: false, proto: fwProtoICMP, startPort: 1, endPort: 1, groups: nil, host: "a", ip: nil}, mf.lastCall)
  552. // Test adding any rule
  553. conf = NewConfig()
  554. mf = &mockFirewall{}
  555. conf.Settings["firewall"] = map[interface{}]interface{}{"inbound": []interface{}{map[interface{}]interface{}{"port": "1", "proto": "any", "host": "a"}}}
  556. assert.Nil(t, AddFirewallRulesFromConfig(true, conf, mf))
  557. assert.Equal(t, addRuleCall{incoming: true, proto: fwProtoAny, startPort: 1, endPort: 1, groups: nil, host: "a", ip: nil}, mf.lastCall)
  558. // Test adding rule with ca_sha
  559. conf = NewConfig()
  560. mf = &mockFirewall{}
  561. conf.Settings["firewall"] = map[interface{}]interface{}{"inbound": []interface{}{map[interface{}]interface{}{"port": "1", "proto": "any", "ca_sha": "12312313123"}}}
  562. assert.Nil(t, AddFirewallRulesFromConfig(true, conf, mf))
  563. assert.Equal(t, addRuleCall{incoming: true, proto: fwProtoAny, startPort: 1, endPort: 1, groups: nil, ip: nil, caSha: "12312313123"}, mf.lastCall)
  564. // Test adding rule with ca_name
  565. conf = NewConfig()
  566. mf = &mockFirewall{}
  567. conf.Settings["firewall"] = map[interface{}]interface{}{"inbound": []interface{}{map[interface{}]interface{}{"port": "1", "proto": "any", "ca_name": "root01"}}}
  568. assert.Nil(t, AddFirewallRulesFromConfig(true, conf, mf))
  569. assert.Equal(t, addRuleCall{incoming: true, proto: fwProtoAny, startPort: 1, endPort: 1, groups: nil, ip: nil, caName: "root01"}, mf.lastCall)
  570. // Test single group
  571. conf = NewConfig()
  572. mf = &mockFirewall{}
  573. conf.Settings["firewall"] = map[interface{}]interface{}{"inbound": []interface{}{map[interface{}]interface{}{"port": "1", "proto": "any", "group": "a"}}}
  574. assert.Nil(t, AddFirewallRulesFromConfig(true, conf, mf))
  575. assert.Equal(t, addRuleCall{incoming: true, proto: fwProtoAny, startPort: 1, endPort: 1, groups: []string{"a"}, ip: nil}, mf.lastCall)
  576. // Test single groups
  577. conf = NewConfig()
  578. mf = &mockFirewall{}
  579. conf.Settings["firewall"] = map[interface{}]interface{}{"inbound": []interface{}{map[interface{}]interface{}{"port": "1", "proto": "any", "groups": "a"}}}
  580. assert.Nil(t, AddFirewallRulesFromConfig(true, conf, mf))
  581. assert.Equal(t, addRuleCall{incoming: true, proto: fwProtoAny, startPort: 1, endPort: 1, groups: []string{"a"}, ip: nil}, mf.lastCall)
  582. // Test multiple AND groups
  583. conf = NewConfig()
  584. mf = &mockFirewall{}
  585. conf.Settings["firewall"] = map[interface{}]interface{}{"inbound": []interface{}{map[interface{}]interface{}{"port": "1", "proto": "any", "groups": []string{"a", "b"}}}}
  586. assert.Nil(t, AddFirewallRulesFromConfig(true, conf, mf))
  587. assert.Equal(t, addRuleCall{incoming: true, proto: fwProtoAny, startPort: 1, endPort: 1, groups: []string{"a", "b"}, ip: nil}, mf.lastCall)
  588. // Test Add error
  589. conf = NewConfig()
  590. mf = &mockFirewall{}
  591. mf.nextCallReturn = errors.New("test error")
  592. conf.Settings["firewall"] = map[interface{}]interface{}{"inbound": []interface{}{map[interface{}]interface{}{"port": "1", "proto": "any", "host": "a"}}}
  593. assert.EqualError(t, AddFirewallRulesFromConfig(true, conf, mf), "firewall.inbound rule #0; `test error`")
  594. }
  595. func TestTCPRTTTracking(t *testing.T) {
  596. b := make([]byte, 200)
  597. // Max ip IHL (60 bytes) and tcp IHL (60 bytes)
  598. b[0] = 15
  599. b[60+12] = 15 << 4
  600. f := Firewall{
  601. metricTCPRTT: metrics.GetOrRegisterHistogram("nope", nil, metrics.NewExpDecaySample(1028, 0.015)),
  602. }
  603. // Set SEQ to 1
  604. binary.BigEndian.PutUint32(b[60+4:60+8], 1)
  605. c := &conn{}
  606. setTCPRTTTracking(c, b)
  607. assert.Equal(t, uint32(1), c.Seq)
  608. // Bad ack - no ack flag
  609. binary.BigEndian.PutUint32(b[60+8:60+12], 80)
  610. assert.False(t, f.checkTCPRTT(c, b))
  611. // Bad ack, number is too low
  612. binary.BigEndian.PutUint32(b[60+8:60+12], 0)
  613. b[60+13] = uint8(0x10)
  614. assert.False(t, f.checkTCPRTT(c, b))
  615. // Good ack
  616. binary.BigEndian.PutUint32(b[60+8:60+12], 80)
  617. assert.True(t, f.checkTCPRTT(c, b))
  618. assert.Equal(t, uint32(0), c.Seq)
  619. // Set SEQ to 1
  620. binary.BigEndian.PutUint32(b[60+4:60+8], 1)
  621. c = &conn{}
  622. setTCPRTTTracking(c, b)
  623. assert.Equal(t, uint32(1), c.Seq)
  624. // Good acks
  625. binary.BigEndian.PutUint32(b[60+8:60+12], 81)
  626. assert.True(t, f.checkTCPRTT(c, b))
  627. assert.Equal(t, uint32(0), c.Seq)
  628. // Set SEQ to max uint32 - 20
  629. binary.BigEndian.PutUint32(b[60+4:60+8], ^uint32(0)-20)
  630. c = &conn{}
  631. setTCPRTTTracking(c, b)
  632. assert.Equal(t, ^uint32(0)-20, c.Seq)
  633. // Good acks
  634. binary.BigEndian.PutUint32(b[60+8:60+12], 81)
  635. assert.True(t, f.checkTCPRTT(c, b))
  636. assert.Equal(t, uint32(0), c.Seq)
  637. // Set SEQ to max uint32 / 2
  638. binary.BigEndian.PutUint32(b[60+4:60+8], ^uint32(0)/2)
  639. c = &conn{}
  640. setTCPRTTTracking(c, b)
  641. assert.Equal(t, ^uint32(0)/2, c.Seq)
  642. // Below
  643. binary.BigEndian.PutUint32(b[60+8:60+12], ^uint32(0)/2-1)
  644. assert.False(t, f.checkTCPRTT(c, b))
  645. assert.Equal(t, ^uint32(0)/2, c.Seq)
  646. // Halfway below
  647. binary.BigEndian.PutUint32(b[60+8:60+12], uint32(0))
  648. assert.False(t, f.checkTCPRTT(c, b))
  649. assert.Equal(t, ^uint32(0)/2, c.Seq)
  650. // Halfway above is ok
  651. binary.BigEndian.PutUint32(b[60+8:60+12], ^uint32(0))
  652. assert.True(t, f.checkTCPRTT(c, b))
  653. assert.Equal(t, uint32(0), c.Seq)
  654. // Set SEQ to max uint32
  655. binary.BigEndian.PutUint32(b[60+4:60+8], ^uint32(0))
  656. c = &conn{}
  657. setTCPRTTTracking(c, b)
  658. assert.Equal(t, ^uint32(0), c.Seq)
  659. // Halfway + 1 above
  660. binary.BigEndian.PutUint32(b[60+8:60+12], ^uint32(0)/2+1)
  661. assert.False(t, f.checkTCPRTT(c, b))
  662. assert.Equal(t, ^uint32(0), c.Seq)
  663. // Halfway above
  664. binary.BigEndian.PutUint32(b[60+8:60+12], ^uint32(0)/2)
  665. assert.True(t, f.checkTCPRTT(c, b))
  666. assert.Equal(t, uint32(0), c.Seq)
  667. }
  668. func TestFirewall_convertRule(t *testing.T) {
  669. ob := &bytes.Buffer{}
  670. out := l.Out
  671. l.SetOutput(ob)
  672. defer l.SetOutput(out)
  673. // Ensure group array of 1 is converted and a warning is printed
  674. c := map[interface{}]interface{}{
  675. "group": []interface{}{"group1"},
  676. }
  677. r, err := convertRule(c, "test", 1)
  678. assert.Contains(t, ob.String(), "test rule #1; group was an array with a single value, converting to simple value")
  679. assert.Nil(t, err)
  680. assert.Equal(t, "group1", r.Group)
  681. // Ensure group array of > 1 is errord
  682. ob.Reset()
  683. c = map[interface{}]interface{}{
  684. "group": []interface{}{"group1", "group2"},
  685. }
  686. r, err = convertRule(c, "test", 1)
  687. assert.Equal(t, "", ob.String())
  688. assert.Error(t, err, "group should contain a single value, an array with more than one entry was provided")
  689. // Make sure a well formed group is alright
  690. ob.Reset()
  691. c = map[interface{}]interface{}{
  692. "group": "group1",
  693. }
  694. r, err = convertRule(c, "test", 1)
  695. assert.Nil(t, err)
  696. assert.Equal(t, "group1", r.Group)
  697. }
  698. type addRuleCall struct {
  699. incoming bool
  700. proto uint8
  701. startPort int32
  702. endPort int32
  703. groups []string
  704. host string
  705. ip *net.IPNet
  706. caName string
  707. caSha string
  708. }
  709. type mockFirewall struct {
  710. lastCall addRuleCall
  711. nextCallReturn error
  712. }
  713. func (mf *mockFirewall) AddRule(incoming bool, proto uint8, startPort int32, endPort int32, groups []string, host string, ip *net.IPNet, caName string, caSha string) error {
  714. mf.lastCall = addRuleCall{
  715. incoming: incoming,
  716. proto: proto,
  717. startPort: startPort,
  718. endPort: endPort,
  719. groups: groups,
  720. host: host,
  721. ip: ip,
  722. caName: caName,
  723. caSha: caSha,
  724. }
  725. err := mf.nextCallReturn
  726. mf.nextCallReturn = nil
  727. return err
  728. }
  729. func resetConntrack(fw *Firewall) {
  730. fw.connMutex.Lock()
  731. fw.Conns = map[FirewallPacket]*conn{}
  732. fw.connMutex.Unlock()
  733. }