-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathoption.go
1158 lines (948 loc) · 28.1 KB
/
option.go
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 ndp
import (
"bytes"
"crypto/rand"
"crypto/subtle"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"io"
"math"
"net"
"net/netip"
"net/url"
"strings"
"time"
"unicode"
"golang.org/x/net/idna"
)
// Infinity indicates that a prefix is valid for an infinite amount of time,
// unless a new, finite, value is received in a subsequent router advertisement.
const Infinity = time.Duration(0xffffffff) * time.Second
const (
// Length of a link-layer address for Ethernet networks.
ethAddrLen = 6
// The assumed NDP option length (in units of 8 bytes) for fixed length options.
llaOptLen = 1
piOptLen = 4
mtuOptLen = 1
// Type values for each type of valid Option.
optSourceLLA = 1
optTargetLLA = 2
optPrefixInformation = 3
optMTU = 5
optNonce = 14
optRouteInformation = 24
optRDNSS = 25
optRAFlagsExtension = 26
optDNSSL = 31
optCaptivePortal = 37
optPREF64 = 38
)
// A Direction specifies the direction of a LinkLayerAddress Option as a source
// or target.
type Direction int
// Possible Direction values.
const (
Source Direction = optSourceLLA
Target Direction = optTargetLLA
)
// An Option is a Neighbor Discovery Protocol option.
type Option interface {
// Code specifies the NDP option code for an Option.
Code() uint8
// "Code" as a method name isn't actually accurate because NDP options
// also refer to that field as "Type", but we want to avoid confusion
// with Message implementations which already use Type.
// Called when dealing with a Message's Options.
marshal() ([]byte, error)
unmarshal(b []byte) error
}
var _ Option = &LinkLayerAddress{}
// A LinkLayerAddress is a Source or Target Link-Layer Address option, as
// described in RFC 4861, Section 4.6.1.
type LinkLayerAddress struct {
Direction Direction
Addr net.HardwareAddr
}
// TODO(mdlayher): deal with non-ethernet links and variable option length?
// Code implements Option.
func (lla *LinkLayerAddress) Code() byte { return byte(lla.Direction) }
func (lla *LinkLayerAddress) marshal() ([]byte, error) {
if d := lla.Direction; d != Source && d != Target {
return nil, fmt.Errorf("ndp: invalid link-layer address direction: %d", d)
}
if len(lla.Addr) != ethAddrLen {
return nil, fmt.Errorf("ndp: invalid link-layer address: %q", lla.Addr)
}
raw := &RawOption{
Type: lla.Code(),
Length: llaOptLen,
Value: lla.Addr,
}
return raw.marshal()
}
func (lla *LinkLayerAddress) unmarshal(b []byte) error {
raw := new(RawOption)
if err := raw.unmarshal(b); err != nil {
return err
}
d := Direction(raw.Type)
if d != Source && d != Target {
return fmt.Errorf("ndp: invalid link-layer address direction: %d", d)
}
if l := raw.Length; l != llaOptLen {
return fmt.Errorf("ndp: unexpected link-layer address option length: %d", l)
}
*lla = LinkLayerAddress{
Direction: d,
Addr: net.HardwareAddr(raw.Value),
}
return nil
}
var _ Option = new(MTU)
// An MTU is an MTU option, as described in RFC 4861, Section 4.6.1.
type MTU struct {
MTU uint32
}
// NewMTU creates an MTU Option from an MTU value.
func NewMTU(mtu uint32) *MTU {
return &MTU{MTU: mtu}
}
// Code implements Option.
func (*MTU) Code() byte { return optMTU }
func (m *MTU) marshal() ([]byte, error) {
raw := &RawOption{
Type: m.Code(),
Length: mtuOptLen,
// 2 reserved bytes, 4 for MTU.
Value: make([]byte, 6),
}
binary.BigEndian.PutUint32(raw.Value[2:6], uint32(m.MTU))
return raw.marshal()
}
func (m *MTU) unmarshal(b []byte) error {
raw := new(RawOption)
if err := raw.unmarshal(b); err != nil {
return err
}
*m = MTU{MTU: binary.BigEndian.Uint32(raw.Value[2:6])}
return nil
}
var _ Option = &PrefixInformation{}
// A PrefixInformation is a a Prefix Information option, as described in RFC 4861, Section 4.6.1.
type PrefixInformation struct {
PrefixLength uint8
OnLink bool
AutonomousAddressConfiguration bool
ValidLifetime time.Duration
PreferredLifetime time.Duration
Prefix netip.Addr
}
// Code implements Option.
func (*PrefixInformation) Code() byte { return optPrefixInformation }
func (pi *PrefixInformation) marshal() ([]byte, error) {
// Per the RFC:
// "The bits in the prefix after the prefix length are reserved and MUST
// be initialized to zero by the sender and ignored by the receiver."
//
// Therefore, any prefix, when masked with its specified length, should be
// identical to the prefix itself for it to be valid.
p := netip.PrefixFrom(pi.Prefix, int(pi.PrefixLength))
if masked := p.Masked(); pi.Prefix != masked.Addr() {
return nil, fmt.Errorf("ndp: invalid prefix information: %s/%d",
pi.Prefix, pi.PrefixLength)
}
raw := &RawOption{
Type: pi.Code(),
Length: piOptLen,
// 30 bytes for PrefixInformation body.
Value: make([]byte, 30),
}
raw.Value[0] = pi.PrefixLength
if pi.OnLink {
raw.Value[1] |= (1 << 7)
}
if pi.AutonomousAddressConfiguration {
raw.Value[1] |= (1 << 6)
}
valid := pi.ValidLifetime.Seconds()
binary.BigEndian.PutUint32(raw.Value[2:6], uint32(valid))
pref := pi.PreferredLifetime.Seconds()
binary.BigEndian.PutUint32(raw.Value[6:10], uint32(pref))
// 4 bytes reserved.
copy(raw.Value[14:30], pi.Prefix.AsSlice())
return raw.marshal()
}
func (pi *PrefixInformation) unmarshal(b []byte) error {
raw := new(RawOption)
if err := raw.unmarshal(b); err != nil {
return err
}
// Guard against incorrect option length.
if raw.Length != piOptLen {
return io.ErrUnexpectedEOF
}
var (
oFlag = (raw.Value[1] & 0x80) != 0
aFlag = (raw.Value[1] & 0x40) != 0
valid = time.Duration(binary.BigEndian.Uint32(raw.Value[2:6])) * time.Second
preferred = time.Duration(binary.BigEndian.Uint32(raw.Value[6:10])) * time.Second
)
// Skip to address.
addr := raw.Value[14:30]
ip, ok := netip.AddrFromSlice(addr)
if !ok {
panicf("ndp: invalid IPv6 address slice: %v", addr)
}
if err := checkIPv6(ip); err != nil {
return err
}
// Per the RFC, bits in prefix past prefix length are ignored by the
// receiver.
pl := raw.Value[0]
p := netip.PrefixFrom(ip, int(pl)).Masked()
*pi = PrefixInformation{
PrefixLength: pl,
OnLink: oFlag,
AutonomousAddressConfiguration: aFlag,
ValidLifetime: valid,
PreferredLifetime: preferred,
Prefix: p.Addr(),
}
return nil
}
var _ Option = &RouteInformation{}
// A RouteInformation is a Route Information option, as described in RFC 4191,
// Section 2.3.
type RouteInformation struct {
PrefixLength uint8
Preference Preference
RouteLifetime time.Duration
Prefix netip.Addr
}
// Code implements Option.
func (*RouteInformation) Code() byte { return optRouteInformation }
func (ri *RouteInformation) marshal() ([]byte, error) {
// Per the RFC:
// "The bits in the prefix after the prefix length are reserved and MUST
// be initialized to zero by the sender and ignored by the receiver."
//
// Therefore, any prefix, when masked with its specified length, should be
// identical to the prefix itself for it to be valid.
err := fmt.Errorf("ndp: invalid route information: %s/%d", ri.Prefix, ri.PrefixLength)
p := netip.PrefixFrom(ri.Prefix, int(ri.PrefixLength))
if masked := p.Masked(); ri.Prefix != masked.Addr() {
return nil, err
}
// Depending on the length of the prefix, we can add fewer bytes to the
// option.
var iplen int
switch {
case ri.PrefixLength == 0:
iplen = 0
case ri.PrefixLength > 0 && ri.PrefixLength < 65:
iplen = 1
case ri.PrefixLength > 64 && ri.PrefixLength < 129:
iplen = 2
default:
// Invalid IPv6 prefix.
return nil, err
}
raw := &RawOption{
Type: ri.Code(),
Length: uint8(iplen) + 1,
// Prefix length, preference, lifetime, and prefix body as computed by
// using iplen.
Value: make([]byte, 1+1+4+(iplen*8)),
}
raw.Value[0] = ri.PrefixLength
// Adjacent bits are reserved.
if prf := uint8(ri.Preference); prf != 0 {
raw.Value[1] |= (prf << 3)
}
lt := ri.RouteLifetime.Seconds()
binary.BigEndian.PutUint32(raw.Value[2:6], uint32(lt))
copy(raw.Value[6:], ri.Prefix.AsSlice())
return raw.marshal()
}
func (ri *RouteInformation) unmarshal(b []byte) error {
raw := new(RawOption)
if err := raw.unmarshal(b); err != nil {
return err
}
// Verify the option's length against prefix length using the rules defined
// in the RFC.
l := raw.Value[0]
rerr := fmt.Errorf("ndp: invalid route information for /%d prefix", l)
switch {
case l == 0:
if raw.Length < 1 || raw.Length > 3 {
return rerr
}
case l > 0 && l < 65:
// Some devices will use length 3 anyway for a route that fits in /64.
if raw.Length != 2 && raw.Length != 3 {
return rerr
}
case l > 64 && l < 129:
if raw.Length != 3 {
return rerr
}
default:
// Invalid IPv6 prefix.
return rerr
}
// Unpack preference (with adjacent reserved bits) and lifetime values.
var (
pref = Preference((raw.Value[1] & 0x18) >> 3)
lt = time.Duration(binary.BigEndian.Uint32(raw.Value[2:6])) * time.Second
)
if err := checkPreference(pref); err != nil {
return err
}
// Take up to the specified number of IP bytes into the prefix.
var (
addr [16]byte
buf = raw.Value[6 : 6+(l/8)]
)
copy(addr[:], buf)
*ri = RouteInformation{
PrefixLength: l,
Preference: pref,
RouteLifetime: lt,
Prefix: netip.AddrFrom16(addr),
}
return nil
}
// A RecursiveDNSServer is a Recursive DNS Server option, as described in
// RFC 8106, Section 5.1.
type RecursiveDNSServer struct {
Lifetime time.Duration
Servers []netip.Addr
}
// Code implements Option.
func (*RecursiveDNSServer) Code() byte { return optRDNSS }
// Offsets for the RDNSS option.
const (
rdnssLifetimeOff = 2
rdnssServersOff = 6
)
var (
errRDNSSNoServers = errors.New("ndp: recursive DNS server option requires at least one server")
errRDNSSBadServer = errors.New("ndp: recursive DNS server option has malformed IPv6 address")
)
func (r *RecursiveDNSServer) marshal() ([]byte, error) {
slen := len(r.Servers)
if slen == 0 {
return nil, errRDNSSNoServers
}
raw := &RawOption{
Type: r.Code(),
// Always have one length unit to start, and then each IPv6 address
// occupies two length units.
Length: 1 + uint8((slen * 2)),
// Allocate enough space for all data.
Value: make([]byte, rdnssServersOff+(slen*net.IPv6len)),
}
binary.BigEndian.PutUint32(
raw.Value[rdnssLifetimeOff:rdnssServersOff],
uint32(r.Lifetime.Seconds()),
)
for i := 0; i < len(r.Servers); i++ {
// Determine the start and end byte offsets for each address,
// effectively iterating 16 bytes at a time to insert an address.
var (
start = rdnssServersOff + (i * net.IPv6len)
end = rdnssServersOff + net.IPv6len + (i * net.IPv6len)
)
copy(raw.Value[start:end], r.Servers[i].AsSlice())
}
return raw.marshal()
}
func (r *RecursiveDNSServer) unmarshal(b []byte) error {
raw := new(RawOption)
if err := raw.unmarshal(b); err != nil {
return err
}
// Skip 2 reserved bytes to get lifetime.
lt := time.Duration(binary.BigEndian.Uint32(
raw.Value[rdnssLifetimeOff:rdnssServersOff])) * time.Second
// Determine the number of DNS servers specified using the method described
// in the RFC. Remember, length is specified in units of 8 octets.
//
// "That is, the number of addresses is equal to (Length - 1) / 2."
//
// Make sure at least one server is present, and that the IPv6 addresses are
// the expected 16 byte length.
dividend := (int(raw.Length) - 1)
if dividend%2 != 0 {
return errRDNSSBadServer
}
count := dividend / 2
if count == 0 {
return errRDNSSNoServers
}
servers := make([]netip.Addr, 0, count)
for i := 0; i < count; i++ {
// Determine the start and end byte offsets for each address,
// effectively iterating 16 bytes at a time to fetch an address.
var (
start = rdnssServersOff + (i * net.IPv6len)
end = rdnssServersOff + net.IPv6len + (i * net.IPv6len)
)
s, ok := netip.AddrFromSlice(raw.Value[start:end])
if !ok {
return errRDNSSBadServer
}
servers = append(servers, s)
}
*r = RecursiveDNSServer{
Lifetime: lt,
Servers: servers,
}
return nil
}
// A DNSSearchList is a DNS search list option, as described in
// RFC 8106, Section 5.2.
type DNSSearchList struct {
Lifetime time.Duration
DomainNames []string
}
// Code implements Option.
func (*DNSSearchList) Code() byte { return optDNSSL }
// Offsets for the RDNSS option.
const (
dnsslLifetimeOff = 2
dnsslDomainsOff = 6
)
var (
errDNSSLBadDomains = errors.New("ndp: DNS search list option has malformed domain names")
errDNSSLNoDomains = errors.New("ndp: DNS search list option requires at least one domain name")
)
func (d *DNSSearchList) marshal() ([]byte, error) {
if len(d.DomainNames) == 0 {
return nil, errDNSSLNoDomains
}
// Make enough room for reserved bytes and lifetime.
value := make([]byte, dnsslDomainsOff)
binary.BigEndian.PutUint32(
value[dnsslLifetimeOff:dnsslDomainsOff],
uint32(d.Lifetime.Seconds()),
)
// Attach each label component of a domain name with a one byte length prefix
// and a null terminator between full domain names, using the algorithm from:
// https://tools.ietf.org/html/rfc1035#section-3.1.
for _, dn := range d.DomainNames {
// All unicode names must be converted to punycode.
dn, err := idna.ToASCII(dn)
if err != nil {
return nil, errDNSSLBadDomains
}
for _, label := range strings.Split(dn, ".") {
// Label must be convertable to valid Punycode.
if !isASCII(label) {
return nil, errDNSSLBadDomains
}
value = append(value, byte(len(label)))
value = append(value, label...)
}
value = append(value, 0)
}
// Pad null bytes into value, so that when combined with type and length,
// the entire buffer length is divisible by 8 bytes for proper NDP option
// length.
if r := (len(value) + 2) % 8; r != 0 {
value = append(value, bytes.Repeat([]byte{0x00}, 8-r)...)
}
raw := &RawOption{
Type: d.Code(),
// Always have one length unit to start, and then calculate the length
// needed for value.
Length: uint8((len(value) + 2) / 8),
Value: value,
}
return raw.marshal()
}
func (d *DNSSearchList) unmarshal(b []byte) error {
raw := new(RawOption)
if err := raw.unmarshal(b); err != nil {
return err
}
// Skip 2 reserved bytes to get lifetime.
lt := time.Duration(binary.BigEndian.Uint32(
raw.Value[dnsslLifetimeOff:dnsslDomainsOff])) * time.Second
// This block implements the domain name space parsing algorithm from:
// https://tools.ietf.org/html/rfc1035#section-3.1.
//
// A domain is comprised of a sequence of labels, which are accumulated and
// then separated by periods later on.
var domains []string
var labels []string
for i := dnsslDomainsOff; ; {
if len(raw.Value[i:]) < 2 {
return errDNSSLBadDomains
}
// Parse the length of the upcoming label.
length := int(raw.Value[i])
if length >= len(raw.Value[i:])-1 {
// Length out of range.
return errDNSSLBadDomains
}
if length == 0 {
// No more labels.
break
}
i++
// Parse the label string and ensure it is ASCII, and that it doesn't
// contain invalid characters.
label := string(raw.Value[i : i+length])
if !isASCII(label) {
return errDNSSLBadDomains
}
// TODO(mdlayher): much smarter validation.
if label == "" || strings.Contains(label, ".") || strings.Contains(label, " ") {
return errDNSSLBadDomains
}
// Verify that the Punycode label decodes to something sane.
label, err := idna.ToUnicode(label)
if err != nil {
return errDNSSLBadDomains
}
// TODO(mdlayher): much smarter validation.
if label == "" || hasUnicodeReplacement(label) || strings.Contains(label, ".") || strings.Contains(label, " ") {
return errDNSSLBadDomains
}
labels = append(labels, label)
i += length
// If we've reached a null byte, join labels into a domain name and
// empty the label stack for reuse.
if raw.Value[i] == 0 {
i++
domain, err := idna.ToUnicode(strings.Join(labels, "."))
if err != nil {
return errDNSSLBadDomains
}
domains = append(domains, domain)
labels = []string{}
// Have we reached the end of the value slice?
if len(raw.Value[i:]) == 0 || (len(raw.Value[i:]) == 1 && raw.Value[i] == 0) {
// No more non-padding bytes, no more labels.
break
}
}
}
// Must have found at least one domain.
if len(domains) == 0 {
return errDNSSLNoDomains
}
*d = DNSSearchList{
Lifetime: lt,
DomainNames: domains,
}
return nil
}
// Unrestricted is the IANA-assigned URI for a network with no captive portal
// restrictions, as specified in RFC 8910, Section 2.
const Unrestricted = "urn:ietf:params:capport:unrestricted"
// A CaptivePortal is a Captive-Portal option, as described in RFC 8910, Section
// 2.3.
type CaptivePortal struct {
URI string
}
// NewCaptivePortal produces a CaptivePortal Option for the input URI string. As
// a special case, if uri is empty, Unrestricted is used as the CaptivePortal
// OptionURI.
//
// If uri is an IP address literal, an error is returned. Per RFC 8910, uri
// "SHOULD NOT" be an IP address, but there are circumstances where this
// behavior may be useful. In that case, the caller can bypass NewCaptivePortal
// and construct a CaptivePortal Option directly.
func NewCaptivePortal(uri string) (*CaptivePortal, error) {
if uri == "" {
return &CaptivePortal{URI: Unrestricted}, nil
}
// Try to comply with the max limit for DHCPv4.
if len(uri) > 255 {
return nil, errors.New("ndp: captive portal option URI is too long")
}
// TODO(mdlayher): a URN is almost a URL, but investigate compliance with
// https://datatracker.ietf.org/doc/html/rfc8141. In particular there are
// some tricky rules around case-sensitivity.
urn, err := url.Parse(uri)
if err != nil {
return nil, err
}
// "The URI SHOULD NOT contain an IP address literal."
//
// Since this is a constructor and there's nothing stopping the user from
// manually creating this string if they so choose, we'll return an error
// IP addresses. This includes bare IP addresses or IP addresses with some
// kind of path appended.
for _, s := range strings.Split(urn.Path, "/") {
if ip, err := netip.ParseAddr(s); err == nil {
return nil, fmt.Errorf("ndp: captive portal option URIs should not contain IP addresses: %s", ip)
}
}
return &CaptivePortal{URI: urn.String()}, nil
}
// Code implements Option.
func (*CaptivePortal) Code() byte { return optCaptivePortal }
func (cp *CaptivePortal) marshal() ([]byte, error) {
if len(cp.URI) == 0 {
return nil, errors.New("ndp: captive portal option requires a non-empty URI")
}
// Pad up to next unit of 8 bytes including 2 bytes for code, length, and
// bytes for the URI string. Extra bytes will be null.
l := len(cp.URI)
if r := (l + 2) % 8; r != 0 {
l += 8 - r
}
value := make([]byte, l)
copy(value, []byte(cp.URI))
raw := &RawOption{
Type: cp.Code(),
Length: (uint8(l) + 2) / 8,
Value: value,
}
return raw.marshal()
}
func (cp *CaptivePortal) unmarshal(b []byte) error {
raw := new(RawOption)
if err := raw.unmarshal(b); err != nil {
return err
}
// Don't allow a null URI.
if len(raw.Value) == 0 || raw.Value[0] == 0x00 {
return errors.New("ndp: captive portal URI is null")
}
// Find any trailing null bytes and trim them away before setting the URI.
i := bytes.Index(raw.Value, []byte{0x00})
if i == -1 {
i = len(raw.Value)
}
// Our constructor does validation of URIs, but we treat the URI as opaque
// for parsing, since we likely have to interop with other implementations.
*cp = CaptivePortal{URI: string(raw.Value[:i])}
return nil
}
// PREF64 is a PREF64 option, as described in RFC 8781, Section 4. The prefix
// must have a prefix length of 96, 64, 56, 40, or 32. The lifetime is used to
// indicate to clients how long the PREF64 prefix is valid for. A lifetime of 0
// indicates the prefix is no longer valid. If unsure, refer to RFC 8781
// Section 4.1 for how to calculate an appropriate lifetime.
type PREF64 struct {
Lifetime time.Duration
Prefix netip.Prefix
}
func (p *PREF64) Code() byte { return optPREF64 }
func (p *PREF64) marshal() ([]byte, error) {
var plc uint8
switch p.Prefix.Bits() {
case 96:
plc = 0
case 64:
plc = 1
case 56:
plc = 2
case 48:
plc = 3
case 40:
plc = 4
case 32:
plc = 5
default:
return nil, errors.New("ndp: invalid pref64 prefix size")
}
scaledLifetime := uint16(math.Round(p.Lifetime.Seconds() / 8))
// The scaled lifetime must be less than the maximum of 8191.
if scaledLifetime > 8191 {
return nil, errors.New("ndp: pref64 scaled lifetime is too large")
}
value := []byte{}
// The scaled lifetime and PLC values live within the same 16-bit field.
// Here we move the scaled lifetime to the left-most 13 bits and place the
// PLC at the last 3 bits of the 16-bit field.
value = binary.BigEndian.AppendUint16(
value,
(scaledLifetime<<3&(0xffff^0b111))|uint16(plc&0b111),
)
allPrefixBits := p.Prefix.Masked().Addr().As16()
optionPrefixBits := allPrefixBits[:96/8]
value = append(value, optionPrefixBits...)
raw := &RawOption{
Type: p.Code(),
Length: (uint8(len(value)) + 2) / 8,
Value: value,
}
return raw.marshal()
}
func (p *PREF64) unmarshal(b []byte) error {
raw := new(RawOption)
if err := raw.unmarshal(b); err != nil {
return err
}
if raw.Type != optPREF64 {
return errors.New("ndp: invalid pref64 type")
}
if len(raw.Value) != (96/8)+2 {
return errors.New("ndp: invalid pref64 message length")
}
lifetimeAndPlc := binary.BigEndian.Uint16(raw.Value[:2])
plc := uint8(lifetimeAndPlc & 0b111)
var prefixSize int
switch plc {
case 0:
prefixSize = 96
case 1:
prefixSize = 64
case 2:
prefixSize = 56
case 3:
prefixSize = 48
case 4:
prefixSize = 40
case 5:
prefixSize = 32
default:
return errors.New("ndp: invalid pref64 prefix length code")
}
addr := [16]byte{}
copy(addr[:], raw.Value[2:])
prefix, err := netip.AddrFrom16(addr).Prefix(int(prefixSize))
if err != nil {
return err
}
scaledLifetime := (lifetimeAndPlc & (0xffff ^ 0b111)) >> 3
lifetime := time.Duration(scaledLifetime) * 8 * time.Second
*p = PREF64{
Lifetime: lifetime,
Prefix: prefix,
}
return nil
}
// A RAFlagsExtension is a Router Advertisement Flags Extension (or Expansion)
// option, as described in RFC 5175, Section 4.
type RAFlagsExtension struct {
Flags RAFlags
}
// RAFlags is a bitmask of Router Advertisement flags contained within an
// RAFlagsExtension.
type RAFlags []byte
// Code implements Option.
func (*RAFlagsExtension) Code() byte { return optRAFlagsExtension }
func (ra *RAFlagsExtension) marshal() ([]byte, error) {
// "MUST NOT be added to a Router Advertisement message if no flags in the
// option are set."
//
// TODO(mdlayher): replace with slices.IndexFunc when we raise the minimum
// Go version.
var found bool
for _, b := range ra.Flags {
if b != 0x00 {
found = true
break
}
}
if !found {
return nil, errors.New("ndp: RA flags extension requires one or more flags to be set")
}
// Enforce the option size matches the next unit of 8 bytes including 2
// bytes for code and length.
l := len(ra.Flags)
if r := (l + 2) % 8; r != 0 {
return nil, errors.New("ndp: RA flags extension length is invalid")
}
value := make([]byte, l)
copy(value, ra.Flags)
raw := &RawOption{
Type: ra.Code(),
Length: (uint8(l) + 2) / 8,
Value: value,
}
return raw.marshal()
}
func (ra *RAFlagsExtension) unmarshal(b []byte) error {
raw := new(RawOption)
if err := raw.unmarshal(b); err != nil {
return err
}
// Don't allow short bytes.
if len(raw.Value) < 6 {
return errors.New("ndp: RA Flags Extension too short")
}
// raw already made a copy.
ra.Flags = raw.Value
return nil
}
// A Nonce is a Nonce option, as described in RFC 3971, Section 5.3.2.
type Nonce struct {
b []byte
}
// NewNonce creates a Nonce option with an opaque random value.
func NewNonce() *Nonce {
// Minimum is 6 bytes, and this is also the only value that the Linux kernel
// recognizes as of kernel 5.17.
const n = 6
b := make([]byte, n)
if _, err := rand.Read(b); err != nil {
panicf("ndp: failed to generate nonce bytes: %v", err)
}
return &Nonce{b: b}
}
// Equal reports whether n and x are the same nonce.
func (n *Nonce) Equal(x *Nonce) bool { return subtle.ConstantTimeCompare(n.b, x.b) == 1 }
// Code implements Option.
func (*Nonce) Code() byte { return optNonce }
// String returns the string representation of a Nonce.
func (n *Nonce) String() string { return hex.EncodeToString(n.b) }
func (n *Nonce) marshal() ([]byte, error) {
if len(n.b) == 0 {
return nil, errors.New("ndp: nonce option requires a non-empty nonce value")
}
// Enforce the nonce size matches the next unit of 8 bytes including 2 bytes
// for code and length.
l := len(n.b)
if r := (l + 2) % 8; r != 0 {
return nil, errors.New("ndp: nonce size is invalid")
}
value := make([]byte, l)
copy(value, n.b)
raw := &RawOption{
Type: n.Code(),
Length: (uint8(l) + 2) / 8,
Value: value,
}
return raw.marshal()
}