Example #1
1
// readARP watches a handle for incoming ARP responses we might care about, and prints them.
//
// readARP loops until 'stop' is closed.
func readARP(handle *pcap.Handle, iface *net.Interface, stop chan struct{}) {
	src := gopacket.NewPacketSource(handle, layers.LayerTypeEthernet)
	in := src.Packets()
	for {
		var packet gopacket.Packet
		select {
		case <-stop:
			return
		case packet = <-in:
			arpLayer := packet.Layer(layers.LayerTypeARP)
			if arpLayer == nil {
				continue
			}
			arp := arpLayer.(*layers.ARP)
			if arp.Operation != layers.ARPReply || bytes.Equal([]byte(iface.HardwareAddr), arp.SourceHwAddress) {
				// This is a packet I sent.
				continue
			}
			// Note:  we might get some packets here that aren't responses to ones we've sent,
			// if for example someone else sends US an ARP request.  Doesn't much matter, though...
			// all information is good information :)
			log.Printf("IP %v is at %v", net.IP(arp.SourceProtAddress), net.HardwareAddr(arp.SourceHwAddress))
		}
	}
}
Example #2
0
// HandlePacketTmp used in development to display package data
func (krb *krbAuth) HandlePacketTmp(packet gopacket.Packet) {
	app := packet.ApplicationLayer()
	if app == nil {
		return
	}
	udp := packet.TransportLayer().(*layers.UDP)

	if udp.DstPort == 88 {
		msgType := app.Payload()[17:18]
		if msgType[0] == 10 { // AS-REQ type = 10
			var n kdcReq
			_, err := asn1.UnmarshalWithParams(app.Payload(), &n, asReqParam)
			if err != nil {
				fmt.Println("Error in asn.1 parse")
				fmt.Println(err)
			} else {
				fmt.Println("-------------------------------")
				fmt.Printf("PnDataType: %v\n", n.PnData[0].PnDataType)
				//fmt.Println(hex.Dump(n.Pdata[0].PdataValue))
				var encData encryptedData
				asn1.Unmarshal(n.PnData[0].PnDataValue, &encData)
				fmt.Printf("Etype: %v\n", encData.Etype)
				fmt.Printf("Kvno: %v\n", encData.Kvno)
				//fmt.Println(hex.Dump(encData.Cipher))
				//fmt.Println(len(encData.Cipher))
				fmt.Printf("Cname: %v\n", n.ReqBody.Cname)
				fmt.Printf("Sname %v\n", n.ReqBody.Sname)
				fmt.Printf("Realm: %v\n", n.ReqBody.Realm)

			}
		}
	}
}
Example #3
0
File: main.go Project: flier/gohs
func (b *Benchmark) decodePacket(pkt gopacket.Packet) (key *FiveTuple, payload []byte) {
	ipv4, ok := pkt.NetworkLayer().(*layers.IPv4)

	if !ok {
		return // Ignore packets that aren't IPv4
	}

	if ipv4.FragOffset != 0 || (ipv4.Flags&layers.IPv4MoreFragments) != 0 {
		return // Ignore fragmented packets.
	}

	var stream FiveTuple

	stream.protocol = ipv4.Protocol
	stream.srcAddr = ipv4.SrcIP
	stream.dstAddr = ipv4.DstIP

	switch t := pkt.TransportLayer().(type) {
	case *layers.TCP:
		stream.srcPort = uint16(t.SrcPort)
		stream.dstPort = uint16(t.DstPort)
		return &stream, t.Payload

	case *layers.UDP:
		stream.srcPort = uint16(t.SrcPort)
		stream.dstPort = uint16(t.DstPort)
		return &stream, t.Payload
	}

	return
}
Example #4
0
//if it is the output stream from local machine
func outputStream(packet gopacket.Packet, Srcaddr *metrics.Address, Destaddr *metrics.Address) {
	ishttp, httpcontent := detectHttp(packet)
	if httpcontent != nil {
		if glog.V(1) {
			//glog.Info("the content of packet sent:", string(httpcontent))
		}
	}

	if ishttp {
		sendtime := time.Now()
		//iphandler := packet.Layer(layers.LayerTypeIPv4)
		reqdetail := string(packet.ApplicationLayer().LayerContents())
		httpinstance := &metrics.HttpTransaction{
			Srcip:        Srcaddr.IP,
			Srcport:      Srcaddr.PORT,
			Destip:       Destaddr.IP,
			Destport:     Destaddr.PORT,
			Timesend:     sendtime,
			Packetdetail: metrics.Packetdetail{Requestdetail: reqdetail, Responddetail: ""},
		}
		//put the httpinstance into a list
		if glog.V(1) {
			glog.Infof("store the instance:%v\n", httpinstance)
		}
		httpinstancelist.PushBack(httpinstance)
		if glog.V(2) {
			glog.Infof("the length of the list :", httpinstancelist.Len())
		}
	}

}
Example #5
0
// GetDstIP returns the destination ipV4ยง as a string
func GetDstIP(packet gopacket.Packet) string {
	if ipLayer := packet.Layer(layers.LayerTypeIPv4); ipLayer != nil {
		ip, _ := ipLayer.(*layers.IPv4)
		return ip.DstIP.String()
	}
	return ""
}
Example #6
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
}
Example #7
0
// newIPv4 returns a new initialized IPv4 Flow
func newipv6(packet gopacket.Packet) ipv6 {
	frag := packet.Layer(layers.LayerTypeIPv6Fragment).(*layers.IPv6Fragment)
	ip := packet.Layer(layers.LayerTypeIPv6).(*layers.IPv6)
	return ipv6{
		ip6: ip.NetworkFlow(),
		id:  frag.Identification,
	}
}
Example #8
0
func parseForSip(packet gopacket.Packet) *sipparser.SipMsg {
	ipLayer := packet.Layer(layers.LayerTypeIPv4)
	appLayer := packet.ApplicationLayer()
	fmt.Println("PAYLOAD: " + string(appLayer.Payload()) + " - END.")
	if ipLayer != nil && appLayer != nil && strings.Contains(string(appLayer.Payload()), "SIP") {
		return sipparser.ParseMsg(string(appLayer.Payload()))
	}

	return nil
}
Example #9
0
func (p *processor) getFlow(pkt gopacket.Packet) gopacket.Flow {
	mu := moldudp64Layer(pkt)
	//p.flowBufSrc.Reset()
	//p.flowBufSrc.Write(pkt.NetworkLayer().NetworkFlow().Src().Raw())
	//p.flowBufSrc.Write(pkt.TransportLayer().TransportFlow().Src().Raw())
	//p.flowBufSrc.Write(mu.Flow().Src().Raw())
	p.flowBufDst.Reset()
	p.flowBufDst.Write(pkt.NetworkLayer().NetworkFlow().Dst().Raw())
	p.flowBufDst.Write(pkt.TransportLayer().TransportFlow().Dst().Raw())
	p.flowBufDst.Write(mu.Flow().Dst().Raw())
	return gopacket.NewFlow(packet.EndpointCombinedSession, p.flowBufSrc.Bytes(), p.flowBufDst.Bytes())
}
Example #10
0
//RetrieveSrcIP retrieves the src ip of a packet
func RetrieveSrcIP(packet gopacket.Packet) (net.IP, error) {
	iplayers := packet.Layer(layers.LayerTypeIPv4)

	if iplayers != nil {
		ipc, ok := iplayers.(*layers.IPv4)

		if ok {
			return ipc.SrcIP, nil
		}
	}
	return nil, ErrBadPacket
}
Example #11
0
//RetrieveSrcPort retrieves the src port of a packet
func RetrieveSrcPort(packet gopacket.Packet) (int, error) {
	iplayers := packet.Layer(layers.LayerTypeTCP)

	if iplayers != nil {
		ipc, ok := iplayers.(*layers.TCP)

		if ok {
			return int(ipc.SrcPort), nil
		}
	}
	return 0, ErrBadPacket
}
Example #12
0
File: scanner.go Project: ev46/DNA
//------ PCAP Print PCAP Data -----
func process_gopacket(packet gopacket.Packet) {

	// Let's see if the packet is IP (even though the ether type told us)
	ipLayer := packet.Layer(layers.LayerTypeIPv4)
	if ipLayer != nil {
		ip, _ := ipLayer.(*layers.IPv4)

		register_network_call_with_redis(ip.Protocol, ip.DstIP)
	}

	// Check for errors
	if err := packet.ErrorLayer(); err != nil {
		fmt.Println("Error decoding some part of the packet:", err)
	}
}
Example #13
0
//detect the http packet return the info
func detectHttp(packet gopacket.Packet) (bool, []byte) {
	applicationLayer := packet.ApplicationLayer()
	if applicationLayer != nil {
		if strings.Contains(string(applicationLayer.Payload()), "HTTP") {

			if glog.V(1) {
				glog.Info("HTTP found!")
			}
			return true, applicationLayer.LayerContents()
		} else {
			return false, nil
		}
	} else {
		return false, nil
	}
}
Example #14
0
func printPacketInfo(packet gopacket.Packet) {
	applicationLayer := packet.ApplicationLayer()
	if applicationLayer != nil {
		buff := []byte(applicationLayer.Payload())
		p := rfc3164.NewParser(buff)
		err := p.Parse()
		if err != nil {
			fmt.Println("Error decoding Payload:", err)
		}
		fmt.Printf("%s", p.Dump()["content"])
	}

	if err := packet.ErrorLayer(); err != nil {
		fmt.Println("Error decoding some part of the packet:", err)
	}
}
Example #15
0
func (d *IPv6Defragmenter) DefragIPv6(in gopacket.Packet) (gopacket.Packet, error) {
	// check if we need to defrag
	frag := in.Layer(layers.LayerTypeIPv6Fragment)
	if frag == nil {
		return in, nil
	}
	v6frag := frag.(*layers.IPv6Fragment)
	// ok, got a fragment
	debug.Printf("defrag: got in.Id=%d in.FragOffset=%d",
		v6frag.Identification, v6frag.FragmentOffset*8)

	// do we already has seen a flow between src/dst with that Id
	ipf := newipv6(in)
	var fl *fragmentList
	var exist bool
	d.Lock()
	fl, exist = d.ipFlows[ipf]
	if !exist {
		debug.Printf("defrag: creating a new flow\n")
		fl = new(fragmentList)
		d.ipFlows[ipf] = fl
	}
	d.Unlock()
	// insert, and if final build it
	out, err2 := fl.insert(in)

	// at last, if we hit the maximum frag list len
	// without any defrag success, we just drop everything and
	// raise an error
	if out == nil && fl.List.Len()+1 > IPv6MaximumFragmentListLen {
		d.Lock()
		fl = new(fragmentList)
		d.ipFlows[ipf] = fl
		d.Unlock()
		return nil, fmt.Errorf("defrag: Fragment List hits its maximum"+
			"size(%d), without sucess. Flushing the list",
			IPv6MaximumFragmentListLen)
	}

	// if we got a packet, it's a new one, and he is defragmented
	if out != nil {
		return out, nil
	}
	return nil, err2
}
Example #16
0
// HandlePacket extract the krb5 AS-Requests
func (krb *krbAuth) HandlePacket(packet gopacket.Packet) {
	app := packet.ApplicationLayer()
	if app == nil {
		return
	}
	udp := packet.TransportLayer().(*layers.UDP)

	if udp.DstPort == 88 {
		var n kdcReq
		_, err := asn1.UnmarshalWithParams(app.Payload(), &n, asReqParam)
		if err != nil {
			return
		}
		if n.MsgType == asRequestType {
			krb.addKdcReq(n)
		}
	}
}
Example #17
0
File: ping.go Project: adoyee/probe
func onRecvPing(pkt gopacket.Packet, icmp *layers.ICMPv4, ci *gopacket.CaptureInfo) {
	payload := icmp.Payload
	if payload == nil || len(payload) <= 0 {
		return
	}
	sendStamp := binary.LittleEndian.Uint64(payload)
	if sendStamp < 1000000 {
		return
	}
	delay := ci.Timestamp.UnixNano() - int64(sendStamp)

	probeResult := &types.ProbeResult{}
	probeResult.Src = pkt.NetworkLayer().NetworkFlow().Dst().Raw()
	probeResult.Dest = pkt.NetworkLayer().NetworkFlow().Src().Raw()
	probeResult.Delay = int(delay / 1000)
	probeResult.Stamp = ci.Timestamp.Unix()
	probeResult.Type = types.ProbeTypePing
	db.InsertProbeResult(probeResult)
}
Example #18
0
func readARP(handle *pcap.Handle, iface *net.Interface, stop chan struct{}) {
	src := gopacket.NewPacketSource(handle, layers.LayerTypeEthernet)
	in := src.Packets()
	for {
		var packet gopacket.Packet
		select {
		case <-stop:
			return
		case packet = <-in:
			arpLayer := packet.Layer(layers.LayerTypeARP)
			if arpLayer == nil {
				continue
			}

			arp := arpLayer.(*layers.ARP)

			if !net.IP(arp.SourceProtAddress).Equal(net.ParseIP("0.0.0.0")) {
				continue
			}

			found := false

			for mac, fn := range DashMacs {
				if net.HardwareAddr(arp.SourceHwAddress).String() == mac {

					if !State[mac] {
						log.Printf("Click sniffed for %v", mac)
						State[mac] = true
						fn()
						State[mac] = false
					}

					found = true
				}
			}

			if !found {
				log.Printf("FOUND UNKNOWN MAC: %v", net.HardwareAddr(arp.SourceHwAddress))
			}
		}
	}
}
Example #19
0
func checkLayers(p gopacket.Packet, want []gopacket.LayerType, t *testing.T) {
	layers := p.Layers()
	t.Log("Checking packet layers, want", want)
	for _, l := range layers {
		t.Logf("  Got layer %v, %d bytes, payload of %d bytes", l.LayerType(),
			len(l.LayerContents()), len(l.LayerPayload()))
	}
	t.Log(p)
	if len(layers) != len(want) {
		t.Errorf("  Number of layers mismatch: got %d want %d", len(layers),
			len(want))
		return
	}
	for i, l := range layers {
		if l.LayerType() != want[i] {
			t.Errorf("  Layer %d mismatch: got %v want %v", i, l.LayerType(),
				want[i])
		}
	}
}
Example #20
0
func main() {
	flag.Usage = usage
	flag.Parse()

	pcapfile, err := openPcap()
	if err != nil {
		glog.Fatalf("%v", err)
	}

	bpf := strings.Join(flag.Args(), " ")
	if err = pcapfile.SetBPFFilter(bpf); err != nil {
		glog.Fatalf("unable to set BPF: %v", err)
	}

	// "Pass this stream factory to an tcpassembly.StreamPool ,
	// start up an tcpassembly.Assembler, and you're good to go!"

	done := make(chan struct{})
	results := make(chan string)
	go printResults(done, results)

	wg := &sync.WaitGroup{}
	rtmp := &rtmpStreamWrapper{wg, results}
	pool := tcpassembly.NewStreamPool(rtmp)
	asm := tcpassembly.NewAssembler(pool)
	asm.MaxBufferedPagesTotal = 4096 // limit gopacket memory allocation

	source := gopacket.NewPacketSource(pcapfile, pcapfile.LinkType())

	var pkt gopacket.Packet
	for {
		pkt, err = source.NextPacket()
		if pkt == nil || err != nil {
			break
		}

		if tcp := pkt.Layer(layers.LayerTypeTCP); tcp != nil {
			asm.AssembleWithTimestamp(
				pkt.TransportLayer().TransportFlow(),
				tcp.(*layers.TCP),
				pkt.Metadata().Timestamp)
		}
	}

	if err != nil && !errIsEOF(err) {
		glog.Errorf("packet: %v", err)
		if err = pcapfile.Error(); err != nil {
			glog.Errorf("pcap: %v", err)
		}
	}

	asm.FlushAll() // abort any in progress tcp connections
	wg.Wait()      // tcp streams have finished processing
	close(results) // no more results will be generated by tcp streams
	<-done         // printResults has finished
}
Example #21
0
//if it is the input stream to local machine
func inputStream(packet gopacket.Packet, Srcaddr *metrics.Address, Destaddr *metrics.Address) {
	//get the instance from the list which has the reverse srcaddr and the destaddr
	respdetail := string(packet.Data())
	if glog.V(1) {
		glog.Info("the length of the list before extract element:", httpinstancelist.Len())
	}

	for element := httpinstancelist.Front(); element != nil; element = element.Next() {
		httpinstance := element.Value.(*metrics.HttpTransaction)
		isreverse := ifreverse(httpinstance, Srcaddr, Destaddr)
		if isreverse {
			httpinstance.Timereceive = time.Now()
			//the units of time is ms
			responsetime := httpinstance.Timereceive.Sub(httpinstance.Timesend).Seconds() * 1000
			httpinstance.Respondtime = responsetime
			//store the respond detail
			glog.Info("respond info:", respdetail)
			httpinstance.Packetdetail.Responddetail = respdetail
			if glog.V(0) {
				glog.Infof("Respond duration:%vms", responsetime)
				glog.Infof("Get the response: %v", httpinstance)
				//glog.Info("detail:", httpinstance.Packetdetail)

			}
			httpinstancelist.Remove(element)
			//??how to use generic to realize the push function of different type
			//jsoninfo, _ := json.Marshal(httpinstance)
			//the type should be the ip of this machine
			//the first parameter is index the second one is type
			//err := ESClient.Push(jsoninfo, "packetagent", localip)
			//measurement := "respondtime"
			glog.Info("send the respondtime measurement")
			err := Influxstorage.AddStats("type_packet", "abcde", httpinstance)
			if err != nil {
				glog.Info("error to push")
			}
			break
		}
	}

}
Example #22
0
func getPacketInfo(packet gopacket.Packet) *PacketInfo {
	ipLayer := packet.Layer(layers.LayerTypeIPv4)
	var packetInfo PacketInfo

	if ipLayer != nil {
		ip, _ := ipLayer.(*layers.IPv4)

		//Set the ports
		if ip.Protocol == layers.IPProtocolTCP {
			protocol, _ := packet.Layer(layers.LayerTypeTCP).(*layers.TCP)
			packetInfo.srcIP = ip.SrcIP.String()
			packetInfo.dstIP = ip.DstIP.String()
			packetInfo.srcPort = strconv.Itoa(int(protocol.SrcPort))
			packetInfo.dstPort = strconv.Itoa(int(protocol.DstPort))
		} else if ip.Protocol == layers.IPProtocolUDP {
			protocol, _ := packet.Layer(layers.LayerTypeUDP).(*layers.UDP)
			packetInfo.srcIP = ip.SrcIP.String()
			packetInfo.dstIP = ip.DstIP.String()
			packetInfo.srcPort = strconv.Itoa(int(protocol.SrcPort))
			packetInfo.dstPort = strconv.Itoa(int(protocol.DstPort))
		}
	}

	return &packetInfo
}
Example #23
0
func handlePacket(packet gopacket.Packet) {

	// Get the TCP layer from this packet
	tcpLayer := packet.Layer(layers.LayerTypeTCP)

	if tcpLayer != nil {

		// Get actual TCP data from this layer
		tcp, _ := tcpLayer.(*layers.TCP)
		fmt.Printf("From: src port %6d\tTo: dst port %6d\t", tcp.SrcPort, tcp.DstPort)
		fmt.Printf("Ack: %12v\t", tcp.Ack)
	}

	// Iterate over all layers, printing out each layer type
	for _, layer := range packet.Layers() {
		layerType := layer.LayerType()
		fmt.Printf("%8v %5v", layerType, len(layer.LayerPayload()))
	}

	applicationLayer := packet.ApplicationLayer()
	if applicationLayer != nil {
		fmt.Println("Application layer/Payload found.")
		//fmt.Printf("%s\n", applicationLayer.Payload())
	}
	fmt.Println("")

}
Example #24
0
func (p *processor) decodeAppLayer(pkt gopacket.Packet) error {
	var moldUdp64Decoder gopacket.Decoder = nasdaq.LayerTypeMoldUDP64
	var ittoDecoder gopacket.Decoder = nasdaq.LayerTypeItto
	//log.Println("decodeAppLayer", pkt)
	transpLayer := pkt.TransportLayer()
	appLayer := pkt.ApplicationLayer()
	if transpLayer == nil || transpLayer.LayerType() != layers.LayerTypeUDP || appLayer == nil {
		return nil
	}

	packetBuilder := pkt.(gopacket.PacketBuilder)
	if packetBuilder == nil {
		panic("packet is not packetBuilder")
	}
	if appLayer.LayerType() != gopacket.LayerTypePayload {
		panic("appLayer is not LayerTypePayload")
	}
	data := appLayer.LayerContents()
	if err := moldUdp64Decoder.Decode(data, packetBuilder); err != nil {
		return err
	}
	for _, l := range pkt.Layers() {
		if mb, ok := l.(*nasdaq.MoldUDP64MessageBlockChained); ok {
			ittoDecoder.Decode(mb.Payload, packetBuilder)
		}
	}
	return nil
}
Example #25
0
//every time get a new packet
func processPacketInfo(packet gopacket.Packet) {
	//get the specified layer
	tcpLayer := packet.Layer(layers.LayerTypeTCP)
	if tcpLayer != nil {
		if glog.V(2) {
			glog.Info("TCP layer is detected.")
		}

		tcphandler, _ := tcpLayer.(*layers.TCP)
		srcport := tcphandler.SrcPort
		destport := tcphandler.DstPort
		//get the specified layer
		iplayer := packet.Layer(layers.LayerTypeIPv4)
		httphandler, _ := iplayer.(*layers.IPv4)
		srcip := httphandler.SrcIP
		destip := httphandler.DstIP
		//log.Println(srcip.String())
		//send the packet from local machine
		Srcaddr := &Address{IP: srcip.String(), PORT: srcport.String()}
		Destaddr := &Address{IP: destip.String(), PORT: destport.String()}
		if glog.V(2) {
			glog.Infof("srcaddr %v destaddr %v \n", Srcaddr, Destaddr)
		}
		var mutex = &sync.Mutex{}

		if srcip.String() == localip {
			mutex.Lock()
			outputStream(packet, Srcaddr, Destaddr)
			mutex.Unlock()
		}
		//get the packet from the local machine
		if destip.String() == localip {

			mutex.Lock()
			inputStream(packet, Srcaddr, Destaddr)
			mutex.Unlock()
		}

	}
}
Example #26
0
func SendPacket(packet gopacket.Packet,
	connectionWaitGroup *sync.WaitGroup,
	mongodHost string,
	mongodPort string) {
	// If packet contains a mongo message
	if packet.ApplicationLayer() != nil {
		payload := packet.ApplicationLayer().Payload()
		delta := GetPacketTime(packet).Sub(packetMinTimestamp)

		// Get timestamp's delta from first packet
		// Get mongo wire protocol payload
		mongoPacket := MongoPacket{
			payload: payload,
			delta:   delta,
		}

		transportLayer := packet.TransportLayer()
		networkLayer := packet.NetworkLayer()

		var srcIp string
		var srcPort string

		if networkLayer.LayerType() == layers.LayerTypeIPv4 {
			ip4header := networkLayer.LayerContents()
			// Convert binary to IP string
			srcIp = strconv.Itoa(int(ip4header[12])) + "." +
				strconv.Itoa(int(ip4header[13])) + "." +
				strconv.Itoa(int(ip4header[14])) + "." +
				strconv.Itoa(int(ip4header[15]))
		}
		if transportLayer.LayerType() == layers.LayerTypeTCP {
			tcpHeader := transportLayer.LayerContents()
			// Hack to be able to use convert what should be a uint16 to string
			tcpHeaderSrcPort := []byte{0, 0, tcpHeader[0], tcpHeader[1]}
			srcPort = strconv.Itoa(int(binary.BigEndian.Uint32(tcpHeaderSrcPort)))
		}

		src := srcIp + ":" + srcPort

		if mConnection, ok := mapHostConnection[src]; ok {
			mConnection.Send(mongoPacket)
		} else {
			connectionWaitGroup.Add(1)
			mConnection := NewMongoConnection(mongodHost, mongodPort, 100)
			mapHostConnection[src] = mConnection
			go mConnection.ExecuteConnection(connectionWaitGroup)
			mConnection.Send(mongoPacket)
		}
	}
}
Example #27
0
// HandlePacket assemble the correct challenge with the response
func (nt *ntlm) HandlePacket(packet gopacket.Packet) {
	app := packet.ApplicationLayer()
	if app == nil {
		return
	}
	nlen := len(app.Payload())
	values := strings.Split(string(app.Payload()[:nlen]), "\r\n")
	for _, s := range values {
		if isNtlm(s) {
			baseStrings := strings.Split(s, " ")
			if len(baseStrings) != 3 {
				return
			}
			tcp := packet.TransportLayer().(*layers.TCP)
			if isChallenge(s) {
				nt.addServerResponse(tcp.Ack, baseStrings[2])
			} else if isResponse(s) {
				nt.addClientResponse(tcp.Seq, baseStrings[2])
			}
		}
	}
}
Example #28
0
// IsUdpPacket returns true if the packet is of UDP type
func IsUdpPacket(packet gopacket.Packet) bool {
	if packet == nil {
		return false
	}
	if packet.NetworkLayer() == nil || packet.TransportLayer() == nil || packet.TransportLayer().LayerType() != layers.LayerTypeUDP {
		return false
	}
	return true
}
Example #29
0
// Extract the ftp login reposnses and requests
func (ftp *ftpLogin) HandlePacket(packet gopacket.Packet) {
	app := packet.ApplicationLayer()
	if app == nil {
		return
	}
	n := len(app.Payload())
	values := strings.Split(string(app.Payload()[:n]), "\r\n")
	for _, s := range values {
		if isFtp(s) {
			tcp := packet.TransportLayer().(*layers.TCP)
			if isUser(s) {
				ftp.user(tcp.Ack, strings.Split(s, " ")[1])
				ftp.destination(tcp.Ack, destAndPort{
					Destination: util.GetDstIP(packet),
					Port:        tcp.DstPort,
				})
			} else if isServer(s) {
				ftp.server(tcp.Seq, tcp.Ack)
			} else if isPass(s) {
				ftp.pass(tcp.Seq, strings.Split(s, " ")[1])
			}
		}
	}
}
Example #30
0
func handlePacket(packet gopacket.Packet) {
	var eth layers.Ethernet
	var ip4 layers.IPv4
	var udp layers.UDP
	var payload gopacket.Payload
	parser := gopacket.NewDecodingLayerParser(layers.LayerTypeEthernet, &eth, &ip4, &udp, &payload)
	decoded := []gopacket.LayerType{}

	err := parser.DecodeLayers(packet.Data(), &decoded)
	if err != nil {
		log.Printf("Decoding error:%v\n", err)
	}
	for _, layerType := range decoded {
		switch layerType {
		case layers.LayerTypeEthernet:
			fmt.Println("    Eth ", eth.SrcMAC, eth.DstMAC)
		case layers.LayerTypeIPv4:
			fmt.Println("    IP4 ", ip4.SrcIP, ip4.DstIP)
		case layers.LayerTypeUDP:
			fmt.Println("    UDP ", udp.SrcPort, udp.DstPort, payload.GoString())
		}

	}
}