// writeARP writes an ARP request for each address on our local network to the // pcap handle. func writeARP(handle *pcap.Handle, iface *net.Interface, addr *net.IPNet) error { // Set up all the layers' fields we can. eth := layers.Ethernet{ SrcMAC: iface.HardwareAddr, DstMAC: net.HardwareAddr{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, EthernetType: layers.EthernetTypeARP, } arp := layers.ARP{ AddrType: layers.LinkTypeEthernet, Protocol: layers.EthernetTypeIPv4, HwAddressSize: 6, ProtAddressSize: 4, Operation: layers.ARPRequest, SourceHwAddress: []byte(iface.HardwareAddr), SourceProtAddress: []byte(addr.IP), DstHwAddress: []byte{0, 0, 0, 0, 0, 0}, } // Set up buffer and options for serialization. buf := gopacket.NewSerializeBuffer() opts := gopacket.SerializeOptions{ FixLengths: true, ComputeChecksums: true, } // Send one packet for every address. for ip := range ips(addr) { arp.DstProtAddress = []byte(ip) gopacket.SerializeLayers(buf, opts, ð, &arp) if err := handle.WritePacketData(buf.Bytes()); err != nil { return err } } return nil }
func main() { flag.Parse() var handle *pcap.Handle var err error if *fname != "" { if handle, err = pcap.OpenOffline(*fname); err != nil { log.Fatalln("PCAP OpenOffline error:", err) } } else { if handle, err = pcap.OpenLive(*iface, int32(*snaplen), true, time.Second); err != nil { log.Fatalln("PCAP OpenLive error:", err) } if *tstype != "" { if t, err := pcap.TimestampSourceFromString(*tstype); err != nil { log.Fatalf("Supported timestamp types: %v", handle.SupportedTimestamps()) } else if err := handle.SetTimestampSource(t); err != nil { log.Fatalf("Supported timestamp types: %v", handle.SupportedTimestamps()) } } if len(flag.Args()) > 0 { bpffilter := strings.Join(flag.Args(), " ") fmt.Fprintf(os.Stderr, "Using BPF filter %q\n", bpffilter) if err = handle.SetBPFFilter(bpffilter); err != nil { log.Fatalln("BPF filter error:", err) } } } dumpcommand.Run(handle) }
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)) } } }
func nextPkt(h *pcap.Handle) (p Packet) { for { pbuf, _, err := h.ReadPacketData() if err != nil { panic(err) } var ok bool if p, ok = NewPkt(pbuf); ok { return } } return }
func (tap *Wiretap) capture(handle *pcap.Handle, channel chan gopacket.Packet) { defer handle.Close() src := gopacket.NewPacketSource(handle, handle.LinkType()) src.DecodeOptions = gopacket.NoCopy for { packet, err := src.NextPacket() if err == io.EOF { return } else if err == nil { channel <- packet } } }
func main() { flag.Parse() var handle *pcap.Handle var err error if *fname != "" { if handle, err = pcap.OpenOffline(*fname); err != nil { log.Fatalln("PCAP OpenOffline error:", err) } } else { if handle, err = pcap.OpenLive(*iface, int32(*snaplen), true, time.Second); err != nil { log.Fatalln("PCAP OpenLive error:", err) } if len(flag.Args()) > 0 { bpffilter := strings.Join(flag.Args(), " ") fmt.Fprintf(os.Stderr, "Using BPF filter %q\n", bpffilter) if err = handle.SetBPFFilter(bpffilter); err != nil { log.Fatalln("BPF filter error:", err) } } } dumpcommand.Run(handle) }
//startCapture captures all packets on any interface for an unlimited duration. //Packets can be filtered by a BPF filter string. (E.g. tcp port 22) func capture(snaplen int32, quit chan bool, captureReady chan bool, pcapFile string) error { var handle *pcap.Handle var err error if pcapFile != "" { log.Println("Reading packet loss data from pcap-file:", pcapFile) handle, err = pcap.OpenOffline(pcapFile) } else { //https://godoc.org/code.google.com/p/gopacket/pcap //This might have been the culprit //Alternative to try: 250*time.Millisecond handle, err = pcap.OpenLive("any", snaplen, true, 250*time.Millisecond) } if err != nil { log.Println("Error while start capturing packets", err) return err } packetSource := gopacket.NewPacketSource(handle, handle.LinkType()) captureReady <- true for { select { case packet := <-packetSource.Packets(): if packet != nil { if packet.Layer(layers.LayerTypeIPSecESP) != nil { putChannel(packet, ipSecChannel) } if packet.Layer(layers.LayerTypeICMPv4) != nil { putChannel(packet, icmpChannel) } } case <-quit: log.Println("Received quit message, stopping Listener.") return nil } } }
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 }