firewall_test.go 25 KB

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