github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/pkg/tcpip/header/parse/parse.go (about)

     1  // Copyright 2020 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 parse provides utilities to parse packets.
    16  package parse
    17  
    18  import (
    19  	"fmt"
    20  
    21  	"github.com/SagerNet/gvisor/pkg/tcpip"
    22  	"github.com/SagerNet/gvisor/pkg/tcpip/buffer"
    23  	"github.com/SagerNet/gvisor/pkg/tcpip/header"
    24  	"github.com/SagerNet/gvisor/pkg/tcpip/stack"
    25  )
    26  
    27  // ARP populates pkt's network header with an ARP header found in
    28  // pkt.Data.
    29  //
    30  // Returns true if the header was successfully parsed.
    31  func ARP(pkt *stack.PacketBuffer) bool {
    32  	_, ok := pkt.NetworkHeader().Consume(header.ARPSize)
    33  	if ok {
    34  		pkt.NetworkProtocolNumber = header.ARPProtocolNumber
    35  	}
    36  	return ok
    37  }
    38  
    39  // IPv4 parses an IPv4 packet found in pkt.Data and populates pkt's network
    40  // header with the IPv4 header.
    41  //
    42  // Returns true if the header was successfully parsed.
    43  func IPv4(pkt *stack.PacketBuffer) bool {
    44  	hdr, ok := pkt.Data().PullUp(header.IPv4MinimumSize)
    45  	if !ok {
    46  		return false
    47  	}
    48  	ipHdr := header.IPv4(hdr)
    49  
    50  	// Header may have options, determine the true header length.
    51  	headerLen := int(ipHdr.HeaderLength())
    52  	if headerLen < header.IPv4MinimumSize {
    53  		// TODO(github.com/SagerNet/issue/2404): Per RFC 791, IHL needs to be at least 5 in
    54  		// order for the packet to be valid. Figure out if we want to reject this
    55  		// case.
    56  		headerLen = header.IPv4MinimumSize
    57  	}
    58  	hdr, ok = pkt.NetworkHeader().Consume(headerLen)
    59  	if !ok {
    60  		return false
    61  	}
    62  	ipHdr = header.IPv4(hdr)
    63  	length := int(ipHdr.TotalLength()) - len(hdr)
    64  	if length < 0 {
    65  		return false
    66  	}
    67  
    68  	pkt.NetworkProtocolNumber = header.IPv4ProtocolNumber
    69  	pkt.Data().CapLength(length)
    70  	return true
    71  }
    72  
    73  // IPv6 parses an IPv6 packet found in pkt.Data and populates pkt's network
    74  // header with the IPv6 header.
    75  func IPv6(pkt *stack.PacketBuffer) (proto tcpip.TransportProtocolNumber, fragID uint32, fragOffset uint16, fragMore bool, ok bool) {
    76  	hdr, ok := pkt.Data().PullUp(header.IPv6MinimumSize)
    77  	if !ok {
    78  		return 0, 0, 0, false, false
    79  	}
    80  	ipHdr := header.IPv6(hdr)
    81  
    82  	// Create a VV to parse the packet. We don't plan to modify anything here.
    83  	// dataVV consists of:
    84  	// - Any IPv6 header bytes after the first 40 (i.e. extensions).
    85  	// - The transport header, if present.
    86  	// - Any other payload data.
    87  	views := [8]buffer.View{}
    88  	dataVV := buffer.NewVectorisedView(0, views[:0])
    89  	dataVV.AppendViews(pkt.Data().Views())
    90  	dataVV.TrimFront(header.IPv6MinimumSize)
    91  	it := header.MakeIPv6PayloadIterator(header.IPv6ExtensionHeaderIdentifier(ipHdr.NextHeader()), dataVV)
    92  
    93  	// Iterate over the IPv6 extensions to find their length.
    94  	var nextHdr tcpip.TransportProtocolNumber
    95  	var extensionsSize int
    96  
    97  traverseExtensions:
    98  	for {
    99  		extHdr, done, err := it.Next()
   100  		if err != nil {
   101  			break
   102  		}
   103  
   104  		// If we exhaust the extension list, the entire packet is the IPv6 header
   105  		// and (possibly) extensions.
   106  		if done {
   107  			extensionsSize = dataVV.Size()
   108  			break
   109  		}
   110  
   111  		switch extHdr := extHdr.(type) {
   112  		case header.IPv6FragmentExtHdr:
   113  			if fragID == 0 && fragOffset == 0 && !fragMore {
   114  				fragID = extHdr.ID()
   115  				fragOffset = extHdr.FragmentOffset()
   116  				fragMore = extHdr.More()
   117  			}
   118  			rawPayload := it.AsRawHeader(true /* consume */)
   119  			extensionsSize = dataVV.Size() - rawPayload.Buf.Size()
   120  			break traverseExtensions
   121  
   122  		case header.IPv6RawPayloadHeader:
   123  			// We've found the payload after any extensions.
   124  			extensionsSize = dataVV.Size() - extHdr.Buf.Size()
   125  			nextHdr = tcpip.TransportProtocolNumber(extHdr.Identifier)
   126  			break traverseExtensions
   127  
   128  		default:
   129  			// Any other extension is a no-op, keep looping until we find the payload.
   130  		}
   131  	}
   132  
   133  	// Put the IPv6 header with extensions in pkt.NetworkHeader().
   134  	hdr, ok = pkt.NetworkHeader().Consume(header.IPv6MinimumSize + extensionsSize)
   135  	if !ok {
   136  		panic(fmt.Sprintf("pkt.Data should have at least %d bytes, but only has %d.", header.IPv6MinimumSize+extensionsSize, pkt.Data().Size()))
   137  	}
   138  	ipHdr = header.IPv6(hdr)
   139  	pkt.Data().CapLength(int(ipHdr.PayloadLength()))
   140  	pkt.NetworkProtocolNumber = header.IPv6ProtocolNumber
   141  
   142  	return nextHdr, fragID, fragOffset, fragMore, true
   143  }
   144  
   145  // UDP parses a UDP packet found in pkt.Data and populates pkt's transport
   146  // header with the UDP header.
   147  //
   148  // Returns true if the header was successfully parsed.
   149  func UDP(pkt *stack.PacketBuffer) bool {
   150  	_, ok := pkt.TransportHeader().Consume(header.UDPMinimumSize)
   151  	pkt.TransportProtocolNumber = header.UDPProtocolNumber
   152  	return ok
   153  }
   154  
   155  // TCP parses a TCP packet found in pkt.Data and populates pkt's transport
   156  // header with the TCP header.
   157  //
   158  // Returns true if the header was successfully parsed.
   159  func TCP(pkt *stack.PacketBuffer) bool {
   160  	// TCP header is variable length, peek at it first.
   161  	hdrLen := header.TCPMinimumSize
   162  	hdr, ok := pkt.Data().PullUp(hdrLen)
   163  	if !ok {
   164  		return false
   165  	}
   166  
   167  	// If the header has options, pull those up as well.
   168  	if offset := int(header.TCP(hdr).DataOffset()); offset > header.TCPMinimumSize && offset <= pkt.Data().Size() {
   169  		// TODO(github.com/SagerNet/issue/2404): Figure out whether to reject this kind of
   170  		// packets.
   171  		hdrLen = offset
   172  	}
   173  
   174  	_, ok = pkt.TransportHeader().Consume(hdrLen)
   175  	pkt.TransportProtocolNumber = header.TCPProtocolNumber
   176  	return ok
   177  }