-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpacket_test.go
More file actions
3596 lines (3479 loc) · 145 KB
/
Copy pathpacket_test.go
File metadata and controls
3596 lines (3479 loc) · 145 KB
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
package mipstack
import (
"bytes"
"encoding"
"encoding/binary"
"errors"
"fmt"
"net/netip"
"syscall"
"testing"
"time"
)
type binaryAppender interface {
AppendBinary([]byte) ([]byte, error)
}
var (
_ encoding.BinaryMarshaler = IPPacket{}
_ encoding.BinaryMarshaler = TCPSegment{}
_ encoding.BinaryMarshaler = UDPDatagram{}
_ encoding.BinaryMarshaler = ICMPMessage{}
_ binaryAppender = IPPacket{}
_ binaryAppender = TCPSegment{}
_ binaryAppender = UDPDatagram{}
_ binaryAppender = ICMPMessage{}
)
func referenceChecksum(data []byte) uint16 {
var sum uint32
for len(data) >= 2 {
sum += uint32(data[0])<<8 | uint32(data[1])
data = data[2:]
}
if len(data) != 0 {
sum += uint32(data[0]) << 8
}
for sum>>16 != 0 {
sum = sum&0xffff + sum>>16
}
return ^uint16(sum)
}
// referenceTransportChecksum constructs only the RFC pseudo-header around the
// byte-at-a-time referenceChecksum oracle. It is independent of mipstack's
// word-at-a-time checksum and transport encoders.
func referenceTransportChecksum(source, destination netip.Addr, protocol byte, payload []byte) uint16 {
source, destination = source.Unmap(), destination.Unmap()
pseudoHeader := make([]byte, 0, 40+len(payload))
pseudoHeader = append(pseudoHeader, source.AsSlice()...)
pseudoHeader = append(pseudoHeader, destination.AsSlice()...)
if source.Is4() {
pseudoHeader = append(pseudoHeader, 0, protocol, byte(len(payload)>>8), byte(len(payload)))
} else {
length := uint32(len(payload))
pseudoHeader = append(pseudoHeader,
byte(length>>24), byte(length>>16), byte(length>>8), byte(length), 0, 0, 0, protocol)
}
pseudoHeader = append(pseudoHeader, payload...)
return referenceChecksum(pseudoHeader)
}
func TestChecksumRFC1071KnownAnswers(t *testing.T) {
data := mustCodecVector(t, "0001f203f4f5f6f7")
if got := referenceChecksum(data); got != 0x220d {
t.Fatalf("reference checksum = %#x, want %#x", got, uint16(0x220d))
}
if got := checksum(data); got != 0x220d {
t.Fatalf("checksum = %#x, want %#x", got, uint16(0x220d))
}
withChecksum := mustCodecVector(t, "0001f203f4f5f6f7220d")
if got := referenceChecksum(withChecksum); got != 0 {
t.Fatalf("reference checksum over checksummed RFC vector = %#x, want zero", got)
}
if got := checksum(withChecksum); got != 0 {
t.Fatalf("checksum over checksummed RFC vector = %#x, want zero", got)
}
}
func TestPublicIPPacketCodecKnownAnswerMutations(t *testing.T) {
tcp4 := mustCodecVector(t, "4500003c5053400040066665c0000201c0000202"+
"b5fa01bbe3655ed100000000a002faf0e3b40000020405b40402080ad7fe1368000000000103030a")
udp6 := mustCodecVector(t, "67e123450011114020010db800000000000000000000000320010db8000000000000000000000004"+
"ffff30390011600a000102030405060708")
fragment6 := mustCodecVector(t, "622345670020003f20010db800000000000000000000000920010db800000000000000000000000a"+
"2c000502000000000600000110203040000102030405060708090a0b0c0d0e0f")
tests := []struct {
name string
base []byte
mutate func([]byte)
}{
{name: "IPv4 version", base: tcp4, mutate: func(wire []byte) { wire[0] = 0x55 }},
{name: "IPv4 short IHL", base: tcp4, mutate: func(wire []byte) { wire[0] = 0x44 }},
{name: "IPv4 total length below header", base: tcp4, mutate: func(wire []byte) {
binary.BigEndian.PutUint16(wire[2:4], 19)
repairReferenceIPv4Checksum(wire)
}},
{name: "IPv4 reserved fragment bit", base: tcp4, mutate: func(wire []byte) {
wire[6] |= 0x80
repairReferenceIPv4Checksum(wire)
}},
{name: "IPv4 checksum", base: tcp4, mutate: func(wire []byte) { wire[8] ^= 1 }},
{name: "IPv6 declared length", base: udp6, mutate: func(wire []byte) {
binary.BigEndian.PutUint16(wire[4:6], binary.BigEndian.Uint16(wire[4:6])+1)
}},
{name: "IPv6 extension length", base: fragment6, mutate: func(wire []byte) { wire[41] = 0xff }},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
wire := append([]byte(nil), test.base...)
test.mutate(wire)
before := append([]byte(nil), wire...)
if _, err := ParseIPPacket(wire); !errors.Is(err, syscall.EINVAL) {
t.Fatalf("ParseIPPacket error = %v, want EINVAL", err)
}
if !bytes.Equal(wire, before) {
t.Fatal("failed ParseIPPacket modified its input")
}
})
}
}
func TestPublicIPPacketCodecKnownAnswers(t *testing.T) {
tests := []struct {
name string
wire string
packet IPPacket
}{
{
name: "Linux IPv4 TCP SYN",
wire: "4500003c5053400040066665c0000201c0000202" +
"b5fa01bbe3655ed100000000a002faf0e3b40000" +
"020405b40402080ad7fe1368000000000103030a",
packet: IPPacket{
Source: netip.MustParseAddr("192.0.2.1"), Destination: netip.MustParseAddr("192.0.2.2"),
Protocol: ProtocolTCP, HopLimit: 64, Identification: 0x5053, DontFragment: true,
Payload: mustCodecVector(t, "b5fa01bbe3655ed100000000a002faf0e3b40000"+
"020405b40402080ad7fe1368000000000103030a"),
},
},
{
name: "IPv6 TCP odd payload",
wire: "6ab543210025062520010db8000000000000000000000001" +
"20010db8000000000000000000000002" +
"5ba020fb01020304a0b0c0d080184567d9560000" +
"0101080a11223344556677880102030405",
packet: IPPacket{
Source: netip.MustParseAddr("2001:db8::1"), Destination: netip.MustParseAddr("2001:db8::2"),
Protocol: ProtocolTCP, HopLimit: 37, TrafficClass: 0xab, FlowLabel: 0x54321,
Payload: mustCodecVector(t, "5ba020fb01020304a0b0c0d080184567d9560000"+
"0101080a11223344556677880102030405"),
},
},
{
name: "IPv4 TCP SACK",
wire: "45000048999940004006b4dfc6336402c0000201" +
"01bbb5fa1111111122222222d0101000562e0000" +
"0101080a01020304050607080101051200001000000020000000300000004000",
packet: IPPacket{
Source: netip.MustParseAddr("198.51.100.2"), Destination: netip.MustParseAddr("192.0.2.1"),
Protocol: ProtocolTCP, HopLimit: 64, Identification: 0x9999, DontFragment: true,
Payload: mustCodecVector(t, "01bbb5fa1111111122222222d0101000562e0000"+
"0101080a01020304050607080101051200001000000020000000300000004000"),
},
},
{
name: "IPv4 UDP odd payload",
wire: "452e0023123440003711452dc0000203c6336404" + "14e90035000ff26d00010203040506",
packet: IPPacket{
Source: netip.MustParseAddr("192.0.2.3"), Destination: netip.MustParseAddr("198.51.100.4"),
Protocol: ProtocolUDP, HopLimit: 55, TrafficClass: 0x2e, Identification: 0x1234, DontFragment: true,
Payload: mustCodecVector(t, "14e90035000ff26d00010203040506"),
},
},
{
name: "IPv4 UDP zero checksum",
wire: "45000021abcd00004011e2bfc0000205c6336406" + "30390035000d000068656c6c6f",
packet: IPPacket{
Source: netip.MustParseAddr("192.0.2.5"), Destination: netip.MustParseAddr("198.51.100.6"),
Protocol: ProtocolUDP, HopLimit: 64, Identification: 0xabcd,
Payload: mustCodecVector(t, "30390035000d000068656c6c6f"),
},
},
{
name: "IPv4 options and odd payload",
wire: "47030021beef400011fd2a55cb007101cb007102" + "0194040000000000deadbeef01",
packet: IPPacket{
Source: netip.MustParseAddr("203.0.113.1"), Destination: netip.MustParseAddr("203.0.113.2"),
Protocol: 253, HopLimit: 17, TrafficClass: 3, Identification: 0xbeef, DontFragment: true,
IPv4Options: mustCodecVector(t, "0194040000000000"), Payload: mustCodecVector(t, "deadbeef01"),
},
},
{
name: "IPv6 UDP odd payload",
wire: "67e123450011114020010db8000000000000000000000003" +
"20010db8000000000000000000000004" + "ffff30390011600a000102030405060708",
packet: IPPacket{
Source: netip.MustParseAddr("2001:db8::3"), Destination: netip.MustParseAddr("2001:db8::4"),
Protocol: ProtocolUDP, HopLimit: 64, TrafficClass: 0x7e, FlowLabel: 0x12345,
Payload: mustCodecVector(t, "ffff30390011600a000102030405060708"),
},
},
{
name: "Linux IPv4 ICMP Echo",
wire: "45000025ff4740004001b78cc0000201c0000202" + "080039bfaa2f0001000102030405060708",
packet: IPPacket{
Source: netip.MustParseAddr("192.0.2.1"), Destination: netip.MustParseAddr("192.0.2.2"),
Protocol: ProtocolICMPv4, HopLimit: 64, Identification: 0xff47, DontFragment: true,
Payload: mustCodecVector(t, "080039bfaa2f0001000102030405060708"),
},
},
{
name: "IPv6 ICMP Echo odd payload",
wire: "6000000000113aff20010db8000000000000000000000005" +
"20010db8000000000000000000000006" + "8000a77a12345678000102030405060708",
packet: IPPacket{
Source: netip.MustParseAddr("2001:db8::5"), Destination: netip.MustParseAddr("2001:db8::6"),
Protocol: ProtocolICMPv6, HopLimit: 255,
Payload: mustCodecVector(t, "8000a77a12345678000102030405060708"),
},
},
{
name: "IPv4 first fragment",
wire: "45000024778820001ffd170dc000020ac633640a" + "000102030405060708090a0b0c0d0e0f",
packet: IPPacket{
Source: netip.MustParseAddr("192.0.2.10"), Destination: netip.MustParseAddr("198.51.100.10"),
Protocol: 253, HopLimit: 31, Identification: 0x7788, MoreFragments: true,
Payload: mustCodecVector(t, "000102030405060708090a0b0c0d0e0f"),
},
},
{
name: "IPv4 last fragment",
wire: "45000019778800021ffd3716c000020ac633640a1011121314",
packet: IPPacket{
Source: netip.MustParseAddr("192.0.2.10"), Destination: netip.MustParseAddr("198.51.100.10"),
Protocol: 253, HopLimit: 31, Identification: 0x7788, FragmentOffset: 16,
Payload: mustCodecVector(t, "1011121314"),
},
},
{
name: "IPv6 atomic fragment",
wire: "655abcde00162c4020010db8000000000000000000000007" +
"20010db8000000000000000000000008" + "11000000deadbeef9c409c41000e318a61746f6d6963",
packet: IPPacket{
Source: netip.MustParseAddr("2001:db8::7"), Destination: netip.MustParseAddr("2001:db8::8"),
Protocol: IPv6ExtensionHeaderFragment, HopLimit: 64, TrafficClass: 0x55, FlowLabel: 0xabcde,
Payload: mustCodecVector(t, "11000000deadbeef9c409c41000e318a61746f6d6963"),
},
},
{
name: "IPv6 Hop-by-Hop first fragment",
wire: "622345670020003f20010db8000000000000000000000009" +
"20010db800000000000000000000000a" +
"2c000502000000000600000110203040000102030405060708090a0b0c0d0e0f",
packet: IPPacket{
Source: netip.MustParseAddr("2001:db8::9"), Destination: netip.MustParseAddr("2001:db8::a"),
Protocol: IPv6ExtensionHeaderHopByHop, HopLimit: 63, TrafficClass: 0x22, FlowLabel: 0x34567,
Payload: mustCodecVector(t, "2c000502000000000600000110203040000102030405060708090a0b0c0d0e0f"),
},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
wire := mustCodecVector(t, test.wire)
before := append([]byte(nil), wire...)
packet, err := ParseIPPacket(wire)
if err != nil {
t.Fatalf("ParseIPPacket: %v", err)
}
if !bytes.Equal(wire, before) {
t.Fatal("ParseIPPacket modified the known-answer input")
}
if !equalIPPackets(packet, test.packet) {
t.Fatalf("parsed packet = %+v, want %+v", packet, test.packet)
}
encoded, err := test.packet.MarshalBinary()
if err != nil || !bytes.Equal(encoded, wire) {
t.Fatalf("MarshalBinary: error=%v\n got %x\nwant %x", err, encoded, wire)
}
if packet.Source.Is4() {
headerSize := int(wire[0]&0x0f) * 4
if got := referenceChecksum(wire[:headerSize]); got != 0 {
t.Fatalf("IPv4 header reference checksum = %#x, want zero", got)
}
}
})
}
optionPacket, err := ParseIPPacket(mustCodecVector(t,
"47030021beef400011fd2a55cb007101cb0071020194040000000000deadbeef01"))
if err != nil {
t.Fatal(err)
}
options, err := optionPacket.IPv4HeaderOptions()
if err != nil || len(options) != 3 || options[0].Type != IPv4HeaderOptionNOP ||
options[1].Type != IPv4HeaderOptionRouterAlert || options[2].Type != IPv4HeaderOptionEnd {
t.Fatalf("IPv4HeaderOptions = %+v, %v", options, err)
}
if alert, ok := options[1].RouterAlert(); !ok || alert != 0 {
t.Fatalf("IPv4 Router Alert = %d/%t", alert, ok)
}
}
// repairReferenceIPv4Checksum isolates one malformed field from the IPv4
// checksum gate in mutation tests.
func repairReferenceIPv4Checksum(wire []byte) {
headerSize := int(wire[0]&0x0f) * 4
wire[10], wire[11] = 0, 0
binary.BigEndian.PutUint16(wire[10:12], referenceChecksum(wire[:headerSize]))
}
// repairReferenceTransportChecksum isolates a transport mutation from its
// pseudo-header checksum gate.
func repairReferenceTransportChecksum(source, destination netip.Addr, protocol byte, payload []byte, offset int) {
payload[offset], payload[offset+1] = 0, 0
value := referenceTransportChecksum(source, destination, protocol, payload)
if protocol == ProtocolUDP && value == 0 {
value = 0xffff
}
binary.BigEndian.PutUint16(payload[offset:offset+2], value)
}
// FuzzPublicIPPacketWireEncoding drives valid semantic fields into both fixed
// IP header formats and checks the resulting wire fields independently.
func FuzzPublicIPPacketWireEncoding(f *testing.F) {
f.Add(false, byte(99), byte(64), byte(0x2e), uint32(0), uint16(0x1234), true, byte(0), []byte("IPv4 payload"))
f.Add(true, byte(253), byte(1), byte(0xab), uint32(0x54321), uint16(0), false, byte(0), []byte("IPv6 payload"))
f.Fuzz(func(t *testing.T, ipv6 bool, protocol, hopLimit, trafficClass byte, flowLabel uint32,
identification uint16, dontFragment bool, optionForm byte, payload []byte) {
if len(payload) > 4096 {
payload = payload[:4096]
}
packet := IPPacket{
Source: netip.MustParseAddr("192.0.2.101"), Destination: netip.MustParseAddr("198.51.100.101"),
Protocol: int(protocol), HopLimit: int(hopLimit), TrafficClass: int(trafficClass),
Identification: identification, DontFragment: dontFragment, Payload: payload,
}
switch optionForm % 4 {
case 1:
packet.IPv4Options = []byte{IPv4HeaderOptionNOP}
case 2:
packet.IPv4Options = []byte{IPv4HeaderOptionRouterAlert, 4, 0, 0}
case 3:
packet.IPv4Options = []byte{IPv4HeaderOptionEnd, 0xaa, 0xbb}
}
if ipv6 {
packet.Source = netip.MustParseAddr("2001:db8::101")
packet.Destination = netip.MustParseAddr("2001:db8:1::101")
packet.FlowLabel = flowLabel & ipv6MaximumFlowLabel
packet.Identification, packet.DontFragment, packet.IPv4Options = 0, false, nil
switch packet.Protocol {
case IPv6ExtensionHeaderHopByHop, IPv6ExtensionHeaderRouting, IPv6ExtensionHeaderFragment,
IPv6ExtensionHeaderAuthentication, IPv6ExtensionHeaderDestination, IPv6ExtensionHeaderMobility:
// Arbitrary bytes do not form a valid extension header. Dedicated
// extension fuzzers cover those protocol values with framed input.
packet.Protocol = 253
}
}
wire, err := packet.AppendBinary(nil)
if err != nil {
t.Fatalf("AppendBinary: %v (IPv6=%t protocol=%d hop=%d traffic=%d flow=%#x identification=%d DF=%t optionForm=%d options=%x payload=%d)",
err, ipv6, protocol, hopLimit, trafficClass, flowLabel, identification, dontFragment,
optionForm, packet.IPv4Options, len(payload))
}
assertIPPacketWire(t, packet, wire)
parsed, err := ParseIPPacket(wire)
if err != nil {
t.Fatalf("ParseIPPacket(encoded packet): %v", err)
}
if parsed.Source != packet.Source || parsed.Destination != packet.Destination ||
parsed.Protocol != packet.Protocol || parsed.HopLimit != packet.HopLimit ||
parsed.TrafficClass != packet.TrafficClass || parsed.FlowLabel != packet.FlowLabel ||
parsed.Identification != packet.Identification || parsed.DontFragment != packet.DontFragment ||
!bytes.Equal(parsed.Payload, packet.Payload) {
t.Fatalf("parsed encoded packet = %+v, want fields from %+v", parsed, packet)
}
})
}
// equalIPPackets compares semantic slice contents, treating nil and empty
// borrowed views alike.
func equalIPPackets(left, right IPPacket) bool {
return left.Source == right.Source && left.Destination == right.Destination &&
left.Protocol == right.Protocol && left.HopLimit == right.HopLimit &&
left.TrafficClass == right.TrafficClass && left.FlowLabel == right.FlowLabel &&
left.Identification == right.Identification && left.DontFragment == right.DontFragment &&
left.MoreFragments == right.MoreFragments && left.FragmentOffset == right.FragmentOffset &&
bytes.Equal(left.IPv4Options, right.IPv4Options) && bytes.Equal(left.Payload, right.Payload)
}
// assertIPPacketWire compares every fixed IP field, canonical padding, payload,
// and the IPv4 checksum without parsing through the production codec.
func assertIPPacketWire(t testing.TB, packet IPPacket, wire []byte) {
t.Helper()
if packet.Source.Unmap().Is4() {
headerSize := 20 + (len(packet.IPv4Options)+3)&^3
if len(wire) != headerSize+len(packet.Payload) || wire[0] != 0x40|byte(headerSize/4) ||
wire[1] != byte(packet.TrafficClass) || int(binary.BigEndian.Uint16(wire[2:4])) != len(wire) ||
binary.BigEndian.Uint16(wire[4:6]) != packet.Identification || wire[8] != byte(packet.HopLimit) ||
wire[9] != byte(packet.Protocol) || !bytes.Equal(wire[12:16], packet.Source.Unmap().AsSlice()) ||
!bytes.Equal(wire[16:20], packet.Destination.Unmap().AsSlice()) {
t.Fatalf("IPv4 fixed header does not match semantic value: %x", wire[:20])
}
fragment := uint16(packet.FragmentOffset / 8)
if packet.DontFragment {
fragment |= 0x4000
}
if packet.MoreFragments {
fragment |= 0x2000
}
if binary.BigEndian.Uint16(wire[6:8]) != fragment || referenceChecksum(wire[:headerSize]) != 0 {
t.Fatalf("IPv4 fragment/checksum fields are invalid: %x", wire[:headerSize])
}
contentSize := len(packet.IPv4Options)
for offset := 0; offset < len(packet.IPv4Options); {
optionType := packet.IPv4Options[offset]
if optionType == IPv4HeaderOptionEnd {
contentSize = offset + 1
break
}
if optionType == IPv4HeaderOptionNOP {
offset++
} else {
offset += int(packet.IPv4Options[offset+1])
}
}
if !bytes.Equal(wire[20:20+contentSize], packet.IPv4Options[:contentSize]) {
t.Fatalf("IPv4 options = %x, want prefix %x", wire[20:headerSize], packet.IPv4Options[:contentSize])
}
for _, value := range wire[20+contentSize : headerSize] {
if value != 0 {
t.Fatalf("IPv4 option padding is nonzero: %x", wire[20:headerSize])
}
}
if !bytes.Equal(wire[headerSize:], packet.Payload) {
t.Fatalf("IPv4 payload = %x, want %x", wire[headerSize:], packet.Payload)
}
return
}
if len(wire) != 40+len(packet.Payload) || wire[0]>>4 != 6 ||
int(wire[0]&0x0f)<<4|int(wire[1]>>4) != packet.TrafficClass ||
uint32(wire[1]&0x0f)<<16|uint32(binary.BigEndian.Uint16(wire[2:4])) != packet.FlowLabel ||
int(binary.BigEndian.Uint16(wire[4:6])) != len(packet.Payload) || wire[6] != byte(packet.Protocol) ||
wire[7] != byte(packet.HopLimit) || !bytes.Equal(wire[8:24], packet.Source.AsSlice()) ||
!bytes.Equal(wire[24:40], packet.Destination.AsSlice()) || !bytes.Equal(wire[40:], packet.Payload) {
t.Fatalf("IPv6 wire does not match semantic value: %x", wire)
}
}
func TestChecksumMatchesReference(t *testing.T) {
data := make([]byte, 65535)
for index := range data {
data[index] = byte(index*37 + 11)
}
for _, size := range []int{0, 1, 2, 3, 7, 8, 15, 16, 17, 31, 32, 33, 1500, 65534, 65535} {
if got, want := checksum(data[:size]), referenceChecksum(data[:size]); got != want {
t.Fatalf("checksum at length %d = %#x, want %#x", size, got, want)
}
}
}
func TestTransportChecksumMatchesReference(t *testing.T) {
payload := make([]byte, 65535)
for index := range payload {
payload[index] = byte(index*53 + 17)
}
for _, test := range []struct {
name string
source, target netip.Addr
}{
{"IPv4", netip.MustParseAddr("192.0.2.129"), netip.MustParseAddr("198.51.100.231")},
{"IPv6", netip.MustParseAddr("2001:db8:ffff:1::abcd"), netip.MustParseAddr("fdff:ffff:ffff:ffff::1234")},
} {
for _, size := range []int{0, 1, 7, 8, 15, 16, 17, 1500, 65535} {
if got, want := transportChecksum(test.source, test.target, ProtocolTCP, payload[:size]), referenceTransportChecksum(test.source, test.target, ProtocolTCP, payload[:size]); got != want {
t.Fatalf("%s transport checksum at length %d = %#x, want %#x", test.name, size, got, want)
}
}
}
}
func TestTransportChecksumPartsMatchesContiguousPayload(t *testing.T) {
payload := make([]byte, 257)
for index := range payload {
payload[index] = byte(index*29 + 7)
}
for _, addresses := range [][2]netip.Addr{
{netip.MustParseAddr("192.0.2.17"), netip.MustParseAddr("198.51.100.17")},
{netip.MustParseAddr("2001:db8::17"), netip.MustParseAddr("2001:db8:1::17")},
} {
want := transportChecksum(addresses[0], addresses[1], ProtocolUDP, payload)
for split := 0; split <= len(payload); split++ {
if got := transportChecksumParts(addresses[0], addresses[1], ProtocolUDP, len(payload), payload[:split], payload[split:]); got != want {
t.Fatalf("%s split %d checksum = %#x, want %#x", addresses[0], split, got, want)
}
}
}
}
func TestPublicIPPacketCodec(t *testing.T) {
tests := []IPPacket{
{
Source: netip.MustParseAddr("192.0.2.10"), Destination: netip.MustParseAddr("198.51.100.20"),
Protocol: 99, HopLimit: 0, TrafficClass: 0xab, Identification: 0x1234, DontFragment: true,
IPv4Options: []byte{1, 148, 4, 0, 0}, Payload: []byte("ipv4-codec-payload"),
},
{
Source: netip.MustParseAddr("2001:db8::10"), Destination: netip.MustParseAddr("2001:db8::20"),
Protocol: 60, HopLimit: 0, TrafficClass: 0xab, FlowLabel: 0xabcde,
Payload: append([]byte{99, 0, 0x80, 0, 0, 0, 0, 0}, []byte("ipv6-upper-layer")...),
},
}
for _, test := range tests {
name := "IPv4"
if test.Source.Is6() {
name = "IPv6"
}
t.Run(name, func(t *testing.T) {
prefix := []byte{0xaa, 0xbb, 0xcc}
wire, err := test.AppendBinary(append([]byte(nil), prefix...))
if err != nil {
t.Fatalf("append packet: %v", err)
}
if !bytes.Equal(wire[:len(prefix)], prefix) {
t.Fatal("AppendBinary changed the destination prefix")
}
wire = wire[len(prefix):]
parsed, err := ParseIPPacket(wire)
if err != nil {
t.Fatalf("parse packet: %v", err)
}
if parsed.Source != test.Source || parsed.Destination != test.Destination || parsed.Protocol != test.Protocol || parsed.HopLimit != 0 || parsed.TrafficClass != test.TrafficClass || parsed.FlowLabel != test.FlowLabel || parsed.Identification != test.Identification || parsed.DontFragment != test.DontFragment {
t.Fatalf("parsed packet metadata = %+v, want %+v", parsed, test)
}
protocol, upper, err := parsed.UpperLayer()
if err != nil {
t.Fatalf("locate upper layer: %v", err)
}
wantProtocol, wantUpper := test.Protocol, test.Payload
if test.Source.Is6() {
wantProtocol, wantUpper = 99, test.Payload[8:]
}
if protocol != wantProtocol || !bytes.Equal(upper, wantUpper) {
t.Fatalf("upper layer = protocol %d payload %x, want %d %x", protocol, upper, wantProtocol, wantUpper)
}
roundTrip, err := parsed.MarshalBinary()
if err != nil || !bytes.Equal(roundTrip, wire) {
t.Fatalf("packet round trip: error=%v\n got %x\nwant %x", err, roundTrip, wire)
}
inPlace := append([]byte(nil), wire...)
inPlacePacket, err := ParseIPPacket(inPlace)
if err != nil {
t.Fatal(err)
}
inPlaceResult, appendErr := inPlacePacket.AppendBinary(inPlace[:0])
if appendErr != nil || len(inPlaceResult) == 0 || &inPlaceResult[0] != &inPlace[0] || !bytes.Equal(inPlaceResult, wire) {
t.Fatalf("in-place packet round trip: error=%v\n got %x\nwant %x", appendErr, inPlaceResult, wire)
}
})
}
}
func TestPublicRawIPPacketCodec(t *testing.T) {
tests := []IPPacket{
{
Source: netip.MustParseAddr("192.0.2.30"), Destination: netip.MustParseAddr("198.51.100.30"),
Protocol: 99, HopLimit: 31, TrafficClass: 0x2e, Identification: 0x1234,
IPv4Options: []byte{IPv4HeaderOptionNOP}, Payload: []byte("raw-ipv4-payload"),
},
{
Source: netip.MustParseAddr("2001:db8::30"), Destination: netip.MustParseAddr("2001:db8::31"),
Protocol: 99, HopLimit: 32, TrafficClass: 0x03, FlowLabel: 0x12345,
Payload: []byte("raw-ipv6-payload"),
},
}
for _, packet := range tests {
strict, err := packet.MarshalBinary()
if err != nil {
t.Fatal(err)
}
prefix := []byte{0xaa, 0xbb, 0xcc}
raw, err := packet.AppendRawBinary(append([]byte(nil), prefix...))
if err != nil {
t.Fatalf("append raw packet: %v", err)
}
if !bytes.Equal(raw[:len(prefix)], prefix) || !bytes.Equal(raw[len(prefix):], strict) {
t.Fatalf("raw packet differs from strict encoding:\n raw %x\nstrict %x", raw[len(prefix):], strict)
}
}
fragment := IPv6ExtensionHeader{
Type: IPv6ExtensionHeaderFragment,
Data: []byte{0x7f, 0, 0x06, 0x12, 0x34, 0x56, 0x78},
}
packet := IPPacket{
Source: netip.MustParseAddr("2001:db8::32"), Destination: netip.MustParseAddr("2001:db8::33"), HopLimit: 64,
}
if err := packet.SetRawIPv6ExtensionHeaders([]IPv6ExtensionHeader{fragment}, 99, []byte("opaque")); err != nil {
t.Fatal(err)
}
raw, err := packet.MarshalRawBinary()
if err != nil {
t.Fatalf("marshal reserved raw Fragment fields: %v", err)
}
if !bytes.Equal(raw[40:], packet.Payload) {
t.Fatalf("raw payload = %x, want %x", raw[40:], packet.Payload)
}
strict, err := packet.MarshalBinary()
if err != nil {
t.Fatalf("marshal strict atomic Fragment: %v", err)
}
if strict[41] != 0 || binary.BigEndian.Uint16(strict[42:44]) != 0 {
t.Fatalf("strict Fragment reserved fields = %x", strict[40:44])
}
if raw[41] != 0x7f || binary.BigEndian.Uint16(raw[42:44]) != 0x0006 {
t.Fatalf("raw Fragment reserved fields = %x", raw[40:44])
}
wantRaw := append([]byte(nil), raw...)
inPlace := append([]byte(nil), raw...)
packet.Payload = inPlace[40:]
inPlace, err = packet.AppendRawBinary(inPlace[:0])
if err != nil || !bytes.Equal(inPlace, wantRaw) {
t.Fatalf("in-place raw packet: error=%v\n got %x\nwant %x", err, inPlace, wantRaw)
}
malformed := IPPacket{
Source: netip.MustParseAddr("192.0.2.34"), Destination: netip.MustParseAddr("198.51.100.34"),
Protocol: 99, HopLimit: 64, IPv4Options: []byte{30, 1, 0xaa}, Payload: []byte("malformed-option"),
}
if _, err = malformed.MarshalBinary(); !errors.Is(err, syscall.EINVAL) {
t.Fatalf("strict malformed IPv4 option error = %v", err)
}
raw, err = malformed.MarshalRawBinary()
if err != nil {
t.Fatalf("marshal raw malformed IPv4 option: %v", err)
}
if !bytes.Equal(raw[20:24], []byte{30, 1, 0xaa, 0}) || InternetChecksum(raw[:24]) != 0 {
t.Fatalf("raw malformed IPv4 option packet = %x", raw)
}
if _, err = ParseIPPacket(raw); !errors.Is(err, syscall.EINVAL) {
t.Fatalf("parse malformed raw IPv4 option error = %v", err)
}
}
func TestPublicIPv4HeaderOptions(t *testing.T) {
data := []byte{0xaa, 0xbb}
options := []IPv4HeaderOption{
{Type: IPv4HeaderOptionNOP},
{Type: IPv4HeaderOptionRouterAlert, Data: []byte{0, 0}},
{Type: 30, Data: data},
{Type: 30, Data: []byte{0xcc}},
{Type: IPv4HeaderOptionEnd},
}
packet := IPPacket{
Source: netip.MustParseAddr("192.0.2.1"), Destination: netip.MustParseAddr("198.51.100.1"),
Protocol: 99, HopLimit: 64, Payload: []byte("structured-ipv4-options"),
}
if err := packet.SetIPv4HeaderOptions(options); err != nil {
t.Fatalf("SetIPv4HeaderOptions: %v", err)
}
wantOptions := append([]byte(nil), packet.IPv4Options...)
if literal := mustCodecVector(t, "01940400001e04aabb1e03cc00"); !bytes.Equal(wantOptions, literal) {
t.Fatalf("structured IPv4 option wire = %x, want %x", wantOptions, literal)
}
data[0] ^= 0xff
if !bytes.Equal(packet.IPv4Options, wantOptions) {
t.Fatal("SetIPv4HeaderOptions retained caller storage")
}
parsed, err := packet.IPv4HeaderOptions()
if err != nil {
t.Fatalf("IPv4HeaderOptions: %v", err)
}
if len(parsed) != len(options) || parsed[0].Type != IPv4HeaderOptionNOP ||
parsed[1].Type != IPv4HeaderOptionRouterAlert || !bytes.Equal(parsed[1].Data, []byte{0, 0}) ||
parsed[2].Type != 30 || parsed[3].Type != 30 || parsed[4].Type != IPv4HeaderOptionEnd {
t.Fatalf("parsed IPv4 options = %+v", parsed)
}
sourceRoute := IPv4HeaderOption{Type: IPv4HeaderOptionLooseSourceRoute}
if !sourceRoute.Copied() || sourceRoute.Class() != 0 || sourceRoute.Number() != 3 {
t.Fatalf("source-route type fields = copied %t class %d number %d", sourceRoute.Copied(), sourceRoute.Class(), sourceRoute.Number())
}
copyPacket := packet
if err = copyPacket.SetIPv4HeaderOptions(parsed); err != nil {
t.Fatalf("copy parsed IPv4 options: %v", err)
}
parsed[2].Data[0] ^= 0xff
if packet.IPv4Options[7] != 0x55 {
t.Fatal("IPv4HeaderOptions Data did not borrow IPv4Options")
}
if !bytes.Equal(copyPacket.IPv4Options, wantOptions) {
t.Fatal("SetIPv4HeaderOptions did not copy parsed Data")
}
wire, err := copyPacket.AppendBinary(nil)
if err != nil {
t.Fatalf("encode IPv4 options: %v", err)
}
decoded, err := ParseIPPacket(wire)
if err != nil {
t.Fatalf("decode IPv4 options: %v", err)
}
decodedOptions, err := decoded.IPv4HeaderOptions()
if err != nil || len(decodedOptions) != len(options) {
t.Fatalf("decoded IPv4 options = %+v, %v", decodedOptions, err)
}
}
func TestPublicRouterAlertOptions(t *testing.T) {
for _, value := range []uint16{0, 1, 0xffff} {
t.Run(fmt.Sprintf("value-%d", value), func(t *testing.T) {
ipv4Option := IPv4HeaderOption{Type: IPv4HeaderOptionNOP, Data: []byte{1, 2, 3}}
ipv4Option.SetRouterAlert(value)
if got, ok := ipv4Option.RouterAlert(); !ok || got != value {
t.Fatalf("IPv4 Router Alert = %d/%t, want %d/true", got, ok, value)
}
ipv4Packet := IPPacket{
Source: netip.MustParseAddr("192.0.2.1"), Destination: netip.MustParseAddr("198.51.100.1"),
Protocol: 99, HopLimit: 64, Payload: []byte("router-alert-v4"),
}
if err := ipv4Packet.SetIPv4HeaderOptions([]IPv4HeaderOption{{Type: IPv4HeaderOptionNOP}, ipv4Option}); err != nil {
t.Fatalf("set IPv4 Router Alert: %v", err)
}
wire, err := ipv4Packet.AppendBinary(nil)
if err != nil {
t.Fatalf("encode IPv4 Router Alert: %v", err)
}
parsedPacket, err := ParseIPPacket(wire)
if err != nil {
t.Fatalf("parse IPv4 Router Alert: %v", err)
}
options, err := parsedPacket.IPv4HeaderOptions()
if err != nil || len(options) < 2 {
t.Fatalf("parse IPv4 Router Alert options: %+v, %v", options, err)
}
if got, ok := options[1].RouterAlert(); !ok || got != value {
t.Fatalf("parsed IPv4 Router Alert = %d/%t, want %d/true", got, ok, value)
}
ipv6Option := IPv6ExtensionOption{Type: IPv6ExtensionOptionPad1, Data: []byte{1, 2, 3}}
ipv6Option.SetRouterAlert(value)
if got, ok := ipv6Option.RouterAlert(); !ok || got != value {
t.Fatalf("IPv6 Router Alert = %d/%t, want %d/true", got, ok, value)
}
hopByHop := IPv6ExtensionHeader{Type: IPv6ExtensionHeaderHopByHop}
if err = hopByHop.SetOptions([]IPv6ExtensionOption{ipv6Option}); err != nil {
t.Fatalf("set IPv6 Router Alert: %v", err)
}
ipv6Packet := IPPacket{
Source: netip.MustParseAddr("2001:db8::1"), Destination: netip.MustParseAddr("2001:db8::2"), HopLimit: 64,
}
if err = ipv6Packet.SetIPv6ExtensionHeaders([]IPv6ExtensionHeader{hopByHop}, 99, []byte("router-alert-v6")); err != nil {
t.Fatalf("set IPv6 Router Alert header: %v", err)
}
wire, err = ipv6Packet.AppendBinary(nil)
if err != nil {
t.Fatalf("encode IPv6 Router Alert: %v", err)
}
parsedPacket, err = ParseIPPacket(wire)
if err != nil {
t.Fatalf("parse IPv6 Router Alert: %v", err)
}
headers, _, _, err := parsedPacket.IPv6ExtensionHeaders()
if err != nil || len(headers) != 1 {
t.Fatalf("parse IPv6 Router Alert headers: %+v, %v", headers, err)
}
options6, err := headers[0].Options()
if err != nil || len(options6) < 1 {
t.Fatalf("parse IPv6 Router Alert options: %+v, %v", options6, err)
}
if got, ok := options6[0].RouterAlert(); !ok || got != value {
t.Fatalf("parsed IPv6 Router Alert = %d/%t, want %d/true", got, ok, value)
}
})
}
for index, option := range []IPv4HeaderOption{
{},
{Type: IPv4HeaderOptionRouterAlert},
{Type: IPv4HeaderOptionRouterAlert, Data: []byte{0}},
{Type: IPv4HeaderOptionRouterAlert, Data: []byte{0, 0, 0}},
} {
if value, ok := option.RouterAlert(); ok || value != 0 {
t.Fatalf("malformed IPv4 Router Alert %d was accepted", index)
}
}
for index, option := range []IPv6ExtensionOption{
{},
{Type: IPv6ExtensionOptionRouterAlert},
{Type: IPv6ExtensionOptionRouterAlert, Data: []byte{0}},
{Type: IPv6ExtensionOptionRouterAlert, Data: []byte{0, 0, 0}},
} {
if value, ok := option.RouterAlert(); ok || value != 0 {
t.Fatalf("malformed IPv6 Router Alert %d was accepted", index)
}
}
}
func TestPublicIPv4HeaderOptionErrors(t *testing.T) {
packet := IPPacket{
Source: netip.MustParseAddr("192.0.2.1"), Destination: netip.MustParseAddr("198.51.100.1"),
IPv4Options: []byte{IPv4HeaderOptionNOP},
}
want := append([]byte(nil), packet.IPv4Options...)
tests := []struct {
name string
options []IPv4HeaderOption
wantErr error
}{
{name: "End data", options: []IPv4HeaderOption{{Type: IPv4HeaderOptionEnd, Data: []byte{1}}}, wantErr: syscall.EINVAL},
{name: "NOP data", options: []IPv4HeaderOption{{Type: IPv4HeaderOptionNOP, Data: []byte{1}}}, wantErr: syscall.EINVAL},
{name: "after End", options: []IPv4HeaderOption{{Type: IPv4HeaderOptionEnd}, {Type: IPv4HeaderOptionNOP}}, wantErr: syscall.EINVAL},
{name: "oversized", options: []IPv4HeaderOption{{Type: 30, Data: make([]byte, 39)}}, wantErr: syscall.EMSGSIZE},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if err := packet.SetIPv4HeaderOptions(test.options); !errors.Is(err, test.wantErr) {
t.Fatalf("SetIPv4HeaderOptions error = %v, want %v", err, test.wantErr)
}
if !bytes.Equal(packet.IPv4Options, want) {
t.Fatal("failed SetIPv4HeaderOptions changed the receiver")
}
})
}
for _, raw := range [][]byte{{30}, {30, 1}, make([]byte, 41)} {
packet.IPv4Options = raw
if _, err := packet.IPv4HeaderOptions(); err == nil {
t.Fatalf("IPv4HeaderOptions accepted %x", raw)
}
}
v6 := IPPacket{Source: netip.MustParseAddr("2001:db8::1"), Destination: netip.MustParseAddr("2001:db8::2")}
if _, err := v6.IPv4HeaderOptions(); !errors.Is(err, syscall.EAFNOSUPPORT) {
t.Fatalf("IPv6 IPv4HeaderOptions error = %v", err)
}
if err := v6.SetIPv4HeaderOptions(nil); !errors.Is(err, syscall.EAFNOSUPPORT) {
t.Fatalf("IPv6 SetIPv4HeaderOptions error = %v", err)
}
}
func TestPublicIPv4HeaderOptionsNormalizeEOLPadding(t *testing.T) {
packet := IPPacket{
Source: netip.MustParseAddr("192.0.2.1"), Destination: netip.MustParseAddr("198.51.100.1"),
Protocol: ProtocolUDP, HopLimit: 64,
IPv4Options: []byte{IPv4HeaderOptionEnd, 0xaa, 0xbb, 0xcc}, Payload: make([]byte, udpHeaderSize),
}
wire, err := packet.AppendBinary(nil)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(wire[20:24], []byte{0, 0, 0, 0}) {
t.Fatalf("generated IPv4 EOL padding = %x, want zeros", wire[20:24])
}
raw := append([]byte(nil), wire...)
copy(raw[21:24], []byte{0xaa, 0xbb, 0xcc})
raw[10], raw[11] = 0, 0
binary.BigEndian.PutUint16(raw[10:12], checksum(raw[:24]))
parsed, err := ParseIPPacket(raw)
if err != nil {
t.Fatalf("parse nonzero IPv4 EOL padding: %v", err)
}
if !bytes.Equal(parsed.IPv4Options, raw[20:24]) {
t.Fatalf("parsed IPv4 EOL padding = %x, want %x", parsed.IPv4Options, raw[20:24])
}
options, err := parsed.IPv4HeaderOptions()
if err != nil || len(options) != 1 || options[0].Type != IPv4HeaderOptionEnd {
t.Fatalf("structured IPv4 EOL = %+v, error=%v", options, err)
}
reencoded, err := parsed.AppendBinary(nil)
if err != nil || !bytes.Equal(reencoded, wire) {
t.Fatalf("normalized IPv4 packet: error=%v\n got %x\nwant %x", err, reencoded, wire)
}
wantRaw := append([]byte(nil), raw...)
rawReencoded, err := parsed.AppendRawBinary(nil)
if err != nil || !bytes.Equal(rawReencoded, wantRaw) {
t.Fatalf("raw IPv4 packet round trip: error=%v\n got %x\nwant %x", err, rawReencoded, wantRaw)
}
rawReencoded, err = parsed.AppendRawBinary(raw[:0])
if err != nil || !bytes.Equal(rawReencoded, wantRaw) {
t.Fatalf("in-place raw IPv4 packet round trip: error=%v\n got %x\nwant %x", err, rawReencoded, wantRaw)
}
internal, ok := parseIPPacket(raw)
if !ok || internal.parameterError {
t.Fatalf("runtime parser rejected Linux-compatible EOL padding: %+v, ok=%t", internal, ok)
}
}
func TestPublicIPv6ExtensionHeaders(t *testing.T) {
unknownData := []byte{1, 2, 3}
hop := IPv6ExtensionHeader{Type: IPv6ExtensionHeaderHopByHop}
if err := hop.SetOptions([]IPv6ExtensionOption{
{Type: IPv6ExtensionOptionRouterAlert, Data: []byte{0, 0}},
{Type: 0xe3, Data: unknownData},
{Type: IPv6ExtensionOptionPad1},
}); err != nil {
t.Fatalf("set Hop-by-Hop options: %v", err)
}
wantHop := append([]byte(nil), hop.Data...)
if literal := mustCodecVector(t, "0105020000e3030102030001020000"); !bytes.Equal(wantHop, literal) {
t.Fatalf("structured Hop-by-Hop option wire = %x, want %x", wantHop, literal)
}
unknownData[0] ^= 0xff
if !bytes.Equal(hop.Data, wantHop) {
t.Fatal("SetOptions retained caller storage")
}
options, err := hop.Options()
if err != nil {
t.Fatalf("parse Hop-by-Hop options: %v", err)
}
if len(options) < 3 || options[0].Type != IPv6ExtensionOptionRouterAlert || options[1].Type != 0xe3 ||
options[1].Action() != 3 || !options[1].MayChangeInTransit() || !bytes.Equal(options[1].Data, []byte{1, 2, 3}) {
t.Fatalf("parsed IPv6 options = %+v", options)
}
hopCopy := IPv6ExtensionHeader{Type: IPv6ExtensionHeaderHopByHop}
if err = hopCopy.SetOptions(options); err != nil {
t.Fatalf("copy parsed IPv6 options: %v", err)
}
options[1].Data[0] ^= 0xff
if !bytes.Equal(hopCopy.Data, wantHop) {
t.Fatal("SetOptions did not copy parsed Data")
}
destination := IPv6ExtensionHeader{Type: IPv6ExtensionHeaderDestination}
if err = destination.SetOptions(nil); err != nil {
t.Fatal(err)
}
routing := IPv6ExtensionHeader{Type: IPv6ExtensionHeaderRouting, Data: []byte{0, 0, 0, 0, 0, 0, 0}}
fragment := IPv6ExtensionHeader{Type: IPv6ExtensionHeaderFragment, Data: []byte{0, 0, 0, 0x12, 0x34, 0x56, 0x78}}
authentication := IPv6ExtensionHeader{Type: IPv6ExtensionHeaderAuthentication, Data: make([]byte, 15)}
authentication.Data[0] = 2
mobility := IPv6ExtensionHeader{Type: IPv6ExtensionHeaderMobility, Data: []byte{0, 0, 0, 0, 0, 0, 0}}
headers := []IPv6ExtensionHeader{hopCopy, routing, fragment, authentication, destination, mobility}
payload := []byte("extension-payload")
packet := IPPacket{
Source: netip.MustParseAddr("2001:db8::1"), Destination: netip.MustParseAddr("2001:db8::2"), HopLimit: 64,
}
if err = packet.SetIPv6ExtensionHeaders(headers, 99, payload); err != nil {
t.Fatalf("SetIPv6ExtensionHeaders: %v", err)
}
wantPayload := mustCodecVector(t,
"2b0105020000e3030102030001020000"+
"2c00000000000000"+
"3300000012345678"+
"3c020000000000000000000000000000"+
"8700010400000000"+
"6300000000000000"+
"657874656e73696f6e2d7061796c6f6164")
if packet.Protocol != IPv6ExtensionHeaderHopByHop || !bytes.Equal(packet.Payload, wantPayload) {
t.Fatalf("structured IPv6 extension wire = protocol %d payload %x, want %d/%x",
packet.Protocol, packet.Payload, IPv6ExtensionHeaderHopByHop, wantPayload)
}
headers[1].Data[1] ^= 0xff
payload[0] ^= 0xff
if !bytes.Equal(packet.Payload, wantPayload) {
t.Fatal("SetIPv6ExtensionHeaders retained caller storage")
}
parsedHeaders, protocol, upper, err := packet.IPv6ExtensionHeaders()
if err != nil || protocol != 99 || !bytes.Equal(upper, []byte("extension-payload")) || len(parsedHeaders) != len(headers) {
t.Fatalf("IPv6ExtensionHeaders = %d headers, protocol %d, payload %x, %v", len(parsedHeaders), protocol, upper, err)
}
for index := range headers {
if parsedHeaders[index].Type != headers[index].Type {
t.Fatalf("header %d type = %d, want %d", index, parsedHeaders[index].Type, headers[index].Type)
}
}
if gotProtocol, gotPayload, upperErr := packet.UpperLayer(); upperErr != nil || gotProtocol != 99 || !bytes.Equal(gotPayload, upper) {
t.Fatalf("UpperLayer = %d/%x, %v", gotProtocol, gotPayload, upperErr)
}
wire, err := packet.AppendBinary(nil)
if err != nil {
t.Fatalf("encode extension chain: %v", err)
}
decoded, err := ParseIPPacket(wire)
if err != nil {
t.Fatalf("decode extension chain: %v", err)
}
decodedHeaders, protocol, upper, err := decoded.IPv6ExtensionHeaders()
if err != nil || protocol != 99 || !bytes.Equal(upper, []byte("extension-payload")) || len(decodedHeaders) != len(headers) {
t.Fatalf("decoded extension chain = %d/%d/%x, %v", len(decodedHeaders), protocol, upper, err)
}
noNext := packet
trailing := []byte{1, 2, 3}
if err = noNext.SetIPv6ExtensionHeaders(nil, ProtocolNoNextHeader, trailing); err != nil {
t.Fatal(err)
}
noHeaders, noProtocol, noPayload, err := noNext.IPv6ExtensionHeaders()
if err != nil || len(noHeaders) != 0 || noProtocol != ProtocolNoNextHeader || !bytes.Equal(noPayload, trailing) {
t.Fatalf("No Next Header structural result = %+v/%d/%x, %v", noHeaders, noProtocol, noPayload, err)
}
if _, ignored, err := noNext.UpperLayer(); err != nil || ignored != nil {
t.Fatalf("No Next Header upper payload = %x, %v", ignored, err)
}
}
func TestPublicRawIPv6ExtensionHeaders(t *testing.T) {
destinationData := make([]byte, 7)
hopData := make([]byte, 7)
payload := []byte("raw-extension-payload")
headers := []IPv6ExtensionHeader{
{Type: IPv6ExtensionHeaderDestination, Data: destinationData},
{Type: IPv6ExtensionHeaderHopByHop, Data: hopData},