summaryrefslogtreecommitdiffhomepage
path: root/wgengine/netstack/netstack_test.go
blob: 4f920c8e0271f7b09063b7bf6a3dc3402fee48f2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause

package netstack

import (
	"context"
	"fmt"
	"maps"
	"net"
	"net/netip"
	"runtime"
	"testing"
	"time"

	"gvisor.dev/gvisor/pkg/buffer"
	"gvisor.dev/gvisor/pkg/tcpip"
	"gvisor.dev/gvisor/pkg/tcpip/adapters/gonet"
	"gvisor.dev/gvisor/pkg/tcpip/header"
	"gvisor.dev/gvisor/pkg/tcpip/stack"
	"tailscale.com/envknob"
	"tailscale.com/ipn"
	"tailscale.com/ipn/ipnlocal"
	"tailscale.com/ipn/store/mem"
	"tailscale.com/metrics"
	"tailscale.com/net/netx"
	"tailscale.com/net/packet"
	"tailscale.com/net/tsaddr"
	"tailscale.com/net/tsdial"
	"tailscale.com/net/tstun"
	"tailscale.com/tsd"
	"tailscale.com/tstest"
	"tailscale.com/types/ipproto"
	"tailscale.com/types/logid"
	"tailscale.com/types/netmap"
	"tailscale.com/util/clientmetric"
	"tailscale.com/wgengine"
	"tailscale.com/wgengine/filter"
)

// TestInjectInboundLeak tests that injectInbound doesn't leak memory.
// See https://github.com/tailscale/tailscale/issues/3762
func TestInjectInboundLeak(t *testing.T) {
	tunDev := tstun.NewFake()
	dialer := new(tsdial.Dialer)
	logf := func(format string, args ...any) {
		if !t.Failed() {
			t.Logf(format, args...)
		}
	}
	sys := tsd.NewSystem()
	eng, err := wgengine.NewUserspaceEngine(logf, wgengine.Config{
		Tun:           tunDev,
		Dialer:        dialer,
		SetSubsystem:  sys.Set,
		HealthTracker: sys.HealthTracker.Get(),
		Metrics:       sys.UserMetricsRegistry(),
		EventBus:      sys.Bus.Get(),
	})
	if err != nil {
		t.Fatal(err)
	}
	defer eng.Close()
	sys.Set(eng)
	sys.Set(new(mem.Store))

	tunWrap := sys.Tun.Get()
	lb, err := ipnlocal.NewLocalBackend(logf, logid.PublicID{}, sys, 0)
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(lb.Shutdown)

	ns, err := Create(logf, tunWrap, eng, sys.MagicSock.Get(), dialer, sys.DNSManager.Get(), sys.ProxyMapper())
	if err != nil {
		t.Fatal(err)
	}
	defer ns.Close()
	ns.ProcessLocalIPs = true
	if err := ns.Start(lb); err != nil {
		t.Fatalf("Start: %v", err)
	}
	ns.atomicIsLocalIPFunc.Store(func(netip.Addr) bool { return true })

	pkt := &packet.Parsed{}
	const N = 10_000
	ms0 := getMemStats()
	for range N {
		outcome, _ := ns.injectInbound(pkt, tunWrap, nil)
		if outcome != filter.DropSilently {
			t.Fatalf("got outcome %v; want DropSilently", outcome)
		}
	}
	ms1 := getMemStats()
	if grew := int64(ms1.HeapObjects) - int64(ms0.HeapObjects); grew >= N {
		t.Fatalf("grew by %v (which is too much and >= the %v packets we sent)", grew, N)
	}
}

func getMemStats() (ms runtime.MemStats) {
	runtime.GC()
	runtime.ReadMemStats(&ms)
	return
}

func makeNetstack(tb testing.TB, config func(*Impl)) *Impl {
	tunDev := tstun.NewFake()
	sys := tsd.NewSystem()
	sys.Set(new(mem.Store))
	dialer := new(tsdial.Dialer)
	logf := tstest.WhileTestRunningLogger(tb)
	eng, err := wgengine.NewUserspaceEngine(logf, wgengine.Config{
		Tun:           tunDev,
		Dialer:        dialer,
		SetSubsystem:  sys.Set,
		HealthTracker: sys.HealthTracker.Get(),
		Metrics:       sys.UserMetricsRegistry(),
		EventBus:      sys.Bus.Get(),
	})
	if err != nil {
		tb.Fatal(err)
	}
	tb.Cleanup(func() { eng.Close() })
	sys.Set(eng)

	ns, err := Create(logf, sys.Tun.Get(), eng, sys.MagicSock.Get(), dialer, sys.DNSManager.Get(), sys.ProxyMapper())
	if err != nil {
		tb.Fatal(err)
	}
	tb.Cleanup(func() { ns.Close() })
	sys.Set(ns)

	lb, err := ipnlocal.NewLocalBackend(logf, logid.PublicID{}, sys, 0)
	if err != nil {
		tb.Fatalf("NewLocalBackend: %v", err)
	}
	tb.Cleanup(lb.Shutdown)

	ns.atomicIsLocalIPFunc.Store(func(netip.Addr) bool { return true })
	if config != nil {
		config(ns)
	}
	if err := ns.Start(lb); err != nil {
		tb.Fatalf("Start: %v", err)
	}
	return ns
}

func TestShouldHandlePing(t *testing.T) {
	srcIP := netip.AddrFrom4([4]byte{1, 2, 3, 4})

	t.Run("ICMP4", func(t *testing.T) {
		dst := netip.MustParseAddr("5.6.7.8")
		icmph := packet.ICMP4Header{
			IP4Header: packet.IP4Header{
				IPProto: ipproto.ICMPv4,
				Src:     srcIP,
				Dst:     dst,
			},
			Type: packet.ICMP4EchoRequest,
			Code: packet.ICMP4NoCode,
		}
		_, payload := packet.ICMPEchoPayload(nil)
		icmpPing := packet.Generate(icmph, payload)
		pkt := &packet.Parsed{}
		pkt.Decode(icmpPing)

		impl := makeNetstack(t, func(impl *Impl) {
			impl.ProcessSubnets = true
		})
		pingDst, ok := impl.shouldHandlePing(pkt)
		if !ok {
			t.Errorf("expected shouldHandlePing==true")
		}
		if pingDst != dst {
			t.Errorf("got dst %s; want %s", pingDst, dst)
		}
	})

	t.Run("ICMP6-no-via", func(t *testing.T) {
		dst := netip.MustParseAddr("2a09:8280:1::4169")
		icmph := packet.ICMP6Header{
			IP6Header: packet.IP6Header{
				IPProto: ipproto.ICMPv6,
				Src:     srcIP,
				Dst:     dst,
			},
			Type: packet.ICMP6EchoRequest,
			Code: packet.ICMP6NoCode,
		}
		_, payload := packet.ICMPEchoPayload(nil)
		icmpPing := packet.Generate(icmph, payload)
		pkt := &packet.Parsed{}
		pkt.Decode(icmpPing)

		impl := makeNetstack(t, func(impl *Impl) {
			impl.ProcessSubnets = true
		})
		pingDst, ok := impl.shouldHandlePing(pkt)

		// Expect that we handle this since it's going out onto the
		// network.
		if !ok {
			t.Errorf("expected shouldHandlePing==true")
		}
		if pingDst != dst {
			t.Errorf("got dst %s; want %s", pingDst, dst)
		}
	})

	t.Run("ICMP6-tailscale-addr", func(t *testing.T) {
		dst := netip.MustParseAddr("fd7a:115c:a1e0:ab12::1")
		icmph := packet.ICMP6Header{
			IP6Header: packet.IP6Header{
				IPProto: ipproto.ICMPv6,
				Src:     srcIP,
				Dst:     dst,
			},
			Type: packet.ICMP6EchoRequest,
			Code: packet.ICMP6NoCode,
		}
		_, payload := packet.ICMPEchoPayload(nil)
		icmpPing := packet.Generate(icmph, payload)
		pkt := &packet.Parsed{}
		pkt.Decode(icmpPing)

		impl := makeNetstack(t, func(impl *Impl) {
			impl.ProcessSubnets = true
		})
		_, ok := impl.shouldHandlePing(pkt)

		// We don't handle this because it's a Tailscale IP and not 4via6
		if ok {
			t.Errorf("expected shouldHandlePing==false")
		}
	})

	// Handle pings for 4via6 addresses regardless of ProcessSubnets
	for _, subnets := range []bool{true, false} {
		t.Run("ICMP6-4via6-ProcessSubnets-"+fmt.Sprint(subnets), func(t *testing.T) {
			// The 4via6 route 10.1.1.0/24 siteid 7, and then the IP
			// 10.1.1.9 within that route.
			dst := netip.MustParseAddr("fd7a:115c:a1e0:b1a:0:7:a01:109")
			expectedPingDst := netip.MustParseAddr("10.1.1.9")
			icmph := packet.ICMP6Header{
				IP6Header: packet.IP6Header{
					IPProto: ipproto.ICMPv6,
					Src:     srcIP,
					Dst:     dst,
				},
				Type: packet.ICMP6EchoRequest,
				Code: packet.ICMP6NoCode,
			}
			_, payload := packet.ICMPEchoPayload(nil)
			icmpPing := packet.Generate(icmph, payload)
			pkt := &packet.Parsed{}
			pkt.Decode(icmpPing)

			impl := makeNetstack(t, func(impl *Impl) {
				impl.ProcessSubnets = subnets
			})
			pingDst, ok := impl.shouldHandlePing(pkt)

			// Handled due to being 4via6
			if !ok {
				t.Errorf("expected shouldHandlePing==true")
			} else if pingDst != expectedPingDst {
				t.Errorf("got dst %s; want %s", pingDst, expectedPingDst)
			}
		})
	}
}

