Example #1
0
func Testv4Defrag(t *testing.T) {
	nomalPack := make(chan gopacket.Packet, 5)
	fragV4Pack := make(chan gopacket.Packet, 5)
	go v4Defrag(fragV4Pack, nomalPack)
	pack1 := gopacket.NewPacket(testPing1Frag1, layers.LinkTypeEthernet, gopacket.Default)
	fragV4Pack <- pack1
	pack2 := gopacket.NewPacket(testPing1Frag2, layers.LinkTypeEthernet, gopacket.Default)
	fragV4Pack <- pack2
	pack3 := gopacket.NewPacket(testPing1Frag3, layers.LinkTypeEthernet, gopacket.Default)
	fragV4Pack <- pack3
	pack4 := gopacket.NewPacket(testPing1Frag4, layers.LinkTypeEthernet, gopacket.Default)
	fragV4Pack <- pack4
	result := <-nomalPack
	ip := result.Layer(layers.LayerTypeIPv4)
	//TEST if the ip matches expectation
	if ip == nil {
		t.Errorf("defrag does not return IPV4 LAYER")
	}
	if len(ip.LayerPayload()) != 4508 {
		t.Fatalf("defrag: expecting a packet of 4508 bytes, got %d", len(ip.LayerPayload()))
	}

	validPayload := append(testPing1Frag1[34:], testPing1Frag2[34:]...)
	validPayload = append(validPayload, testPing1Frag3[34:]...)
	validPayload = append(validPayload, testPing1Frag4[34:]...)

	if bytes.Compare(validPayload, ip.LayerPayload()) != 0 {
		fmt.Println(bytediff.BashOutput.String(
			bytediff.Diff(validPayload, ip.LayerPayload())))
		t.Errorf("defrag: payload is not correctly defragmented")
	}
}
Example #2
0
func TestUDPPacketVXLANGetInnerEthernetLayer(t *testing.T) {
	p := gopacket.NewPacket(testUDPPacketVXLAN, LinkTypeEthernet, gopacket.Default)
	if p.ErrorLayer() != nil {
		t.Error("Failed to decode packet:", p.ErrorLayer().Error())
	}
	// show how to extract the inner ethernet header
	vxlan := p.Layer(LayerTypeVxlan)
	p2 := gopacket.NewPacket(vxlan.LayerPayload(), LinkTypeEthernet, gopacket.Default)
	ethernetL := p2.Layer(LayerTypeEthernet)
	ethernet, _ := ethernetL.(*Ethernet)
	if ethernet == nil {
		t.Error("Failed to find ethernet header")
	}
	dstmac := net.HardwareAddr{0x00, 0x30, 0x88, 0x01, 0x00, 0x02}
	srcmac := net.HardwareAddr{0x00, 0x16, 0x3e, 0x37, 0xf6, 0x04}
	if ethernet.DstMAC[0] != dstmac[0] &&
		ethernet.DstMAC[1] != dstmac[1] &&
		ethernet.DstMAC[2] != dstmac[2] &&
		ethernet.DstMAC[3] != dstmac[3] &&
		ethernet.DstMAC[4] != dstmac[4] &&
		ethernet.DstMAC[5] != dstmac[5] &&
		ethernet.SrcMAC[0] != srcmac[0] &&
		ethernet.SrcMAC[1] != srcmac[1] &&
		ethernet.SrcMAC[2] != srcmac[2] &&
		ethernet.SrcMAC[3] != srcmac[3] &&
		ethernet.SrcMAC[4] != srcmac[4] &&
		ethernet.SrcMAC[5] != srcmac[5] &&
		ethernet.EthernetType != 0x0800 {
		t.Error("Decoded packet incorrect values")
	}

}
Example #3
0
func main() {
	// If we don't have a handle to a device or a file, but we have a bunch
	// of raw bytes, we can try to decode them in to packet information

	// NewPacket() takes the raw bytes that make up the packet as the first parameter
	// The second parameter is the lowest level layer you want to decode. It will
	// decode that layer and all layers on top of it. The third layer
	// is the type of decoding: default(all at once), lazy(on demand), and NoCopy
	// which will not create a copy of the buffer

	// Create an packet with ethernet, IP, TCP, and payload layers
	// We are creating one we know will be decoded properly but
	// your byte source could be anything. If any of the packets
	// come back as nil, that means it could not decode it in to
	// the proper layer (malformed or incorrect packet type)
	payload := []byte{2, 4, 6}
	options := gopacket.SerializeOptions{}
	buffer := gopacket.NewSerializeBuffer()
	gopacket.SerializeLayers(buffer, options,
		&layers.Ethernet{},
		&layers.IPv4{},
		&layers.TCP{},
		gopacket.Payload(payload),
	)
	rawBytes := buffer.Bytes()

	// Decode an ethernet packet
	ethPacket :=
		gopacket.NewPacket(
			rawBytes,
			layers.LayerTypeEthernet,
			gopacket.Default,
		)

	// with Lazy decoding it will only decode what it needs when it needs it
	// This is not concurrency safe. If using concurrency, use default
	ipPacket :=
		gopacket.NewPacket(
			rawBytes,
			layers.LayerTypeIPv4,
			gopacket.Lazy,
		)

	// With the NoCopy option, the underlying slices are referenced
	// directly and not copied. If the underlying bytes change so will
	// the packet
	tcpPacket :=
		gopacket.NewPacket(
			rawBytes,
			layers.LayerTypeTCP,
			gopacket.NoCopy,
		)

	fmt.Println(ethPacket)
	fmt.Println(ipPacket)
	fmt.Println(tcpPacket)
}
Example #4
0
func Testv4Defrag(t *testing.T) {
	v4defragger := ip4defrag.NewIPv4Defragmenter()
	pack1 := gopacket.NewPacket(testPing1Frag1, layers.LinkTypeEthernet, gopacket.Default)
	pack2 := gopacket.NewPacket(testPing1Frag2, layers.LinkTypeEthernet, gopacket.Default)
	pack3 := gopacket.NewPacket(testPing1Frag3, layers.LinkTypeEthernet, gopacket.Default)
	pack4 := gopacket.NewPacket(testPing1Frag4, layers.LinkTypeEthernet, gopacket.Default)
	result, err := v4defragger.DefragIPv4(pack1.Layer(layers.LayerTypeIPv4).(*layers.IPv4))
	if err != nil {
		t.Fatalf("error defragmenting pack1")
	}
	if result != nil {
		t.Fatalf("unexpected defragmented packet after pack1")
	}
	result, err = v4defragger.DefragIPv4(pack2.Layer(layers.LayerTypeIPv4).(*layers.IPv4))
	if err != nil {
		t.Fatalf("error defragmenting pack2")
	}
	if result != nil {
		t.Fatalf("unexpected defragmented packet after pack2")
	}
	result, err = v4defragger.DefragIPv4(pack3.Layer(layers.LayerTypeIPv4).(*layers.IPv4))
	if err != nil {
		t.Fatalf("error defragmenting pack3")
	}
	if result != nil {
		t.Fatalf("unexpected defragmented packet after pack3")
	}
	result, err = v4defragger.DefragIPv4(pack4.Layer(layers.LayerTypeIPv4).(*layers.IPv4))
	if err != nil {
		t.Fatalf("error defragmenting pack4")
	}
	if result == nil {
		t.Fatalf("missing defragmented packet after pack4")
	}
	ip := result
	// TEST if the ip matches expectation
	if ip == nil {
		t.Errorf("defrag does not return IPV4 LAYER")
	}
	if len(ip.LayerPayload()) != 4508 {
		t.Fatalf("defrag: expecting a packet of 4508 bytes, got %d", len(ip.LayerPayload()))
	}

	validPayload := append(testPing1Frag1[34:], testPing1Frag2[34:]...)
	validPayload = append(validPayload, testPing1Frag3[34:]...)
	validPayload = append(validPayload, testPing1Frag4[34:]...)

	if bytes.Compare(validPayload, ip.LayerPayload()) != 0 {
		fmt.Println(bytediff.BashOutput.String(
			bytediff.Diff(validPayload, ip.LayerPayload())))
		t.Errorf("defrag: payload is not correctly defragmented")
	}
}
Example #5
0
// Layers returns gopacket layer representation of this frame. layers contents are all pointer to struct,
// so you can modify the frame information simply setting values to the slice contents directly.
func (self *Frame) Layers() []gopacket.Layer {
	if len(self.serialized) != 0 {
		self.layers = gopacket.NewPacket(self.serialized, layers.LinkTypeEthernet, gopacket.Lazy).Layers()
		self.serialized = self.serialized[:0]
	}
	return self.layers
}
func getack(conn net.PacketConn, srcport layers.TCPPort, dstip string) (ack uint32, err error) {
	for {
		b := make([]byte, 4096)
		log.Println("reading from conn")
		var n int
		var addr net.Addr
		n, addr, err = conn.ReadFrom(b)
		if err != nil {
			log.Println("reading..", err)
			return
		} else if addr.String() == dstip {
			// Decode a packet
			packet := gopacket.NewPacket(b[:n], layers.LayerTypeTCP, gopacket.Default)
			// Get the TCP layer from this packet
			if tcpLayer := packet.Layer(layers.LayerTypeTCP); tcpLayer != nil {
				tcp, _ := tcpLayer.(*layers.TCP)
				if tcp.DstPort == srcport {
					if tcp.SYN && tcp.ACK {
						ack = tcp.Seq
					} else {
						err = errors.New("Port is CLOSED")
					}
					return
				}
			}
		} else {
			err = errors.New("Got packet not matching addr")
		}
	}
	return
}
Example #7
0
func v4Defrag(v4frag chan gopacket.Packet, normalPack chan gopacket.Packet) error {
	defragger := ip4defrag.NewIPv4Defragmenter()
	for {
		fragpack := <-v4frag
		layer := fragpack.Layer(layers.LayerTypeIPv4).(*layers.IPv4)
		in, err := defragger.DefragIPv4(layer)
		if err != nil {
			return err //error handle
		} else if in == nil { //part of fragment continue
			continue
		} else {
			b := gopacket.NewSerializeBuffer()
			ops := gopacket.SerializeOptions{
				FixLengths:       true,
				ComputeChecksums: true,
			}
			// it should be remebered that you should copy the payload in when you use SerializeTo
			ip_payload, _ := b.PrependBytes(len(in.Payload))
			copy(ip_payload, in.Payload)
			in.SerializeTo(b, ops)
			resultPack := gopacket.NewPacket(b.Bytes(), layers.LayerTypeIPv4, gopacket.Default)
			err := resultPack.ErrorLayer()
			if err != nil {
				fmt.Println("Error decoding some part of the packet:", err) //need error handle here
				//return
				continue
			}
			resultPack.Metadata().CaptureLength = len(resultPack.Data())
			resultPack.Metadata().Length = len(resultPack.Data())
			fmt.Println("defrag a package")
			normalPack <- resultPack
		}
	}
	return nil
}
Example #8
0
func main() {
	var err error
	var ci gopacket.CaptureInfo
	var frame []byte
	sniffer, err := bsdbpf.NewBPFSniffer("alc0", nil)
	if err != nil {
		panic(err)
	}
	for {
		frame, ci, err = sniffer.ReadPacketData()
		if err != nil {
			panic(err)
		}
		fmt.Printf("timeStamp %s\n", ci.Timestamp)
		packet := gopacket.NewPacket(frame, layers.LayerTypeEthernet, gopacket.Default)

		// Get the TCP layer from this packet
		if tcpLayer := packet.Layer(layers.LayerTypeTCP); tcpLayer != nil {
			fmt.Println("This is a TCP packet!")
			// Get actual TCP data from this layer
			tcp, _ := tcpLayer.(*layers.TCP)
			fmt.Printf("From src port %d to dst port %d\n", tcp.SrcPort, tcp.DstPort)
		}

		// Iterate over all layers, printing out each layer type
		for _, layer := range packet.Layers() {
			fmt.Println("PACKET LAYER:", layer.LayerType())
		}
	}
}
Example #9
0
func TestPacketDot11DataIP(t *testing.T) {
	p := gopacket.NewPacket(testPacketDot11DataIP, LinkTypeIEEE80211Radio, gopacket.Default)
	if p.ErrorLayer() != nil {
		t.Error("Failed to decode packet:", p.ErrorLayer().Error())
	}
	checkLayers(p, []gopacket.LayerType{LayerTypeRadioTap, LayerTypeDot11, LayerTypeDot11Data, LayerTypeLLC, LayerTypeSNAP, LayerTypeIPv4, LayerTypeUDP, gopacket.LayerTypePayload}, t)
}
Example #10
0
func TestDHCPv4EncodeResponse(t *testing.T) {
	dhcp := &DHCPv4{Operation: DHCPOpReply, HardwareType: LinkTypeEthernet, Xid: 0x12345678,
		ClientIP: net.IP{0, 0, 0, 0}, YourClientIP: net.IP{192, 168, 0, 123}, NextServerIP: net.IP{192, 168, 0, 1}, RelayAgentIP: net.IP{0, 0, 0, 0},
		ClientHWAddr: net.HardwareAddr{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc},
		ServerName:   make([]byte, 64), File: make([]byte, 128)}

	dhcp.Options = append(dhcp.Options, NewDHCPOption(DHCPOptMessageType, []byte{byte(DHCPMsgTypeOffer)}))
	dhcp.Options = append(dhcp.Options, NewDHCPOption(DHCPOptSubnetMask, []byte{255, 255, 255, 0}))
	dhcp.Options = append(dhcp.Options, NewDHCPOption(DHCPOptT1, []byte{0x00, 0x00, 0x0e, 0x10}))
	dhcp.Options = append(dhcp.Options, NewDHCPOption(DHCPOptT2, []byte{0x00, 0x00, 0x0e, 0x10}))
	dhcp.Options = append(dhcp.Options, NewDHCPOption(DHCPOptLeaseTime, []byte{0x00, 0x00, 0x0e, 0x10}))
	dhcp.Options = append(dhcp.Options, NewDHCPOption(DHCPOptServerID, []byte{192, 168, 0, 1}))

	buf := gopacket.NewSerializeBuffer()
	opts := gopacket.SerializeOptions{FixLengths: true}
	err := gopacket.SerializeLayers(buf, opts, dhcp)
	if err != nil {
		t.Fatal(err)
	}

	p2 := gopacket.NewPacket(buf.Bytes(), LayerTypeDHCPv4, testDecodeOptions)
	dhcp2 := p2.Layer(LayerTypeDHCPv4).(*DHCPv4)
	testDHCPEqual(t, dhcp, dhcp2)
	fmt.Print(p2)
}
Example #11
0
func TestVRRPPacketPacket0(t *testing.T) {
	p := gopacket.NewPacket(vrrpPacketPriority100, LinkTypeEthernet, gopacket.Default)
	if p.ErrorLayer() != nil {
		t.Error("Failed to decode packet", p.ErrorLayer().Error())
	}
	checkLayers(p, []gopacket.LayerType{LayerTypeEthernet, LayerTypeIPv4, LayerTypeVRRP}, t)

	// Version=2 Type=VRRPv2 Advertisement VirtualRtrID=1 Priority=100
	vrrp := p.Layer(LayerTypeVRRP).(*VRRPv2)
	if vrrp.Version != 2 {
		t.Fatalf("Unable to decode VRRPv2 version. Received %d, expected %d", vrrp.Version, 2)
	}

	if vrrp.Type != 1 {
		t.Fatalf("Unable to decode VRRPv2 type. Received %d, expected %d", vrrp.Type, 1)
	}

	if vrrp.Priority != 100 {
		t.Fatalf("Unable to decode VRRPv2 priority. Received %d, expected %d", vrrp.Priority, 100)
	}

	if vrrp.Checksum != 47698 {
		t.Fatalf("Unable to decode VRRPv2 checksum. Received %d, expected %d", vrrp.Checksum, 47698)
	}
}
Example #12
0
func (h *arpPktInHandler) Rcv(msg bh.Msg, ctx bh.RcvContext) error {
	pin := msg.Data().(nom.PacketIn)
	p := gopacket.NewPacket([]byte(pin.Packet), layers.LayerTypeEthernet, gopacket.Default)
	etherlayer := p.Layer(layers.LayerTypeEthernet)

	if etherlayer == nil {
		return nil
	}

	e, _ := etherlayer.(*layers.Ethernet)

	if e.EthernetType != layers.EthernetTypeARP {
		return nil
	}

	host, _, err := decodeARP([]byte(pin.Packet))
	host.Node = pin.Node

	if err != nil {
		glog.Errorf("ARP decoding error: %v", err)
		return err
	}
	glog.V(2).Infof("Host detected: %v", host)

	ctx.Emit(nom.HostConnected(host))

	return nil
}
Example #13
0
func TestPacketVXLAN(t *testing.T) {
	p := gopacket.NewPacket(testPacketVXLAN, LinkTypeEthernet, gopacket.Default)
	if p.ErrorLayer() != nil {
		t.Error("Failed to decode packet:", p.ErrorLayer().Error())
	}
	checkLayers(p, []gopacket.LayerType{LayerTypeEthernet, LayerTypeIPv4, LayerTypeUDP, LayerTypeVXLAN, LayerTypeEthernet, LayerTypeIPv4, LayerTypeICMPv4, gopacket.LayerTypePayload}, t)
	if got, ok := p.Layer(LayerTypeVXLAN).(*VXLAN); ok {
		want := &VXLAN{
			BaseLayer: BaseLayer{
				Contents: []byte{0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00},
				Payload: []byte{0x00, 0x30, 0x88, 0x01, 0x00, 0x02, 0x00, 0x16, 0x3e, 0x37, 0xf6, 0x04, 0x08, 0x00,
					0x45, 0x00, 0x00, 0x54, 0x00, 0x00, 0x40, 0x00, 0x40, 0x01, 0x23, 0x4f, 0xc0, 0xa8, 0xcb, 0x03,
					0xc0, 0xa8, 0xcb, 0x05, 0x08, 0x00, 0xf6, 0xf2, 0x05, 0x0c, 0x00, 0x01, 0xfc, 0xe2, 0x97, 0x51,
					0x00, 0x00, 0x00, 0x00, 0xa6, 0xf8, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x11, 0x12, 0x13,
					0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
					0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33,
					0x34, 0x35, 0x36, 0x37},
			},
			ValidIDFlag:      true,
			VNI:              255,
			GBPExtension:     false,
			GBPApplied:       false,
			GBPDontLearn:     false,
			GBPGroupPolicyID: 0,
		}
		if !reflect.DeepEqual(want, got) {
			t.Errorf("VXLAN layer mismatch, \nwant %#v\ngot %#v\n", want, got)
		}
	}
}
Example #14
0
func (vnet *VNET) runReader(ctx context.Context) {
	defer vnet.wg.Done()

	var maxPktSize = vnet.iface.MaxPacketSize()

	for {
		var pkt = NewPacket(maxPktSize)

		n, flags, err := vnet.iface.ReadPacket(pkt.buf)
		if err == io.EOF {
			pkt.Release()
			return
		}
		if err != nil {
			pkt.Release()
			log.Printf("error during read: %s", err)
			time.Sleep(10 * time.Millisecond)
			continue
		}

		pkt.Packet = gopacket.NewPacket(pkt.buf[:n], layers.LayerTypeEthernet, gopacket.NoCopy)
		pkt.Flags = flags
		pkt.layers = pkt.Layers()

		vnet.dispatch(ctx, pkt)
	}
}
Example #15
0
func TestPacketUSB0(t *testing.T) {
	p := gopacket.NewPacket(testPacketUSB0, LinkTypeLinuxUSB, gopacket.Default)
	if p.ErrorLayer() != nil {
		t.Error("Failed to decode packet:", p.ErrorLayer().Error())
	}
	checkLayers(p, []gopacket.LayerType{LayerTypeUSB, LayerTypeUSBInterrupt}, t)

	if got, ok := p.Layer(LayerTypeUSB).(*USB); ok {
		want := &USB{
			BaseLayer: BaseLayer{
				Contents: []uint8{0x0, 0x38, 0x4a, 0x3b, 0x0, 0x88, 0xff, 0xff, 0x43, 0x1, 0x81, 0x1, 0x2, 0x0, 0x2d, 0x0, 0xc0, 0xd3, 0x5b, 0x50, 0x0, 0x0, 0x0, 0x0, 0x8a, 0x85, 0xa, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0},
				Payload:  []uint8{0x4},
			},
			ID:             0xffff88003b4a3800,
			EventType:      USBEventTypeComplete,
			TransferType:   USBTransportTypeInterrupt,
			Direction:      0x1,
			EndpointNumber: 0x1,
			DeviceAddress:  0x1,
			BusID:          0x2,
			TimestampSec:   1348195264,
			TimestampUsec:  689546,
			Setup:          false,
			Data:           true,
			Status:         0,
			UrbLength:      0x1,
			UrbDataLength:  0x1,
		}

		if !reflect.DeepEqual(got, want) {
			t.Errorf("USB packet processing failed:\ngot  :\n%#v\n\nwant :\n%#v\n\n", got, want)
		}
	}

}
Example #16
0
func TestDHCPv4EncodeRequest(t *testing.T) {
	dhcp := &DHCPv4{Operation: DHCPOpRequest, HardwareType: LinkTypeEthernet, Xid: 0x12345678,
		ClientIP: net.IP{0, 0, 0, 0}, YourClientIP: net.IP{0, 0, 0, 0}, NextServerIP: net.IP{0, 0, 0, 0}, RelayAgentIP: net.IP{0, 0, 0, 0},
		ClientHWAddr: net.HardwareAddr{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc},
		ServerName:   make([]byte, 64), File: make([]byte, 128)}

	dhcp.Options = append(dhcp.Options, NewDHCPOption(DHCPOptMessageType, []byte{byte(DHCPMsgTypeDiscover)}))
	dhcp.Options = append(dhcp.Options, NewDHCPOption(DHCPOptHostname, []byte{'e', 'x', 'a', 'm', 'p', 'l', 'e', '.', 'c', 'o', 'm'}))
	dhcp.Options = append(dhcp.Options, NewDHCPOption(DHCPOptParamsRequest,
		[]byte{byte(DHCPOptSubnetMask), byte(DHCPOptBroadcastAddr), byte(DHCPOptTimeOffset),
			byte(DHCPOptRouter), byte(DHCPOptDomainName), byte(DHCPOptDNS), byte(DHCPOptDomainSearch),
			byte(DHCPOptHostname), byte(DHCPOptNetBIOSTCPNS), byte(DHCPOptInterfaceMTU), byte(DHCPOptClasslessStaticRoute),
			byte(DHCPOptNTPServers)}))

	buf := gopacket.NewSerializeBuffer()
	opts := gopacket.SerializeOptions{FixLengths: true}
	err := gopacket.SerializeLayers(buf, opts, dhcp)
	if err != nil {
		t.Fatal(err)
	}

	p2 := gopacket.NewPacket(buf.Bytes(), LayerTypeDHCPv4, testDecodeOptions)
	dhcp2 := p2.Layer(LayerTypeDHCPv4).(*DHCPv4)
	testDHCPEqual(t, dhcp, dhcp2)
}
Example #17
0
func decodeInGRELayer(data []byte, p gopacket.PacketBuilder) error {
	switch (data[0] >> 4) & 0xf {
	case 4:
		ip4 := &layers.IPv4{}
		err := ip4.DecodeFromBytes(data, p)
		p.AddLayer(ip4)
		p.SetNetworkLayer(ip4)
		if err != nil {
			return err
		}
		return p.NextDecoder(ip4.NextLayerType())
	case 6:
		ip6 := &layers.IPv6{}
		err := ip6.DecodeFromBytes(data, p)
		p.AddLayer(ip6)
		p.SetNetworkLayer(ip6)
		if err != nil {
			return err
		}
		return p.NextDecoder(ip6.NextLayerType())
	}
	packet := gopacket.NewPacket(data, layers.LayerTypeARP, gopacket.Lazy)
	layer := packet.Layer(layers.LayerTypeARP)

	p.AddLayer(layer)

	return nil
}
Example #18
0
func TestPacketDot11DataARP(t *testing.T) {
	p := gopacket.NewPacket(testPacketDot11DataARP, LinkTypeIEEE80211Radio, gopacket.Default)
	if p.ErrorLayer() != nil {
		t.Error("Failed to decode packet:", p.ErrorLayer().Error())
	}
	checkLayers(p, []gopacket.LayerType{LayerTypeRadioTap, LayerTypeDot11, LayerTypeDot11Data, LayerTypeLLC, LayerTypeSNAP, LayerTypeARP}, t)

	if got, ok := p.Layer(LayerTypeARP).(*ARP); ok {
		want := &ARP{
			BaseLayer: BaseLayer{
				Contents: []uint8{0x0, 0x1, 0x8, 0x0, 0x6, 0x4, 0x0, 0x1, 0x0, 0x19, 0xe3, 0xd3, 0x53, 0x52, 0xa9, 0xfe, 0xf7, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x43, 0x8, 0xe, 0x36},
				Payload:  []uint8{},
			},
			AddrType:          0x1,
			Protocol:          0x800,
			HwAddressSize:     0x6,
			ProtAddressSize:   0x4,
			Operation:         0x1,
			SourceHwAddress:   []uint8{0x0, 0x19, 0xe3, 0xd3, 0x53, 0x52},
			SourceProtAddress: []uint8{0xa9, 0xfe, 0xf7, 0x0},
			DstHwAddress:      []uint8{0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
			DstProtAddress:    []uint8{0x43, 0x8, 0xe, 0x36},
		}

		if !reflect.DeepEqual(got, want) {
			t.Errorf("ARP packet processing failed:\ngot  :\n%#v\n\nwant :\n%#v\n\n", got, want)
		}
	}
}
Example #19
0
// checkNTP() uses the ntp.go code to analyse the packet bytes as an NTP UDP
// packet and generate an NTP object. It then compares the generated NTP object
// with the one provided and raises the alarm if there is any difference.
// The desc argument is output with any failure message to identify the test.
func checkNTP(desc string, t *testing.T, packetBytes []byte, pExpectedNTP *NTP) {

	// Analyse the packet bytes, yielding a new packet object p.
	p := gopacket.NewPacket(packetBytes, LinkTypeEthernet, gopacket.Default)
	if p.ErrorLayer() != nil {
		t.Errorf("Failed to decode packet %s: %v", desc, p.ErrorLayer().Error())
	}

	// Ensure that the packet analysis yielded the correct set of layers:
	//    Link Layer        = Ethernet.
	//    Network Layer     = IPv4.
	//    Transport Layer   = UDP.
	//    Application Layer = NTP.
	checkLayers(p, []gopacket.LayerType{
		LayerTypeEthernet,
		LayerTypeIPv4,
		LayerTypeUDP,
		LayerTypeNTP}, t)

	// Select the Application (NTP) layer.
	pResultNTP, ok := p.ApplicationLayer().(*NTP)
	if !ok {
		t.Error("No NTP layer type found in packet in " + desc + ".")
	}

	// Compare the generated NTP object with the expected NTP object.
	if !reflect.DeepEqual(pResultNTP, pExpectedNTP) {
		t.Errorf("NTP packet processing failed for packet "+desc+
			":\ngot  :\n%#v\n\nwant :\n%#v\n\n", pResultNTP, pExpectedNTP)
	}
}
Example #20
0
func TestUDPPacketVXLAN(t *testing.T) {
	p := gopacket.NewPacket(testUDPPacketVXLAN, LinkTypeEthernet, gopacket.Default)
	if p.ErrorLayer() != nil {
		t.Error("Failed to decode packet:", p.ErrorLayer().Error())
	}
	checkLayers(p, []gopacket.LayerType{LayerTypeEthernet, LayerTypeIPv4,
		LayerTypeUDP, LayerTypeVxlan, LayerTypeEthernet, LayerTypeIPv4,
		LayerTypeICMPv4, gopacket.LayerTypePayload}, t)

	vxlanL := p.Layer(LayerTypeVxlan)
	if vxlanL == nil {
		t.Fatal("Failed to get a pointer to VXLAN struct")
	}
	vxlan, _ := vxlanL.(*VXLAN)
	if vxlan.Flags != 0x08 {
		t.Fatal("Failed to decode Flags properly")
	}

	if vxlan.VNI[0] != 0x00 ||
		vxlan.VNI[1] != 0x00 ||
		vxlan.VNI[2] != 0x00 {
		t.Fatal("Failed to decode VNI properly")
	}

}
Example #21
0
func main() {
	var err error
	sniffer := bpf_sniffer.NewBpfSniffer()
	err = sniffer.Init("vio0")
	if err != nil {
		panic(err)
	}

	for {
		timedFrame := sniffer.ReadTimedFrame()
		// Decode a packet
		fmt.Printf("timedFrame timestamp %s\n", timedFrame.Timestamp)
		packet := gopacket.NewPacket(timedFrame.RawFrame, layers.LayerTypeEthernet, gopacket.Default)
		// Get the TCP layer from this packet
		if tcpLayer := packet.Layer(layers.LayerTypeTCP); tcpLayer != nil {
			fmt.Println("This is a TCP packet!")
			// Get actual TCP data from this layer
			tcp, _ := tcpLayer.(*layers.TCP)
			fmt.Printf("From src port %d to dst port %d\n", tcp.SrcPort, tcp.DstPort)
		}

		// Iterate over all layers, printing out each layer type
		for _, layer := range packet.Layers() {
			fmt.Println("PACKET LAYER:", layer.LayerType())
		}
	}
}
Example #22
0
func TestPacketIPSecESP(t *testing.T) {
	p := gopacket.NewPacket(testPacketIPSecESP, LinkTypeEthernet, gopacket.Default)
	if p.ErrorLayer() != nil {
		t.Error("Failed to decode packet:", p.ErrorLayer().Error())
	}
	checkLayers(p, []gopacket.LayerType{LayerTypeEthernet, LayerTypeIPv4, LayerTypeIPSecESP}, t)
}
Example #23
0
func (sfa *SFlowAgent) feedFlowTable(packetsChan chan flow.FlowPackets) {
	var buf [maxDgramSize]byte
	for {
		_, _, err := sfa.Conn.ReadFromUDP(buf[:])
		if err != nil {
			return
		}

		// TODO use gopacket.NoCopy ? instead of gopacket.Default
		p := gopacket.NewPacket(buf[:], layers.LayerTypeSFlow, gopacket.Default)
		sflowLayer := p.Layer(layers.LayerTypeSFlow)
		sflowPacket, ok := sflowLayer.(*layers.SFlowDatagram)
		if !ok {
			continue
		}

		if sflowPacket.SampleCount > 0 {
			logging.GetLogger().Debugf("%d sample captured", sflowPacket.SampleCount)
			for _, sample := range sflowPacket.FlowSamples {
				// iterate over a set of FlowPackets as a sample contains multiple
				// records each generating FlowPackets.
				for _, flowPackets := range flow.FlowPacketsFromSFlowSample(&sample) {
					packetsChan <- flowPackets
				}
			}
		}
	}
}
Example #24
0
func TestPacketDNSRegression(t *testing.T) {
	p := gopacket.NewPacket(testPacketDNSRegression, LinkTypeEthernet, testDecodeOptions)
	if p.ErrorLayer() != nil {
		t.Error("Failed to decode packet:", p.ErrorLayer().Error())
	}
	checkLayers(p, []gopacket.LayerType{LayerTypeEthernet, LayerTypeIPv4, LayerTypeUDP, LayerTypeDNS}, t)
}
Example #25
0
func main() {
	// If you create your own encoding and decoding you can essentially
	// create your own protocol or implement a protocol that is not
	// already defined in the layers package. In our example we are just
	// wrapping a normal ethernet packet with our own layer.
	// Creating your own protocol is good if you want to create
	// some obfuscated binary data type that was difficult for others
	// to decode

	// Finally, decode your packets:
	rawBytes := []byte{0xF0, 0x0F, 65, 65, 66, 67, 68}
	packet := gopacket.NewPacket(
		rawBytes,
		CustomLayerType,
		gopacket.Default,
	)
	fmt.Println("Created packet out of raw bytes.")
	fmt.Println(packet)

	// Decode the packet as our custom layer
	customLayer := packet.Layer(CustomLayerType)
	if customLayer != nil {
		fmt.Println("Packet was successfully decoded with custom layer decoder.")
		customLayerContent, _ := customLayer.(*CustomLayer)
		// Now we can access the elements of the custom struct
		fmt.Println("Payload: ", customLayerContent.LayerPayload())
		fmt.Println("SomeByte element:", customLayerContent.SomeByte)
		fmt.Println("AnotherByte element:", customLayerContent.AnotherByte)

	}
}
Example #26
0
func TestDNSEncodeQuery(t *testing.T) {
	dns := &DNS{ID: 1234, OpCode: DNSOpCodeQuery, RD: true}
	dns.Questions = append(dns.Questions,
		DNSQuestion{
			Name:  []byte("example1.com"),
			Type:  DNSTypeA,
			Class: DNSClassIN,
		})

	dns.Questions = append(dns.Questions,
		DNSQuestion{
			Name:  []byte("example2.com"),
			Type:  DNSTypeA,
			Class: DNSClassIN,
		})

	buf := gopacket.NewSerializeBuffer()
	opts := gopacket.SerializeOptions{FixLengths: true}
	err := gopacket.SerializeLayers(buf, opts, dns)
	if err != nil {
		t.Fatal(err)
	}
	if int(dns.QDCount) != len(dns.Questions) {
		t.Errorf("fix lengths did not adjust QDCount, expected %d got %d", len(dns.Questions), dns.QDCount)
	}

	p2 := gopacket.NewPacket(buf.Bytes(), LayerTypeDNS, testDecodeOptions)
	dns2 := p2.Layer(LayerTypeDNS).(*DNS)
	testDNSEqual(t, dns, dns2)
}
Example #27
0
func forgeEthIPTCP(t *testing.T, seed int64) *gopacket.Packet {
	var options gopacket.SerializeOptions
	rnd := rand.New(rand.NewSource(seed))

	rawBytes := []byte{10, 20, 30}
	ethernetLayer := &layers.Ethernet{
		SrcMAC: net.HardwareAddr{0x00, 0x0F, 0xAA, 0xFA, 0xAA, byte(rnd.Intn(0x100))},
		DstMAC: net.HardwareAddr{0x00, 0x0D, 0xBD, 0xBD, byte(rnd.Intn(0x100)), 0xBD},
	}
	ipLayer := &layers.IPv4{
		SrcIP: net.IP{127, 0, 0, byte(rnd.Intn(0x100))},
		DstIP: net.IP{byte(rnd.Intn(0x100)), 8, 8, 8},
	}
	tcpLayer := &layers.TCP{
		SrcPort: layers.TCPPort(byte(rnd.Intn(0x10000))),
		DstPort: layers.TCPPort(byte(rnd.Intn(0x10000))),
	}
	// And create the packet with the layers
	buffer := gopacket.NewSerializeBuffer()
	err := gopacket.SerializeLayers(buffer, options,
		ethernetLayer,
		ipLayer,
		tcpLayer,
		gopacket.Payload(rawBytes),
	)
	if err != nil {
		t.Fail()
	}

	gpacket := gopacket.NewPacket(buffer.Bytes(), layers.LayerTypeEthernet, gopacket.Default)
	return &gpacket

}
Example #28
0
func TestGREChecksum(t *testing.T) {
	buf := gopacket.NewSerializeBuffer()
	opts := gopacket.SerializeOptions{
		ComputeChecksums: true,
		FixLengths:       true,
	}
	for cksum, packet := range testGREChecksum {
		buf.Clear()
		if err := setNetworkLayer(packet); err != nil {
			t.Errorf("Failed to set network layer: %v", err)
			continue
		}
		if err := gopacket.SerializeLayers(buf, opts, packet...); err != nil {
			t.Errorf("Failed to serialize packet: %v", err)
			continue
		}
		p := gopacket.NewPacket(buf.Bytes(), LinkTypeEthernet, gopacket.Default)
		t.Log(p)
		if p.ErrorLayer() != nil {
			t.Error("Failed to decode packet:", p.ErrorLayer().Error())
			continue
		}
		if got, ok := p.Layer(LayerTypeGRE).(*GRE); ok {
			if got.Checksum != cksum {
				t.Errorf("Incorrect checksum calculated for GRE packet: want %v, got %v", cksum, got.Checksum)
			}
		}
	}
}
Example #29
0
func TestPacketIPv6Destination0Decode(t *testing.T) {
	ip6 := &IPv6{
		BaseLayer: BaseLayer{
			Contents: []byte{
				0x60, 0x00, 0x00, 0x00, 0x00, 0x08, 0x3c, 0x40, 0x20, 0x01, 0x0d, 0xb8, 0x00, 0x00, 0x00, 0x00,
				0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x20, 0x01, 0x0d, 0xb8, 0x00, 0x00, 0x00, 0x00,
				0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
			},
			Payload: []byte{0x3b, 0x00, 0x01, 0x04, 0x00, 0x00, 0x00, 0x00},
		},
		Version:      6,
		TrafficClass: 0,
		FlowLabel:    0,
		Length:       8,
		NextHeader:   IPProtocolIPv6Destination,
		HopLimit:     64,
		SrcIP:        net.IP{0x20, 0x01, 0x0d, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		DstIP: net.IP{0x20, 0x01, 0x0d, 0xb8, 0x00, 0x00, 0x00, 0x00,
			0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02},
	}

	dst := &IPv6Destination{}
	dst.BaseLayer = BaseLayer{
		Contents: []byte{0x3b, 0x00, 0x01, 0x04, 0x00, 0x00, 0x00, 0x00},
		Payload:  []byte{},
	}
	dst.NextHeader = IPProtocolNoNextHeader
	dst.HeaderLength = uint8(0)
	dst.ActualLength = 8
	opt := &IPv6DestinationOption{
		OptionType:   uint8(0x01),
		OptionLength: uint8(0x04),
		ActualLength: 6,
		OptionData:   []byte{0x00, 0x00, 0x00, 0x00},
	}
	dst.Options = append(dst.Options, opt)

	p := gopacket.NewPacket(testPacketIPv6Destination0, LinkTypeRaw, gopacket.Default)
	if p.ErrorLayer() != nil {
		t.Error("Failed to decode packet:", p.ErrorLayer().Error())
	}
	checkLayers(p, []gopacket.LayerType{LayerTypeIPv6, LayerTypeIPv6Destination}, t)
	if got, ok := p.Layer(LayerTypeIPv6).(*IPv6); ok {
		want := ip6
		if !reflect.DeepEqual(got, want) {
			t.Errorf("IPv6 packet processing failed:\ngot:\n%#v\n\nwant:\n%#v\n\n", got, want)
		}
	} else {
		t.Error("No IPv6 layer type found in packet")
	}
	if got, ok := p.Layer(LayerTypeIPv6Destination).(*IPv6Destination); ok {
		want := dst
		if !reflect.DeepEqual(got, want) {
			t.Errorf("IPv6Destination packet processing failed:\ngot:\n%#v\n\nwant:\n%#v\n\n", got, want)
		}
	} else {
		t.Error("No IPv6Destination layer type found in packet")
	}
}
Example #30
0
//need work
func (f *fragmentList) build(in gopacket.Packet) (gopacket.Packet, error) {
	var final []byte
	var currentOffset uint16 = 0

	debug.Printf("defrag: building the datagram \n")
	for e := f.List.Front(); e != nil; e = e.Next() {
		pack, _ := e.Value.(gopacket.Packet)
		frag := pack.Layer(layers.LayerTypeIPv6Fragment).(*layers.IPv6Fragment)
		ip := pack.Layer(layers.LayerTypeIPv6).(*layers.IPv6)
		if frag.FragmentOffset*8 == currentOffset {
			debug.Printf("defrag: building - adding %d\n", frag.FragmentOffset*8)
			final = append(final, frag.Payload...)
			currentOffset = currentOffset + ip.Length - 8
		} else if frag.FragmentOffset*8 < currentOffset {
			// overlapping fragment - let's take only what we need
			startAt := currentOffset - frag.FragmentOffset*8
			debug.Printf("defrag: building - overlapping, starting at %d\n",
				startAt)
			if startAt > ip.Length-8 {
				return nil, fmt.Errorf("defrag: building - invalid fragment")
			}
			final = append(final, frag.Payload[startAt:]...)
			currentOffset = currentOffset + frag.FragmentOffset*8
		} else {
			// Houston - we have an hole !
			debug.Printf("defrag: hole found while building, " +
				"stopping the defrag process\n")
			return nil, fmt.Errorf("defrag: building - hole found")
		}
		debug.Printf("defrag: building - next is %d\n", currentOffset)
	}
	final_ipv6 := in.Layer(layers.LayerTypeIPv6).(*layers.IPv6)
	final_frag := in.Layer(layers.LayerTypeIPv6Fragment).(*layers.IPv6Fragment)
	// TODO recompute IP Checksum
	out := &layers.IPv6{
		Version:      final_ipv6.Version,
		TrafficClass: final_ipv6.TrafficClass,
		FlowLabel:    final_ipv6.FlowLabel,
		Length:       f.Highest,
		NextHeader:   final_frag.NextHeader,
		HopLimit:     final_ipv6.HopLimit,
		SrcIP:        final_ipv6.SrcIP,
		DstIP:        final_ipv6.DstIP,
		HopByHop:     final_ipv6.HopByHop,
	}
	out.Payload = final
	v6SerailizeBuffer := gopacket.NewSerializeBuffer()
	v6Buffer, _ := v6SerailizeBuffer.PrependBytes(len(final))
	copy(v6Buffer, final)
	ops := gopacket.SerializeOptions{
		FixLengths:       true,
		ComputeChecksums: true,
	}
	out.SerializeTo(v6SerailizeBuffer, ops)
	outPacket := gopacket.NewPacket(v6SerailizeBuffer.Bytes(), layers.LayerTypeIPv6, gopacket.Default)
	outPacket.Metadata().CaptureLength = len(outPacket.Data())
	outPacket.Metadata().Length = len(outPacket.Data())
	return outPacket, nil
}