summaryrefslogtreecommitdiffhomepage
path: root/pkg/tcpip/tests/integration/loopback_test.go
blob: b04169751803e6ed3b3ace86c78e22c87ab7a916 (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
// Copyright 2020 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package loopback_test

import (
	"bytes"
	"testing"
	"time"

	"github.com/google/go-cmp/cmp"
	"gvisor.dev/gvisor/pkg/tcpip"
	"gvisor.dev/gvisor/pkg/tcpip/buffer"
	"gvisor.dev/gvisor/pkg/tcpip/checker"
	"gvisor.dev/gvisor/pkg/tcpip/header"
	"gvisor.dev/gvisor/pkg/tcpip/link/channel"
	"gvisor.dev/gvisor/pkg/tcpip/link/loopback"
	"gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
	"gvisor.dev/gvisor/pkg/tcpip/network/ipv6"
	"gvisor.dev/gvisor/pkg/tcpip/stack"
	"gvisor.dev/gvisor/pkg/tcpip/tests/utils"
	"gvisor.dev/gvisor/pkg/tcpip/testutil"
	"gvisor.dev/gvisor/pkg/tcpip/transport/icmp"
	"gvisor.dev/gvisor/pkg/tcpip/transport/tcp"
	"gvisor.dev/gvisor/pkg/tcpip/transport/udp"
	"gvisor.dev/gvisor/pkg/waiter"
)

var _ ipv6.NDPDispatcher = (*ndpDispatcher)(nil)

type ndpDispatcher struct{}

func (*ndpDispatcher) OnDuplicateAddressDetectionResult(tcpip.NICID, tcpip.Address, stack.DADResult) {
}

func (*ndpDispatcher) OnDefaultRouterDiscovered(tcpip.NICID, tcpip.Address) bool {
	return false
}

func (*ndpDispatcher) OnDefaultRouterInvalidated(tcpip.NICID, tcpip.Address) {}

func (*ndpDispatcher) OnOnLinkPrefixDiscovered(tcpip.NICID, tcpip.Subnet) bool {
	return false
}

func (*ndpDispatcher) OnOnLinkPrefixInvalidated(tcpip.NICID, tcpip.Subnet) {}

func (*ndpDispatcher) OnAutoGenAddress(tcpip.NICID, tcpip.AddressWithPrefix) bool {
	return true
}

func (*ndpDispatcher) OnAutoGenAddressDeprecated(tcpip.NICID, tcpip.AddressWithPrefix) {}

func (*ndpDispatcher) OnAutoGenAddressInvalidated(tcpip.NICID, tcpip.AddressWithPrefix) {}

func (*ndpDispatcher) OnRecursiveDNSServerOption(tcpip.NICID, []tcpip.Address, time.Duration) {}

func (*ndpDispatcher) OnDNSSearchListOption(tcpip.NICID, []string, time.Duration) {}

func (*ndpDispatcher) OnDHCPv6Configuration(tcpip.NICID, ipv6.DHCPv6ConfigurationFromNDPRA) {}

// TestInitialLoopbackAddresses tests that the loopback interface does not
// auto-generate a link-local address when it is brought up.
func TestInitialLoopbackAddresses(t *testing.T) {
	const nicID = 1

	s := stack.New(stack.Options{
		NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocolWithOptions(ipv6.Options{
			NDPDisp:          &ndpDispatcher{},
			AutoGenLinkLocal: true,
			OpaqueIIDOpts: ipv6.OpaqueInterfaceIdentifierOptions{
				NICNameFromID: func(nicID tcpip.NICID, nicName string) string {
					t.Fatalf("should not attempt to get name for NIC with ID = %d; nicName = %s", nicID, nicName)
					return ""
				},
			},
		})},
	})

	if err := s.CreateNIC(nicID, loopback.New()); err != nil {
		t.Fatalf("CreateNIC(%d, _): %s", nicID, err)
	}

	nicsInfo := s.NICInfo()
	if nicInfo, ok := nicsInfo[nicID]; !ok {
		t.Fatalf("did not find NIC with ID = %d in s.NICInfo() = %#v", nicID, nicsInfo)
	} else if got := len(nicInfo.ProtocolAddresses); got != 0 {
		t.Fatalf("got len(nicInfo.ProtocolAddresses) = %d, want = 0; nicInfo.ProtocolAddresses = %#v", got, nicInfo.ProtocolAddresses)
	}
}