// looksLikeATailscaleSelfAddress reports whether addr looks like
// a Tailscale self address, for tests.
func looksLikeATailscaleSelfAddress(addr netip.Addr) bool {
	return addr.Is4() && tsaddr.IsTailscaleIP(addr) ||
		addr.Is6() && tsaddr.Tailscale4To6Range().Contains(addr)
}

func TestShouldProcessInbound(t *testing.T) {
	testCases := []struct {
		name        string
		pkt         *packet.Parsed
		afterStart  func(*Impl) // optional; after Impl.Start is called
		beforeStart func(*Impl) // optional; before Impl.Start is called
		want        bool
		runOnGOOS   string
	}{
		{
			name: "ipv6-via",
			pkt: &packet.Parsed{
				IPVersion: 6,
				IPProto:   ipproto.TCP,
				Src:       netip.MustParseAddrPort("100.101.102.103:1234"),

				// $ tailscale debug via 7 10.1.1.9/24
				// fd7a:115c:a1e0:b1a:0:7:a01:109/120
				Dst:      netip.MustParseAddrPort("[fd7a:115c:a1e0:b1a:0:7:a01:109]:5678"),
				TCPFlags: packet.TCPSyn,
			},
			afterStart: func(i *Impl) {
				prefs := ipn.NewPrefs()
				prefs.AdvertiseRoutes = []netip.Prefix{
					// $ tailscale debug via 7 10.1.1.0/24
					// fd7a:115c:a1e0:b1a:0:7:a01:100/120
					netip.MustParsePrefix("fd7a:115c:a1e0:b1a:0:7:a01:100/120"),
				}
				i.lb.Start(ipn.Options{
					UpdatePrefs: prefs,
				})
				i.atomicIsLocalIPFunc.Store(looksLikeATailscaleSelfAddress)
			},
			beforeStart: func(i *Impl) {
				// This should be handled even if we're
				// otherwise not processing local IPs or
				// subnets.
				i.ProcessLocalIPs = false
				i.ProcessSubnets = false
			},
			want: true,
		},
		{
			name: "ipv6-via-not-advertised",
			pkt: &packet.Parsed{
				IPVersion: 6,
				IPProto:   ipproto.TCP,
				Src:       netip.MustParseAddrPort("100.101.102.103:1234"),

				// $ tailscale debug via 7 10.1.1.9/24
				// fd7a:115c:a1e0:b1a:0:7:a01:109/120
				Dst:      netip.MustParseAddrPort("[fd7a:115c:a1e0:b1a:0:7:a01:109]:5678"),
				TCPFlags: packet.TCPSyn,
			},
			afterStart: func(i *Impl) {
				prefs := ipn.NewPrefs()
				prefs.AdvertiseRoutes = []netip.Prefix{
					// tailscale debug via 7 10.1.2.0/24
					// fd7a:115c:a1e0:b1a:0:7:a01:200/120
					netip.MustParsePrefix("fd7a:115c:a1e0:b1a:0:7:a01:200/120"),
				}
				i.lb.Start(ipn.Options{
					UpdatePrefs: prefs,
				})
			},
			want: false,
		},
		{
			name: "tailscale-ssh-enabled",
			pkt: &packet.Parsed{
				IPVersion: 4,
				IPProto:   ipproto.TCP,
				Src:       netip.MustParseAddrPort("100.101.102.103:1234"),
				Dst:       netip.MustParseAddrPort("100.101.102.104:22"),
				TCPFlags:  packet.TCPSyn,
			},
			afterStart: func(i *Impl) {
				prefs := ipn.NewPrefs()
				prefs.RunSSH = true
				i.lb.Start(ipn.Options{
					UpdatePrefs: prefs,
				})
				i.atomicIsLocalIPFunc.Store(func(addr netip.Addr) bool {
					return addr.String() == "100.101.102.104" // Dst, above
				})
			},
			want:      true,
			runOnGOOS: "linux",
		},
		{
			name: "tailscale-ssh-disabled",
			pkt: &packet.Parsed{
				IPVersion: 4,
				IPProto:   ipproto.TCP,
				Src:       netip.MustParseAddrPort("100.101.102.103:1234"),
				Dst:       netip.MustParseAddrPort("100.101.102.104:22"),
				TCPFlags:  packet.TCPSyn,
			},
			afterStart: func(i *Impl) {
				prefs := ipn.NewPrefs()
				prefs.RunSSH = false // default, but to be explicit
				i.lb.Start(ipn.Options{
					UpdatePrefs: prefs,
				})
				i.atomicIsLocalIPFunc.Store(func(addr netip.Addr) bool {
					return addr.String() == "100.101.102.104" // Dst, above
				})
			},
			want: false,
		},
		{
			name: "process-local-ips",
			pkt: &packet.Parsed{
				IPVersion: 4,
				IPProto:   ipproto.TCP,
				Src:       netip.MustParseAddrPort("100.101.102.103:1234"),
				Dst:       netip.MustParseAddrPort("100.101.102.104:4567"),
				TCPFlags:  packet.TCPSyn,
			},
			afterStart: func(i *Impl) {
				i.ProcessLocalIPs = true
				i.atomicIsLocalIPFunc.Store(func(addr netip.Addr) bool {
					return addr.String() == "100.101.102.104" // Dst, above
				})
			},
			want: true,
		},
		{
			name: "process-subnets",
			pkt: &packet.Parsed{
				IPVersion: 4,
				IPProto:   ipproto.TCP,
				Src:       netip.MustParseAddrPort("100.101.102.103:1234"),
				Dst:       netip.MustParseAddrPort("10.1.2.3:4567"),
				TCPFlags:  packet.TCPSyn,
			},
			beforeStart: func(i *Impl) {
				i.ProcessSubnets = true
			},
			afterStart: func(i *Impl) {
				// For testing purposes, assume all Tailscale
				// IPs are local; the Dst above is something
				// not in that range.
				i.atomicIsLocalIPFunc.Store(looksLikeATailscaleSelfAddress)
			},
			want: true,
		},
		{
			name: "peerapi-port-subnet-router", // see #6235
			pkt: &packet.Parsed{
				IPVersion: 4,
				IPProto:   ipproto.TCP,
				Src:       netip.MustParseAddrPort("100.101.102.103:1234"),
				Dst:       netip.MustParseAddrPort("10.0.0.23:5555"),
				TCPFlags:  packet.TCPSyn,
			},
			beforeStart: func(i *Impl) {
				// As if we were running on Linux where netstack isn't used.
				i.ProcessSubnets = false
				i.atomicIsLocalIPFunc.Store(func(netip.Addr) bool { return false })
			},
			afterStart: func(i *Impl) {
				prefs := ipn.NewPrefs()
				prefs.AdvertiseRoutes = []netip.Prefix{
					netip.MustParsePrefix("10.0.0.1/24"),
				}
				i.lb.Start(ipn.Options{
					UpdatePrefs: prefs,
				})

				// Set the PeerAPI port to the Dst port above.
				i.peerapiPort4Atomic.Store(5555)
				i.peerapiPort6Atomic.Store(5555)
			},
			want: false,
		},
		{
			name: "udp-on-service-vip-with-listener-ipv4",
			pkt: &packet.Parsed{
				IPVersion: 4,
				IPProto:   ipproto.UDP,
				Src:       netip.MustParseAddrPort("100.101.102.103:1234"),
				Dst:       netip.MustParseAddrPort("100.100.100.100:8080"),
			},
			beforeStart: func(i *Impl) {
				i.ProcessLocalIPs = false
				i.ProcessSubnets = false
			},
			afterStart: func(i *Impl) {
				IPServiceMap := netmap.IPServiceMappings{
					serviceIP: "svc:test-service",
				}
				i.lb.SetIPServiceMappingsForTest(IPServiceMap)

				i.atomicIsVIPServiceIPFunc.Store(func(addr netip.Addr) bool {
					return addr == serviceIP
				})

				// Register the service VIP address on the NIC so gVisor can route to it
				protocolAddr := tcpip.ProtocolAddress{
					Protocol:          header.IPv4ProtocolNumber,
					AddressWithPrefix: tcpip.AddrFrom4(serviceIP.As4()).WithPrefix(),
				}

				if err := i.ipstack.AddProtocolAddress(nicID, protocolAddr, stack.AddressProperties{}); err != nil {
					t.Fatalf("AddProtocolAddress: %v", err)
				}

				// Create a UDP listener on the service VIP
				pc, err := gonet.DialUDP(i.ipstack, &tcpip.FullAddress{
					NIC:  nicID,
					Addr: tcpip.AddrFrom4(serviceIP.As4()),
					Port: 8080,
				}, nil, header.IPv4ProtocolNumber)
				if err != nil {
					t.Fatalf("DialUDP: %v", err)
				}
				t.Cleanup(func() { pc.Close() })

				i.atomicIsLocalIPFunc.Store(looksLikeATailscaleSelfAddress)
			},
			want: true,
		},
		{
			name: "udp-on-service-vip-no-listener-ipv4",
			pkt: &packet.Parsed{
				IPVersion: 4,
				IPProto:   ipproto.UDP,
				Src:       netip.MustParseAddrPort("100.101.102.103:1234"),
				Dst:       netip.MustParseAddrPort("100.100.100.100:9999"),
			},
			beforeStart: func(i *Impl) {
				i.ProcessLocalIPs = false
				i.ProcessSubnets = false
			},
			afterStart: func(i *Impl) {
				IPServiceMap := netmap.IPServiceMappings{
					serviceIP: "svc:test-service",
				}
				i.lb.SetIPServiceMappingsForTest(IPServiceMap)

				i.atomicIsVIPServiceIPFunc.Store(func(addr netip.Addr) bool {
					return addr == serviceIP
				})

				i.atomicIsLocalIPFunc.Store(looksLikeATailscaleSelfAddress)
			},
			want: false,
		},
		{
			name: "udp-on-service-vip-with-listener-ipv6",
			pkt: &packet.Parsed{
				IPVersion: 6,
				IPProto:   ipproto.UDP,
				Src:       netip.MustParseAddrPort("[fd7a:115c:a1e0::1]:1234"),
				Dst:       netip.MustParseAddrPort("[fd7a:115c:a1e0::53]:8080"),
			},
			beforeStart: func(i *Impl) {
				i.ProcessLocalIPs = false
				i.ProcessSubnets = false
			},
			afterStart: func(i *Impl) {
				IPServiceMap := netmap.IPServiceMappings{
					serviceIPv6: "svc:test-service",
				}
				i.lb.SetIPServiceMappingsForTest(IPServiceMap)

				i.atomicIsVIPServiceIPFunc.Store(func(addr netip.Addr) bool {
					return addr == serviceIPv6
				})

				protocolAddr := tcpip.ProtocolAddress{
					Protocol:          header.IPv6ProtocolNumber,
					AddressWithPrefix: tcpip.AddrFrom16(serviceIPv6.As16()).WithPrefix(),
				}
				if err := i.ipstack.AddProtocolAddress(nicID, protocolAddr, stack.AddressProperties{}); err != nil {
					t.Fatalf("AddProtocolAddress: %v", err)
				}

				pc, err := gonet.DialUDP(i.ipstack, &tcpip.FullAddress{
					NIC:  nicID,
					Addr: tcpip.AddrFrom16(serviceIPv6.As16()),
					Port: 8080,
				}, nil, header.IPv6ProtocolNumber)
				if err != nil {
					t.Fatalf("DialUDP: %v", err)
				}
				t.Cleanup(func() { pc.Close() })

				i.atomicIsLocalIPFunc.Store(looksLikeATailscaleSelfAddress)
			},
			want: true,
		},
		{
			name: "udp-on-service-vip-no-listener-ipv6",
			pkt: &packet.Parsed{
				IPVersion: 6,
				IPProto:   ipproto.UDP,
				Src:       netip.MustParseAddrPort("[fd7a:115c:a1e0::1]:1234"),
				Dst:       netip.AddrPortFrom(serviceIPv6, 9999),
			},
			beforeStart: func(i *Impl) {
				i.ProcessLocalIPs = false
				i.ProcessSubnets = false
			},
			afterStart: func(i *Impl) {
				IPServiceMap := netmap.IPServiceMappings{
					serviceIPv6: "svc:test-service",
				}
				i.lb.SetIPServiceMappingsForTest(IPServiceMap)

				i.atomicIsVIPServiceIPFunc.Store(func(addr netip.Addr) bool {
					return addr == serviceIPv6
				})

				i.atomicIsLocalIPFunc.Store(looksLikeATailscaleSelfAddress)
			},
			want: false,
		},
		{
			name: "tcp-on-service-vip-with-udp-listener",
			pkt: &packet.Parsed{
				IPVersion: 4,
				IPProto:   ipproto.TCP,
				Src:       netip.MustParseAddrPort("100.101.102.103:1234"),
				Dst:       netip.MustParseAddrPort("100.100.100.100:8080"), // serviceIP
				TCPFlags:  packet.TCPSyn,
			},
			beforeStart: func(i *Impl) {
				i.ProcessLocalIPs = false
				i.ProcessSubnets = false
			},
			afterStart: func(i *Impl) {
				IPServiceMap := netmap.IPServiceMappings{
					serviceIP: "svc:test-service",
				}
				i.lb.SetIPServiceMappingsForTest(IPServiceMap)

				i.atomicIsVIPServiceIPFunc.Store(func(addr netip.Addr) bool {
					return addr == serviceIP
				})

				protocolAddr := tcpip.ProtocolAddress{
					Protocol:          header.IPv4ProtocolNumber,
					AddressWithPrefix: tcpip.AddrFrom4(serviceIP.As4()).WithPrefix(),
				}
				if err := i.ipstack.AddProtocolAddress(nicID, protocolAddr, stack.AddressProperties{}); err != nil {
					t.Fatalf("AddProtocolAddress: %v", err)
				}

				pc, err := gonet.DialUDP(i.ipstack, &tcpip.FullAddress{
					NIC:  nicID,
					Addr: tcpip.AddrFrom4(serviceIP.As4()),
					Port: 8080,
				}, nil, header.IPv4ProtocolNumber)
				if err != nil {
					t.Fatalf("DialUDP: %v", err)
				}
				t.Cleanup(func() { pc.Close() })

				i.atomicIsLocalIPFunc.Store(looksLikeATailscaleSelfAddress)
			},
			want: false,
		},

		// TODO(andrew): test PeerAPI
		// TODO(andrew): test TCP packets without the SYN flag set
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			if tc.runOnGOOS != "" && runtime.GOOS != tc.runOnGOOS {
				t.Skipf("skipping on GOOS=%v", runtime.GOOS)
			}
			impl := makeNetstack(t, tc.beforeStart)
			if tc.afterStart != nil {
				tc.afterStart(impl)
			}

			got := impl.shouldProcessInbound(tc.pkt, nil)
			if got != tc.want {
				t.Errorf("got shouldProcessInbound()=%v; want %v", got, tc.want)
			} else {
				t.Logf("OK: shouldProcessInbound() = %v", got)
			}
		})
	}
}

