filter_test.go 25 KB

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