// TestLoopbackAcceptAllInSubnetUDP tests that a loopback interface considers
// itself bound to all addresses in the subnet of an assigned address and UDP
// traffic is sent/received correctly.
func TestLoopbackAcceptAllInSubnetUDP(t *testing.T) {
	const (
		nicID     = 1
		localPort = 80
	)

	data := []byte{1, 2, 3, 4}

	ipv4ProtocolAddress := tcpip.ProtocolAddress{
		Protocol:          header.IPv4ProtocolNumber,
		AddressWithPrefix: utils.Ipv4Addr,
	}
	ipv4Bytes := []byte(ipv4ProtocolAddress.AddressWithPrefix.Address)
	ipv4Bytes[len(ipv4Bytes)-1]++
	otherIPv4Address := tcpip.Address(ipv4Bytes)

	ipv6ProtocolAddress := tcpip.ProtocolAddress{
		Protocol:          header.IPv6ProtocolNumber,
		AddressWithPrefix: utils.Ipv6Addr,
	}
	ipv6Bytes := []byte(utils.Ipv6Addr.Address)
	ipv6Bytes[len(ipv6Bytes)-1]++
	otherIPv6Address := tcpip.Address(ipv6Bytes)

	tests := []struct {
		name       string
		addAddress tcpip.ProtocolAddress
		bindAddr   tcpip.Address
		dstAddr    tcpip.Address
		expectRx   bool
	}{
		{
			name:       "IPv4 bind to wildcard and send to assigned address",
			addAddress: ipv4ProtocolAddress,
			dstAddr:    ipv4ProtocolAddress.AddressWithPrefix.Address,
			expectRx:   true,
		},
		{
			name:       "IPv4 bind to wildcard and send to other subnet-local address",
			addAddress: ipv4ProtocolAddress,
			dstAddr:    otherIPv4Address,
			expectRx:   true,
		},
		{
			name:       "IPv4 bind to wildcard send to other address",
			addAddress: ipv4ProtocolAddress,
			dstAddr:    utils.RemoteIPv4Addr,
			expectRx:   false,
		},
		{
			name:       "IPv4 bind to other subnet-local address and send to assigned address",
			addAddress: ipv4ProtocolAddress,
			bindAddr:   otherIPv4Address,
			dstAddr:    ipv4ProtocolAddress.AddressWithPrefix.Address,
			expectRx:   false,
		},
		{
			name:       "IPv4 bind and send to other subnet-local address",
			addAddress: ipv4ProtocolAddress,
			bindAddr:   otherIPv4Address,
			dstAddr:    otherIPv4Address,
			expectRx:   true,
		},
		{
			name:       "IPv4 bind to assigned address and send to other subnet-local address",
			addAddress: ipv4ProtocolAddress,
			bindAddr:   ipv4ProtocolAddress.AddressWithPrefix.Address,
			dstAddr:    otherIPv4Address,
			expectRx:   false,
		},

		{
			name:       "IPv6 bind and send to assigned address",
			addAddress: ipv6ProtocolAddress,
			bindAddr:   utils.Ipv6Addr.Address,
			dstAddr:    utils.Ipv6Addr.Address,
			expectRx:   true,
		},
		{
			name:       "IPv6 bind to wildcard and send to other subnet-local address",
			addAddress: ipv6ProtocolAddress,
			dstAddr:    otherIPv6Address,
			expectRx:   false,
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			s := stack.New(stack.Options{
				NetworkProtocols:   []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},
				TransportProtocols: []stack.TransportProtocolFactory{udp.NewProtocol},
			})
			if err := s.CreateNIC(nicID, loopback.New()); err != nil {
				t.Fatalf("CreateNIC(%d, _): %s", nicID, err)
			}
			if err := s.AddProtocolAddress(nicID, test.addAddress); err != nil {
				t.Fatalf("AddProtocolAddress(%d, %+v): %s", nicID, test.addAddress, err)
			}
			s.SetRouteTable([]tcpip.Route{
				{
					Destination: header.IPv4EmptySubnet,
					NIC:         nicID,
				},
				{
					Destination: header.IPv6EmptySubnet,
					NIC:         nicID,
				},
			})

			var wq waiter.Queue
			rep, err := s.NewEndpoint(udp.ProtocolNumber, test.addAddress.Protocol, &wq)
			if err != nil {
				t.Fatalf("NewEndpoint(%d, %d, _): %s", udp.ProtocolNumber, test.addAddress.Protocol, err)
			}
			defer rep.Close()

			bindAddr := tcpip.FullAddress{Addr: test.bindAddr, Port: localPort}
			if err := rep.Bind(bindAddr); err != nil {
				t.Fatalf("rep.Bind(%+v): %s", bindAddr, err)
			}

			sep, err := s.NewEndpoint(udp.ProtocolNumber, test.addAddress.Protocol, &wq)
			if err != nil {
				t.Fatalf("NewEndpoint(%d, %d, _): %s", udp.ProtocolNumber, test.addAddress.Protocol, err)
			}
			defer sep.Close()

			wopts := tcpip.WriteOptions{
				To: &tcpip.FullAddress{
					Addr: test.dstAddr,
					Port: localPort,
				},
			}
			var r bytes.Reader
			r.Reset(data)
			n, err := sep.Write(&r, wopts)
			if err != nil {
				t.Fatalf("sep.Write(_, _): %s", err)
			}
			if want := int64(len(data)); n != want {
				t.Fatalf("got sep.Write(_, _) = (%d, nil), want = (%d, nil)", n, want)
			}

			var buf bytes.Buffer
			opts := tcpip.ReadOptions{NeedRemoteAddr: true}
			if res, err := rep.Read(&buf, opts); test.expectRx {
				if err != nil {
					t.Fatalf("rep.Read(_, %#v): %s", opts, err)
				}
				if diff := cmp.Diff(tcpip.ReadResult{
					Count: buf.Len(),
					Total: buf.Len(),
					RemoteAddr: tcpip.FullAddress{
						Addr: test.addAddress.AddressWithPrefix.Address,
					},
				}, res,
					checker.IgnoreCmpPath("ControlMessages", "RemoteAddr.NIC", "RemoteAddr.Port"),
				); diff != "" {
					t.Errorf("rep.Read: unexpected result (-want +got):\n%s", diff)
				}
				if diff := cmp.Diff(data, buf.Bytes()); diff != "" {
					t.Errorf("got UDP payload mismatch (-want +got):\n%s", diff)
				}
			} else if _, ok := err.(*tcpip.ErrWouldBlock); !ok {
				t.Fatalf("got rep.Read = (%v, %s) [with data %x], want = (_, %s)", res, err, buf.Bytes(), &tcpip.ErrWouldBlock{})
			}
		})
	}
}