func tcp4syn(tb testing.TB, src, dst netip.Addr, sport, dport uint16) []byte {
	ip := header.IPv4(make([]byte, header.IPv4MinimumSize+header.TCPMinimumSize))
	ip.Encode(&header.IPv4Fields{
		Protocol:    uint8(header.TCPProtocolNumber),
		TotalLength: header.IPv4MinimumSize + header.TCPMinimumSize,
		TTL:         64,
		SrcAddr:     tcpip.AddrFrom4Slice(src.AsSlice()),
		DstAddr:     tcpip.AddrFrom4Slice(dst.AsSlice()),
	})
	ip.SetChecksum(^ip.CalculateChecksum())
	if !ip.IsChecksumValid() {
		tb.Fatal("test broken; packet has incorrect IP checksum")
	}

	tcp := header.TCP(ip[header.IPv4MinimumSize:])
	tcp.Encode(&header.TCPFields{
		SrcPort:    sport,
		DstPort:    dport,
		SeqNum:     0,
		DataOffset: header.TCPMinimumSize,
		Flags:      header.TCPFlagSyn,
		WindowSize: 65535,
		Checksum:   0,
	})
	xsum := header.PseudoHeaderChecksum(
		header.TCPProtocolNumber,
		tcpip.AddrFrom4Slice(src.AsSlice()),
		tcpip.AddrFrom4Slice(dst.AsSlice()),
		uint16(header.TCPMinimumSize),
	)
	tcp.SetChecksum(^tcp.CalculateChecksum(xsum))
	if !tcp.IsChecksumValid(tcpip.AddrFrom4Slice(src.AsSlice()), tcpip.AddrFrom4Slice(dst.AsSlice()), 0, 0) {
		tb.Fatal("test broken; packet has incorrect TCP checksum")
	}

	return ip
}

