github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/pkg/tcpip/header/ipv4.go (about) 1 // Copyright 2021 The gVisor Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package header 16 17 import ( 18 "encoding/binary" 19 "fmt" 20 "time" 21 22 "github.com/SagerNet/gvisor/pkg/tcpip" 23 ) 24 25 // RFC 971 defines the fields of the IPv4 header on page 11 using the following 26 // diagram: ("Figure 4") 27 // 0 1 2 3 28 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 29 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 30 // |Version| IHL |Type of Service| Total Length | 31 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 32 // | Identification |Flags| Fragment Offset | 33 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 34 // | Time to Live | Protocol | Header Checksum | 35 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 36 // | Source Address | 37 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 38 // | Destination Address | 39 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 40 // | Options | Padding | 41 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 42 const ( 43 versIHL = 0 44 tos = 1 45 // IPv4TotalLenOffset is the offset of the total length field in the 46 // IPv4 header. 47 IPv4TotalLenOffset = 2 48 id = 4 49 flagsFO = 6 50 ttl = 8 51 protocol = 9 52 checksum = 10 53 srcAddr = 12 54 dstAddr = 16 55 options = 20 56 ) 57 58 // IPv4Fields contains the fields of an IPv4 packet. It is used to describe the 59 // fields of a packet that needs to be encoded. The IHL field is not here as 60 // it is totally defined by the size of the options. 61 type IPv4Fields struct { 62 // TOS is the "type of service" field of an IPv4 packet. 63 TOS uint8 64 65 // TotalLength is the "total length" field of an IPv4 packet. 66 TotalLength uint16 67 68 // ID is the "identification" field of an IPv4 packet. 69 ID uint16 70 71 // Flags is the "flags" field of an IPv4 packet. 72 Flags uint8 73 74 // FragmentOffset is the "fragment offset" field of an IPv4 packet. 75 FragmentOffset uint16 76 77 // TTL is the "time to live" field of an IPv4 packet. 78 TTL uint8 79 80 // Protocol is the "protocol" field of an IPv4 packet. 81 Protocol uint8 82 83 // Checksum is the "checksum" field of an IPv4 packet. 84 Checksum uint16 85 86 // SrcAddr is the "source ip address" of an IPv4 packet. 87 SrcAddr tcpip.Address 88 89 // DstAddr is the "destination ip address" of an IPv4 packet. 90 DstAddr tcpip.Address 91 92 // Options must be 40 bytes or less as they must fit along with the 93 // rest of the IPv4 header into the maximum size describable in the 94 // IHL field. RFC 791 section 3.1 says: 95 // IHL: 4 bits 96 // 97 // Internet Header Length is the length of the internet header in 32 98 // bit words, and thus points to the beginning of the data. Note that 99 // the minimum value for a correct header is 5. 100 // 101 // That leaves ten 32 bit (4 byte) fields for options. An attempt to encode 102 // more will fail. 103 Options IPv4OptionsSerializer 104 } 105 106 // IPv4 is an IPv4 header. 107 // Most of the methods of IPv4 access to the underlying slice without 108 // checking the boundaries and could panic because of 'index out of range'. 109 // Always call IsValid() to validate an instance of IPv4 before using other 110 // methods. 111 type IPv4 []byte 112 113 const ( 114 // IPv4MinimumSize is the minimum size of a valid IPv4 packet; 115 // i.e. a packet header with no options. 116 IPv4MinimumSize = 20 117 118 // IPv4MaximumHeaderSize is the maximum size of an IPv4 header. Given 119 // that there are only 4 bits (max 0xF (15)) to represent the header length 120 // in 32-bit (4 byte) units, the header cannot exceed 15*4 = 60 bytes. 121 IPv4MaximumHeaderSize = 60 122 123 // IPv4MaximumOptionsSize is the largest size the IPv4 options can be. 124 IPv4MaximumOptionsSize = IPv4MaximumHeaderSize - IPv4MinimumSize 125 126 // IPv4MaximumPayloadSize is the maximum size of a valid IPv4 payload. 127 // 128 // Linux limits this to 65,515 octets (the max IP datagram size - the IPv4 129 // header size). But RFC 791 section 3.2 discusses the design of the IPv4 130 // fragment "allows 2**13 = 8192 fragments of 8 octets each for a total of 131 // 65,536 octets. Note that this is consistent with the datagram total 132 // length field (of course, the header is counted in the total length and not 133 // in the fragments)." 134 IPv4MaximumPayloadSize = 65536 135 136 // MinIPFragmentPayloadSize is the minimum number of payload bytes that 137 // the first fragment must carry when an IPv4 packet is fragmented. 138 MinIPFragmentPayloadSize = 8 139 140 // IPv4AddressSize is the size, in bytes, of an IPv4 address. 141 IPv4AddressSize = 4 142 143 // IPv4ProtocolNumber is IPv4's network protocol number. 144 IPv4ProtocolNumber tcpip.NetworkProtocolNumber = 0x0800 145 146 // IPv4Version is the version of the IPv4 protocol. 147 IPv4Version = 4 148 149 // IPv4AllSystems is the all systems IPv4 multicast address as per 150 // IANA's IPv4 Multicast Address Space Registry. See 151 // https://www.iana.org/assignments/multicast-addresses/multicast-addresses.xhtml. 152 IPv4AllSystems tcpip.Address = "\xe0\x00\x00\x01" 153 154 // IPv4Broadcast is the broadcast address of the IPv4 procotol. 155 IPv4Broadcast tcpip.Address = "\xff\xff\xff\xff" 156 157 // IPv4Any is the non-routable IPv4 "any" meta address. 158 IPv4Any tcpip.Address = "\x00\x00\x00\x00" 159 160 // IPv4AllRoutersGroup is a multicast address for all routers. 161 IPv4AllRoutersGroup tcpip.Address = "\xe0\x00\x00\x02" 162 163 // IPv4MinimumProcessableDatagramSize is the minimum size of an IP 164 // packet that every IPv4 capable host must be able to 165 // process/reassemble. 166 IPv4MinimumProcessableDatagramSize = 576 167 168 // IPv4MinimumMTU is the minimum MTU required by IPv4, per RFC 791, 169 // section 3.2: 170 // Every internet module must be able to forward a datagram of 68 octets 171 // without further fragmentation. This is because an internet header may be 172 // up to 60 octets, and the minimum fragment is 8 octets. 173 IPv4MinimumMTU = 68 174 ) 175 176 // Flags that may be set in an IPv4 packet. 177 const ( 178 IPv4FlagMoreFragments = 1 << iota 179 IPv4FlagDontFragment 180 ) 181 182 // ipv4LinkLocalUnicastSubnet is the IPv4 link local unicast subnet as defined 183 // by RFC 3927 section 1. 184 var ipv4LinkLocalUnicastSubnet = func() tcpip.Subnet { 185 subnet, err := tcpip.NewSubnet("\xa9\xfe\x00\x00", "\xff\xff\x00\x00") 186 if err != nil { 187 panic(err) 188 } 189 return subnet 190 }() 191 192 // ipv4LinkLocalMulticastSubnet is the IPv4 link local multicast subnet as 193 // defined by RFC 5771 section 4. 194 var ipv4LinkLocalMulticastSubnet = func() tcpip.Subnet { 195 subnet, err := tcpip.NewSubnet("\xe0\x00\x00\x00", "\xff\xff\xff\x00") 196 if err != nil { 197 panic(err) 198 } 199 return subnet 200 }() 201 202 // IPv4EmptySubnet is the empty IPv4 subnet. 203 var IPv4EmptySubnet = func() tcpip.Subnet { 204 subnet, err := tcpip.NewSubnet(IPv4Any, tcpip.AddressMask(IPv4Any)) 205 if err != nil { 206 panic(err) 207 } 208 return subnet 209 }() 210 211 // IPVersion returns the version of IP used in the given packet. It returns -1 212 // if the packet is not large enough to contain the version field. 213 func IPVersion(b []byte) int { 214 // Length must be at least offset+length of version field. 215 if len(b) < versIHL+1 { 216 return -1 217 } 218 return int(b[versIHL] >> ipVersionShift) 219 } 220 221 // RFC 791 page 11 shows the header length (IHL) is in the lower 4 bits 222 // of the first byte, and is counted in multiples of 4 bytes. 223 // 224 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 225 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 226 // |Version| IHL |Type of Service| Total Length | 227 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 228 // (...) 229 // Version: 4 bits 230 // The Version field indicates the format of the internet header. This 231 // document describes version 4. 232 // 233 // IHL: 4 bits 234 // Internet Header Length is the length of the internet header in 32 235 // bit words, and thus points to the beginning of the data. Note that 236 // the minimum value for a correct header is 5. 237 const ( 238 ipVersionShift = 4 239 ipIHLMask = 0x0f 240 IPv4IHLStride = 4 241 ) 242 243 // HeaderLength returns the value of the "header length" field of the IPv4 244 // header. The length returned is in bytes. 245 func (b IPv4) HeaderLength() uint8 { 246 return (b[versIHL] & ipIHLMask) * IPv4IHLStride 247 } 248 249 // SetHeaderLength sets the value of the "Internet Header Length" field. 250 func (b IPv4) SetHeaderLength(hdrLen uint8) { 251 if hdrLen > IPv4MaximumHeaderSize { 252 panic(fmt.Sprintf("got IPv4 Header size = %d, want <= %d", hdrLen, IPv4MaximumHeaderSize)) 253 } 254 b[versIHL] = (IPv4Version << ipVersionShift) | ((hdrLen / IPv4IHLStride) & ipIHLMask) 255 } 256 257 // ID returns the value of the identifier field of the IPv4 header. 258 func (b IPv4) ID() uint16 { 259 return binary.BigEndian.Uint16(b[id:]) 260 } 261 262 // Protocol returns the value of the protocol field of the IPv4 header. 263 func (b IPv4) Protocol() uint8 { 264 return b[protocol] 265 } 266 267 // Flags returns the "flags" field of the IPv4 header. 268 func (b IPv4) Flags() uint8 { 269 return uint8(binary.BigEndian.Uint16(b[flagsFO:]) >> 13) 270 } 271 272 // More returns whether the more fragments flag is set. 273 func (b IPv4) More() bool { 274 return b.Flags()&IPv4FlagMoreFragments != 0 275 } 276 277 // TTL returns the "TTL" field of the IPv4 header. 278 func (b IPv4) TTL() uint8 { 279 return b[ttl] 280 } 281 282 // FragmentOffset returns the "fragment offset" field of the IPv4 header. 283 func (b IPv4) FragmentOffset() uint16 { 284 return binary.BigEndian.Uint16(b[flagsFO:]) << 3 285 } 286 287 // TotalLength returns the "total length" field of the IPv4 header. 288 func (b IPv4) TotalLength() uint16 { 289 return binary.BigEndian.Uint16(b[IPv4TotalLenOffset:]) 290 } 291 292 // Checksum returns the checksum field of the IPv4 header. 293 func (b IPv4) Checksum() uint16 { 294 return binary.BigEndian.Uint16(b[checksum:]) 295 } 296 297 // SourceAddress returns the "source address" field of the IPv4 header. 298 func (b IPv4) SourceAddress() tcpip.Address { 299 return tcpip.Address(b[srcAddr : srcAddr+IPv4AddressSize]) 300 } 301 302 // DestinationAddress returns the "destination address" field of the IPv4 303 // header. 304 func (b IPv4) DestinationAddress() tcpip.Address { 305 return tcpip.Address(b[dstAddr : dstAddr+IPv4AddressSize]) 306 } 307 308 // SetSourceAddressWithChecksumUpdate implements ChecksummableNetwork. 309 func (b IPv4) SetSourceAddressWithChecksumUpdate(new tcpip.Address) { 310 b.SetChecksum(^checksumUpdate2ByteAlignedAddress(^b.Checksum(), b.SourceAddress(), new)) 311 b.SetSourceAddress(new) 312 } 313 314 // SetDestinationAddressWithChecksumUpdate implements ChecksummableNetwork. 315 func (b IPv4) SetDestinationAddressWithChecksumUpdate(new tcpip.Address) { 316 b.SetChecksum(^checksumUpdate2ByteAlignedAddress(^b.Checksum(), b.DestinationAddress(), new)) 317 b.SetDestinationAddress(new) 318 } 319 320 // padIPv4OptionsLength returns the total length for IPv4 options of length l 321 // after applying padding according to RFC 791: 322 // The internet header padding is used to ensure that the internet 323 // header ends on a 32 bit boundary. 324 func padIPv4OptionsLength(length uint8) uint8 { 325 return (length + IPv4IHLStride - 1) & ^uint8(IPv4IHLStride-1) 326 } 327 328 // IPv4Options is a buffer that holds all the raw IP options. 329 type IPv4Options []byte 330 331 // Options returns a buffer holding the options. 332 func (b IPv4) Options() IPv4Options { 333 hdrLen := b.HeaderLength() 334 return IPv4Options(b[options:hdrLen:hdrLen]) 335 } 336 337 // TransportProtocol implements Network.TransportProtocol. 338 func (b IPv4) TransportProtocol() tcpip.TransportProtocolNumber { 339 return tcpip.TransportProtocolNumber(b.Protocol()) 340 } 341 342 // Payload implements Network.Payload. 343 func (b IPv4) Payload() []byte { 344 return b[b.HeaderLength():][:b.PayloadLength()] 345 } 346 347 // PayloadLength returns the length of the payload portion of the IPv4 packet. 348 func (b IPv4) PayloadLength() uint16 { 349 return b.TotalLength() - uint16(b.HeaderLength()) 350 } 351 352 // TOS returns the "type of service" field of the IPv4 header. 353 func (b IPv4) TOS() (uint8, uint32) { 354 return b[tos], 0 355 } 356 357 // SetTOS sets the "type of service" field of the IPv4 header. 358 func (b IPv4) SetTOS(v uint8, _ uint32) { 359 b[tos] = v 360 } 361 362 // SetTTL sets the "Time to Live" field of the IPv4 header. 363 func (b IPv4) SetTTL(v byte) { 364 b[ttl] = v 365 } 366 367 // SetTotalLength sets the "total length" field of the IPv4 header. 368 func (b IPv4) SetTotalLength(totalLength uint16) { 369 binary.BigEndian.PutUint16(b[IPv4TotalLenOffset:], totalLength) 370 } 371 372 // SetChecksum sets the checksum field of the IPv4 header. 373 func (b IPv4) SetChecksum(v uint16) { 374 binary.BigEndian.PutUint16(b[checksum:], v) 375 } 376 377 // SetFlagsFragmentOffset sets the "flags" and "fragment offset" fields of the 378 // IPv4 header. 379 func (b IPv4) SetFlagsFragmentOffset(flags uint8, offset uint16) { 380 v := (uint16(flags) << 13) | (offset >> 3) 381 binary.BigEndian.PutUint16(b[flagsFO:], v) 382 } 383 384 // SetID sets the identification field. 385 func (b IPv4) SetID(v uint16) { 386 binary.BigEndian.PutUint16(b[id:], v) 387 } 388 389 // SetSourceAddress sets the "source address" field of the IPv4 header. 390 func (b IPv4) SetSourceAddress(addr tcpip.Address) { 391 copy(b[srcAddr:srcAddr+IPv4AddressSize], addr) 392 } 393 394 // SetDestinationAddress sets the "destination address" field of the IPv4 395 // header. 396 func (b IPv4) SetDestinationAddress(addr tcpip.Address) { 397 copy(b[dstAddr:dstAddr+IPv4AddressSize], addr) 398 } 399 400 // CalculateChecksum calculates the checksum of the IPv4 header. 401 func (b IPv4) CalculateChecksum() uint16 { 402 return Checksum(b[:b.HeaderLength()], 0) 403 } 404 405 // Encode encodes all the fields of the IPv4 header. 406 func (b IPv4) Encode(i *IPv4Fields) { 407 // The size of the options defines the size of the whole header and thus the 408 // IHL field. Options are rare and this is a heavily used function so it is 409 // worth a bit of optimisation here to keep the serializer out of the fast 410 // path. 411 hdrLen := uint8(IPv4MinimumSize) 412 if len(i.Options) != 0 { 413 hdrLen += i.Options.Serialize(b[options:]) 414 } 415 if hdrLen > IPv4MaximumHeaderSize { 416 panic(fmt.Sprintf("%d is larger than maximum IPv4 header size of %d", hdrLen, IPv4MaximumHeaderSize)) 417 } 418 b.SetHeaderLength(hdrLen) 419 b[tos] = i.TOS 420 b.SetTotalLength(i.TotalLength) 421 binary.BigEndian.PutUint16(b[id:], i.ID) 422 b.SetFlagsFragmentOffset(i.Flags, i.FragmentOffset) 423 b[ttl] = i.TTL 424 b[protocol] = i.Protocol 425 b.SetChecksum(i.Checksum) 426 copy(b[srcAddr:srcAddr+IPv4AddressSize], i.SrcAddr) 427 copy(b[dstAddr:dstAddr+IPv4AddressSize], i.DstAddr) 428 } 429 430 // EncodePartial updates the total length and checksum fields of IPv4 header, 431 // taking in the partial checksum, which is the checksum of the header without 432 // the total length and checksum fields. It is useful in cases when similar 433 // packets are produced. 434 func (b IPv4) EncodePartial(partialChecksum, totalLength uint16) { 435 b.SetTotalLength(totalLength) 436 checksum := Checksum(b[IPv4TotalLenOffset:IPv4TotalLenOffset+2], partialChecksum) 437 b.SetChecksum(^checksum) 438 } 439 440 // IsValid performs basic validation on the packet. 441 func (b IPv4) IsValid(pktSize int) bool { 442 if len(b) < IPv4MinimumSize { 443 return false 444 } 445 446 hlen := int(b.HeaderLength()) 447 tlen := int(b.TotalLength()) 448 if hlen < IPv4MinimumSize || hlen > tlen || tlen > pktSize { 449 return false 450 } 451 452 if IPVersion(b) != IPv4Version { 453 return false 454 } 455 456 return true 457 } 458 459 // IsV4LinkLocalUnicastAddress determines if the provided address is an IPv4 460 // link-local unicast address. 461 func IsV4LinkLocalUnicastAddress(addr tcpip.Address) bool { 462 return ipv4LinkLocalUnicastSubnet.Contains(addr) 463 } 464 465 // IsV4LinkLocalMulticastAddress determines if the provided address is an IPv4 466 // link-local multicast address. 467 func IsV4LinkLocalMulticastAddress(addr tcpip.Address) bool { 468 return ipv4LinkLocalMulticastSubnet.Contains(addr) 469 } 470 471 // IsChecksumValid returns true iff the IPv4 header's checksum is valid. 472 func (b IPv4) IsChecksumValid() bool { 473 // There has been some confusion regarding verifying checksums. We need 474 // just look for negative 0 (0xffff) as the checksum, as it's not possible to 475 // get positive 0 (0) for the checksum. Some bad implementations could get it 476 // when doing entry replacement in the early days of the Internet, 477 // however the lore that one needs to check for both persists. 478 // 479 // RFC 1624 section 1 describes the source of this confusion as: 480 // [the partial recalculation method described in RFC 1071] computes a 481 // result for certain cases that differs from the one obtained from 482 // scratch (one's complement of one's complement sum of the original 483 // fields). 484 // 485 // However RFC 1624 section 5 clarifies that if using the verification method 486 // "recommended by RFC 1071, it does not matter if an intermediate system 487 // generated a -0 instead of +0". 488 // 489 // RFC1071 page 1 specifies the verification method as: 490 // (3) To check a checksum, the 1's complement sum is computed over the 491 // same set of octets, including the checksum field. If the result 492 // is all 1 bits (-0 in 1's complement arithmetic), the check 493 // succeeds. 494 return b.CalculateChecksum() == 0xffff 495 } 496 497 // IsV4MulticastAddress determines if the provided address is an IPv4 multicast 498 // address (range 224.0.0.0 to 239.255.255.255). The four most significant bits 499 // will be 1110 = 0xe0. 500 func IsV4MulticastAddress(addr tcpip.Address) bool { 501 if len(addr) != IPv4AddressSize { 502 return false 503 } 504 return (addr[0] & 0xf0) == 0xe0 505 } 506 507 // IsV4LoopbackAddress determines if the provided address is an IPv4 loopback 508 // address (belongs to 127.0.0.0/8 subnet). See RFC 1122 section 3.2.1.3. 509 func IsV4LoopbackAddress(addr tcpip.Address) bool { 510 if len(addr) != IPv4AddressSize { 511 return false 512 } 513 return addr[0] == 0x7f 514 } 515 516 // ========================= Options ========================== 517 518 // An IPv4OptionType can hold the valuse for the Type in an IPv4 option. 519 type IPv4OptionType byte 520 521 // These constants are needed to identify individual options in the option list. 522 // While RFC 791 (page 31) says "Every internet module must be able to act on 523 // every option." This has not generally been adhered to and some options have 524 // very low rates of support. We do not support options other than those shown 525 // below. 526 527 const ( 528 // IPv4OptionListEndType is the option type for the End Of Option List 529 // option. Anything following is ignored. 530 IPv4OptionListEndType IPv4OptionType = 0 531 532 // IPv4OptionNOPType is the No-Operation option. May appear between other 533 // options and may appear multiple times. 534 IPv4OptionNOPType IPv4OptionType = 1 535 536 // IPv4OptionRouterAlertType is the option type for the Router Alert option, 537 // defined in RFC 2113 Section 2.1. 538 IPv4OptionRouterAlertType IPv4OptionType = 20 | 0x80 539 540 // IPv4OptionRecordRouteType is used by each router on the path of the packet 541 // to record its path. It is carried over to an Echo Reply. 542 IPv4OptionRecordRouteType IPv4OptionType = 7 543 544 // IPv4OptionTimestampType is the option type for the Timestamp option. 545 IPv4OptionTimestampType IPv4OptionType = 68 546 547 // ipv4OptionTypeOffset is the offset in an option of its type field. 548 ipv4OptionTypeOffset = 0 549 550 // IPv4OptionLengthOffset is the offset in an option of its length field. 551 IPv4OptionLengthOffset = 1 552 ) 553 554 // IPv4OptParameterProblem indicates that a Parameter Problem message 555 // should be generated, and gives the offset in the current entity 556 // that should be used in that packet. 557 type IPv4OptParameterProblem struct { 558 Pointer uint8 559 NeedICMP bool 560 } 561 562 // IPv4Option is an interface representing various option types. 563 type IPv4Option interface { 564 // Type returns the type identifier of the option. 565 Type() IPv4OptionType 566 567 // Size returns the size of the option in bytes. 568 Size() uint8 569 570 // Contents returns a slice holding the contents of the option. 571 Contents() []byte 572 } 573 574 var _ IPv4Option = (*IPv4OptionGeneric)(nil) 575 576 // IPv4OptionGeneric is an IPv4 Option of unknown type. 577 type IPv4OptionGeneric []byte 578 579 // Type implements IPv4Option. 580 func (o *IPv4OptionGeneric) Type() IPv4OptionType { 581 return IPv4OptionType((*o)[ipv4OptionTypeOffset]) 582 } 583 584 // Size implements IPv4Option. 585 func (o *IPv4OptionGeneric) Size() uint8 { return uint8(len(*o)) } 586 587 // Contents implements IPv4Option. 588 func (o *IPv4OptionGeneric) Contents() []byte { return *o } 589 590 // IPv4OptionIterator is an iterator pointing to a specific IP option 591 // at any point of time. It also holds information as to a new options buffer 592 // that we are building up to hand back to the caller. 593 // TODO(https://github.com/SagerNet/issues/5513): Add unit tests for IPv4OptionIterator. 594 type IPv4OptionIterator struct { 595 options IPv4Options 596 // ErrCursor is where we are while parsing options. It is exported as any 597 // resulting ICMP packet is supposed to have a pointer to the byte within 598 // the IP packet where the error was detected. 599 ErrCursor uint8 600 nextErrCursor uint8 601 newOptions [IPv4MaximumOptionsSize]byte 602 writePoint int 603 } 604 605 // MakeIterator sets up and returns an iterator of options. It also sets up the 606 // building of a new option set. 607 func (o IPv4Options) MakeIterator() IPv4OptionIterator { 608 return IPv4OptionIterator{ 609 options: o, 610 nextErrCursor: IPv4MinimumSize, 611 } 612 } 613 614 // InitReplacement copies the option into the new option buffer. 615 func (i *IPv4OptionIterator) InitReplacement(option IPv4Option) IPv4Options { 616 replacementOption := i.RemainingBuffer()[:option.Size()] 617 if copied := copy(replacementOption, option.Contents()); copied != len(replacementOption) { 618 panic(fmt.Sprintf("copied %d bytes in the replacement option buffer, expected %d bytes", copied, len(replacementOption))) 619 } 620 return replacementOption 621 } 622 623 // RemainingBuffer returns the remaining (unused) part of the new option buffer, 624 // into which a new option may be written. 625 func (i *IPv4OptionIterator) RemainingBuffer() IPv4Options { 626 return i.newOptions[i.writePoint:] 627 } 628 629 // ConsumeBuffer marks a portion of the new buffer as used. 630 func (i *IPv4OptionIterator) ConsumeBuffer(size int) { 631 i.writePoint += size 632 } 633 634 // PushNOPOrEnd puts one of the single byte options onto the new options. 635 // Only values 0 or 1 (ListEnd or NOP) are valid input. 636 func (i *IPv4OptionIterator) PushNOPOrEnd(val IPv4OptionType) { 637 if val > IPv4OptionNOPType { 638 panic(fmt.Sprintf("invalid option type %d pushed onto option build buffer", val)) 639 } 640 i.newOptions[i.writePoint] = byte(val) 641 i.writePoint++ 642 } 643 644 // Finalize returns the completed replacement options buffer padded 645 // as needed. 646 func (i *IPv4OptionIterator) Finalize() IPv4Options { 647 // RFC 791 page 31 says: 648 // The options might not end on a 32-bit boundary. The internet header 649 // must be filled out with octets of zeros. The first of these would 650 // be interpreted as the end-of-options option, and the remainder as 651 // internet header padding. 652 // Since the buffer is already zero filled we just need to step the write 653 // pointer up to the next multiple of 4. 654 options := IPv4Options(i.newOptions[:(i.writePoint+0x3) & ^0x3]) 655 // Poison the write pointer. 656 i.writePoint = len(i.newOptions) 657 return options 658 } 659 660 // Next returns the next IP option in the buffer/list of IP options. 661 // It returns 662 // - A slice of bytes holding the next option or nil if there is error. 663 // - A boolean which is true if parsing of all the options is complete. 664 // Undefined in the case of error. 665 // - An error indication which is non-nil if an error condition was found. 666 func (i *IPv4OptionIterator) Next() (IPv4Option, bool, *IPv4OptParameterProblem) { 667 // The opts slice gets shorter as we process the options. When we have no 668 // bytes left we are done. 669 if len(i.options) == 0 { 670 return nil, true, nil 671 } 672 673 i.ErrCursor = i.nextErrCursor 674 675 optType := IPv4OptionType(i.options[ipv4OptionTypeOffset]) 676 677 if optType == IPv4OptionNOPType || optType == IPv4OptionListEndType { 678 optionBody := i.options[:1] 679 i.options = i.options[1:] 680 i.nextErrCursor = i.ErrCursor + 1 681 retval := IPv4OptionGeneric(optionBody) 682 return &retval, false, nil 683 } 684 685 // There are no more single byte options defined. All the rest have a length 686 // field so we need to sanity check it. 687 if len(i.options) == 1 { 688 return nil, false, &IPv4OptParameterProblem{ 689 Pointer: i.ErrCursor, 690 NeedICMP: true, 691 } 692 } 693 694 optLen := i.options[IPv4OptionLengthOffset] 695 696 if optLen <= IPv4OptionLengthOffset || optLen > uint8(len(i.options)) { 697 // The actual error is in the length (2nd byte of the option) but we 698 // return the start of the option for compatibility with Linux. 699 700 return nil, false, &IPv4OptParameterProblem{ 701 Pointer: i.ErrCursor, 702 NeedICMP: true, 703 } 704 } 705 706 optionBody := i.options[:optLen] 707 i.nextErrCursor = i.ErrCursor + optLen 708 i.options = i.options[optLen:] 709 710 // Check the length of some option types that we know. 711 switch optType { 712 case IPv4OptionTimestampType: 713 if optLen < IPv4OptionTimestampHdrLength { 714 i.ErrCursor++ 715 return nil, false, &IPv4OptParameterProblem{ 716 Pointer: i.ErrCursor, 717 NeedICMP: true, 718 } 719 } 720 retval := IPv4OptionTimestamp(optionBody) 721 return &retval, false, nil 722 723 case IPv4OptionRecordRouteType: 724 if optLen < IPv4OptionRecordRouteHdrLength { 725 i.ErrCursor++ 726 return nil, false, &IPv4OptParameterProblem{ 727 Pointer: i.ErrCursor, 728 NeedICMP: true, 729 } 730 } 731 retval := IPv4OptionRecordRoute(optionBody) 732 return &retval, false, nil 733 734 case IPv4OptionRouterAlertType: 735 if optLen != IPv4OptionRouterAlertLength { 736 i.ErrCursor++ 737 return nil, false, &IPv4OptParameterProblem{ 738 Pointer: i.ErrCursor, 739 NeedICMP: true, 740 } 741 } 742 retval := IPv4OptionRouterAlert(optionBody) 743 return &retval, false, nil 744 } 745 retval := IPv4OptionGeneric(optionBody) 746 return &retval, false, nil 747 } 748 749 // 750 // IP Timestamp option - RFC 791 page 22. 751 // +--------+--------+--------+--------+ 752 // |01000100| length | pointer|oflw|flg| 753 // +--------+--------+--------+--------+ 754 // | internet address | 755 // +--------+--------+--------+--------+ 756 // | timestamp | 757 // +--------+--------+--------+--------+ 758 // | ... | 759 // 760 // Type = 68 761 // 762 // The Option Length is the number of octets in the option counting 763 // the type, length, pointer, and overflow/flag octets (maximum 764 // length 40). 765 // 766 // The Pointer is the number of octets from the beginning of this 767 // option to the end of timestamps plus one (i.e., it points to the 768 // octet beginning the space for next timestamp). The smallest 769 // legal value is 5. The timestamp area is full when the pointer 770 // is greater than the length. 771 // 772 // The Overflow (oflw) [4 bits] is the number of IP modules that 773 // cannot register timestamps due to lack of space. 774 // 775 // The Flag (flg) [4 bits] values are 776 // 777 // 0 -- time stamps only, stored in consecutive 32-bit words, 778 // 779 // 1 -- each timestamp is preceded with internet address of the 780 // registering entity, 781 // 782 // 3 -- the internet address fields are prespecified. An IP 783 // module only registers its timestamp if it matches its own 784 // address with the next specified internet address. 785 // 786 // Timestamps are defined in RFC 791 page 22 as milliseconds since midnight UTC. 787 // 788 // The Timestamp is a right-justified, 32-bit timestamp in 789 // milliseconds since midnight UT. If the time is not available in 790 // milliseconds or cannot be provided with respect to midnight UT 791 // then any time may be inserted as a timestamp provided the high 792 // order bit of the timestamp field is set to one to indicate the 793 // use of a non-standard value. 794 795 // IPv4OptTSFlags sefines the values expected in the Timestamp 796 // option Flags field. 797 type IPv4OptTSFlags uint8 798 799 // 800 // Timestamp option specific related constants. 801 const ( 802 // IPv4OptionTimestampHdrLength is the length of the timestamp option header. 803 IPv4OptionTimestampHdrLength = 4 804 805 // IPv4OptionTimestampSize is the size of an IP timestamp. 806 IPv4OptionTimestampSize = 4 807 808 // IPv4OptionTimestampWithAddrSize is the size of an IP timestamp + Address. 809 IPv4OptionTimestampWithAddrSize = IPv4AddressSize + IPv4OptionTimestampSize 810 811 // IPv4OptionTimestampMaxSize is limited by space for options 812 IPv4OptionTimestampMaxSize = IPv4MaximumOptionsSize 813 814 // IPv4OptionTimestampOnlyFlag is a flag indicating that only timestamp 815 // is present. 816 IPv4OptionTimestampOnlyFlag IPv4OptTSFlags = 0 817 818 // IPv4OptionTimestampWithIPFlag is a flag indicating that both timestamps and 819 // IP are present. 820 IPv4OptionTimestampWithIPFlag IPv4OptTSFlags = 1 821 822 // IPv4OptionTimestampWithPredefinedIPFlag is a flag indicating that 823 // predefined IP is present. 824 IPv4OptionTimestampWithPredefinedIPFlag IPv4OptTSFlags = 3 825 ) 826 827 // ipv4TimestampTime provides the current time as specified in RFC 791. 828 func ipv4TimestampTime(clock tcpip.Clock) uint32 { 829 // Per RFC 791 page 21: 830 // The Timestamp is a right-justified, 32-bit timestamp in 831 // milliseconds since midnight UT. 832 now := clock.Now().UTC() 833 midnight := now.Truncate(24 * time.Hour) 834 return uint32(now.Sub(midnight).Milliseconds()) 835 } 836 837 // IP Timestamp option fields. 838 const ( 839 // IPv4OptTSPointerOffset is the offset of the Timestamp pointer field. 840 IPv4OptTSPointerOffset = 2 841 842 // IPv4OptTSPointerOffset is the offset of the combined Flag and Overflow 843 // fields, (each being 4 bits). 844 IPv4OptTSOFLWAndFLGOffset = 3 845 // These constants define the sub byte fields of the Flag and OverFlow field. 846 ipv4OptionTimestampOverflowshift = 4 847 ipv4OptionTimestampFlagsMask byte = 0x0f 848 ) 849 850 var _ IPv4Option = (*IPv4OptionTimestamp)(nil) 851 852 // IPv4OptionTimestamp is a Timestamp option from RFC 791. 853 type IPv4OptionTimestamp []byte 854 855 // Type implements IPv4Option.Type(). 856 func (ts *IPv4OptionTimestamp) Type() IPv4OptionType { return IPv4OptionTimestampType } 857 858 // Size implements IPv4Option. 859 func (ts *IPv4OptionTimestamp) Size() uint8 { return uint8(len(*ts)) } 860 861 // Contents implements IPv4Option. 862 func (ts *IPv4OptionTimestamp) Contents() []byte { return *ts } 863 864 // Pointer returns the pointer field in the IP Timestamp option. 865 func (ts *IPv4OptionTimestamp) Pointer() uint8 { 866 return (*ts)[IPv4OptTSPointerOffset] 867 } 868 869 // Flags returns the flags field in the IP Timestamp option. 870 func (ts *IPv4OptionTimestamp) Flags() IPv4OptTSFlags { 871 return IPv4OptTSFlags((*ts)[IPv4OptTSOFLWAndFLGOffset] & ipv4OptionTimestampFlagsMask) 872 } 873 874 // Overflow returns the Overflow field in the IP Timestamp option. 875 func (ts *IPv4OptionTimestamp) Overflow() uint8 { 876 return (*ts)[IPv4OptTSOFLWAndFLGOffset] >> ipv4OptionTimestampOverflowshift 877 } 878 879 // IncOverflow increments the Overflow field in the IP Timestamp option. It 880 // returns the incremented value. If the return value is 0 then the field 881 // overflowed. 882 func (ts *IPv4OptionTimestamp) IncOverflow() uint8 { 883 (*ts)[IPv4OptTSOFLWAndFLGOffset] += 1 << ipv4OptionTimestampOverflowshift 884 return ts.Overflow() 885 } 886 887 // UpdateTimestamp updates the fields of the next free timestamp slot. 888 func (ts *IPv4OptionTimestamp) UpdateTimestamp(addr tcpip.Address, clock tcpip.Clock) { 889 slot := (*ts)[ts.Pointer()-1:] 890 891 switch ts.Flags() { 892 case IPv4OptionTimestampOnlyFlag: 893 binary.BigEndian.PutUint32(slot, ipv4TimestampTime(clock)) 894 (*ts)[IPv4OptTSPointerOffset] += IPv4OptionTimestampSize 895 case IPv4OptionTimestampWithIPFlag: 896 if n := copy(slot, addr); n != IPv4AddressSize { 897 panic(fmt.Sprintf("copied %d bytes, expected %d bytes", n, IPv4AddressSize)) 898 } 899 binary.BigEndian.PutUint32(slot[IPv4AddressSize:], ipv4TimestampTime(clock)) 900 (*ts)[IPv4OptTSPointerOffset] += IPv4OptionTimestampWithAddrSize 901 case IPv4OptionTimestampWithPredefinedIPFlag: 902 if tcpip.Address(slot[:IPv4AddressSize]) == addr { 903 binary.BigEndian.PutUint32(slot[IPv4AddressSize:], ipv4TimestampTime(clock)) 904 (*ts)[IPv4OptTSPointerOffset] += IPv4OptionTimestampWithAddrSize 905 } 906 } 907 } 908 909 // RecordRoute option specific related constants. 910 // 911 // from RFC 791 page 20: 912 // Record Route 913 // 914 // +--------+--------+--------+---------//--------+ 915 // |00000111| length | pointer| route data | 916 // +--------+--------+--------+---------//--------+ 917 // Type=7 918 // 919 // The record route option provides a means to record the route of 920 // an internet datagram. 921 // 922 // The option begins with the option type code. The second octet 923 // is the option length which includes the option type code and the 924 // length octet, the pointer octet, and length-3 octets of route 925 // data. The third octet is the pointer into the route data 926 // indicating the octet which begins the next area to store a route 927 // address. The pointer is relative to this option, and the 928 // smallest legal value for the pointer is 4. 929 const ( 930 // IPv4OptionRecordRouteHdrLength is the length of the Record Route option 931 // header. 932 IPv4OptionRecordRouteHdrLength = 3 933 934 // IPv4OptRRPointerOffset is the offset to the pointer field in an RR 935 // option, which points to the next free slot in the list of addresses. 936 IPv4OptRRPointerOffset = 2 937 ) 938 939 var _ IPv4Option = (*IPv4OptionRecordRoute)(nil) 940 941 // IPv4OptionRecordRoute is an IPv4 RecordRoute option defined by RFC 791. 942 type IPv4OptionRecordRoute []byte 943 944 // Pointer returns the pointer field in the IP RecordRoute option. 945 func (rr *IPv4OptionRecordRoute) Pointer() uint8 { 946 return (*rr)[IPv4OptRRPointerOffset] 947 } 948 949 // StoreAddress stores the given IPv4 address into the next free slot. 950 func (rr *IPv4OptionRecordRoute) StoreAddress(addr tcpip.Address) { 951 start := rr.Pointer() - 1 // A one based number. 952 // start and room checked by caller. 953 if n := copy((*rr)[start:], addr); n != IPv4AddressSize { 954 panic(fmt.Sprintf("copied %d bytes, expected %d bytes", n, IPv4AddressSize)) 955 } 956 (*rr)[IPv4OptRRPointerOffset] += IPv4AddressSize 957 } 958 959 // Type implements IPv4Option. 960 func (rr *IPv4OptionRecordRoute) Type() IPv4OptionType { return IPv4OptionRecordRouteType } 961 962 // Size implements IPv4Option. 963 func (rr *IPv4OptionRecordRoute) Size() uint8 { return uint8(len(*rr)) } 964 965 // Contents implements IPv4Option. 966 func (rr *IPv4OptionRecordRoute) Contents() []byte { return *rr } 967 968 // Router Alert option specific related constants. 969 // 970 // from RFC 2113 section 2.1: 971 // 972 // +--------+--------+--------+--------+ 973 // |10010100|00000100| 2 octet value | 974 // +--------+--------+--------+--------+ 975 // 976 // Type: 977 // Copied flag: 1 (all fragments must carry the option) 978 // Option class: 0 (control) 979 // Option number: 20 (decimal) 980 // 981 // Length: 4 982 // 983 // Value: A two octet code with the following values: 984 // 0 - Router shall examine packet 985 // 1-65535 - Reserved 986 const ( 987 // IPv4OptionRouterAlertLength is the length of a Router Alert option. 988 IPv4OptionRouterAlertLength = 4 989 990 // IPv4OptionRouterAlertValue is the only permissible value of the 16 bit 991 // payload of the router alert option. 992 IPv4OptionRouterAlertValue = 0 993 994 // IPv4OptionRouterAlertValueOffset is the offset for the value of a 995 // RouterAlert option. 996 IPv4OptionRouterAlertValueOffset = 2 997 ) 998 999 var _ IPv4Option = (*IPv4OptionRouterAlert)(nil) 1000 1001 // IPv4OptionRouterAlert is an IPv4 RouterAlert option defined by RFC 2113. 1002 type IPv4OptionRouterAlert []byte 1003 1004 // Type implements IPv4Option. 1005 func (*IPv4OptionRouterAlert) Type() IPv4OptionType { return IPv4OptionRouterAlertType } 1006 1007 // Size implements IPv4Option. 1008 func (ra *IPv4OptionRouterAlert) Size() uint8 { return uint8(len(*ra)) } 1009 1010 // Contents implements IPv4Option. 1011 func (ra *IPv4OptionRouterAlert) Contents() []byte { return *ra } 1012 1013 // Value returns the value of the IPv4OptionRouterAlert. 1014 func (ra *IPv4OptionRouterAlert) Value() uint16 { 1015 return binary.BigEndian.Uint16(ra.Contents()[IPv4OptionRouterAlertValueOffset:]) 1016 } 1017 1018 // IPv4SerializableOption is an interface to represent serializable IPv4 option 1019 // types. 1020 type IPv4SerializableOption interface { 1021 // optionType returns the type identifier of the option. 1022 optionType() IPv4OptionType 1023 } 1024 1025 // IPv4SerializableOptionPayload is an interface providing serialization of the 1026 // payload of an IPv4 option. 1027 type IPv4SerializableOptionPayload interface { 1028 // length returns the size of the payload. 1029 length() uint8 1030 1031 // serializeInto serializes the payload into the provided byte buffer. 1032 // 1033 // Note, the caller MUST provide a byte buffer with size of at least 1034 // Length. Implementers of this function may assume that the byte buffer 1035 // is of sufficient size. serializeInto MUST panic if the provided byte 1036 // buffer is not of sufficient size. 1037 // 1038 // serializeInto will return the number of bytes that was used to 1039 // serialize the receiver. Implementers must only use the number of 1040 // bytes required to serialize the receiver. Callers MAY provide a 1041 // larger buffer than required to serialize into. 1042 serializeInto(buffer []byte) uint8 1043 } 1044 1045 // IPv4OptionsSerializer is a serializer for IPv4 options. 1046 type IPv4OptionsSerializer []IPv4SerializableOption 1047 1048 // Length returns the total number of bytes required to serialize the options. 1049 func (s IPv4OptionsSerializer) Length() uint8 { 1050 var total uint8 1051 for _, opt := range s { 1052 total++ 1053 if withPayload, ok := opt.(IPv4SerializableOptionPayload); ok { 1054 // Add 1 to reported length to account for the length byte. 1055 total += 1 + withPayload.length() 1056 } 1057 } 1058 return padIPv4OptionsLength(total) 1059 } 1060 1061 // Serialize serializes the provided list of IPV4 options into b. 1062 // 1063 // Note, b must be of sufficient size to hold all the options in s. See 1064 // IPv4OptionsSerializer.Length for details on the getting the total size 1065 // of a serialized IPv4OptionsSerializer. 1066 // 1067 // Serialize panics if b is not of sufficient size to hold all the options in s. 1068 func (s IPv4OptionsSerializer) Serialize(b []byte) uint8 { 1069 var total uint8 1070 for _, opt := range s { 1071 ty := opt.optionType() 1072 if withPayload, ok := opt.(IPv4SerializableOptionPayload); ok { 1073 // Serialize first to reduce bounds checks. 1074 l := 2 + withPayload.serializeInto(b[2:]) 1075 b[0] = byte(ty) 1076 b[1] = l 1077 b = b[l:] 1078 total += l 1079 continue 1080 } 1081 // Options without payload consist only of the type field. 1082 // 1083 // NB: Repeating code from the branch above is intentional to minimize 1084 // bounds checks. 1085 b[0] = byte(ty) 1086 b = b[1:] 1087 total++ 1088 } 1089 1090 // According to RFC 791: 1091 // 1092 // The internet header padding is used to ensure that the internet 1093 // header ends on a 32 bit boundary. The padding is zero. 1094 padded := padIPv4OptionsLength(total) 1095 b = b[:padded-total] 1096 for i := range b { 1097 b[i] = 0 1098 } 1099 return padded 1100 } 1101 1102 var _ IPv4SerializableOptionPayload = (*IPv4SerializableRouterAlertOption)(nil) 1103 var _ IPv4SerializableOption = (*IPv4SerializableRouterAlertOption)(nil) 1104 1105 // IPv4SerializableRouterAlertOption provides serialization of the Router Alert 1106 // IPv4 option according to RFC 2113. 1107 type IPv4SerializableRouterAlertOption struct{} 1108 1109 // Type implements IPv4SerializableOption. 1110 func (*IPv4SerializableRouterAlertOption) optionType() IPv4OptionType { 1111 return IPv4OptionRouterAlertType 1112 } 1113 1114 // Length implements IPv4SerializableOption. 1115 func (*IPv4SerializableRouterAlertOption) length() uint8 { 1116 return IPv4OptionRouterAlertLength - IPv4OptionRouterAlertValueOffset 1117 } 1118 1119 // SerializeInto implements IPv4SerializableOption. 1120 func (o *IPv4SerializableRouterAlertOption) serializeInto(buffer []byte) uint8 { 1121 binary.BigEndian.PutUint16(buffer, IPv4OptionRouterAlertValue) 1122 return o.length() 1123 } 1124 1125 var _ IPv4SerializableOption = (*IPv4SerializableNOPOption)(nil) 1126 1127 // IPv4SerializableNOPOption provides serialization for the IPv4 no-op option. 1128 type IPv4SerializableNOPOption struct{} 1129 1130 // Type implements IPv4SerializableOption. 1131 func (*IPv4SerializableNOPOption) optionType() IPv4OptionType { 1132 return IPv4OptionNOPType 1133 } 1134 1135 var _ IPv4SerializableOption = (*IPv4SerializableListEndOption)(nil) 1136 1137 // IPv4SerializableListEndOption provides serialization for the IPv4 List End 1138 // option. 1139 type IPv4SerializableListEndOption struct{} 1140 1141 // Type implements IPv4SerializableOption. 1142 func (*IPv4SerializableListEndOption) optionType() IPv4OptionType { 1143 return IPv4OptionListEndType 1144 }