private async UniTask SendPingResponsePacketAsync(IPEndPoint ip, int id) { try { var commands = new Command[1]; commands[0] = new Command { P2PEventType = CommandType.PingResponse, Value = new PingPacket { PingID = id }.Serialize() }; var l2 = new UdpPacketL2 { ACKNumber = 0, PacketNumber = 0, Commands = commands, }.Serialize(); var packet = new UdpPacket { PeerID = null, UdpPacketL2 = l2, UdpPacketL2IV = null }.Serialize(); await UdpSocket.SendAsync(packet, packet.Length, ip); PacketCapture.Write(ip.ToString(), packet.Length, "PingResponse"); } catch (ObjectDisposedException ex) { Debugger.Error(ex.Message); Debugger.Log("[SocketUDP] Closed"); } }
public async UniTask RequestKey(UdpClient UdpSocket) { State = UdpConnectionState.KeyExchange; RSA = new RSA(); var publickey = RSA.RequestKey(); Command obj = new Command { P2PEventType = CommandType.RequestKey, Value = publickey.Serialize(), }; var array = new Command[1]; array[0] = obj; var l2 = new UdpPacketL2 { Commands = array, PacketNumber = 0, ACKNumber = 0, }.Serialize(); var buf = new UdpPacket { PeerID = UniP2PManager.MyPeerID, UdpPacketL2 = l2, UdpPacketL2IV = null }.Serialize(); await UdpSocket.SendAsync(buf, buf.Length, Peer.IPEndPoint); PacketCapture.Write(Peer.IPEndPoint.ToString(),buf.Length, "RequestKey"); }
public async UniTask CreateKey(byte[] buffer, UdpClient udpSocket ,SocketUdp socketUdp) { var publicKey = RSAPublicKey.Deserialize(buffer); RSA = new RSA(); var key = RSA.CreateKey(publicKey.Modules, publicKey.Exponent); AESKey = key.aeskey; Command obj = new Command { P2PEventType = CommandType.AcceptKey, Value = key.encrypted, }; var array = new Command[1]; array[0] = obj; var l2 = new UdpPacketL2 { Commands = array, PacketNumber = 0, ACKNumber = 0, }.Serialize(); var buf = new UdpPacket { PeerID = UniP2PManager.MyPeerID, UdpPacketL2 = l2, UdpPacketL2IV = null }.Serialize(); await udpSocket.SendAsync(buf, buf.Length, Peer.IPEndPoint); PacketCapture.Write(Peer.IPEndPoint.ToString(), buf.Length, "CreateKey"); State = UdpConnectionState.Connected; Peer.State = PeerState.Connected; InitHeartBeatAsync(socketUdp); }
protected override GetPacketStatus GetUnfilteredPacket(out PacketCapture e, TimeSpan timeout) { unsafe { fixed(byte *bufferPtr = ReadBuffer) { var ethRequest = new EthRequest(); ethRequest.AdapterHandle = AdapterHandle; ethRequest.Buffer = new IntPtr(bufferPtr); var ret = NativeMethods.ReadPacket(DriverHandle, ref ethRequest); if (!ret) { e = default; return(GetPacketStatus.ReadTimeout); } } } var bufferHeader = MemoryMarshal.Read <IntermediateBufferHeader>(ReadBuffer); var bufferData = new ReadOnlySpan <byte>(ReadBuffer, NativeMethods.IntermediateBufferHeaderSize, (int)bufferHeader.Length); var header = new WinpkFilterHeader() { Source = bufferHeader.Source, Dot1q = bufferHeader.Dot1q, }; e = new PacketCapture(this, header, bufferData); return(GetPacketStatus.PacketRead); }
public TabbedTools() { this.InitializeComponent(); try { this.packetCapture1 = new PacketCapture(); this.PcapTabPage.Controls.Add(this.packetCapture1); this.PcapTabPage.Location = new Point(4, 22); this.PcapTabPage.Name = "PcapTabPage"; this.PcapTabPage.Padding = new Padding(3); this.PcapTabPage.Size = new Size(886, 309); this.PcapTabPage.TabIndex = 15; this.PcapTabPage.Text = "Packets"; this.PcapTabPage.UseVisualStyleBackColor = true; this.packetCapture1.Dock = DockStyle.Fill; this.packetCapture1.Location = new Point(3, 3); this.packetCapture1.Name = "packetCapture1"; this.packetCapture1.Size = new Size(880, 303); this.packetCapture1.TabIndex = 0; } catch (Exception ex) { this.PcapTabPage.Controls.Clear(); Label l = new Label { Text = "The software \"WinPCap\" is either not installed or not supported on this version of windows.", Dock = DockStyle.Top }; this.PcapTabPage.Controls.Add(l); Log.Info(l.Text, ex); } }
private async UniTask SendConnectAcceptEvent(UdpConnection udp) { Command command = new Command(); command.P2PEventType = CommandType.RequestAccept; command.Value = null; var p = new Command[1]; p[0] = command; var l2 = new UdpPacketL2 { PacketNumber = 0, ACKNumber = 0, Commands = p, }.Serialize(); var packet = new UdpPacket { PeerID = UniP2PManager.MyPeerID, UdpPacketL2 = l2, UdpPacketL2IV = null, }.Serialize(); await UdpSocket.SendAsync(packet, packet.Length, udp.Peer.IPEndPoint); PacketCapture.Write(udp.Peer.IPEndPoint.ToString(), packet.Length, "ConnectAcceptEvent"); Debugger.Log("[SocketUDP] SendConnectAcceptEvent: dist:" + udp.Peer.IPEndPoint.ToString()); }
public async UniTask SendUnreliable(UdpClient UdpSocket) { if (UnreliableCommandBuffer.ToArray().Length != 0) { var l2 = new UdpPacketL2 { PacketNumber = 0, ACKNumber = 0, Commands = UnreliableCommandBuffer.ToArray() }.Serialize(); var l2Encrypt = AES.Encrypt(l2, AESKey); var packet = new UdpPacket { PeerID = UniP2PManager.MyPeerID, UdpPacketL2 = l2Encrypt.result, UdpPacketL2IV = l2Encrypt.iv, }.Serialize(); await UdpSocket.SendAsync(packet, packet.Length, Peer.IPEndPoint); PacketCapture.Write(Peer.IPEndPoint.ToString(), packet.Length, "Unreliable"); UnreliableCommandBuffer.Clear(); } }
/// <summary> /// Packet data is only valid until the next call /// </summary> /// <param name="e"></param> /// <returns>Status of the operation</returns> public GetPacketStatus GetNextPacket(out PacketCapture e) { var packets = new List <PacketRecord>(); var res = GetNextPackets(packets, 1); e = packets.Count > 0 ? packets[0].GetPacketCapture(this) : default; return(res); }
/// <summary> /// Prints the time and length of each received packet /// </summary> private static void device_OnPacketArrival(object sender, PacketCapture e) { var time = e.Header.Timeval.Date; var len = e.Data.Length; Console.WriteLine("{0}:{1}:{2},{3} Len={4}", time.Hour, time.Minute, time.Second, time.Millisecond, len); }
public async UniTask SendHeartBeatAsync(UdpConnection udp) { byte[] b = { }; Debugger.Log("[SocketUDP] SendHeartBeatAsync:" + udp.Peer.IPEndPoint.ToString()); await SendAsync(udp, b, CommandType.HeartBeat, SocketQosType.Unreliable); PacketCapture.Write(udp.Peer.IPEndPoint.ToString(), b.Length, "HeartBeat"); }
/* Main * Volá zpracování argumentů a poté funkci na chytání paketů */ static void Main(string[] args) { Argument arg = new Argument(); PacketCapture pc = new PacketCapture(); arg.parse_arguments(args); pc.find_device(arg.Inter); pc.catch_packets(arg); }
private void InsertPacketToQueue(object sender, PacketCapture e) { var packet = PacketDotNet.Packet.ParsePacket(e.GetPacket().LinkLayerType, e.GetPacket().Data); lock (_packetsQueueLock) { _packets.Enqueue(packet); } }
private void device_OnPacketArrival(object sender, PacketCapture e) { if (!sniffEnabled) { return; } lock (packetQueue) { packetQueue.Add(e.GetPacket()); } }
private static void Device_OnPacketArrival(object sender, PacketCapture e) { var device = (WinpkFilterDevice)sender; var packet = e.GetPacket().GetPacket(); if (packet.PayloadPacket is IPPacket ip) { Console.WriteLine(ip.ToString(StringOutputType.Colored)); } device.SendPacket(e.Data, e.Header); }
/// <summary> /// Prints the time and length of each received packet /// </summary> private static void device_OnPacketArrival(object sender, PacketCapture e) { var rawPacket = e.GetPacket(); var time = rawPacket.Timeval.Date; var len = rawPacket.Data.Length; Console.WriteLine("{0}:{1}:{2},{3} Len={4}", time.Hour, time.Minute, time.Second, time.Millisecond, len); var p = Packet.ParsePacket(rawPacket.LinkLayerType, rawPacket.Data); Console.WriteLine(p.ToString()); }
private static void device_OnPacketArrival(object sender, PacketCapture e) { var rawPacket = e.GetPacket(); var packet = PacketDotNet.Packet.ParsePacket(rawPacket.LinkLayerType, rawPacket.Data); if (packet is PacketDotNet.EthernetPacket eth) { Console.WriteLine("Original Eth packet: " + eth.ToString()); //Manipulate ethernet parameters eth.SourceHardwareAddress = PhysicalAddress.Parse("00-11-22-33-44-55"); eth.DestinationHardwareAddress = PhysicalAddress.Parse("00-99-88-77-66-55"); var ip = packet.Extract <PacketDotNet.IPPacket>(); if (ip != null) { Console.WriteLine("Original IP packet: " + ip.ToString()); //manipulate IP parameters ip.SourceAddress = System.Net.IPAddress.Parse("1.2.3.4"); ip.DestinationAddress = System.Net.IPAddress.Parse("44.33.22.11"); ip.TimeToLive = 11; var tcp = packet.Extract <PacketDotNet.TcpPacket>(); if (tcp != null) { Console.WriteLine("Original TCP packet: " + tcp.ToString()); //manipulate TCP parameters tcp.SourcePort = 9999; tcp.DestinationPort = 8888; tcp.Synchronize = !tcp.Synchronize; tcp.Finished = !tcp.Finished; tcp.Acknowledgment = !tcp.Acknowledgment; tcp.WindowSize = 500; tcp.AcknowledgmentNumber = 800; tcp.SequenceNumber = 800; } var udp = packet.Extract <PacketDotNet.UdpPacket>(); if (udp != null) { Console.WriteLine("Original UDP packet: " + udp.ToString()); //manipulate UDP parameters udp.SourcePort = 9999; udp.DestinationPort = 8888; } } Console.WriteLine("Manipulated Eth packet: " + eth.ToString()); } }
public async UniTask SendPacketDataAsync(Peer peer, byte[] data, CommandType p2PEvent = CommandType.Nothing, SocketQosType qosType = SocketQosType.Unreliable) { foreach (var connection in UdpConnections) { if (connection.Peer == peer) { await SendAsync(GetUdpConnection(peer.ID), data, p2PEvent, qosType); PacketCapture.Write(peer.IPEndPoint.ToString(), data.Length, "PacketData"); return; } } }
public async UniTask SendEmptyPacketAsync(IPEndPoint ip) { byte[] buf = { }; try { await UdpSocket.SendAsync(buf, buf.Length, ip); PacketCapture.Write(ip.ToString(), buf.Length, "EmptyPacket"); } catch (ObjectDisposedException ex) { //Debugger.Log("[SocketUDP] Closed"); } }
private void Device_OnPacketArrival(object sender, PacketCapture e) { if (e.GetPacket().LinkLayerType != PacketDotNet.LinkLayers.Ethernet) { return; } var packet = Packet.ParsePacket(e.GetPacket().LinkLayerType, e.GetPacket().Data); var ethernetPacket = (EthernetPacket)packet; var requestItem = new PCAPFeatureExtractionRequestItem(ethernetPacket.PayloadPacket.Bytes); _packetPredictions.Add(_mlEngine.Predict(requestItem)); }
public async UniTask <int> SendPingPacketAsync(IPEndPoint ip) { int ms = 0; try { var objs = new Command[1]; objs[0] = new Command { P2PEventType = CommandType.PingRequest, Value = new PingPacket { PingID = pingid }.Serialize() }; var u = new UdpPacketL2 { ACKNumber = 0, PacketNumber = 0, Commands = objs }.Serialize(); var packet = new UdpPacket { PeerID = null, UdpPacketL2 = u, UdpPacketL2IV = null }.Serialize(); await UdpSocket.SendAsync(packet, packet.Length, ip); PacketCapture.Write(ip.ToString(), packet.Length, "Ping"); var id = pingid; PingTemp.Add(id, false); pingid++; do { await UniTask.Delay(1); ms++; }while (PingTemp[id]); PingTemp.Remove(id); return(ms); } catch (ObjectDisposedException ex) { Debugger.Error(ex.Message); Debugger.Log("[SocketUDP] Closed"); } return(-1); }
/// <summary> /// Prints the time and length of each received packet /// </summary> private static void device_OnPacketArrival(object sender, PacketCapture e) { PacketCount++; var rawPacket = e.GetPacket(); var p = PacketDotNet.Packet.ParsePacket(rawPacket.LinkLayerType, rawPacket.Data); var tcpPacket = p.Extract <TcpPacket>(); if (tcpPacket != null) { log.Debug("passing packet to TcpConnectionManager"); tcpConnectionManager.ProcessPacket(rawPacket.Timeval, tcpPacket); } }
/// <summary> /// Retrieve the next packet data /// </summary> /// <param name="e">Structure to hold the packet data info</param> /// <returns>Status of the operation</returns> public virtual GetPacketStatus GetNextPacket(out PacketCapture e) { //Pointer to a packet info struct IntPtr header = IntPtr.Zero; //Pointer to a packet struct IntPtr data = IntPtr.Zero; // using an invalid PcapHandle can result in an unmanaged segfault // so check for that here ThrowIfNotOpen("Device must be opened via Open() prior to use"); // If a user is calling GetNextPacket() when the background capture loop // is also calling into libpcap then bad things can happen // // The bad behavior I (Chris M.) saw was that the background capture would keep running // but no more packets were captured. Took two days to debug and regular users // may hit the issue more often so check and report the issue here if (Started) { throw new InvalidOperationDuringBackgroundCaptureException("GetNextPacket() invalid during background capture"); } if (!PollFileDescriptor()) { e = default; // We checked, there is no data using poll() return(GetPacketStatus.ReadTimeout); } int res; unsafe { //Get a packet from npcap res = LibPcapSafeNativeMethods.pcap_next_ex(PcapHandle, ref header, ref data); var pcapHeader = PcapHeader.FromPointer(header); var dataSpan = new Span <byte>(data.ToPointer(), (int)pcapHeader.CaptureLength); e = new PacketCapture(this, pcapHeader, dataSpan); } return((GetPacketStatus)res); }
public async UniTask TickReliablePacket(UdpClient UdpSocket) { while (isTickReliablePacket) { foreach (var value in SentReliableBuffer.Values) { value.WaitTime++; if (RTT <= value.WaitTime) { await UdpSocket.SendAsync(value.Buffer, value.Buffer.Length, Peer.IPEndPoint); PacketCapture.Write(Peer.IPEndPoint.ToString(), value.Buffer.Length, "TickReliablePacket"); } } await UniTask.Delay(1); } }
/// <summary> /// Packet data is only valid until the next call /// </summary> /// <param name="e"></param> /// <returns>Status of the operation</returns> public GetPacketStatus GetNextPacket(out PacketCapture e) { ThrowIfNotOpen(); while (true) { bool ret; WinDivertAddress addr; uint readLen; unsafe { fixed(byte *p = buffer) { ret = WinDivertNative.WinDivertRecv(Handle, new IntPtr(p), (uint)buffer.Length, out readLen, out addr); } } if (!ret) { var err = Marshal.GetLastWin32Error(); if (err == ERROR_INSUFFICIENT_BUFFER) { // Increase buffer size buffer = new byte[buffer.Length * 2]; continue; } if (err == ERROR_NO_DATA) { e = default; return((GetPacketStatus)(-err)); } ThrowWin32Error("Recv failed", err); } var timestamp = new PosixTimeval(BootTime + TimeSpan.FromTicks(addr.Timestamp)); var data = new ReadOnlySpan <byte>(buffer, 0, (int)readLen); var header = new WinDivertHeader(timestamp) { InterfaceIndex = addr.IfIdx, SubInterfaceIndex = addr.SubIfIdx, Flags = addr.Flags }; e = new PacketCapture(this, header, data); return(GetPacketStatus.PacketRead); } }
/// <summary> /// Prints the time and length of each received packet /// </summary> private static void device_OnPacketArrival(object sender, PacketCapture e) { // print out periodic statistics about this device 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); LastStatisticsOutput = Now; } // lock QueueLock to prevent multiple threads accessing PacketQueue at // the same time lock (QueueLock) { PacketQueue.Add(e.GetPacket()); } }
/// <summary> /// Prints the source and dest MAC addresses of each received Ethernet frame /// </summary> private static void device_OnPacketArrival(object sender, PacketCapture e) { packetIndex++; var rawPacket = e.GetPacket(); var packet = PacketDotNet.Packet.ParsePacket(rawPacket.LinkLayerType, rawPacket.Data); var ethernetPacket = packet.Extract <EthernetPacket>(); if (ethernetPacket != null) { Console.WriteLine("{0} At: {1}:{2}: MAC:{3} -> MAC:{4}", packetIndex, e.Header.Timeval.Date.ToString(), e.Header.Timeval.Date.Millisecond, ethernetPacket.SourceHardwareAddress, ethernetPacket.DestinationHardwareAddress); } }
public async UniTask SendReliable(UdpClient UdpSocket) { if (State == UdpConnectionState.Connected) { /*if (!isTickReliablePacket) * { * isTickReliablePacket = true; * await TickReliablePacket(UdpSocket); * }*/ if (ReliableCommandBuffer.Count != 0) { var l2 = new UdpPacketL2 { PacketNumber = MyPacketCount, ACKNumber = 0, Commands = ReliableCommandBuffer.ToArray(), }.Serialize(); var l2Encrypt = AES.Encrypt(l2, AESKey); var packet = new UdpPacket { PeerID = UniP2PManager.MyPeerID, UdpPacketL2 = l2Encrypt.result, UdpPacketL2IV = l2Encrypt.iv, }.Serialize(); await UdpSocket.SendAsync(packet, packet.Length, Peer.IPEndPoint); PacketCapture.Write(Peer.IPEndPoint.ToString(), packet.Length, "Reliable"); //SentReliableBuffer.Add(MyPacketCount, new ReliablePacketInfo { Buffer = packet, WaitTime = 0 }); MyPacketCount++; } /*if (SentReliableBuffer.ContainsKey(PeerWaitPacketNumber)) * { * await UdpSocket.SendAsync(SentReliableBuffer[PeerWaitPacketNumber].Buffer, SentReliableBuffer[PeerWaitPacketNumber].Buffer.Length, Peer.IPEndPoint); * PacketCapture.Write(Peer.IPEndPoint.ToString(), SentReliableBuffer[PeerWaitPacketNumber].Buffer.Length, "SentReliableBuffer"); * }*/ } }
private async UniTask SendConnectRequestEvent(IPEndPoint ip, bool isBroadcast = false, int localport = 0) { Command command = new Command(); command.P2PEventType = CommandType.ConnectRequest; command.Value = null; var p = new Command[1]; p[0] = command; var l2 = new UdpPacketL2 { PacketNumber = 0, ACKNumber = 0, Commands = p, }.Serialize(); var packet = new UdpPacket { PeerID = UniP2PManager.MyPeerID, UdpPacketL2 = l2, UdpPacketL2IV = null, }.Serialize(); if (isBroadcast && localport != 0) { UdpSocket.EnableBroadcast = true; await UdpSocket.SendAsync(packet, packet.Length, new IPEndPoint(IPAddress.Broadcast, localport)); PacketCapture.Write("Broadcast:" + localport, packet.Length, "ConnectRequestEvent"); UdpSocket.EnableBroadcast = false; await UdpSocket.SendAsync(packet, packet.Length, new IPEndPoint(UniP2PManager.PrivateIPEndPoint.Address, localport)); PacketCapture.Write(UniP2PManager.PrivateIPEndPoint.Address.ToString() + ":" + localport, packet.Length, "ConnectRequestEvent"); } else { await UdpSocket.SendAsync(packet, packet.Length, ip); } }
/// <summary> /// Prints the time and length of each received packet /// </summary> private static void device_OnPacketArrival(object sender, PacketCapture e) { #if false 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()); #endif var rawPacket = e.GetPacket(); var p = PacketDotNet.Packet.ParsePacket(rawPacket.LinkLayerType, rawPacket.Data); var tcpPacket = p.Extract <TcpPacket>(); if (tcpPacket == null) { return; } log.Debug("passing packet to TcpConnectionManager"); tcpConnectionManager.ProcessPacket(rawPacket.Timeval, tcpPacket); }
public TabbedTools() { InitializeComponent(); try { packetCapture1 = new PacketCapture(); // // PcapTabPage // this.PcapTabPage.Controls.Add(packetCapture1); this.PcapTabPage.Location = new System.Drawing.Point(4, 22); this.PcapTabPage.Name = "PcapTabPage"; this.PcapTabPage.Padding = new Padding(3); this.PcapTabPage.Size = new System.Drawing.Size(886, 309); this.PcapTabPage.TabIndex = 15; this.PcapTabPage.Text = "Packets"; this.PcapTabPage.UseVisualStyleBackColor = true; // // packetCapture1 // this.packetCapture1.Dock = DockStyle.Fill; this.packetCapture1.Location = new System.Drawing.Point(3, 3); this.packetCapture1.Name = "packetCapture1"; this.packetCapture1.Size = new System.Drawing.Size(880, 303); this.packetCapture1.TabIndex = 0; } catch (Exception e) { this.PcapTabPage.Controls.Clear(); Label l = new Label(); this.PcapTabPage.Controls.Add(l); l.Text = "Packet Capture is either not install or not supported on this version of windows."; l.Dock = DockStyle.Top; Logging.Info(l.Text, e); } }