// makeHangDialer returns a dialer that notifies the returned channel when a
// connection is dialed and then hangs until the test finishes.
func makeHangDialer(tb testing.TB) (netx.DialFunc, chan struct{}) {
	done := make(chan struct{})
	tb.Cleanup(func() {
		close(done)
	})

	gotConn := make(chan struct{}, 1)
	fn := func(ctx context.Context, network, address string) (net.Conn, error) {
		// Signal that we have a new connection
		tb.Logf("hangDialer: called with network=%q address=%q", network, address)
		select {
		case gotConn <- struct{}{}:
		default:
		}

		// Hang until the test is done.
		select {
		case <-ctx.Done():
			tb.Logf("context done")
		case <-done:
			tb.Logf("function completed")
		}
		return nil, fmt.Errorf("canceled")
	}
	return fn, gotConn
}

// TestTCPForwardLimits verifies that the limits on the TCP forwarder work in a
// success case (i.e. when we don't hit the limit).
func TestTCPForwardLimits(t *testing.T) {
	envknob.Setenv("TS_DEBUG_NETSTACK", "true")
	impl := makeNetstack(t, func(impl *Impl) {
		impl.ProcessSubnets = true
	})

	dialFn, gotConn := makeHangDialer(t)
	impl.forwardDialFunc = dialFn

	prefs := ipn.NewPrefs()
	prefs.AdvertiseRoutes = []netip.Prefix{
		// This is the TEST-NET-1 IP block for use in documentation,
		// and should never actually be routable.
		netip.MustParsePrefix("192.0.2.0/24"),
	}
	impl.lb.Start(ipn.Options{
		UpdatePrefs: prefs,
	})
	impl.atomicIsLocalIPFunc.Store(looksLikeATailscaleSelfAddress)

	// Inject an "outbound" packet that's going to an IP address that times
	// out. We need to re-parse from a byte slice so that the internal
	// buffer in the packet.Parsed type is filled out.
	client := netip.MustParseAddr("100.101.102.103")
	destAddr := netip.MustParseAddr("192.0.2.1")
	pkt := tcp4syn(t, client, destAddr, 1234, 4567)
	var parsed packet.Parsed
	parsed.Decode(pkt)

	// When injecting this packet, we want the outcome to be "drop
	// silently", which indicates that netstack is processing the
	// packet and not delivering it to the host system.
	if resp, _ := impl.injectInbound(&parsed, impl.tundev, nil); resp != filter.DropSilently {
		t.Errorf("got filter outcome %v, want filter.DropSilently", resp)
	}

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	// Wait until we have an in-flight outgoing connection.
	select {
	case <-ctx.Done():
		t.Fatalf("timed out waiting for connection")
	case <-gotConn:
		t.Logf("got connection in progress")
	}

	// Inject another packet, which will be deduplicated and thus not
	// increment our counter.
	parsed.Decode(pkt)
	if resp, _ := impl.injectInbound(&parsed, impl.tundev, nil); resp != filter.DropSilently {
		t.Errorf("got filter outcome %v, want filter.DropSilently", resp)
	}

	// Verify that we now have a single in-flight address in our map.
	impl.mu.Lock()
	inFlight := maps.Clone(impl.connsInFlightByClient)
	impl.mu.Unlock()

	if got, ok := inFlight[client]; !ok || got != 1 {
		t.Errorf("expected 1 in-flight connection for %v, got: %v", client, inFlight)
	}

	// Get the expvar statistics and verify that we're exporting the
	// correct metric.
	metrics := impl.ExpVar().(*metrics.Set)

	const metricName = "gauge_tcp_forward_in_flight"
	if v := metrics.Get(metricName).String(); v != "1" {
		t.Errorf("got metric %q=%s, want 1", metricName, v)
	}
}

// TestTCPForwardLimits_PerClient verifies that the per-client limit for TCP
// forwarding works.
func TestTCPForwardLimits_PerClient(t *testing.T) {
	clientmetric.ResetForTest(t)
	tstest.AssertNotParallel(t) // calls envknob.Setenv
	envknob.Setenv("TS_DEBUG_NETSTACK", "true")

	// Set our test override limits during this test.
	maxInFlightConnectionAttemptsForTest.Store(2)
	t.Cleanup(func() { maxInFlightConnectionAttemptsForTest.Store(0) })
	maxInFlightConnectionAttemptsPerClientForTest.Store(1)
	t.Cleanup(func() { maxInFlightConnectionAttemptsPerClientForTest.Store(0) })

	impl := makeNetstack(t, func(impl *Impl) {
		impl.ProcessSubnets = true
	})

	dialFn, gotConn := makeHangDialer(t)
	impl.forwardDialFunc = dialFn

	prefs := ipn.NewPrefs()
	prefs.AdvertiseRoutes = []netip.Prefix{
		// This is the TEST-NET-1 IP block for use in documentation,
		// and should never actually be routable.
		netip.MustParsePrefix("192.0.2.0/24"),
	}
	impl.lb.Start(ipn.Options{
		UpdatePrefs: prefs,
	})
	impl.atomicIsLocalIPFunc.Store(looksLikeATailscaleSelfAddress)

	// Inject an "outbound" packet that's going to an IP address that times
	// out. We need to re-parse from a byte slice so that the internal
	// buffer in the packet.Parsed type is filled out.
	client := netip.MustParseAddr("100.101.102.103")
	destAddr := netip.MustParseAddr("192.0.2.1")

	// Helpers
	var port uint16 = 1234
	mustInjectPacket := func() {
		pkt := tcp4syn(t, client, destAddr, port, 4567)
		port++ // to avoid deduplication based on endpoint

		var parsed packet.Parsed
		parsed.Decode(pkt)

		// When injecting this packet, we want the outcome to be "drop
		// silently", which indicates that netstack is processing the
		// packet and not delivering it to the host system.
		if resp, _ := impl.injectInbound(&parsed, impl.tundev, nil); resp != filter.DropSilently {
			t.Fatalf("got filter outcome %v, want filter.DropSilently", resp)
		}
	}

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	waitPacket := func() {
		select {
		case <-ctx.Done():
			t.Fatalf("timed out waiting for connection")
		case <-gotConn:
			t.Logf("got connection in progress")
		}
	}

	// Inject the packet to start the TCP forward and wait until we have an
	// in-flight outgoing connection.
	mustInjectPacket()
	waitPacket()

	// Verify that we now have a single in-flight address in our map.
	impl.mu.Lock()
	inFlight := maps.Clone(impl.connsInFlightByClient)
	impl.mu.Unlock()

	if got, ok := inFlight[client]; !ok || got != 1 {
		t.Errorf("expected 1 in-flight connection for %v, got: %v", client, inFlight)
	}

	metrics := impl.ExpVar().(*metrics.Set)

	// One client should have reached the limit at this point.
	if v := metrics.Get("gauge_tcp_forward_in_flight_per_client_limit_reached").String(); v != "1" {
		t.Errorf("got limit reached expvar metric=%s, want 1", v)
	}

	// Inject another packet, and verify that we've incremented our
	// "dropped" metrics since this will have been dropped.
	mustInjectPacket()

	// expvar metric
	const metricName = "counter_tcp_forward_max_in_flight_per_client_drop"
	if v := metrics.Get(metricName).String(); v != "1" {
		t.Errorf("got expvar metric %q=%s, want 1", metricName, v)
	}

	// client metric
	if v := metricPerClientForwardLimit.Value(); v != 1 {
		t.Errorf("got clientmetric limit metric=%d, want 1", v)
	}
}