// TestLoopbackSubnetLifetimeBoundToAddr tests that the lifetime of an address
// in a loopback interface's associated subnet is bound to the permanently bound
// address.
func TestLoopbackSubnetLifetimeBoundToAddr(t *testing.T) {
	const nicID = 1

	protoAddr := tcpip.ProtocolAddress{
		Protocol:          ipv4.ProtocolNumber,
		AddressWithPrefix: utils.Ipv4Addr,
	}
	addrBytes := []byte(utils.Ipv4Addr.Address)
	addrBytes[len(addrBytes)-1]++
	otherAddr := tcpip.Address(addrBytes)

	s := stack.New(stack.Options{
		NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol},
	})
	if err := s.CreateNIC(nicID, loopback.New()); err != nil {
		t.Fatalf("s.CreateNIC(%d, _): %s", nicID, err)
	}
	if err := s.AddProtocolAddress(nicID, protoAddr); err != nil {
		t.Fatalf("s.AddProtocolAddress(%d, %#v): %s", nicID, protoAddr, err)
	}
	s.SetRouteTable([]tcpip.Route{
		{
			Destination: header.IPv4EmptySubnet,
			NIC:         nicID,
		},
	})

	r, err := s.FindRoute(nicID, otherAddr, utils.RemoteIPv4Addr, ipv4.ProtocolNumber, false /* multicastLoop */)
	if err != nil {
		t.Fatalf("s.FindRoute(%d, %s, %s, %d, false): %s", nicID, otherAddr, utils.RemoteIPv4Addr, ipv4.ProtocolNumber, err)
	}
	defer r.Release()

	params := stack.NetworkHeaderParams{
		Protocol: 111,
		TTL:      64,
		TOS:      stack.DefaultTOS,
	}
	data := buffer.View([]byte{1, 2, 3, 4})
	if err := r.WritePacket(nil /* gso */, params, stack.NewPacketBuffer(stack.PacketBufferOptions{
		ReserveHeaderBytes: int(r.MaxHeaderLength()),
		Data:               data.ToVectorisedView(),
	})); err != nil {
		t.Fatalf("r.WritePacket(nil, %#v, _): %s", params, err)
	}

	// Removing the address should make the endpoint invalid.
	if err := s.RemoveAddress(nicID, protoAddr.AddressWithPrefix.Address); err != nil {
		t.Fatalf("s.RemoveAddress(%d, %s): %s", nicID, protoAddr.AddressWithPrefix.Address, err)
	}
	{
		err := r.WritePacket(nil /* gso */, params, stack.NewPacketBuffer(stack.PacketBufferOptions{
			ReserveHeaderBytes: int(r.MaxHeaderLength()),
			Data:               data.ToVectorisedView(),
		}))
		if _, ok := err.(*tcpip.ErrInvalidEndpointState); !ok {
			t.Fatalf("got r.WritePacket(nil, %#v, _) = %s, want = %s", params, err, &tcpip.ErrInvalidEndpointState{})
		}
	}
}

