public void TestFileCreationAndDeletion() { using (var wd = new CaptureFileWriterDevice(filename)) { wd.Open(); Assert.AreEqual(filename, wd.Name); Assert.IsNotEmpty(wd.Description); var bytes = new byte[] { 1, 2, 3, 4 }; wd.Write(bytes); var p = new RawCapture(PacketDotNet.LinkLayers.Ethernet, new PosixTimeval(), bytes); wd.Write(p); } System.IO.File.Delete(@"abc.pcap"); }
public void TestInjectable() { using (var wd = new CaptureFileWriterDevice(filename)) { wd.Open(); Assert.AreEqual(filename, wd.Name); Assert.IsNotEmpty(wd.Description); var bytes = new byte[] { 1, 2, 3, 4 }; var injectionDevice = wd as IInjectionDevice; var p = new RawCapture(PacketDotNet.LinkLayers.Ethernet, new PosixTimeval(), bytes); injectionDevice.SendPacket(p); var span = new ReadOnlySpan <byte>(bytes, 0, bytes.Length); injectionDevice.SendPacket(span); } System.IO.File.Delete(@"abc.pcap"); }
private void Save_Click(object sender, EventArgs e) { var sfd = new SaveFileDialog { Filter = "Pcap Files (*.pcap)|*.pcap", FilterIndex = 2, RestoreDirectory = true }; if (sfd.ShowDialog() == DialogResult.OK) { var writer = new CaptureFileWriterDevice(sfd.FileName); writer.Open(); foreach (var packet in _reader.RawCapturedPacked) { writer.Write(packet); } writer.Close(); } }
public async Task <ActionResult> OnPostPcap(int cid, int sid, string source, string dest, string output) { SnortContext db = HttpContext.RequestServices.GetService(typeof(SnortContext)) as SnortContext; Utils.Tcpdump tcpdump_path = HttpContext.RequestServices.GetService(typeof(Utils.Tcpdump)) as Utils.Tcpdump; string path = tcpdump_path.path; if (StaticData.alerts == null) { StaticData.alerts = AlertMapper.ResolveAlerts(0, ref StaticData.signatureStrings, db.GetConnection()); } //alerts = SessionExtensions.Get<List<Alert>>(HttpContext.Session,"alert"); this.cid = cid; this.sid = sid; alerts.Add(StaticData.alerts.Where(x => x.cid == cid && x.sid == sid).FirstOrDefault()); targetSec = ((DateTimeOffset)alerts.First().time).ToUnixTimeSeconds(); long epochTicks = new DateTime(1970, 1, 1).Ticks; targetMS = alerts.First().time.Ticks - epochTicks; //TimeSpan epochTicks2 = new TimeSpan(new DateTime(1970, 1, 1).Ticks); //targetMS = (ulong) (((DateTimeOffset)alerts.First().time).Ticks - epochTicks2.Ticks)/10; IEnumerable <string> files; try { files = Directory.EnumerateFiles(path, "tcpdump.log.*"); } catch (Exception) { return(RedirectToPage("Error", "Issue", new { issue = "Snort packet log folder not found (" + path + "). Change the path in appsettings.json to match the Snort output path." })); } long closestTS = 0; string closestFile = ""; foreach (string f in files) { //ulong currentTS = Convert.ToUInt64(f.Split('.').Last()); long currentTSS = Convert.ToInt64(f.Split('.').Last()); //DateTime currentTS = Convert.ToDateTime(f.Split('.').Last()); if (currentTSS <= targetSec && currentTSS > closestTS) { closestTS = currentTSS; closestFile = f; } } if (closestFile == "") { return(RedirectToPage("Error", "Issue", new { issue = "No appropriate packet log found in " + path + ". Please review your Snort output configuration and activate: output log_tcpdump: tcpdump.log" })); } string dir = Path.Combine(Startup.AppPath, "wwwroot/pcaps/"); if (!System.IO.File.Exists(dir + sid + "." + cid)) { (new FileInfo(dir + sid + "." + cid)).Directory.Create(); //CaptureDeviceList devices = CaptureDeviceList.Instance; CaptureFileReaderDevice device = new CaptureFileReaderDevice(closestFile); captureFileWriter = new CaptureFileWriterDevice(dir + sid + "." + cid); captureFileWriter.Open(); device.OnPacketArrival += new PacketArrivalEventHandler(this.device_OnPacketArrival); device.OnCaptureStopped += new CaptureStoppedEventHandler(this.device_OnCaptureStopped); device.Filter = "host " + source + " and host " + dest; device.StartCapture(); signal = new SemaphoreSlim(0, 1); await signal.WaitAsync(); } switch (output) { case "pcap": { return(File("/pcaps/" + sid + "." + cid, "application/octet-stream", sid + "." + cid + ".pcap")); } case "tcpdump": { string tcpdump = Utils.Bash("tcpdump -r " + dir + sid + "." + cid); return(File(new MemoryStream(Encoding.UTF8.GetBytes(tcpdump ?? "tcpdump is not available")), "application/octet-stream", sid + "." + cid + ".txt")); } default: { return(File("/pcaps/" + sid + "." + cid, "application/octet-stream", sid + "." + cid + ".pcap")); } } }
public async void extractFromPcap(int cid, int sid) { string dir = Path.Combine(Startup.AppPath, "wwwroot/pcaps/"); SnortContext db = HttpContext.RequestServices.GetService(typeof(SnortContext)) as SnortContext; Utils.Tcpdump tcpdump_path = HttpContext.RequestServices.GetService(typeof(Utils.Tcpdump)) as Utils.Tcpdump; string path = tcpdump_path.path; if (StaticData.alerts == null) { StaticData.alerts = AlertMapper.ResolveAlerts(0, ref StaticData.signatureStrings, db.GetConnection()); } //alerts = SessionExtensions.Get<List<Alert>>(HttpContext.Session,"alert"); this.cid = cid; this.sid = sid; alerts.Add(StaticData.alerts.Where(x => x.cid == cid && x.sid == sid).FirstOrDefault()); //UTC targetSec = ((DateTimeOffset)alerts.First().time).ToUnixTimeSeconds(); //Local Time //TimeSpan epochSecs = new TimeSpan(new DateTime(1970, 1, 1).Second); //targetSec = (((DateTimeOffset)alerts.First().time).Second - epochSecs.Seconds); if (!System.IO.File.Exists(dir + sid + "." + cid)) { string source = StaticData.alerts.Where(x => x.cid == cid && x.sid == sid).FirstOrDefault().src_ip; string dest = StaticData.alerts.Where(x => x.cid == cid && x.sid == sid).FirstOrDefault().dest_ip; long epochTicks = new DateTime(1970, 1, 1).Ticks; targetMS = alerts.First().time.Ticks - epochTicks; //TimeSpan epochTicks2 = new TimeSpan(new DateTime(1970, 1, 1).Ticks); //targetMS = (ulong) (((DateTimeOffset)alerts.First().time).Ticks - epochTicks2.Ticks)/10; IEnumerable <string> files; try { files = Directory.EnumerateFiles(path, "tcpdump.log.*"); long closestTS = 0; string closestFile = ""; foreach (string f in files) { //ulong currentTS = Convert.ToUInt64(f.Split('.').Last()); long currentTSS = Convert.ToInt64(f.Split('.').Last()); //DateTime currentTS = Convert.ToDateTime(f.Split('.').Last()); if (currentTSS <= targetSec && currentTSS > closestTS) { closestTS = currentTSS; closestFile = f; } } (new FileInfo(dir + sid + "." + cid)).Directory.Create(); //CaptureDeviceList devices = CaptureDeviceList.Instance; CaptureFileReaderDevice device = new CaptureFileReaderDevice(closestFile); captureFileWriter = new CaptureFileWriterDevice(dir + sid + "." + cid); captureFileWriter.Open(); device.OnPacketArrival += new PacketArrivalEventHandler(this.device_OnPacketArrival); device.OnCaptureStopped += new CaptureStoppedEventHandler(this.device_OnCaptureStopped); device.Filter = "host " + source + " and host " + dest; device.StartCapture(); signal = new SemaphoreSlim(0, 1); await signal.WaitAsync(); } catch (Exception) {; } } }
public static void Main() { // Print SharpPcap version var ver = Pcap.SharpPcapVersion; Console.WriteLine("SharpPcap {0}, CreatingCaptureFile", ver); // Retrieve the device list var devices = LibPcapLiveDeviceList.Instance; // If no devices were found print an error if (devices.Count < 1) { Console.WriteLine("No devices were found on this machine"); return; } Console.WriteLine(); Console.WriteLine("The following devices are available on this machine:"); Console.WriteLine("----------------------------------------------------"); Console.WriteLine(); int i = 0; // Print out the devices foreach (var dev in devices) { /* Description */ Console.WriteLine("{0}) {1} {2}", i, dev.Name, dev.Description); i++; } Console.WriteLine(); Console.Write("-- Please choose a device to capture on: "); i = int.Parse(Console.ReadLine()); Console.Write("-- Please enter the output file name: "); string capFile = Console.ReadLine(); using var device = devices[i]; // Register our handler function to the 'packet arrival' event device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival); // Open the device for capturing int readTimeoutMilliseconds = 1000; device.Open(mode: DeviceModes.Promiscuous | DeviceModes.DataTransferUdp | DeviceModes.NoCaptureLocal, read_timeout: readTimeoutMilliseconds); Console.WriteLine(); Console.WriteLine("-- Listening on {0} {1}, writing to {2}, hit 'Enter' to stop...", device.Name, device.Description, capFile); // open the output file captureFileWriter = new CaptureFileWriterDevice(capFile); captureFileWriter.Open(device); // Start the capturing process device.StartCapture(); // Wait for 'Enter' from the user. Console.ReadLine(); // Stop the capturing process device.StopCapture(); Console.WriteLine("-- Capture stopped."); // Print out the device statistics Console.WriteLine(device.Statistics.ToString()); }