// TestHandleLocalPackets tests the handleLocalPackets function, ensuring that
// we are properly deciding to handle packets that are destined for "local"
// IPs–addresses that are either for this node, or that it is responsible for.
//
// See, e.g. #11304
func TestHandleLocalPackets(t *testing.T) {
	var (
		selfIP4 = netip.MustParseAddr("100.64.1.2")
		selfIP6 = netip.MustParseAddr("fd7a:115c:a1e0::123")
	)

	impl := makeNetstack(t, func(impl *Impl) {
		impl.ProcessSubnets = false
		impl.ProcessLocalIPs = false
		impl.atomicIsLocalIPFunc.Store(func(addr netip.Addr) bool {
			return addr == selfIP4 || addr == selfIP6
		})
	})

	prefs := ipn.NewPrefs()
	prefs.AdvertiseRoutes = []netip.Prefix{
		// $ tailscale debug via 7 10.1.1.0/24
		// fd7a:115c:a1e0:b1a:0:7:a01:100/120
		netip.MustParsePrefix("fd7a:115c:a1e0:b1a:0:7:a01:100/120"),
	}
	prefs.AdvertiseServices = []string{"svc:test-service"}
	_, err := impl.lb.EditPrefs(&ipn.MaskedPrefs{
		Prefs:                *prefs,
		AdvertiseRoutesSet:   true,
		AdvertiseServicesSet: true,
	})
	if err != nil {
		t.Fatalf("EditPrefs: %v", err)
	}
	IPServiceMap := netmap.IPServiceMappings{
		netip.MustParseAddr("100.99.55.111"):        "svc:test-service",
		netip.MustParseAddr("fd7a:115c:a1e0::abcd"): "svc:test-service",
	}
	impl.lb.SetIPServiceMappingsForTest(IPServiceMap)

	t.Run("ShouldHandleServiceIP", func(t *testing.T) {
		t.Parallel()
		pkt := &packet.Parsed{
			IPVersion: 4,
			IPProto:   ipproto.TCP,
			Src:       netip.MustParseAddrPort("127.0.0.1:9999"),
			Dst:       netip.MustParseAddrPort("100.100.100.100:53"),
			TCPFlags:  packet.TCPSyn,
		}
		resp, _ := impl.handleLocalPackets(pkt, impl.tundev, nil)
		if resp != filter.DropSilently {
			t.Errorf("got filter outcome %v, want filter.DropSilently", resp)
		}
	})
	// Any port on the quad-100 service IP must be absorbed locally by
	// netstack and never leak out to the WireGuard / peer-routing
	// layers. Historically we only intercepted specific ports (UDP 53
	// and TCP 53/80/8080), causing stray traffic to other ports such
	// as 100.100.100.100:853 (DoT) to time out in wireguard-go and
	// produce "open-conn-track: timeout opening ...; no associated
	// peer node" log spam. See the handleLocalPackets comment.
	quad100LeakCases := []struct {
		name  string
		proto ipproto.Proto
		dst   string
	}{
		{"TCP-853-DoT-v4", ipproto.TCP, "100.100.100.100:853"},
		{"TCP-443-DoH-v4", ipproto.TCP, "100.100.100.100:443"},
		{"TCP-9000-stray-v4", ipproto.TCP, "100.100.100.100:9000"},
		{"UDP-853-DoQ-v4", ipproto.UDP, "100.100.100.100:853"},
		{"UDP-443-v4", ipproto.UDP, "100.100.100.100:443"},
		{"TCP-853-DoT-v6", ipproto.TCP, "[fd7a:115c:a1e0::53]:853"},
		{"UDP-443-v6", ipproto.UDP, "[fd7a:115c:a1e0::53]:443"},
	}
	for _, tc := range quad100LeakCases {
		t.Run("ShouldNotLeakQuad100_"+tc.name, func(t *testing.T) {
			t.Parallel()
			dst := netip.MustParseAddrPort(tc.dst)
			ipVersion := uint8(4)
			if dst.Addr().Is6() {
				ipVersion = 6
			}
			src := "127.0.0.1:9999"
			if ipVersion == 6 {
				src = "[::1]:9999"
			}
			pkt := &packet.Parsed{
				IPVersion: ipVersion,
				IPProto:   tc.proto,
				Src:       netip.MustParseAddrPort(src),
				Dst:       dst,
			}
			if tc.proto == ipproto.TCP {
				pkt.TCPFlags = packet.TCPSyn
			}
			resp, _ := impl.handleLocalPackets(pkt, impl.tundev, nil)
			if resp != filter.DropSilently {
				t.Errorf("quad-100 %s packet leaked: got filter outcome %v, want filter.DropSilently", tc.name, resp)
			}
		})
	}
	// Exhaustive sweep of all ports for both transport protocols and
	// both IP versions, confirming no port leaks. The quad-100 branch
	// of handleLocalPackets is port-independent by construction; this
	// test serves as a regression guard against accidental port-based
	// exemptions slipping back in.
	t.Run("ShouldNotLeakQuad100_AllPorts", func(t *testing.T) {
		t.Parallel()
		protos := []ipproto.Proto{ipproto.TCP, ipproto.UDP}
		dsts := []netip.Addr{
			netip.MustParseAddr("100.100.100.100"),
			netip.MustParseAddr("fd7a:115c:a1e0::53"),
		}
		for _, proto := range protos {
			for _, dstAddr := range dsts {
				ipVersion := uint8(4)
				srcStr := "127.0.0.1:9999"
				if dstAddr.Is6() {
					ipVersion = 6
					srcStr = "[::1]:9999"
				}
				src := netip.MustParseAddrPort(srcStr)
				for port := 1; port <= 65535; port++ {
					pkt := &packet.Parsed{
						IPVersion: ipVersion,
						IPProto:   proto,
						Src:       src,
						Dst:       netip.AddrPortFrom(dstAddr, uint16(port)),
					}
					if proto == ipproto.TCP {
						pkt.TCPFlags = packet.TCPSyn
					}
					resp, _ := impl.handleLocalPackets(pkt, impl.tundev, nil)
					if resp != filter.DropSilently {
						t.Fatalf("port=%d proto=%v dst=%v: got %v, want filter.DropSilently", port, proto, dstAddr, resp)
					}
				}
			}
		}
	})
	t.Run("ShouldHandle4via6", func(t *testing.T) {
		t.Parallel()
		pkt := &packet.Parsed{
			IPVersion: 6,
			IPProto:   ipproto.TCP,
			Src:       netip.MustParseAddrPort("[::1]:1234"),

			// This is an IP in the above 4via6 subnet that this node handles.
			//    $ tailscale debug via 7 10.1.1.9/24
			//    fd7a:115c:a1e0:b1a:0:7:a01:109/120
			Dst:      netip.MustParseAddrPort("[fd7a:115c:a1e0:b1a:0:7:a01:109]:5678"),
			TCPFlags: packet.TCPSyn,
		}
		resp, _ := impl.handleLocalPackets(pkt, impl.tundev, nil)

		// DropSilently is the outcome we expected, since we actually
		// handled this packet by injecting it into netstack, which
		// will handle creating the TCP forwarder. We drop it so we
		// don't process the packet outside of netstack.
		if resp != filter.DropSilently {
			t.Errorf("got filter outcome %v, want filter.DropSilently", resp)
		}
	})
	t.Run("ShouldHandleLocalTailscaleServices", func(t *testing.T) {
		t.Parallel()
		pkt := &packet.Parsed{
			IPVersion: 4,
			IPProto:   ipproto.TCP,
			Src:       netip.MustParseAddrPort("127.0.0.1:9999"),
			Dst:       netip.MustParseAddrPort("100.99.55.111:80"),
			TCPFlags:  packet.TCPSyn,
		}
		resp, _ := impl.handleLocalPackets(pkt, impl.tundev, nil)
		if resp != filter.DropSilently {
			t.Errorf("got filter outcome %v, want filter.DropSilently", resp)
		}
	})
	t.Run("OtherNonHandled", func(t *testing.T) {
		t.Parallel()
		pkt := &packet.Parsed{
			IPVersion: 6,
			IPProto:   ipproto.TCP,
			Src:       netip.MustParseAddrPort("[::1]:1234"),

			// This IP is *not* in the above 4via6 route
			//    $ tailscale debug via 99 10.1.1.9/24
			//    fd7a:115c:a1e0:b1a:0:63:a01:109/120
			Dst:      netip.MustParseAddrPort("[fd7a:115c:a1e0:b1a:0:63:a01:109]:5678"),
			TCPFlags: packet.TCPSyn,
		}
		resp, _ := impl.handleLocalPackets(pkt, impl.tundev, nil)

		// Accept means that handleLocalPackets does not handle this
		// packet, we "accept" it to continue further processing,
		// instead of dropping because it was already handled.
		if resp != filter.Accept {
			t.Errorf("got filter outcome %v, want filter.Accept", resp)
		}
	})
}