// TestLoopbackAcceptAllInSubnetTCP tests that a loopback interface considers
// itself bound to all addresses in the subnet of an assigned address and TCP
// traffic is sent/received correctly.
func TestLoopbackAcceptAllInSubnetTCP(t *testing.T) {
	const (
		nicID     = 1
		localPort = 80
	)

	ipv4ProtocolAddress := tcpip.ProtocolAddress{
		Protocol:          header.IPv4ProtocolNumber,
		AddressWithPrefix: utils.Ipv4Addr,
	}
	ipv4ProtocolAddress.AddressWithPrefix.PrefixLen = 8
	ipv4Bytes := []byte(ipv4ProtocolAddress.AddressWithPrefix.Address)
	ipv4Bytes[len(ipv4Bytes)-1]++
	otherIPv4Address := tcpip.Address(ipv4Bytes)

	ipv6ProtocolAddress := tcpip.ProtocolAddress{
		Protocol:          header.IPv6ProtocolNumber,
		AddressWithPrefix: utils.Ipv6Addr,
	}
	ipv6Bytes := []byte(utils.Ipv6Addr.Address)
	ipv6Bytes[len(ipv6Bytes)-1]++
	otherIPv6Address := tcpip.Address(ipv6Bytes)

	tests := []struct {
		name         string
		addAddress   tcpip.ProtocolAddress
		bindAddr     tcpip.Address
		dstAddr      tcpip.Address
		expectAccept bool
	}{
		{
			name:         "IPv4 bind to wildcard and send to assigned address",
			addAddress:   ipv4ProtocolAddress,
			dstAddr:      ipv4ProtocolAddress.AddressWithPrefix.Address,
			expectAccept: true,
		},
		{
			name:         "IPv4 bind to wildcard and send to other subnet-local address",
			addAddress:   ipv4ProtocolAddress,
			dstAddr:      otherIPv4Address,
			expectAccept: true,
		},
		{
			name:         "IPv4 bind to wildcard send to other address",
			addAddress:   ipv4ProtocolAddress,
			dstAddr:      utils.RemoteIPv4Addr,
			expectAccept: false,
		},
		{
			name:         "IPv4 bind to other subnet-local address and send to assigned address",
			addAddress:   ipv4ProtocolAddress,
			bindAddr:     otherIPv4Address,
			dstAddr:      ipv4ProtocolAddress.AddressWithPrefix.Address,
			expectAccept: false,
		},
		{
			name:         "IPv4 bind and send to other subnet-local address",
			addAddress:   ipv4ProtocolAddress,
			bindAddr:     otherIPv4Address,
			dstAddr:      otherIPv4Address,
			expectAccept: true,
		},
		{
			name:         "IPv4 bind to assigned address and send to other subnet-local address",
			addAddress:   ipv4ProtocolAddress,
			bindAddr:     ipv4ProtocolAddress.AddressWithPrefix.Address,
			dstAddr:      otherIPv4Address,
			expectAccept: false,
		},

		{
			name:         "IPv6 bind and send to assigned address",
			addAddress:   ipv6ProtocolAddress,
			bindAddr:     utils.Ipv6Addr.Address,
			dstAddr:      utils.Ipv6Addr.Address,
			expectAccept: true,
		},
		{
			name:         "IPv6 bind to wildcard and send to other subnet-local address",
			addAddress:   ipv6ProtocolAddress,
			dstAddr:      otherIPv6Address,
			expectAccept: false,
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			s := stack.New(stack.Options{
				NetworkProtocols:   []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},
				TransportProtocols: []stack.TransportProtocolFactory{tcp.NewProtocol},
			})
			if err := s.CreateNIC(nicID, loopback.New()); err != nil {
				t.Fatalf("CreateNIC(%d, _): %s", nicID, err)
			}
			if err := s.AddProtocolAddress(nicID, test.addAddress); err != nil {
				t.Fatalf("AddProtocolAddress(%d, %#v): %s", nicID, test.addAddress, err)
			}
			s.SetRouteTable([]tcpip.Route{
				{
					Destination: header.IPv4EmptySubnet,
					NIC:         nicID,
				},
				{
					Destination: header.IPv6EmptySubnet,
					NIC:         nicID,
				},
			})

			var wq waiter.Queue
			we, ch := waiter.NewChannelEntry(nil)
			wq.EventRegister(&we, waiter.ReadableEvents)
			defer wq.EventUnregister(&we)
			listeningEndpoint, err := s.NewEndpoint(tcp.ProtocolNumber, test.addAddress.Protocol, &wq)
			if err != nil {
				t.Fatalf("NewEndpoint(%d, %d, _): %s", udp.ProtocolNumber, test.addAddress.Protocol, err)
			}
			defer listeningEndpoint.Close()

			bindAddr := tcpip.FullAddress{Addr: test.bindAddr, Port: localPort}
			if err := listeningEndpoint.Bind(bindAddr); err != nil {
				t.Fatalf("listeningEndpoint.Bind(%#v): %s", bindAddr, err)
			}

			if err := listeningEndpoint.Listen(1); err != nil {
				t.Fatalf("listeningEndpoint.Listen(1): %s", err)
			}

			connectingEndpoint, err := s.NewEndpoint(tcp.ProtocolNumber, test.addAddress.Protocol, &wq)
			if err != nil {
				t.Fatalf("s.NewEndpoint(%d, %d, _): %s", udp.ProtocolNumber, test.addAddress.Protocol, err)
			}
			defer connectingEndpoint.Close()

			connectAddr := tcpip.FullAddress{
				Addr: test.dstAddr,
				Port: localPort,
			}
			{
				err := connectingEndpoint.Connect(connectAddr)
				if _, ok := err.(*tcpip.ErrConnectStarted); !ok {
					t.Fatalf("connectingEndpoint.Connect(%#v): %s", connectAddr, err)
				}
			}

			if !test.expectAccept {
				_, _, err := listeningEndpoint.Accept(nil)
				if _, ok := err.(*tcpip.ErrWouldBlock); !ok {
					t.Fatalf("got listeningEndpoint.Accept(nil) = %s, want = %s", err, &tcpip.ErrWouldBlock{})
				}
				return
			}

			// Wait for the listening endpoint to be "readable". That is, wait for a
			// new connection.
			<-ch
			var addr tcpip.FullAddress
			if _, _, err := listeningEndpoint.Accept(&addr); err != nil {
				t.Fatalf("listeningEndpoint.Accept(nil): %s", err)
			}
			if addr.Addr != test.addAddress.AddressWithPrefix.Address {
				t.Errorf("got addr.Addr = %s, want = %s", addr.Addr, test.addAddress.AddressWithPrefix.Address)
			}
		})
	}
}

