public void IcmpPacketCapture(object sender, CaptureEventArgs e) //Packet capture and return to string (async) { RawCapture capturePacket = e.Packet; try { if (this.NowCaptureNum <= this.CaptureNum) { var packet = PacketDotNet.Packet.ParsePacket(capturePacket.LinkLayerType, capturePacket.Data); IpPacket ipPacket = (IpPacket)packet.Extract(typeof(PacketDotNet.IpPacket)); if (ipPacket.Version != IpVersion.IPv4 || ipPacket.Protocol != IPProtocolType.ICMP) { return; } ICMPv4Packet icmpPacket = (ICMPv4Packet)ipPacket.Extract(typeof(PacketDotNet.ICMPv4Packet)); this.NowCaptureNum++; ResultData += "Header:" + icmpPacket.Header + "\n"; int i = 1; if (icmpPacket.PayloadData != null) { foreach (byte data in icmpPacket.PayloadData) { ResultData += Convert.ToString(data, 16) + " "; if (i % 8 == 0) { ResultData += "\n"; } i++; } } ResultData += "\n--------------------------------------------\n"; if (this.NowCaptureNum == this.CaptureNum) { StopPacketCapture(); } SendPacketData(); } else { StopPacketCapture(); //PacketCaptureDevice.Close(); CaptureEndEvent(); } } catch (NullReferenceException nullException) { Console.WriteLine(nullException.StackTrace); MessageBox.Show("Can't packet extracted. \n Are you set others protocol in filter?" , "Warining", System.Windows.MessageBoxButton.OK); StopPacketCapture(); //PacketCaptureDevice.Close(); } }
private void ipNext(IpPacket ip) { switch (ip.NextHeader) { case IPProtocolType.TCP: TcpPacket tcp = (TcpPacket)ip.Extract(typeof(TcpPacket)); TCP(tcp); break; case IPProtocolType.UDP: UdpPacket udp = (UdpPacket)ip.Extract(typeof(UdpPacket)); UDP(udp); break; case IPProtocolType.ICMP: ICMPv4Packet icmp = (ICMPv4Packet)ip.Extract(typeof(ICMPv4Packet)); ICMP(icmp); break; case IPProtocolType.ICMPV6: ICMPv6Packet icmpv6 = (ICMPv6Packet)ip.Extract(typeof(ICMPv6Packet)); ICMPv6(icmpv6); break; case IPProtocolType.IGMP: break; default: break; } }
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 { } }
public void Get() { var icmpv4Packet = new ICMPv4Packet { Bytes = new Byte[32] }; icmpv4Packet.SetBytes(6, 2, new Byte[] { 0x00, 0x11 }); icmpv4Packet.Sequence.Should().Be(17); }
public void Set() { var icmpv4Packet = new ICMPv4Packet { Bytes = new Byte[32] }; icmpv4Packet.Sequence = 17; icmpv4Packet.Sequence.Should().Be(17); }
public void Get(Byte[] input, ICMPv4TypeCode expected) { var icmpv4Packet = new ICMPv4Packet { Bytes = new Byte[32] }; icmpv4Packet.SetBytes(0, 2, input); icmpv4Packet.TypeCode.Should().Be(expected); }
public void Set(Byte[] expected, ICMPv4TypeCode input) { var icmpv4Packet = new ICMPv4Packet { Bytes = new Byte[32] }; icmpv4Packet.TypeCode = input; icmpv4Packet.GetBytes(0, 2).ToArray().Should().Equal(expected); icmpv4Packet.TypeCode.Should().Be(input); }
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"; } }
public void Get() { var icmpv4Packet = new ICMPv4Packet { Bytes = new Byte[32] }; icmpv4Packet.SetBytes(2, 2, new Byte[] { 0x4d, 0x4a }); icmpv4Packet.Checksum.Should().Be(19786); }
public void Set() { var icmpv4Packet = new ICMPv4Packet { Bytes = new Byte[32] }; icmpv4Packet.Checksum = 19786; icmpv4Packet.Checksum.Should().Be(19786); }
public void Get() { var icmpv4Packet = new ICMPv4Packet { Bytes = new Byte[32] }; icmpv4Packet.SetBytes(4, 2, new Byte[] { 0x00, 0x01 }); icmpv4Packet.Id.Should().Be(1); }
public void Set() { var icmpv4Packet = new ICMPv4Packet { Bytes = new Byte[32] }; icmpv4Packet.Id = 1; icmpv4Packet.Id.Should().Be(1); }
private void ICMPv4(ICMPv4Packet v4) { if (ICMPv4Node == null) { ICMPv4Node = CreatNode("ICMPv4", 4); } ICMPv4Node.Nodes.Clear(); ICMPv4Node.Nodes.Add("Type/Code: " + v4.TypeCode.ToString() + " [0x" + v4.TypeCode.ToString("X") + "]"); ICMPv4Node.Nodes.Add("Checksum: 0x" + v4.Checksum.ToString("X")); ICMPv4Node.Nodes.Add("Identifier: " + v4.ID.ToString("d") + " [0x" + v4.ID.ToString("X") + "]"); ICMPv4Node.Nodes.Add("Sequence Number: " + v4.Sequence.ToString() + " [0x" + v4.Sequence.ToString("X") + "]"); Tree.Nodes.Add(ICMPv4Node); }
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; } }
private void ICMP(ICMPv4Packet icmp) { if (ICMPv4Node == null) { ICMPv4Node = new TreeNode(); } ICMPv4Node.Nodes.Clear(); ICMPv4Node.Text = string.Format("Internet Control Message Protocol v4"); ICMPv4Node.Nodes.Add(string.Format("Type/Code: {0}", icmp.TypeCode)); ICMPv4Node.Nodes.Add(string.Format("Sequence Number: {0}", icmp.Sequence)); ICMPv4Node.Nodes.Add(string.Format("Identification: {0}", icmp.ID)); ICMPv4Node.Nodes.Add(string.Format("Checksum: {0}", icmp.Checksum)); //ICMPv6Node.Nodes.Add(string.Format("")); //ICMPv6Node.Nodes.Add(string.Format("")); tree.Nodes.Add(ICMPv4Node); }
public void BinarySerialization() { var dev = new CaptureFileReaderDevice("../../CaptureFiles/ICMPv4.pcap"); dev.Open(); RawCapture rawCapture; Boolean foundicmp = false; while ((rawCapture = dev.GetNextPacket()) != null) { Packet p = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data); var icmp = (ICMPv4Packet)p.Extract(typeof(ICMPv4Packet)); if (icmp == null) { continue; } foundicmp = true; var memoryStream = new MemoryStream(); BinaryFormatter serializer = new BinaryFormatter(); serializer.Serialize(memoryStream, icmp); memoryStream.Seek(0, SeekOrigin.Begin); BinaryFormatter deserializer = new BinaryFormatter(); ICMPv4Packet fromFile = (ICMPv4Packet)deserializer.Deserialize(memoryStream); Assert.AreEqual(icmp.Bytes, fromFile.Bytes); Assert.AreEqual(icmp.BytesHighPerformance.Bytes, fromFile.BytesHighPerformance.Bytes); Assert.AreEqual(icmp.BytesHighPerformance.BytesLength, fromFile.BytesHighPerformance.BytesLength); Assert.AreEqual(icmp.BytesHighPerformance.Length, fromFile.BytesHighPerformance.Length); Assert.AreEqual(icmp.BytesHighPerformance.NeedsCopyForActualBytes, fromFile.BytesHighPerformance.NeedsCopyForActualBytes); Assert.AreEqual(icmp.BytesHighPerformance.Offset, fromFile.BytesHighPerformance.Offset); Assert.AreEqual(icmp.Checksum, fromFile.Checksum); Assert.AreEqual(icmp.Color, fromFile.Color); Assert.AreEqual(icmp.Data, fromFile.Data); Assert.AreEqual(icmp.HeaderData, fromFile.HeaderData); Assert.AreEqual(icmp.ID, fromFile.ID); Assert.AreEqual(icmp.PayloadData, fromFile.PayloadData); Assert.AreEqual(icmp.Sequence, fromFile.Sequence); Assert.AreEqual(icmp.TypeCode, fromFile.TypeCode); } dev.Close(); Assert.IsTrue(foundicmp, "Capture file contained no icmp packets"); }
public void echo_request() { var icmpv4 = new ICMPv4Packet { Bytes = new Byte[] { 0x08, 0x00, 0x4d, 0x4a, 0x00, 0x01, 0x00, 0x11, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69 } }; icmpv4.TypeCode.Should().Be(ICMPv4TypeCode.EchoRequest); icmpv4.Checksum.Should().Be(19786); icmpv4.Id.Should().Be(1); icmpv4.Sequence.Should().Be(17); }
public void analyzuj(Rozhranie rozhranie, EthernetPacket eth, Packet paket) { if (eth.Type.ToString().Equals("Arp")) { IPAddress odosielatel_adres = new IPAddress(paket.Bytes.Skip(28).Take(4).ToArray()); IPAddress ciel_adres = new IPAddress(paket.Bytes.Skip(38).Take(4).ToArray()); if (ciel_adres.ToString().Equals("255.255.255.255") || ciel_adres.ToString().Equals(rozhranie.ip_adresa)) { if (paket.Bytes[21] == 1) { arp_reply(eth, rozhranie, odosielatel_adres, ciel_adres); //dosla mi request tak odpovedam } else if (paket.Bytes[21] == 2 && !eth.SourceHwAddress.ToString().Equals("02004C4F4F50")) //IGNORUJEM LOOPBACK { bool pridaj_arp_zaznam = true; arp = new Arp(odosielatel_adres.ToString(), eth.SourceHwAddress.ToString(), arp_casovac); foreach (var zaznam in arp_tabulka) { if (zaznam.ip.Equals(arp.ip) && zaznam.mac.Equals(arp.mac)) { zaznam.casovac = arp_casovac; pridaj_arp_zaznam = false; } if (zaznam.ip.Equals(arp.ip)) { pridaj_arp_zaznam = false; } } if (pridaj_arp_zaznam) { arp_tabulka.Add(arp); } } } else { if (paket.Bytes[21] == 1) // PROXY ARP { Smerovaci_zaznam naslo_zaznam = null; naslo_zaznam = najdi_zaznam_v_smerovacej_tabulke(ciel_adres); if (naslo_zaznam != null && naslo_zaznam.exit_interface == -1) { string via = null; naslo_zaznam = rekurzivne_prehladanie(naslo_zaznam, ref via); } if (naslo_zaznam != null && naslo_zaznam.exit_interface != -1 && (rozhranie.cislo_rozhrania != naslo_zaznam.exit_interface)) { arp_reply(eth, rozhranie, odosielatel_adres, ciel_adres); } } } } else if (eth.Type.ToString().Equals("IpV4")) { if ((--paket.Bytes[22]) > 0) { IPAddress odosielatel_address = new IPAddress(paket.Bytes.Skip(26).Take(4).ToArray()); IPAddress ciel_adres = new IPAddress(paket.Bytes.Skip(30).Take(4).ToArray()); Smerovaci_zaznam smerovaci_zaznam = null; string via = null; IPv4Packet ip_pak = (IPv4Packet)eth.PayloadPacket; ip_pak.UpdateIPChecksum(); if ((ciel_adres.ToString() == rozhranie1.ip_adresa || ciel_adres.ToString() == rozhranie2.ip_adresa) && (int)eth.Bytes[23] == 1) { ICMPv4Packet ping = (ICMPv4Packet)ip_pak.PayloadPacket; if ((int)eth.Bytes[34] == 8) { ping.Checksum = 0; ping.TypeCode = ICMPv4TypeCodes.EchoReply; byte[] bytes = BitConverter.GetBytes(GetCrc(ping.Bytes)); Array.Reverse(bytes); ushort result = BitConverter.ToUInt16(bytes, 0); ping.Checksum = result; ip_pak.SourceAddress = ciel_adres; ip_pak.DestinationAddress = odosielatel_address; ip_pak.PayloadPacket = ping; ip_pak.UpdateIPChecksum(); eth.PayloadPacket = ip_pak; smerovaci_zaznam = najdi_zaznam_v_smerovacej_tabulke(odosielatel_address); if (smerovaci_zaznam != null && smerovaci_zaznam.exit_interface == -1) { smerovaci_zaznam = rekurzivne_prehladanie(smerovaci_zaznam, ref via); } if (smerovaci_zaznam != null && smerovaci_zaznam.exit_interface != -1 && smerovaci_zaznam.next_hop != "X") { via = smerovaci_zaznam.next_hop; } if (smerovaci_zaznam != null) { if (smerovaci_zaznam.exit_interface == 2) { rozhranie = rozhranie2; } if (smerovaci_zaznam.exit_interface == 1) { rozhranie = rozhranie1; } Thread posielanie = new Thread(() => preposli(rozhranie, eth, smerovaci_zaznam, via, odosielatel_address)); posielanie.Start(); } } else if ((int)eth.Bytes[34] == 0) { if (zapis_ping) { // main_view.vypis("!", 99); main_view.lbl_ping += "!"; zapis_ping = false; } } } else if ((ciel_adres.ToString() == rozhranie.ip_adresa || ciel_adres.ToString() == "224.0.0.9") && ((int)eth.Bytes[43] == 2)) { spracuj_rip(eth, paket, rozhranie, odosielatel_address); } else { smerovaci_zaznam = najdi_zaznam_v_smerovacej_tabulke(ciel_adres); if (smerovaci_zaznam != null && smerovaci_zaznam.exit_interface == -1) { smerovaci_zaznam = rekurzivne_prehladanie(smerovaci_zaznam, ref via); } if (smerovaci_zaznam != null && smerovaci_zaznam.exit_interface != -1 && smerovaci_zaznam.next_hop != "X") { via = smerovaci_zaznam.next_hop; } if (smerovaci_zaznam != null) { if (smerovaci_zaznam.exit_interface == 1) { rozhranie = rozhranie1; } if (smerovaci_zaznam.exit_interface == 2) { rozhranie = rozhranie2; } Thread posielanie = new Thread(() => preposli(rozhranie, eth, smerovaci_zaznam, via, ciel_adres)); posielanie.Start(); } } } } if (zastav_vlakno) { rozhranie.adapter.Close(); } }
public ICMPv4Header(ICMPv4Packet icmpv4Packet) { _icmpv4Packet = icmpv4Packet; }
private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e) { string protocol = e.Item.SubItems[4].Text; int key = int.Parse(e.Item.SubItems[0].Text); bool getPacket = capturedPackets_list.TryGetValue(key, out Packet packet); switch (protocol) { case "TCP": if (getPacket) { TcpPacket tcpPacket = (TcpPacket)packet.Extract(typeof(TcpPacket)); if (tcpPacket != null) { string Data = PrintBytes(tcpPacket.Bytes).Replace(PrintBytes(tcpPacket.Header) + ",", ""); if (!string.IsNullOrEmpty(TargetIP) && Data.Length > 1) { textBox2.Text = ""; textBox2.Text = PacketDecrypt(Data); } else { int srcPort = tcpPacket.SourcePort; int dstPort = tcpPacket.DestinationPort; ushort checksum = tcpPacket.Checksum; textBox2.Text = ""; textBox2.Text = "Packet number: " + key + " Type: TCP" + "\r\nSource port: " + srcPort + "\r\nDestination port: " + dstPort + "\r\nTCP header size: " + tcpPacket.DataOffset + "\r\nWindow size: " + tcpPacket.WindowSize + // bytes that the receiver is willing to receive //"\r\nChecksum:" + checksum.ToString() + (tcpPacket.ValidChecksum ? ",valid" : ",invalid") + //"\r\nTCP checksum: " + (tcpPacket.ValidTCPChecksum ? ",valid" : ",invalid") + //"\r\nSequence number: " + tcpPacket.SequenceNumber.ToString() + //"\r\nAcknowledgment number: " + tcpPacket.AcknowledgmentNumber + (tcpPacket.Ack ? ",valid" : ",invalid") + //// flags //"\r\nUrgent pointer: " + (tcpPacket.Urg ? "valid" : "invalid") + //"\r\nACK flag: " + (tcpPacket.Ack ? "1" : "0") + // indicates if the AcknowledgmentNumber is valid //"\r\nPSH flag: " + (tcpPacket.Psh ? "1" : "0") + // push 1 = the receiver should pass the data to the app immidiatly, don't buffer it //"\r\nRST flag: " + (tcpPacket.Rst ? "1" : "0") + // reset 1 is to abort existing connection // // SYN indicates the sequence numbers should be synchronized between the sender and receiver to initiate a connection //"\r\nSYN flag: " + (tcpPacket.Syn ? "1" : "0") + //// closing the connection with a deal, host_A sends FIN to host_B, B responds with ACK //// FIN flag indicates the sender is finished sending //"\r\nFIN flag: " + (tcpPacket.Fin ? "1" : "0") + //"\r\nECN flag: " + (tcpPacket.ECN ? "1" : "0") + //"\r\nCWR flag: " + (tcpPacket.CWR ? "1" : "0") + //"\r\nNS flag: " + (tcpPacket.NS ? "1" : "0") + "\r\nRawBytes: " + Data; } } } break; case "UDP": if (getPacket) { UdpPacket udpPacket = (UdpPacket)packet.Extract(typeof(UdpPacket)); if (udpPacket != null) { int srcPort = udpPacket.SourcePort; int dstPort = udpPacket.DestinationPort; ushort checksum = udpPacket.Checksum; textBox2.Text = ""; textBox2.Text = "Packet number: " + key + " Type: UDP" + "\r\nSource port:" + srcPort + "\r\nDestination port: " + dstPort + "\r\nChecksum:" + checksum.ToString() + " valid: " + udpPacket.ValidChecksum + "\r\nValid UDP checksum: " + udpPacket.ValidUDPChecksum + "\r\nData: " + PrintBytes(udpPacket.Bytes) + "\r\nTryGetString: " + Encoding.Default.GetString(udpPacket.Bytes); } } break; case "ARP": if (getPacket) { ARPPacket arpPacket = (ARPPacket)packet.Extract(typeof(ARPPacket)); if (arpPacket != null) { System.Net.IPAddress senderAddress = arpPacket.SenderProtocolAddress; System.Net.IPAddress targerAddress = arpPacket.TargetProtocolAddress; System.Net.NetworkInformation.PhysicalAddress senderHardwareAddress = arpPacket.SenderHardwareAddress; System.Net.NetworkInformation.PhysicalAddress targerHardwareAddress = arpPacket.TargetHardwareAddress; textBox2.Text = ""; textBox2.Text = "Packet number: " + key + " Type: ARP" + "\r\nHardware address length:" + arpPacket.HardwareAddressLength + "\r\nProtocol address length: " + arpPacket.ProtocolAddressLength + "\r\nOperation: " + arpPacket.Operation.ToString() + // ARP request or ARP reply ARP_OP_REQ_CODE, ARP_OP_REP_CODE "\r\nSender protocol address: " + senderAddress + "\r\nTarget protocol address: " + targerAddress + "\r\nSender hardware address: " + senderHardwareAddress + "\r\nTarget hardware address: " + targerHardwareAddress; } } break; case "ICMP": if (getPacket) { ICMPv4Packet icmpPacket = (ICMPv4Packet)packet.Extract(typeof(ICMPv4Packet)); if (icmpPacket != null) { textBox2.Text = ""; textBox2.Text = "Packet number: " + key + " Type: ICMP v4" + "\r\nType Code: 0x" + icmpPacket.TypeCode.ToString("x") + "\r\nChecksum: " + icmpPacket.Checksum.ToString("x") + "\r\nID: 0x" + icmpPacket.ID.ToString("x") + "\r\nSequence number: " + icmpPacket.Sequence.ToString("x"); } } break; case "IGMP": if (getPacket) { IGMPv2Packet igmpPacket = (IGMPv2Packet)packet.Extract(typeof(IGMPv2Packet)); if (igmpPacket != null) { textBox2.Text = ""; textBox2.Text = "Packet number: " + key + " Type: IGMP v2" + "\r\nType: " + igmpPacket.Type + "\r\nGroup address: " + igmpPacket.GroupAddress + "\r\nMax response time" + igmpPacket.MaxResponseTime; } } break; default: textBox2.Text = ""; break; } }
private void lbxCapturedPacketList_SelectionChanged(object sender, SelectionChangedEventArgs e) { try { gbxPacketInfo.Visibility = Visibility.Visible; Packet packet = lbxCapturedPacketList.SelectedItem as Packet; Console.WriteLine(packet.GetType()); TcpPacket tcp = (TcpPacket)packet.Extract(typeof(TcpPacket)); IpPacket ip = (IpPacket)packet.Extract(typeof(IpPacket)); EthernetPacket ethernet = (EthernetPacket)packet.Extract(typeof(EthernetPacket)); UdpPacket udp = (UdpPacket)packet.Extract(typeof(UdpPacket)); ICMPv4Packet icmpv4 = (ICMPv4Packet)packet.Extract(typeof(ICMPv4Packet)); ICMPv6Packet icmpv6 = (ICMPv6Packet)packet.Extract(typeof(ICMPv6Packet)); ICMPv6Packet igmp = (ICMPv6Packet)packet.Extract(typeof(ICMPv6Packet)); PPPoEPacket PPPoE = (PPPoEPacket)packet.Extract(typeof(PPPoEPacket)); PPPPacket pppp = (PPPPacket)packet.Extract(typeof(PPPPacket)); LLDPPacket LLDP = (LLDPPacket)packet.Extract(typeof(LLDPPacket)); WakeOnLanPacket WOL = (WakeOnLanPacket)packet.Extract(typeof(WakeOnLanPacket)); if (tcp != null) { this.Dispatcher.Invoke((Action)(() => { tbxInfo.Text = tcp.ToString(StringOutputType.Verbose); })); } if (ip != null) { this.Dispatcher.Invoke((Action)(() => { tbxInfo.Text = ip.ToString(StringOutputType.Verbose); })); } if (ethernet != null) { this.Dispatcher.Invoke((Action)(() => { tbxInfo.Text = ethernet.ToString(StringOutputType.Verbose); })); } if (udp != null) { this.Dispatcher.Invoke((Action)(() => { tbxInfo.Text = udp.ToString(StringOutputType.Verbose); })); } if (icmpv4 != null) { this.Dispatcher.Invoke((Action)(() => { tbxInfo.Text = icmpv4.ToString(StringOutputType.Verbose); })); } if (icmpv6 != null) { this.Dispatcher.Invoke((Action)(() => { tbxInfo.Text = icmpv6.ToString(StringOutputType.Verbose); })); } if (igmp != null) { this.Dispatcher.Invoke((Action)(() => { tbxInfo.Text = igmp.ToString(StringOutputType.Verbose); })); } if (PPPoE != null) { this.Dispatcher.Invoke((Action)(() => { tbxInfo.Text = PPPoE.ToString(StringOutputType.Verbose); })); } if (pppp != null) { this.Dispatcher.Invoke((Action)(() => { tbxInfo.Text = pppp.ToString(StringOutputType.Verbose); })); } if (LLDP != null) { this.Dispatcher.Invoke((Action)(() => { tbxInfo.Text = LLDP.ToString(StringOutputType.Verbose); })); } if (WOL != null) { this.Dispatcher.Invoke((Action)(() => { tbxInfo.Text = WOL.ToString(StringOutputType.Verbose); })); } } catch (Exception ex) { Console.WriteLine("{0} Exception caught.", ex); } }
public static Packet CreatePacket(Param param) { Packet ret = null; //create layer 4 if (param.packetType == Param.PacketType.TCP) { TcpPacket tcpPacket = new TcpPacket(param.sPort, param.dPort); tcpPacket.AllFlags = param.tcpFlag; if (param.dIP.ToString().Contains(".")) { IPv4Packet ipPacket = new IPv4Packet(param.sIP, param.dIP); if (param.IPv4Frag) { ipPacket.FragmentFlags = (int)1; } ret = new EthernetPacket(param.sMAC, param.dMAC, EthernetPacketType.IpV4); ipPacket.PayloadPacket = tcpPacket; tcpPacket.PayloadData = param.payload; ret.PayloadPacket = ipPacket; ipPacket.UpdateCalculatedValues(); ipPacket.UpdateIPChecksum(); tcpPacket.Checksum = (ushort)tcpPacket.CalculateTCPChecksum(); } else { IPv6Packet ipPacket = new IPv6Packet(param.sIP, param.dIP); ret = new EthernetPacket(param.sMAC, param.dMAC, EthernetPacketType.IpV6); ipPacket.PayloadPacket = tcpPacket; tcpPacket.PayloadData = param.payload; ret.PayloadPacket = ipPacket; } } else if (param.packetType == Param.PacketType.UDP) { UdpPacket udpPacket = new UdpPacket(param.sPort, param.dPort); if (param.dIP.ToString().Contains(".")) { IPv4Packet ipPacket = new IPv4Packet(param.sIP, param.dIP); if (param.IPv4Frag) { ipPacket.FragmentFlags = (int)1; } ret = new EthernetPacket(param.sMAC, param.dMAC, EthernetPacketType.IpV4); ipPacket.PayloadPacket = udpPacket; udpPacket.PayloadData = param.payload; udpPacket.UpdateUDPChecksum(); ipPacket.PayloadLength = (ushort)(ipPacket.PayloadLength + param.payload.Length); ipPacket.UpdateIPChecksum(); ret.PayloadPacket = ipPacket; } else { IPv6Packet ipPacket = new IPv6Packet(param.sIP, param.dIP); ret = new EthernetPacket(param.sMAC, param.dMAC, EthernetPacketType.IpV6); ipPacket.PayloadPacket = udpPacket; udpPacket.PayloadData = param.payload; udpPacket.UpdateUDPChecksum(); ipPacket.PayloadLength = (ushort)(ipPacket.PayloadLength + param.payload.Length); ret.PayloadPacket = ipPacket; } } else if (param.packetType == Param.PacketType.ICMP) { ICMPv4Packet icmpPacket = new ICMPv4Packet(new ByteArraySegment(new byte[32])); if (param.type != 0 && param.code != 0) { icmpPacket.TypeCode = (ICMPv4TypeCodes)((param.type * 256) + (param.code)); } else if (param.type != 0) { icmpPacket.TypeCode = (ICMPv4TypeCodes)((param.type * 256)); } else { icmpPacket.TypeCode = ICMPv4TypeCodes.EchoRequest; } IPv4Packet ipPacket = new IPv4Packet(param.sIP, param.dIP); if (param.IPv4Frag) { ipPacket.FragmentFlags = (int)1; } ipPacket.PayloadPacket = icmpPacket; ipPacket.Checksum = ipPacket.CalculateIPChecksum(); ret = new EthernetPacket(param.sMAC, param.dMAC, EthernetPacketType.IpV4); ret.PayloadPacket = ipPacket; } else if (param.packetType == Param.PacketType.ICMPv6) { ICMPv6Packet icmpv6Packet = CreateICMPv6Packet(param); IPv6Packet ipPacket = new IPv6Packet(param.sIP, param.dIP); ipPacket.PayloadPacket = icmpv6Packet; ret = new EthernetPacket(param.sMAC, param.dMAC, EthernetPacketType.IpV6); ret.PayloadPacket = ipPacket; } else if (param.packetType == Param.PacketType.IP) { if (param.dIP.ToString().Contains(".")) { ret = new EthernetPacket(param.sMAC, param.dMAC, EthernetPacketType.IpV4); IPv4Packet ipPacket = new IPv4Packet(param.sIP, param.dIP); if (param.IPv4Frag) { ipPacket.FragmentFlags = (int)1; } ipPacket.Protocol = param.IPProtocol; ipPacket.PayloadData = param.payload; ipPacket.UpdateCalculatedValues(); ret.PayloadPacket = ipPacket; ipPacket.UpdateIPChecksum(); } else { ret = new EthernetPacket(param.sMAC, param.dMAC, EthernetPacketType.IpV6); //if extension headers were not specified, just put the payload if (param.ExtentionHeader.Count == 0) { IPv6Packet ipPacket = new IPv6Packet(param.sIP, param.dIP); ipPacket.Protocol = param.IPProtocol; ipPacket.PayloadData = param.payload; ipPacket.PayloadLength = (ushort)param.payload.Length; ipPacket.UpdateCalculatedValues(); ret.PayloadPacket = ipPacket; } else { ret = PacketFactory.CreateEHPacket(param, (EthernetPacket)ret); } ret.UpdateCalculatedValues(); } } else if (param.packetType == Param.PacketType.EtherType) { ret = new EthernetPacket(param.sMAC, param.dMAC, param.EtherTypeProtocol); byte[] etherBuffer = (new byte[64]); var payload = new byte[etherBuffer.Length + (param.payload).Length]; etherBuffer.CopyTo(payload, 0); (param.payload).CopyTo(payload, etherBuffer.Length); ret.PayloadData = payload; ret.UpdateCalculatedValues(); } return ret; }
private static void Worker_DoWork(object sender, DoWorkEventArgs e) { string InterfaceSelectedByUser = null; if (GlobalResources.SelectedNetworkInterface == 0) { InterfaceSelectedByUser = "******"; } else { InterfaceSelectedByUser = "******"; } Packet_Sniffer_Resources Packet_Capture_Resources_OfWorker = e.Argument as Packet_Sniffer_Resources; CaptureDeviceList Devices = CaptureDeviceList.Instance; foreach (ICaptureDevice Dev in Devices) { if (string.Equals(Dev.Name.ToString(), Packet_Capture_Resources_OfWorker.Ethernet)) { Packet_Capture_Resources_OfWorker.I_Ethernet = Dev; } if (string.Equals(Dev.Name.ToString(), Packet_Capture_Resources_OfWorker.WiFi)) { Packet_Capture_Resources_OfWorker.I_WiFi = Dev; } } #region Capture Method for 802.3-Ethernet if (string.Equals(InterfaceSelectedByUser, Packet_Capture_Resources_OfWorker.FriendlyNameOfEthernet)) { RawCapture Raw_Packet = null; Packet packet = null; string ConnectionType; Packet_Capture_Resources_OfWorker.PacketCount = 0; Packet_Capture_Resources_OfWorker.I_Ethernet.Open(DeviceMode.Promiscuous); while ((Raw_Packet = Packet_Capture_Resources_OfWorker.I_Ethernet.GetNextPacket()) != null) { Packet_Capture_Resources_OfWorker.PacketCaptureCount++; Packet_Capture_Resources_OfWorker.PacketCount += 1; if (Worker.CancellationPending == true) { e.Cancel = true; Packet_Capture_Resources_OfWorker.I_Ethernet.Close(); return; } DateTime PacketArrivalTime = Raw_Packet.Timeval.Date; int PacketLength = Raw_Packet.Data.Length; packet = Packet.ParsePacket(Raw_Packet.LinkLayerType, Raw_Packet.Data); EthernetPacket ethernet_packet = null; IpPacket ip_packet = null; ICMPv4Packet icmpv4_packet = null; ICMPv6Packet icmpv6_packet = null; TcpPacket tcp_packet = null; UdpPacket udp_packet = null; try { ethernet_packet = (EthernetPacket)packet.Extract(typeof(EthernetPacket)); ip_packet = (IpPacket)packet.Extract(typeof(IpPacket)); icmpv4_packet = (ICMPv4Packet)packet.Extract(typeof(ICMPv4Packet)); icmpv6_packet = (ICMPv6Packet)packet.Extract(typeof(ICMPv6Packet)); tcp_packet = (TcpPacket)packet.Extract(typeof(TcpPacket)); udp_packet = (UdpPacket)packet.Extract(typeof(UdpPacket)); } catch (Exception) { } #region For ICMP Packets if (icmpv4_packet != null) { ConnectionType = "ICMP-v4"; try { App.Current.Dispatcher.Invoke((Action) delegate { try { Packet_Capture_Resources_OfWorker.Packet_HolderList.Add(new PacketSnifferModel() { PacketNo = Packet_Capture_Resources_OfWorker.PacketCount, PacketArrivalTime = PacketArrivalTime.ToString(), EthernetSourceAddress = ethernet_packet.SourceHwAddress.ToString(), EthernetDestinationAddress = ethernet_packet.DestinationHwAddress.ToString(), IpSource = ip_packet.SourceAddress.ToString(), IpDestination = ip_packet.DestinationAddress.ToString(), ConnectionType = ConnectionType, SourcePort = "Unknown", DesinationPort = "Unknown", PayloadLength = "Unknown" }); } catch (NullReferenceException) { } }); Packet_Capture_Resources_OfWorker.packets.Add(packet); } catch (Exception) { } } else if (icmpv6_packet != null) { ConnectionType = "ICMP-v6"; try { App.Current.Dispatcher.Invoke((Action) delegate { try { Packet_Capture_Resources_OfWorker.Packet_HolderList.Add(new PacketSnifferModel() { PacketNo = Packet_Capture_Resources_OfWorker.PacketCount, PacketArrivalTime = PacketArrivalTime.ToString(), EthernetSourceAddress = ethernet_packet.SourceHwAddress.ToString(), EthernetDestinationAddress = ethernet_packet.DestinationHwAddress.ToString(), IpSource = ip_packet.SourceAddress.ToString(), IpDestination = ip_packet.DestinationAddress.ToString(), ConnectionType = ConnectionType, SourcePort = "Unknown", DesinationPort = "Unknown", PayloadLength = "Unknown" }); } catch (NullReferenceException) { } }); Packet_Capture_Resources_OfWorker.packets.Add(packet); } catch (Exception) { } } #endregion #region For TCP Packets else if (tcp_packet != null) { ConnectionType = "TCP"; try { App.Current.Dispatcher.Invoke((Action) delegate { try { Packet_Capture_Resources_OfWorker.Packet_HolderList.Add(new PacketSnifferModel() { PacketNo = Packet_Capture_Resources_OfWorker.PacketCount, PacketArrivalTime = PacketArrivalTime.ToString(), EthernetSourceAddress = ethernet_packet.SourceHwAddress.ToString(), EthernetDestinationAddress = ethernet_packet.DestinationHwAddress.ToString(), IpSource = ip_packet.SourceAddress.ToString(), IpDestination = ip_packet.DestinationAddress.ToString(), ConnectionType = ConnectionType, SourcePort = tcp_packet.SourcePort.ToString(), DesinationPort = tcp_packet.DestinationPort.ToString(), PayloadLength = "Unknown" }); } catch (NullReferenceException) { } }); Packet_Capture_Resources_OfWorker.packets.Add(packet); } catch (Exception) { } } #endregion #region For UDP Packets else if (udp_packet != null) { ConnectionType = "UDP"; try { App.Current.Dispatcher.Invoke((Action) delegate { try { Packet_Capture_Resources_OfWorker.Packet_HolderList.Add(new PacketSnifferModel() { PacketNo = Packet_Capture_Resources_OfWorker.PacketCount, PacketArrivalTime = PacketArrivalTime.ToString(), EthernetSourceAddress = ethernet_packet.SourceHwAddress.ToString(), EthernetDestinationAddress = ethernet_packet.DestinationHwAddress.ToString(), IpSource = ip_packet.SourceAddress.ToString(), IpDestination = ip_packet.DestinationAddress.ToString(), ConnectionType = ConnectionType, SourcePort = udp_packet.SourcePort.ToString(), DesinationPort = udp_packet.DestinationPort.ToString(), PayloadLength = udp_packet.Length.ToString() + " bytes" }); } catch (NullReferenceException) { } }); Packet_Capture_Resources_OfWorker.packets.Add(packet); } catch (Exception) { } } #endregion #region For Other Packets else { ConnectionType = "Others"; try { App.Current.Dispatcher.Invoke((Action) delegate { try { Packet_Capture_Resources_OfWorker.Packet_HolderList.Add(new PacketSnifferModel() { PacketNo = Packet_Capture_Resources_OfWorker.PacketCount, PacketArrivalTime = PacketArrivalTime.ToString(), EthernetSourceAddress = ethernet_packet.SourceHwAddress.ToString(), EthernetDestinationAddress = ethernet_packet.DestinationHwAddress.ToString(), IpSource = ip_packet.SourceAddress.ToString(), IpDestination = ip_packet.DestinationAddress.ToString(), ConnectionType = ConnectionType, SourcePort = "Unknown", DesinationPort = "Unknown", PayloadLength = udp_packet.Length.ToString() + " bytes" }); } catch (NullReferenceException) { } }); Packet_Capture_Resources_OfWorker.packets.Add(packet); } catch (Exception) { } } #endregion } } #endregion #region Capture Method for 8011ac-WiFi else if (string.Equals(InterfaceSelectedByUser, Packet_Capture_Resources_OfWorker.FriendlyNameOfWiFi)) { RawCapture Raw_Packet = null; Packet packet = null; string ConnectionType; Packet_Capture_Resources_OfWorker.PacketCount = 0; Packet_Capture_Resources_OfWorker.I_Ethernet.Open(DeviceMode.Promiscuous); while ((Raw_Packet = Packet_Capture_Resources_OfWorker.I_Ethernet.GetNextPacket()) != null) { Packet_Capture_Resources_OfWorker.PacketCaptureCount++; Packet_Capture_Resources_OfWorker.PacketCount += 1; if (Worker.CancellationPending == true) { e.Cancel = true; Packet_Capture_Resources_OfWorker.I_Ethernet.Close(); return; } DateTime PacketArrivalTime = Raw_Packet.Timeval.Date; int PacketLength = Raw_Packet.Data.Length; packet = Packet.ParsePacket(Raw_Packet.LinkLayerType, Raw_Packet.Data); EthernetPacket ethernet_packet = null; IpPacket ip_packet = null; ICMPv4Packet icmpv4_packet = null; ICMPv6Packet icmpv6_packet = null; TcpPacket tcp_packet = null; UdpPacket udp_packet = null; try { ethernet_packet = (EthernetPacket)packet.Extract(typeof(EthernetPacket)); ip_packet = (IpPacket)packet.Extract(typeof(IpPacket)); icmpv4_packet = (ICMPv4Packet)packet.Extract(typeof(ICMPv4Packet)); icmpv6_packet = (ICMPv6Packet)packet.Extract(typeof(ICMPv6Packet)); tcp_packet = (TcpPacket)packet.Extract(typeof(TcpPacket)); udp_packet = (UdpPacket)packet.Extract(typeof(UdpPacket)); } catch (Exception) { } #region For ICMP Packets if (icmpv4_packet != null) { ConnectionType = "ICMP-v4"; try { App.Current.Dispatcher.Invoke((Action) delegate { try { Packet_Capture_Resources_OfWorker.Packet_HolderList.Add(new PacketSnifferModel() { PacketNo = Packet_Capture_Resources_OfWorker.PacketCount, PacketArrivalTime = PacketArrivalTime.ToString(), EthernetSourceAddress = ethernet_packet.SourceHwAddress.ToString(), EthernetDestinationAddress = ethernet_packet.DestinationHwAddress.ToString(), IpSource = ip_packet.SourceAddress.ToString(), IpDestination = ip_packet.DestinationAddress.ToString(), ConnectionType = ConnectionType, SourcePort = "Unknown", DesinationPort = "Unknown", PayloadLength = "Unknown" }); } catch (NullReferenceException) { } }); Packet_Capture_Resources_OfWorker.packets.Add(packet); } catch (Exception) { } } else if (icmpv6_packet != null) { ConnectionType = "ICMP-v6"; try { App.Current.Dispatcher.Invoke((Action) delegate { try { Packet_Capture_Resources_OfWorker.Packet_HolderList.Add(new PacketSnifferModel() { PacketNo = Packet_Capture_Resources_OfWorker.PacketCount, PacketArrivalTime = PacketArrivalTime.ToString(), EthernetSourceAddress = ethernet_packet.SourceHwAddress.ToString(), EthernetDestinationAddress = ethernet_packet.DestinationHwAddress.ToString(), IpSource = ip_packet.SourceAddress.ToString(), IpDestination = ip_packet.DestinationAddress.ToString(), ConnectionType = ConnectionType, SourcePort = "Unknown", DesinationPort = "Unknown", PayloadLength = "Unknown" }); } catch (NullReferenceException) { } }); Packet_Capture_Resources_OfWorker.packets.Add(packet); } catch (Exception) { } } #endregion #region For TCP Packets else if (tcp_packet != null) { ConnectionType = "TCP"; try { App.Current.Dispatcher.Invoke((Action) delegate { try { Packet_Capture_Resources_OfWorker.Packet_HolderList.Add(new PacketSnifferModel() { PacketNo = Packet_Capture_Resources_OfWorker.PacketCount, PacketArrivalTime = PacketArrivalTime.ToString(), EthernetSourceAddress = ethernet_packet.SourceHwAddress.ToString(), EthernetDestinationAddress = ethernet_packet.DestinationHwAddress.ToString(), IpSource = ip_packet.SourceAddress.ToString(), IpDestination = ip_packet.DestinationAddress.ToString(), ConnectionType = ConnectionType, SourcePort = tcp_packet.SourcePort.ToString(), DesinationPort = tcp_packet.DestinationPort.ToString(), PayloadLength = "Unknown" }); } catch (NullReferenceException) { } }); Packet_Capture_Resources_OfWorker.packets.Add(packet); } catch (Exception) { } } #endregion #region For UDP Packets else if (udp_packet != null) { ConnectionType = "UDP"; try { App.Current.Dispatcher.Invoke((Action) delegate { try { Packet_Capture_Resources_OfWorker.Packet_HolderList.Add(new PacketSnifferModel() { PacketNo = Packet_Capture_Resources_OfWorker.PacketCount, PacketArrivalTime = PacketArrivalTime.ToString(), EthernetSourceAddress = ethernet_packet.SourceHwAddress.ToString(), EthernetDestinationAddress = ethernet_packet.DestinationHwAddress.ToString(), IpSource = ip_packet.SourceAddress.ToString(), IpDestination = ip_packet.DestinationAddress.ToString(), ConnectionType = ConnectionType, SourcePort = udp_packet.SourcePort.ToString(), DesinationPort = udp_packet.DestinationPort.ToString(), PayloadLength = udp_packet.Length.ToString() + " bytes" }); } catch (NullReferenceException) { } }); Packet_Capture_Resources_OfWorker.packets.Add(packet); } catch (Exception) { } } #endregion #region For Other Packets else { ConnectionType = "Others"; try { App.Current.Dispatcher.Invoke((Action) delegate { try { Packet_Capture_Resources_OfWorker.Packet_HolderList.Add(new PacketSnifferModel() { PacketNo = Packet_Capture_Resources_OfWorker.PacketCount, PacketArrivalTime = PacketArrivalTime.ToString(), EthernetSourceAddress = ethernet_packet.SourceHwAddress.ToString(), EthernetDestinationAddress = ethernet_packet.DestinationHwAddress.ToString(), IpSource = ip_packet.SourceAddress.ToString(), IpDestination = ip_packet.DestinationAddress.ToString(), ConnectionType = ConnectionType, SourcePort = "Unknown", DesinationPort = "Unknown", PayloadLength = udp_packet.Length.ToString() + " bytes" }); } catch (NullReferenceException) { } }); Packet_Capture_Resources_OfWorker.packets.Add(packet); } catch (Exception) { } } #endregion } } #endregion e.Result = Packet_Capture_Resources_OfWorker.Packet_HolderList; }
/// <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); }
//标记当前数据是否有效 #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); }
private void button1_Click(object sender, EventArgs e) { //ICMP if (comboBox1.SelectedIndex == 4) { byte[] buffer = new byte[32]; ICMPv4Packet icmp = new ICMPv4Packet(new PacketDotNet.Utils.ByteArraySegment(buffer)); icmp.TypeCode = ICMPv4TypeCodes.EchoRequest; icmp.ID = (ushort)0; icmp.Sequence = (ushort)0; icmp.PayloadData = new byte[32]; icmp.Checksum = GetChecksum(icmp.Header); IPAddress sourceIP = IPAddress.Parse(ipAddressBox1.Text); IPAddress destinationIP = IPAddress.Parse(ipAddressBox2.Text); IPv4Packet ipv4 = new IPv4Packet(sourceIP, destinationIP); ipv4.PayloadPacket = icmp; ipv4.TimeToLive = 128; ipv4.Checksum = GetChecksum(ipv4.Header); if (!softRoute.macAddress.ContainsKey(sourceIP)) { MacAddress.GetMacAddress(sourceIP); MessageBox.Show("源MAC不存在,获取中,请稍候再试!", "提示"); return; } PhysicalAddress sourceMac = softRoute.macAddress[sourceIP]; if (!softRoute.macAddress.ContainsKey(destinationIP)) { MacAddress.GetMacAddress(destinationIP); MessageBox.Show("目的MAC不存在,获取中,请稍候再试!", "提示"); return; } PhysicalAddress destinationMac = softRoute.macAddress[destinationIP]; EthernetPacket eth = new EthernetPacket(sourceMac, destinationMac, EthernetPacketType.IpV4); eth.PayloadPacket = ipv4; softRoute.deviceList[comboBox2.SelectedIndex].Interface.SendPacket(eth); } //ARP else if (comboBox1.SelectedIndex == 0) { ARPPacket arp = new ARPPacket(ARPOperation.Request, PhysicalAddress.Parse(textBox2.Text), IPAddress.Parse(ipAddressBox2.Text), PhysicalAddress.Parse(textBox1.Text), IPAddress.Parse(ipAddressBox1.Text)); EthernetPacket eth = new EthernetPacket(PhysicalAddress.Parse(textBox1.Text), PhysicalAddress.Parse(textBox2.Text), EthernetPacketType.Arp); eth.PayloadPacket = arp; softRoute.deviceList[comboBox2.SelectedIndex].Interface.SendPacket(eth); } //IP else if (comboBox1.SelectedIndex == 1) { //IPv4Packet ipv4 = new IPv4Packet(IPAddress.Parse(ipAddressBox1.Text), IPAddress.Parse(ipAddressBox2.Text)); } //TCP else if (comboBox1.SelectedIndex == 2) { //TcpPacket tcp = new TcpPacket(1, 2); } //UDP else if (comboBox1.SelectedIndex == 3) { } }
public void Display(ICMPv4Packet icmpv4Packet) { NewLine($"icmpv4 : id={icmpv4Packet.Id,-10} seq={icmpv4Packet.Sequence,-10} type_code={icmpv4Packet.TypeCode}"); }
public void posli_ping(string ip) { if (ip.Equals(rozhranie1.ip_adresa) || ip.Equals(rozhranie2.ip_adresa)) { main_view.lbl_ping = "!!!!!"; } else { string cmdString = "abcdefghijklmnoprstu"; byte[] sendBuffer = Encoding.ASCII.GetBytes(cmdString); ICMPv4Packet ping = new ICMPv4Packet(new ByteArraySegment(sendBuffer)); string via = null; Rozhranie rozhranie = null; ping.Checksum = 0; ping.TypeCode = ICMPv4TypeCodes.EchoRequest; ping.Sequence = 1; ping.UpdateCalculatedValues(); byte[] bytes = BitConverter.GetBytes(GetCrc(ping.Bytes)); Array.Reverse(bytes); ushort result = BitConverter.ToUInt16(bytes, 0); ping.Checksum = result; Smerovaci_zaznam smerovaci_zaznam = najdi_zaznam_v_smerovacej_tabulke(IPAddress.Parse(ip)); if (smerovaci_zaznam != null && smerovaci_zaznam.exit_interface == -1) { smerovaci_zaznam = rekurzivne_prehladanie(smerovaci_zaznam, ref via); } if (smerovaci_zaznam != null && smerovaci_zaznam.exit_interface != -1 && smerovaci_zaznam.next_hop != "X") { via = smerovaci_zaznam.next_hop; } if (smerovaci_zaznam != null) { if (smerovaci_zaznam.exit_interface == 2) { rozhranie = rozhranie2; } if (smerovaci_zaznam.exit_interface == 1) { rozhranie = rozhranie1; } IPv4Packet ip_pak = new IPv4Packet(IPAddress.Parse(rozhranie1.ip_adresa), IPAddress.Parse(ip)); ip_pak.SourceAddress = IPAddress.Parse(rozhranie.ip_adresa); ip_pak.DestinationAddress = IPAddress.Parse(ip); ip_pak.PayloadPacket = ping; ip_pak.UpdateIPChecksum(); string label = ""; EthernetPacket eth = new EthernetPacket(rozhranie.adapter.MacAddress, rozhranie.adapter.MacAddress, EthernetPacketType.IpV4); eth.PayloadPacket = ip_pak; int pokus = 5; while (pokus-- > 0) { Thread posielanie = new Thread(() => preposli(rozhranie, eth, smerovaci_zaznam, via, IPAddress.Parse(ip))); posielanie.Start(); zapis_ping = true; Thread.Sleep(1000); if (zapis_ping.Equals(true)) { main_view.lbl_ping += "."; // main_view.lbl_ping = label;//main_view.vypis(".", 85); } } } else { main_view.lbl_ping = "neviem smerovat"; } } Thread.CurrentThread.Abort(); }
public void injectRemotePacket(ref byte[] data, PhysicalAddress dstMAC, PhysicalAddress srcMAC, ref xbs_node sending_node) { Packet p = null; ARPPacket p_arp = null; IPv4Packet p_ipv4 = null; ICMPv4Packet p_icmp = null; UdpPacket p_udp = null; TcpPacket p_tcp = null; IPAddress source_IP = null; int srcMac_hash = srcMAC.GetHashCode(); // collect all injected source MACs. sniffer needs this to filter packets out lock (injected_macs_hash) { if (!injected_macs_hash.Contains(srcMac_hash)) { injected_macs_hash.Add(srcMac_hash); addMacToKnownMacListFromRemoteNodes(srcMAC); } } if (sending_node != null) { if (sending_node.addXbox(srcMAC)) { node_list.listHasJustChanged(); } } try { p = Packet.ParsePacket(LinkLayers.Ethernet, data); } catch (PcapException pcex) { #if DEBUG xbs_messages.addDebugMessage("!! ERROR! parse packet failed in injectRemotePacket (1): " + pcex.ToString(), xbs_message_sender.SNIFFER, xbs_message_type.ERROR); #endif return; } catch (NotImplementedException niex) { #if DEBUG xbs_messages.addDebugMessage("!! ERROR! parse packet failed in injectRemotePacket (2): " + niex.ToString(), xbs_message_sender.SNIFFER, xbs_message_type.ERROR); #endif return; } // DETERMINE PACKET TYPE if (p.PayloadPacket is IPv4Packet) { p_ipv4 = p.PayloadPacket as IPv4Packet; source_IP = p_ipv4.SourceAddress; if (p_ipv4.PayloadPacket is UdpPacket) { p_udp = p_ipv4.PayloadPacket as UdpPacket; } else if (p_ipv4.PayloadPacket is TcpPacket) { p_tcp = p_ipv4.PayloadPacket as TcpPacket; } } else if (p.PayloadPacket is ARPPacket) { p_arp = p.PayloadPacket as ARPPacket; source_IP = p_arp.SenderProtocolAddress; } else if (p.PayloadPacket is ICMPv4Packet) { p_icmp = p.PayloadPacket as ICMPv4Packet; } else { // UNKNOWN OR UNSUPPORTED PACKET TYPE #if DEBUG //xbs_messages.addDebugMessage("?? WARNING! unknown incoming packet type: " + p.ToString(), xbs_message_sender.SNIFFER, xbs_message_type.WARNING); #endif return; } // filter packet if needed if (is_injected_packet_to_be_filtered(ref p_arp, ref p_ipv4, ref p_udp, ref p_tcp)) { #if DEBUG xbs_messages.addDebugMessage("i> filtered packet: " + p, xbs_message_sender.SNIFFER); #endif return; } // add IP to device from node if (sending_node != null && source_IP != null) { if (sending_node.addIPtoXbox(srcMAC, source_IP)) { #if DEBUG xbs_messages.addDebugMessage("i> added new IP " + source_IP + " to xbox " + srcMAC + " for node " + sending_node, xbs_message_sender.SNIFFER); #endif node_list.listHasJustChanged(); } } #if DEBUG xbs_messages.addDebugMessage("i> " + p, xbs_message_sender.SNIFFER); #endif if (NAT.NAT_enabled) { #if DEBUG System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch(); stopWatch.Start(); #endif EthernetPacketType p_type = NAT.NAT_incoming_packet_PacketDotNet(ref data, dstMAC, srcMAC, ref p, ref p_ipv4, ref p_arp); #if DEBUG stopWatch.Stop(); if (p_type == EthernetPacketType.IpV4) { xbs_sniffer_statistics.NAT_callCount++; if (xbs_sniffer_statistics.NAT_callCount > 1) { xbs_sniffer_statistics.NAT_timeInCode += (UInt64)stopWatch.ElapsedTicks; UInt32 average = (UInt32)(xbs_sniffer_statistics.NAT_timeInCode / (xbs_sniffer_statistics.NAT_callCount - 1)); double average_ms = new TimeSpan(average).TotalMilliseconds; xbs_messages.addDebugMessage("- NAT time: " + stopWatch.ElapsedTicks + "t/" + stopWatch.ElapsedMilliseconds + "ms | NAT count: " + (xbs_sniffer_statistics.NAT_callCount - 1) + " Total Time: " + xbs_sniffer_statistics.NAT_timeInCode + "t=> Average " + average + "t / " + average_ms + "ms", xbs_message_sender.SNIFFER); } } p = Packet.ParsePacket(LinkLayers.Ethernet, data); xbs_messages.addDebugMessage("i> " + p, xbs_message_sender.SNIFFER); #endif } // inject the packet try { pdev.SendPacket(data, data.Length); } catch (PcapException pex) { xbs_messages.addInfoMessage("!! error while injecting packet from " + srcMAC + " to " + dstMAC + " (" + data.Length + ") : " + pex.Message, xbs_message_sender.SNIFFER, xbs_message_type.FATAL_ERROR); } catch (ArgumentException aex) { xbs_messages.addInfoMessage("!! error while injecting packet from " + srcMAC + " to " + dstMAC + " (" + data.Length + ") : " + aex.Message, xbs_message_sender.SNIFFER, xbs_message_type.FATAL_ERROR); } }