filter_test.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package filter
  4. import (
  5. "encoding/hex"
  6. "fmt"
  7. "net/netip"
  8. "reflect"
  9. "strconv"
  10. "strings"
  11. "testing"
  12. "github.com/google/go-cmp/cmp"
  13. "go4.org/netipx"
  14. "tailscale.com/net/packet"
  15. "tailscale.com/net/tsaddr"
  16. "tailscale.com/tailcfg"
  17. "tailscale.com/tstest"
  18. "tailscale.com/tstime/rate"
  19. "tailscale.com/types/ipproto"
  20. "tailscale.com/types/logger"
  21. )
  22. // testAllowedProto is an IP protocol number we treat as allowed for
  23. // these tests.
  24. const (
  25. testAllowedProto ipproto.Proto = 116
  26. testDeniedProto ipproto.Proto = 127 // CRUDP, appropriately cruddy
  27. )
  28. func m(srcs []netip.Prefix, dsts []NetPortRange, protos ...ipproto.Proto) Match {
  29. if protos == nil {
  30. protos = defaultProtos
  31. }
  32. return Match{
  33. IPProto: protos,
  34. Srcs: srcs,
  35. Dsts: dsts,
  36. }
  37. }
  38. func newFilter(logf logger.Logf) *Filter {
  39. matches := []Match{
  40. m(nets("8.1.1.1", "8.2.2.2"), netports("1.2.3.4:22", "5.6.7.8:23-24")),
  41. m(nets("9.1.1.1", "9.2.2.2"), netports("1.2.3.4:22", "5.6.7.8:23-24"), ipproto.SCTP),
  42. m(nets("8.1.1.1", "8.2.2.2"), netports("5.6.7.8:27-28")),
  43. m(nets("2.2.2.2"), netports("8.1.1.1:22")),
  44. m(nets("0.0.0.0/0"), netports("100.122.98.50:*")),
  45. m(nets("0.0.0.0/0"), netports("0.0.0.0/0:443")),
  46. m(nets("153.1.1.1", "153.1.1.2", "153.3.3.3"), netports("1.2.3.4:999")),
  47. m(nets("::1", "::2"), netports("2001::1:22", "2001::2:22")),
  48. m(nets("::/0"), netports("::/0:443")),
  49. m(nets("0.0.0.0/0"), netports("0.0.0.0/0:*"), testAllowedProto),
  50. m(nets("::/0"), netports("::/0:*"), testAllowedProto),
  51. }
  52. // Expects traffic to 100.122.98.50, 1.2.3.4, 5.6.7.8,
  53. // 102.102.102.102, 119.119.119.119, 8.1.0.0/16
  54. var localNets netipx.IPSetBuilder
  55. for _, n := range nets("100.122.98.50", "1.2.3.4", "5.6.7.8", "102.102.102.102", "119.119.119.119", "8.1.0.0/16", "2001::/16") {
  56. localNets.AddPrefix(n)
  57. }
  58. var logB netipx.IPSetBuilder
  59. logB.Complement()
  60. localNetsSet, _ := localNets.IPSet()
  61. logBSet, _ := logB.IPSet()
  62. return New(matches, localNetsSet, logBSet, nil, logf)
  63. }
  64. func TestFilter(t *testing.T) {
  65. acl := newFilter(t.Logf)
  66. type InOut struct {
  67. want Response
  68. p packet.Parsed
  69. }
  70. tests := []InOut{
  71. // allow 8.1.1.1 => 1.2.3.4:22
  72. {Accept, parsed(ipproto.TCP, "8.1.1.1", "1.2.3.4", 999, 22)},
  73. {Accept, parsed(ipproto.ICMPv4, "8.1.1.1", "1.2.3.4", 0, 0)},
  74. {Drop, parsed(ipproto.TCP, "8.1.1.1", "1.2.3.4", 0, 0)},
  75. {Accept, parsed(ipproto.TCP, "8.1.1.1", "1.2.3.4", 0, 22)},
  76. {Drop, parsed(ipproto.TCP, "8.1.1.1", "1.2.3.4", 0, 21)},
  77. // allow 8.2.2.2. => 1.2.3.4:22
  78. {Accept, parsed(ipproto.TCP, "8.2.2.2", "1.2.3.4", 0, 22)},
  79. {Drop, parsed(ipproto.TCP, "8.2.2.2", "1.2.3.4", 0, 23)},
  80. {Drop, parsed(ipproto.TCP, "8.3.3.3", "1.2.3.4", 0, 22)},
  81. // allow 8.1.1.1 => 5.6.7.8:23-24
  82. {Accept, parsed(ipproto.TCP, "8.1.1.1", "5.6.7.8", 0, 23)},
  83. {Accept, parsed(ipproto.TCP, "8.1.1.1", "5.6.7.8", 0, 24)},
  84. {Drop, parsed(ipproto.TCP, "8.1.1.3", "5.6.7.8", 0, 24)},
  85. {Drop, parsed(ipproto.TCP, "8.1.1.1", "5.6.7.8", 0, 22)},
  86. // allow * => *:443
  87. {Accept, parsed(ipproto.TCP, "17.34.51.68", "8.1.34.51", 0, 443)},
  88. {Drop, parsed(ipproto.TCP, "17.34.51.68", "8.1.34.51", 0, 444)},
  89. // allow * => 100.122.98.50:*
  90. {Accept, parsed(ipproto.TCP, "17.34.51.68", "100.122.98.50", 0, 999)},
  91. {Accept, parsed(ipproto.TCP, "17.34.51.68", "100.122.98.50", 0, 0)},
  92. // allow ::1, ::2 => [2001::1]:22
  93. {Accept, parsed(ipproto.TCP, "::1", "2001::1", 0, 22)},
  94. {Accept, parsed(ipproto.ICMPv6, "::1", "2001::1", 0, 0)},
  95. {Accept, parsed(ipproto.TCP, "::2", "2001::1", 0, 22)},
  96. {Accept, parsed(ipproto.TCP, "::2", "2001::2", 0, 22)},
  97. {Drop, parsed(ipproto.TCP, "::1", "2001::1", 0, 23)},
  98. {Drop, parsed(ipproto.TCP, "::1", "2001::3", 0, 22)},
  99. {Drop, parsed(ipproto.TCP, "::3", "2001::1", 0, 22)},
  100. // allow * => *:443
  101. {Accept, parsed(ipproto.TCP, "::1", "2001::1", 0, 443)},
  102. {Drop, parsed(ipproto.TCP, "::1", "2001::1", 0, 444)},
  103. // localNets prefilter - accepted by policy filter, but
  104. // unexpected dst IP.
  105. {Drop, parsed(ipproto.TCP, "8.1.1.1", "16.32.48.64", 0, 443)},
  106. {Drop, parsed(ipproto.TCP, "1::", "2602::1", 0, 443)},
  107. // Don't allow protocols not specified by filter
  108. {Drop, parsed(ipproto.SCTP, "8.1.1.1", "1.2.3.4", 999, 22)},
  109. // But SCTP is allowed for 9.1.1.1
  110. {Accept, parsed(ipproto.SCTP, "9.1.1.1", "1.2.3.4", 999, 22)},
  111. // Unknown protocol is allowed if all its ports are allowed.
  112. {Accept, parsed(testAllowedProto, "1.2.3.4", "5.6.7.8", 0, 0)},
  113. {Accept, parsed(testAllowedProto, "2001::1", "2001::2", 0, 0)},
  114. {Drop, parsed(testDeniedProto, "1.2.3.4", "5.6.7.8", 0, 0)},
  115. {Drop, parsed(testDeniedProto, "2001::1", "2001::2", 0, 0)},
  116. }
  117. for i, test := range tests {
  118. aclFunc := acl.runIn4
  119. if test.p.IPVersion == 6 {
  120. aclFunc = acl.runIn6
  121. }
  122. if got, why := aclFunc(&test.p); test.want != got {
  123. t.Errorf("#%d runIn got=%v want=%v why=%q packet:%v", i, got, test.want, why, test.p)
  124. }
  125. if test.p.IPProto == ipproto.TCP {
  126. var got Response
  127. if test.p.IPVersion == 4 {
  128. got = acl.CheckTCP(test.p.Src.Addr(), test.p.Dst.Addr(), test.p.Dst.Port())
  129. } else {
  130. got = acl.CheckTCP(test.p.Src.Addr(), test.p.Dst.Addr(), test.p.Dst.Port())
  131. }
  132. if test.want != got {
  133. t.Errorf("#%d CheckTCP got=%v want=%v packet:%v", i, got, test.want, test.p)
  134. }
  135. // TCP and UDP are treated equivalently in the filter - verify that.
  136. test.p.IPProto = ipproto.UDP
  137. if got, why := aclFunc(&test.p); test.want != got {
  138. t.Errorf("#%d runIn (UDP) got=%v want=%v why=%q packet:%v", i, got, test.want, why, test.p)
  139. }
  140. }
  141. // Update UDP state
  142. _, _ = acl.runOut(&test.p)
  143. }
  144. }
  145. func TestUDPState(t *testing.T) {
  146. acl := newFilter(t.Logf)
  147. flags := LogDrops | LogAccepts
  148. a4 := parsed(ipproto.UDP, "119.119.119.119", "102.102.102.102", 4242, 4343)
  149. b4 := parsed(ipproto.UDP, "102.102.102.102", "119.119.119.119", 4343, 4242)
  150. // Unsolicited UDP traffic gets dropped
  151. if got := acl.RunIn(&a4, flags); got != Drop {
  152. t.Fatalf("incoming initial packet not dropped, got=%v: %v", got, a4)
  153. }
  154. // We talk to that peer
  155. if got := acl.RunOut(&b4, flags); got != Accept {
  156. t.Fatalf("outbound packet didn't egress, got=%v: %v", got, b4)
  157. }
  158. // Now, the same packet as before is allowed back.
  159. if got := acl.RunIn(&a4, flags); got != Accept {
  160. t.Fatalf("incoming response packet not accepted, got=%v: %v", got, a4)
  161. }
  162. a6 := parsed(ipproto.UDP, "2001::2", "2001::1", 4242, 4343)
  163. b6 := parsed(ipproto.UDP, "2001::1", "2001::2", 4343, 4242)
  164. // Unsolicited UDP traffic gets dropped
  165. if got := acl.RunIn(&a6, flags); got != Drop {
  166. t.Fatalf("incoming initial packet not dropped: %v", a4)
  167. }
  168. // We talk to that peer
  169. if got := acl.RunOut(&b6, flags); got != Accept {
  170. t.Fatalf("outbound packet didn't egress: %v", b4)
  171. }
  172. // Now, the same packet as before is allowed back.
  173. if got := acl.RunIn(&a6, flags); got != Accept {
  174. t.Fatalf("incoming response packet not accepted: %v", a4)
  175. }
  176. }
  177. func TestNoAllocs(t *testing.T) {
  178. acl := newFilter(t.Logf)
  179. tcp4Packet := raw4(ipproto.TCP, "8.1.1.1", "1.2.3.4", 999, 22, 0)
  180. udp4Packet := raw4(ipproto.UDP, "8.1.1.1", "1.2.3.4", 999, 22, 0)
  181. tcp6Packet := raw6(ipproto.TCP, "2001::1", "2001::2", 999, 22, 0)
  182. udp6Packet := raw6(ipproto.UDP, "2001::1", "2001::2", 999, 22, 0)
  183. tests := []struct {
  184. name string
  185. dir direction
  186. packet []byte
  187. }{
  188. {"tcp4_in", in, tcp4Packet},
  189. {"tcp6_in", in, tcp6Packet},
  190. {"tcp4_out", out, tcp4Packet},
  191. {"tcp6_out", out, tcp6Packet},
  192. {"udp4_in", in, udp4Packet},
  193. {"udp6_in", in, udp6Packet},
  194. {"udp4_out", out, udp4Packet},
  195. {"udp6_out", out, udp6Packet},
  196. }
  197. for _, test := range tests {
  198. t.Run(test.name, func(t *testing.T) {
  199. err := tstest.MinAllocsPerRun(t, 0, func() {
  200. q := &packet.Parsed{}
  201. q.Decode(test.packet)
  202. switch test.dir {
  203. case in:
  204. acl.RunIn(q, 0)
  205. case out:
  206. acl.RunOut(q, 0)
  207. }
  208. })
  209. if err != nil {
  210. t.Error(err)
  211. }
  212. })
  213. }
  214. }
  215. func TestParseIPSet(t *testing.T) {
  216. tests := []struct {
  217. host string
  218. bits int
  219. want []netip.Prefix
  220. wantErr string
  221. }{
  222. {"8.8.8.8", 24, pfx("8.8.8.8/24"), ""},
  223. {"2601:1234::", 64, pfx("2601:1234::/64"), ""},
  224. {"8.8.8.8", 33, nil, `invalid CIDR size 33 for IP "8.8.8.8"`},
  225. {"8.8.8.8", -1, pfx("8.8.8.8/32"), ""},
  226. {"8.8.8.8", 32, pfx("8.8.8.8/32"), ""},
  227. {"8.8.8.8/24", -1, nil, "8.8.8.8/24 contains non-network bits set"},
  228. {"8.8.8.0/24", 18, pfx("8.8.8.0/24"), ""}, // the 18 is ignored
  229. {"1.0.0.0-1.255.255.255", 5, pfx("1.0.0.0/8"), ""},
  230. {"1.0.0.0-2.1.2.3", 5, pfx("1.0.0.0/8", "2.0.0.0/16", "2.1.0.0/23", "2.1.2.0/30"), ""},
  231. {"1.0.0.2-1.0.0.1", -1, nil, "invalid IP range \"1.0.0.2-1.0.0.1\""},
  232. {"2601:1234::", 129, nil, `invalid CIDR size 129 for IP "2601:1234::"`},
  233. {"0.0.0.0", 24, pfx("0.0.0.0/24"), ""},
  234. {"::", 64, pfx("::/64"), ""},
  235. {"*", 24, pfx("0.0.0.0/0", "::/0"), ""},
  236. }
  237. for _, tt := range tests {
  238. var bits *int
  239. if tt.bits != -1 {
  240. bits = &tt.bits
  241. }
  242. got, err := parseIPSet(tt.host, bits)
  243. if err != nil {
  244. if err.Error() == tt.wantErr {
  245. continue
  246. }
  247. t.Errorf("parseIPSet(%q, %v) error: %v; want error %q", tt.host, tt.bits, err, tt.wantErr)
  248. }
  249. compareIP := cmp.Comparer(func(a, b netip.Addr) bool { return a == b })
  250. compareIPPrefix := cmp.Comparer(func(a, b netip.Prefix) bool { return a == b })
  251. if diff := cmp.Diff(got, tt.want, compareIP, compareIPPrefix); diff != "" {
  252. t.Errorf("parseIPSet(%q, %v) = %s; want %s", tt.host, tt.bits, got, tt.want)
  253. continue
  254. }
  255. }
  256. }
  257. func BenchmarkFilter(b *testing.B) {
  258. tcp4Packet := raw4(ipproto.TCP, "8.1.1.1", "1.2.3.4", 999, 22, 0)
  259. udp4Packet := raw4(ipproto.UDP, "8.1.1.1", "1.2.3.4", 999, 22, 0)
  260. icmp4Packet := raw4(ipproto.ICMPv4, "8.1.1.1", "1.2.3.4", 0, 0, 0)
  261. tcp6Packet := raw6(ipproto.TCP, "::1", "2001::1", 999, 22, 0)
  262. udp6Packet := raw6(ipproto.UDP, "::1", "2001::1", 999, 22, 0)
  263. icmp6Packet := raw6(ipproto.ICMPv6, "::1", "2001::1", 0, 0, 0)
  264. benches := []struct {
  265. name string
  266. dir direction
  267. packet []byte
  268. }{
  269. // Non-SYN TCP and ICMP have similar code paths in and out.
  270. {"icmp4", in, icmp4Packet},
  271. {"tcp4_syn_in", in, tcp4Packet},
  272. {"tcp4_syn_out", out, tcp4Packet},
  273. {"udp4_in", in, udp4Packet},
  274. {"udp4_out", out, udp4Packet},
  275. {"icmp6", in, icmp6Packet},
  276. {"tcp6_syn_in", in, tcp6Packet},
  277. {"tcp6_syn_out", out, tcp6Packet},
  278. {"udp6_in", in, udp6Packet},
  279. {"udp6_out", out, udp6Packet},
  280. }
  281. for _, bench := range benches {
  282. b.Run(bench.name, func(b *testing.B) {
  283. acl := newFilter(b.Logf)
  284. b.ReportAllocs()
  285. b.ResetTimer()
  286. for i := 0; i < b.N; i++ {
  287. q := &packet.Parsed{}
  288. q.Decode(bench.packet)
  289. // This branch seems to have no measurable impact on performance.
  290. if bench.dir == in {
  291. acl.RunIn(q, 0)
  292. } else {
  293. acl.RunOut(q, 0)
  294. }
  295. }
  296. })
  297. }
  298. }
  299. func TestPreFilter(t *testing.T) {
  300. packets := []struct {
  301. desc string
  302. want Response
  303. b []byte
  304. }{
  305. {"empty", Accept, []byte{}},
  306. {"short", Drop, []byte("short")},
  307. {"junk", Drop, raw4default(ipproto.Unknown, 10)},
  308. {"fragment", Accept, raw4default(ipproto.Fragment, 40)},
  309. {"tcp", noVerdict, raw4default(ipproto.TCP, 0)},
  310. {"udp", noVerdict, raw4default(ipproto.UDP, 0)},
  311. {"icmp", noVerdict, raw4default(ipproto.ICMPv4, 0)},
  312. }
  313. f := NewAllowNone(t.Logf, &netipx.IPSet{})
  314. for _, testPacket := range packets {
  315. p := &packet.Parsed{}
  316. p.Decode(testPacket.b)
  317. got := f.pre(p, LogDrops|LogAccepts, in)
  318. if got != testPacket.want {
  319. t.Errorf("%q got=%v want=%v packet:\n%s", testPacket.desc, got, testPacket.want, packet.Hexdump(testPacket.b))
  320. }
  321. }
  322. }
  323. func TestOmitDropLogging(t *testing.T) {
  324. tests := []struct {
  325. name string
  326. pkt *packet.Parsed
  327. dir direction
  328. want bool
  329. }{
  330. {
  331. name: "v4_tcp_out",
  332. pkt: &packet.Parsed{IPVersion: 4, IPProto: ipproto.TCP},
  333. dir: out,
  334. want: false,
  335. },
  336. {
  337. name: "v6_icmp_out", // as seen on Linux
  338. pkt: parseHexPkt(t, "60 00 00 00 00 00 3a 00 fe800000000000000000000000000000 ff020000000000000000000000000002"),
  339. dir: out,
  340. want: true,
  341. },
  342. {
  343. name: "v6_to_MLDv2_capable_routers", // as seen on Windows
  344. pkt: parseHexPkt(t, "60 00 00 00 00 24 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ff 02 00 00 00 00 00 00 00 00 00 00 00 00 00 16 3a 00 05 02 00 00 01 00 8f 00 6e 80 00 00 00 01 04 00 00 00 ff 02 00 00 00 00 00 00 00 00 00 00 00 00 00 0c"),
  345. dir: out,
  346. want: true,
  347. },
  348. {
  349. name: "v4_igmp_out", // on Windows, from https://github.com/tailscale/tailscale/issues/618
  350. pkt: parseHexPkt(t, "46 00 00 30 37 3a 00 00 01 02 10 0e a9 fe 53 6b e0 00 00 16 94 04 00 00 22 00 14 05 00 00 00 02 04 00 00 00 e0 00 00 fb 04 00 00 00 e0 00 00 fc"),
  351. dir: out,
  352. want: true,
  353. },
  354. {
  355. name: "v6_udp_multicast",
  356. pkt: parseHexPkt(t, "60 00 00 00 00 00 11 00 fe800000000000007dc6bc04499262a3 ff120000000000000000000000008384"),
  357. dir: out,
  358. want: true,
  359. },
  360. {
  361. name: "v4_multicast_out_low",
  362. pkt: &packet.Parsed{IPVersion: 4, Dst: mustIPPort("224.0.0.0:0")},
  363. dir: out,
  364. want: true,
  365. },
  366. {
  367. name: "v4_multicast_out_high",
  368. pkt: &packet.Parsed{IPVersion: 4, Dst: mustIPPort("239.255.255.255:0")},
  369. dir: out,
  370. want: true,
  371. },
  372. {
  373. name: "v4_link_local_unicast",
  374. pkt: &packet.Parsed{IPVersion: 4, Dst: mustIPPort("169.254.1.2:0")},
  375. dir: out,
  376. want: true,
  377. },
  378. }
  379. for _, tt := range tests {
  380. t.Run(tt.name, func(t *testing.T) {
  381. got := omitDropLogging(tt.pkt, tt.dir)
  382. if got != tt.want {
  383. t.Errorf("got %v; want %v\npacket: %#v\n%s", got, tt.want, tt.pkt, packet.Hexdump(tt.pkt.Buffer()))
  384. }
  385. })
  386. }
  387. }
  388. func TestLoggingPrivacy(t *testing.T) {
  389. tstest.Replace(t, &dropBucket, rate.NewLimiter(2^32, 2^32))
  390. tstest.Replace(t, &acceptBucket, dropBucket)
  391. var (
  392. logged bool
  393. testLogger logger.Logf
  394. )
  395. logf := func(format string, args ...any) {
  396. testLogger(format, args...)
  397. logged = true
  398. }
  399. var logB netipx.IPSetBuilder
  400. logB.AddPrefix(netip.MustParsePrefix("100.64.0.0/10"))
  401. logB.AddPrefix(tsaddr.TailscaleULARange())
  402. f := newFilter(logf)
  403. f.logIPs, _ = logB.IPSet()
  404. var (
  405. ts4 = netip.AddrPortFrom(tsaddr.CGNATRange().Addr().Next(), 1234)
  406. internet4 = netip.AddrPortFrom(netip.MustParseAddr("8.8.8.8"), 1234)
  407. ts6 = netip.AddrPortFrom(tsaddr.TailscaleULARange().Addr().Next(), 1234)
  408. internet6 = netip.AddrPortFrom(netip.MustParseAddr("2001::1"), 1234)
  409. )
  410. tests := []struct {
  411. name string
  412. pkt *packet.Parsed
  413. dir direction
  414. logged bool
  415. }{
  416. {
  417. name: "ts_to_ts_v4_out",
  418. pkt: &packet.Parsed{IPVersion: 4, IPProto: ipproto.TCP, Src: ts4, Dst: ts4},
  419. dir: out,
  420. logged: true,
  421. },
  422. {
  423. name: "ts_to_internet_v4_out",
  424. pkt: &packet.Parsed{IPVersion: 4, IPProto: ipproto.TCP, Src: ts4, Dst: internet4},
  425. dir: out,
  426. logged: false,
  427. },
  428. {
  429. name: "internet_to_ts_v4_out",
  430. pkt: &packet.Parsed{IPVersion: 4, IPProto: ipproto.TCP, Src: internet4, Dst: ts4},
  431. dir: out,
  432. logged: false,
  433. },
  434. {
  435. name: "ts_to_ts_v4_in",
  436. pkt: &packet.Parsed{IPVersion: 4, IPProto: ipproto.TCP, Src: ts4, Dst: ts4},
  437. dir: in,
  438. logged: true,
  439. },
  440. {
  441. name: "ts_to_internet_v4_in",
  442. pkt: &packet.Parsed{IPVersion: 4, IPProto: ipproto.TCP, Src: ts4, Dst: internet4},
  443. dir: in,
  444. logged: false,
  445. },
  446. {
  447. name: "internet_to_ts_v4_in",
  448. pkt: &packet.Parsed{IPVersion: 4, IPProto: ipproto.TCP, Src: internet4, Dst: ts4},
  449. dir: in,
  450. logged: false,
  451. },
  452. {
  453. name: "ts_to_ts_v6_out",
  454. pkt: &packet.Parsed{IPVersion: 6, IPProto: ipproto.TCP, Src: ts6, Dst: ts6},
  455. dir: out,
  456. logged: true,
  457. },
  458. {
  459. name: "ts_to_internet_v6_out",
  460. pkt: &packet.Parsed{IPVersion: 6, IPProto: ipproto.TCP, Src: ts6, Dst: internet6},
  461. dir: out,
  462. logged: false,
  463. },
  464. {
  465. name: "internet_to_ts_v6_out",
  466. pkt: &packet.Parsed{IPVersion: 6, IPProto: ipproto.TCP, Src: internet6, Dst: ts6},
  467. dir: out,
  468. logged: false,
  469. },
  470. {
  471. name: "ts_to_ts_v6_in",
  472. pkt: &packet.Parsed{IPVersion: 6, IPProto: ipproto.TCP, Src: ts6, Dst: ts6},
  473. dir: in,
  474. logged: true,
  475. },
  476. {
  477. name: "ts_to_internet_v6_in",
  478. pkt: &packet.Parsed{IPVersion: 6, IPProto: ipproto.TCP, Src: ts6, Dst: internet6},
  479. dir: in,
  480. logged: false,
  481. },
  482. {
  483. name: "internet_to_ts_v6_in",
  484. pkt: &packet.Parsed{IPVersion: 6, IPProto: ipproto.TCP, Src: internet6, Dst: ts6},
  485. dir: in,
  486. logged: false,
  487. },
  488. }
  489. for _, test := range tests {
  490. t.Run(test.name, func(t *testing.T) {
  491. test.pkt.StuffForTesting(1024)
  492. logged = false
  493. testLogger = t.Logf
  494. switch test.dir {
  495. case out:
  496. f.RunOut(test.pkt, LogDrops|LogAccepts)
  497. case in:
  498. f.RunIn(test.pkt, LogDrops|LogAccepts)
  499. default:
  500. panic("unknown direction")
  501. }
  502. if logged != test.logged {
  503. t.Errorf("logged = %v, want %v", logged, test.logged)
  504. }
  505. })
  506. }
  507. }
  508. var mustIP = netip.MustParseAddr
  509. func parsed(proto ipproto.Proto, src, dst string, sport, dport uint16) packet.Parsed {
  510. sip, dip := mustIP(src), mustIP(dst)
  511. var ret packet.Parsed
  512. ret.Decode(dummyPacket)
  513. ret.IPProto = proto
  514. ret.Src = netip.AddrPortFrom(sip, sport)
  515. ret.Dst = netip.AddrPortFrom(dip, dport)
  516. ret.TCPFlags = packet.TCPSyn
  517. if sip.Is4() {
  518. ret.IPVersion = 4
  519. } else {
  520. ret.IPVersion = 6
  521. }
  522. return ret
  523. }
  524. func raw6(proto ipproto.Proto, src, dst string, sport, dport uint16, trimLen int) []byte {
  525. u := packet.UDP6Header{
  526. IP6Header: packet.IP6Header{
  527. Src: mustIP(src),
  528. Dst: mustIP(dst),
  529. },
  530. SrcPort: sport,
  531. DstPort: dport,
  532. }
  533. payload := make([]byte, 12)
  534. // Set the right bit to look like a TCP SYN, if the packet ends up interpreted as TCP
  535. payload[5] = byte(packet.TCPSyn)
  536. b := packet.Generate(&u, payload) // payload large enough to possibly be TCP
  537. // UDP marshaling clobbers IPProto, so override it here.
  538. u.IP6Header.IPProto = proto
  539. if err := u.IP6Header.Marshal(b); err != nil {
  540. panic(err)
  541. }
  542. if trimLen > 0 {
  543. return b[:trimLen]
  544. } else {
  545. return b
  546. }
  547. }
  548. func raw4(proto ipproto.Proto, src, dst string, sport, dport uint16, trimLength int) []byte {
  549. u := packet.UDP4Header{
  550. IP4Header: packet.IP4Header{
  551. Src: mustIP(src),
  552. Dst: mustIP(dst),
  553. },
  554. SrcPort: sport,
  555. DstPort: dport,
  556. }
  557. payload := make([]byte, 12)
  558. // Set the right bit to look like a TCP SYN, if the packet ends up interpreted as TCP
  559. payload[5] = byte(packet.TCPSyn)
  560. b := packet.Generate(&u, payload) // payload large enough to possibly be TCP
  561. // UDP marshaling clobbers IPProto, so override it here.
  562. switch proto {
  563. case ipproto.Unknown, ipproto.Fragment:
  564. default:
  565. u.IP4Header.IPProto = proto
  566. }
  567. if err := u.IP4Header.Marshal(b); err != nil {
  568. panic(err)
  569. }
  570. if proto == ipproto.Fragment {
  571. // Set some fragment offset. This makes the IP
  572. // checksum wrong, but we don't validate the checksum
  573. // when parsing.
  574. b[7] = 255
  575. }
  576. if trimLength > 0 {
  577. return b[:trimLength]
  578. } else {
  579. return b
  580. }
  581. }
  582. func raw4default(proto ipproto.Proto, trimLength int) []byte {
  583. return raw4(proto, "8.8.8.8", "8.8.8.8", 53, 53, trimLength)
  584. }
  585. func parseHexPkt(t *testing.T, h string) *packet.Parsed {
  586. t.Helper()
  587. b, err := hex.DecodeString(strings.ReplaceAll(h, " ", ""))
  588. if err != nil {
  589. t.Fatalf("failed to read hex %q: %v", h, err)
  590. }
  591. p := new(packet.Parsed)
  592. p.Decode(b)
  593. return p
  594. }
  595. func mustIPPort(s string) netip.AddrPort {
  596. ipp, err := netip.ParseAddrPort(s)
  597. if err != nil {
  598. panic(err)
  599. }
  600. return ipp
  601. }
  602. func pfx(strs ...string) (ret []netip.Prefix) {
  603. for _, s := range strs {
  604. pfx, err := netip.ParsePrefix(s)
  605. if err != nil {
  606. panic(err)
  607. }
  608. ret = append(ret, pfx)
  609. }
  610. return ret
  611. }
  612. func nets(nets ...string) (ret []netip.Prefix) {
  613. for _, s := range nets {
  614. if !strings.Contains(s, "/") {
  615. ip, err := netip.ParseAddr(s)
  616. if err != nil {
  617. panic(err)
  618. }
  619. bits := uint8(32)
  620. if ip.Is6() {
  621. bits = 128
  622. }
  623. ret = append(ret, netip.PrefixFrom(ip, int(bits)))
  624. } else {
  625. pfx, err := netip.ParsePrefix(s)
  626. if err != nil {
  627. panic(err)
  628. }
  629. ret = append(ret, pfx)
  630. }
  631. }
  632. return ret
  633. }
  634. func ports(s string) PortRange {
  635. if s == "*" {
  636. return allPorts
  637. }
  638. var fs, ls string
  639. i := strings.IndexByte(s, '-')
  640. if i == -1 {
  641. fs = s
  642. ls = fs
  643. } else {
  644. fs = s[:i]
  645. ls = s[i+1:]
  646. }
  647. first, err := strconv.ParseInt(fs, 10, 16)
  648. if err != nil {
  649. panic(fmt.Sprintf("invalid NetPortRange %q", s))
  650. }
  651. last, err := strconv.ParseInt(ls, 10, 16)
  652. if err != nil {
  653. panic(fmt.Sprintf("invalid NetPortRange %q", s))
  654. }
  655. return PortRange{uint16(first), uint16(last)}
  656. }
  657. func netports(netPorts ...string) (ret []NetPortRange) {
  658. for _, s := range netPorts {
  659. i := strings.LastIndexByte(s, ':')
  660. if i == -1 {
  661. panic(fmt.Sprintf("invalid NetPortRange %q", s))
  662. }
  663. npr := NetPortRange{
  664. Net: nets(s[:i])[0],
  665. Ports: ports(s[i+1:]),
  666. }
  667. ret = append(ret, npr)
  668. }
  669. return ret
  670. }
  671. func TestMatchesFromFilterRules(t *testing.T) {
  672. tests := []struct {
  673. name string
  674. in []tailcfg.FilterRule
  675. want []Match
  676. }{
  677. {
  678. name: "empty",
  679. want: []Match{},
  680. },
  681. {
  682. name: "implicit_protos",
  683. in: []tailcfg.FilterRule{
  684. {
  685. SrcIPs: []string{"100.64.1.1"},
  686. DstPorts: []tailcfg.NetPortRange{{
  687. IP: "*",
  688. Ports: tailcfg.PortRange{First: 22, Last: 22},
  689. }},
  690. },
  691. },
  692. want: []Match{
  693. {
  694. IPProto: []ipproto.Proto{
  695. ipproto.TCP,
  696. ipproto.UDP,
  697. ipproto.ICMPv4,
  698. ipproto.ICMPv6,
  699. },
  700. Dsts: []NetPortRange{
  701. {
  702. Net: netip.MustParsePrefix("0.0.0.0/0"),
  703. Ports: PortRange{22, 22},
  704. },
  705. {
  706. Net: netip.MustParsePrefix("::0/0"),
  707. Ports: PortRange{22, 22},
  708. },
  709. },
  710. Srcs: []netip.Prefix{
  711. netip.MustParsePrefix("100.64.1.1/32"),
  712. },
  713. Caps: []CapMatch{},
  714. },
  715. },
  716. },
  717. {
  718. name: "explicit_protos",
  719. in: []tailcfg.FilterRule{
  720. {
  721. IPProto: []int{int(ipproto.TCP)},
  722. SrcIPs: []string{"100.64.1.1"},
  723. DstPorts: []tailcfg.NetPortRange{{
  724. IP: "1.2.0.0/16",
  725. Ports: tailcfg.PortRange{First: 22, Last: 22},
  726. }},
  727. },
  728. },
  729. want: []Match{
  730. {
  731. IPProto: []ipproto.Proto{
  732. ipproto.TCP,
  733. },
  734. Dsts: []NetPortRange{
  735. {
  736. Net: netip.MustParsePrefix("1.2.0.0/16"),
  737. Ports: PortRange{22, 22},
  738. },
  739. },
  740. Srcs: []netip.Prefix{
  741. netip.MustParsePrefix("100.64.1.1/32"),
  742. },
  743. Caps: []CapMatch{},
  744. },
  745. },
  746. },
  747. }
  748. for _, tt := range tests {
  749. t.Run(tt.name, func(t *testing.T) {
  750. got, err := MatchesFromFilterRules(tt.in)
  751. if err != nil {
  752. t.Fatal(err)
  753. }
  754. compareIP := cmp.Comparer(func(a, b netip.Addr) bool { return a == b })
  755. compareIPPrefix := cmp.Comparer(func(a, b netip.Prefix) bool { return a == b })
  756. if diff := cmp.Diff(got, tt.want, compareIP, compareIPPrefix); diff != "" {
  757. t.Errorf("wrong (-got+want)\n%s", diff)
  758. }
  759. })
  760. }
  761. }
  762. func TestNewAllowAllForTest(t *testing.T) {
  763. f := NewAllowAllForTest(logger.Discard)
  764. src := netip.MustParseAddr("100.100.2.3")
  765. dst := netip.MustParseAddr("100.100.1.2")
  766. res := f.CheckTCP(src, dst, 80)
  767. if res.IsDrop() {
  768. t.Fatalf("unexpected drop verdict: %v", res)
  769. }
  770. }
  771. func TestMatchesMatchProtoAndIPsOnlyIfAllPorts(t *testing.T) {
  772. tests := []struct {
  773. name string
  774. m Match
  775. p packet.Parsed
  776. want bool
  777. }{
  778. {
  779. name: "all_ports_okay",
  780. m: m(nets("0.0.0.0/0"), netports("0.0.0.0/0:*"), testAllowedProto),
  781. p: parsed(testAllowedProto, "1.2.3.4", "5.6.7.8", 0, 0),
  782. want: true,
  783. },
  784. {
  785. name: "all_ports_match_but_packet_wrong_proto",
  786. m: m(nets("0.0.0.0/0"), netports("0.0.0.0/0:*"), testAllowedProto),
  787. p: parsed(testDeniedProto, "1.2.3.4", "5.6.7.8", 0, 0),
  788. want: false,
  789. },
  790. {
  791. name: "ports_requirements_dont_match_unknown_proto",
  792. m: m(nets("0.0.0.0/0"), netports("0.0.0.0/0:12345"), testAllowedProto),
  793. p: parsed(testAllowedProto, "1.2.3.4", "5.6.7.8", 0, 0),
  794. want: false,
  795. },
  796. }
  797. for _, tt := range tests {
  798. t.Run(tt.name, func(t *testing.T) {
  799. matches := matches{tt.m}
  800. got := matches.matchProtoAndIPsOnlyIfAllPorts(&tt.p)
  801. if got != tt.want {
  802. t.Errorf("got = %v; want %v", got, tt.want)
  803. }
  804. })
  805. }
  806. }
  807. func TestCaps(t *testing.T) {
  808. mm, err := MatchesFromFilterRules([]tailcfg.FilterRule{
  809. {
  810. SrcIPs: []string{"*"},
  811. CapGrant: []tailcfg.CapGrant{{
  812. Dsts: []netip.Prefix{
  813. netip.MustParsePrefix("0.0.0.0/0"),
  814. },
  815. Caps: []string{"is_ipv4"},
  816. }},
  817. },
  818. {
  819. SrcIPs: []string{"*"},
  820. CapGrant: []tailcfg.CapGrant{{
  821. Dsts: []netip.Prefix{
  822. netip.MustParsePrefix("::/0"),
  823. },
  824. Caps: []string{"is_ipv6"},
  825. }},
  826. },
  827. {
  828. SrcIPs: []string{"100.199.0.0/16"},
  829. CapGrant: []tailcfg.CapGrant{{
  830. Dsts: []netip.Prefix{
  831. netip.MustParsePrefix("100.200.0.0/16"),
  832. },
  833. Caps: []string{"some_super_admin"},
  834. }},
  835. },
  836. })
  837. if err != nil {
  838. t.Fatal(err)
  839. }
  840. filt := New(mm, nil, nil, nil, t.Logf)
  841. tests := []struct {
  842. name string
  843. src, dst string // IP
  844. want []string
  845. }{
  846. {
  847. name: "v4",
  848. src: "1.2.3.4",
  849. dst: "2.4.5.5",
  850. want: []string{"is_ipv4"},
  851. },
  852. {
  853. name: "v6",
  854. src: "1::1",
  855. dst: "2::2",
  856. want: []string{"is_ipv6"},
  857. },
  858. {
  859. name: "admin",
  860. src: "100.199.1.2",
  861. dst: "100.200.3.4",
  862. want: []string{"is_ipv4", "some_super_admin"},
  863. },
  864. {
  865. name: "not_admin_bad_src",
  866. src: "100.198.1.2", // 198, not 199
  867. dst: "100.200.3.4",
  868. want: []string{"is_ipv4"},
  869. },
  870. {
  871. name: "not_admin_bad_dst",
  872. src: "100.199.1.2",
  873. dst: "100.201.3.4", // 201, not 200
  874. want: []string{"is_ipv4"},
  875. },
  876. }
  877. for _, tt := range tests {
  878. t.Run(tt.name, func(t *testing.T) {
  879. got := filt.AppendCaps(nil, netip.MustParseAddr(tt.src), netip.MustParseAddr(tt.dst))
  880. if !reflect.DeepEqual(got, tt.want) {
  881. t.Errorf("got %q; want %q", got, tt.want)
  882. }
  883. })
  884. }
  885. }