Esempio n. 1
0
func tryCapture(iface net.Interface) error {
	if iface.Name[:2] == "lo" {
		return fmt.Errorf("skipping loopback")
	}
	var h *pcap.Handle
	var err error
	switch *mode {
	case "basic":
		h, err = pcap.OpenLive(iface.Name, 65536, false, time.Second*3)
		if err != nil {
			return fmt.Errorf("openlive: %v", err)
		}
		defer h.Close()
	case "filtered":
		h, err = pcap.OpenLive(iface.Name, 65536, false, time.Second*3)
		if err != nil {
			return fmt.Errorf("openlive: %v", err)
		}
		defer h.Close()
		if err := h.SetBPFFilter("port 80 or port 443"); err != nil {
			return fmt.Errorf("setbpf: %v", err)
		}
	case "timestamp":
		u, err := pcap.NewInactiveHandle(iface.Name)
		if err != nil {
			return err
		}
		defer u.CleanUp()
		if err = u.SetSnapLen(65536); err != nil {
			return err
		} else if err = u.SetPromisc(false); err != nil {
			return err
		} else if err = u.SetTimeout(time.Second * 3); err != nil {
			return err
		}
		sources := u.SupportedTimestamps()
		if len(sources) == 0 {
			return fmt.Errorf("no supported timestamp sources")
		} else if err := u.SetTimestampSource(sources[0]); err != nil {
			return fmt.Errorf("settimestampsource(%v): %v", sources[0], err)
		} else if h, err = u.Activate(); err != nil {
			return fmt.Errorf("could not activate: %v", err)
		}
		defer h.Close()
	default:
		panic("Invalid --mode: " + *mode)
	}
	go generatePackets()
	h.ReadPacketData() // Do one dummy read to clear any timeouts.
	data, ci, err := h.ReadPacketData()
	if err != nil {
		return fmt.Errorf("readpacketdata: %v", err)
	}
	log.Printf("Read packet, %v bytes, CI: %+v", len(data), ci)
	return nil
}
Esempio n. 2
0
/*
   FUNCTION: intiateHandles(iface string)
   RETURNS: Nothing
   ARGUMENTS:
               string iface - the interface to monitor

   ABOUT:
   Intiates all packet capture handles for the client. One for the main system and one for the file thread.
*/
func intiateHandles(iface string) {

	handle, err = pcap.OpenLive(iface, 1600, true, pcap.BlockForever)
	checkError(err)

	err = handle.SetBPFFilter("udp")
	checkError(err)

	fhandle, err = pcap.OpenLive(iface, 1600, true, pcap.BlockForever)
	checkError(err)

	err = fhandle.SetBPFFilter("udp")
	checkError(err)
}
Esempio n. 3
0
func main() {
	getLocalAddresses()
	log.Print(getFilterString())

	//if handle, err := pcap.OpenOffline("attack3.pcap"); err != nil {
	if handle, err := pcap.OpenLive("any", 512, false, pcap.BlockForever); err != nil {
		panic(err)
	} else if err := handle.SetBPFFilter(getFilterString()); err != nil {
		panic(err)
	} else {
		//var offset time.Duration

		packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
		for packet := range packetSource.Packets() {

			/*
				// delay to simulate actual time span
				if offset == 0 {
					offset = time.Now().Sub(packet.Metadata().Timestamp)
				}

				sleep := packet.Metadata().Timestamp.Add(offset).Sub(time.Now())
				time.Sleep(sleep)
			*/

			handlePacket(packet)
		}
	}
}
Esempio n. 4
0
func getOpstream(cfg OpStreamSettings) (*packetHandlerContext, error) {
	if cfg.PacketBufSize < 1 {
		return nil, fmt.Errorf("invalid packet buffer size")
	}

	var pcapHandle *pcap.Handle
	var err error
	if len(cfg.PcapFile) > 0 {
		pcapHandle, err = pcap.OpenOffline(cfg.PcapFile)
		if err != nil {
			return nil, fmt.Errorf("error opening pcap file: %v", err)
		}
	} else if len(cfg.NetworkInterface) > 0 {
		pcapHandle, err = pcap.OpenLive(cfg.NetworkInterface, 32*1024*1024, false, pcap.BlockForever)
		if err != nil {
			return nil, fmt.Errorf("error listening to network interface: %v", err)
		}
	} else {
		return nil, fmt.Errorf("must specify either a pcap file or network interface to record from")
	}

	if len(cfg.Expression) > 0 {
		err = pcapHandle.SetBPFFilter(cfg.Expression)
		if err != nil {
			return nil, fmt.Errorf("error setting packet filter expression: %v", err)
		}
	}

	h := NewPacketHandler(pcapHandle)
	h.Verbose = userInfoLogger.isInVerbosity(DebugLow)

	toolDebugLogger.Logvf(Info, "Created packet buffer size %d", cfg.PacketBufSize)
	m := NewMongoOpStream(cfg.PacketBufSize)
	return &packetHandlerContext{h, m, pcapHandle}, nil
}
Esempio n. 5
0
func (s *PcapSniffer) Open(config *Config) error {
	// Capture settings
	const (
		// Max packet length
		snaplen int32 = 65536
		// Set the interface in promiscuous mode
		promisc bool = true
		// Timeout duration
		flushAfter string = "10s"
		//BPF filter when capturing packets
		filter string = "ip"
	)

	// Open the interface
	flushDuration, err := time.ParseDuration(flushAfter)
	if err != nil {
		return fmt.Errorf("Invalid flush duration: %s", flushAfter)
	}
	handle, err := pcap.OpenLive(*iface, snaplen, promisc, flushDuration/2)
	if err != nil {
		return fmt.Errorf("Error opening pcap handle: %s", err)
	}
	if err := handle.SetBPFFilter(filter); err != nil {
		return fmt.Errorf("Error setting BPF filter: %s", err)
	}
	s.handle = handle

	return nil
}
Esempio n. 6
0
func main() {
	flag.Parse()
	var handle *pcap.Handle
	var err error
	if *fname != "" {
		log.Printf("Reading from pcap dump %q", *fname)
		handle, err = pcap.OpenOffline(*fname)
	} else {
		log.Printf("Starting capture on interface %q", *iface)
		handle, err = pcap.OpenLive(*iface, int32(*snaplen), true, pcap.BlockForever)
	}
	if err != nil {
		log.Fatal(err)
	}

	if err := handle.SetBPFFilter(*filter); err != nil {
		log.Fatal(err)
	}

	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
	for packet := range packetSource.Packets() {
		if packet == nil {
			return
		}
		if udpLayer := packet.Layer(layers.LayerTypeUDP); udpLayer != nil {
			udp, _ := udpLayer.(*layers.UDP)
			fwdSIPPacket(udp.BaseLayer.Payload)
		}
	}
}
Esempio n. 7
0
func packetSource() *gopacket.PacketSource {
	if *inputPcap != "" {
		handle, err := pcap.OpenOffline(*inputPcap)
		if err != nil {
			log.Fatalln(err)
		}
		fmt.Printf("open pcap file \"%s\"\n", *inputPcap)
		return gopacket.NewPacketSource(handle, handle.LinkType())
	}

	if *device == "" {
		*device = autoSelectDev()
		if *device == "" {
			log.Fatalln("no device to capture")
		}
	}

	handle, err := pcap.OpenLive(*device, 1024*1024, true, pcap.BlockForever)
	if err != nil {
		log.Fatalln(err)
	}
	if *bpf != "" {
		if err = handle.SetBPFFilter(*bpf); err != nil {
			log.Fatalln("Failed to set BPF filter:", err)
		}
	}
	fmt.Printf("open live on device \"%s\", bpf \"%s\", serves on port %d\n", *device, *bpf, *bindingPort)
	return gopacket.NewPacketSource(handle, handle.LinkType())
}
Esempio n. 8
0
func openDevice(device string) *pcap.Handle {
	handle, err := pcap.OpenLive(device, 65536, false, pcap.BlockForever)
	if err != nil {
		log.Fatal("Open device", device, "error:", err)
	}
	return handle
}
Esempio n. 9
0
func main() {
	// Open device
	handle, err = pcap.OpenLive(device, snapshot_len, promiscuous, timeout)
	if err != nil {
		log.Fatal(err)
	}
	defer handle.Close()

	bpfInstructions := []pcap.BPFInstruction{
		{0x20, 0, 0, 0xfffff038}, // ld rand
		{0x54, 0, 0, 0x00000004},
		{0x15, 0, 1, 0x00000004},
		{0x06, 0, 0, 0x0000ffff},
		{0x06, 0, 0, 0000000000},
	}

	err = handle.SetBPFInstructionFilter(bpfInstructions)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Capturing ~4th packet (randomly).")

	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
	for packet := range packetSource.Packets() {
		// Do something with a packet here.
		fmt.Println(packet)
	}

}
Esempio n. 10
0
File: scanner.go Progetto: ev46/DNA
//----- PCAP read from
func Read_RAW_Socket_Data() {
	fmt.Println("|---------------------------------------------------------------|")
	fmt.Println("|  [scanner] Opening Device (PROMISCUOUS_MODE): " + networkDeviceName + "\t\t|")

	// Open device
	handle, err = pcap.OpenLive(networkDeviceName, snapshot_len, promiscuous, timeout)
	if err != nil {
		fmt.Println("| ----------------=============================-----------------|")
		fmt.Println("| Looks like there is an error getting live network stream. Try |")
		fmt.Println("| running it again with 'sudo' command                          |")
		fmt.Println("| ----------------=============================-----------------|")
		log.Fatal(err)
	}
	defer handle.Close()

	// Set filter
	var filter string = "tcp"
	err = handle.SetBPFFilter(filter)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Only capturing TCP port 80 packets.")

	// Use the handle as a packet source to process all packets
	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
	for packet := range packetSource.Packets() {
		process_gopacket(packet)
	}
}
Esempio n. 11
0
func Startcollect(port int, device string, timesignal <-chan time.Time) {
	handle, err = pcap.OpenLive(device, snapshotLen, promiscuous, timeout)
	if err != nil {
		glog.Info(err.Error())
	}

	defer handle.Close()
	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
	templocalip, err := checkLocalip(device)
	localip = templocalip
	if glog.V(0) {
		glog.Info(localip)
	}
	httpinstancelist = list.New()
	if err != nil {
		glog.Info(err.Error())
	}
A:
	for packet := range packetSource.Packets() {
		select {
		case <-timesignal:
			break A
		default:
			processPacketInfo(packet)

		}

	}
}
Esempio n. 12
0
//init re-initializes a snifer for uses
func (s *Snifer) init() error {
	var handle *pcap.Handle
	var err error

	if s.conf.Offline {
		handle, err = pcap.OpenOffline(s.source)
		checkError(err, fmt.Sprintf("Create offline handle %s", s.source))
	} else {
		handle, err = pcap.OpenLive(s.source, s.conf.MaxPacket, s.conf.Promod, s.conf.Timeout)
		checkError(err, fmt.Sprintf("Create Live handle %s", s.source))

		if err == nil {
			err = handle.SetBPFFilter(s.conf.Filter)
			checkError(err, fmt.Sprintf("Setting BPFFilter %s: %s", s.source, s.conf.Filter))
		}

	}

	if err != nil {
		checkError(err, fmt.Sprintf("Creating Snifer for %s", s.source))
		return err
	}

	s.handle = handle
	log.Printf("Snifer: Handler created and ready!")

	return nil
}
Esempio n. 13
0
/*
    FUNCTION: main()
    RETURNS: Nothing
    ARGUMENTS: None
    ABOUT:
    Grabs incoming arguments and activates the ARP poisoning thread and the DNS spoofing functionality.
		Also grabs host addresses for use later on and sets global variables.
*/
func main() {

	targetPtr := flag.String("targ", "127.0.0.1", "The address of the host for spoofing.")
	targetMAC := flag.String("targm", "FF:FF:FF:FF:FF:FF", "The target mac address.")
	interfacePtr := flag.String("iface", "eth0", "The interface for the backdoor to monitor for incoming connection, defaults to eth0.")
	gatewayPtr := flag.String("gw", "127.0.0.1", "Sets the gateway to poison.")
	gatewayMAC := flag.String("gwm", "FF:FF:FF:FF:FF:FF", "Sets the gateway MAC address.")

	flag.Parse()

	fmt.Print("Welcome to the DNSMangler!\n")
	handle, err = pcap.OpenLive(*interfacePtr, 1600, false, pcap.BlockForever)
	checkError(err)

	err = handle.SetBPFFilter("dst port 53")
	checkError(err)

	defer handle.Close()

	macAddr, ipAddr = grabAddresses(*interfacePtr)
	target = *targetPtr

	go arpPoison(*targetMAC, *gatewayPtr, *gatewayMAC)
	mangleDNS()
}
Esempio n. 14
0
func main() {
	// Open output pcap file and write header
	dumpFile, _ := os.Create(dumpFilename)
	packetWriter := pcapgo.NewWriter(dumpFile)
	packetWriter.WriteFileHeader(65535, layers.LinkTypeEthernet)
	defer dumpFile.Close()

	// Open device for capturing
	handle, err = pcap.OpenLive(deviceName, snapshotLen, promiscuous, timeout)
	if err != nil {
		log.Fatal("Error opening device %s: %v", deviceName, err)
	}
	defer handle.Close()
	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())

	// Start processing packets
	for packet := range packetSource.Packets() {
		fmt.Println(packet)
		packetWriter.WritePacket(packet.Metadata().CaptureInfo, packet.Data())
		packetCount++

		// Only capture 100 packets
		if packetCount > 100 {
			break
		}
	}
}
Esempio n. 15
0
// newScanner creates a new scanner for a given destination IP address, using
// router to determine how to route packets to that IP.
func newScanner(ip net.IP, router routing.Router) (*scanner, error) {
	s := &scanner{
		dst: ip,
		opts: gopacket.SerializeOptions{
			FixLengths:       true,
			ComputeChecksums: true,
		},
		buf: gopacket.NewSerializeBuffer(),
	}
	// Figure out the route to the IP.
	iface, gw, src, err := router.Route(ip)
	if err != nil {
		return nil, err
	}
	log.Printf("scanning ip %v with interface %v, gateway %v, src %v", ip, iface.Name, gw, src)
	s.gw, s.src, s.iface = gw, src, iface

	// Open the handle for reading/writing.
	// Note we could very easily add some BPF filtering here to greatly
	// decrease the number of packets we have to look at when getting back
	// scan results.
	handle, err := pcap.OpenLive(iface.Name, 65536, true, pcap.BlockForever)
	if err != nil {
		return nil, err
	}
	s.handle = handle
	return s, nil
}
Esempio n. 16
0
func VerifyPacket(ovsDriver *ovsdbDriver.OvsDriver, dstPort string, pkt *Packet, ch chan bool, timeout int, numPkts int) {
	verifiedCountTotal := 0
	handle, err := pcap.OpenLive(dstPort, 1024, true, pcap.BlockForever)

	if err != nil {
		fmt.Println("Error capturing packet")
		ch <- false
	}

	if handle == nil {
		ch <- false
	}
	defer handle.Close()
	// Start up a goroutine to read in packet data.
	//	stop := make(chan struct{}, 1)
	//defer close(stop)
	done := make(chan int)

	fmt.Println("Calling Go routine Read packet", numPkts)
	go readPacket(handle, pkt, dstPort, done)
	verifiedCountTotal = <-done
	fmt.Println(verifiedCountTotal)
	ch <- (verifiedCountTotal == numPkts)
	close(done)
	return
}
Esempio n. 17
0
func NewPcapWireSniffer(netDevice string, snaplen int32, wireDuration time.Duration, filter string) (*PcapHandle, error) {
	pcapWireHandle, err := pcap.OpenLive(netDevice, snaplen, true, wireDuration)
	pcapHandle := PcapHandle{
		handle: pcapWireHandle,
	}
	err = pcapHandle.handle.SetBPFFilter(filter)
	return &pcapHandle, err
}
Esempio n. 18
0
func setupPcap(device *string, port *string, rediscommand_ch chan<- redis_protocol.RedisCommand) {
	var h *pcap.Handle
	var err error

	ifs, err_str := pcap.FindAllDevs()
	if len(ifs) == 0 {
		fmt.Printf("Warning: no devices found : %s\n", err_str)
	}

	h, err = pcap.OpenLive(*device, int32(65535), true, 1000)
	if h == nil {
		fmt.Printf("Openlive(%s) failed: %s\n", *device, err)
		return
	}
	defer h.Close()

	err = h.SetBPFFilter("dst port " + *port)
	if err != nil {
		fmt.Println("set filter failed")
		return
	}

	packetSource := gopacket.NewPacketSource(h, h.LinkType())
	for pkt := range packetSource.Packets() {
		applicationLayer := pkt.ApplicationLayer()

		if applicationLayer == nil {
			continue
		}

		s := string(applicationLayer.Payload())

		if s == "" {
			continue
		}

		rediscommand, err := redis_protocol.Parse(s)
		if err != nil {
			fmt.Println(err)
			continue
		}

		ipLayer := pkt.Layer(layers.LayerTypeIPv4)
		if ipLayer != nil {
			ip, _ := ipLayer.(*layers.IPv4)
			rediscommand.Ipaddr = []byte(ip.SrcIP.String())
		} else {
			ipLayer := pkt.Layer(layers.LayerTypeIPv6)
			if ipLayer != nil {
				ip, _ := ipLayer.(*layers.IPv6)
				rediscommand.Ipaddr = []byte(ip.SrcIP.String())
			}
		}
		rediscommand_ch <- *rediscommand
	}
}
Esempio n. 19
0
func main() {
	// Open device
	handle, _ = pcap.OpenLive(device, snapshot_len, promiscuous, timeout)
	if err != nil {
		log.Fatal(err)
	}
	defer handle.Close()

	fmt.Println(handle)
}
Esempio n. 20
0
func main() {
	// Open device
	handle, err = pcap.OpenLive(device, snapshot_len, promiscuous, timeout)
	if err != nil {
		log.Fatal(err)
	}
	defer handle.Close()

	// Send raw bytes over wire
	rawBytes := []byte{10, 20, 30}
	err = handle.WritePacketData(rawBytes)
	if err != nil {
		log.Fatal(err)
	}

	// Create a properly formed packet, just with
	// empty details. Should fill out MAC addresses,
	// IP addresses, etc.
	buffer = gopacket.NewSerializeBuffer()
	gopacket.SerializeLayers(buffer, options,
		&layers.Ethernet{},
		&layers.IPv4{},
		&layers.TCP{},
		gopacket.Payload(rawBytes),
	)
	outgoingPacket := buffer.Bytes()
	// Send our packet
	err = handle.WritePacketData(outgoingPacket)
	if err != nil {
		log.Fatal(err)
	}

	// This time lets fill out some information
	ipLayer := &layers.IPv4{
		SrcIP: net.IP{127, 0, 0, 1},
		DstIP: net.IP{8, 8, 8, 8},
	}
	ethernetLayer := &layers.Ethernet{
		SrcMAC: net.HardwareAddr{0xFF, 0xAA, 0xFA, 0xAA, 0xFF, 0xAA, 0xFA, 0xAA},
		DstMAC: net.HardwareAddr{0xBD, 0xBD, 0xBD, 0xBD, 0xBD, 0xBD, 0xBD, 0xBD},
	}
	tcpLayer := &layers.TCP{
		SrcPort: layers.TCPPort(4321),
		DstPort: layers.TCPPort(80),
	}
	// And create the packet with the layers
	buffer = gopacket.NewSerializeBuffer()
	gopacket.SerializeLayers(buffer, options,
		ethernetLayer,
		ipLayer,
		tcpLayer,
		gopacket.Payload(rawBytes),
	)
	outgoingPacket = buffer.Bytes()
}
Esempio n. 21
0
func decodePackets(iface string, producer sarama.AsyncProducer) {

	// Try to open live packet capture
	h, err := pcap.OpenLive(iface,
		spanlen,
		true, pcap.BlockForever)
	if err != nil {
		log.Printf("Couldn't start live packet capture on %s interface", iface)
	}

	ps := gopacket.NewPacketSource(h, h.LinkType())
	packets := ps.Packets()

	// Read packets from the channel
	for {
		select {

		case packet := <-packets:
			if packet.TransportLayer() != nil && packet.NetworkLayer() != nil {
				pckt := Packt{}
				// Figure out the application layer protocol
				// from the destination port
				var dstPort, srcPort uint16
				if packet.TransportLayer().LayerType() == layers.LayerTypeTCP {
					tcp := packet.TransportLayer().(*layers.TCP)
					dstPort = uint16(tcp.DstPort)
					srcPort = uint16(tcp.SrcPort)
					pckt.Protocol = ianaPort(packet.TransportLayer().LayerType(), dstPort)
				} else if packet.TransportLayer().LayerType() == layers.LayerTypeUDP {
					udp := packet.TransportLayer().(*layers.UDP)
					dstPort = uint16(udp.DstPort)
					srcPort = uint16(udp.SrcPort)
					pckt.Protocol = ianaPort(packet.TransportLayer().LayerType(), dstPort)
				}

				pckt.DstPort = dstPort
				pckt.SrcPort = srcPort

				// Extract the protocol, the source and the destination IP
				// addresses
				if packet.NetworkLayer().LayerType() == layers.LayerTypeIPv4 {
					ipv4 := packet.NetworkLayer().(*layers.IPv4)
					pckt.SrcIP = ipv4.SrcIP.String()
					pckt.DstIP = ipv4.DstIP.String()
				} else {
					pckt.Protocol = "N/A (IPv6)"
				}

				// Emit the packet data to Kafka
				emitPacket(pckt, producer)
			}
		}
	}
}
Esempio n. 22
0
func main() {
	defer util.Run()()
	var handle *pcap.Handle
	var err error

	// Set up pcap packet capture
	if *fname != "" {
		log.Printf("Reading from pcap dump %q", *fname)
		handle, err = pcap.OpenOffline(*fname)
	} else {
		log.Printf("Starting capture on interface %q", *iface)
		handle, err = pcap.OpenLive(*iface, int32(*snaplen), true, pcap.BlockForever)
	}
	if err != nil {
		log.Fatal(err)
	}

	if err := handle.SetBPFFilter(*filter); err != nil {
		log.Fatal(err)
	}

	// Set up assembly
	streamFactory := &httpStreamFactory{}
	streamPool := tcpassembly.NewStreamPool(streamFactory)
	assembler := tcpassembly.NewAssembler(streamPool)

	log.Println("reading in packets")
	// Read in packets, pass to assembler.
	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
	packets := packetSource.Packets()
	ticker := time.Tick(time.Minute)
	for {
		select {
		case packet := <-packets:
			// A nil packet indicates the end of a pcap file.
			if packet == nil {
				return
			}
			if *logAllPackets {
				log.Println(packet)
			}
			if packet.NetworkLayer() == nil || packet.TransportLayer() == nil || packet.TransportLayer().LayerType() != layers.LayerTypeTCP {
				log.Println("Unusable packet")
				continue
			}
			tcp := packet.TransportLayer().(*layers.TCP)
			assembler.AssembleWithTimestamp(packet.NetworkLayer().NetworkFlow(), tcp, packet.Metadata().Timestamp)

		case <-ticker:
			// Every minute, flush connections that haven't seen activity in the past 2 minutes.
			assembler.FlushOlderThan(time.Now().Add(time.Minute * -2))
		}
	}
}
Esempio n. 23
0
// Setup creates a new handle for the given interface.
// The handle is configured to capture only IEEE 802.11 probe request packets.
func Setup(iface string) (*pcap.Handle, error) {
	handle, err := pcap.OpenLive(iface, 1600, true, 0)
	if err != nil {
		return handle, err
	}
	// only capture probe request packets
	err = handle.SetBPFFilter("type mgt subtype probe-req")
	if err != nil {
		return handle, err
	}
	return handle, nil
}
Esempio n. 24
0
// Sniffs packets over the device.
func Sniff(device string, snaplen int32, promisc bool, filter string) (<-chan gopacket.Packet, error) {
	handle, err := pcap.OpenLive(device, snaplen, promisc, pcap.BlockForever)
	if err != nil {
		return nil, err
	}
	err = handle.SetBPFFilter(filter)
	if err != nil {
		return nil, err
	}
	source := gopacket.NewPacketSource(handle, handle.LinkType())
	return source.Packets(), nil
}
Esempio n. 25
0
File: pcap.go Progetto: adoyee/probe
func openAllInterface(ifaces []net.Interface) (err error) {
	for _, iface := range ifaces {
		log.Println("Open interface", iface.Name)
		handle, err := pcap.OpenLive(iface.Name, 128, false, pcap.BlockForever)
		if err != nil {
			return err
		}
		en0 = handle
		go doReadPacket(handle)
	}

	return
}
Esempio n. 26
0
func sniff() {

	if handle, err := pcap.OpenLive("eth0", 1600, true, pcap.BlockForever); err != nil {
		panic(err)
	} else if err := handle.SetBPFFilter("udp and (port 68 or port 67)"); err != nil { // optional
		panic(err)
	} else {
		packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
		for packet := range packetSource.Packets() {
			handlePacket(packet) // Do something with a packet here.
		}
	}
}
Esempio n. 27
0
func main() {
	// Open device
	handle, _ = pcap.OpenLive(device, snapshotLen, promiscuous, timeout)
	if err != nil {
		log.Fatal(err)
	}
	defer handle.Close()

	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
	for packet := range packetSource.Packets() {
		printPacketInfo(packet)
	}
}
Esempio n. 28
0
func scan(iface *net.Interface, interval time.Duration, queue NodeQueue) error {
	//look for IPv4 address on the interface
	var addr *net.IPNet

	addrs, err := iface.Addrs()
	if err != nil {
		return fmt.Errorf("could not get addresses: %s", err)
	}

	for _, a := range addrs {
		if ipnet, ok := a.(*net.IPNet); ok {
			if ip4 := ipnet.IP.To4(); ip4 != nil {
				addr = &net.IPNet{
					IP:   ip4,
					Mask: ipnet.Mask[len(ipnet.Mask)-4:],
				}
				break
			}
		}
	}

	// Sanity-check that the interface has a good address.
	if addr == nil {
		return fmt.Errorf("no good IP network found")
	} else if addr.IP[0] == 127 {
		return fmt.Errorf("skipping localhost")
	} else if addr.Mask[0] != 0xff || addr.Mask[1] != 0xff {
		return fmt.Errorf("mask means network is too large")
	}

	log.Printf("Using network range %v for interface %v", addr, iface.Name)

	// Open up a pcap handle for packet reads/writes.
	handle, err := pcap.OpenLive(iface.Name, 65536, true, pcap.BlockForever)
	if err != nil {
		return err
	}
	defer handle.Close()

	// Start up a goroutine to read in packet data.
	stop := make(chan bool)
	go readARP(handle, iface, stop, queue)
	defer close(stop)
	for {
		// Write our scan packets out to the handle.
		if err := writeARP(handle, iface, addr); err != nil {
			return fmt.Errorf("writing packets: %v", err)
		}
		time.Sleep(interval)
	}
}
Esempio n. 29
0
// scan scans an individual interface's local network for machines using ARP requests/replies.
//
// scan loops forever, sending packets out regularly.  It returns an error if
// it's ever unable to write a packet.
func scan(iface *net.Interface) error {
	// We just look for IPv4 addresses, so try to find if the interface has one.
	var addr *net.IPNet
	if addrs, err := iface.Addrs(); err != nil {
		return err
	} else {
		for _, a := range addrs {
			if ipnet, ok := a.(*net.IPNet); ok {
				if ip4 := ipnet.IP.To4(); ip4 != nil {
					addr = &net.IPNet{
						IP:   ip4,
						Mask: ipnet.Mask[len(ipnet.Mask)-4:],
					}
					break
				}
			}
		}
	}
	// Sanity-check that the interface has a good address.
	if addr == nil {
		return fmt.Errorf("no good IP network found")
	} else if addr.IP[0] == 127 {
		return fmt.Errorf("skipping localhost")
	} else if addr.Mask[0] != 0xff || addr.Mask[1] != 0xff {
		return fmt.Errorf("mask means network is too large")
	}
	log.Printf("Using network range %v for interface %v", addr, iface.Name)

	// Open up a pcap handle for packet reads/writes.
	handle, err := pcap.OpenLive(iface.Name, 65536, true, pcap.BlockForever)
	if err != nil {
		return err
	}
	defer handle.Close()

	// Start up a goroutine to read in packet data.
	stop := make(chan struct{})
	go readARP(handle, iface, stop)
	defer close(stop)
	for {
		// Write our scan packets out to the handle.
		if err := writeARP(handle, iface, addr); err != nil {
			log.Printf("error writing packets on %v: %v", iface.Name, err)
			return err
		}
		// We don't know exactly how long it'll take for packets to be
		// sent back to us, but 10 seconds should be more than enough
		// time ;)
		time.Sleep(10 * time.Second)
	}
}
Esempio n. 30
0
func (t *Listener) readRAWSocket() {

	var d syscall.WSAData
	err := syscall.WSAStartup(uint32(0x202), &d)
	if err != nil {
		log.Fatalln("Error:WSAStartup", err)
	}
	fd, err := sysSocket(syscall.AF_INET, syscall.SOCK_RAW, syscall.IPPROTO_IP)
	if err != nil {
		log.Fatalln("Error:socket", err)
	}
	defer syscall.Close(fd)

	ip := net.ParseIP(t.addr)
	if len(t.addr) == 0 || t.addr == "0.0.0.0" {
		ip = net.IPv4zero
	}
	if ip = ip.To4(); ip == nil {
		log.Fatalln("Error: non-IPv4 address " + t.addr)
	}
	la := new(syscall.SockaddrInet4)
	for i := 0; i < net.IPv4len; i++ {
		la.Addr[i] = ip[i]
	}
	if err := syscall.Bind(fd, la); err != nil {
		log.Fatalln("Error:Bind", err)
	}

	var snapshotLen int32 = 1024
	var promiscuous bool = false
	var timeout time.Duration = 30 * time.Second

	inet := getInterfaceName()
	handle, err := pcap.OpenLive(inet, snapshotLen, promiscuous, timeout)
	if err != nil {
		log.Fatal(err)
	}
	defer handle.Close()

	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
	for packet := range packetSource.Packets() {
		if tcpLayer := packet.Layer(layers.LayerTypeTCP); tcpLayer != nil {
			tcp, _ := tcpLayer.(*layers.TCP)

			src_ip := packet.NetworkLayer().NetworkFlow().Src().String()
			dest_ip := packet.NetworkLayer().NetworkFlow().Dst().String()

			t.parsePacket(src_ip, dest_ip, tcp)
		}
	}
}