func TestExternalLoopbackTraffic(t *testing.T) {
	const (
		nicID1 = 1
		nicID2 = 2

		numPackets = 1
		ttl        = 64
	)
	ipv4Loopback := testutil.MustParse4("127.0.0.1")

	loopbackSourcedICMPv4 := func(e *channel.Endpoint) {
		utils.RxICMPv4EchoRequest(e, ipv4Loopback, utils.Ipv4Addr.Address, ttl)
	}

	loopbackSourcedICMPv6 := func(e *channel.Endpoint) {
		utils.RxICMPv6EchoRequest(e, header.IPv6Loopback, utils.Ipv6Addr.Address, ttl)
	}

	loopbackDestinedICMPv4 := func(e *channel.Endpoint) {
		utils.RxICMPv4EchoRequest(e, utils.RemoteIPv4Addr, ipv4Loopback, ttl)
	}

	loopbackDestinedICMPv6 := func(e *channel.Endpoint) {
		utils.RxICMPv6EchoRequest(e, utils.RemoteIPv6Addr, header.IPv6Loopback, ttl)
	}

	invalidSrcAddrStat := func(s tcpip.IPStats) *tcpip.StatCounter {
		return s.InvalidSourceAddressesReceived
	}

	invalidDestAddrStat := func(s tcpip.IPStats) *tcpip.StatCounter {
		return s.InvalidDestinationAddressesReceived
	}

	tests := []struct {
		name                  string
		allowExternalLoopback bool
		forwarding            bool
		rxICMP                func(*channel.Endpoint)
		invalidAddressStat    func(tcpip.IPStats) *tcpip.StatCounter
		shouldAccept          bool
	}{
		{
			name:                  "IPv4 external loopback sourced traffic without forwarding and drop external loopback disabled",
			allowExternalLoopback: true,
			forwarding:            false,
			rxICMP:                loopbackSourcedICMPv4,
			invalidAddressStat:    invalidSrcAddrStat,
			shouldAccept:          true,
		},
		{
			name:                  "IPv4 external loopback sourced traffic without forwarding and drop external loopback enabled",
			allowExternalLoopback: false,
			forwarding:            false,
			rxICMP:                loopbackSourcedICMPv4,
			invalidAddressStat:    invalidSrcAddrStat,
			shouldAccept:          false,
		},
		{
			name:                  "IPv4 external loopback sourced traffic with forwarding and drop external loopback disabled",
			allowExternalLoopback: true,
			forwarding:            true,
			rxICMP:                loopbackSourcedICMPv4,
			invalidAddressStat:    invalidSrcAddrStat,
			shouldAccept:          true,
		},
		{
			name:                  "IPv4 external loopback sourced traffic with forwarding and drop external loopback enabled",
			allowExternalLoopback: false,
			forwarding:            true,
			rxICMP:                loopbackSourcedICMPv4,
			invalidAddressStat:    invalidSrcAddrStat,
			shouldAccept:          false,
		},
		{
			name:                  "IPv4 external loopback destined traffic without forwarding and drop external loopback disabled",
			allowExternalLoopback: true,
			forwarding:            false,
			rxICMP:                loopbackDestinedICMPv4,
			invalidAddressStat:    invalidDestAddrStat,
			shouldAccept:          false,
		},
		{
			name:                  "IPv4 external loopback destined traffic without forwarding and drop external loopback enabled",
			allowExternalLoopback: false,
			forwarding:            false,
			rxICMP:                loopbackDestinedICMPv4,
			invalidAddressStat:    invalidDestAddrStat,
			shouldAccept:          false,
		},
		{
			name:                  "IPv4 external loopback destined traffic with forwarding and drop external loopback disabled",
			allowExternalLoopback: true,
			forwarding:            true,
			rxICMP:                loopbackDestinedICMPv4,
			invalidAddressStat:    invalidDestAddrStat,
			shouldAccept:          true,
		},
		{
			name:                  "IPv4 external loopback destined traffic with forwarding and drop external loopback enabled",
			allowExternalLoopback: false,
			forwarding:            true,
			rxICMP:                loopbackDestinedICMPv4,
			invalidAddressStat:    invalidDestAddrStat,
			shouldAccept:          false,
		},

		{
			name:                  "IPv6 external loopback sourced traffic without forwarding and drop external loopback disabled",
			allowExternalLoopback: true,
			forwarding:            false,
			rxICMP:                loopbackSourcedICMPv6,
			invalidAddressStat:    invalidSrcAddrStat,
			shouldAccept:          true,
		},
		{
			name:                  "IPv6 external loopback sourced traffic without forwarding and drop external loopback enabled",
			allowExternalLoopback: false,
			forwarding:            false,
			rxICMP:                loopbackSourcedICMPv6,
			invalidAddressStat:    invalidSrcAddrStat,
			shouldAccept:          false,
		},
		{
			name:                  "IPv6 external loopback sourced traffic with forwarding and drop external loopback disabled",
			allowExternalLoopback: true,
			forwarding:            true,
			rxICMP:                loopbackSourcedICMPv6,
			invalidAddressStat:    invalidSrcAddrStat,
			shouldAccept:          true,
		},
		{
			name:                  "IPv6 external loopback sourced traffic with forwarding and drop external loopback enabled",
			allowExternalLoopback: false,
			forwarding:            true,
			rxICMP:                loopbackSourcedICMPv6,
			invalidAddressStat:    invalidSrcAddrStat,
			shouldAccept:          false,
		},
		{
			name:                  "IPv6 external loopback destined traffic without forwarding and drop external loopback disabled",
			allowExternalLoopback: true,
			forwarding:            false,
			rxICMP:                loopbackDestinedICMPv6,
			invalidAddressStat:    invalidDestAddrStat,
			shouldAccept:          false,
		},
		{
			name:                  "IPv6 external loopback destined traffic without forwarding and drop external loopback enabled",
			allowExternalLoopback: false,
			forwarding:            false,
			rxICMP:                loopbackDestinedICMPv6,
			invalidAddressStat:    invalidDestAddrStat,
			shouldAccept:          false,
		},
		{
			name:                  "IPv6 external loopback destined traffic with forwarding and drop external loopback disabled",
			allowExternalLoopback: true,
			forwarding:            true,
			rxICMP:                loopbackDestinedICMPv6,
			invalidAddressStat:    invalidDestAddrStat,
			shouldAccept:          true,
		},
		{
			name:                  "IPv6 external loopback destined traffic with forwarding and drop external loopback enabled",
			allowExternalLoopback: false,
			forwarding:            true,
			rxICMP:                loopbackDestinedICMPv6,
			invalidAddressStat:    invalidDestAddrStat,
			shouldAccept:          false,
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			s := stack.New(stack.Options{
				NetworkProtocols: []stack.NetworkProtocolFactory{
					ipv4.NewProtocolWithOptions(ipv4.Options{
						AllowExternalLoopbackTraffic: test.allowExternalLoopback,
					}),
					ipv6.NewProtocolWithOptions(ipv6.Options{
						AllowExternalLoopbackTraffic: test.allowExternalLoopback,
					}),
				},
				TransportProtocols: []stack.TransportProtocolFactory{icmp.NewProtocol4, icmp.NewProtocol6},
			})
			e := channel.New(1, header.IPv6MinimumMTU, "")
			if err := s.CreateNIC(nicID1, e); err != nil {
				t.Fatalf("CreateNIC(%d, _): %s", nicID1, err)
			}
			if err := s.AddAddressWithPrefix(nicID1, ipv4.ProtocolNumber, utils.Ipv4Addr); err != nil {
				t.Fatalf("AddAddressWithPrefix(%d, %d, %s): %s", nicID1, ipv4.ProtocolNumber, utils.Ipv4Addr, err)
			}
			if err := s.AddAddressWithPrefix(nicID1, ipv6.ProtocolNumber, utils.Ipv6Addr); err != nil {
				t.Fatalf("AddAddressWithPrefix(%d, %d, %s): %s", nicID1, ipv6.ProtocolNumber, utils.Ipv6Addr, err)
			}

			if err := s.CreateNIC(nicID2, loopback.New()); err != nil {
				t.Fatalf("CreateNIC(%d, _): %s", nicID2, err)
			}
			if err := s.AddAddress(nicID2, ipv4.ProtocolNumber, ipv4Loopback); err != nil {
				t.Fatalf("AddAddress(%d, %d, %s): %s", nicID2, ipv4.ProtocolNumber, ipv4Loopback, err)
			}
			if err := s.AddAddress(nicID2, ipv6.ProtocolNumber, header.IPv6Loopback); err != nil {
				t.Fatalf("AddAddress(%d, %d, %s): %s", nicID2, ipv6.ProtocolNumber, header.IPv6Loopback, err)
			}

			if test.forwarding {
				if err := s.SetForwarding(ipv4.ProtocolNumber, true); err != nil {
					t.Fatalf("SetForwarding(%d, true): %s", ipv4.ProtocolNumber, err)
				}
				if err := s.SetForwarding(ipv6.ProtocolNumber, true); err != nil {
					t.Fatalf("SetForwarding(%d, true): %s", ipv6.ProtocolNumber, err)
				}
			}

			s.SetRouteTable([]tcpip.Route{
				tcpip.Route{
					Destination: header.IPv4EmptySubnet,
					NIC:         nicID1,
				},
				tcpip.Route{
					Destination: header.IPv6EmptySubnet,
					NIC:         nicID1,
				},
				tcpip.Route{
					Destination: ipv4Loopback.WithPrefix().Subnet(),
					NIC:         nicID2,
				},
				tcpip.Route{
					Destination: header.IPv6Loopback.WithPrefix().Subnet(),
					NIC:         nicID2,
				},
			})

			stats := s.Stats().IP
			invalidAddressStat := test.invalidAddressStat(stats)
			deliveredPacketsStat := stats.PacketsDelivered
			if got := invalidAddressStat.Value(); got != 0 {
				t.Fatalf("got invalidAddressStat.Value() = %d, want = 0", got)
			}
			if got := deliveredPacketsStat.Value(); got != 0 {
				t.Fatalf("got deliveredPacketsStat.Value() = %d, want = 0", got)
			}
			test.rxICMP(e)
			var expectedInvalidPackets uint64
			if !test.shouldAccept {
				expectedInvalidPackets = numPackets
			}
			if got := invalidAddressStat.Value(); got != expectedInvalidPackets {
				t.Fatalf("got invalidAddressStat.Value() = %d, want = %d", got, expectedInvalidPackets)
			}
			if got, want := deliveredPacketsStat.Value(), numPackets-expectedInvalidPackets; got != want {
				t.Fatalf("got deliveredPacketsStat.Value() = %d, want = %d", got, want)
			}
		})
	}
}