├── init.go ├── README.md ├── .github └── FUNDING.yml ├── layers ├── ports.go ├── base.go ├── layertypes.go ├── endpoints.go ├── enums_generated.go ├── tcpip.go ├── udp.go ├── enums.go ├── ip4.go ├── tcp.go └── ip6.go ├── ip4defrag └── defrag.go ├── OPENSOURCELICENSES ├── tcpassembly └── assembly.go └── LICENSE /init.go: -------------------------------------------------------------------------------- 1 | package ipio 2 | 3 | func init(){ 4 | } 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ipio 2 | 3 | > The CLI version of [Brook GUI](https://www.txthinking.com/brook.html) 4 | 5 | Proxy all traffic just one line command. 6 | 7 | ### Install via [nami](https://github.com/txthinking/nami) 8 | 9 | ``` 10 | nami install ipio 11 | ``` 12 | 13 | ### Usage 14 | 15 | **root/sudo/Windows in GitBash with Admin** 16 | 17 | ``` 18 | ipio --link 'brook://...' 19 | ``` 20 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: txthinking 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: 13 | -------------------------------------------------------------------------------- /layers/ports.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 Google, Inc. All rights reserved. 2 | // 3 | // Use of this source code is governed by a BSD-style license 4 | // that can be found in the LICENSE file in the root of the source 5 | // tree. 6 | 7 | package layers 8 | 9 | import ( 10 | "strconv" 11 | 12 | "github.com/google/gopacket" 13 | ) 14 | 15 | // TCPPort is a port in a TCP layer. 16 | type TCPPort uint16 17 | 18 | // UDPPort is a port in a UDP layer. 19 | type UDPPort uint16 20 | 21 | // {TCP,UDP,SCTP}PortNames can be found in iana_ports.go 22 | 23 | // String returns the port as "number(name)" if there's a well-known port name, 24 | // or just "number" if there isn't. Well-known names are stored in 25 | // TCPPortNames. 26 | func (a TCPPort) String() string { 27 | return strconv.Itoa(int(a)) 28 | } 29 | 30 | // LayerType returns a LayerType that would be able to decode the 31 | // application payload. It uses some well-known ports such as 53 for 32 | // DNS. 33 | // 34 | // Returns gopacket.LayerTypePayload for unknown/unsupported port numbers. 35 | func (a TCPPort) LayerType() gopacket.LayerType { 36 | return gopacket.LayerTypePayload 37 | } 38 | 39 | // String returns the port as "number(name)" if there's a well-known port name, 40 | // or just "number" if there isn't. Well-known names are stored in 41 | // UDPPortNames. 42 | func (a UDPPort) String() string { 43 | return strconv.Itoa(int(a)) 44 | } 45 | 46 | // LayerType returns a LayerType that would be able to decode the 47 | // application payload. It uses some well-known ports such as 53 for 48 | // DNS. 49 | // 50 | // Returns gopacket.LayerTypePayload for unknown/unsupported port numbers. 51 | func (a UDPPort) LayerType() gopacket.LayerType { 52 | return gopacket.LayerTypePayload 53 | } 54 | -------------------------------------------------------------------------------- /layers/base.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 Google, Inc. All rights reserved. 2 | // 3 | // Use of this source code is governed by a BSD-style license 4 | // that can be found in the LICENSE file in the root of the source 5 | // tree. 6 | 7 | package layers 8 | 9 | import ( 10 | "github.com/google/gopacket" 11 | ) 12 | 13 | // BaseLayer is a convenience struct which implements the LayerData and 14 | // LayerPayload functions of the Layer interface. 15 | type BaseLayer struct { 16 | // Contents is the set of bytes that make up this layer. IE: for an 17 | // Ethernet packet, this would be the set of bytes making up the 18 | // Ethernet frame. 19 | Contents []byte 20 | // Payload is the set of bytes contained by (but not part of) this 21 | // Layer. Again, to take Ethernet as an example, this would be the 22 | // set of bytes encapsulated by the Ethernet protocol. 23 | Payload []byte 24 | } 25 | 26 | // LayerContents returns the bytes of the packet layer. 27 | func (b *BaseLayer) LayerContents() []byte { return b.Contents } 28 | 29 | // LayerPayload returns the bytes contained within the packet layer. 30 | func (b *BaseLayer) LayerPayload() []byte { return b.Payload } 31 | 32 | type layerDecodingLayer interface { 33 | gopacket.Layer 34 | DecodeFromBytes([]byte, gopacket.DecodeFeedback) error 35 | NextLayerType() gopacket.LayerType 36 | } 37 | 38 | func decodingLayerDecoder(d layerDecodingLayer, data []byte, p gopacket.PacketBuilder) error { 39 | err := d.DecodeFromBytes(data, p) 40 | if err != nil { 41 | return err 42 | } 43 | p.AddLayer(d) 44 | next := d.NextLayerType() 45 | if next == gopacket.LayerTypeZero { 46 | return nil 47 | } 48 | return p.NextDecoder(next) 49 | } 50 | 51 | // hacky way to zero out memory... there must be a better way? 52 | var lotsOfZeros [1024]byte 53 | -------------------------------------------------------------------------------- /layers/layertypes.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 Google, Inc. All rights reserved. 2 | // 3 | // Use of this source code is governed by a BSD-style license 4 | // that can be found in the LICENSE file in the root of the source 5 | // tree. 6 | 7 | package layers 8 | 9 | import ( 10 | "github.com/google/gopacket" 11 | ) 12 | 13 | var ( 14 | LayerTypeIPv4 = gopacket.RegisterLayerType(20, gopacket.LayerTypeMetadata{Name: "IPv4", Decoder: gopacket.DecodeFunc(decodeIPv4)}) 15 | LayerTypeIPv6 = gopacket.RegisterLayerType(21, gopacket.LayerTypeMetadata{Name: "IPv6", Decoder: gopacket.DecodeFunc(decodeIPv6)}) 16 | LayerTypeTCP = gopacket.RegisterLayerType(44, gopacket.LayerTypeMetadata{Name: "TCP", Decoder: gopacket.DecodeFunc(decodeTCP)}) 17 | LayerTypeUDP = gopacket.RegisterLayerType(45, gopacket.LayerTypeMetadata{Name: "UDP", Decoder: gopacket.DecodeFunc(decodeUDP)}) 18 | LayerTypeIPv6HopByHop = gopacket.RegisterLayerType(46, gopacket.LayerTypeMetadata{Name: "IPv6HopByHop", Decoder: gopacket.DecodeFunc(decodeIPv6HopByHop)}) 19 | LayerTypeIPv6Routing = gopacket.RegisterLayerType(47, gopacket.LayerTypeMetadata{Name: "IPv6Routing", Decoder: gopacket.DecodeFunc(decodeIPv6Routing)}) 20 | LayerTypeIPv6Fragment = gopacket.RegisterLayerType(48, gopacket.LayerTypeMetadata{Name: "IPv6Fragment", Decoder: gopacket.DecodeFunc(decodeIPv6Fragment)}) 21 | LayerTypeIPv6Destination = gopacket.RegisterLayerType(49, gopacket.LayerTypeMetadata{Name: "IPv6Destination", Decoder: gopacket.DecodeFunc(decodeIPv6Destination)}) 22 | ) 23 | 24 | var ( 25 | // LayerClassIPNetwork contains TCP/IP network layer types. 26 | LayerClassIPNetwork = gopacket.NewLayerClass([]gopacket.LayerType{ 27 | LayerTypeIPv4, 28 | LayerTypeIPv6, 29 | }) 30 | // LayerClassIPTransport contains TCP/IP transport layer types. 31 | LayerClassIPTransport = gopacket.NewLayerClass([]gopacket.LayerType{ 32 | LayerTypeTCP, 33 | LayerTypeUDP, 34 | }) 35 | // LayerClassIPv6Extension contains IPv6 extension headers. 36 | LayerClassIPv6Extension = gopacket.NewLayerClass([]gopacket.LayerType{ 37 | LayerTypeIPv6HopByHop, 38 | LayerTypeIPv6Routing, 39 | LayerTypeIPv6Fragment, 40 | LayerTypeIPv6Destination, 41 | }) 42 | ) 43 | -------------------------------------------------------------------------------- /layers/endpoints.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 Google, Inc. All rights reserved. 2 | // 3 | // Use of this source code is governed by a BSD-style license 4 | // that can be found in the LICENSE file in the root of the source 5 | // tree. 6 | 7 | package layers 8 | 9 | import ( 10 | "encoding/binary" 11 | "net" 12 | "strconv" 13 | 14 | "github.com/google/gopacket" 15 | ) 16 | 17 | var ( 18 | // We use two different endpoint types for IPv4 vs IPv6 addresses, so that 19 | // ordering with endpointA.LessThan(endpointB) sanely groups all IPv4 20 | // addresses and all IPv6 addresses, such that IPv6 > IPv4 for all addresses. 21 | EndpointIPv4 = gopacket.RegisterEndpointType(1, gopacket.EndpointTypeMetadata{Name: "IPv4", Formatter: func(b []byte) string { 22 | return net.IP(b).String() 23 | }}) 24 | EndpointIPv6 = gopacket.RegisterEndpointType(2, gopacket.EndpointTypeMetadata{Name: "IPv6", Formatter: func(b []byte) string { 25 | return net.IP(b).String() 26 | }}) 27 | 28 | EndpointTCPPort = gopacket.RegisterEndpointType(4, gopacket.EndpointTypeMetadata{Name: "TCP", Formatter: func(b []byte) string { 29 | return strconv.Itoa(int(binary.BigEndian.Uint16(b))) 30 | }}) 31 | EndpointUDPPort = gopacket.RegisterEndpointType(5, gopacket.EndpointTypeMetadata{Name: "UDP", Formatter: func(b []byte) string { 32 | return strconv.Itoa(int(binary.BigEndian.Uint16(b))) 33 | }}) 34 | ) 35 | 36 | // NewIPEndpoint creates a new IP (v4 or v6) endpoint from a net.IP address. 37 | // It returns gopacket.InvalidEndpoint if the IP address is invalid. 38 | func NewIPEndpoint(a net.IP) gopacket.Endpoint { 39 | ipv4 := a.To4() 40 | if ipv4 != nil { 41 | return gopacket.NewEndpoint(EndpointIPv4, []byte(ipv4)) 42 | } 43 | 44 | ipv6 := a.To16() 45 | if ipv6 != nil { 46 | return gopacket.NewEndpoint(EndpointIPv6, []byte(ipv6)) 47 | } 48 | 49 | return gopacket.InvalidEndpoint 50 | } 51 | 52 | func newPortEndpoint(t gopacket.EndpointType, p uint16) gopacket.Endpoint { 53 | return gopacket.NewEndpoint(t, []byte{byte(p >> 8), byte(p)}) 54 | } 55 | 56 | // NewTCPPortEndpoint returns an endpoint based on a TCP port. 57 | func NewTCPPortEndpoint(p TCPPort) gopacket.Endpoint { 58 | return newPortEndpoint(EndpointTCPPort, uint16(p)) 59 | } 60 | 61 | // NewUDPPortEndpoint returns an endpoint based on a UDP port. 62 | func NewUDPPortEndpoint(p UDPPort) gopacket.Endpoint { 63 | return newPortEndpoint(EndpointUDPPort, uint16(p)) 64 | } 65 | -------------------------------------------------------------------------------- /layers/enums_generated.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 Google, Inc. All rights reserved. 2 | 3 | package layers 4 | 5 | // Created by gen2.go, don't edit manually 6 | // Generated at 2017-10-23 10:20:24.458771856 -0600 MDT m=+0.001159033 7 | 8 | import ( 9 | "fmt" 10 | 11 | "github.com/google/gopacket" 12 | ) 13 | 14 | func init() { 15 | initUnknownTypesForIPProtocol() 16 | initUnknownTypesForProtocolFamily() 17 | initActualTypeData() 18 | } 19 | 20 | // Decoder calls IPProtocolMetadata.DecodeWith's decoder. 21 | func (a IPProtocol) Decode(data []byte, p gopacket.PacketBuilder) error { 22 | return IPProtocolMetadata[a].DecodeWith.Decode(data, p) 23 | } 24 | 25 | // String returns IPProtocolMetadata.Name. 26 | func (a IPProtocol) String() string { 27 | return IPProtocolMetadata[a].Name 28 | } 29 | 30 | // LayerType returns IPProtocolMetadata.LayerType. 31 | func (a IPProtocol) LayerType() gopacket.LayerType { 32 | return IPProtocolMetadata[a].LayerType 33 | } 34 | 35 | type errorDecoderForIPProtocol int 36 | 37 | func (a *errorDecoderForIPProtocol) Decode(data []byte, p gopacket.PacketBuilder) error { 38 | return a 39 | } 40 | func (a *errorDecoderForIPProtocol) Error() string { 41 | return fmt.Sprintf("Unable to decode IPProtocol %d", int(*a)) 42 | } 43 | 44 | var errorDecodersForIPProtocol [256]errorDecoderForIPProtocol 45 | var IPProtocolMetadata [256]EnumMetadata 46 | 47 | func initUnknownTypesForIPProtocol() { 48 | for i := 0; i < 256; i++ { 49 | errorDecodersForIPProtocol[i] = errorDecoderForIPProtocol(i) 50 | IPProtocolMetadata[i] = EnumMetadata{ 51 | DecodeWith: &errorDecodersForIPProtocol[i], 52 | Name: "UnknownIPProtocol", 53 | } 54 | } 55 | } 56 | 57 | // Decoder calls ProtocolFamilyMetadata.DecodeWith's decoder. 58 | func (a ProtocolFamily) Decode(data []byte, p gopacket.PacketBuilder) error { 59 | return ProtocolFamilyMetadata[a].DecodeWith.Decode(data, p) 60 | } 61 | 62 | // String returns ProtocolFamilyMetadata.Name. 63 | func (a ProtocolFamily) String() string { 64 | return ProtocolFamilyMetadata[a].Name 65 | } 66 | 67 | // LayerType returns ProtocolFamilyMetadata.LayerType. 68 | func (a ProtocolFamily) LayerType() gopacket.LayerType { 69 | return ProtocolFamilyMetadata[a].LayerType 70 | } 71 | 72 | type errorDecoderForProtocolFamily int 73 | 74 | func (a *errorDecoderForProtocolFamily) Decode(data []byte, p gopacket.PacketBuilder) error { 75 | return a 76 | } 77 | func (a *errorDecoderForProtocolFamily) Error() string { 78 | return fmt.Sprintf("Unable to decode ProtocolFamily %d", int(*a)) 79 | } 80 | 81 | var errorDecodersForProtocolFamily [256]errorDecoderForProtocolFamily 82 | var ProtocolFamilyMetadata [256]EnumMetadata 83 | 84 | func initUnknownTypesForProtocolFamily() { 85 | for i := 0; i < 256; i++ { 86 | errorDecodersForProtocolFamily[i] = errorDecoderForProtocolFamily(i) 87 | ProtocolFamilyMetadata[i] = EnumMetadata{ 88 | DecodeWith: &errorDecodersForProtocolFamily[i], 89 | Name: "UnknownProtocolFamily", 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /layers/tcpip.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 Google, Inc. All rights reserved. 2 | // Copyright 2009-2011 Andreas Krennmair. All rights reserved. 3 | // 4 | // Use of this source code is governed by a BSD-style license 5 | // that can be found in the LICENSE file in the root of the source 6 | // tree. 7 | 8 | package layers 9 | 10 | import ( 11 | "errors" 12 | "fmt" 13 | 14 | "github.com/google/gopacket" 15 | ) 16 | 17 | // Checksum computation for TCP/UDP. 18 | type tcpipchecksum struct { 19 | pseudoheader tcpipPseudoHeader 20 | } 21 | 22 | type tcpipPseudoHeader interface { 23 | pseudoheaderChecksum() (uint32, error) 24 | } 25 | 26 | func (ip *IPv4) pseudoheaderChecksum() (csum uint32, err error) { 27 | if err := ip.AddressTo4(); err != nil { 28 | return 0, err 29 | } 30 | csum += (uint32(ip.SrcIP[0]) + uint32(ip.SrcIP[2])) << 8 31 | csum += uint32(ip.SrcIP[1]) + uint32(ip.SrcIP[3]) 32 | csum += (uint32(ip.DstIP[0]) + uint32(ip.DstIP[2])) << 8 33 | csum += uint32(ip.DstIP[1]) + uint32(ip.DstIP[3]) 34 | return csum, nil 35 | } 36 | 37 | func (ip *IPv6) pseudoheaderChecksum() (csum uint32, err error) { 38 | if err := ip.AddressTo16(); err != nil { 39 | return 0, err 40 | } 41 | for i := 0; i < 16; i += 2 { 42 | csum += uint32(ip.SrcIP[i]) << 8 43 | csum += uint32(ip.SrcIP[i+1]) 44 | csum += uint32(ip.DstIP[i]) << 8 45 | csum += uint32(ip.DstIP[i+1]) 46 | } 47 | return csum, nil 48 | } 49 | 50 | // Calculate the TCP/IP checksum defined in rfc1071. The passed-in csum is any 51 | // initial checksum data that's already been computed. 52 | func tcpipChecksum(data []byte, csum uint32) uint16 { 53 | // to handle odd lengths, we loop to length - 1, incrementing by 2, then 54 | // handle the last byte specifically by checking against the original 55 | // length. 56 | length := len(data) - 1 57 | for i := 0; i < length; i += 2 { 58 | // For our test packet, doing this manually is about 25% faster 59 | // (740 ns vs. 1000ns) than doing it by calling binary.BigEndian.Uint16. 60 | csum += uint32(data[i]) << 8 61 | csum += uint32(data[i+1]) 62 | } 63 | if len(data)%2 == 1 { 64 | csum += uint32(data[length]) << 8 65 | } 66 | for csum > 0xffff { 67 | csum = (csum >> 16) + (csum & 0xffff) 68 | } 69 | return ^uint16(csum) 70 | } 71 | 72 | // computeChecksum computes a TCP or UDP checksum. headerAndPayload is the 73 | // serialized TCP or UDP header plus its payload, with the checksum zero'd 74 | // out. headerProtocol is the IP protocol number of the upper-layer header. 75 | func (c *tcpipchecksum) computeChecksum(headerAndPayload []byte, headerProtocol IPProtocol) (uint16, error) { 76 | if c.pseudoheader == nil { 77 | return 0, errors.New("TCP/IP layer 4 checksum cannot be computed without network layer... call SetNetworkLayerForChecksum to set which layer to use") 78 | } 79 | length := uint32(len(headerAndPayload)) 80 | csum, err := c.pseudoheader.pseudoheaderChecksum() 81 | if err != nil { 82 | return 0, err 83 | } 84 | csum += uint32(headerProtocol) 85 | csum += length & 0xffff 86 | csum += length >> 16 87 | return tcpipChecksum(headerAndPayload, csum), nil 88 | } 89 | 90 | // SetNetworkLayerForChecksum tells this layer which network layer is wrapping it. 91 | // This is needed for computing the checksum when serializing, since TCP/IP transport 92 | // layer checksums depends on fields in the IPv4 or IPv6 layer that contains it. 93 | // The passed in layer must be an *IPv4 or *IPv6. 94 | func (i *tcpipchecksum) SetNetworkLayerForChecksum(l gopacket.NetworkLayer) error { 95 | switch v := l.(type) { 96 | case *IPv4: 97 | i.pseudoheader = v 98 | case *IPv6: 99 | i.pseudoheader = v 100 | default: 101 | return fmt.Errorf("cannot use layer type %v for tcp checksum network layer", l.LayerType()) 102 | } 103 | return nil 104 | } 105 | -------------------------------------------------------------------------------- /layers/udp.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 Google, Inc. All rights reserved. 2 | // Copyright 2009-2011 Andreas Krennmair. All rights reserved. 3 | // 4 | // Use of this source code is governed by a BSD-style license 5 | // that can be found in the LICENSE file in the root of the source 6 | // tree. 7 | 8 | package layers 9 | 10 | import ( 11 | "encoding/binary" 12 | "fmt" 13 | 14 | "github.com/google/gopacket" 15 | ) 16 | 17 | // UDP is the layer for UDP headers. 18 | type UDP struct { 19 | BaseLayer 20 | SrcPort, DstPort UDPPort 21 | Length uint16 22 | Checksum uint16 23 | sPort, dPort []byte 24 | tcpipchecksum 25 | } 26 | 27 | // LayerType returns gopacket.LayerTypeUDP 28 | func (u *UDP) LayerType() gopacket.LayerType { return LayerTypeUDP } 29 | 30 | func (udp *UDP) DecodeFromBytes(data []byte, df gopacket.DecodeFeedback) error { 31 | if len(data) < 8 { 32 | df.SetTruncated() 33 | return fmt.Errorf("Invalid UDP header. Length %d less than 8", len(data)) 34 | } 35 | udp.SrcPort = UDPPort(binary.BigEndian.Uint16(data[0:2])) 36 | udp.sPort = data[0:2] 37 | udp.DstPort = UDPPort(binary.BigEndian.Uint16(data[2:4])) 38 | udp.dPort = data[2:4] 39 | udp.Length = binary.BigEndian.Uint16(data[4:6]) 40 | udp.Checksum = binary.BigEndian.Uint16(data[6:8]) 41 | udp.BaseLayer = BaseLayer{Contents: data[:8]} 42 | switch { 43 | case udp.Length >= 8: 44 | hlen := int(udp.Length) 45 | if hlen > len(data) { 46 | df.SetTruncated() 47 | hlen = len(data) 48 | } 49 | udp.Payload = data[8:hlen] 50 | case udp.Length == 0: // Jumbogram, use entire rest of data 51 | udp.Payload = data[8:] 52 | default: 53 | return fmt.Errorf("UDP packet too small: %d bytes", udp.Length) 54 | } 55 | return nil 56 | } 57 | 58 | // SerializeTo writes the serialized form of this layer into the 59 | // SerializationBuffer, implementing gopacket.SerializableLayer. 60 | // See the docs for gopacket.SerializableLayer for more info. 61 | func (u *UDP) SerializeTo(b gopacket.SerializeBuffer, opts gopacket.SerializeOptions) error { 62 | var jumbo bool 63 | 64 | payload := b.Bytes() 65 | if _, ok := u.pseudoheader.(*IPv6); ok { 66 | if len(payload)+8 > 65535 { 67 | jumbo = true 68 | } 69 | } 70 | bytes, err := b.PrependBytes(8) 71 | if err != nil { 72 | return err 73 | } 74 | binary.BigEndian.PutUint16(bytes, uint16(u.SrcPort)) 75 | binary.BigEndian.PutUint16(bytes[2:], uint16(u.DstPort)) 76 | if opts.FixLengths { 77 | if jumbo { 78 | u.Length = 0 79 | } else { 80 | u.Length = uint16(len(payload)) + 8 81 | } 82 | } 83 | binary.BigEndian.PutUint16(bytes[4:], u.Length) 84 | if opts.ComputeChecksums { 85 | // zero out checksum bytes 86 | bytes[6] = 0 87 | bytes[7] = 0 88 | csum, err := u.computeChecksum(b.Bytes(), IPProtocolUDP) 89 | if err != nil { 90 | return err 91 | } 92 | u.Checksum = csum 93 | } 94 | binary.BigEndian.PutUint16(bytes[6:], u.Checksum) 95 | return nil 96 | } 97 | 98 | func (u *UDP) CanDecode() gopacket.LayerClass { 99 | return LayerTypeUDP 100 | } 101 | 102 | // NextLayerType use the destination port to select the 103 | // right next decoder. It tries first to decode via the 104 | // destination port, then the source port. 105 | func (u *UDP) NextLayerType() gopacket.LayerType { 106 | if lt := u.DstPort.LayerType(); lt != gopacket.LayerTypePayload { 107 | return lt 108 | } 109 | return u.SrcPort.LayerType() 110 | } 111 | 112 | func decodeUDP(data []byte, p gopacket.PacketBuilder) error { 113 | udp := &UDP{} 114 | err := udp.DecodeFromBytes(data, p) 115 | p.AddLayer(udp) 116 | p.SetTransportLayer(udp) 117 | if err != nil { 118 | return err 119 | } 120 | return p.NextDecoder(udp.NextLayerType()) 121 | } 122 | 123 | func (u *UDP) TransportFlow() gopacket.Flow { 124 | return gopacket.NewFlow(EndpointUDPPort, u.sPort, u.dPort) 125 | } 126 | 127 | // For testing only 128 | func (u *UDP) SetInternalPortsForTesting() { 129 | u.sPort = make([]byte, 2) 130 | u.dPort = make([]byte, 2) 131 | binary.BigEndian.PutUint16(u.sPort, uint16(u.SrcPort)) 132 | binary.BigEndian.PutUint16(u.dPort, uint16(u.DstPort)) 133 | } 134 | -------------------------------------------------------------------------------- /layers/enums.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 Google, Inc. All rights reserved. 2 | // Copyright 2009-2011 Andreas Krennmair. All rights reserved. 3 | // 4 | // Use of this source code is governed by a BSD-style license 5 | // that can be found in the LICENSE file in the root of the source 6 | // tree. 7 | 8 | package layers 9 | 10 | import ( 11 | "fmt" 12 | 13 | "github.com/google/gopacket" 14 | ) 15 | 16 | // EnumMetadata keeps track of a set of metadata for each enumeration value 17 | // for protocol enumerations. 18 | type EnumMetadata struct { 19 | // DecodeWith is the decoder to use to decode this protocol's data. 20 | DecodeWith gopacket.Decoder 21 | // Name is the name of the enumeration value. 22 | Name string 23 | // LayerType is the layer type implied by the given enum. 24 | LayerType gopacket.LayerType 25 | } 26 | 27 | // IPProtocol is an enumeration of IP protocol values, and acts as a decoder 28 | // for any type it supports. 29 | type IPProtocol uint8 30 | 31 | const ( 32 | IPProtocolIPv6HopByHop IPProtocol = 0 33 | IPProtocolIPv4 IPProtocol = 4 34 | IPProtocolTCP IPProtocol = 6 35 | IPProtocolUDP IPProtocol = 17 36 | IPProtocolIPv6 IPProtocol = 41 37 | IPProtocolIPv6Routing IPProtocol = 43 38 | IPProtocolIPv6Fragment IPProtocol = 44 39 | IPProtocolNoNextHeader IPProtocol = 59 40 | IPProtocolIPv6Destination IPProtocol = 60 41 | ) 42 | 43 | // ProtocolFamily is the set of values defined as PF_* in sys/socket.h 44 | type ProtocolFamily uint8 45 | 46 | const ( 47 | ProtocolFamilyIPv4 ProtocolFamily = 2 48 | // BSDs use different values for INET6... glory be. These values taken from 49 | // tcpdump 4.3.0. 50 | ProtocolFamilyIPv6BSD ProtocolFamily = 24 51 | ProtocolFamilyIPv6FreeBSD ProtocolFamily = 28 52 | ProtocolFamilyIPv6Darwin ProtocolFamily = 30 53 | ProtocolFamilyIPv6Linux ProtocolFamily = 10 54 | ) 55 | 56 | // Decode a raw v4 or v6 IP packet. 57 | func decodeIPv4or6(data []byte, p gopacket.PacketBuilder) error { 58 | version := data[0] >> 4 59 | switch version { 60 | case 4: 61 | return decodeIPv4(data, p) 62 | case 6: 63 | return decodeIPv6(data, p) 64 | } 65 | return fmt.Errorf("Invalid IP packet version %v", version) 66 | } 67 | 68 | func initActualTypeData() { 69 | // Each of the XXXTypeMetadata arrays contains mappings of how to handle enum 70 | // values for various enum types in gopacket/layers. 71 | // These arrays are actually created by gen2.go and stored in 72 | // enums_generated.go. 73 | // 74 | // So, EthernetTypeMetadata[2] contains information on how to handle EthernetType 75 | // 2, including which name to give it and which decoder to use to decode 76 | // packet data of that type. These arrays are filled by default with all of the 77 | // protocols gopacket/layers knows how to handle, but users of the library can 78 | // add new decoders or override existing ones. For example, if you write a better 79 | // TCP decoder, you can override IPProtocolMetadata[IPProtocolTCP].DecodeWith 80 | // with your new decoder, and all gopacket/layers decoding will use your new 81 | // decoder whenever they encounter that IPProtocol. 82 | 83 | // Here we link up all enumerations with their respective names and decoders. 84 | IPProtocolMetadata[IPProtocolIPv4] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeIPv4), Name: "IPv4", LayerType: LayerTypeIPv4} 85 | IPProtocolMetadata[IPProtocolTCP] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeTCP), Name: "TCP", LayerType: LayerTypeTCP} 86 | IPProtocolMetadata[IPProtocolUDP] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeUDP), Name: "UDP", LayerType: LayerTypeUDP} 87 | IPProtocolMetadata[IPProtocolIPv6] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeIPv6), Name: "IPv6", LayerType: LayerTypeIPv6} 88 | IPProtocolMetadata[IPProtocolIPv6HopByHop] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeIPv6HopByHop), Name: "IPv6HopByHop", LayerType: LayerTypeIPv6HopByHop} 89 | IPProtocolMetadata[IPProtocolIPv6Routing] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeIPv6Routing), Name: "IPv6Routing", LayerType: LayerTypeIPv6Routing} 90 | IPProtocolMetadata[IPProtocolIPv6Fragment] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeIPv6Fragment), Name: "IPv6Fragment", LayerType: LayerTypeIPv6Fragment} 91 | IPProtocolMetadata[IPProtocolIPv6Destination] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeIPv6Destination), Name: "IPv6Destination", LayerType: LayerTypeIPv6Destination} 92 | IPProtocolMetadata[IPProtocolNoNextHeader] = EnumMetadata{DecodeWith: gopacket.DecodePayload, Name: "NoNextHeader", LayerType: gopacket.LayerTypePayload} 93 | } 94 | -------------------------------------------------------------------------------- /layers/ip4.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 Google, Inc. All rights reserved. 2 | // Copyright 2009-2011 Andreas Krennmair. All rights reserved. 3 | // 4 | // Use of this source code is governed by a BSD-style license 5 | // that can be found in the LICENSE file in the root of the source 6 | // tree. 7 | 8 | package layers 9 | 10 | import ( 11 | "encoding/binary" 12 | "errors" 13 | "fmt" 14 | "net" 15 | "strings" 16 | 17 | "github.com/google/gopacket" 18 | ) 19 | 20 | type IPv4Flag uint8 21 | 22 | const ( 23 | IPv4EvilBit IPv4Flag = 1 << 2 // http://tools.ietf.org/html/rfc3514 ;) 24 | IPv4DontFragment IPv4Flag = 1 << 1 25 | IPv4MoreFragments IPv4Flag = 1 << 0 26 | ) 27 | 28 | func (f IPv4Flag) String() string { 29 | var s []string 30 | if f&IPv4EvilBit != 0 { 31 | s = append(s, "Evil") 32 | } 33 | if f&IPv4DontFragment != 0 { 34 | s = append(s, "DF") 35 | } 36 | if f&IPv4MoreFragments != 0 { 37 | s = append(s, "MF") 38 | } 39 | return strings.Join(s, "|") 40 | } 41 | 42 | // IPv4 is the header of an IP packet. 43 | type IPv4 struct { 44 | BaseLayer 45 | Version uint8 46 | IHL uint8 47 | TOS uint8 48 | Length uint16 49 | Id uint16 50 | Flags IPv4Flag 51 | FragOffset uint16 52 | TTL uint8 53 | Protocol IPProtocol 54 | Checksum uint16 55 | SrcIP net.IP 56 | DstIP net.IP 57 | Options []IPv4Option 58 | Padding []byte 59 | } 60 | 61 | // LayerType returns LayerTypeIPv4 62 | func (i *IPv4) LayerType() gopacket.LayerType { return LayerTypeIPv4 } 63 | func (i *IPv4) NetworkFlow() gopacket.Flow { 64 | return gopacket.NewFlow(EndpointIPv4, i.SrcIP, i.DstIP) 65 | } 66 | 67 | type IPv4Option struct { 68 | OptionType uint8 69 | OptionLength uint8 70 | OptionData []byte 71 | } 72 | 73 | func (i IPv4Option) String() string { 74 | return fmt.Sprintf("IPv4Option(%v:%v)", i.OptionType, i.OptionData) 75 | } 76 | 77 | // for the current ipv4 options, return the number of bytes (including 78 | // padding that the options used) 79 | func (ip *IPv4) getIPv4OptionSize() uint8 { 80 | optionSize := uint8(0) 81 | for _, opt := range ip.Options { 82 | switch opt.OptionType { 83 | case 0: 84 | // this is the end of option lists 85 | optionSize++ 86 | case 1: 87 | // this is the padding 88 | optionSize++ 89 | default: 90 | optionSize += opt.OptionLength 91 | 92 | } 93 | } 94 | // make sure the options are aligned to 32 bit boundary 95 | if (optionSize % 4) != 0 { 96 | optionSize += 4 - (optionSize % 4) 97 | } 98 | return optionSize 99 | } 100 | 101 | // SerializeTo writes the serialized form of this layer into the 102 | // SerializationBuffer, implementing gopacket.SerializableLayer. 103 | func (ip *IPv4) SerializeTo(b gopacket.SerializeBuffer, opts gopacket.SerializeOptions) error { 104 | optionLength := ip.getIPv4OptionSize() 105 | bytes, err := b.PrependBytes(20 + int(optionLength)) 106 | if err != nil { 107 | return err 108 | } 109 | if opts.FixLengths { 110 | ip.IHL = 5 + (optionLength / 4) 111 | ip.Length = uint16(len(b.Bytes())) 112 | } 113 | bytes[0] = (ip.Version << 4) | ip.IHL 114 | bytes[1] = ip.TOS 115 | binary.BigEndian.PutUint16(bytes[2:], ip.Length) 116 | binary.BigEndian.PutUint16(bytes[4:], ip.Id) 117 | binary.BigEndian.PutUint16(bytes[6:], ip.flagsfrags()) 118 | bytes[8] = ip.TTL 119 | bytes[9] = byte(ip.Protocol) 120 | if err := ip.AddressTo4(); err != nil { 121 | return err 122 | } 123 | copy(bytes[12:16], ip.SrcIP) 124 | copy(bytes[16:20], ip.DstIP) 125 | 126 | curLocation := 20 127 | // Now, we will encode the options 128 | for _, opt := range ip.Options { 129 | switch opt.OptionType { 130 | case 0: 131 | // this is the end of option lists 132 | bytes[curLocation] = 0 133 | curLocation++ 134 | case 1: 135 | // this is the padding 136 | bytes[curLocation] = 1 137 | curLocation++ 138 | default: 139 | bytes[curLocation] = opt.OptionType 140 | bytes[curLocation+1] = opt.OptionLength 141 | 142 | // sanity checking to protect us from buffer overrun 143 | if len(opt.OptionData) > int(opt.OptionLength-2) { 144 | return errors.New("option length is smaller than length of option data") 145 | } 146 | copy(bytes[curLocation+2:curLocation+int(opt.OptionLength)], opt.OptionData) 147 | curLocation += int(opt.OptionLength) 148 | } 149 | } 150 | 151 | if opts.ComputeChecksums { 152 | ip.Checksum = checksum(bytes) 153 | } 154 | binary.BigEndian.PutUint16(bytes[10:], ip.Checksum) 155 | return nil 156 | } 157 | 158 | func checksum(bytes []byte) uint16 { 159 | // Clear checksum bytes 160 | bytes[10] = 0 161 | bytes[11] = 0 162 | 163 | // Compute checksum 164 | var csum uint32 165 | for i := 0; i < len(bytes); i += 2 { 166 | csum += uint32(bytes[i]) << 8 167 | csum += uint32(bytes[i+1]) 168 | } 169 | for { 170 | // Break when sum is less or equals to 0xFFFF 171 | if csum <= 65535 { 172 | break 173 | } 174 | // Add carry to the sum 175 | csum = (csum >> 16) + uint32(uint16(csum)) 176 | } 177 | // Flip all the bits 178 | return ^uint16(csum) 179 | } 180 | 181 | func (ip *IPv4) flagsfrags() (ff uint16) { 182 | ff |= uint16(ip.Flags) << 13 183 | ff |= ip.FragOffset 184 | return 185 | } 186 | 187 | // DecodeFromBytes decodes the given bytes into this layer. 188 | func (ip *IPv4) DecodeFromBytes(data []byte, df gopacket.DecodeFeedback) error { 189 | if len(data) < 20 { 190 | df.SetTruncated() 191 | return fmt.Errorf("Invalid ip4 header. Length %d less than 20", len(data)) 192 | } 193 | flagsfrags := binary.BigEndian.Uint16(data[6:8]) 194 | 195 | ip.Version = uint8(data[0]) >> 4 196 | ip.IHL = uint8(data[0]) & 0x0F 197 | ip.TOS = data[1] 198 | ip.Length = binary.BigEndian.Uint16(data[2:4]) 199 | ip.Id = binary.BigEndian.Uint16(data[4:6]) 200 | ip.Flags = IPv4Flag(flagsfrags >> 13) 201 | ip.FragOffset = flagsfrags & 0x1FFF 202 | ip.TTL = data[8] 203 | ip.Protocol = IPProtocol(data[9]) 204 | ip.Checksum = binary.BigEndian.Uint16(data[10:12]) 205 | ip.SrcIP = data[12:16] 206 | ip.DstIP = data[16:20] 207 | ip.Options = ip.Options[:0] 208 | ip.Padding = nil 209 | // Set up an initial guess for contents/payload... we'll reset these soon. 210 | ip.BaseLayer = BaseLayer{Contents: data} 211 | 212 | // This code is added for the following enviroment: 213 | // * Windows 10 with TSO option activated. ( tested on Hyper-V, RealTek ethernet driver ) 214 | if ip.Length == 0 { 215 | // If using TSO(TCP Segmentation Offload), length is zero. 216 | // The actual packet length is the length of data. 217 | ip.Length = uint16(len(data)) 218 | } 219 | 220 | if ip.Length < 20 { 221 | return fmt.Errorf("Invalid (too small) IP length (%d < 20)", ip.Length) 222 | } else if ip.IHL < 5 { 223 | return fmt.Errorf("Invalid (too small) IP header length (%d < 5)", ip.IHL) 224 | } else if int(ip.IHL*4) > int(ip.Length) { 225 | return fmt.Errorf("Invalid IP header length > IP length (%d > %d)", ip.IHL, ip.Length) 226 | } 227 | if cmp := len(data) - int(ip.Length); cmp > 0 { 228 | data = data[:ip.Length] 229 | } else if cmp < 0 { 230 | df.SetTruncated() 231 | if int(ip.IHL)*4 > len(data) { 232 | return errors.New("Not all IP header bytes available") 233 | } 234 | } 235 | ip.Contents = data[:ip.IHL*4] 236 | ip.Payload = data[ip.IHL*4:] 237 | // From here on, data contains the header options. 238 | data = data[20 : ip.IHL*4] 239 | // Pull out IP options 240 | for len(data) > 0 { 241 | if ip.Options == nil { 242 | // Pre-allocate to avoid growing the slice too much. 243 | ip.Options = make([]IPv4Option, 0, 4) 244 | } 245 | opt := IPv4Option{OptionType: data[0]} 246 | switch opt.OptionType { 247 | case 0: // End of options 248 | opt.OptionLength = 1 249 | ip.Options = append(ip.Options, opt) 250 | ip.Padding = data[1:] 251 | return nil 252 | case 1: // 1 byte padding 253 | opt.OptionLength = 1 254 | data = data[1:] 255 | ip.Options = append(ip.Options, opt) 256 | default: 257 | if len(data) < 2 { 258 | df.SetTruncated() 259 | return fmt.Errorf("Invalid ip4 option length. Length %d less than 2", len(data)) 260 | } 261 | opt.OptionLength = data[1] 262 | if len(data) < int(opt.OptionLength) { 263 | df.SetTruncated() 264 | return fmt.Errorf("IP option length exceeds remaining IP header size, option type %v length %v", opt.OptionType, opt.OptionLength) 265 | } 266 | if opt.OptionLength <= 2 { 267 | return fmt.Errorf("Invalid IP option type %v length %d. Must be greater than 2", opt.OptionType, opt.OptionLength) 268 | } 269 | opt.OptionData = data[2:opt.OptionLength] 270 | data = data[opt.OptionLength:] 271 | ip.Options = append(ip.Options, opt) 272 | } 273 | } 274 | return nil 275 | } 276 | 277 | func (i *IPv4) CanDecode() gopacket.LayerClass { 278 | return LayerTypeIPv4 279 | } 280 | 281 | func (i *IPv4) NextLayerType() gopacket.LayerType { 282 | if i.Flags&IPv4MoreFragments != 0 || i.FragOffset != 0 { 283 | return gopacket.LayerTypeFragment 284 | } 285 | return i.Protocol.LayerType() 286 | } 287 | 288 | func decodeIPv4(data []byte, p gopacket.PacketBuilder) error { 289 | ip := &IPv4{} 290 | err := ip.DecodeFromBytes(data, p) 291 | p.AddLayer(ip) 292 | p.SetNetworkLayer(ip) 293 | if err != nil { 294 | return err 295 | } 296 | return p.NextDecoder(ip.NextLayerType()) 297 | } 298 | 299 | func checkIPv4Address(addr net.IP) (net.IP, error) { 300 | if c := addr.To4(); c != nil { 301 | return c, nil 302 | } 303 | if len(addr) == net.IPv6len { 304 | return nil, errors.New("address is IPv6") 305 | } 306 | return nil, fmt.Errorf("wrong length of %d bytes instead of %d", len(addr), net.IPv4len) 307 | } 308 | 309 | func (ip *IPv4) AddressTo4() error { 310 | var src, dst net.IP 311 | 312 | if addr, err := checkIPv4Address(ip.SrcIP); err != nil { 313 | return fmt.Errorf("Invalid source IPv4 address (%s)", err) 314 | } else { 315 | src = addr 316 | } 317 | if addr, err := checkIPv4Address(ip.DstIP); err != nil { 318 | return fmt.Errorf("Invalid destination IPv4 address (%s)", err) 319 | } else { 320 | dst = addr 321 | } 322 | ip.SrcIP = src 323 | ip.DstIP = dst 324 | return nil 325 | } 326 | -------------------------------------------------------------------------------- /layers/tcp.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 Google, Inc. All rights reserved. 2 | // Copyright 2009-2011 Andreas Krennmair. All rights reserved. 3 | // 4 | // Use of this source code is governed by a BSD-style license 5 | // that can be found in the LICENSE file in the root of the source 6 | // tree. 7 | 8 | package layers 9 | 10 | import ( 11 | "encoding/binary" 12 | "encoding/hex" 13 | "errors" 14 | "fmt" 15 | 16 | "github.com/google/gopacket" 17 | ) 18 | 19 | // TCP is the layer for TCP headers. 20 | type TCP struct { 21 | BaseLayer 22 | SrcPort, DstPort TCPPort 23 | Seq uint32 24 | Ack uint32 25 | DataOffset uint8 26 | FIN, SYN, RST, PSH, ACK, URG, ECE, CWR, NS bool 27 | Window uint16 28 | Checksum uint16 29 | Urgent uint16 30 | sPort, dPort []byte 31 | Options []TCPOption 32 | Padding []byte 33 | opts [4]TCPOption 34 | tcpipchecksum 35 | } 36 | 37 | // TCPOptionKind represents a TCP option code. 38 | type TCPOptionKind uint8 39 | 40 | const ( 41 | TCPOptionKindEndList = 0 42 | TCPOptionKindNop = 1 43 | TCPOptionKindMSS = 2 // len = 4 44 | TCPOptionKindWindowScale = 3 // len = 3 45 | TCPOptionKindSACKPermitted = 4 // len = 2 46 | TCPOptionKindSACK = 5 // len = n 47 | TCPOptionKindEcho = 6 // len = 6, obsolete 48 | TCPOptionKindEchoReply = 7 // len = 6, obsolete 49 | TCPOptionKindTimestamps = 8 // len = 10 50 | TCPOptionKindPartialOrderConnectionPermitted = 9 // len = 2, obsolete 51 | TCPOptionKindPartialOrderServiceProfile = 10 // len = 3, obsolete 52 | TCPOptionKindCC = 11 // obsolete 53 | TCPOptionKindCCNew = 12 // obsolete 54 | TCPOptionKindCCEcho = 13 // obsolete 55 | TCPOptionKindAltChecksum = 14 // len = 3, obsolete 56 | TCPOptionKindAltChecksumData = 15 // len = n, obsolete 57 | ) 58 | 59 | func (k TCPOptionKind) String() string { 60 | switch k { 61 | case TCPOptionKindEndList: 62 | return "EndList" 63 | case TCPOptionKindNop: 64 | return "NOP" 65 | case TCPOptionKindMSS: 66 | return "MSS" 67 | case TCPOptionKindWindowScale: 68 | return "WindowScale" 69 | case TCPOptionKindSACKPermitted: 70 | return "SACKPermitted" 71 | case TCPOptionKindSACK: 72 | return "SACK" 73 | case TCPOptionKindEcho: 74 | return "Echo" 75 | case TCPOptionKindEchoReply: 76 | return "EchoReply" 77 | case TCPOptionKindTimestamps: 78 | return "Timestamps" 79 | case TCPOptionKindPartialOrderConnectionPermitted: 80 | return "PartialOrderConnectionPermitted" 81 | case TCPOptionKindPartialOrderServiceProfile: 82 | return "PartialOrderServiceProfile" 83 | case TCPOptionKindCC: 84 | return "CC" 85 | case TCPOptionKindCCNew: 86 | return "CCNew" 87 | case TCPOptionKindCCEcho: 88 | return "CCEcho" 89 | case TCPOptionKindAltChecksum: 90 | return "AltChecksum" 91 | case TCPOptionKindAltChecksumData: 92 | return "AltChecksumData" 93 | default: 94 | return fmt.Sprintf("Unknown(%d)", k) 95 | } 96 | } 97 | 98 | type TCPOption struct { 99 | OptionType TCPOptionKind 100 | OptionLength uint8 101 | OptionData []byte 102 | } 103 | 104 | func (t TCPOption) String() string { 105 | hd := hex.EncodeToString(t.OptionData) 106 | if len(hd) > 0 { 107 | hd = " 0x" + hd 108 | } 109 | switch t.OptionType { 110 | case TCPOptionKindMSS: 111 | return fmt.Sprintf("TCPOption(%s:%v%s)", 112 | t.OptionType, 113 | binary.BigEndian.Uint16(t.OptionData), 114 | hd) 115 | 116 | case TCPOptionKindTimestamps: 117 | if len(t.OptionData) == 8 { 118 | return fmt.Sprintf("TCPOption(%s:%v/%v%s)", 119 | t.OptionType, 120 | binary.BigEndian.Uint32(t.OptionData[:4]), 121 | binary.BigEndian.Uint32(t.OptionData[4:8]), 122 | hd) 123 | } 124 | } 125 | return fmt.Sprintf("TCPOption(%s:%s)", t.OptionType, hd) 126 | } 127 | 128 | // LayerType returns gopacket.LayerTypeTCP 129 | func (t *TCP) LayerType() gopacket.LayerType { return LayerTypeTCP } 130 | 131 | // SerializeTo writes the serialized form of this layer into the 132 | // SerializationBuffer, implementing gopacket.SerializableLayer. 133 | // See the docs for gopacket.SerializableLayer for more info. 134 | func (t *TCP) SerializeTo(b gopacket.SerializeBuffer, opts gopacket.SerializeOptions) error { 135 | var optionLength int 136 | for _, o := range t.Options { 137 | switch o.OptionType { 138 | case 0, 1: 139 | optionLength += 1 140 | default: 141 | optionLength += 2 + len(o.OptionData) 142 | } 143 | } 144 | if opts.FixLengths { 145 | if rem := optionLength % 4; rem != 0 { 146 | t.Padding = lotsOfZeros[:4-rem] 147 | } 148 | t.DataOffset = uint8((len(t.Padding) + optionLength + 20) / 4) 149 | } 150 | bytes, err := b.PrependBytes(20 + optionLength + len(t.Padding)) 151 | if err != nil { 152 | return err 153 | } 154 | binary.BigEndian.PutUint16(bytes, uint16(t.SrcPort)) 155 | binary.BigEndian.PutUint16(bytes[2:], uint16(t.DstPort)) 156 | binary.BigEndian.PutUint32(bytes[4:], t.Seq) 157 | binary.BigEndian.PutUint32(bytes[8:], t.Ack) 158 | binary.BigEndian.PutUint16(bytes[12:], t.flagsAndOffset()) 159 | binary.BigEndian.PutUint16(bytes[14:], t.Window) 160 | binary.BigEndian.PutUint16(bytes[18:], t.Urgent) 161 | start := 20 162 | for _, o := range t.Options { 163 | bytes[start] = byte(o.OptionType) 164 | switch o.OptionType { 165 | case 0, 1: 166 | start++ 167 | default: 168 | if opts.FixLengths { 169 | o.OptionLength = uint8(len(o.OptionData) + 2) 170 | } 171 | bytes[start+1] = o.OptionLength 172 | copy(bytes[start+2:start+len(o.OptionData)+2], o.OptionData) 173 | start += len(o.OptionData) + 2 174 | } 175 | } 176 | copy(bytes[start:], t.Padding) 177 | if opts.ComputeChecksums { 178 | // zero out checksum bytes in current serialization. 179 | bytes[16] = 0 180 | bytes[17] = 0 181 | csum, err := t.computeChecksum(b.Bytes(), IPProtocolTCP) 182 | if err != nil { 183 | return err 184 | } 185 | t.Checksum = csum 186 | } 187 | binary.BigEndian.PutUint16(bytes[16:], t.Checksum) 188 | return nil 189 | } 190 | 191 | func (t *TCP) ComputeChecksum() (uint16, error) { 192 | return t.computeChecksum(append(t.Contents, t.Payload...), IPProtocolTCP) 193 | } 194 | 195 | func (t *TCP) flagsAndOffset() uint16 { 196 | f := uint16(t.DataOffset) << 12 197 | if t.FIN { 198 | f |= 0x0001 199 | } 200 | if t.SYN { 201 | f |= 0x0002 202 | } 203 | if t.RST { 204 | f |= 0x0004 205 | } 206 | if t.PSH { 207 | f |= 0x0008 208 | } 209 | if t.ACK { 210 | f |= 0x0010 211 | } 212 | if t.URG { 213 | f |= 0x0020 214 | } 215 | if t.ECE { 216 | f |= 0x0040 217 | } 218 | if t.CWR { 219 | f |= 0x0080 220 | } 221 | if t.NS { 222 | f |= 0x0100 223 | } 224 | return f 225 | } 226 | 227 | func (tcp *TCP) DecodeFromBytes(data []byte, df gopacket.DecodeFeedback) error { 228 | if len(data) < 20 { 229 | df.SetTruncated() 230 | return fmt.Errorf("Invalid TCP header. Length %d less than 20", len(data)) 231 | } 232 | tcp.SrcPort = TCPPort(binary.BigEndian.Uint16(data[0:2])) 233 | tcp.sPort = data[0:2] 234 | tcp.DstPort = TCPPort(binary.BigEndian.Uint16(data[2:4])) 235 | tcp.dPort = data[2:4] 236 | tcp.Seq = binary.BigEndian.Uint32(data[4:8]) 237 | tcp.Ack = binary.BigEndian.Uint32(data[8:12]) 238 | tcp.DataOffset = data[12] >> 4 239 | tcp.FIN = data[13]&0x01 != 0 240 | tcp.SYN = data[13]&0x02 != 0 241 | tcp.RST = data[13]&0x04 != 0 242 | tcp.PSH = data[13]&0x08 != 0 243 | tcp.ACK = data[13]&0x10 != 0 244 | tcp.URG = data[13]&0x20 != 0 245 | tcp.ECE = data[13]&0x40 != 0 246 | tcp.CWR = data[13]&0x80 != 0 247 | tcp.NS = data[12]&0x01 != 0 248 | tcp.Window = binary.BigEndian.Uint16(data[14:16]) 249 | tcp.Checksum = binary.BigEndian.Uint16(data[16:18]) 250 | tcp.Urgent = binary.BigEndian.Uint16(data[18:20]) 251 | if tcp.Options == nil { 252 | // Pre-allocate to avoid allocating a slice. 253 | tcp.Options = tcp.opts[:0] 254 | } else { 255 | tcp.Options = tcp.Options[:0] 256 | } 257 | if tcp.DataOffset < 5 { 258 | return fmt.Errorf("Invalid TCP data offset %d < 5", tcp.DataOffset) 259 | } 260 | dataStart := int(tcp.DataOffset) * 4 261 | if dataStart > len(data) { 262 | df.SetTruncated() 263 | tcp.Payload = nil 264 | tcp.Contents = data 265 | return errors.New("TCP data offset greater than packet length") 266 | } 267 | tcp.Contents = data[:dataStart] 268 | tcp.Payload = data[dataStart:] 269 | // From here on, data points just to the header options. 270 | data = data[20:dataStart] 271 | OPTIONS: 272 | for len(data) > 0 { 273 | tcp.Options = append(tcp.Options, TCPOption{OptionType: TCPOptionKind(data[0])}) 274 | opt := &tcp.Options[len(tcp.Options)-1] 275 | switch opt.OptionType { 276 | case TCPOptionKindEndList: // End of options 277 | opt.OptionLength = 1 278 | tcp.Padding = data[1:] 279 | break OPTIONS 280 | case TCPOptionKindNop: // 1 byte padding 281 | opt.OptionLength = 1 282 | default: 283 | if len(data) < 2 { 284 | df.SetTruncated() 285 | return fmt.Errorf("Invalid TCP option length. Length %d less than 2", len(data)) 286 | } 287 | opt.OptionLength = data[1] 288 | if opt.OptionLength < 2 { 289 | return fmt.Errorf("Invalid TCP option length %d < 2", opt.OptionLength) 290 | } else if int(opt.OptionLength) > len(data) { 291 | df.SetTruncated() 292 | return fmt.Errorf("Invalid TCP option length %d exceeds remaining %d bytes", opt.OptionLength, len(data)) 293 | } 294 | opt.OptionData = data[2:opt.OptionLength] 295 | } 296 | data = data[opt.OptionLength:] 297 | } 298 | return nil 299 | } 300 | 301 | func (t *TCP) CanDecode() gopacket.LayerClass { 302 | return LayerTypeTCP 303 | } 304 | 305 | func (t *TCP) NextLayerType() gopacket.LayerType { 306 | lt := t.DstPort.LayerType() 307 | if lt == gopacket.LayerTypePayload { 308 | lt = t.SrcPort.LayerType() 309 | } 310 | return lt 311 | } 312 | 313 | func decodeTCP(data []byte, p gopacket.PacketBuilder) error { 314 | tcp := &TCP{} 315 | err := tcp.DecodeFromBytes(data, p) 316 | p.AddLayer(tcp) 317 | p.SetTransportLayer(tcp) 318 | if err != nil { 319 | return err 320 | } 321 | if p.DecodeOptions().DecodeStreamsAsDatagrams { 322 | return p.NextDecoder(tcp.NextLayerType()) 323 | } else { 324 | return p.NextDecoder(gopacket.LayerTypePayload) 325 | } 326 | } 327 | 328 | func (t *TCP) TransportFlow() gopacket.Flow { 329 | return gopacket.NewFlow(EndpointTCPPort, t.sPort, t.dPort) 330 | } 331 | 332 | // For testing only 333 | func (t *TCP) SetInternalPortsForTesting() { 334 | t.sPort = make([]byte, 2) 335 | t.dPort = make([]byte, 2) 336 | binary.BigEndian.PutUint16(t.sPort, uint16(t.SrcPort)) 337 | binary.BigEndian.PutUint16(t.dPort, uint16(t.DstPort)) 338 | } 339 | -------------------------------------------------------------------------------- /ip4defrag/defrag.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Google, Inc. All rights reserved. 2 | // 3 | // Use of this source code is governed by a BSD-style license 4 | // that can be found in the LICENSE file in the root of the source 5 | // tree. 6 | 7 | // Package ip4defrag implements a IPv4 defragmenter 8 | package ip4defrag 9 | 10 | import ( 11 | "container/list" 12 | "errors" 13 | "fmt" 14 | "log" 15 | "sync" 16 | "time" 17 | 18 | "github.com/google/gopacket" 19 | "github.com/txthinking/ipio/layers" 20 | ) 21 | 22 | // Quick and Easy to use debug code to trace 23 | // how defrag works. 24 | var debug debugging = false // or flip to true 25 | type debugging bool 26 | 27 | func (d debugging) Printf(format string, args ...interface{}) { 28 | if d { 29 | log.Printf(format, args...) 30 | } 31 | } 32 | 33 | // Constants determining how to handle fragments. 34 | // Reference RFC 791, page 25 35 | const ( 36 | IPv4MinimumFragmentSize = 8 // Minimum size of a single fragment 37 | IPv4MaximumSize = 65535 // Maximum size of a fragment (2^16) 38 | IPv4MaximumFragmentOffset = 8183 // Maximum offset of a fragment 39 | IPv4MaximumFragmentListLen = 8192 // Back out if we get more than this many fragments 40 | ) 41 | 42 | // DefragIPv4 takes in an IPv4 packet with a fragment payload. 43 | // 44 | // It do not modify the IPv4 layer in place, 'in' remains untouched 45 | // It returns a ready-to be used IPv4 layer. 46 | // 47 | // If the passed-in IPv4 layer is NOT fragmented, it will 48 | // immediately return it without modifying the layer. 49 | // 50 | // If the IPv4 layer is a fragment and we don't have all 51 | // fragments, it will return nil and store whatever internal 52 | // information it needs to eventually defrag the packet. 53 | // 54 | // If the IPv4 layer is the last fragment needed to reconstruct 55 | // the packet, a new IPv4 layer will be returned, and will be set to 56 | // the entire defragmented packet, 57 | // 58 | // It use a map of all the running flows 59 | // 60 | // Usage example: 61 | // 62 | // func HandlePacket(in *layers.IPv4) err { 63 | // defragger := ip4defrag.NewIPv4Defragmenter() 64 | // in, err := defragger.DefragIPv4(in) 65 | // if err != nil { 66 | // return err 67 | // } else if in == nil { 68 | // return nil // packet fragment, we don't have whole packet yet. 69 | // } 70 | // // At this point, we know that 'in' is defragmented. 71 | // //It may be the same 'in' passed to 72 | // // HandlePacket, or it may not, but we don't really care :) 73 | // ... do stuff to 'in' ... 74 | //} 75 | // 76 | func (d *IPv4Defragmenter) DefragIPv4(in *layers.IPv4) (*layers.IPv4, error) { 77 | return d.DefragIPv4WithTimestamp(in, time.Now()) 78 | } 79 | 80 | // DefragIPv4WithTimestamp provides functionality of DefragIPv4 with 81 | // an additional timestamp parameter which is used for discarding 82 | // old fragments instead of time.Now() 83 | // 84 | // This is useful when operating on pcap files instead of live captured data 85 | // 86 | func (d *IPv4Defragmenter) DefragIPv4WithTimestamp(in *layers.IPv4, t time.Time) (*layers.IPv4, error) { 87 | // check if we need to defrag 88 | if st := d.dontDefrag(in); st == true { 89 | debug.Printf("defrag: do nothing, do not need anything") 90 | return in, nil 91 | } 92 | // perfom security checks 93 | if err := d.securityChecks(in); err != nil { 94 | debug.Printf("defrag: alert security check") 95 | return nil, err 96 | } 97 | 98 | // ok, got a fragment 99 | debug.Printf("defrag: got a new fragment in.Id=%d in.FragOffset=%d in.Flags=%d\n", 100 | in.Id, in.FragOffset*8, in.Flags) 101 | 102 | // have we already seen a flow between src/dst with that Id? 103 | ipf := newIPv4(in) 104 | var fl *fragmentList 105 | var exist bool 106 | d.Lock() 107 | fl, exist = d.ipFlows[ipf] 108 | if !exist { 109 | debug.Printf("defrag: unknown flow, creating a new one\n") 110 | fl = new(fragmentList) 111 | d.ipFlows[ipf] = fl 112 | } 113 | d.Unlock() 114 | // insert, and if final build it 115 | out, err2 := fl.insert(in, t) 116 | 117 | // at last, if we hit the maximum frag list len 118 | // without any defrag success, we just drop everything and 119 | // raise an error 120 | if out == nil && fl.List.Len()+1 > IPv4MaximumFragmentListLen { 121 | d.flush(ipf) 122 | return nil, fmt.Errorf("defrag: Fragment List hits its maximum"+ 123 | "size(%d), without success. Flushing the list", 124 | IPv4MaximumFragmentListLen) 125 | } 126 | 127 | // if we got a packet, it's a new one, and he is defragmented 128 | if out != nil { 129 | // when defrag is done for a flow between two ip 130 | // clean the list 131 | d.flush(ipf) 132 | return out, nil 133 | } 134 | return nil, err2 135 | } 136 | 137 | // DiscardOlderThan forgets all packets without any activity since 138 | // time t. It returns the number of FragmentList aka number of 139 | // fragment packets it has discarded. 140 | func (d *IPv4Defragmenter) DiscardOlderThan(t time.Time) int { 141 | var nb int 142 | d.Lock() 143 | for k, v := range d.ipFlows { 144 | if v.LastSeen.Before(t) { 145 | nb = nb + 1 146 | delete(d.ipFlows, k) 147 | } 148 | } 149 | d.Unlock() 150 | return nb 151 | } 152 | 153 | // flush the fragment list for a particular flow 154 | func (d *IPv4Defragmenter) flush(ipf ipv4) { 155 | d.Lock() 156 | delete(d.ipFlows, ipf) 157 | d.Unlock() 158 | } 159 | 160 | // dontDefrag returns true if the IPv4 packet do not need 161 | // any defragmentation 162 | func (d *IPv4Defragmenter) dontDefrag(ip *layers.IPv4) bool { 163 | // don't defrag packet with DF flag 164 | if ip.Flags&layers.IPv4DontFragment != 0 { 165 | return true 166 | } 167 | // don't defrag not fragmented ones 168 | if ip.Flags&layers.IPv4MoreFragments == 0 && ip.FragOffset == 0 { 169 | return true 170 | } 171 | return false 172 | } 173 | 174 | // securityChecks performs the needed security checks 175 | func (d *IPv4Defragmenter) securityChecks(ip *layers.IPv4) error { 176 | fragSize := ip.Length - uint16(ip.IHL)*4 177 | 178 | // don't allow small fragments outside of specification 179 | if fragSize < IPv4MinimumFragmentSize { 180 | return fmt.Errorf("defrag: fragment too small "+ 181 | "(handcrafted? %d < %d)", fragSize, IPv4MinimumFragmentSize) 182 | } 183 | 184 | // don't allow too big fragment offset 185 | if ip.FragOffset > IPv4MaximumFragmentOffset { 186 | return fmt.Errorf("defrag: fragment offset too big "+ 187 | "(handcrafted? %d > %d)", ip.FragOffset, IPv4MaximumFragmentOffset) 188 | } 189 | fragOffset := ip.FragOffset * 8 190 | 191 | // don't allow fragment that would oversize an IP packet 192 | if fragOffset+ip.Length > IPv4MaximumSize { 193 | return fmt.Errorf("defrag: fragment will overrun "+ 194 | "(handcrafted? %d > %d)", fragOffset+ip.Length, IPv4MaximumSize) 195 | } 196 | 197 | return nil 198 | } 199 | 200 | // fragmentList holds a container/list used to contains IP 201 | // packets/fragments. It stores internal counters to track the 202 | // maximum total of byte, and the current length it has received. 203 | // It also stores a flag to know if he has seen the last packet. 204 | type fragmentList struct { 205 | List list.List 206 | Highest uint16 207 | Current uint16 208 | FinalReceived bool 209 | LastSeen time.Time 210 | } 211 | 212 | // insert insert an IPv4 fragment/packet into the Fragment List 213 | // It use the following strategy : we are inserting fragment based 214 | // on their offset, latest first. This is sometimes called BSD-Right. 215 | // See: http://www.sans.org/reading-room/whitepapers/detection/ip-fragment-reassembly-scapy-33969 216 | func (f *fragmentList) insert(in *layers.IPv4, t time.Time) (*layers.IPv4, error) { 217 | // TODO: should keep a copy of *in in the list 218 | // or not (ie the packet source is reliable) ? -> depends on Lazy / last packet 219 | fragOffset := in.FragOffset * 8 220 | if fragOffset >= f.Highest { 221 | f.List.PushBack(in) 222 | } else { 223 | for e := f.List.Front(); e != nil; e = e.Next() { 224 | frag, _ := e.Value.(*layers.IPv4) 225 | if in.FragOffset == frag.FragOffset { 226 | // TODO: what if we receive a fragment 227 | // that begins with duplicate data but 228 | // *also* has new data? For example: 229 | // 230 | // AAAA 231 | // BB 232 | // BBCC 233 | // DDDD 234 | // 235 | // In this situation we completely 236 | // ignore CC and the complete packet can 237 | // never be reassembled. 238 | debug.Printf("defrag: ignoring frag %d as we already have it (duplicate?)\n", 239 | fragOffset) 240 | return nil, nil 241 | } 242 | if in.FragOffset < frag.FragOffset { 243 | debug.Printf("defrag: inserting frag %d before existing frag %d\n", 244 | fragOffset, frag.FragOffset*8) 245 | f.List.InsertBefore(in, e) 246 | break 247 | } 248 | } 249 | } 250 | 251 | f.LastSeen = t 252 | 253 | fragLength := in.Length - 20 254 | // After inserting the Fragment, we update the counters 255 | if f.Highest < fragOffset+fragLength { 256 | f.Highest = fragOffset + fragLength 257 | } 258 | f.Current = f.Current + fragLength 259 | 260 | debug.Printf("defrag: insert ListLen: %d Highest:%d Current:%d\n", 261 | f.List.Len(), 262 | f.Highest, f.Current) 263 | 264 | // Final Fragment ? 265 | if in.Flags&layers.IPv4MoreFragments == 0 { 266 | f.FinalReceived = true 267 | } 268 | // Ready to try defrag ? 269 | if f.FinalReceived && f.Highest == f.Current { 270 | return f.build(in) 271 | } 272 | return nil, nil 273 | } 274 | 275 | // Build builds the final datagram, modifying ip in place. 276 | // It puts priority to packet in the early position of the list. 277 | // See Insert for more details. 278 | func (f *fragmentList) build(in *layers.IPv4) (*layers.IPv4, error) { 279 | var final []byte 280 | var currentOffset uint16 281 | 282 | debug.Printf("defrag: building the datagram \n") 283 | for e := f.List.Front(); e != nil; e = e.Next() { 284 | frag, _ := e.Value.(*layers.IPv4) 285 | if frag.FragOffset*8 == currentOffset { 286 | debug.Printf("defrag: building - adding %d\n", frag.FragOffset*8) 287 | final = append(final, frag.Payload...) 288 | currentOffset = currentOffset + frag.Length - 20 289 | } else if frag.FragOffset*8 < currentOffset { 290 | // overlapping fragment - let's take only what we need 291 | startAt := currentOffset - frag.FragOffset*8 292 | debug.Printf("defrag: building - overlapping, starting at %d\n", 293 | startAt) 294 | if startAt > frag.Length-20 { 295 | return nil, errors.New("defrag: building - invalid fragment") 296 | } 297 | final = append(final, frag.Payload[startAt:]...) 298 | currentOffset = currentOffset + frag.FragOffset*8 299 | } else { 300 | // Houston - we have an hole ! 301 | debug.Printf("defrag: hole found while building, " + 302 | "stopping the defrag process\n") 303 | return nil, errors.New("defrag: building - hole found") 304 | } 305 | debug.Printf("defrag: building - next is %d\n", currentOffset) 306 | } 307 | 308 | // TODO recompute IP Checksum 309 | out := &layers.IPv4{ 310 | Version: in.Version, 311 | IHL: in.IHL, 312 | TOS: in.TOS, 313 | Length: f.Highest, 314 | Id: in.Id, 315 | Flags: 0, 316 | FragOffset: 0, 317 | TTL: in.TTL, 318 | Protocol: in.Protocol, 319 | Checksum: 0, 320 | SrcIP: in.SrcIP, 321 | DstIP: in.DstIP, 322 | Options: in.Options, 323 | Padding: in.Padding, 324 | } 325 | out.Payload = final 326 | 327 | return out, nil 328 | } 329 | 330 | // ipv4 is a struct to be used as a key. 331 | type ipv4 struct { 332 | ip4 gopacket.Flow 333 | id uint16 334 | } 335 | 336 | // newIPv4 returns a new initialized IPv4 Flow 337 | func newIPv4(ip *layers.IPv4) ipv4 { 338 | return ipv4{ 339 | ip4: ip.NetworkFlow(), 340 | id: ip.Id, 341 | } 342 | } 343 | 344 | // IPv4Defragmenter is a struct which embedded a map of 345 | // all fragment/packet. 346 | type IPv4Defragmenter struct { 347 | sync.RWMutex 348 | ipFlows map[ipv4]*fragmentList 349 | } 350 | 351 | // NewIPv4Defragmenter returns a new IPv4Defragmenter 352 | // with an initialized map. 353 | func NewIPv4Defragmenter() *IPv4Defragmenter { 354 | return &IPv4Defragmenter{ 355 | ipFlows: make(map[ipv4]*fragmentList), 356 | } 357 | } 358 | -------------------------------------------------------------------------------- /layers/ip6.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 Google, Inc. All rights reserved. 2 | // Copyright 2009-2011 Andreas Krennmair. All rights reserved. 3 | // 4 | // Use of this source code is governed by a BSD-style license 5 | // that can be found in the LICENSE file in the root of the source 6 | // tree. 7 | 8 | package layers 9 | 10 | import ( 11 | "encoding/binary" 12 | "errors" 13 | "fmt" 14 | "net" 15 | 16 | "github.com/google/gopacket" 17 | ) 18 | 19 | const ( 20 | // IPv6HopByHopOptionJumbogram code as defined in RFC 2675 21 | IPv6HopByHopOptionJumbogram = 0xC2 22 | ) 23 | 24 | const ( 25 | ipv6MaxPayloadLength = 65535 26 | ) 27 | 28 | // IPv6 is the layer for the IPv6 header. 29 | type IPv6 struct { 30 | // http://www.networksorcery.com/enp/protocol/ipv6.htm 31 | BaseLayer 32 | Version uint8 33 | TrafficClass uint8 34 | FlowLabel uint32 35 | Length uint16 36 | NextHeader IPProtocol 37 | HopLimit uint8 38 | SrcIP net.IP 39 | DstIP net.IP 40 | HopByHop *IPv6HopByHop 41 | // hbh will be pointed to by HopByHop if that layer exists. 42 | hbh IPv6HopByHop 43 | } 44 | 45 | // LayerType returns LayerTypeIPv6 46 | func (ipv6 *IPv6) LayerType() gopacket.LayerType { return LayerTypeIPv6 } 47 | 48 | // NetworkFlow returns this new Flow (EndpointIPv6, SrcIP, DstIP) 49 | func (ipv6 *IPv6) NetworkFlow() gopacket.Flow { 50 | return gopacket.NewFlow(EndpointIPv6, ipv6.SrcIP, ipv6.DstIP) 51 | } 52 | 53 | // Search for Jumbo Payload TLV in IPv6HopByHop and return (length, true) if found 54 | func getIPv6HopByHopJumboLength(hopopts *IPv6HopByHop) (uint32, bool, error) { 55 | var tlv *IPv6HopByHopOption 56 | 57 | for _, t := range hopopts.Options { 58 | if t.OptionType == IPv6HopByHopOptionJumbogram { 59 | tlv = t 60 | break 61 | } 62 | } 63 | if tlv == nil { 64 | // Not found 65 | return 0, false, nil 66 | } 67 | if len(tlv.OptionData) != 4 { 68 | return 0, false, errors.New("Jumbo length TLV data must have length 4") 69 | } 70 | l := binary.BigEndian.Uint32(tlv.OptionData) 71 | if l <= ipv6MaxPayloadLength { 72 | return 0, false, fmt.Errorf("Jumbo length cannot be less than %d", ipv6MaxPayloadLength+1) 73 | } 74 | // Found 75 | return l, true, nil 76 | } 77 | 78 | // Adds zero-valued Jumbo TLV to IPv6 header if it does not exist 79 | // (if necessary add hop-by-hop header) 80 | func addIPv6JumboOption(ip6 *IPv6) { 81 | var tlv *IPv6HopByHopOption 82 | 83 | if ip6.HopByHop == nil { 84 | // Add IPv6 HopByHop 85 | ip6.HopByHop = &IPv6HopByHop{} 86 | ip6.HopByHop.NextHeader = ip6.NextHeader 87 | ip6.HopByHop.HeaderLength = 0 88 | ip6.NextHeader = IPProtocolIPv6HopByHop 89 | } 90 | for _, t := range ip6.HopByHop.Options { 91 | if t.OptionType == IPv6HopByHopOptionJumbogram { 92 | tlv = t 93 | break 94 | } 95 | } 96 | if tlv == nil { 97 | // Add Jumbo TLV 98 | tlv = &IPv6HopByHopOption{} 99 | ip6.HopByHop.Options = append(ip6.HopByHop.Options, tlv) 100 | } 101 | tlv.SetJumboLength(0) 102 | } 103 | 104 | // Set jumbo length in serialized IPv6 payload (starting with HopByHop header) 105 | func setIPv6PayloadJumboLength(hbh []byte) error { 106 | pLen := len(hbh) 107 | if pLen < 8 { 108 | //HopByHop is minimum 8 bytes 109 | return fmt.Errorf("Invalid IPv6 payload (length %d)", pLen) 110 | } 111 | hbhLen := int((hbh[1] + 1) * 8) 112 | if hbhLen > pLen { 113 | return fmt.Errorf("Invalid hop-by-hop length (length: %d, payload: %d", hbhLen, pLen) 114 | } 115 | offset := 2 //start with options 116 | for offset < hbhLen { 117 | opt := hbh[offset] 118 | if opt == 0 { 119 | //Pad1 120 | offset++ 121 | continue 122 | } 123 | optLen := int(hbh[offset+1]) 124 | if opt == IPv6HopByHopOptionJumbogram { 125 | if optLen == 4 { 126 | binary.BigEndian.PutUint32(hbh[offset+2:], uint32(pLen)) 127 | return nil 128 | } 129 | return fmt.Errorf("Jumbo TLV too short (%d bytes)", optLen) 130 | } 131 | offset += 2 + optLen 132 | } 133 | return errors.New("Jumbo TLV not found") 134 | } 135 | 136 | // SerializeTo writes the serialized form of this layer into the 137 | // SerializationBuffer, implementing gopacket.SerializableLayer. 138 | // See the docs for gopacket.SerializableLayer for more info. 139 | func (ipv6 *IPv6) SerializeTo(b gopacket.SerializeBuffer, opts gopacket.SerializeOptions) error { 140 | var jumbo bool 141 | var err error 142 | 143 | payload := b.Bytes() 144 | pLen := len(payload) 145 | if pLen > ipv6MaxPayloadLength { 146 | jumbo = true 147 | if opts.FixLengths { 148 | // We need to set the length later because the hop-by-hop header may 149 | // not exist or else need padding, so pLen may yet change 150 | addIPv6JumboOption(ipv6) 151 | } else if ipv6.HopByHop == nil { 152 | return fmt.Errorf("Cannot fit payload length of %d into IPv6 packet", pLen) 153 | } else { 154 | _, ok, err := getIPv6HopByHopJumboLength(ipv6.HopByHop) 155 | if err != nil { 156 | return err 157 | } 158 | if !ok { 159 | return errors.New("Missing jumbo length hop-by-hop option") 160 | } 161 | } 162 | } 163 | 164 | hbhAlreadySerialized := false 165 | if ipv6.HopByHop != nil { 166 | for _, l := range b.Layers() { 167 | if l == LayerTypeIPv6HopByHop { 168 | hbhAlreadySerialized = true 169 | break 170 | } 171 | } 172 | } 173 | if ipv6.HopByHop != nil && !hbhAlreadySerialized { 174 | if ipv6.NextHeader != IPProtocolIPv6HopByHop { 175 | // Just fix it instead of throwing an error 176 | ipv6.NextHeader = IPProtocolIPv6HopByHop 177 | } 178 | err = ipv6.HopByHop.SerializeTo(b, opts) 179 | if err != nil { 180 | return err 181 | } 182 | payload = b.Bytes() 183 | pLen = len(payload) 184 | if opts.FixLengths && jumbo { 185 | err := setIPv6PayloadJumboLength(payload) 186 | if err != nil { 187 | return err 188 | } 189 | } 190 | } 191 | 192 | if !jumbo && pLen > ipv6MaxPayloadLength { 193 | return errors.New("Cannot fit payload into IPv6 header") 194 | } 195 | bytes, err := b.PrependBytes(40) 196 | if err != nil { 197 | return err 198 | } 199 | bytes[0] = (ipv6.Version << 4) | (ipv6.TrafficClass >> 4) 200 | bytes[1] = (ipv6.TrafficClass << 4) | uint8(ipv6.FlowLabel>>16) 201 | binary.BigEndian.PutUint16(bytes[2:], uint16(ipv6.FlowLabel)) 202 | if opts.FixLengths { 203 | if jumbo { 204 | ipv6.Length = 0 205 | } else { 206 | ipv6.Length = uint16(pLen) 207 | } 208 | } 209 | binary.BigEndian.PutUint16(bytes[4:], ipv6.Length) 210 | bytes[6] = byte(ipv6.NextHeader) 211 | bytes[7] = byte(ipv6.HopLimit) 212 | if err := ipv6.AddressTo16(); err != nil { 213 | return err 214 | } 215 | copy(bytes[8:], ipv6.SrcIP) 216 | copy(bytes[24:], ipv6.DstIP) 217 | return nil 218 | } 219 | 220 | // DecodeFromBytes implementation according to gopacket.DecodingLayer 221 | func (ipv6 *IPv6) DecodeFromBytes(data []byte, df gopacket.DecodeFeedback) error { 222 | if len(data) < 40 { 223 | df.SetTruncated() 224 | return fmt.Errorf("Invalid ip6 header. Length %d less than 40", len(data)) 225 | } 226 | ipv6.Version = uint8(data[0]) >> 4 227 | ipv6.TrafficClass = uint8((binary.BigEndian.Uint16(data[0:2]) >> 4) & 0x00FF) 228 | ipv6.FlowLabel = binary.BigEndian.Uint32(data[0:4]) & 0x000FFFFF 229 | ipv6.Length = binary.BigEndian.Uint16(data[4:6]) 230 | ipv6.NextHeader = IPProtocol(data[6]) 231 | ipv6.HopLimit = data[7] 232 | ipv6.SrcIP = data[8:24] 233 | ipv6.DstIP = data[24:40] 234 | ipv6.HopByHop = nil 235 | ipv6.BaseLayer = BaseLayer{data[:40], data[40:]} 236 | 237 | // We treat a HopByHop IPv6 option as part of the IPv6 packet, since its 238 | // options are crucial for understanding what's actually happening per packet. 239 | if ipv6.NextHeader == IPProtocolIPv6HopByHop { 240 | err := ipv6.hbh.DecodeFromBytes(ipv6.Payload, df) 241 | if err != nil { 242 | return err 243 | } 244 | ipv6.HopByHop = &ipv6.hbh 245 | pEnd, jumbo, err := getIPv6HopByHopJumboLength(ipv6.HopByHop) 246 | if err != nil { 247 | return err 248 | } 249 | if jumbo && ipv6.Length == 0 { 250 | pEnd := int(pEnd) 251 | if pEnd > len(ipv6.Payload) { 252 | df.SetTruncated() 253 | pEnd = len(ipv6.Payload) 254 | } 255 | ipv6.Payload = ipv6.Payload[:pEnd] 256 | return nil 257 | } else if jumbo && ipv6.Length != 0 { 258 | return errors.New("IPv6 has jumbo length and IPv6 length is not 0") 259 | } else if !jumbo && ipv6.Length == 0 { 260 | return errors.New("IPv6 length 0, but HopByHop header does not have jumbogram option") 261 | } else { 262 | ipv6.Payload = ipv6.Payload[ipv6.hbh.ActualLength:] 263 | } 264 | } 265 | 266 | if ipv6.Length == 0 { 267 | return fmt.Errorf("IPv6 length 0, but next header is %v, not HopByHop", ipv6.NextHeader) 268 | } 269 | 270 | pEnd := int(ipv6.Length) 271 | if pEnd > len(ipv6.Payload) { 272 | df.SetTruncated() 273 | pEnd = len(ipv6.Payload) 274 | } 275 | ipv6.Payload = ipv6.Payload[:pEnd] 276 | 277 | return nil 278 | } 279 | 280 | // CanDecode implementation according to gopacket.DecodingLayer 281 | func (ipv6 *IPv6) CanDecode() gopacket.LayerClass { 282 | return LayerTypeIPv6 283 | } 284 | 285 | // NextLayerType implementation according to gopacket.DecodingLayer 286 | func (ipv6 *IPv6) NextLayerType() gopacket.LayerType { 287 | if ipv6.HopByHop != nil { 288 | return ipv6.HopByHop.NextHeader.LayerType() 289 | } 290 | return ipv6.NextHeader.LayerType() 291 | } 292 | 293 | func decodeIPv6(data []byte, p gopacket.PacketBuilder) error { 294 | ip6 := &IPv6{} 295 | err := ip6.DecodeFromBytes(data, p) 296 | p.AddLayer(ip6) 297 | p.SetNetworkLayer(ip6) 298 | if ip6.HopByHop != nil { 299 | p.AddLayer(ip6.HopByHop) 300 | } 301 | if err != nil { 302 | return err 303 | } 304 | return p.NextDecoder(ip6.NextLayerType()) 305 | } 306 | 307 | type ipv6HeaderTLVOption struct { 308 | OptionType, OptionLength uint8 309 | ActualLength int 310 | OptionData []byte 311 | OptionAlignment [2]uint8 // Xn+Y = [2]uint8{X, Y} 312 | } 313 | 314 | func (h *ipv6HeaderTLVOption) serializeTo(data []byte, fixLengths bool, dryrun bool) int { 315 | if fixLengths { 316 | h.OptionLength = uint8(len(h.OptionData)) 317 | } 318 | length := int(h.OptionLength) + 2 319 | if !dryrun { 320 | data[0] = h.OptionType 321 | data[1] = h.OptionLength 322 | copy(data[2:], h.OptionData) 323 | } 324 | return length 325 | } 326 | 327 | func decodeIPv6HeaderTLVOption(data []byte) (h *ipv6HeaderTLVOption) { 328 | h = &ipv6HeaderTLVOption{} 329 | if data[0] == 0 { 330 | h.ActualLength = 1 331 | return 332 | } 333 | h.OptionType = data[0] 334 | h.OptionLength = data[1] 335 | h.ActualLength = int(h.OptionLength) + 2 336 | h.OptionData = data[2:h.ActualLength] 337 | return 338 | } 339 | 340 | func serializeTLVOptionPadding(data []byte, padLength int) { 341 | if padLength <= 0 { 342 | return 343 | } 344 | if padLength == 1 { 345 | data[0] = 0x0 346 | return 347 | } 348 | tlvLength := uint8(padLength) - 2 349 | data[0] = 0x1 350 | data[1] = tlvLength 351 | if tlvLength != 0 { 352 | for k := range data[2:] { 353 | data[k+2] = 0x0 354 | } 355 | } 356 | return 357 | } 358 | 359 | // If buf is 'nil' do a serialize dry run 360 | func serializeIPv6HeaderTLVOptions(buf []byte, options []*ipv6HeaderTLVOption, fixLengths bool) int { 361 | var l int 362 | 363 | dryrun := buf == nil 364 | length := 2 365 | for _, opt := range options { 366 | if fixLengths { 367 | x := int(opt.OptionAlignment[0]) 368 | y := int(opt.OptionAlignment[1]) 369 | if x != 0 { 370 | n := length / x 371 | offset := x*n + y 372 | if offset < length { 373 | offset += x 374 | } 375 | if length != offset { 376 | pad := offset - length 377 | if !dryrun { 378 | serializeTLVOptionPadding(buf[length-2:], pad) 379 | } 380 | length += pad 381 | } 382 | } 383 | } 384 | if dryrun { 385 | l = opt.serializeTo(nil, fixLengths, true) 386 | } else { 387 | l = opt.serializeTo(buf[length-2:], fixLengths, false) 388 | } 389 | length += l 390 | } 391 | if fixLengths { 392 | pad := length % 8 393 | if pad != 0 { 394 | if !dryrun { 395 | serializeTLVOptionPadding(buf[length-2:], pad) 396 | } 397 | length += pad 398 | } 399 | } 400 | return length - 2 401 | } 402 | 403 | type ipv6ExtensionBase struct { 404 | BaseLayer 405 | NextHeader IPProtocol 406 | HeaderLength uint8 407 | ActualLength int 408 | } 409 | 410 | func decodeIPv6ExtensionBase(data []byte, df gopacket.DecodeFeedback) (i ipv6ExtensionBase, returnedErr error) { 411 | if len(data) < 2 { 412 | df.SetTruncated() 413 | return ipv6ExtensionBase{}, fmt.Errorf("Invalid ip6-extension header. Length %d less than 2", len(data)) 414 | } 415 | i.NextHeader = IPProtocol(data[0]) 416 | i.HeaderLength = data[1] 417 | i.ActualLength = int(i.HeaderLength)*8 + 8 418 | if len(data) < i.ActualLength { 419 | return ipv6ExtensionBase{}, fmt.Errorf("Invalid ip6-extension header. Length %d less than specified length %d", len(data), i.ActualLength) 420 | } 421 | i.Contents = data[:i.ActualLength] 422 | i.Payload = data[i.ActualLength:] 423 | return 424 | } 425 | 426 | // IPv6ExtensionSkipper is a DecodingLayer which decodes and ignores v6 427 | // extensions. You can use it with a DecodingLayerParser to handle IPv6 stacks 428 | // which may or may not have extensions. 429 | type IPv6ExtensionSkipper struct { 430 | NextHeader IPProtocol 431 | BaseLayer 432 | } 433 | 434 | // DecodeFromBytes implementation according to gopacket.DecodingLayer 435 | func (i *IPv6ExtensionSkipper) DecodeFromBytes(data []byte, df gopacket.DecodeFeedback) error { 436 | extension, err := decodeIPv6ExtensionBase(data, df) 437 | if err != nil { 438 | return err 439 | } 440 | i.BaseLayer = BaseLayer{data[:extension.ActualLength], data[extension.ActualLength:]} 441 | i.NextHeader = extension.NextHeader 442 | return nil 443 | } 444 | 445 | // CanDecode implementation according to gopacket.DecodingLayer 446 | func (i *IPv6ExtensionSkipper) CanDecode() gopacket.LayerClass { 447 | return LayerClassIPv6Extension 448 | } 449 | 450 | // NextLayerType implementation according to gopacket.DecodingLayer 451 | func (i *IPv6ExtensionSkipper) NextLayerType() gopacket.LayerType { 452 | return i.NextHeader.LayerType() 453 | } 454 | 455 | // IPv6HopByHopOption is a TLV option present in an IPv6 hop-by-hop extension. 456 | type IPv6HopByHopOption ipv6HeaderTLVOption 457 | 458 | // IPv6HopByHop is the IPv6 hop-by-hop extension. 459 | type IPv6HopByHop struct { 460 | ipv6ExtensionBase 461 | Options []*IPv6HopByHopOption 462 | } 463 | 464 | // LayerType returns LayerTypeIPv6HopByHop. 465 | func (i *IPv6HopByHop) LayerType() gopacket.LayerType { return LayerTypeIPv6HopByHop } 466 | 467 | // SerializeTo implementation according to gopacket.SerializableLayer 468 | func (i *IPv6HopByHop) SerializeTo(b gopacket.SerializeBuffer, opts gopacket.SerializeOptions) error { 469 | var bytes []byte 470 | var err error 471 | 472 | o := make([]*ipv6HeaderTLVOption, 0, len(i.Options)) 473 | for _, v := range i.Options { 474 | o = append(o, (*ipv6HeaderTLVOption)(v)) 475 | } 476 | 477 | l := serializeIPv6HeaderTLVOptions(nil, o, opts.FixLengths) 478 | bytes, err = b.PrependBytes(l) 479 | if err != nil { 480 | return err 481 | } 482 | serializeIPv6HeaderTLVOptions(bytes, o, opts.FixLengths) 483 | 484 | length := len(bytes) + 2 485 | if length%8 != 0 { 486 | return errors.New("IPv6HopByHop actual length must be multiple of 8") 487 | } 488 | bytes, err = b.PrependBytes(2) 489 | if err != nil { 490 | return err 491 | } 492 | bytes[0] = uint8(i.NextHeader) 493 | if opts.FixLengths { 494 | i.HeaderLength = uint8((length / 8) - 1) 495 | } 496 | bytes[1] = uint8(i.HeaderLength) 497 | return nil 498 | } 499 | 500 | // DecodeFromBytes implementation according to gopacket.DecodingLayer 501 | func (i *IPv6HopByHop) DecodeFromBytes(data []byte, df gopacket.DecodeFeedback) error { 502 | var err error 503 | i.ipv6ExtensionBase, err = decodeIPv6ExtensionBase(data, df) 504 | if err != nil { 505 | return err 506 | } 507 | offset := 2 508 | for offset < i.ActualLength { 509 | opt := decodeIPv6HeaderTLVOption(data[offset:]) 510 | i.Options = append(i.Options, (*IPv6HopByHopOption)(opt)) 511 | offset += opt.ActualLength 512 | } 513 | return nil 514 | } 515 | 516 | func decodeIPv6HopByHop(data []byte, p gopacket.PacketBuilder) error { 517 | i := &IPv6HopByHop{} 518 | err := i.DecodeFromBytes(data, p) 519 | p.AddLayer(i) 520 | if err != nil { 521 | return err 522 | } 523 | return p.NextDecoder(i.NextHeader) 524 | } 525 | 526 | // SetJumboLength adds the IPv6HopByHopOptionJumbogram with the given length 527 | func (o *IPv6HopByHopOption) SetJumboLength(len uint32) { 528 | o.OptionType = IPv6HopByHopOptionJumbogram 529 | o.OptionLength = 4 530 | o.ActualLength = 6 531 | if o.OptionData == nil { 532 | o.OptionData = make([]byte, 4) 533 | } 534 | binary.BigEndian.PutUint32(o.OptionData, len) 535 | o.OptionAlignment = [2]uint8{4, 2} 536 | } 537 | 538 | // IPv6Routing is the IPv6 routing extension. 539 | type IPv6Routing struct { 540 | ipv6ExtensionBase 541 | RoutingType uint8 542 | SegmentsLeft uint8 543 | // This segment is supposed to be zero according to RFC2460, the second set of 544 | // 4 bytes in the extension. 545 | Reserved []byte 546 | // SourceRoutingIPs is the set of IPv6 addresses requested for source routing, 547 | // set only if RoutingType == 0. 548 | SourceRoutingIPs []net.IP 549 | } 550 | 551 | // LayerType returns LayerTypeIPv6Routing. 552 | func (i *IPv6Routing) LayerType() gopacket.LayerType { return LayerTypeIPv6Routing } 553 | 554 | func decodeIPv6Routing(data []byte, p gopacket.PacketBuilder) error { 555 | base, err := decodeIPv6ExtensionBase(data, p) 556 | if err != nil { 557 | return err 558 | } 559 | i := &IPv6Routing{ 560 | ipv6ExtensionBase: base, 561 | RoutingType: data[2], 562 | SegmentsLeft: data[3], 563 | Reserved: data[4:8], 564 | } 565 | switch i.RoutingType { 566 | case 0: // Source routing 567 | if (i.ActualLength-8)%16 != 0 { 568 | return fmt.Errorf("Invalid IPv6 source routing, length of type 0 packet %d", i.ActualLength) 569 | } 570 | for d := i.Contents[8:]; len(d) >= 16; d = d[16:] { 571 | i.SourceRoutingIPs = append(i.SourceRoutingIPs, net.IP(d[:16])) 572 | } 573 | default: 574 | return fmt.Errorf("Unknown IPv6 routing header type %d", i.RoutingType) 575 | } 576 | p.AddLayer(i) 577 | return p.NextDecoder(i.NextHeader) 578 | } 579 | 580 | // IPv6Fragment is the IPv6 fragment header, used for packet 581 | // fragmentation/defragmentation. 582 | type IPv6Fragment struct { 583 | BaseLayer 584 | NextHeader IPProtocol 585 | // Reserved1 is bits [8-16), from least to most significant, 0-indexed 586 | Reserved1 uint8 587 | FragmentOffset uint16 588 | // Reserved2 is bits [29-31), from least to most significant, 0-indexed 589 | Reserved2 uint8 590 | MoreFragments bool 591 | Identification uint32 592 | } 593 | 594 | // LayerType returns LayerTypeIPv6Fragment. 595 | func (i *IPv6Fragment) LayerType() gopacket.LayerType { return LayerTypeIPv6Fragment } 596 | 597 | func decodeIPv6Fragment(data []byte, p gopacket.PacketBuilder) error { 598 | if len(data) < 8 { 599 | p.SetTruncated() 600 | return fmt.Errorf("Invalid ip6-fragment header. Length %d less than 8", len(data)) 601 | } 602 | i := &IPv6Fragment{ 603 | BaseLayer: BaseLayer{data[:8], data[8:]}, 604 | NextHeader: IPProtocol(data[0]), 605 | Reserved1: data[1], 606 | FragmentOffset: binary.BigEndian.Uint16(data[2:4]) >> 3, 607 | Reserved2: data[3] & 0x6 >> 1, 608 | MoreFragments: data[3]&0x1 != 0, 609 | Identification: binary.BigEndian.Uint32(data[4:8]), 610 | } 611 | p.AddLayer(i) 612 | return p.NextDecoder(gopacket.DecodeFragment) 613 | } 614 | 615 | // IPv6DestinationOption is a TLV option present in an IPv6 destination options extension. 616 | type IPv6DestinationOption ipv6HeaderTLVOption 617 | 618 | // IPv6Destination is the IPv6 destination options header. 619 | type IPv6Destination struct { 620 | ipv6ExtensionBase 621 | Options []*IPv6DestinationOption 622 | } 623 | 624 | // LayerType returns LayerTypeIPv6Destination. 625 | func (i *IPv6Destination) LayerType() gopacket.LayerType { return LayerTypeIPv6Destination } 626 | 627 | // DecodeFromBytes implementation according to gopacket.DecodingLayer 628 | func (i *IPv6Destination) DecodeFromBytes(data []byte, df gopacket.DecodeFeedback) error { 629 | var err error 630 | i.ipv6ExtensionBase, err = decodeIPv6ExtensionBase(data, df) 631 | if err != nil { 632 | return err 633 | } 634 | offset := 2 635 | for offset < i.ActualLength { 636 | opt := decodeIPv6HeaderTLVOption(data[offset:]) 637 | i.Options = append(i.Options, (*IPv6DestinationOption)(opt)) 638 | offset += opt.ActualLength 639 | } 640 | return nil 641 | } 642 | 643 | func decodeIPv6Destination(data []byte, p gopacket.PacketBuilder) error { 644 | i := &IPv6Destination{} 645 | err := i.DecodeFromBytes(data, p) 646 | p.AddLayer(i) 647 | if err != nil { 648 | return err 649 | } 650 | return p.NextDecoder(i.NextHeader) 651 | } 652 | 653 | // SerializeTo writes the serialized form of this layer into the 654 | // SerializationBuffer, implementing gopacket.SerializableLayer. 655 | // See the docs for gopacket.SerializableLayer for more info. 656 | func (i *IPv6Destination) SerializeTo(b gopacket.SerializeBuffer, opts gopacket.SerializeOptions) error { 657 | var bytes []byte 658 | var err error 659 | 660 | o := make([]*ipv6HeaderTLVOption, 0, len(i.Options)) 661 | for _, v := range i.Options { 662 | o = append(o, (*ipv6HeaderTLVOption)(v)) 663 | } 664 | 665 | l := serializeIPv6HeaderTLVOptions(nil, o, opts.FixLengths) 666 | bytes, err = b.PrependBytes(l) 667 | if err != nil { 668 | return err 669 | } 670 | serializeIPv6HeaderTLVOptions(bytes, o, opts.FixLengths) 671 | 672 | length := len(bytes) + 2 673 | if length%8 != 0 { 674 | return errors.New("IPv6Destination actual length must be multiple of 8") 675 | } 676 | bytes, err = b.PrependBytes(2) 677 | if err != nil { 678 | return err 679 | } 680 | bytes[0] = uint8(i.NextHeader) 681 | if opts.FixLengths { 682 | i.HeaderLength = uint8((length / 8) - 1) 683 | } 684 | bytes[1] = uint8(i.HeaderLength) 685 | return nil 686 | } 687 | 688 | func checkIPv6Address(addr net.IP) error { 689 | if len(addr) == net.IPv6len { 690 | return nil 691 | } 692 | if len(addr) == net.IPv4len { 693 | return errors.New("address is IPv4") 694 | } 695 | return fmt.Errorf("wrong length of %d bytes instead of %d", len(addr), net.IPv6len) 696 | } 697 | 698 | // AddressTo16 ensures IPv6.SrcIP and IPv6.DstIP are actually IPv6 addresses (i.e. 16 byte addresses) 699 | func (ipv6 *IPv6) AddressTo16() error { 700 | if err := checkIPv6Address(ipv6.SrcIP); err != nil { 701 | return fmt.Errorf("Invalid source IPv6 address (%s)", err) 702 | } 703 | if err := checkIPv6Address(ipv6.DstIP); err != nil { 704 | return fmt.Errorf("Invalid destination IPv6 address (%s)", err) 705 | } 706 | return nil 707 | } 708 | -------------------------------------------------------------------------------- /OPENSOURCELICENSES: -------------------------------------------------------------------------------- 1 | ### cli 2 | 3 | https://github.com/urfave/cli 4 | 5 | MIT License 6 | 7 | Copyright (c) 2016 Jeremy Saenz & Contributors 8 | 9 | Permission is hereby granted, free of charge, to any person obtaining a copy 10 | of this software and associated documentation files (the "Software"), to deal 11 | in the Software without restriction, including without limitation the rights 12 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | copies of the Software, and to permit persons to whom the Software is 14 | furnished to do so, subject to the following conditions: 15 | 16 | The above copyright notice and this permission notice shall be included in all 17 | copies or substantial portions of the Software. 18 | 19 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 25 | SOFTWARE. 26 | 27 | ### dns 28 | 29 | https://github.com/miekg/dns 30 | 31 | Copyright (c) 2009 The Go Authors. All rights reserved. 32 | 33 | Redistribution and use in source and binary forms, with or without 34 | modification, are permitted provided that the following conditions are 35 | met: 36 | 37 | * Redistributions of source code must retain the above copyright 38 | notice, this list of conditions and the following disclaimer. 39 | * Redistributions in binary form must reproduce the above 40 | copyright notice, this list of conditions and the following disclaimer 41 | in the documentation and/or other materials provided with the 42 | distribution. 43 | * Neither the name of Google Inc. nor the names of its 44 | contributors may be used to endorse or promote products derived from 45 | this software without specific prior written permission. 46 | 47 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 48 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 49 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 50 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 51 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 52 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 53 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 54 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 55 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 56 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 57 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 58 | 59 | As this is fork of the official Go code the same license applies. 60 | Extensions of the original work are copyright (c) 2011 Miek Gieben 61 | 62 | ### gopacket 63 | 64 | https://github.com/google/gopacket 65 | 66 | Copyright (c) 2012 Google, Inc. All rights reserved. 67 | Copyright (c) 2009-2011 Andreas Krennmair. All rights reserved. 68 | 69 | Redistribution and use in source and binary forms, with or without 70 | modification, are permitted provided that the following conditions are 71 | met: 72 | 73 | * Redistributions of source code must retain the above copyright 74 | notice, this list of conditions and the following disclaimer. 75 | * Redistributions in binary form must reproduce the above 76 | copyright notice, this list of conditions and the following disclaimer 77 | in the documentation and/or other materials provided with the 78 | distribution. 79 | * Neither the name of Andreas Krennmair, Google, nor the names of its 80 | contributors may be used to endorse or promote products derived from 81 | this software without specific prior written permission. 82 | 83 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 84 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 85 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 86 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 87 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 88 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 89 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 90 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 91 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 92 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 93 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 94 | 95 | ### gvisor 96 | 97 | https://github.com/google/gvisor 98 | 99 | 100 | Apache License 101 | Version 2.0, January 2004 102 | http://www.apache.org/licenses/ 103 | 104 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 105 | 106 | 1. Definitions. 107 | 108 | "License" shall mean the terms and conditions for use, reproduction, 109 | and distribution as defined by Sections 1 through 9 of this document. 110 | 111 | "Licensor" shall mean the copyright owner or entity authorized by 112 | the copyright owner that is granting the License. 113 | 114 | "Legal Entity" shall mean the union of the acting entity and all 115 | other entities that control, are controlled by, or are under common 116 | control with that entity. For the purposes of this definition, 117 | "control" means (i) the power, direct or indirect, to cause the 118 | direction or management of such entity, whether by contract or 119 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 120 | outstanding shares, or (iii) beneficial ownership of such entity. 121 | 122 | "You" (or "Your") shall mean an individual or Legal Entity 123 | exercising permissions granted by this License. 124 | 125 | "Source" form shall mean the preferred form for making modifications, 126 | including but not limited to software source code, documentation 127 | source, and configuration files. 128 | 129 | "Object" form shall mean any form resulting from mechanical 130 | transformation or translation of a Source form, including but 131 | not limited to compiled object code, generated documentation, 132 | and conversions to other media types. 133 | 134 | "Work" shall mean the work of authorship, whether in Source or 135 | Object form, made available under the License, as indicated by a 136 | copyright notice that is included in or attached to the work 137 | (an example is provided in the Appendix below). 138 | 139 | "Derivative Works" shall mean any work, whether in Source or Object 140 | form, that is based on (or derived from) the Work and for which the 141 | editorial revisions, annotations, elaborations, or other modifications 142 | represent, as a whole, an original work of authorship. For the purposes 143 | of this License, Derivative Works shall not include works that remain 144 | separable from, or merely link (or bind by name) to the interfaces of, 145 | the Work and Derivative Works thereof. 146 | 147 | "Contribution" shall mean any work of authorship, including 148 | the original version of the Work and any modifications or additions 149 | to that Work or Derivative Works thereof, that is intentionally 150 | submitted to Licensor for inclusion in the Work by the copyright owner 151 | or by an individual or Legal Entity authorized to submit on behalf of 152 | the copyright owner. For the purposes of this definition, "submitted" 153 | means any form of electronic, verbal, or written communication sent 154 | to the Licensor or its representatives, including but not limited to 155 | communication on electronic mailing lists, source code control systems, 156 | and issue tracking systems that are managed by, or on behalf of, the 157 | Licensor for the purpose of discussing and improving the Work, but 158 | excluding communication that is conspicuously marked or otherwise 159 | designated in writing by the copyright owner as "Not a Contribution." 160 | 161 | "Contributor" shall mean Licensor and any individual or Legal Entity 162 | on behalf of whom a Contribution has been received by Licensor and 163 | subsequently incorporated within the Work. 164 | 165 | 2. Grant of Copyright License. Subject to the terms and conditions of 166 | this License, each Contributor hereby grants to You a perpetual, 167 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 168 | copyright license to reproduce, prepare Derivative Works of, 169 | publicly display, publicly perform, sublicense, and distribute the 170 | Work and such Derivative Works in Source or Object form. 171 | 172 | 3. Grant of Patent License. Subject to the terms and conditions of 173 | this License, each Contributor hereby grants to You a perpetual, 174 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 175 | (except as stated in this section) patent license to make, have made, 176 | use, offer to sell, sell, import, and otherwise transfer the Work, 177 | where such license applies only to those patent claims licensable 178 | by such Contributor that are necessarily infringed by their 179 | Contribution(s) alone or by combination of their Contribution(s) 180 | with the Work to which such Contribution(s) was submitted. If You 181 | institute patent litigation against any entity (including a 182 | cross-claim or counterclaim in a lawsuit) alleging that the Work 183 | or a Contribution incorporated within the Work constitutes direct 184 | or contributory patent infringement, then any patent licenses 185 | granted to You under this License for that Work shall terminate 186 | as of the date such litigation is filed. 187 | 188 | 4. Redistribution. You may reproduce and distribute copies of the 189 | Work or Derivative Works thereof in any medium, with or without 190 | modifications, and in Source or Object form, provided that You 191 | meet the following conditions: 192 | 193 | (a) You must give any other recipients of the Work or 194 | Derivative Works a copy of this License; and 195 | 196 | (b) You must cause any modified files to carry prominent notices 197 | stating that You changed the files; and 198 | 199 | (c) You must retain, in the Source form of any Derivative Works 200 | that You distribute, all copyright, patent, trademark, and 201 | attribution notices from the Source form of the Work, 202 | excluding those notices that do not pertain to any part of 203 | the Derivative Works; and 204 | 205 | (d) If the Work includes a "NOTICE" text file as part of its 206 | distribution, then any Derivative Works that You distribute must 207 | include a readable copy of the attribution notices contained 208 | within such NOTICE file, excluding those notices that do not 209 | pertain to any part of the Derivative Works, in at least one 210 | of the following places: within a NOTICE text file distributed 211 | as part of the Derivative Works; within the Source form or 212 | documentation, if provided along with the Derivative Works; or, 213 | within a display generated by the Derivative Works, if and 214 | wherever such third-party notices normally appear. The contents 215 | of the NOTICE file are for informational purposes only and 216 | do not modify the License. You may add Your own attribution 217 | notices within Derivative Works that You distribute, alongside 218 | or as an addendum to the NOTICE text from the Work, provided 219 | that such additional attribution notices cannot be construed 220 | as modifying the License. 221 | 222 | You may add Your own copyright statement to Your modifications and 223 | may provide additional or different license terms and conditions 224 | for use, reproduction, or distribution of Your modifications, or 225 | for any such Derivative Works as a whole, provided Your use, 226 | reproduction, and distribution of the Work otherwise complies with 227 | the conditions stated in this License. 228 | 229 | 5. Submission of Contributions. Unless You explicitly state otherwise, 230 | any Contribution intentionally submitted for inclusion in the Work 231 | by You to the Licensor shall be under the terms and conditions of 232 | this License, without any additional terms or conditions. 233 | Notwithstanding the above, nothing herein shall supersede or modify 234 | the terms of any separate license agreement you may have executed 235 | with Licensor regarding such Contributions. 236 | 237 | 6. Trademarks. This License does not grant permission to use the trade 238 | names, trademarks, service marks, or product names of the Licensor, 239 | except as required for reasonable and customary use in describing the 240 | origin of the Work and reproducing the content of the NOTICE file. 241 | 242 | 7. Disclaimer of Warranty. Unless required by applicable law or 243 | agreed to in writing, Licensor provides the Work (and each 244 | Contributor provides its Contributions) on an "AS IS" BASIS, 245 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 246 | implied, including, without limitation, any warranties or conditions 247 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 248 | PARTICULAR PURPOSE. You are solely responsible for determining the 249 | appropriateness of using or redistributing the Work and assume any 250 | risks associated with Your exercise of permissions under this License. 251 | 252 | 8. Limitation of Liability. In no event and under no legal theory, 253 | whether in tort (including negligence), contract, or otherwise, 254 | unless required by applicable law (such as deliberate and grossly 255 | negligent acts) or agreed to in writing, shall any Contributor be 256 | liable to You for damages, including any direct, indirect, special, 257 | incidental, or consequential damages of any character arising as a 258 | result of this License or out of the use or inability to use the 259 | Work (including but not limited to damages for loss of goodwill, 260 | work stoppage, computer failure or malfunction, or any and all 261 | other commercial damages or losses), even if such Contributor 262 | has been advised of the possibility of such damages. 263 | 264 | 9. Accepting Warranty or Additional Liability. While redistributing 265 | the Work or Derivative Works thereof, You may choose to offer, 266 | and charge a fee for, acceptance of support, warranty, indemnity, 267 | or other liability obligations and/or rights consistent with this 268 | License. However, in accepting such obligations, You may act only 269 | on Your own behalf and on Your sole responsibility, not on behalf 270 | of any other Contributor, and only if You agree to indemnify, 271 | defend, and hold each Contributor harmless for any liability 272 | incurred by, or claims asserted against, such Contributor by reason 273 | of your accepting any such warranty or additional liability. 274 | 275 | END OF TERMS AND CONDITIONS 276 | 277 | APPENDIX: How to apply the Apache License to your work. 278 | 279 | To apply the Apache License to your work, attach the following 280 | boilerplate notice, with the fields enclosed by brackets "[]" 281 | replaced with your own identifying information. (Don't include 282 | the brackets!) The text should be enclosed in the appropriate 283 | comment syntax for the file format. We also recommend that a 284 | file or class name and description of purpose be included on the 285 | same "printed page" as the copyright notice for easier 286 | identification within third-party archives. 287 | 288 | Copyright [yyyy] [name of copyright owner] 289 | 290 | Licensed under the Apache License, Version 2.0 (the "License"); 291 | you may not use this file except in compliance with the License. 292 | You may obtain a copy of the License at 293 | 294 | http://www.apache.org/licenses/LICENSE-2.0 295 | 296 | Unless required by applicable law or agreed to in writing, software 297 | distributed under the License is distributed on an "AS IS" BASIS, 298 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 299 | See the License for the specific language governing permissions and 300 | limitations under the License. 301 | 302 | ------------------ 303 | 304 | Some files carry the following license, noted at the top of each file: 305 | 306 | Permission is hereby granted, free of charge, to any person obtaining a copy 307 | of this software and associated documentation files (the "Software"), to deal 308 | in the Software without restriction, including without limitation the rights 309 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 310 | copies of the Software, and to permit persons to whom the Software is 311 | furnished to do so, subject to the following conditions: 312 | 313 | The above copyright notice and this permission notice shall be included in 314 | all copies or substantial portions of the Software. 315 | 316 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 317 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 318 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 319 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 320 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 321 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 322 | THE SOFTWARE. 323 | 324 | ### socks5 325 | 326 | https://github.com/txthinking/socks5 327 | 328 | MIT License 329 | 330 | Copyright (c) 2015-present Cloud https://www.txthinking.com 331 | 332 | Permission is hereby granted, free of charge, to any person obtaining a copy 333 | of this software and associated documentation files (the "Software"), to deal 334 | in the Software without restriction, including without limitation the rights 335 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 336 | copies of the Software, and to permit persons to whom the Software is 337 | furnished to do so, subject to the following conditions: 338 | 339 | The above copyright notice and this permission notice shall be included in all 340 | copies or substantial portions of the Software. 341 | 342 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 343 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 344 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 345 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 346 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 347 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 348 | SOFTWARE. 349 | 350 | ### x 351 | 352 | https://github.com/txthinking/x 353 | 354 | The MIT License (MIT) 355 | 356 | Copyright (c) 2013-present Cloud https://www.txthinking.com 357 | 358 | Permission is hereby granted, free of charge, to any person obtaining a copy of 359 | this software and associated documentation files (the "Software"), to deal in 360 | the Software without restriction, including without limitation the rights to 361 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 362 | the Software, and to permit persons to whom the Software is furnished to do so, 363 | subject to the following conditions: 364 | 365 | The above copyright notice and this permission notice shall be included in all 366 | copies or substantial portions of the Software. 367 | 368 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 369 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 370 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 371 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 372 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 373 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 374 | 375 | ### water 376 | 377 | https://github.com/songgao/water 378 | 379 | Copyright (c) 2016, Song Gao 380 | All rights reserved. 381 | 382 | Redistribution and use in source and binary forms, with or without 383 | modification, are permitted provided that the following conditions are met: 384 | 385 | * Redistributions of source code must retain the above copyright notice, this 386 | list of conditions and the following disclaimer. 387 | 388 | * Redistributions in binary form must reproduce the above copyright notice, 389 | this list of conditions and the following disclaimer in the documentation 390 | and/or other materials provided with the distribution. 391 | 392 | * Neither the name of water nor the names of its contributors may be used to 393 | endorse or promote products derived from this software without specific prior 394 | written permission. 395 | 396 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 397 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 398 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 399 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 400 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 401 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 402 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 403 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 404 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 405 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 406 | 407 | ### wintun.dll 408 | 409 | Prebuilt Binaries License 410 | ------------------------- 411 | 412 | 1. DEFINITIONS. "Software" means the precise contents of the "wintun.dll" 413 | files that are included in the .zip file that contains this document as 414 | downloaded from wintun.net/builds. 415 | 416 | 2. LICENSE GRANT. WireGuard LLC grants to you a non-exclusive and 417 | non-transferable right to use Software for lawful purposes under certain 418 | obligations and limited rights as set forth in this agreement. 419 | 420 | 3. RESTRICTIONS. Software is owned and copyrighted by WireGuard LLC. It is 421 | licensed, not sold. Title to Software and all associated intellectual 422 | property rights are retained by WireGuard. You must not: 423 | a. reverse engineer, decompile, disassemble, extract from, or otherwise 424 | modify the Software; 425 | b. modify or create derivative work based upon Software in whole or in 426 | parts, except insofar as only the API interfaces of the "wintun.h" file 427 | distributed alongside the Software (the "Permitted API") are used; 428 | c. remove any proprietary notices, labels, or copyrights from the Software; 429 | d. resell, redistribute, lease, rent, transfer, sublicense, or otherwise 430 | transfer rights of the Software without the prior written consent of 431 | WireGuard LLC, except insofar as the Software is distributed alongside 432 | other software that uses the Software only via the Permitted API; 433 | e. use the name of WireGuard LLC, the WireGuard project, the Wintun 434 | project, or the names of its contributors to endorse or promote products 435 | derived from the Software without specific prior written consent. 436 | 437 | 4. LIMITED WARRANTY. THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTY OF 438 | ANY KIND. WIREGUARD LLC HEREBY EXCLUDES AND DISCLAIMS ALL IMPLIED OR 439 | STATUTORY WARRANTIES, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, FITNESS 440 | FOR A PARTICULAR PURPOSE, QUALITY, NON-INFRINGEMENT, TITLE, RESULTS, 441 | EFFORTS, OR QUIET ENJOYMENT. THERE IS NO WARRANTY THAT THE PRODUCT WILL BE 442 | ERROR-FREE OR WILL FUNCTION WITHOUT INTERRUPTION. YOU ASSUME THE ENTIRE 443 | RISK FOR THE RESULTS OBTAINED USING THE PRODUCT. TO THE EXTENT THAT 444 | WIREGUARD LLC MAY NOT DISCLAIM ANY WARRANTY AS A MATTER OF APPLICABLE LAW, 445 | THE SCOPE AND DURATION OF SUCH WARRANTY WILL BE THE MINIMUM PERMITTED UNDER 446 | SUCH LAW. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND 447 | WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR 448 | A PARTICULAR PURPOSE OR NON-INFRINGEMENT ARE DISCLAIMED, EXCEPT TO THE 449 | EXTENT THAT THESE DISCLAIMERS ARE HELD TO BE LEGALLY INVALID. 450 | 451 | 5. LIMITATION OF LIABILITY. To the extent not prohibited by law, in no event 452 | WireGuard LLC or any third-party-developer will be liable for any lost 453 | revenue, profit or data or for special, indirect, consequential, incidental 454 | or punitive damages, however caused regardless of the theory of liability, 455 | arising out of or related to the use of or inability to use Software, even 456 | if WireGuard LLC has been advised of the possibility of such damages. 457 | Solely you are responsible for determining the appropriateness of using 458 | Software and accept full responsibility for all risks associated with its 459 | exercise of rights under this agreement, including but not limited to the 460 | risks and costs of program errors, compliance with applicable laws, damage 461 | to or loss of data, programs or equipment, and unavailability or 462 | interruption of operations. The foregoing limitations will apply even if 463 | the above stated warranty fails of its essential purpose. You acknowledge, 464 | that it is in the nature of software that software is complex and not 465 | completely free of errors. In no event shall WireGuard LLC or any 466 | third-party-developer be liable to you under any theory for any damages 467 | suffered by you or any user of Software or for any special, incidental, 468 | indirect, consequential or similar damages (including without limitation 469 | damages for loss of business profits, business interruption, loss of 470 | business information or any other pecuniary loss) arising out of the use or 471 | inability to use Software, even if WireGuard LLC has been advised of the 472 | possibility of such damages and regardless of the legal or quitable theory 473 | (contract, tort, or otherwise) upon which the claim is based. 474 | 475 | 6. TERMINATION. This agreement is affected until terminated. You may 476 | terminate this agreement at any time. This agreement will terminate 477 | immediately without notice from WireGuard LLC if you fail to comply with 478 | the terms and conditions of this agreement. Upon termination, you must 479 | delete Software and all copies of Software and cease all forms of 480 | distribution of Software. 481 | 482 | 7. SEVERABILITY. If any provision of this agreement is held to be 483 | unenforceable, this agreement will remain in effect with the provision 484 | omitted, unless omission would frustrate the intent of the parties, in 485 | which case this agreement will immediately terminate. 486 | 487 | 8. RESERVATION OF RIGHTS. All rights not expressly granted in this agreement 488 | are reserved by WireGuard LLC. For example, WireGuard LLC reserves the 489 | right at any time to cease development of Software, to alter distribution 490 | details, features, specifications, capabilities, functions, licensing 491 | terms, release dates, APIs, ABIs, general availability, or other 492 | characteristics of the Software. 493 | 494 | ### wireguard-go 495 | 496 | https://github.com/WireGuard/wireguard-go 497 | 498 | MIT License 499 | 500 | Permission is hereby granted, free of charge, to any person obtaining a copy of 501 | this software and associated documentation files (the "Software"), to deal in 502 | the Software without restriction, including without limitation the rights to 503 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 504 | of the Software, and to permit persons to whom the Software is furnished to do 505 | so, subject to the following conditions: 506 | 507 | The above copyright notice and this permission notice shall be included in all 508 | copies or substantial portions of the Software. 509 | 510 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 511 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 512 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 513 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 514 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 515 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 516 | SOFTWARE. 517 | -------------------------------------------------------------------------------- /tcpassembly/assembly.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 Google, Inc. All rights reserved. 2 | // 3 | // Use of this source code is governed by a BSD-style license 4 | // that can be found in the LICENSE file in the root of the source 5 | // tree. 6 | 7 | // Package tcpassembly provides TCP stream re-assembly. 8 | // 9 | // The tcpassembly package implements uni-directional TCP reassembly, for use in 10 | // packet-sniffing applications. The caller reads packets off the wire, then 11 | // presents them to an Assembler in the form of gopacket layers.TCP packets 12 | // (github.com/google/gopacket, github.com/google/gopacket/layers). 13 | // 14 | // The Assembler uses a user-supplied 15 | // StreamFactory to create a user-defined Stream interface, then passes packet 16 | // data in stream order to that object. A concurrency-safe StreamPool keeps 17 | // track of all current Streams being reassembled, so multiple Assemblers may 18 | // run at once to assemble packets while taking advantage of multiple cores. 19 | package tcpassembly 20 | 21 | import ( 22 | "flag" 23 | "fmt" 24 | "github.com/google/gopacket" 25 | "github.com/txthinking/ipio/layers" 26 | "log" 27 | "sync" 28 | "time" 29 | ) 30 | 31 | var memLog = flag.Bool("assembly_memuse_log", false, "If true, the github.com/google/gopacket/tcpassembly library will log information regarding its memory use every once in a while.") 32 | var debugLog = flag.Bool("assembly_debug_log", false, "If true, the github.com/google/gopacket/tcpassembly library will log verbose debugging information (at least one line per packet)") 33 | 34 | const invalidSequence = -1 35 | const uint32Size = 1 << 32 36 | 37 | // Sequence is a TCP sequence number. It provides a few convenience functions 38 | // for handling TCP wrap-around. The sequence should always be in the range 39 | // [0,0xFFFFFFFF]... its other bits are simply used in wrap-around calculations 40 | // and should never be set. 41 | type Sequence int64 42 | 43 | // Difference defines an ordering for comparing TCP sequences that's safe for 44 | // roll-overs. It returns: 45 | // > 0 : if t comes after s 46 | // < 0 : if t comes before s 47 | // 0 : if t == s 48 | // The number returned is the sequence difference, so 4.Difference(8) will 49 | // return 4. 50 | // 51 | // It handles rollovers by considering any sequence in the first quarter of the 52 | // uint32 space to be after any sequence in the last quarter of that space, thus 53 | // wrapping the uint32 space. 54 | func (s Sequence) Difference(t Sequence) int { 55 | if s > uint32Size-uint32Size/4 && t < uint32Size/4 { 56 | t += uint32Size 57 | } else if t > uint32Size-uint32Size/4 && s < uint32Size/4 { 58 | s += uint32Size 59 | } 60 | return int(t - s) 61 | } 62 | 63 | // Add adds an integer to a sequence and returns the resulting sequence. 64 | func (s Sequence) Add(t int) Sequence { 65 | return (s + Sequence(t)) & (uint32Size - 1) 66 | } 67 | 68 | // Reassembly objects are passed by an Assembler into Streams using the 69 | // Reassembled call. Callers should not need to create these structs themselves 70 | // except for testing. 71 | type Reassembly struct { 72 | // Bytes is the next set of bytes in the stream. May be empty. 73 | Bytes []byte 74 | // Skip is set to non-zero if bytes were skipped between this and the 75 | // last Reassembly. If this is the first packet in a connection and we 76 | // didn't see the start, we have no idea how many bytes we skipped, so 77 | // we set it to -1. Otherwise, it's set to the number of bytes skipped. 78 | Skip int 79 | // Start is set if this set of bytes has a TCP SYN accompanying it. 80 | Start bool 81 | // End is set if this set of bytes has a TCP FIN or RST accompanying it. 82 | End bool 83 | // Seen is the timestamp this set of bytes was pulled off the wire. 84 | Seen time.Time 85 | } 86 | 87 | const pageBytes = 1900 88 | 89 | // page is used to store TCP data we're not ready for yet (out-of-order 90 | // packets). Unused pages are stored in and returned from a pageCache, which 91 | // avoids memory allocation. Used pages are stored in a doubly-linked list in 92 | // a connection. 93 | type page struct { 94 | Reassembly 95 | seq Sequence 96 | index int 97 | prev, next *page 98 | buf [pageBytes]byte 99 | } 100 | 101 | // pageCache is a concurrency-unsafe store of page objects we use to avoid 102 | // memory allocation as much as we can. It grows but never shrinks. 103 | type pageCache struct { 104 | free []*page 105 | pcSize int 106 | size, used int 107 | pages [][]page 108 | pageRequests int64 109 | } 110 | 111 | const initialAllocSize = 1024 112 | 113 | func newPageCache() *pageCache { 114 | pc := &pageCache{ 115 | free: make([]*page, 0, initialAllocSize), 116 | pcSize: initialAllocSize, 117 | } 118 | pc.grow() 119 | return pc 120 | } 121 | 122 | // grow exponentially increases the size of our page cache as much as necessary. 123 | func (c *pageCache) grow() { 124 | pages := make([]page, c.pcSize) 125 | c.pages = append(c.pages, pages) 126 | c.size += c.pcSize 127 | for i := range pages { 128 | c.free = append(c.free, &pages[i]) 129 | } 130 | if *memLog { 131 | log.Println("PageCache: created", c.pcSize, "new pages") 132 | } 133 | c.pcSize *= 2 134 | } 135 | 136 | // next returns a clean, ready-to-use page object. 137 | func (c *pageCache) next(ts time.Time) (p *page) { 138 | if *memLog { 139 | c.pageRequests++ 140 | if c.pageRequests&0xFFFF == 0 { 141 | log.Println("PageCache:", c.pageRequests, "requested,", c.used, "used,", len(c.free), "free") 142 | } 143 | } 144 | if len(c.free) == 0 { 145 | c.grow() 146 | } 147 | i := len(c.free) - 1 148 | p, c.free = c.free[i], c.free[:i] 149 | p.prev = nil 150 | p.next = nil 151 | p.Reassembly = Reassembly{Bytes: p.buf[:0], Seen: ts} 152 | c.used++ 153 | return p 154 | } 155 | 156 | // replace replaces a page into the pageCache. 157 | func (c *pageCache) replace(p *page) { 158 | c.used-- 159 | c.free = append(c.free, p) 160 | } 161 | 162 | // Stream is implemented by the caller to handle incoming reassembled 163 | // TCP data. Callers create a StreamFactory, then StreamPool uses 164 | // it to create a new Stream for every TCP stream. 165 | // 166 | // assembly will, in order: 167 | // 1) Create the stream via StreamFactory.New 168 | // 2) Call Reassembled 0 or more times, passing in reassembled TCP data in order 169 | // 3) Call ReassemblyComplete one time, after which the stream is dereferenced by assembly. 170 | type Stream interface { 171 | // Reassembled is called zero or more times. assembly guarantees 172 | // that the set of all Reassembly objects passed in during all 173 | // calls are presented in the order they appear in the TCP stream. 174 | // Reassembly objects are reused after each Reassembled call, 175 | // so it's important to copy anything you need out of them 176 | // (specifically out of Reassembly.Bytes) that you need to stay 177 | // around after you return from the Reassembled call. 178 | Reassembled([]Reassembly) 179 | // ReassemblyComplete is called when assembly decides there is 180 | // no more data for this Stream, either because a FIN or RST packet 181 | // was seen, or because the stream has timed out without any new 182 | // packet data (due to a call to FlushOlderThan). 183 | ReassemblyComplete() 184 | } 185 | 186 | // StreamFactory is used by assembly to create a new stream for each 187 | // new TCP session. 188 | type StreamFactory interface { 189 | // New should return a new stream for the given TCP key. 190 | New(netFlow, tcpFlow gopacket.Flow) Stream 191 | } 192 | 193 | func (p *StreamPool) connections() []*connection { 194 | p.mu.RLock() 195 | conns := make([]*connection, 0, len(p.conns)) 196 | for _, conn := range p.conns { 197 | conns = append(conns, conn) 198 | } 199 | p.mu.RUnlock() 200 | return conns 201 | } 202 | 203 | // FlushOptions provide options for flushing connections. 204 | type FlushOptions struct { 205 | T time.Time // If nonzero, only connections with data older than T are flushed 206 | CloseAll bool // If true, ALL connections are closed post flush, not just those that correctly see FIN/RST. 207 | } 208 | 209 | // FlushWithOptions finds any streams waiting for packets older than 210 | // the given time, and pushes through the data they have (IE: tells 211 | // them to stop waiting and skip the data they're waiting for). 212 | // 213 | // Each Stream maintains a list of zero or more sets of bytes it has received 214 | // out-of-order. For example, if it has processed up through sequence number 215 | // 10, it might have bytes [15-20), [20-25), [30,50) in its list. Each set of 216 | // bytes also has the timestamp it was originally viewed. A flush call will 217 | // look at the smallest subsequent set of bytes, in this case [15-20), and if 218 | // its timestamp is older than the passed-in time, it will push it and all 219 | // contiguous byte-sets out to the Stream's Reassembled function. In this case, 220 | // it will push [15-20), but also [20-25), since that's contiguous. It will 221 | // only push [30-50) if its timestamp is also older than the passed-in time, 222 | // otherwise it will wait until the next FlushOlderThan to see if bytes [25-30) 223 | // come in. 224 | // 225 | // If it pushes all bytes (or there were no sets of bytes to begin with) 226 | // AND the connection has not received any bytes since the passed-in time, 227 | // the connection will be closed. 228 | // 229 | // If CloseAll is set, it will close out connections that have been drained. 230 | // Regardless of the CloseAll setting, connections stale for the specified 231 | // time will be closed. 232 | // 233 | // Returns the number of connections flushed, and of those, the number closed 234 | // because of the flush. 235 | func (a *Assembler) FlushWithOptions(opt FlushOptions) (flushed, closed int) { 236 | conns := a.connPool.connections() 237 | closes := 0 238 | flushes := 0 239 | for _, conn := range conns { 240 | flushed := false 241 | conn.mu.Lock() 242 | if conn.closed { 243 | // Already closed connection, nothing to do here. 244 | conn.mu.Unlock() 245 | continue 246 | } 247 | for conn.first != nil && conn.first.Seen.Before(opt.T) { 248 | a.skipFlush(conn) 249 | flushed = true 250 | if conn.closed { 251 | closes++ 252 | break 253 | } 254 | } 255 | if opt.CloseAll && !conn.closed && conn.first == nil && conn.lastSeen.Before(opt.T) { 256 | flushed = true 257 | a.closeConnection(conn) 258 | closes++ 259 | } 260 | if flushed { 261 | flushes++ 262 | } 263 | conn.mu.Unlock() 264 | } 265 | return flushes, closes 266 | } 267 | 268 | // FlushOlderThan calls FlushWithOptions with the CloseAll option set to true. 269 | func (a *Assembler) FlushOlderThan(t time.Time) (flushed, closed int) { 270 | return a.FlushWithOptions(FlushOptions{CloseAll: true, T: t}) 271 | } 272 | 273 | // FlushAll flushes all remaining data into all remaining connections, closing 274 | // those connections. It returns the total number of connections flushed/closed 275 | // by the call. 276 | func (a *Assembler) FlushAll() (closed int) { 277 | conns := a.connPool.connections() 278 | closed = len(conns) 279 | for _, conn := range conns { 280 | conn.mu.Lock() 281 | for !conn.closed { 282 | a.skipFlush(conn) 283 | } 284 | conn.mu.Unlock() 285 | } 286 | return 287 | } 288 | 289 | type key [2]gopacket.Flow 290 | 291 | func (k *key) String() string { 292 | return fmt.Sprintf("%s:%s", k[0], k[1]) 293 | } 294 | 295 | // StreamPool stores all streams created by Assemblers, allowing multiple 296 | // assemblers to work together on stream processing while enforcing the fact 297 | // that a single stream receives its data serially. It is safe 298 | // for concurrency, usable by multiple Assemblers at once. 299 | // 300 | // StreamPool handles the creation and storage of Stream objects used by one or 301 | // more Assembler objects. When a new TCP stream is found by an Assembler, it 302 | // creates an associated Stream by calling its StreamFactory's New method. 303 | // Thereafter (until the stream is closed), that Stream object will receive 304 | // assembled TCP data via Assembler's calls to the stream's Reassembled 305 | // function. 306 | // 307 | // Like the Assembler, StreamPool attempts to minimize allocation. Unlike the 308 | // Assembler, though, it does have to do some locking to make sure that the 309 | // connection objects it stores are accessible to multiple Assemblers. 310 | type StreamPool struct { 311 | conns map[key]*connection 312 | users int 313 | mu sync.RWMutex 314 | factory StreamFactory 315 | free []*connection 316 | all [][]connection 317 | nextAlloc int 318 | newConnectionCount int64 319 | } 320 | 321 | func (p *StreamPool) grow() { 322 | conns := make([]connection, p.nextAlloc) 323 | p.all = append(p.all, conns) 324 | for i := range conns { 325 | p.free = append(p.free, &conns[i]) 326 | } 327 | if *memLog { 328 | log.Println("StreamPool: created", p.nextAlloc, "new connections") 329 | } 330 | p.nextAlloc *= 2 331 | } 332 | 333 | // NewStreamPool creates a new connection pool. Streams will 334 | // be created as necessary using the passed-in StreamFactory. 335 | func NewStreamPool(factory StreamFactory) *StreamPool { 336 | return &StreamPool{ 337 | conns: make(map[key]*connection, initialAllocSize), 338 | free: make([]*connection, 0, initialAllocSize), 339 | factory: factory, 340 | nextAlloc: initialAllocSize, 341 | } 342 | } 343 | 344 | const assemblerReturnValueInitialSize = 16 345 | 346 | // NewAssembler creates a new assembler. Pass in the StreamPool 347 | // to use, may be shared across assemblers. 348 | // 349 | // This sets some sane defaults for the assembler options, 350 | // see DefaultAssemblerOptions for details. 351 | func NewAssembler(pool *StreamPool) *Assembler { 352 | pool.mu.Lock() 353 | pool.users++ 354 | pool.mu.Unlock() 355 | return &Assembler{ 356 | ret: make([]Reassembly, assemblerReturnValueInitialSize), 357 | pc: newPageCache(), 358 | connPool: pool, 359 | AssemblerOptions: DefaultAssemblerOptions, 360 | } 361 | } 362 | 363 | // DefaultAssemblerOptions provides default options for an assembler. 364 | // These options are used by default when calling NewAssembler, so if 365 | // modified before a NewAssembler call they'll affect the resulting Assembler. 366 | // 367 | // Note that the default options can result in ever-increasing memory usage 368 | // unless one of the Flush* methods is called on a regular basis. 369 | var DefaultAssemblerOptions = AssemblerOptions{ 370 | MaxBufferedPagesPerConnection: 0, // unlimited 371 | MaxBufferedPagesTotal: 0, // unlimited 372 | } 373 | 374 | type connection struct { 375 | key key 376 | pages int 377 | first, last *page 378 | nextSeq Sequence 379 | created, lastSeen time.Time 380 | stream Stream 381 | closed bool 382 | mu sync.Mutex 383 | } 384 | 385 | func (c *connection) reset(k key, s Stream, ts time.Time) { 386 | c.key = k 387 | c.pages = 0 388 | c.first, c.last = nil, nil 389 | c.nextSeq = invalidSequence 390 | c.created = ts 391 | c.stream = s 392 | c.closed = false 393 | } 394 | 395 | // AssemblerOptions controls the behavior of each assembler. Modify the 396 | // options of each assembler you create to change their behavior. 397 | type AssemblerOptions struct { 398 | // MaxBufferedPagesTotal is an upper limit on the total number of pages to 399 | // buffer while waiting for out-of-order packets. Once this limit is 400 | // reached, the assembler will degrade to flushing every connection it 401 | // gets a packet for. If <= 0, this is ignored. 402 | MaxBufferedPagesTotal int 403 | // MaxBufferedPagesPerConnection is an upper limit on the number of pages 404 | // buffered for a single connection. Should this limit be reached for a 405 | // particular connection, the smallest sequence number will be flushed, along 406 | // with any contiguous data. If <= 0, this is ignored. 407 | MaxBufferedPagesPerConnection int 408 | } 409 | 410 | // Assembler handles reassembling TCP streams. It is not safe for 411 | // concurrency... after passing a packet in via the Assemble call, the caller 412 | // must wait for that call to return before calling Assemble again. Callers can 413 | // get around this by creating multiple assemblers that share a StreamPool. In 414 | // that case, each individual stream will still be handled serially (each stream 415 | // has an individual mutex associated with it), however multiple assemblers can 416 | // assemble different connections concurrently. 417 | // 418 | // The Assembler provides (hopefully) fast TCP stream re-assembly for sniffing 419 | // applications written in Go. The Assembler uses the following methods to be 420 | // as fast as possible, to keep packet processing speedy: 421 | // 422 | // Avoids Lock Contention 423 | // 424 | // Assemblers locks connections, but each connection has an individual lock, and 425 | // rarely will two Assemblers be looking at the same connection. Assemblers 426 | // lock the StreamPool when looking up connections, but they use Reader 427 | // locks initially, and only force a write lock if they need to create a new 428 | // connection or close one down. These happen much less frequently than 429 | // individual packet handling. 430 | // 431 | // Each assembler runs in its own goroutine, and the only state shared between 432 | // goroutines is through the StreamPool. Thus all internal Assembler state 433 | // can be handled without any locking. 434 | // 435 | // NOTE: If you can guarantee that packets going to a set of Assemblers will 436 | // contain information on different connections per Assembler (for example, 437 | // they're already hashed by PF_RING hashing or some other hashing mechanism), 438 | // then we recommend you use a seperate StreamPool per Assembler, thus 439 | // avoiding all lock contention. Only when different Assemblers could receive 440 | // packets for the same Stream should a StreamPool be shared between them. 441 | // 442 | // Avoids Memory Copying 443 | // 444 | // In the common case, handling of a single TCP packet should result in zero 445 | // memory allocations. The Assembler will look up the connection, figure out 446 | // that the packet has arrived in order, and immediately pass that packet on to 447 | // the appropriate connection's handling code. Only if a packet arrives out of 448 | // order is its contents copied and stored in memory for later. 449 | // 450 | // Avoids Memory Allocation 451 | // 452 | // Assemblers try very hard to not use memory allocation unless absolutely 453 | // necessary. Packet data for sequential packets is passed directly to streams 454 | // with no copying or allocation. Packet data for out-of-order packets is 455 | // copied into reusable pages, and new pages are only allocated rarely when the 456 | // page cache runs out. Page caches are Assembler-specific, thus not used 457 | // concurrently and requiring no locking. 458 | // 459 | // Internal representations for connection objects are also reused over time. 460 | // Because of this, the most common memory allocation done by the Assembler is 461 | // generally what's done by the caller in StreamFactory.New. If no allocation 462 | // is done there, then very little allocation is done ever, mostly to handle 463 | // large increases in bandwidth or numbers of connections. 464 | // 465 | // TODO: The page caches used by an Assembler will grow to the size necessary 466 | // to handle a workload, and currently will never shrink. This means that 467 | // traffic spikes can result in large memory usage which isn't garbage 468 | // collected when typical traffic levels return. 469 | type Assembler struct { 470 | AssemblerOptions 471 | ret []Reassembly 472 | pc *pageCache 473 | connPool *StreamPool 474 | } 475 | 476 | func (p *StreamPool) newConnection(k key, s Stream, ts time.Time) (c *connection) { 477 | if *memLog { 478 | p.newConnectionCount++ 479 | if p.newConnectionCount&0x7FFF == 0 { 480 | log.Println("StreamPool:", p.newConnectionCount, "requests,", len(p.conns), "used,", len(p.free), "free") 481 | } 482 | } 483 | if len(p.free) == 0 { 484 | p.grow() 485 | } 486 | index := len(p.free) - 1 487 | c, p.free = p.free[index], p.free[:index] 488 | c.reset(k, s, ts) 489 | return c 490 | } 491 | 492 | // getConnection returns a connection. If end is true and a connection 493 | // does not already exist, returns nil. This allows us to check for a 494 | // connection without actually creating one if it doesn't already exist. 495 | func (p *StreamPool) getConnection(k key, end bool, ts time.Time) *connection { 496 | p.mu.RLock() 497 | conn := p.conns[k] 498 | p.mu.RUnlock() 499 | if end || conn != nil { 500 | return conn 501 | } 502 | s := p.factory.New(k[0], k[1]) 503 | p.mu.Lock() 504 | conn = p.newConnection(k, s, ts) 505 | if conn2 := p.conns[k]; conn2 != nil { 506 | p.mu.Unlock() 507 | return conn2 508 | } 509 | p.conns[k] = conn 510 | p.mu.Unlock() 511 | return conn 512 | } 513 | 514 | // Assemble calls AssembleWithTimestamp with the current timestamp, useful for 515 | // packets being read directly off the wire. 516 | func (a *Assembler) Assemble(netFlow gopacket.Flow, t *layers.TCP) { 517 | a.AssembleWithTimestamp(netFlow, t, time.Now()) 518 | } 519 | 520 | // AssembleWithTimestamp reassembles the given TCP packet into its appropriate 521 | // stream. 522 | // 523 | // The timestamp passed in must be the timestamp the packet was seen. 524 | // For packets read off the wire, time.Now() should be fine. For packets read 525 | // from PCAP files, CaptureInfo.Timestamp should be passed in. This timestamp 526 | // will affect which streams are flushed by a call to FlushOlderThan. 527 | // 528 | // Each Assemble call results in, in order: 529 | // 530 | // zero or one calls to StreamFactory.New, creating a stream 531 | // zero or one calls to Reassembled on a single stream 532 | // zero or one calls to ReassemblyComplete on the same stream 533 | func (a *Assembler) AssembleWithTimestamp(netFlow gopacket.Flow, t *layers.TCP, timestamp time.Time) { 534 | // Ignore empty TCP packets 535 | if !t.SYN && !t.FIN && !t.RST && len(t.LayerPayload()) == 0 { 536 | if *debugLog { 537 | log.Println("ignoring useless packet") 538 | } 539 | return 540 | } 541 | 542 | a.ret = a.ret[:0] 543 | key := key{netFlow, t.TransportFlow()} 544 | var conn *connection 545 | // This for loop handles a race condition where a connection will close, lock 546 | // the connection pool, and remove itself, but before it locked the connection 547 | // pool it's returned to another Assemble statement. This should loop 0-1 548 | // times for the VAST majority of cases. 549 | for { 550 | conn = a.connPool.getConnection( 551 | key, !t.SYN && len(t.LayerPayload()) == 0, timestamp) 552 | if conn == nil { 553 | if *debugLog { 554 | log.Printf("%v got empty packet on otherwise empty connection", key) 555 | } 556 | return 557 | } 558 | conn.mu.Lock() 559 | if !conn.closed { 560 | break 561 | } 562 | conn.mu.Unlock() 563 | } 564 | if conn.lastSeen.Before(timestamp) { 565 | conn.lastSeen = timestamp 566 | } 567 | seq, bytes := Sequence(t.Seq), t.Payload 568 | if conn.nextSeq == invalidSequence { 569 | if t.SYN { 570 | if *debugLog { 571 | log.Printf("%v saw first SYN packet, returning immediately, seq=%v", key, seq) 572 | } 573 | a.ret = append(a.ret, Reassembly{ 574 | Bytes: bytes, 575 | Skip: 0, 576 | Start: true, 577 | Seen: timestamp, 578 | }) 579 | conn.nextSeq = seq.Add(len(bytes) + 1) 580 | } else { 581 | if *debugLog { 582 | log.Printf("%v waiting for start, storing into connection", key) 583 | } 584 | a.insertIntoConn(t, conn, timestamp) 585 | } 586 | } else if diff := conn.nextSeq.Difference(seq); diff > 0 { 587 | if *debugLog { 588 | log.Printf("%v gap in sequence numbers (%v, %v) diff %v, storing into connection", key, conn.nextSeq, seq, diff) 589 | } 590 | a.insertIntoConn(t, conn, timestamp) 591 | } else { 592 | bytes, conn.nextSeq = byteSpan(conn.nextSeq, seq, bytes) 593 | if *debugLog { 594 | log.Printf("%v found contiguous data (%v, %v), returning immediately", key, seq, conn.nextSeq) 595 | } 596 | a.ret = append(a.ret, Reassembly{ 597 | Bytes: bytes, 598 | Skip: 0, 599 | End: t.RST || t.FIN, 600 | Seen: timestamp, 601 | }) 602 | } 603 | if len(a.ret) > 0 { 604 | a.sendToConnection(conn) 605 | } 606 | conn.mu.Unlock() 607 | } 608 | 609 | func byteSpan(expected, received Sequence, bytes []byte) (toSend []byte, next Sequence) { 610 | if expected == invalidSequence { 611 | return bytes, received.Add(len(bytes)) 612 | } 613 | span := int(received.Difference(expected)) 614 | if span <= 0 { 615 | return bytes, received.Add(len(bytes)) 616 | } else if len(bytes) < span { 617 | return nil, expected 618 | } 619 | return bytes[span:], expected.Add(len(bytes) - span) 620 | } 621 | 622 | // sendToConnection sends the current values in a.ret to the connection, closing 623 | // the connection if the last thing sent had End set. 624 | func (a *Assembler) sendToConnection(conn *connection) { 625 | a.addContiguous(conn) 626 | if conn.stream == nil { 627 | panic("why?") 628 | } 629 | conn.stream.Reassembled(a.ret) 630 | if a.ret[len(a.ret)-1].End { 631 | a.closeConnection(conn) 632 | } 633 | } 634 | 635 | // addContiguous adds contiguous byte-sets to a connection. 636 | func (a *Assembler) addContiguous(conn *connection) { 637 | for conn.first != nil && conn.nextSeq.Difference(conn.first.seq) <= 0 { 638 | a.addNextFromConn(conn) 639 | } 640 | } 641 | 642 | // skipFlush skips the first set of bytes we're waiting for and returns the 643 | // first set of bytes we have. If we have no bytes pending, it closes the 644 | // connection. 645 | func (a *Assembler) skipFlush(conn *connection) { 646 | if *debugLog { 647 | log.Printf("%v skipFlush %v", conn.key, conn.nextSeq) 648 | } 649 | if conn.first == nil { 650 | a.closeConnection(conn) 651 | return 652 | } 653 | a.ret = a.ret[:0] 654 | a.addNextFromConn(conn) 655 | a.addContiguous(conn) 656 | a.sendToConnection(conn) 657 | } 658 | 659 | func (p *StreamPool) remove(conn *connection) { 660 | p.mu.Lock() 661 | delete(p.conns, conn.key) 662 | p.free = append(p.free, conn) 663 | p.mu.Unlock() 664 | } 665 | 666 | func (a *Assembler) closeConnection(conn *connection) { 667 | if *debugLog { 668 | log.Printf("%v closing", conn.key) 669 | } 670 | conn.stream.ReassemblyComplete() 671 | conn.closed = true 672 | a.connPool.remove(conn) 673 | for p := conn.first; p != nil; p = p.next { 674 | a.pc.replace(p) 675 | } 676 | } 677 | 678 | // traverseConn traverses our doubly-linked list of pages for the correct 679 | // position to put the given sequence number. Note that it traverses backwards, 680 | // starting at the highest sequence number and going down, since we assume the 681 | // common case is that TCP packets for a stream will appear in-order, with 682 | // minimal loss or packet reordering. 683 | func (c *connection) traverseConn(seq Sequence) (prev, current *page) { 684 | prev = c.last 685 | for prev != nil && prev.seq.Difference(seq) < 0 { 686 | current = prev 687 | prev = current.prev 688 | } 689 | return 690 | } 691 | 692 | // pushBetween inserts the doubly-linked list first-...-last in between the 693 | // nodes prev-next in another doubly-linked list. If prev is nil, makes first 694 | // the new first page in the connection's list. If next is nil, makes last the 695 | // new last page in the list. first/last may point to the same page. 696 | func (c *connection) pushBetween(prev, next, first, last *page) { 697 | // Maintain our doubly linked list 698 | if next == nil || c.last == nil { 699 | c.last = last 700 | } else { 701 | last.next = next 702 | next.prev = last 703 | } 704 | if prev == nil || c.first == nil { 705 | c.first = first 706 | } else { 707 | first.prev = prev 708 | prev.next = first 709 | } 710 | } 711 | 712 | func (a *Assembler) insertIntoConn(t *layers.TCP, conn *connection, ts time.Time) { 713 | if conn.first != nil && conn.first.seq == conn.nextSeq { 714 | panic("wtf") 715 | } 716 | p, p2, numPages := a.pagesFromTCP(t, ts) 717 | prev, current := conn.traverseConn(Sequence(t.Seq)) 718 | conn.pushBetween(prev, current, p, p2) 719 | conn.pages += numPages 720 | if (a.MaxBufferedPagesPerConnection > 0 && conn.pages >= a.MaxBufferedPagesPerConnection) || 721 | (a.MaxBufferedPagesTotal > 0 && a.pc.used >= a.MaxBufferedPagesTotal) { 722 | if *debugLog { 723 | log.Printf("%v hit max buffer size: %+v, %v, %v", conn.key, a.AssemblerOptions, conn.pages, a.pc.used) 724 | } 725 | a.addNextFromConn(conn) 726 | } 727 | } 728 | 729 | // pagesFromTCP creates a page (or set of pages) from a TCP packet. Note that 730 | // it should NEVER receive a SYN packet, as it doesn't handle sequences 731 | // correctly. 732 | // 733 | // It returns the first and last page in its doubly-linked list of new pages. 734 | func (a *Assembler) pagesFromTCP(t *layers.TCP, ts time.Time) (p, p2 *page, numPages int) { 735 | first := a.pc.next(ts) 736 | current := first 737 | numPages++ 738 | seq, bytes := Sequence(t.Seq), t.Payload 739 | for { 740 | length := min(len(bytes), pageBytes) 741 | current.Bytes = current.buf[:length] 742 | copy(current.Bytes, bytes) 743 | current.seq = seq 744 | bytes = bytes[length:] 745 | if len(bytes) == 0 { 746 | break 747 | } 748 | seq = seq.Add(length) 749 | current.next = a.pc.next(ts) 750 | current.next.prev = current 751 | current = current.next 752 | numPages++ 753 | } 754 | current.End = t.RST || t.FIN 755 | return first, current, numPages 756 | } 757 | 758 | // addNextFromConn pops the first page from a connection off and adds it to the 759 | // return array. 760 | func (a *Assembler) addNextFromConn(conn *connection) { 761 | if conn.nextSeq == invalidSequence { 762 | conn.first.Skip = -1 763 | } else if diff := conn.nextSeq.Difference(conn.first.seq); diff > 0 { 764 | conn.first.Skip = int(diff) 765 | } 766 | conn.first.Bytes, conn.nextSeq = byteSpan(conn.nextSeq, conn.first.seq, conn.first.Bytes) 767 | if *debugLog { 768 | log.Printf("%v adding from conn (%v, %v)", conn.key, conn.first.seq, conn.nextSeq) 769 | } 770 | a.ret = append(a.ret, conn.first.Reassembly) 771 | a.pc.replace(conn.first) 772 | if conn.first == conn.last { 773 | conn.first = nil 774 | conn.last = nil 775 | } else { 776 | conn.first = conn.first.next 777 | conn.first.prev = nil 778 | } 779 | conn.pages-- 780 | } 781 | 782 | func min(a, b int) int { 783 | if a < b { 784 | return a 785 | } 786 | return b 787 | } 788 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------