// tcp public void VerifyPacket1(Packet p, RawCapture rawCapture) { Console.WriteLine(p.ToString()); EthernetPacket e = (EthernetPacket)p; Assert.AreEqual("0016CFC91E29", e.SourceHwAddress.ToString()); Assert.AreEqual("0014BFF2EF0A", e.DestinationHwAddress.ToString()); IpPacket ip = (IpPacket)p.PayloadPacket; Assert.AreEqual(System.Net.IPAddress.Parse("192.168.1.104"), ip.SourceAddress); Assert.AreEqual(System.Net.IPAddress.Parse("86.42.196.13"), ip.DestinationAddress); Assert.AreEqual(64, ip.TimeToLive); Assert.AreEqual(0x2ff4, ((IPv4Packet)ip).CalculateIPChecksum()); Assert.AreEqual(1171483600, rawCapture.Timeval.Seconds); Assert.AreEqual(125234.000, rawCapture.Timeval.MicroSeconds); TcpPacket tcp = (TcpPacket)ip.PayloadPacket; Assert.AreEqual(56925, tcp.SourcePort); Assert.AreEqual(50199, tcp.DestinationPort); Assert.IsTrue(tcp.Ack); Assert.IsTrue(tcp.Psh); Assert.AreEqual(16666, tcp.WindowSize); Assert.AreEqual(0x9b02, tcp.CalculateTCPChecksum()); Assert.AreEqual(0x9b02, tcp.Checksum); Assert.IsTrue(tcp.ValidTCPChecksum); }
// tcp public void VerifyPacket0(Packet p, RawCapture rawCapture) { Console.WriteLine(p.ToString()); EthernetPacket e = (EthernetPacket)p; Assert.AreEqual(PhysicalAddress.Parse("00-13-10-03-71-47"), e.SourceHwAddress); Assert.AreEqual(PhysicalAddress.Parse("00-E0-4C-E5-73-AD"), e.DestinationHwAddress); IpPacket ip = (IpPacket)e.PayloadPacket; Assert.AreEqual(System.Net.IPAddress.Parse("82.165.240.134"), ip.SourceAddress); Assert.AreEqual(System.Net.IPAddress.Parse("192.168.1.221"), ip.DestinationAddress); Assert.AreEqual(IpVersion.IPv4, ip.Version); Assert.AreEqual(IPProtocolType.TCP, ip.Protocol); Assert.AreEqual(254, ip.TimeToLive); Assert.AreEqual(0x0df8, ((IPv4Packet)ip).CalculateIPChecksum()); Assert.AreEqual(1176685346, rawCapture.Timeval.Seconds); Assert.AreEqual(885259.000, rawCapture.Timeval.MicroSeconds); TcpPacket tcp = (TcpPacket)ip.PayloadPacket; Assert.AreEqual(80, tcp.SourcePort); Assert.AreEqual(4324, tcp.DestinationPort); Assert.IsTrue(tcp.Ack); Assert.AreEqual(3536, tcp.WindowSize); Assert.AreEqual(0xc835, tcp.CalculateTCPChecksum()); Console.WriteLine("tcp.Checksum is {0}", tcp.Checksum); Assert.AreEqual(0xc835, tcp.Checksum, "tcp.Checksum mismatch"); Assert.IsTrue(tcp.ValidTCPChecksum); }
public PacketWrapper(TcpRecon tcpRecon) { Count = ++CaptureForm.packetCount; ipPacket = tcpRecon.IpPacket; rawCapture = tcpRecon.RawCapture; tcpPacket = tcpRecon.TcpPacket; Msg = tcpRecon.Msg.ToString(); }
private void PacketHandler(RawCapture packet) { totalReceived++; packets[iPacket] = packet.Data; nPackets++; if (nPackets > 100) nPackets = 100; iPacket++; if (iPacket == 100) iPacket = 0; }
/// <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); }
// icmpv6 public void VerifyPacket0(Packet p, RawCapture rawCapture) { Assert.IsNotNull(p); Console.WriteLine(p.ToString()); EthernetPacket e = (EthernetPacket)p; Assert.AreEqual(PhysicalAddress.Parse("00-A0-CC-D9-41-75"), e.SourceHwAddress); Assert.AreEqual(PhysicalAddress.Parse("33-33-00-00-00-02"), e.DestinationHwAddress); var ip = IpPacket.GetEncapsulated(p); Console.WriteLine("ip {0}", ip.ToString()); Assert.AreEqual(System.Net.IPAddress.Parse("fe80::2a0:ccff:fed9:4175"), ip.SourceAddress); Assert.AreEqual(System.Net.IPAddress.Parse("ff02::2"), ip.DestinationAddress); Assert.AreEqual(IpVersion.IPv6, ip.Version); Assert.AreEqual(IPProtocolType.ICMPV6, ip.Protocol); Assert.AreEqual(16, ip.PayloadPacket.Bytes.Length, "ip.PayloadPacket.Bytes.Length mismatch"); Assert.AreEqual(255, ip.HopLimit); Assert.AreEqual(255, ip.TimeToLive); Assert.AreEqual(0x3a, (byte)ip.NextHeader); Console.WriteLine("Failed: ip.ComputeIPChecksum() not implemented."); Assert.AreEqual(1221145299, rawCapture.Timeval.Seconds); Assert.AreEqual(453568.000, rawCapture.Timeval.MicroSeconds); }
private void PcapPorcessContext(SharpPcap.RawCapture pPacket) { //把包存起来(不论是否过滤) packet temp = new packet(pPacket); temp.index = packets.Count; PacketDotNet.Packet rPacket = PacketDotNet.Packet.ParsePacket(pPacket.LinkLayerType, pPacket.Data); bytes_persec += rPacket.Bytes.Length; packets.Add(temp); //判断是否过滤,若过滤,则调用过滤函数,否则直接显示 bool flag = true; if (applyfilter) { flag = apply_filter(temp); } if (!flag) { return; } show_pac(temp); }
private void ParseDataFrame(RawCapture raw) { var packet = PacketDotNet.Packet.ParsePacket(raw.LinkLayerType, raw.Data); var ethernetPacket = (EthernetPacket)packet; var ipv4 = (IPv4Packet)packet.PayloadPacket; var udpPacket = ethernetPacket.PayloadPacket.PayloadPacket as UdpPacket; if (udpPacket == null) return; if (_firstPacket == DateTime.MinValue) { _firstPacket = raw.Timeval.Date; } var num = ethernetPacket.DestinationHwAddress; //0 = toDrone, 1 = toControl var buffer = _buffers[ipv4.SourceAddress.Equals(_controlIp) ? 0 : 1]; buffer.AddData(udpPacket.PayloadData); Frame f = null; var numPackets = 0; do { f = buffer.ReadFrame(); if (f != null) { numPackets++; f.Time = (raw.Timeval.Date - _firstPacket).TotalSeconds; if (dumpVideo && f.Id == 125) { // Process video data ProcessVideoFrame(f); } var ev = OnFrameReceived; if (ev != null) { OnFrameReceived(this, new FrameReceivedEventArgs(f)); } } } while (f != null); if (numPackets == 1 && buffer.BytesRemaining != 0) { Debug.WriteLine("Warning: larger packet found than MTU."); } }
/* Indicates searching activity. */ private static bool SearchIn(RawCapture raw, String str) { String PacketData = ""; for (int i = 0; i < raw.Data.Length; i++) PacketData += (char)raw.Data[i]; return PacketData.Contains(str); }
/* Save packet information to a .txt file */ private void SavePacket(RawCapture raw, int index, String path) { try { TreeView temptree = new TreeView(); TextBox tempbox = new TextBox(); StreamWriter OutStream = new StreamWriter(path, true, Encoding.Unicode); OutStream.Write("-----------Packet No." + index + "--------------\r\n"); OutStream.Write("arrive time = " + raw.Timeval.Date.ToLocalTime().ToString() + "." + raw.Timeval.MicroSeconds.ToString() + "\r\n"); OutStream.Write("length= " + raw.Data.Length.ToString() + "\r\n"); OutStream.Write(PacketAnalysis.PacketDetail(ref temptree, ref tempbox, ref tempbox, raw)); OutStream.Write("\r\n------------End of Packet No." + index + "---------------\r\n"); OutStream.Write("\r\n"); OutStream.Close(); MessageBox.Show("Saved."); return; } catch (System.Exception) { MessageBox.Show("Save failed!"); return; } }
/// <summary> /// Constructor /// </summary> /// <param name="packet"> /// A <see cref="RawCapture"/> /// </param> /// <param name="device"> /// A <see cref="ICaptureDevice"/> /// </param> public CaptureEventArgs(RawCapture packet, ICaptureDevice device) { this.packet = packet; this.device = device; }
void OnPacketArrival(RawCapture packet) { // don't process any packet too short to not be valid if (packet.Data.Length <= 17) return; byte[] buffer = packet.Data; int offset = 0; int length; byte dsap, ssap, control; // Got frames send by me, not for me, not broadcast byte[] dest = Mac(buffer, offset); if (!_isOutboundPacket(dest, 0) && (dest[0] != 255)) return; offset += 6; // source address BacnetAddress Bac_source = new BacnetAddress(BacnetAddressTypes.Ethernet, 0, Mac(buffer, offset)); offset += 6; // len length = buffer[offset] * 256 + buffer[offset + 1]; offset += 2; // 3 bytes LLC hearder dsap = buffer[offset++]; ssap = buffer[offset++]; control = buffer[offset++]; length -= 3; // Bacnet content length eq. ethernet lenght minus LLC header length // don't process non-BACnet packets if (dsap != 0x82 || ssap != 0x82 || control != 0x03) return; if (MessageRecieved != null) MessageRecieved(this, buffer, HeaderLength, length, Bac_source); }
// icmp public void VerifyPacket5(Packet p, RawCapture rawCapture) { Console.WriteLine(p.ToString()); EthernetPacket e = (EthernetPacket)p; Assert.AreEqual("0016CFC91E29", e.SourceHwAddress.ToString()); Assert.AreEqual("0014BFF2EF0A", e.DestinationHwAddress.ToString()); var ip = (IpPacket)p.Extract (typeof(IpPacket)); Assert.AreEqual(System.Net.IPAddress.Parse("192.168.1.104"), ip.SourceAddress); Assert.AreEqual(System.Net.IPAddress.Parse("85.195.52.22"), ip.DestinationAddress); }
// dns public void VerifyPacket3(Packet p, RawCapture rawCapture) { Console.WriteLine(p.ToString()); EthernetPacket e = (EthernetPacket)p; Assert.AreEqual("0016CFC91E29", e.SourceHwAddress.ToString()); Assert.AreEqual("0014BFF2EF0A", e.DestinationHwAddress.ToString()); var ip = (IpPacket)p.Extract (typeof(IpPacket)); Assert.AreEqual(System.Net.IPAddress.Parse("192.168.1.172"), ip.SourceAddress); Assert.AreEqual(System.Net.IPAddress.Parse("66.189.0.29"), ip.DestinationAddress); Assert.AreEqual(IPProtocolType.UDP, ip.Protocol); Assert.AreEqual(0x7988, ((IPv4Packet)ip).CalculateIPChecksum()); var udp = (UdpPacket)p.Extract (typeof(UdpPacket)); Assert.AreEqual(3619, udp.SourcePort); Assert.AreEqual(53, udp.DestinationPort); Assert.AreEqual(47, udp.Length); Assert.AreEqual(0xbe2d, udp.Checksum); }
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 processDetails(RawCapture p) { var processing_packet = PacketDotNet.Packet.ParsePacket(p.LinkLayerType, p.Data); var ARP_packet = (ARPPacket)processing_packet.Extract(typeof(ARPPacket)); if (ARP_packet != null) { arpTreeView(ARP_packet); } var IP_packet = (IpPacket)processing_packet.Extract(typeof(IpPacket)); if (IP_packet != null) { var TCP_packet = (TcpPacket)processing_packet.Extract(typeof(TcpPacket)); if (TCP_packet != null) { tcpTreeView(IP_packet); } var UDP_packet = (UdpPacket)processing_packet.Extract(typeof(UdpPacket)); if (UDP_packet != null) { udpTreeView(IP_packet); } var ICMP_packet = (ICMPv4Packet)processing_packet.Extract(typeof(ICMPv4Packet)); if (ICMP_packet != null) { icmpTreeView(IP_packet); } var IGMP_packet = (IGMPv2Packet)processing_packet.Extract(typeof(IGMPv2Packet)); if (IGMP_packet != null) { igmpTreeView(IP_packet); } } }
//保存抓到的每个包以及每个包的七元组属性 public void savePackets(RawCapture p) { packet_save.Add(p); List<string> packet_attribute = new List<string>(); packet_attribute.Add(this.No); packet_attribute.Add(this.Time_arrival); packet_attribute.Add(this.srcIP); packet_attribute.Add(this.dstIP); packet_attribute.Add(this.protocal); packet_attribute.Add(this.Length); packet_attribute.Add(this.Info); packet_attribute.Add(this.Payload_data); attributes_save.Add(packet_attribute); }
public PacketForm(RawCapture capture) { this.rawCapture = capture; InitializeComponent(); }
public void dispatch_packet(ref RawCapture rawPacket) { byte[] src_mac = new byte[6]; byte[] dst_mac = new byte[6]; byte[] packet_data = rawPacket.Data; // copy source and destination MAC addresses from sniffed packet Buffer.BlockCopy(rawPacket.Data, 0, dst_mac, 0, 6); PhysicalAddress dstMAC = new PhysicalAddress(dst_mac); Buffer.BlockCopy(rawPacket.Data, 6, src_mac, 0, 6); PhysicalAddress srcMAC = new PhysicalAddress(src_mac); #if DEBUG xbs_messages.addDebugMessage("s> " + srcMAC + "=>" + dstMAC + "Len:" + rawPacket.Data.Length, xbs_message_sender.SNIFFER); Packet p = Packet.ParsePacket(rawPacket.LinkLayerType, rawPacket.Data); xbs_messages.addDebugMessage("s> " + p, xbs_message_sender.SNIFFER); #endif // if sniffed packet has MAC of packet we injected, discard bool is_injected_packet = false; lock (injected_macs_hash) is_injected_packet = injected_macs_hash.Contains(srcMAC.GetHashCode()); if (is_injected_packet) return; if (NAT.NAT_enabled) { #if DEBUG System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch(); stopWatch.Start(); #endif EthernetPacketType p_type = NAT.deNAT_outgoing_packet_PacketDotNet(ref packet_data, dstMAC, srcMAC); #if DEBUG stopWatch.Stop(); if (p_type == EthernetPacketType.IpV4) { xbs_sniffer_statistics.deNAT_callCount++; if (xbs_sniffer_statistics.deNAT_callCount > 1) { xbs_sniffer_statistics.deNAT_timeInCode += (UInt64)stopWatch.ElapsedTicks; UInt32 average = (UInt32)(xbs_sniffer_statistics.deNAT_timeInCode / (xbs_sniffer_statistics.deNAT_callCount - 1)); double average_ms = new TimeSpan(average).TotalMilliseconds; xbs_messages.addDebugMessage("- deNAT time: " + stopWatch.ElapsedTicks + " deNAT count: " + (xbs_sniffer_statistics.deNAT_callCount - 1) + " Total Time: " + xbs_sniffer_statistics.deNAT_timeInCode + "=> " + average + " / " + average_ms + "ms", xbs_message_sender.SNIFFER); } } p = Packet.ParsePacket(rawPacket.LinkLayerType, packet_data); xbs_messages.addDebugMessage("s> " + p, xbs_message_sender.SNIFFER); #endif } // count the sniffed packets from local xboxs xbs_sniffer_statistics.packet_count++; // find node with destination MAC Address in network and send packet xbs_node node = node_list.distributeDataPacket(dstMAC, packet_data); int srcMac_hash = srcMAC.GetHashCode(); bool pdevfilter_needs_change = false; lock (sniffed_macs_hash) { if (!sniffed_macs_hash.Contains(srcMac_hash)) { sniffed_macs_hash.Add(srcMac_hash); lock (sniffed_macs) sniffed_macs.Add(srcMAC); pdevfilter_needs_change = true; } } if (pdevfilter_needs_change) setPdevFilter(); }
static public TimeSpan TimeToTimeSpan(SharpPcap.RawCapture rawCapture) { DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0); return(rawCapture.Timeval.Date - origin); }
private void ParseDiscovery(RawCapture raw) { var packet = PacketDotNet.Packet.ParsePacket(LinkLayers.Ethernet, raw.Data); var ethernetPacket = (EthernetPacket)packet; var ipv4 = (IPv4Packet)ethernetPacket.PayloadPacket; var tcpPacket = ethernetPacket.PayloadPacket.PayloadPacket as TcpPacket; if (tcpPacket == null) return; if (tcpPacket.PayloadData.Length > 0) { var json = Encoding.ASCII.GetString(tcpPacket.PayloadData).TrimEnd(); var obj = JObject.Parse(json); if (obj["d2c_port"] != null) { _recvPort = (ushort)obj["d2c_port"]; _controlIp = ipv4.SourceAddress; Debug.WriteLine("Control at {0}:{1}", ipv4.SourceAddress, _recvPort); } else if (obj["c2d_port"] != null) { _sendPort = (ushort)obj["c2d_port"]; _droneIp = ipv4.SourceAddress; Debug.WriteLine("Drone at {0}:{1}", ipv4.SourceAddress, _sendPort); } else { Debug.WriteLine("Invalid TCP packet on port 44444"); } } if (_recvPort != 0 && _sendPort != 0) { _device.Filter = string.Format("udp dst port {0} or udp dst port {1}", _sendPort, _recvPort); _hadDiscovery = true; } }
public DAN_gui_msg parsePacket(RawCapture packet) { if (packet == null) { return null; } int wtf = DAN_gui_msg.DAN_MSG_CMD_OFFSET_WITHIN_RAW_PACKET; byte cmd = packet.Data[wtf]; //Console.WriteLine("Inspecting packet with {0} at byte[{1}]", cmd.ToString("X2"), wtf.ToString("X2")); if (packet.Data[12] == 8 && packet.Data[13] == 0 && packet.Data[14] == 0x15 && (packet.Data[DAN_gui_msg.DAN_MSG_CMD_OFFSET_WITHIN_RAW_PACKET] >= (byte)DAN_gui_msg.MSG_TYPE.RSP_READ)) { ByteArraySegment bas = new ByteArraySegment(packet.Data, EthernetFields.HeaderLength, IPv4Fields.HeaderLength); IpPacket ipPacket = new IPv4Packet(bas); DAN_gui_msg responseMessage = DAN_gui_msg.unmarshal(packet.Data); //responseMessage.print(); return responseMessage; } else { return null; } }
private void ProcessPacket(RawCapture Packet) { var tcpPacket = PacketDotNet.Packet.ParsePacket(Packet.LinkLayerType, Packet.Data) .Extract(typeof(PacketDotNet.TcpPacket)) as PacketDotNet.TcpPacket; if (tcpPacket != null) { var ipPacket = (PacketDotNet.IpPacket)tcpPacket.ParentPacket; var fromServer = ServerAddress.Equals(ipPacket.SourceAddress); var localPort = (fromServer ? tcpPacket.DestinationPort : tcpPacket.SourcePort); if (localPort != ClientPort) { if (ClientPort != 0 && Packet.Timeval.Seconds < LastPacketTime + 10) { // might be multiboxing, so let's completely ignore this packet return; } } LastPacketTime = Packet.Timeval.Seconds; var data = tcpPacket.PayloadData; var length = data.Length; // handle TCP SYN (connection started) if (tcpPacket.Syn) { if (!fromServer) { Console.WriteLine("<connection started>"); Reset(); ClientSeqNum = tcpPacket.SequenceNumber + 1; ClientPort = localPort; } else { ServerSeqNum = tcpPacket.SequenceNumber + 1; } return; } // handle TCP FIN (connection terminated) if (tcpPacket.Fin && State != -1) { Console.WriteLine("<connection terminated>"); Reset(); return; } // early exit if no data if (length == 0) return; // initial packet (state: -1) if (State == -1) { // check for "01 00 00 00" if (length == 4 && BitConverter.ToUInt32(data, 0) == 0x01) { ServerSeqNum = tcpPacket.SequenceNumber + 4; State = 0; } return; } if (fromServer) { while (tcpPacket != null) { if (tcpPacket.SequenceNumber > ServerSeqNum) { Console.WriteLine("out-of-order packet {0} (expected {1}) :: queue -> {2}", tcpPacket.SequenceNumber, ServerSeqNum, TcpBuffer.Count + 1); TcpBuffer.Enqueue(tcpPacket, tcpPacket.SequenceNumber); return; } data = tcpPacket.PayloadData; length = data.Length; // check for old seq int rewind = (int)(ServerSeqNum - tcpPacket.SequenceNumber); if (rewind > 0) { // seq in past? if (length - rewind <= 0) { // no additional data? Console.Write("duplicate packet {0}, dropping :: queue -> {1}", tcpPacket.SequenceNumber, TcpBuffer.Count); if (TcpBuffer.Count > 0) Console.Write(", next = {0}", TcpBuffer.Peek().SequenceNumber); Console.WriteLine(); tcpPacket = (TcpBuffer.Count > 0) ? TcpBuffer.Dequeue() : null; continue; } // catch up length -= rewind; Console.Write("catching up, +{0} bytes :: queue -> {1}", length, TcpBuffer.Count); if (TcpBuffer.Count > 0) Console.Write(", next = {0}", TcpBuffer.Peek().SequenceNumber); Console.WriteLine(); Array.Copy(data, rewind, data, 0, length); Array.Resize(ref data, length); } // advance expected sequence number ServerSeqNum += (uint)length; // add to server buffer if (State == 2) Session.Encrypt(ref data); AppendBuffer(ref ServerBuffer, data); // get next packet in queue tcpPacket = (TcpBuffer.Count > 0) ? TcpBuffer.Dequeue() : null; if (tcpPacket != null) { Console.Write("fetching buffered packet :: queue -> {0}", TcpBuffer.Count); if (TcpBuffer.Count > 0) Console.Write(", next = {0}", TcpBuffer.Peek().SequenceNumber); Console.WriteLine(); } } while (ProcessServerData()); } else { if (tcpPacket.SequenceNumber < ClientSeqNum) { uint rewind = ClientSeqNum - tcpPacket.SequenceNumber; if (length <= rewind) return; length -= (int)rewind; Array.Copy(data, rewind, data, 0, length); Array.Resize(ref data, length); } ClientSeqNum += (uint)length; if (State == 2) Session.Decrypt(ref data); AppendBuffer(ref ClientBuffer, data); while (ProcessClientData()); } } }
private CustomerPacket AchieiveNewPacket(RawCapture packet) { string source = ""; string destination = ""; string protocol = ""; string info = ""; var currentPacket = PacketDotNet.Packet.ParsePacket(packet.LinkLayerType, packet.Data); var tempPacket = currentPacket; while (tempPacket.PayloadPacket != null) { tempPacket = tempPacket.PayloadPacket; } if (tempPacket is PacketDotNet.ApplicationPacket) { var applicationPacket = tempPacket as PacketDotNet.ApplicationPacket; string headerString = ""; for (int index = 12; index <= 15; ++index) { if (index == 12) { headerString += (char)(ConvertString2Int(applicationPacket.Header[index].ToString())); } headerString += (char)(ConvertString2Int(applicationPacket.Header[index].ToString())); } if (headerString.CompareTo("HTTP") == 0) { protocol = "HTTP"; } else if (applicationPacket.ParentPacket is PacketDotNet.UdpPacket) { protocol = "UDP"; } else { protocol = "TCP"; } var ipPacket = tempPacket.ParentPacket.ParentPacket as PacketDotNet.IpPacket; source = ipPacket.SourceAddress.ToString(); destination = ipPacket.DestinationAddress.ToString(); } else if (tempPacket is PacketDotNet.TcpPacket) { protocol = "TCP"; var ipPacket = tempPacket.ParentPacket as PacketDotNet.IpPacket; source = ipPacket.SourceAddress.ToString(); destination = ipPacket.DestinationAddress.ToString(); var tcpPacket = tempPacket as PacketDotNet.TcpPacket; if ((tcpPacket.DestinationPort.ToString().CompareTo("80") == 0) || (tcpPacket.DestinationPort.ToString().CompareTo("8080") == 0)) { protocol = "HTTP"; } else if (tcpPacket.DestinationPort.ToString().CompareTo("1900") == 0) { protocol = "SSDP"; } } else if (tempPacket is PacketDotNet.UdpPacket) { protocol = "UDP"; var ipPacket = tempPacket.ParentPacket as PacketDotNet.IpPacket; source = ipPacket.SourceAddress.ToString(); destination = ipPacket.DestinationAddress.ToString(); var udpPacket = tempPacket as PacketDotNet.UdpPacket; if (udpPacket.DestinationPort.ToString().CompareTo("80") == 0 || udpPacket.DestinationPort.ToString().CompareTo("8080") == 0) { protocol = "HTTP"; } else if (udpPacket.DestinationPort.ToString().CompareTo("1900") == 0) { protocol = "SSDP"; } } else if (tempPacket is PacketDotNet.IpPacket) { if (tempPacket is PacketDotNet.IPv4Packet) { protocol = "Ipv4"; } else { protocol = "Ipv6"; } var ipPacket = tempPacket as PacketDotNet.IpPacket; source = ipPacket.SourceAddress.ToString(); destination = ipPacket.DestinationAddress.ToString(); } else if (tempPacket is PacketDotNet.ARPPacket) { var arpPacket = tempPacket as PacketDotNet.ARPPacket; source = arpPacket.SenderHardwareAddress.ToString(); destination = arpPacket.TargetHardwareAddress.ToString(); protocol = "ARP"; //info = System.Text.Encoding.ASCII.GetString(arpPacket.Bytes); } else if (tempPacket is PacketDotNet.EthernetPacket) { var ethernetPacket = tempPacket as PacketDotNet.EthernetPacket; source = ethernetPacket.SourceHwAddress.ToString(); destination = ethernetPacket.DestinationHwAddress.ToString(); protocol = "Ethernet"; //info = System.Text.Encoding.ASCII.GetString(arpPacket.Bytes); } else if (tempPacket.ParentPacket is PacketDotNet.IpPacket) { var ipPacket = tempPacket.ParentPacket as PacketDotNet.IpPacket; System.Net.IPAddress srcIp = ipPacket.SourceAddress; System.Net.IPAddress dstIp = ipPacket.DestinationAddress; source = srcIp.ToString(); destination = dstIp.ToString(); protocol = ipPacket.Protocol.ToString(); //ipPacket.Bytes } else if (tempPacket.ParentPacket is PacketDotNet.TcpPacket) { var tcpPacket = tempPacket.ParentPacket as PacketDotNet.TcpPacket; source = ((PacketDotNet.IpPacket)tcpPacket.ParentPacket).SourceAddress.ToString(); destination = ((PacketDotNet.IpPacket)tcpPacket.ParentPacket).DestinationAddress.ToString(); protocol = ((PacketDotNet.IpPacket)tcpPacket.ParentPacket).Protocol.ToString(); } else if (tempPacket.ParentPacket is PacketDotNet.UdpPacket) { var udpPacket = tempPacket.ParentPacket as PacketDotNet.UdpPacket; source = ((PacketDotNet.IpPacket)udpPacket.ParentPacket).SourceAddress.ToString(); destination = ((PacketDotNet.IpPacket)udpPacket.ParentPacket).DestinationAddress.ToString(); protocol = ((PacketDotNet.IpPacket)udpPacket.ParentPacket).Protocol.ToString(); } else if (tempPacket.ParentPacket is PacketDotNet.EthernetPacket) { var ethernetPacket = tempPacket.ParentPacket as PacketDotNet.EthernetPacket; source = ethernetPacket.SourceHwAddress.ToString(); destination = ethernetPacket.DestinationHwAddress.ToString(); protocol = ethernetPacket.Type.ToString(); } return new CustomerPacket((PacketCount++).ToString(), packet.Timeval.ToString(), source, destination, protocol, packet.Data.Length.ToString(), info); }
// arp public void VerifyPacket4(Packet p, RawCapture rawCapture) { Console.WriteLine(p.ToString()); EthernetPacket e = (EthernetPacket)p; Assert.AreEqual("0018F84B17A0", e.SourceHwAddress.ToString()); Assert.AreEqual("FFFFFFFFFFFF", e.DestinationHwAddress.ToString()); }
/* Parses raw captured packets into ListView in columns. */ public static void PacketParse(ref ListView list, RawCapture raw, int cnt) { /* Column properties: number, time, protocol, source, destination, content. */ ListViewItem newItem = new ListViewItem(); newItem.SubItems[0].Text = (cnt - 1).ToString(); newItem.SubItems.Add(raw.Timeval.Date.ToLocalTime().ToString() + '.' + raw.Timeval.MicroSeconds.ToString()); /* Analyzes Link Layers information, and gets a EthernetPacket. */ var packet = PacketDotNet.Packet.ParsePacket(raw.LinkLayerType, raw.Data); if (packet != null) { /* Uses PayloadPacket to identify packet protocol, thus leveraging different parsing solutions. */ if (packet.PayloadPacket is ARPPacket)// is ARP. { string ARPPacketSource; string ARPPacketTarget; string ARPPacketProtocol; ARPPacket arpPacket = (ARPPacket)packet.Extract(typeof(ARPPacket)); try { ARPPacketSource = arpPacket.SenderHardwareAddress.ToString(); } catch (Exception) { ARPPacketSource = ""; } try { ARPPacketTarget = arpPacket.TargetHardwareAddress.ToString(); } catch (Exception) { ARPPacketTarget = ""; } try { ARPPacketProtocol = arpPacket.SenderProtocolAddress.ToString(); } catch (Exception) { ARPPacketProtocol = ""; } newItem.SubItems.Add(ARPPacketSource); newItem.SubItems.Add(ARPPacketTarget); newItem.SubItems.Add("ARP"); if (arpPacket.Operation == ARPOperation.Request) newItem.SubItems.Add(ARPPacketSource + " ask for " + arpPacket.TargetProtocolAddress.ToString() + "'s MAC address"); else if (arpPacket.Operation == ARPOperation.Response) newItem.SubItems.Add(ARPPacketProtocol + "'s MAC address is " + ARPPacketSource); else newItem.SubItems.Add(""); newItem.BackColor = Color.Orchid; list.Items.Add(newItem);// Merges all subitems and create a new item to the trail of ListView. return; } else if (packet.PayloadPacket.PayloadPacket is TcpPacket)// is TCP, possibly segmented. { TcpPacket tcpPacket = (TcpPacket)packet.Extract(typeof(TcpPacket)); IpPacket ipPacket = (IpPacket)tcpPacket.ParentPacket;// TCP/UDP/ICMP/IGMP's src. & dst. information is covered in its IP header. newItem.SubItems.Add(ipPacket.SourceAddress.ToString()); newItem.SubItems.Add(ipPacket.DestinationAddress.ToString()); newItem.SubItems.Add("TCP"); try { newItem.SubItems.Add("Src.Port: " + tcpPacket.SourcePort.ToString() + " ---> Dst.Port: " + tcpPacket.DestinationPort.ToString()); } catch (Exception) { newItem.SubItems.Add("TCP segment or incomplete header"); } newItem.BackColor = Color.Lavender; list.Items.Add(newItem); return; } else if (packet.PayloadPacket.PayloadPacket is UdpPacket)// is UDP, possibly segmented. { UdpPacket udpPacket = (UdpPacket)packet.Extract(typeof(UdpPacket)); IpPacket ipPacket = (IpPacket)udpPacket.ParentPacket;// TCP/UDP/ICMP/IGMP's src. & dst. information is covered in its IP header. newItem.SubItems.Add(ipPacket.SourceAddress.ToString()); newItem.SubItems.Add(ipPacket.DestinationAddress.ToString()); newItem.SubItems.Add("UDP"); try { newItem.SubItems.Add("Src.Port: " + udpPacket.SourcePort.ToString() + " ---> Dst.Port: " + udpPacket.DestinationPort.ToString()); } catch (Exception) { newItem.SubItems.Add("TCP segment or incomplete header"); } newItem.BackColor = Color.Ivory; list.Items.Add(newItem); return; } else if (packet.PayloadPacket is IGMPv2Packet)// is IGMP, possibly segmented. { IGMPv2Packet igmpPacket = (IGMPv2Packet)packet.Extract(typeof(IGMPv2Packet)); IpPacket ipPacket = (IpPacket)packet.Extract(typeof(IpPacket));// TCP/UDP/ICMP/IGMP's src. & dst. information is covered in its IP header. newItem.SubItems.Add(ipPacket.SourceAddress.ToString()); newItem.SubItems.Add(ipPacket.DestinationAddress.ToString()); newItem.SubItems.Add("IGMP"); try { newItem.SubItems.Add(igmpPacket.Type.ToString()); } catch (Exception) { newItem.SubItems.Add("IGMP segment or incomplete header"); } newItem.BackColor = Color.LightBlue; list.Items.Add(newItem); return; } else if (packet.PayloadPacket is ICMPv4Packet)// is ICMPv4, possibly segmented. { ICMPv4Packet icmpv4Packet = (ICMPv4Packet)packet.Extract(typeof(ICMPv4Packet)); IPv4Packet ipPacket = (IPv4Packet)icmpv4Packet.ParentPacket;// TCP/UDP/ICMP/IGMP's src. & dst. information is covered in its IP header. newItem.SubItems.Add(ipPacket.SourceAddress.ToString()); newItem.SubItems.Add(ipPacket.DestinationAddress.ToString()); newItem.SubItems.Add("ICMPv4"); if ((ipPacket.FragmentFlags / 2 == 0) && (ipPacket.FragmentOffset != 0)) newItem.SubItems.Add("ICMP segment"); else newItem.SubItems.Add(icmpv4Packet.TypeCode.ToString()); newItem.BackColor = Color.Wheat; list.Items.Add(newItem); return; } else if (packet.PayloadPacket.PayloadPacket is ICMPv6Packet)// is ICMPv6, possibly segmented. { ICMPv6Packet icmpv6Packet = (ICMPv6Packet)packet.Extract(typeof(ICMPv6Packet)); IpPacket ipPacket = (IpPacket)icmpv6Packet.ParentPacket;// TCP/UDP/ICMP/IGMP's src. & dst. information is covered in its IP header. newItem.SubItems.Add(ipPacket.SourceAddress.ToString()); newItem.SubItems.Add(ipPacket.DestinationAddress.ToString()); newItem.SubItems.Add("ICMPv6"); newItem.SubItems.Add("//PacketAnalysis.ICMPv6msgAnalyzor((int)icmpv6Packet.Header[0])"); newItem.BackColor = Color.GreenYellow; list.Items.Add(newItem); return; } else if (packet.PayloadPacket is IpPacket)// is IP except above protocols. { IpPacket ippacket = (IpPacket)packet.Extract(typeof(IpPacket)); newItem.SubItems.Add(ippacket.SourceAddress.ToString()); newItem.SubItems.Add(ippacket.DestinationAddress.ToString()); newItem.SubItems.Add("IP"); newItem.SubItems.Add("Not TCP or UDP or ICMP or IGMP"); newItem.BackColor = Color.Gray; list.Items.Add(newItem); return; } else// Irrecognizable protocol packet. { newItem.SubItems.Add("xxxx"); newItem.SubItems.Add("xxxx"); newItem.SubItems.Add("xxxx"); newItem.SubItems.Add("xxxx"); newItem.BackColor = Color.Empty; list.Items.Add(newItem); return; } } }
/// <summary> /// Send a raw packet through this device /// </summary> /// <param name="device"></param> /// <param name="p"></param> /// <param name="header"></param> public static void SendPacket(this IInjectionDevice device, RawCapture p, ICaptureHeader header = null) { device.SendPacket(new ReadOnlySpan <byte>(p.Data), header); }
// udp public void VerifyPacket2(Packet p, RawCapture rawCapture) { Console.WriteLine(p.ToString()); EthernetPacket e = (EthernetPacket)p; Assert.AreEqual("0014BFF2EF0A", e.SourceHwAddress.ToString()); Assert.AreEqual("0016CFC91E29", e.DestinationHwAddress.ToString()); var ip = (IpPacket)p.Extract (typeof(IpPacket)); Assert.AreEqual(System.Net.IPAddress.Parse("172.210.164.56"), ip.SourceAddress); Assert.AreEqual(System.Net.IPAddress.Parse("192.168.1.104"), ip.DestinationAddress); Assert.AreEqual(IpVersion.IPv4, ip.Version); Assert.AreEqual(IPProtocolType.UDP, ip.Protocol); Assert.AreEqual(112, ip.TimeToLive); Assert.AreEqual(0xe0a2, ((IPv4Packet)ip).CalculateIPChecksum()); Assert.AreEqual(1171483602, rawCapture.Timeval.Seconds); Assert.AreEqual(578641.000, rawCapture.Timeval.MicroSeconds); var udp = (UdpPacket)p.Extract(typeof(UdpPacket)); Assert.AreEqual(52886, udp.SourcePort); Assert.AreEqual(56924, udp.DestinationPort); Assert.AreEqual(71, udp.Length); Assert.AreEqual(0xc8b8, udp.Checksum); }
private bool _ParsePacket(RawCapture r, OPacket p) { Packet packet = PacketDotNet.Packet.ParsePacket(r.LinkLayerType, r.Data); IpPacket ip = PacketDotNet.IpPacket.GetEncapsulated(packet); if (null == ip) { return false; } p.SetSourceIP(ip.SourceAddress.ToString()); p.SetDestinationIP(ip.DestinationAddress.ToString()); p.SetLength(r.Data.Length); p.SetTimeCollected(r.Timeval.Seconds); TcpPacket tcp = PacketDotNet.TcpPacket.GetEncapsulated(packet); if (null != tcp) { p.SetProtocol(tcp.DestinationPort); return true; } // UdpPacket udp = PacketDotNet.UdpPacket.GetEncapsulated(packet); // if (null != udp) // { // p.SetProtocol(udp.DestinationPort); // return true; // } return false; }
private void ViewBody_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { int selectedIndex = this.ViewBody.SelectedIndex; if (selectedIndex == -1) { return; } this.selectedRawCapture = this.rawCapturesList[selectedIndex]; ShowTreeViewWithThirdBoard(); }
public PacketWrapper(int count, RawCapture p) { this.Count = count; this.p = p; }
private void Init() { this.PacketCount = 0; this.device = null; this.continueGetPacket = false; this.filterRule = ""; this.canStopListening = false; this.selectedRawCapture = null; this.captureMode = 1;//default is p mode, 0 is normal mode. 1 is p mode }
/* Parses details into TreeView and TextBox. */ public static string PacketDetail(ref TreeView tree, ref TextBox box, ref TextBox data, RawCapture raw) { tree.Nodes.Clear(); box.Clear(); Packet packet = PacketDotNet.Packet.ParsePacket(raw.LinkLayerType, raw.Data); string info = ""; if (packet.Header.Length == 14) info += EthernetAnalyzor(ref tree, packet); else { TreeNode EtherNode = new TreeNode("unsupport ethernet protocol!"); return info += "unsupport ethernet protocol!\r\n"; } /* Parses upper layer protocols. */ if (packet.PayloadPacket is IPv4Packet) { IPv4Packet ipv4Packet = (IPv4Packet)packet.Extract(typeof(IPv4Packet)); info += IPv4Analyzor(ref tree, ipv4Packet); } else if (packet.PayloadPacket is IPv6Packet) { IPv6Packet ipv6Packet = (IPv6Packet)packet.Extract(typeof(IPv6Packet)); info += IPv6Analyzor(ref tree, ipv6Packet); } else if (packet.PayloadPacket is ARPPacket) { ARPPacket arppacket = (ARPPacket)packet.Extract(typeof(ARPPacket)); info += ARPAnalyzor(ref tree, arppacket); } else { tree.Nodes.Add("Unable to analyze!"); return info += "Unable to analyze!\r\n"; } /* Parses network layer protocols. */ if (packet.PayloadPacket.PayloadPacket is ICMPv4Packet) { ICMPv4Packet icmpv4packet = (ICMPv4Packet)packet.Extract(typeof(ICMPv4Packet)); info += ICMPv4Analyzor(ref tree, icmpv4packet); } else if (packet.PayloadPacket.PayloadPacket is ICMPv6Packet) { ICMPv6Packet icmpv6packet = (ICMPv6Packet)packet.Extract(typeof(ICMPv6Packet)); info += ICMPv6Analyzor(ref tree, icmpv6packet); } else if (packet.PayloadPacket.PayloadPacket is IGMPv2Packet) { IGMPv2Packet igmpv2packet = (IGMPv2Packet)packet.Extract(typeof(IGMPv2Packet)); info += IGMPv2Analyzor(ref tree, igmpv2packet); } else if (packet.PayloadPacket.PayloadPacket is TcpPacket) { TcpPacket tcppacket = (TcpPacket)packet.Extract(typeof(TcpPacket)); info += TCPAnalyzor(ref tree, tcppacket); } else if (packet.PayloadPacket.PayloadPacket is UdpPacket) { UdpPacket udppacket = (UdpPacket)packet.Extract(typeof(UdpPacket)); info += UDPAnalyzor(ref tree, udppacket); } /* Print packet's hex and ascii informations in the TextBox. */ if (packet != null) { if (packet.PayloadPacket.PayloadPacket is TcpPacket) { byte[] tmp = packet.PayloadPacket.PayloadPacket.PayloadData; string str = System.Text.Encoding.Default.GetString(tmp); data.Text = str; } else data.Text = "No readable data!"; box.Text = packet.PrintHex(); info += "\r\n----------Hex & ASCII Information--------\r\n"; info += packet.PrintHex(); } else { box.Text = "A bad packet!"; info += "A bad packet!\r\n"; } return info;// info contains all packet information and serves to write .txt file for saving. }