// TestQuad100UnservedTCPPortDoesNotForward verifies that a TCP SYN to the
// Tailscale service IP (100.100.100.100) on a port we don't serve is
// absorbed by netstack and rejected cleanly, without triggering the
// outbound forwardTCP dialer.
//
// handleLocalPackets now absorbs all quad-100 traffic regardless of
// port to prevent it leaking to WireGuard peers (which produced noisy
// "open-conn-track: timeout opening ...; no associated peer node" log
// lines). That leaves acceptTCP responsible for rejecting connections
// to ports we don't handle; without an explicit guard, execution would
// fall through to the isTailscaleIP case (quad-100 is in the tailscale
// range), rewriting the dial target to 127.0.0.1:<port> and forwarding
// the connection to whatever random service happened to be listening
// on the host's loopback at that port.
//
// This test asserts that the forward dialer is NOT invoked for quad-100
// SYNs on unserved ports; the guard in acceptTCP must RST instead.
func TestQuad100UnservedTCPPortDoesNotForward(t *testing.T) {
	impl := makeNetstack(t, func(impl *Impl) {
		impl.ProcessSubnets = false
		impl.ProcessLocalIPs = false
		impl.atomicIsLocalIPFunc.Store(looksLikeATailscaleSelfAddress)
	})

	dialFn, gotConn := makeHangDialer(t)
	impl.forwardDialFunc = dialFn

	// Use a client IP in the CGNAT range so shouldProcessInbound-adjacent
	// code paths treat this as plausibly-peer-sourced traffic, matching
	// what a real stray quad-100 probe from the host OS would look like.
	client := netip.MustParseAddr("100.101.102.103")
	quad100 := tsaddr.TailscaleServiceIP()

	// 853 is DoT, the specific case called out in the original bug
	// report ("conntrack error no peer found for 100.100.100.100:853").
	// Before the fix, port 853 (and any non-{53,80,8080} port) leaked
	// out to WireGuard; after the fix it is absorbed here and must NOT
	// trigger forwardTCP.
	pkt := tcp4syn(t, client, quad100, 1234, 853)
	var parsed packet.Parsed
	parsed.Decode(pkt)

	resp, _ := impl.handleLocalPackets(&parsed, impl.tundev, nil)
	if resp != filter.DropSilently {
		t.Fatalf("handleLocalPackets for quad-100:853: got %v, want filter.DropSilently", resp)
	}

	// acceptTCP runs asynchronously in the gVisor TCP dispatcher after
	// handleLocalPackets injects the packet into netstack. Use the
	// in-flight connection counter as a deterministic synchronization
	// point: wrapTCPProtocolHandler increments connsInFlightByClient
	// when the dispatcher hands the connection off to acceptTCP, and
	// acceptTCP's deferred decrementInFlightTCPForward decrements it
	// on return.
	//
	// On the green path (RST guard fires), acceptTCP returns promptly
	// and the counter reaches 0. On the red path (fall-through to
	// forwardTCP), acceptTCP blocks inside the forwardDialFunc call —
	// makeHangDialer signals gotConn on entry (buffered, non-blocking)
	// and then blocks forever — so the counter never reaches 0 but
	// gotConn fires synchronously from the dispatcher goroutine. A
	// select on both races those outcomes without real-time padding.
	//
	// testing/synctest is not usable here: gVisor's sleep package calls
	// the runtime's gopark directly rather than via the standard
	// library, so synctest.Wait() cannot observe those goroutines
	// becoming durably blocked and hangs indefinitely.
	inFlightZero := make(chan struct{})
	go func() {
		for {
			impl.mu.Lock()
			n := impl.connsInFlightByClient[client]
			impl.mu.Unlock()
			if n == 0 {
				close(inFlightZero)
				return
			}
			time.Sleep(time.Millisecond)
		}
	}()

	select {
	case <-gotConn:
		t.Fatalf("forwardDialFunc was called for quad-100:853; acceptTCP fell through to forwardTCP instead of sending RST. This means stray traffic to quad-100 on unserved ports is being redirected to the host's loopback at the same port.")
	case <-inFlightZero:
		// acceptTCP returned cleanly; the RST guard fired.
	case <-time.After(5 * time.Second):
		// Safety net so a regression in the in-flight counter plumbing
		// doesn't hang the whole test run; both outcomes above should
		// fire within milliseconds in practice.
		t.Fatal("timed out waiting for acceptTCP to dispatch quad-100:853 SYN")
	}
}

func TestShouldSendToHost(t *testing.T) {
	var (
		selfIP4             = netip.MustParseAddr("100.64.1.2")
		selfIP6             = netip.MustParseAddr("fd7a:115c:a1e0::123")
		tailscaleServiceIP4 = netip.MustParseAddr("100.99.55.111")
		tailscaleServiceIP6 = netip.MustParseAddr("fd7a:115c:a1e0::abcd")
	)

	makeTestNetstack := func(tb testing.TB) *Impl {
		impl := makeNetstack(tb, func(impl *Impl) {
			impl.ProcessSubnets = false
			impl.ProcessLocalIPs = false
			impl.atomicIsLocalIPFunc.Store(func(addr netip.Addr) bool {
				return addr == selfIP4 || addr == selfIP6
			})
			impl.atomicIsVIPServiceIPFunc.Store(func(addr netip.Addr) bool {
				return addr == tailscaleServiceIP4 || addr == tailscaleServiceIP6
			})
		})

		prefs := ipn.NewPrefs()
		prefs.AdvertiseRoutes = []netip.Prefix{
			// $ tailscale debug via 7 10.1.1.0/24
			// fd7a:115c:a1e0:b1a:0:7:a01:100/120
			netip.MustParsePrefix("fd7a:115c:a1e0:b1a:0:7:a01:100/120"),
		}
		_, err := impl.lb.EditPrefs(&ipn.MaskedPrefs{
			Prefs:              *prefs,
			AdvertiseRoutesSet: true,
		})
		if err != nil {
			tb.Fatalf("EditPrefs: %v", err)
		}
		return impl
	}

	testCases := []struct {
		name     string
		src, dst netip.AddrPort
		want     bool
	}{
		// Reply from service IP to localhost should be sent to host,
		// not over WireGuard.
		{
			name: "from_service_ip_to_localhost",
			src:  netip.AddrPortFrom(serviceIP, 53),
			dst:  netip.MustParseAddrPort("127.0.0.1:9999"),
			want: true,
		},
		{
			name: "from_service_ip_to_localhost_v6",
			src:  netip.AddrPortFrom(serviceIPv6, 53),
			dst:  netip.MustParseAddrPort("[::1]:9999"),
			want: true,
		},
		// A reply from the local IP to a remote host isn't sent to the
		// host, but rather over WireGuard.
		{
			name: "local_ip_to_remote",
			src:  netip.AddrPortFrom(selfIP4, 12345),
			dst:  netip.MustParseAddrPort("100.64.99.88:7777"),
			want: false,
		},
		{
			name: "local_ip_to_remote_v6",
			src:  netip.AddrPortFrom(selfIP6, 12345),
			dst:  netip.MustParseAddrPort("[fd7a:115:a1e0::99]:7777"),
			want: false,
		},
		// A reply from a 4via6 address to a remote host isn't sent to
		// the local host, but rather over WireGuard. See:
		//     https://github.com/tailscale/tailscale/issues/12448
		{
			name: "4via6_to_remote",

			// $ tailscale debug via 7 10.1.1.99/24
			// fd7a:115c:a1e0:b1a:0:7:a01:163/120
			src:  netip.MustParseAddrPort("[fd7a:115c:a1e0:b1a:0:7:a01:163]:12345"),
			dst:  netip.MustParseAddrPort("[fd7a:115:a1e0::99]:7777"),
			want: false,
		},
		// However, a reply from a 4via6 address to the local Tailscale
		// IP for this host *is* sent to the local host. See:
		//     https://github.com/tailscale/tailscale/issues/11304
		{
			name: "4via6_to_local",

			// $ tailscale debug via 7 10.1.1.99/24
			// fd7a:115c:a1e0:b1a:0:7:a01:163/120
			src:  netip.MustParseAddrPort("[fd7a:115c:a1e0:b1a:0:7:a01:163]:12345"),
			dst:  netip.AddrPortFrom(selfIP6, 7777),
			want: true,
		},
		// Traffic from a 4via6 address that we're not handling to
		// either the local Tailscale IP or a remote host is sent
		// outbound.
		//
		// In most cases, we won't see this type of traffic in the
		// shouldSendToHost function, but let's confirm.
		{
			name: "other_4via6_to_local",

			// $ tailscale debug via 4444 10.1.1.88/24
			// fd7a:115c:a1e0:b1a:0:7:a01:163/120
			src:  netip.MustParseAddrPort("[fd7a:115c:a1e0:b1a:0:115c:a01:158]:12345"),
			dst:  netip.AddrPortFrom(selfIP6, 7777),
			want: false,
		},
		{
			name: "other_4via6_to_remote",

			// $ tailscale debug via 4444 10.1.1.88/24
			// fd7a:115c:a1e0:b1a:0:7:a01:163/120
			src:  netip.MustParseAddrPort("[fd7a:115c:a1e0:b1a:0:115c:a01:158]:12345"),
			dst:  netip.MustParseAddrPort("[fd7a:115:a1e0::99]:7777"),
			want: false,
		},
		// After accessing the Tailscale service from host, replies from Tailscale Service IPs
		// to the local Tailscale IPs should be sent to the host.
		{
			name: "from_service_ip_to_local_ip",
			src:  netip.AddrPortFrom(tailscaleServiceIP4, 80),
			dst:  netip.AddrPortFrom(selfIP4, 12345),
			want: true,
		},
		{
			name: "from_service_ip_to_local_ip_v6",
			src:  netip.AddrPortFrom(tailscaleServiceIP6, 80),
			dst:  netip.AddrPortFrom(selfIP6, 12345),
			want: true,
		},
		// Traffic from remote IPs to Tailscale Service IPs should be sent over WireGuard.
		{
			name: "from_service_ip_to_remote",
			src:  netip.AddrPortFrom(tailscaleServiceIP4, 80),
			dst:  netip.MustParseAddrPort("173.201.32.56:54321"),
			want: false,
		},
		{
			name: "from_service_ip_to_remote_v6",
			src:  netip.AddrPortFrom(tailscaleServiceIP6, 80),
			dst:  netip.MustParseAddrPort("[2001:4860:4860::8888]:54321"),
			want: false,
		},
	}

	for _, tt := range testCases {
		t.Run(tt.name, func(t *testing.T) {
			var pkt *stack.PacketBuffer
			if tt.src.Addr().Is4() {
				pkt = makeUDP4PacketBuffer(tt.src, tt.dst)
			} else {
				pkt = makeUDP6PacketBuffer(tt.src, tt.dst)
			}

			ns := makeTestNetstack(t)
			if got := ns.shouldSendToHost(pkt); got != tt.want {
				t.Errorf("shouldSendToHost returned %v, want %v", got, tt.want)
			}
		})
	}
}

