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 } } }
func (p *PcapLogger) Start() { if p.fileWriter == nil { p.basename = filepath.Join(p.LogDir, fmt.Sprintf("%s.pcap", p.Flow)) p.fileWriter = NewRotatingQuotaWriter(p.basename, p.pcapQuota, p.pcapLogNum, p.WriteHeader) p.writer = pcapgo.NewWriter(p.fileWriter) } go p.logPackets() }
func runNGNet(packetSource *gopacket.PacketSource) { streamFactory := ngnet.NewHttpStreamFactory(eventChan) pool := tcpassembly.NewStreamPool(streamFactory) assembler := tcpassembly.NewAssembler(pool) var pcapWriter *pcapgo.Writer if *outputPcap != "" { outPcapFile, err := os.Create(*outputPcap) if err != nil { log.Fatalln(err) } defer outPcapFile.Close() pcapWriter = pcapgo.NewWriter(outPcapFile) pcapWriter.WriteFileHeader(65536, layers.LinkTypeEthernet) } var count int = 0 for packet := range packetSource.Packets() { count++ net_layer := packet.NetworkLayer() if net_layer == nil { continue } trans_layer := packet.TransportLayer() if trans_layer == nil { continue } tcp, _ := trans_layer.(*layers.TCP) if tcp == nil { continue } if pcapWriter != nil { pcapWriter.WritePacket(packet.Metadata().CaptureInfo, packet.Data()) } assembler.AssembleWithTimestamp( net_layer.NetworkFlow(), tcp, packet.Metadata().CaptureInfo.Timestamp) } assembler.FlushAll() streamFactory.Wait() log.Println("Packet count: ", count) }
// Open and create a pcap output file func openPcap(config *Config) error { if config.pcapOut != "" { f, err := os.Create(config.pcapOut) w := pcapgo.NewWriter(f) // Write the PCAP global header w.WriteFileHeader(65536, layers.LinkTypeEthernet) // Store the file/writer handles config.pcapFile = f config.pcapWriter = w log.Printf("Logging packets to %s", config.pcapOut) return err } return nil }
func (s *Splitter) SplitByOptions(confs map[packet.OptionId]SplitByOptionsConfig) (err error) { defer errs.PassE(&err) inHandle, err := pcap.OpenOffline(s.inputFileName) errs.CheckE(err) defer inHandle.Close() type state struct { SplitByOptionsConfig w *pcapgo.Writer lastPacketNum *int } states := make(map[packet.OptionId]*state) for oid, conf := range confs { state := state{ SplitByOptionsConfig: conf, w: pcapgo.NewWriter(conf.Writer), lastPacketNum: conf.LastPacketNum, } if state.lastPacketNum == nil { state.lastPacketNum = new(int) } if !conf.AppendOnly { errs.CheckE(state.w.WriteFileHeader(65536, layers.LinkTypeEthernet)) } states[oid] = &state } for i, poids := range s.allPacketOids[1:] { data, ci, err := inHandle.ZeroCopyReadPacketData() errs.CheckE(err) for _, poid := range poids { if state := states[poid]; state != nil && *state.lastPacketNum < i { errs.CheckE(state.w.WritePacket(ci, data)) *state.lastPacketNum = i } } } return nil }
// PacketsToFile writes all packets from 'in' to 'out', writing out all packets // in a valid PCAP file format. func PacketsToFile(in *PacketChan, out io.Writer) error { w := pcapgo.NewWriter(out) w.WriteFileHeader(snapLen, layers.LinkTypeEthernet) count := 0 defer in.Discard() defer func() { V(1, "wrote %d packets of %d input packets", count, len(in.C)) }() for p := range in.Receive() { if len(p.Data) > snapLen { p.Data = p.Data[:snapLen] } if err := w.WritePacket(p.CaptureInfo, p.Data); err != nil { // This can happen if our pipe is broken, and we don't want to blow stack // traces all over our users when that happens, so Error/Exit instead of // Fatal. return fmt.Errorf("error writing packet: %v", err) } count++ } return in.Err() }
func main() { var FilePathInput string var FilePathOutput string flag.StringVar(&FilePathInput, "in", "", "the path of PCAP file") flag.StringVar(&FilePathOutput, "out", "", "the output file") flag.Parse() // in mind if we need to do search in file. if FilePathInput == "" || FilePathOutput == "" { fmt.Print("lack of parameters!") return } handle, err := pcap.OpenOffline(FilePathInput) if err != nil { panic(err) } defer handle.Close() packetSource := gopacket.NewPacketSource(handle, handle.LinkType()) //need to add tcp assemble and udp defrag here. Output, err := os.Create(FilePathOutput) w := pcapgo.NewWriter(Output) w.WriteFileHeader(65536, layers.LinkTypeRaw) defer Output.Close() // need add function call here tcpPack := make(chan gopacket.Packet, 5) // maybe need change buffersize for chan nomalPack := make(chan gopacket.Packet, 5) fragV4Pack := make(chan gopacket.Packet, 5) fragV6Pack := make(chan gopacket.Packet, 5) endNotification := make(chan bool) go readSource(packetSource, tcpPack, nomalPack, fragV4Pack, fragV6Pack, endNotification) go v6Defrag(fragV6Pack, nomalPack) go v4Defrag(fragV4Pack, nomalPack) go pcapWrite(w, nomalPack) streamFactory := &DNSStreamFactory{normal: nomalPack} streamPool := tcpassembly.NewStreamPool(streamFactory) assembler := tcpassembly.NewAssembler(streamPool) go tcpAssemble(tcpPack, assembler) // wait for the reading to finish <-endNotification }
func (m *memh2pcap) Open(w io.Writer) (err error) { defer errs.PassE(&err) m.pw = pcapgo.NewWriter(w) errs.CheckE(m.pw.WriteFileHeader(65536, layers.LinkTypeEthernet)) eth := &layers.Ethernet{ SrcMAC: net.HardwareAddr([]byte{0, 22, 33, 44, 55, 66}), DstMAC: net.HardwareAddr([]byte{11, 22, 33, 44, 55, 77}), EthernetType: layers.EthernetType(0x800), } ip := &layers.IPv4{ Version: 4, SrcIP: net.IP{1, 2, 3, 4}, DstIP: net.IP{233, 54, 12, 1}, TTL: 1, Protocol: layers.IPProtocolUDP, } udp := &layers.UDP{ SrcPort: 1, DstPort: 18001, } errs.CheckE(udp.SetNetworkLayerForChecksum(ip)) mold := &nasdaq.MoldUDP64{ Session: "TestSess00", SequenceNumber: 0, MessageCount: 1, } moldMb := &nasdaq.MoldUDP64MessageBlockChained{} m.mold = mold m.layers = append([]gopacket.SerializableLayer{}, moldMb, mold, udp, ip, eth) m.sb = gopacket.NewSerializeBuffer() m.so = gopacket.SerializeOptions{ FixLengths: true, ComputeChecksums: true, } return }
// Create a 1 packet PCAP buffer. // // Give a timestamp, a packet and a linktype return a []byte buffer // containing a complete PCAP file. func CreatePcap(timestamp time.Time, packet []byte, linktype layers.LinkType) ([]byte, error) { var output bytes.Buffer var err error pcapWriter := pcapgo.NewWriter(&output) err = pcapWriter.WriteFileHeader(0xffff, linktype) if err != nil { return nil, err } captureInfo := gopacket.CaptureInfo{ Timestamp: timestamp, CaptureLength: len(packet), Length: len(packet), } err = pcapWriter.WritePacket(captureInfo, packet) if err != nil { return nil, err } return output.Bytes(), nil }
func TestPCAPGoWrite(t *testing.T) { f, err := ioutil.TempFile("", "pcapgo") if err != nil { t.Fatal(err) } data := []byte{0xab, 0xcd, 0xef, 0x01, 0x02, 0x03, 0x04} ci := gopacket.CaptureInfo{ Timestamp: time.Unix(12345667, 1234567000), Length: 700, CaptureLength: len(data), } func() { defer f.Close() w := pcapgo.NewWriter(f) if err := w.WriteFileHeader(65536, layers.LinkTypeEthernet); err != nil { t.Fatal(err) } if err := w.WritePacket(ci, data); err != nil { t.Fatal(err) } }() h, err := OpenOffline(f.Name()) if err != nil { t.Fatal(err) } defer h.Close() gotData, gotCI, err := h.ReadPacketData() if err != nil { t.Fatal("could not read first packet:", err) } if !bytes.Equal(gotData, data) { t.Errorf("byte mismatch:\nwant: %v\n got: %v", data, gotData) } if !reflect.DeepEqual(ci, gotCI) { t.Errorf("CI mismatch:\nwant: %v\n got: %v", ci, gotCI) } }
//DumpPackets attaches a gopcap writer to a file for dumping packets coming from the //snifer to a file and calls a function that is supplied when done(i.e frozen or drop) func (b *BaseController) DumpPackets(fx func(string)) error { if b.State() != RunningState { return ErrBadController } dir := fmt.Sprintf("./%s/%s", b.Profile().DataFolder, "packets") err := os.MkdirAll(dir, 0666) if err != nil && !os.IsExist(err) { checkError(err, fmt.Sprintf("Creating dir %s for %s", dir, b.Name())) } fname := path.Clean(fmt.Sprintf("%s/%s.%d.pcap", dir, b.Name(), rand.Intn(3234)*20)) dum, err := os.Create(fname) if err != nil { checkError(err, fmt.Sprintf("Creating file %s for %s", fname, b.Name())) return err } lt, err := b.snifer.LinkType() if err != nil { checkError(err, fmt.Sprintf("Retrieving Snifer linkType for %s", b.Name())) return err } gow := pcapgo.NewWriter(dum) if err := gow.WriteFileHeader(65536, lt); err != nil { checkError(err, fmt.Sprintf("Writing pcap Headers %s", b.Name())) return err } sub := b.Snifer().Listen(func(packet gopacket.Packet, _ flux.Stacks) { data := packet.Data() err := gow.WritePacket(gopacket.CaptureInfo{ Timestamp: time.Now(), CaptureLength: len(data), Length: len(data), }, data) checkError(err, fmt.Sprintf("Dumping Packet Data to %s", fname)) }) end := new(sync.Once) ender := func() { defer sub.Close() dum.Close() log.Printf("Closing gopacket Writer and File for %s snifer on file %s", b.Name(), fname) if fx != nil { fx(fname) } } _ = b.OnFreezed().Stack(func(b interface{}, sz flux.Stacks) interface{} { defer sz.Close() end.Do(ender) return b }, true) _ = b.OnDrop().Stack(func(b interface{}, sz flux.Stacks) interface{} { defer sz.Close() end.Do(ender) return b }, true) return nil }