netstack_test.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package netstack
  4. import (
  5. "context"
  6. "fmt"
  7. "maps"
  8. "net"
  9. "net/netip"
  10. "runtime"
  11. "testing"
  12. "time"
  13. "gvisor.dev/gvisor/pkg/buffer"
  14. "gvisor.dev/gvisor/pkg/tcpip"
  15. "gvisor.dev/gvisor/pkg/tcpip/header"
  16. "gvisor.dev/gvisor/pkg/tcpip/stack"
  17. "tailscale.com/envknob"
  18. "tailscale.com/ipn"
  19. "tailscale.com/ipn/ipnlocal"
  20. "tailscale.com/ipn/store/mem"
  21. "tailscale.com/metrics"
  22. "tailscale.com/net/packet"
  23. "tailscale.com/net/tsaddr"
  24. "tailscale.com/net/tsdial"
  25. "tailscale.com/net/tstun"
  26. "tailscale.com/tsd"
  27. "tailscale.com/tstest"
  28. "tailscale.com/types/ipproto"
  29. "tailscale.com/types/logid"
  30. "tailscale.com/wgengine"
  31. "tailscale.com/wgengine/filter"
  32. )
  33. // TestInjectInboundLeak tests that injectInbound doesn't leak memory.
  34. // See https://github.com/tailscale/tailscale/issues/3762
  35. func TestInjectInboundLeak(t *testing.T) {
  36. tunDev := tstun.NewFake()
  37. dialer := new(tsdial.Dialer)
  38. logf := func(format string, args ...any) {
  39. if !t.Failed() {
  40. t.Logf(format, args...)
  41. }
  42. }
  43. sys := new(tsd.System)
  44. eng, err := wgengine.NewUserspaceEngine(logf, wgengine.Config{
  45. Tun: tunDev,
  46. Dialer: dialer,
  47. SetSubsystem: sys.Set,
  48. HealthTracker: sys.HealthTracker(),
  49. })
  50. if err != nil {
  51. t.Fatal(err)
  52. }
  53. defer eng.Close()
  54. sys.Set(eng)
  55. sys.Set(new(mem.Store))
  56. tunWrap := sys.Tun.Get()
  57. lb, err := ipnlocal.NewLocalBackend(logf, logid.PublicID{}, sys, 0)
  58. if err != nil {
  59. t.Fatal(err)
  60. }
  61. ns, err := Create(logf, tunWrap, eng, sys.MagicSock.Get(), dialer, sys.DNSManager.Get(), sys.ProxyMapper(), nil)
  62. if err != nil {
  63. t.Fatal(err)
  64. }
  65. defer ns.Close()
  66. ns.ProcessLocalIPs = true
  67. if err := ns.Start(lb); err != nil {
  68. t.Fatalf("Start: %v", err)
  69. }
  70. ns.atomicIsLocalIPFunc.Store(func(netip.Addr) bool { return true })
  71. pkt := &packet.Parsed{}
  72. const N = 10_000
  73. ms0 := getMemStats()
  74. for range N {
  75. outcome := ns.injectInbound(pkt, tunWrap)
  76. if outcome != filter.DropSilently {
  77. t.Fatalf("got outcome %v; want DropSilently", outcome)
  78. }
  79. }
  80. ms1 := getMemStats()
  81. if grew := int64(ms1.HeapObjects) - int64(ms0.HeapObjects); grew >= N {
  82. t.Fatalf("grew by %v (which is too much and >= the %v packets we sent)", grew, N)
  83. }
  84. }
  85. func getMemStats() (ms runtime.MemStats) {
  86. runtime.GC()
  87. runtime.ReadMemStats(&ms)
  88. return
  89. }
  90. func makeNetstack(tb testing.TB, config func(*Impl)) *Impl {
  91. tunDev := tstun.NewFake()
  92. sys := &tsd.System{}
  93. sys.Set(new(mem.Store))
  94. dialer := new(tsdial.Dialer)
  95. logf := tstest.WhileTestRunningLogger(tb)
  96. eng, err := wgengine.NewUserspaceEngine(logf, wgengine.Config{
  97. Tun: tunDev,
  98. Dialer: dialer,
  99. SetSubsystem: sys.Set,
  100. HealthTracker: sys.HealthTracker(),
  101. })
  102. if err != nil {
  103. tb.Fatal(err)
  104. }
  105. tb.Cleanup(func() { eng.Close() })
  106. sys.Set(eng)
  107. ns, err := Create(logf, sys.Tun.Get(), eng, sys.MagicSock.Get(), dialer, sys.DNSManager.Get(), sys.ProxyMapper(), nil)
  108. if err != nil {
  109. tb.Fatal(err)
  110. }
  111. tb.Cleanup(func() { ns.Close() })
  112. lb, err := ipnlocal.NewLocalBackend(logf, logid.PublicID{}, sys, 0)
  113. if err != nil {
  114. tb.Fatalf("NewLocalBackend: %v", err)
  115. }
  116. ns.atomicIsLocalIPFunc.Store(func(netip.Addr) bool { return true })
  117. if config != nil {
  118. config(ns)
  119. }
  120. if err := ns.Start(lb); err != nil {
  121. tb.Fatalf("Start: %v", err)
  122. }
  123. return ns
  124. }
  125. func TestShouldHandlePing(t *testing.T) {
  126. srcIP := netip.AddrFrom4([4]byte{1, 2, 3, 4})
  127. t.Run("ICMP4", func(t *testing.T) {
  128. dst := netip.MustParseAddr("5.6.7.8")
  129. icmph := packet.ICMP4Header{
  130. IP4Header: packet.IP4Header{
  131. IPProto: ipproto.ICMPv4,
  132. Src: srcIP,
  133. Dst: dst,
  134. },
  135. Type: packet.ICMP4EchoRequest,
  136. Code: packet.ICMP4NoCode,
  137. }
  138. _, payload := packet.ICMPEchoPayload(nil)
  139. icmpPing := packet.Generate(icmph, payload)
  140. pkt := &packet.Parsed{}
  141. pkt.Decode(icmpPing)
  142. impl := makeNetstack(t, func(impl *Impl) {
  143. impl.ProcessSubnets = true
  144. })
  145. pingDst, ok := impl.shouldHandlePing(pkt)
  146. if !ok {
  147. t.Errorf("expected shouldHandlePing==true")
  148. }
  149. if pingDst != dst {
  150. t.Errorf("got dst %s; want %s", pingDst, dst)
  151. }
  152. })
  153. t.Run("ICMP6-no-via", func(t *testing.T) {
  154. dst := netip.MustParseAddr("2a09:8280:1::4169")
  155. icmph := packet.ICMP6Header{
  156. IP6Header: packet.IP6Header{
  157. IPProto: ipproto.ICMPv6,
  158. Src: srcIP,
  159. Dst: dst,
  160. },
  161. Type: packet.ICMP6EchoRequest,
  162. Code: packet.ICMP6NoCode,
  163. }
  164. _, payload := packet.ICMPEchoPayload(nil)
  165. icmpPing := packet.Generate(icmph, payload)
  166. pkt := &packet.Parsed{}
  167. pkt.Decode(icmpPing)
  168. impl := makeNetstack(t, func(impl *Impl) {
  169. impl.ProcessSubnets = true
  170. })
  171. pingDst, ok := impl.shouldHandlePing(pkt)
  172. // Expect that we handle this since it's going out onto the
  173. // network.
  174. if !ok {
  175. t.Errorf("expected shouldHandlePing==true")
  176. }
  177. if pingDst != dst {
  178. t.Errorf("got dst %s; want %s", pingDst, dst)
  179. }
  180. })
  181. t.Run("ICMP6-tailscale-addr", func(t *testing.T) {
  182. dst := netip.MustParseAddr("fd7a:115c:a1e0:ab12::1")
  183. icmph := packet.ICMP6Header{
  184. IP6Header: packet.IP6Header{
  185. IPProto: ipproto.ICMPv6,
  186. Src: srcIP,
  187. Dst: dst,
  188. },
  189. Type: packet.ICMP6EchoRequest,
  190. Code: packet.ICMP6NoCode,
  191. }
  192. _, payload := packet.ICMPEchoPayload(nil)
  193. icmpPing := packet.Generate(icmph, payload)
  194. pkt := &packet.Parsed{}
  195. pkt.Decode(icmpPing)
  196. impl := makeNetstack(t, func(impl *Impl) {
  197. impl.ProcessSubnets = true
  198. })
  199. _, ok := impl.shouldHandlePing(pkt)
  200. // We don't handle this because it's a Tailscale IP and not 4via6
  201. if ok {
  202. t.Errorf("expected shouldHandlePing==false")
  203. }
  204. })
  205. // Handle pings for 4via6 addresses regardless of ProcessSubnets
  206. for _, subnets := range []bool{true, false} {
  207. t.Run("ICMP6-4via6-ProcessSubnets-"+fmt.Sprint(subnets), func(t *testing.T) {
  208. // The 4via6 route 10.1.1.0/24 siteid 7, and then the IP
  209. // 10.1.1.9 within that route.
  210. dst := netip.MustParseAddr("fd7a:115c:a1e0:b1a:0:7:a01:109")
  211. expectedPingDst := netip.MustParseAddr("10.1.1.9")
  212. icmph := packet.ICMP6Header{
  213. IP6Header: packet.IP6Header{
  214. IPProto: ipproto.ICMPv6,
  215. Src: srcIP,
  216. Dst: dst,
  217. },
  218. Type: packet.ICMP6EchoRequest,
  219. Code: packet.ICMP6NoCode,
  220. }
  221. _, payload := packet.ICMPEchoPayload(nil)
  222. icmpPing := packet.Generate(icmph, payload)
  223. pkt := &packet.Parsed{}
  224. pkt.Decode(icmpPing)
  225. impl := makeNetstack(t, func(impl *Impl) {
  226. impl.ProcessSubnets = subnets
  227. })
  228. pingDst, ok := impl.shouldHandlePing(pkt)
  229. // Handled due to being 4via6
  230. if !ok {
  231. t.Errorf("expected shouldHandlePing==true")
  232. } else if pingDst != expectedPingDst {
  233. t.Errorf("got dst %s; want %s", pingDst, expectedPingDst)
  234. }
  235. })
  236. }
  237. }
  238. // looksLikeATailscaleSelfAddress reports whether addr looks like
  239. // a Tailscale self address, for tests.
  240. func looksLikeATailscaleSelfAddress(addr netip.Addr) bool {
  241. return addr.Is4() && tsaddr.IsTailscaleIP(addr) ||
  242. addr.Is6() && tsaddr.Tailscale4To6Range().Contains(addr)
  243. }
  244. func TestShouldProcessInbound(t *testing.T) {
  245. testCases := []struct {
  246. name string
  247. pkt *packet.Parsed
  248. afterStart func(*Impl) // optional; after Impl.Start is called
  249. beforeStart func(*Impl) // optional; before Impl.Start is called
  250. want bool
  251. runOnGOOS string
  252. }{
  253. {
  254. name: "ipv6-via",
  255. pkt: &packet.Parsed{
  256. IPVersion: 6,
  257. IPProto: ipproto.TCP,
  258. Src: netip.MustParseAddrPort("100.101.102.103:1234"),
  259. // $ tailscale debug via 7 10.1.1.9/24
  260. // fd7a:115c:a1e0:b1a:0:7:a01:109/120
  261. Dst: netip.MustParseAddrPort("[fd7a:115c:a1e0:b1a:0:7:a01:109]:5678"),
  262. TCPFlags: packet.TCPSyn,
  263. },
  264. afterStart: func(i *Impl) {
  265. prefs := ipn.NewPrefs()
  266. prefs.AdvertiseRoutes = []netip.Prefix{
  267. // $ tailscale debug via 7 10.1.1.0/24
  268. // fd7a:115c:a1e0:b1a:0:7:a01:100/120
  269. netip.MustParsePrefix("fd7a:115c:a1e0:b1a:0:7:a01:100/120"),
  270. }
  271. i.lb.Start(ipn.Options{
  272. UpdatePrefs: prefs,
  273. })
  274. i.atomicIsLocalIPFunc.Store(looksLikeATailscaleSelfAddress)
  275. },
  276. beforeStart: func(i *Impl) {
  277. // This should be handled even if we're
  278. // otherwise not processing local IPs or
  279. // subnets.
  280. i.ProcessLocalIPs = false
  281. i.ProcessSubnets = false
  282. },
  283. want: true,
  284. },
  285. {
  286. name: "ipv6-via-not-advertised",
  287. pkt: &packet.Parsed{
  288. IPVersion: 6,
  289. IPProto: ipproto.TCP,
  290. Src: netip.MustParseAddrPort("100.101.102.103:1234"),
  291. // $ tailscale debug via 7 10.1.1.9/24
  292. // fd7a:115c:a1e0:b1a:0:7:a01:109/120
  293. Dst: netip.MustParseAddrPort("[fd7a:115c:a1e0:b1a:0:7:a01:109]:5678"),
  294. TCPFlags: packet.TCPSyn,
  295. },
  296. afterStart: func(i *Impl) {
  297. prefs := ipn.NewPrefs()
  298. prefs.AdvertiseRoutes = []netip.Prefix{
  299. // tailscale debug via 7 10.1.2.0/24
  300. // fd7a:115c:a1e0:b1a:0:7:a01:200/120
  301. netip.MustParsePrefix("fd7a:115c:a1e0:b1a:0:7:a01:200/120"),
  302. }
  303. i.lb.Start(ipn.Options{
  304. UpdatePrefs: prefs,
  305. })
  306. },
  307. want: false,
  308. },
  309. {
  310. name: "tailscale-ssh-enabled",
  311. pkt: &packet.Parsed{
  312. IPVersion: 4,
  313. IPProto: ipproto.TCP,
  314. Src: netip.MustParseAddrPort("100.101.102.103:1234"),
  315. Dst: netip.MustParseAddrPort("100.101.102.104:22"),
  316. TCPFlags: packet.TCPSyn,
  317. },
  318. afterStart: func(i *Impl) {
  319. prefs := ipn.NewPrefs()
  320. prefs.RunSSH = true
  321. i.lb.Start(ipn.Options{
  322. UpdatePrefs: prefs,
  323. })
  324. i.atomicIsLocalIPFunc.Store(func(addr netip.Addr) bool {
  325. return addr.String() == "100.101.102.104" // Dst, above
  326. })
  327. },
  328. want: true,
  329. runOnGOOS: "linux",
  330. },
  331. {
  332. name: "tailscale-ssh-disabled",
  333. pkt: &packet.Parsed{
  334. IPVersion: 4,
  335. IPProto: ipproto.TCP,
  336. Src: netip.MustParseAddrPort("100.101.102.103:1234"),
  337. Dst: netip.MustParseAddrPort("100.101.102.104:22"),
  338. TCPFlags: packet.TCPSyn,
  339. },
  340. afterStart: func(i *Impl) {
  341. prefs := ipn.NewPrefs()
  342. prefs.RunSSH = false // default, but to be explicit
  343. i.lb.Start(ipn.Options{
  344. UpdatePrefs: prefs,
  345. })
  346. i.atomicIsLocalIPFunc.Store(func(addr netip.Addr) bool {
  347. return addr.String() == "100.101.102.104" // Dst, above
  348. })
  349. },
  350. want: false,
  351. },
  352. {
  353. name: "process-local-ips",
  354. pkt: &packet.Parsed{
  355. IPVersion: 4,
  356. IPProto: ipproto.TCP,
  357. Src: netip.MustParseAddrPort("100.101.102.103:1234"),
  358. Dst: netip.MustParseAddrPort("100.101.102.104:4567"),
  359. TCPFlags: packet.TCPSyn,
  360. },
  361. afterStart: func(i *Impl) {
  362. i.ProcessLocalIPs = true
  363. i.atomicIsLocalIPFunc.Store(func(addr netip.Addr) bool {
  364. return addr.String() == "100.101.102.104" // Dst, above
  365. })
  366. },
  367. want: true,
  368. },
  369. {
  370. name: "process-subnets",
  371. pkt: &packet.Parsed{
  372. IPVersion: 4,
  373. IPProto: ipproto.TCP,
  374. Src: netip.MustParseAddrPort("100.101.102.103:1234"),
  375. Dst: netip.MustParseAddrPort("10.1.2.3:4567"),
  376. TCPFlags: packet.TCPSyn,
  377. },
  378. beforeStart: func(i *Impl) {
  379. i.ProcessSubnets = true
  380. },
  381. afterStart: func(i *Impl) {
  382. // For testing purposes, assume all Tailscale
  383. // IPs are local; the Dst above is something
  384. // not in that range.
  385. i.atomicIsLocalIPFunc.Store(looksLikeATailscaleSelfAddress)
  386. },
  387. want: true,
  388. },
  389. {
  390. name: "peerapi-port-subnet-router", // see #6235
  391. pkt: &packet.Parsed{
  392. IPVersion: 4,
  393. IPProto: ipproto.TCP,
  394. Src: netip.MustParseAddrPort("100.101.102.103:1234"),
  395. Dst: netip.MustParseAddrPort("10.0.0.23:5555"),
  396. TCPFlags: packet.TCPSyn,
  397. },
  398. beforeStart: func(i *Impl) {
  399. // As if we were running on Linux where netstack isn't used.
  400. i.ProcessSubnets = false
  401. i.atomicIsLocalIPFunc.Store(func(netip.Addr) bool { return false })
  402. },
  403. afterStart: func(i *Impl) {
  404. prefs := ipn.NewPrefs()
  405. prefs.AdvertiseRoutes = []netip.Prefix{
  406. netip.MustParsePrefix("10.0.0.1/24"),
  407. }
  408. i.lb.Start(ipn.Options{
  409. UpdatePrefs: prefs,
  410. })
  411. // Set the PeerAPI port to the Dst port above.
  412. i.peerapiPort4Atomic.Store(5555)
  413. i.peerapiPort6Atomic.Store(5555)
  414. },
  415. want: false,
  416. },
  417. // TODO(andrew): test PeerAPI
  418. // TODO(andrew): test TCP packets without the SYN flag set
  419. }
  420. for _, tc := range testCases {
  421. t.Run(tc.name, func(t *testing.T) {
  422. if tc.runOnGOOS != "" && runtime.GOOS != tc.runOnGOOS {
  423. t.Skipf("skipping on GOOS=%v", runtime.GOOS)
  424. }
  425. impl := makeNetstack(t, tc.beforeStart)
  426. if tc.afterStart != nil {
  427. tc.afterStart(impl)
  428. }
  429. got := impl.shouldProcessInbound(tc.pkt, nil)
  430. if got != tc.want {
  431. t.Errorf("got shouldProcessInbound()=%v; want %v", got, tc.want)
  432. } else {
  433. t.Logf("OK: shouldProcessInbound() = %v", got)
  434. }
  435. })
  436. }
  437. }
  438. func tcp4syn(tb testing.TB, src, dst netip.Addr, sport, dport uint16) []byte {
  439. ip := header.IPv4(make([]byte, header.IPv4MinimumSize+header.TCPMinimumSize))
  440. ip.Encode(&header.IPv4Fields{
  441. Protocol: uint8(header.TCPProtocolNumber),
  442. TotalLength: header.IPv4MinimumSize + header.TCPMinimumSize,
  443. TTL: 64,
  444. SrcAddr: tcpip.AddrFrom4Slice(src.AsSlice()),
  445. DstAddr: tcpip.AddrFrom4Slice(dst.AsSlice()),
  446. })
  447. ip.SetChecksum(^ip.CalculateChecksum())
  448. if !ip.IsChecksumValid() {
  449. tb.Fatal("test broken; packet has incorrect IP checksum")
  450. }
  451. tcp := header.TCP(ip[header.IPv4MinimumSize:])
  452. tcp.Encode(&header.TCPFields{
  453. SrcPort: sport,
  454. DstPort: dport,
  455. SeqNum: 0,
  456. DataOffset: header.TCPMinimumSize,
  457. Flags: header.TCPFlagSyn,
  458. WindowSize: 65535,
  459. Checksum: 0,
  460. })
  461. xsum := header.PseudoHeaderChecksum(
  462. header.TCPProtocolNumber,
  463. tcpip.AddrFrom4Slice(src.AsSlice()),
  464. tcpip.AddrFrom4Slice(dst.AsSlice()),
  465. uint16(header.TCPMinimumSize),
  466. )
  467. tcp.SetChecksum(^tcp.CalculateChecksum(xsum))
  468. if !tcp.IsChecksumValid(tcpip.AddrFrom4Slice(src.AsSlice()), tcpip.AddrFrom4Slice(dst.AsSlice()), 0, 0) {
  469. tb.Fatal("test broken; packet has incorrect TCP checksum")
  470. }
  471. return ip
  472. }
  473. // makeHangDialer returns a dialer that notifies the returned channel when a
  474. // connection is dialed and then hangs until the test finishes.
  475. func makeHangDialer(tb testing.TB) (func(context.Context, string, string) (net.Conn, error), chan struct{}) {
  476. done := make(chan struct{})
  477. tb.Cleanup(func() {
  478. close(done)
  479. })
  480. gotConn := make(chan struct{}, 1)
  481. fn := func(ctx context.Context, network, address string) (net.Conn, error) {
  482. // Signal that we have a new connection
  483. tb.Logf("hangDialer: called with network=%q address=%q", network, address)
  484. select {
  485. case gotConn <- struct{}{}:
  486. default:
  487. }
  488. // Hang until the test is done.
  489. select {
  490. case <-ctx.Done():
  491. tb.Logf("context done")
  492. case <-done:
  493. tb.Logf("function completed")
  494. }
  495. return nil, fmt.Errorf("canceled")
  496. }
  497. return fn, gotConn
  498. }
  499. // TestTCPForwardLimits verifies that the limits on the TCP forwarder work in a
  500. // success case (i.e. when we don't hit the limit).
  501. func TestTCPForwardLimits(t *testing.T) {
  502. envknob.Setenv("TS_DEBUG_NETSTACK", "true")
  503. impl := makeNetstack(t, func(impl *Impl) {
  504. impl.ProcessSubnets = true
  505. })
  506. dialFn, gotConn := makeHangDialer(t)
  507. impl.forwardDialFunc = dialFn
  508. prefs := ipn.NewPrefs()
  509. prefs.AdvertiseRoutes = []netip.Prefix{
  510. // This is the TEST-NET-1 IP block for use in documentation,
  511. // and should never actually be routable.
  512. netip.MustParsePrefix("192.0.2.0/24"),
  513. }
  514. impl.lb.Start(ipn.Options{
  515. UpdatePrefs: prefs,
  516. })
  517. impl.atomicIsLocalIPFunc.Store(looksLikeATailscaleSelfAddress)
  518. // Inject an "outbound" packet that's going to an IP address that times
  519. // out. We need to re-parse from a byte slice so that the internal
  520. // buffer in the packet.Parsed type is filled out.
  521. client := netip.MustParseAddr("100.101.102.103")
  522. destAddr := netip.MustParseAddr("192.0.2.1")
  523. pkt := tcp4syn(t, client, destAddr, 1234, 4567)
  524. var parsed packet.Parsed
  525. parsed.Decode(pkt)
  526. // When injecting this packet, we want the outcome to be "drop
  527. // silently", which indicates that netstack is processing the
  528. // packet and not delivering it to the host system.
  529. if resp := impl.injectInbound(&parsed, impl.tundev); resp != filter.DropSilently {
  530. t.Errorf("got filter outcome %v, want filter.DropSilently", resp)
  531. }
  532. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  533. defer cancel()
  534. // Wait until we have an in-flight outgoing connection.
  535. select {
  536. case <-ctx.Done():
  537. t.Fatalf("timed out waiting for connection")
  538. case <-gotConn:
  539. t.Logf("got connection in progress")
  540. }
  541. // Inject another packet, which will be deduplicated and thus not
  542. // increment our counter.
  543. parsed.Decode(pkt)
  544. if resp := impl.injectInbound(&parsed, impl.tundev); resp != filter.DropSilently {
  545. t.Errorf("got filter outcome %v, want filter.DropSilently", resp)
  546. }
  547. // Verify that we now have a single in-flight address in our map.
  548. impl.mu.Lock()
  549. inFlight := maps.Clone(impl.connsInFlightByClient)
  550. impl.mu.Unlock()
  551. if got, ok := inFlight[client]; !ok || got != 1 {
  552. t.Errorf("expected 1 in-flight connection for %v, got: %v", client, inFlight)
  553. }
  554. // Get the expvar statistics and verify that we're exporting the
  555. // correct metric.
  556. metrics := impl.ExpVar().(*metrics.Set)
  557. const metricName = "gauge_tcp_forward_in_flight"
  558. if v := metrics.Get(metricName).String(); v != "1" {
  559. t.Errorf("got metric %q=%s, want 1", metricName, v)
  560. }
  561. }
  562. // TestTCPForwardLimits_PerClient verifies that the per-client limit for TCP
  563. // forwarding works.
  564. func TestTCPForwardLimits_PerClient(t *testing.T) {
  565. envknob.Setenv("TS_DEBUG_NETSTACK", "true")
  566. // Set our test override limits during this test.
  567. tstest.Replace(t, &maxInFlightConnectionAttemptsForTest, 2)
  568. tstest.Replace(t, &maxInFlightConnectionAttemptsPerClientForTest, 1)
  569. impl := makeNetstack(t, func(impl *Impl) {
  570. impl.ProcessSubnets = true
  571. })
  572. dialFn, gotConn := makeHangDialer(t)
  573. impl.forwardDialFunc = dialFn
  574. prefs := ipn.NewPrefs()
  575. prefs.AdvertiseRoutes = []netip.Prefix{
  576. // This is the TEST-NET-1 IP block for use in documentation,
  577. // and should never actually be routable.
  578. netip.MustParsePrefix("192.0.2.0/24"),
  579. }
  580. impl.lb.Start(ipn.Options{
  581. UpdatePrefs: prefs,
  582. })
  583. impl.atomicIsLocalIPFunc.Store(looksLikeATailscaleSelfAddress)
  584. // Inject an "outbound" packet that's going to an IP address that times
  585. // out. We need to re-parse from a byte slice so that the internal
  586. // buffer in the packet.Parsed type is filled out.
  587. client := netip.MustParseAddr("100.101.102.103")
  588. destAddr := netip.MustParseAddr("192.0.2.1")
  589. // Helpers
  590. var port uint16 = 1234
  591. mustInjectPacket := func() {
  592. pkt := tcp4syn(t, client, destAddr, port, 4567)
  593. port++ // to avoid deduplication based on endpoint
  594. var parsed packet.Parsed
  595. parsed.Decode(pkt)
  596. // When injecting this packet, we want the outcome to be "drop
  597. // silently", which indicates that netstack is processing the
  598. // packet and not delivering it to the host system.
  599. if resp := impl.injectInbound(&parsed, impl.tundev); resp != filter.DropSilently {
  600. t.Fatalf("got filter outcome %v, want filter.DropSilently", resp)
  601. }
  602. }
  603. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  604. defer cancel()
  605. waitPacket := func() {
  606. select {
  607. case <-ctx.Done():
  608. t.Fatalf("timed out waiting for connection")
  609. case <-gotConn:
  610. t.Logf("got connection in progress")
  611. }
  612. }
  613. // Inject the packet to start the TCP forward and wait until we have an
  614. // in-flight outgoing connection.
  615. mustInjectPacket()
  616. waitPacket()
  617. // Verify that we now have a single in-flight address in our map.
  618. impl.mu.Lock()
  619. inFlight := maps.Clone(impl.connsInFlightByClient)
  620. impl.mu.Unlock()
  621. if got, ok := inFlight[client]; !ok || got != 1 {
  622. t.Errorf("expected 1 in-flight connection for %v, got: %v", client, inFlight)
  623. }
  624. metrics := impl.ExpVar().(*metrics.Set)
  625. // One client should have reached the limit at this point.
  626. if v := metrics.Get("gauge_tcp_forward_in_flight_per_client_limit_reached").String(); v != "1" {
  627. t.Errorf("got limit reached expvar metric=%s, want 1", v)
  628. }
  629. // Inject another packet, and verify that we've incremented our
  630. // "dropped" metrics since this will have been dropped.
  631. mustInjectPacket()
  632. // expvar metric
  633. const metricName = "counter_tcp_forward_max_in_flight_per_client_drop"
  634. if v := metrics.Get(metricName).String(); v != "1" {
  635. t.Errorf("got expvar metric %q=%s, want 1", metricName, v)
  636. }
  637. // client metric
  638. if v := metricPerClientForwardLimit.Value(); v != 1 {
  639. t.Errorf("got clientmetric limit metric=%d, want 1", v)
  640. }
  641. }
  642. // TestHandleLocalPackets tests the handleLocalPackets function, ensuring that
  643. // we are properly deciding to handle packets that are destined for "local"
  644. // IPs–addresses that are either for this node, or that it is responsible for.
  645. //
  646. // See, e.g. #11304
  647. func TestHandleLocalPackets(t *testing.T) {
  648. var (
  649. selfIP4 = netip.MustParseAddr("100.64.1.2")
  650. selfIP6 = netip.MustParseAddr("fd7a:115c:a1e0::123")
  651. )
  652. impl := makeNetstack(t, func(impl *Impl) {
  653. impl.ProcessSubnets = false
  654. impl.ProcessLocalIPs = false
  655. impl.atomicIsLocalIPFunc.Store(func(addr netip.Addr) bool {
  656. return addr == selfIP4 || addr == selfIP6
  657. })
  658. })
  659. prefs := ipn.NewPrefs()
  660. prefs.AdvertiseRoutes = []netip.Prefix{
  661. // $ tailscale debug via 7 10.1.1.0/24
  662. // fd7a:115c:a1e0:b1a:0:7:a01:100/120
  663. netip.MustParsePrefix("fd7a:115c:a1e0:b1a:0:7:a01:100/120"),
  664. }
  665. _, err := impl.lb.EditPrefs(&ipn.MaskedPrefs{
  666. Prefs: *prefs,
  667. AdvertiseRoutesSet: true,
  668. })
  669. if err != nil {
  670. t.Fatalf("EditPrefs: %v", err)
  671. }
  672. t.Run("ShouldHandleServiceIP", func(t *testing.T) {
  673. pkt := &packet.Parsed{
  674. IPVersion: 4,
  675. IPProto: ipproto.TCP,
  676. Src: netip.MustParseAddrPort("127.0.0.1:9999"),
  677. Dst: netip.MustParseAddrPort("100.100.100.100:53"),
  678. TCPFlags: packet.TCPSyn,
  679. }
  680. resp := impl.handleLocalPackets(pkt, impl.tundev)
  681. if resp != filter.DropSilently {
  682. t.Errorf("got filter outcome %v, want filter.DropSilently", resp)
  683. }
  684. })
  685. t.Run("ShouldHandle4via6", func(t *testing.T) {
  686. pkt := &packet.Parsed{
  687. IPVersion: 6,
  688. IPProto: ipproto.TCP,
  689. Src: netip.MustParseAddrPort("[::1]:1234"),
  690. // This is an IP in the above 4via6 subnet that this node handles.
  691. // $ tailscale debug via 7 10.1.1.9/24
  692. // fd7a:115c:a1e0:b1a:0:7:a01:109/120
  693. Dst: netip.MustParseAddrPort("[fd7a:115c:a1e0:b1a:0:7:a01:109]:5678"),
  694. TCPFlags: packet.TCPSyn,
  695. }
  696. resp := impl.handleLocalPackets(pkt, impl.tundev)
  697. // DropSilently is the outcome we expected, since we actually
  698. // handled this packet by injecting it into netstack, which
  699. // will handle creating the TCP forwarder. We drop it so we
  700. // don't process the packet outside of netstack.
  701. if resp != filter.DropSilently {
  702. t.Errorf("got filter outcome %v, want filter.DropSilently", resp)
  703. }
  704. })
  705. t.Run("OtherNonHandled", func(t *testing.T) {
  706. pkt := &packet.Parsed{
  707. IPVersion: 6,
  708. IPProto: ipproto.TCP,
  709. Src: netip.MustParseAddrPort("[::1]:1234"),
  710. // This IP is *not* in the above 4via6 route
  711. // $ tailscale debug via 99 10.1.1.9/24
  712. // fd7a:115c:a1e0:b1a:0:63:a01:109/120
  713. Dst: netip.MustParseAddrPort("[fd7a:115c:a1e0:b1a:0:63:a01:109]:5678"),
  714. TCPFlags: packet.TCPSyn,
  715. }
  716. resp := impl.handleLocalPackets(pkt, impl.tundev)
  717. // Accept means that handleLocalPackets does not handle this
  718. // packet, we "accept" it to continue further processing,
  719. // instead of dropping because it was already handled.
  720. if resp != filter.Accept {
  721. t.Errorf("got filter outcome %v, want filter.Accept", resp)
  722. }
  723. })
  724. }
  725. func TestShouldSendToHost(t *testing.T) {
  726. var (
  727. selfIP4 = netip.MustParseAddr("100.64.1.2")
  728. selfIP6 = netip.MustParseAddr("fd7a:115c:a1e0::123")
  729. )
  730. makeTestNetstack := func(tb testing.TB) *Impl {
  731. impl := makeNetstack(tb, func(impl *Impl) {
  732. impl.ProcessSubnets = false
  733. impl.ProcessLocalIPs = false
  734. impl.atomicIsLocalIPFunc.Store(func(addr netip.Addr) bool {
  735. return addr == selfIP4 || addr == selfIP6
  736. })
  737. })
  738. prefs := ipn.NewPrefs()
  739. prefs.AdvertiseRoutes = []netip.Prefix{
  740. // $ tailscale debug via 7 10.1.1.0/24
  741. // fd7a:115c:a1e0:b1a:0:7:a01:100/120
  742. netip.MustParsePrefix("fd7a:115c:a1e0:b1a:0:7:a01:100/120"),
  743. }
  744. _, err := impl.lb.EditPrefs(&ipn.MaskedPrefs{
  745. Prefs: *prefs,
  746. AdvertiseRoutesSet: true,
  747. })
  748. if err != nil {
  749. tb.Fatalf("EditPrefs: %v", err)
  750. }
  751. return impl
  752. }
  753. testCases := []struct {
  754. name string
  755. src, dst netip.AddrPort
  756. want bool
  757. }{
  758. // Reply from service IP to localhost should be sent to host,
  759. // not over WireGuard.
  760. {
  761. name: "from_service_ip_to_localhost",
  762. src: netip.AddrPortFrom(serviceIP, 53),
  763. dst: netip.MustParseAddrPort("127.0.0.1:9999"),
  764. want: true,
  765. },
  766. {
  767. name: "from_service_ip_to_localhost_v6",
  768. src: netip.AddrPortFrom(serviceIPv6, 53),
  769. dst: netip.MustParseAddrPort("[::1]:9999"),
  770. want: true,
  771. },
  772. // A reply from the local IP to a remote host isn't sent to the
  773. // host, but rather over WireGuard.
  774. {
  775. name: "local_ip_to_remote",
  776. src: netip.AddrPortFrom(selfIP4, 12345),
  777. dst: netip.MustParseAddrPort("100.64.99.88:7777"),
  778. want: false,
  779. },
  780. {
  781. name: "local_ip_to_remote_v6",
  782. src: netip.AddrPortFrom(selfIP6, 12345),
  783. dst: netip.MustParseAddrPort("[fd7a:115:a1e0::99]:7777"),
  784. want: false,
  785. },
  786. // A reply from a 4via6 address to a remote host isn't sent to
  787. // the local host, but rather over WireGuard. See:
  788. // https://github.com/tailscale/tailscale/issues/12448
  789. {
  790. name: "4via6_to_remote",
  791. // $ tailscale debug via 7 10.1.1.99/24
  792. // fd7a:115c:a1e0:b1a:0:7:a01:163/120
  793. src: netip.MustParseAddrPort("[fd7a:115c:a1e0:b1a:0:7:a01:163]:12345"),
  794. dst: netip.MustParseAddrPort("[fd7a:115:a1e0::99]:7777"),
  795. want: false,
  796. },
  797. // However, a reply from a 4via6 address to the local Tailscale
  798. // IP for this host *is* sent to the local host. See:
  799. // https://github.com/tailscale/tailscale/issues/11304
  800. {
  801. name: "4via6_to_local",
  802. // $ tailscale debug via 7 10.1.1.99/24
  803. // fd7a:115c:a1e0:b1a:0:7:a01:163/120
  804. src: netip.MustParseAddrPort("[fd7a:115c:a1e0:b1a:0:7:a01:163]:12345"),
  805. dst: netip.AddrPortFrom(selfIP6, 7777),
  806. want: true,
  807. },
  808. // Traffic from a 4via6 address that we're not handling to
  809. // either the local Tailscale IP or a remote host is sent
  810. // outbound.
  811. //
  812. // In most cases, we won't see this type of traffic in the
  813. // shouldSendToHost function, but let's confirm.
  814. {
  815. name: "other_4via6_to_local",
  816. // $ tailscale debug via 4444 10.1.1.88/24
  817. // fd7a:115c:a1e0:b1a:0:7:a01:163/120
  818. src: netip.MustParseAddrPort("[fd7a:115c:a1e0:b1a:0:115c:a01:158]:12345"),
  819. dst: netip.AddrPortFrom(selfIP6, 7777),
  820. want: false,
  821. },
  822. {
  823. name: "other_4via6_to_remote",
  824. // $ tailscale debug via 4444 10.1.1.88/24
  825. // fd7a:115c:a1e0:b1a:0:7:a01:163/120
  826. src: netip.MustParseAddrPort("[fd7a:115c:a1e0:b1a:0:115c:a01:158]:12345"),
  827. dst: netip.MustParseAddrPort("[fd7a:115:a1e0::99]:7777"),
  828. want: false,
  829. },
  830. }
  831. for _, tt := range testCases {
  832. t.Run(tt.name, func(t *testing.T) {
  833. var pkt *stack.PacketBuffer
  834. if tt.src.Addr().Is4() {
  835. pkt = makeUDP4PacketBuffer(tt.src, tt.dst)
  836. } else {
  837. pkt = makeUDP6PacketBuffer(tt.src, tt.dst)
  838. }
  839. ns := makeTestNetstack(t)
  840. if got := ns.shouldSendToHost(pkt); got != tt.want {
  841. t.Errorf("shouldSendToHost returned %v, want %v", got, tt.want)
  842. }
  843. })
  844. }
  845. }
  846. func makeUDP4PacketBuffer(src, dst netip.AddrPort) *stack.PacketBuffer {
  847. if !src.Addr().Is4() || !dst.Addr().Is4() {
  848. panic("src and dst must be IPv4")
  849. }
  850. data := []byte("hello world\n")
  851. packetLen := header.IPv4MinimumSize + header.UDPMinimumSize
  852. pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{
  853. ReserveHeaderBytes: packetLen,
  854. Payload: buffer.MakeWithData(data),
  855. })
  856. // Initialize the UDP header.
  857. udp := header.UDP(pkt.TransportHeader().Push(header.UDPMinimumSize))
  858. pkt.TransportProtocolNumber = header.UDPProtocolNumber
  859. length := uint16(pkt.Size())
  860. udp.Encode(&header.UDPFields{
  861. SrcPort: src.Port(),
  862. DstPort: dst.Port(),
  863. Length: length,
  864. })
  865. // Add IP header
  866. ipHdr := header.IPv4(pkt.NetworkHeader().Push(header.IPv4MinimumSize))
  867. pkt.NetworkProtocolNumber = header.IPv4ProtocolNumber
  868. ipHdr.Encode(&header.IPv4Fields{
  869. TotalLength: uint16(packetLen),
  870. Protocol: uint8(header.UDPProtocolNumber),
  871. SrcAddr: tcpip.AddrFrom4(src.Addr().As4()),
  872. DstAddr: tcpip.AddrFrom4(dst.Addr().As4()),
  873. Checksum: 0,
  874. })
  875. return pkt
  876. }
  877. func makeUDP6PacketBuffer(src, dst netip.AddrPort) *stack.PacketBuffer {
  878. if !src.Addr().Is6() || !dst.Addr().Is6() {
  879. panic("src and dst must be IPv6")
  880. }
  881. data := []byte("hello world\n")
  882. packetLen := header.IPv6MinimumSize + header.UDPMinimumSize
  883. pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{
  884. ReserveHeaderBytes: packetLen,
  885. Payload: buffer.MakeWithData(data),
  886. })
  887. srcAddr := tcpip.AddrFrom16(src.Addr().As16())
  888. dstAddr := tcpip.AddrFrom16(dst.Addr().As16())
  889. // Add IP header
  890. ipHdr := header.IPv6(pkt.NetworkHeader().Push(header.IPv6MinimumSize))
  891. pkt.NetworkProtocolNumber = header.IPv6ProtocolNumber
  892. ipHdr.Encode(&header.IPv6Fields{
  893. SrcAddr: srcAddr,
  894. DstAddr: dstAddr,
  895. PayloadLength: uint16(header.UDPMinimumSize + len(data)),
  896. TransportProtocol: header.UDPProtocolNumber,
  897. HopLimit: 64,
  898. })
  899. // Initialize the UDP header.
  900. udp := header.UDP(pkt.TransportHeader().Push(header.UDPMinimumSize))
  901. pkt.TransportProtocolNumber = header.UDPProtocolNumber
  902. length := uint16(pkt.Size())
  903. udp.Encode(&header.UDPFields{
  904. SrcPort: src.Port(),
  905. DstPort: dst.Port(),
  906. Length: length,
  907. })
  908. // Calculate the UDP pseudo-header checksum.
  909. xsum := header.PseudoHeaderChecksum(header.UDPProtocolNumber, srcAddr, dstAddr, uint16(len(udp)))
  910. udp.SetChecksum(^udp.CalculateChecksum(xsum))
  911. return pkt
  912. }