func makeUDP4PacketBuffer(src, dst netip.AddrPort) *stack.PacketBuffer {
	if !src.Addr().Is4() || !dst.Addr().Is4() {
		panic("src and dst must be IPv4")
	}

	data := []byte("hello world\n")

	packetLen := header.IPv4MinimumSize + header.UDPMinimumSize
	pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{
		ReserveHeaderBytes: packetLen,
		Payload:            buffer.MakeWithData(data),
	})

	// Initialize the UDP header.
	udp := header.UDP(pkt.TransportHeader().Push(header.UDPMinimumSize))
	pkt.TransportProtocolNumber = header.UDPProtocolNumber

	length := uint16(pkt.Size())
	udp.Encode(&header.UDPFields{
		SrcPort: src.Port(),
		DstPort: dst.Port(),
		Length:  length,
	})

	// Add IP header
	ipHdr := header.IPv4(pkt.NetworkHeader().Push(header.IPv4MinimumSize))
	pkt.NetworkProtocolNumber = header.IPv4ProtocolNumber
	ipHdr.Encode(&header.IPv4Fields{
		TotalLength: uint16(packetLen),
		Protocol:    uint8(header.UDPProtocolNumber),
		SrcAddr:     tcpip.AddrFrom4(src.Addr().As4()),
		DstAddr:     tcpip.AddrFrom4(dst.Addr().As4()),
		Checksum:    0,
	})

	return pkt
}

func makeUDP6PacketBuffer(src, dst netip.AddrPort) *stack.PacketBuffer {
	if !src.Addr().Is6() || !dst.Addr().Is6() {
		panic("src and dst must be IPv6")
	}
	data := []byte("hello world\n")

	packetLen := header.IPv6MinimumSize + header.UDPMinimumSize
	pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{
		ReserveHeaderBytes: packetLen,
		Payload:            buffer.MakeWithData(data),
	})

	srcAddr := tcpip.AddrFrom16(src.Addr().As16())
	dstAddr := tcpip.AddrFrom16(dst.Addr().As16())

	// Add IP header
	ipHdr := header.IPv6(pkt.NetworkHeader().Push(header.IPv6MinimumSize))
	pkt.NetworkProtocolNumber = header.IPv6ProtocolNumber
	ipHdr.Encode(&header.IPv6Fields{
		SrcAddr:           srcAddr,
		DstAddr:           dstAddr,
		PayloadLength:     uint16(header.UDPMinimumSize + len(data)),
		TransportProtocol: header.UDPProtocolNumber,
		HopLimit:          64,
	})

	// Initialize the UDP header.
	udp := header.UDP(pkt.TransportHeader().Push(header.UDPMinimumSize))
	pkt.TransportProtocolNumber = header.UDPProtocolNumber

	length := uint16(pkt.Size())
	udp.Encode(&header.UDPFields{
		SrcPort: src.Port(),
		DstPort: dst.Port(),
		Length:  length,
	})

	// Calculate the UDP pseudo-header checksum.
	xsum := header.PseudoHeaderChecksum(header.UDPProtocolNumber, srcAddr, dstAddr, uint16(len(udp)))
	udp.SetChecksum(^udp.CalculateChecksum(xsum))

	return pkt
}

// TestIsSelfDst verifies that isSelfDst correctly identifies packets whose
// destination IP is a local Tailscale IP assigned to this node.
func TestIsSelfDst(t *testing.T) {
	var (
		selfIP4   = netip.MustParseAddr("100.64.1.2")
		selfIP6   = netip.MustParseAddr("fd7a:115c:a1e0::123")
		remoteIP4 = netip.MustParseAddr("100.64.99.88")
		remoteIP6 = netip.MustParseAddr("fd7a:115c:a1e0::99")
	)

	ns := makeNetstack(t, func(impl *Impl) {
		impl.ProcessLocalIPs = true
		impl.atomicIsLocalIPFunc.Store(func(addr netip.Addr) bool {
			return addr == selfIP4 || addr == selfIP6
		})
	})

	testCases := []struct {
		name     string
		src, dst netip.AddrPort
		want     bool
	}{
		{
			name: "self_to_self_v4",
			src:  netip.AddrPortFrom(selfIP4, 12345),
			dst:  netip.AddrPortFrom(selfIP4, 8081),
			want: true,
		},
		{
			name: "self_to_self_v6",
			src:  netip.AddrPortFrom(selfIP6, 12345),
			dst:  netip.AddrPortFrom(selfIP6, 8081),
			want: true,
		},
		{
			name: "remote_to_self_v4",
			src:  netip.AddrPortFrom(remoteIP4, 12345),
			dst:  netip.AddrPortFrom(selfIP4, 8081),
			want: true,
		},
		{
			name: "remote_to_self_v6",
			src:  netip.AddrPortFrom(remoteIP6, 12345),
			dst:  netip.AddrPortFrom(selfIP6, 8081),
			want: true,
		},
		{
			name: "self_to_remote_v4",
			src:  netip.AddrPortFrom(selfIP4, 12345),
			dst:  netip.AddrPortFrom(remoteIP4, 8081),
			want: false,
		},
		{
			name: "self_to_remote_v6",
			src:  netip.AddrPortFrom(selfIP6, 12345),
			dst:  netip.AddrPortFrom(remoteIP6, 8081),
			want: false,
		},
		{
			name: "remote_to_remote_v4",
			src:  netip.AddrPortFrom(remoteIP4, 12345),
			dst:  netip.MustParseAddrPort("100.64.77.66:7777"),
			want: false,
		},
		{
			name: "service_ip_to_self_v4",
			src:  netip.AddrPortFrom(serviceIP, 53),
			dst:  netip.AddrPortFrom(selfIP4, 9999),
			want: true,
		},
		{
			name: "service_ip_to_self_v6",
			src:  netip.AddrPortFrom(serviceIPv6, 53),
			dst:  netip.AddrPortFrom(selfIP6, 9999),
			want: true,
		},
	}

	for _, tt := range testCases {
		t.Run(tt.name, func(t *testing.T) {
			var pkt *stack.PacketBuffer
			if tt.src.Addr().Is4() {
				pkt = makeUDP4PacketBuffer(tt.src, tt.dst)
			} else {
				pkt = makeUDP6PacketBuffer(tt.src, tt.dst)
			}
			defer pkt.DecRef()

			if got := ns.isSelfDst(pkt); got != tt.want {
				t.Errorf("isSelfDst(%v -> %v) = %v, want %v", tt.src, tt.dst, got, tt.want)
			}
		})
	}
}

// TestDeliverLoopback verifies that DeliverLoopback correctly re-serializes an
// outbound packet and delivers it back into gVisor's inbound path.
func TestDeliverLoopback(t *testing.T) {
	ep := newLinkEndpoint(64, 1280, "", groNotSupported)

	// Track delivered packets via a mock dispatcher.
	type delivered struct {
		proto tcpip.NetworkProtocolNumber
		data  []byte
	}
	deliveredCh := make(chan delivered, 4)
	ep.Attach(&mockDispatcher{
		onDeliverNetworkPacket: func(proto tcpip.NetworkProtocolNumber, pkt *stack.PacketBuffer) {
			// Capture the raw bytes from the delivered packet. At this
			// point the packet is unparsed — everything is in the
			// payload, no headers have been consumed yet.
			buf := pkt.ToBuffer()
			raw := buf.Flatten()
			deliveredCh <- delivered{proto: proto, data: raw}
		},
	})

	t.Run("ipv4", func(t *testing.T) {
		selfAddr := netip.MustParseAddrPort("100.64.1.2:8081")
		pkt := makeUDP4PacketBuffer(selfAddr, selfAddr)
		// Capture what the outbound bytes look like before loopback.
		wantLen := pkt.Size()
		wantProto := pkt.NetworkProtocolNumber

		if !ep.DeliverLoopback(pkt) {
			t.Fatal("DeliverLoopback returned false")
		}

		select {
		case got := <-deliveredCh:
			if got.proto != wantProto {
				t.Errorf("proto = %d, want %d", got.proto, wantProto)
			}
			if len(got.data) != wantLen {
				t.Errorf("data length = %d, want %d", len(got.data), wantLen)
			}
		case <-time.After(time.Second):
			t.Fatal("timeout waiting for loopback delivery")
		}
	})

	t.Run("ipv6", func(t *testing.T) {
		selfAddr := netip.MustParseAddrPort("[fd7a:115c:a1e0::123]:8081")
		pkt := makeUDP6PacketBuffer(selfAddr, selfAddr)
		wantLen := pkt.Size()
		wantProto := pkt.NetworkProtocolNumber

		if !ep.DeliverLoopback(pkt) {
			t.Fatal("DeliverLoopback returned false")
		}

		select {
		case got := <-deliveredCh:
			if got.proto != wantProto {
				t.Errorf("proto = %d, want %d", got.proto, wantProto)
			}
			if len(got.data) != wantLen {
				t.Errorf("data length = %d, want %d", len(got.data), wantLen)
			}
		case <-time.After(time.Second):
			t.Fatal("timeout waiting for loopback delivery")
		}
	})

	t.Run("nil_dispatcher", func(t *testing.T) {
		ep2 := newLinkEndpoint(64, 1280, "", groNotSupported)
		// Don't attach a dispatcher.
		selfAddr := netip.MustParseAddrPort("100.64.1.2:8081")
		pkt := makeUDP4PacketBuffer(selfAddr, selfAddr)
		if ep2.DeliverLoopback(pkt) {
			t.Error("DeliverLoopback should return false with nil dispatcher")
		}
		// pkt refcount was consumed by DeliverLoopback, so we don't DecRef.
	})
}

// mockDispatcher implements stack.NetworkDispatcher for testing.
type mockDispatcher struct {
	onDeliverNetworkPacket func(tcpip.NetworkProtocolNumber, *stack.PacketBuffer)
}

func (d *mockDispatcher) DeliverNetworkPacket(proto tcpip.NetworkProtocolNumber, pkt *stack.PacketBuffer) {
	if d.onDeliverNetworkPacket != nil {
		d.onDeliverNetworkPacket(proto, pkt)
	}
}

func (d *mockDispatcher) DeliverLinkPacket(tcpip.NetworkProtocolNumber, *stack.PacketBuffer) {}

// udp4raw constructs a valid raw IPv4+UDP packet with proper checksums.
func udp4raw(t testing.TB, src, dst netip.Addr, sport, dport uint16, payload []byte) []byte {
	t.Helper()
	totalLen := header.IPv4MinimumSize + header.UDPMinimumSize + len(payload)
	buf := make([]byte, totalLen)

	ip := header.IPv4(buf)
	ip.Encode(&header.IPv4Fields{
		TotalLength: uint16(totalLen),
		Protocol:    uint8(header.UDPProtocolNumber),
		TTL:         64,
		SrcAddr:     tcpip.AddrFrom4Slice(src.AsSlice()),
		DstAddr:     tcpip.AddrFrom4Slice(dst.AsSlice()),
	})
	ip.SetChecksum(^ip.CalculateChecksum())

	// Build UDP header + payload.
	u := header.UDP(buf[header.IPv4MinimumSize:])
	u.Encode(&header.UDPFields{
		SrcPort: sport,
		DstPort: dport,
		Length:  uint16(header.UDPMinimumSize + len(payload)),
	})
	copy(buf[header.IPv4MinimumSize+header.UDPMinimumSize:], payload)

	xsum := header.PseudoHeaderChecksum(
		header.UDPProtocolNumber,
		tcpip.AddrFrom4Slice(src.AsSlice()),
		tcpip.AddrFrom4Slice(dst.AsSlice()),
		uint16(header.UDPMinimumSize+len(payload)),
	)
	u.SetChecksum(^header.UDP(buf[header.IPv4MinimumSize:]).CalculateChecksum(xsum))
	return buf
}

// TestInjectLoopback verifies that the inject goroutine delivers self-addressed
// packets back into gVisor (via DeliverLoopback) instead of sending them to
// WireGuard outbound. This is a regression test for a bug where self-dial
// packets were sent to WireGuard and silently dropped.
func TestInjectLoopback(t *testing.T) {
	selfIP4 := netip.MustParseAddr("100.64.1.2")

	ns := makeNetstack(t, func(impl *Impl) {
		impl.ProcessLocalIPs = true
		impl.atomicIsLocalIPFunc.Store(func(addr netip.Addr) bool {
			return addr == selfIP4
		})
	})

	// Register gVisor's NIC address so the stack accepts and routes
	// packets for this IP.
	protocolAddr := tcpip.ProtocolAddress{
		Protocol:          header.IPv4ProtocolNumber,
		AddressWithPrefix: tcpip.AddrFrom4(selfIP4.As4()).WithPrefix(),
	}
	if err := ns.ipstack.AddProtocolAddress(nicID, protocolAddr, stack.AddressProperties{}); err != nil {
		t.Fatalf("AddProtocolAddress: %v", err)
	}

	// Bind a UDP socket on the gVisor stack to receive the loopback packet.
	pc, err := gonet.DialUDP(ns.ipstack, &tcpip.FullAddress{
		NIC:  nicID,
		Addr: tcpip.AddrFrom4(selfIP4.As4()),
		Port: 8081,
	}, nil, header.IPv4ProtocolNumber)
	if err != nil {
		t.Fatalf("DialUDP: %v", err)
	}
	defer pc.Close()

	// Build a valid self-addressed UDP packet from raw bytes and wrap it
	// in a gVisor PacketBuffer with headers already pushed, as gVisor's
	// outbound path produces.
	payload := []byte("loopback test")
	raw := udp4raw(t, selfIP4, selfIP4, 12345, 8081, payload)

	pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{
		ReserveHeaderBytes: header.IPv4MinimumSize + header.UDPMinimumSize,
		Payload:            buffer.MakeWithData(payload),
	})
	copy(pkt.TransportHeader().Push(header.UDPMinimumSize),
		raw[header.IPv4MinimumSize:header.IPv4MinimumSize+header.UDPMinimumSize])
	pkt.TransportProtocolNumber = header.UDPProtocolNumber
	copy(pkt.NetworkHeader().Push(header.IPv4MinimumSize), raw[:header.IPv4MinimumSize])
	pkt.NetworkProtocolNumber = header.IPv4ProtocolNumber

	if err := ns.linkEP.q.Write(pkt); err != nil {
		t.Fatalf("queue.Write: %v", err)
	}

	// The inject goroutine should detect the self-addressed packet via
	// isSelfDst and deliver it back into gVisor via DeliverLoopback.
	pc.SetReadDeadline(time.Now().Add(5 * time.Second))
	buf := make([]byte, 256)
	n, _, err := pc.ReadFrom(buf)
	if err != nil {
		t.Fatalf("ReadFrom: %v (self-addressed packet was not looped back)", err)
	}
	if got := string(buf[:n]); got != "loopback test" {
		t.Errorf("got %q, want %q", got, "loopback test")
	}
}