예제 #1
0
        public bool Process(Interface sender, ArpPacket arp)
        {
            if (arp.Operation == ArpOperation.Request)
            {
                var arpResponse = new ArpPacket(
                    ArpOperation.Response,
                    arp.SenderHardwareAddress,
                    arp.SenderProtocolAddress,
                    sender.MacAddress,
                    arp.TargetProtocolAddress
                    );

                var ethernetPacket = new EthernetPacket(sender.MacAddress, arp.SenderHardwareAddress, EthernetType.None)
                {
                    PayloadPacket = arpResponse
                };

                sender.Send(ethernetPacket);
            }
            else if (arp.Operation == ArpOperation.Response)
            {
                var record = new ArpRecord(arp.SenderProtocolAddress, arp.SenderHardwareAddress);
                CurrentApp.Logging.Info($"Creating ARP record: {record}");
                return(TryAdd(arp.SenderProtocolAddress, record));
            }

            return(false);
        }
예제 #2
0
        public ArpPacket GetArpPacketFromGUI(ArpOperation arpOperation, string RemoteMAC, string RemoteIP, string LocalMAC, string LocalIP)
        {
            ArpPacket arpPacket = new ArpPacket(
                arpOperation,
                PhysicalAddress.Parse(RemoteMAC),
                IPAddress.Parse(RemoteIP),
                PhysicalAddress.Parse(LocalMAC),
                IPAddress.Parse(LocalIP));

            return(arpPacket);
        }
예제 #3
0
        public void ConstructingFromValues()
        {
            var localIPBytes = new byte[] { 124, 10, 10, 20 };
            var localIP      = new IPAddress(localIPBytes);

            var destinationIPBytes = new byte[] { 192, 168, 1, 10 };
            var destinationIP      = new IPAddress(destinationIPBytes);

            var localMac = PhysicalAddress.Parse("AA-BB-CC-DD-EE-FF");

            var _ = new ArpPacket(ArpOperation.Request,
                                  PhysicalAddress.Parse("00-00-00-00-00-00"),
                                  destinationIP,
                                  localMac,
                                  localIP);
        }
예제 #4
0
        public void Request(Interface @interface, IPAddress ipAddress)
        {
            var arp = new ArpPacket(
                ArpOperation.Request,
                PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"),
                ipAddress,
                @interface.MacAddress,
                @interface.NetworkAddress
                );

            var ethernetPacket =
                new EthernetPacket(@interface.MacAddress, PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"), EthernetType.None)
            {
                PayloadPacket = arp
            };

            @interface.Send(ethernetPacket);
        }
예제 #5
0
        /// <summary>
        ///		Log a new ARP packet.
        /// </summary>
        /// <param name="packet">
        ///		The packet to log.
        ///	</param>
        public void LogPacket(ArpPacket packet)
        {
            lock (m_logger.XmlWriter)
            {
                // <ArpHeader>
                m_logger.XmlWriter.WriteStartElement("ArpHeader");

                m_logger.XmlWriter.WriteElementString("Type", packet.Type.ToString());
                m_logger.XmlWriter.WriteElementString("MediaType", packet.MediaType.ToString());
                m_logger.XmlWriter.WriteElementString("Protocol", packet.Protocol.ToString());
                m_logger.XmlWriter.WriteElementString("SourceMAC", packet.SourceMACAddress.ToString('-'));
                m_logger.XmlWriter.WriteElementString("SourceIP", packet.SourceIPAddress.ToString());
                m_logger.XmlWriter.WriteElementString("TargetMAC", packet.DestinationMACAddress.ToString('-'));
                m_logger.XmlWriter.WriteElementString("TargetIP", packet.DestinationIPAddress.ToString());

                m_logger.XmlWriter.WriteEndElement();
                // </ArpHeader>
            }
        }
예제 #6
0
        /// <summary>
        /// Reconnects device and gateway again disabling the spoofing effect on the selected device.
        /// </summary>
        /// <param name="device"></param>
        /// <returns></returns>
        public async static Task RestoreDevice(Device device)
        {
            await Task.Run(() =>
            {
                ArpPacket devicePacket           = new ArpPacket(ArpOperation.Response, AppConfiguration.BroadcastMac, device.IP, AppConfiguration.GatewayMac, AppConfiguration.GatewayIp);
                EthernetPacket deviceEtherPacket = new EthernetPacket(AppConfiguration.GatewayMac, device.MAC, EthernetType.Arp)
                {
                    PayloadPacket = devicePacket
                };
                ArpPacket gatewayPacket           = new ArpPacket(ArpOperation.Response, AppConfiguration.BroadcastMac, AppConfiguration.GatewayIp, device.MAC, device.IP);
                EthernetPacket gatewayEtherPacket = new EthernetPacket(device.MAC, AppConfiguration.GatewayMac, EthernetType.Arp)
                {
                    PayloadPacket = gatewayPacket
                };

                for (int i = 0; i < 20; i++)
                {
                    capturedevice.SendPacket(gatewayEtherPacket);
                    capturedevice.SendPacket(deviceEtherPacket);
                }
            });
        }
        public async Task StartAsyncReadData(CancellationToken cancellationToken)
        {
            logger.Info("TAP started");
            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    var buffer = new byte[4096];

                    var readBytes = await tapStream.ReadAsync(buffer, 0, 4096, cancellationToken);

                    if (readBytes <= 0)
                    {
                        continue;
                    }
                    var p = EthernetPacket.Parse(buffer.Take(readBytes).ToArray());
                    if (p.DestinationAddress.GetAddressBytes().Take(3).SequenceEqual(new byte[] { 0x01, 0x00, 0x5E }))
                    {
                        continue;
                    }
                    // ReSharper disable once SwitchStatementMissingSomeCases
                    switch (p.Type)
                    {
                    case EthernetPacket.PacketType.IpV4:
                    {
                        var intId = GetIdFromPhysicalAddress(p.DestinationAddress);
                        if (intId >= 0)
                        {
                            if (HostExists((ushort)intId) || intId == selfId)
                            {
                                await Send(p.Payload, (ushort)intId);
                            }
                            continue;
                        }

                        var ipPacket = (IPv4Packet)p.PayloadPacket;

                        switch (intId)
                        {
                        case -ipMacPoolShift:
                        {
                            if (ipPacket.PayloadPacket is UdpPacket udpPacket &&
                                udpPacket.PayloadPacket is DhcpPacket dhcpPacket)
                            {
                                if (dhcpPacket.Op != 1)
                                {
                                    continue;
                                }

                                var dhcpMessageType =
                                    dhcpPacket.Options.ContainsKey(53) &&
                                    dhcpPacket.Options[53].Length > 0
                                                        ? dhcpPacket.Options[53][0]
                                                        : -1;
                                DhcpPacket answerDhcpPacket;

                                switch (dhcpMessageType)
                                {
                                case 1:                     // DHCPDISCOVER
                                    answerDhcpPacket = new DhcpPacket
                                    {
                                        Xid                   = dhcpPacket.Xid,
                                        YourIpAddress         = GetIpFromId(selfId),
                                        ServerIpAddress       = GetIpFromId(-1),
                                        ClientHardwareAddress = dhcpPacket.ClientHardwareAddress,
                                        Options               =
                                            new Dictionary <byte, byte[]>
                                        {
                                            { 53, new byte[] { 2 } },
                                            { 1, new byte[] { 255, 255, 0, 0 } },
                                            {
                                                51,
                                                BitConverter.GetBytes(30 * 60).Reverse().ToArray()
                                            },
                                            { 54, GetIpFromId(-1).GetAddressBytes() },
                                            { 6, GetIpFromId(-1).GetAddressBytes() }
                                        }
                                    };
                                    break;

                                case 3:                     // DHCPREQUEST
                                    answerDhcpPacket = new DhcpPacket
                                    {
                                        Xid                   = dhcpPacket.Xid,
                                        YourIpAddress         = GetIpFromId(selfId),
                                        ServerIpAddress       = GetIpFromId(-1),
                                        ClientHardwareAddress = dhcpPacket.ClientHardwareAddress,
                                        Options               =
                                            new Dictionary <byte, byte[]>
                                        {
                                            { 53, new byte[] { 5 } },
                                            { 1, new byte[] { 255, 255, 0, 0 } },
                                            {
                                                51,
                                                BitConverter.GetBytes(30 * 60).Reverse().ToArray()
                                            },
                                            { 54, GetIpFromId(-1).GetAddressBytes() },
                                            { 6, GetIpFromId(-1).GetAddressBytes() }
                                        }
                                    };
                                    break;

                                default:
                                    continue;
                                }

                                var answerIpV4Packet = new IPv4Packet(GetIpFromId(-1),
                                                                      IPAddress.Broadcast);
                                answerIpV4Packet.SetPayloadPacket(new UdpPacket(67, 68,
                                                                                answerDhcpPacket, answerIpV4Packet));
                                var answerEthernetPacket = new EthernetPacket(
                                    GetPhysicalAddressFromId(-1),
                                    p.SourceAddress, answerIpV4Packet, EthernetPacket.PacketType.IpV4);
                                var answerData = answerEthernetPacket.ToBytes();
                                await tapStream.WriteAsync(answerData, 0, answerData.Length,
                                                           cancellationToken);

                                continue;
                            }

                            await Broadcast(p.Payload);
                        }
                            continue;

                        case -1:
                        {
                            if (ipPacket.PayloadPacket is UdpPacket udpPacket &&
                                udpPacket.PayloadPacket is DnsPacket dnsPacket)
                            {
                                if (dnsPacket.Queries.Count == 1 && dnsPacket.Queries[0].Type == 1 &&
                                    dnsPacket.Queries[0].Class == 1 && DomainNameUtil.GetName(string.Join(".", dnsPacket.Queries[0].Labels), dnsFormat) != null)
                                {
                                    var name = DomainNameUtil.GetName(string.Join(".", dnsPacket.Queries[0].Labels), dnsFormat);
                                    if (string.IsNullOrEmpty(name))
                                    {
                                        continue;
                                    }
                                    if (name == selfName)
                                    {
                                        await DnsReply(dnsPacket.TransactionId, dnsPacket.Queries[0].Labels, selfId, udpPacket.SourcePort);
                                    }
                                    else
                                    {
                                        var clientId = GetNodes().FirstOrDefault(x =>
                                                                                 x.GetDnmpNodeData().DomainName == name)?.Id;
                                        if (clientId != null)
                                        {
                                            await DnsReply(dnsPacket.TransactionId, dnsPacket.Queries[0].Labels, clientId.Value, udpPacket.SourcePort);
                                        }
                                    }
                                }
                            }
                        }
                            continue;
                        }
                    }
                    break;

                    case EthernetPacket.PacketType.Arp:
                    {
                        var arpPacket = (ArpPacket)p.PayloadPacket;
                        var targetIp  = new IPAddress(arpPacket.TargetProtocolAddress);
                        if (!targetIp.GetAddressBytes().Take(2).SequenceEqual(tapIpPrefix))
                        {
                            continue;
                        }
                        var targetId = GetIdFromPhysicalAddress(GetPhysicalAddressFromIp(targetIp));
                        if (targetId == -ipMacPoolShift)
                        {
                            continue;
                        }
                        if (!HostExists((ushort)targetId) && targetId != -1)
                        {
                            break;
                        }
                        var answerArpPacket = new ArpPacket
                        {
                            TargetHardwareAddress = arpPacket.SenderHardwareAddress,
                            TargetProtocolAddress = arpPacket.SenderProtocolAddress,
                            SenderHardwareAddress = GetPhysicalAddressFromIp(targetIp).GetAddressBytes(),
                            SenderProtocolAddress = arpPacket.TargetProtocolAddress,
                            Operation             = ArpPacket.OperationType.Response,
                            HardwareType          = 0x0001,
                            ProtocolType          = 0x0800
                        };
                        var answerEthernetPacket = new EthernetPacket(GetPhysicalAddressFromIp(targetIp),
                                                                      new PhysicalAddress(arpPacket.SenderHardwareAddress), answerArpPacket,
                                                                      EthernetPacket.PacketType.Arp);
                        var answerData = answerEthernetPacket.ToBytes();
                        await tapStream.WriteAsync(answerData, 0, answerData.Length, cancellationToken);
                    }
                    break;

                    default:
                        continue;
                    }
                }
                catch (TaskCanceledException)
                {
                    return;
                }
                catch (Exception e)
                {
                    logger.Error(e, "Exception in processing packet from TAP-Windows");
                }
            }
        }
예제 #8
0
        /// <summary>Parses Arp Packets and writes to the Ethernet the translation.</summary>
        /// <remarks>IpopRouter makes nodes think they are in the same Layer 2 network
        /// so that two nodes in the same network can communicate directly with each
        /// other.  IpopRouter masquerades for those that are not local.</remarks>
        /// <param name="ep">The Ethernet packet to translate</param>
        protected virtual void HandleArp(MemBlock packet)
        {
            // Can't do anything until we have network connectivity!
            if (_dhcp_server == null)
            {
                return;
            }

            ArpPacket ap = new ArpPacket(packet);

            // Not in our range!
            if (!_dhcp_server.IPInRange((byte[])ap.TargetProtoAddress) &&
                !_dhcp_server.IPInRange((byte[])ap.SenderProtoAddress))
            {
                ProtocolLog.WriteIf(IpopLog.Arp, String.Format("Bad Arp request from {0} for {1}",
                                                               Utils.MemBlockToString(ap.SenderProtoAddress, '.'),
                                                               Utils.MemBlockToString(ap.TargetProtoAddress, '.')));
                return;
            }


            if (ap.Operation == ArpPacket.Operations.Reply)
            {
                // This would be a unsolicited Arp
                if (ap.TargetProtoAddress.Equals(IPPacket.BroadcastAddress) &&
                    !ap.SenderHWAddress.Equals(EthernetPacket.BroadcastAddress))
                {
                    HandleNewStaticIP(ap.SenderHWAddress, ap.SenderProtoAddress);
                }
                return;
            }

            // We only support request operation hereafter
            if (ap.Operation != ArpPacket.Operations.Request)
            {
                return;
            }

            // Must return nothing if the node is checking availability of IPs
            // Or he is looking himself up.
            if (_ip_to_ether.ContainsKey(ap.TargetProtoAddress) ||
                ap.SenderProtoAddress.Equals(IPPacket.BroadcastAddress) ||
                ap.SenderProtoAddress.Equals(IPPacket.ZeroAddress))
            {
                return;
            }

            if (!ap.TargetProtoAddress.Equals(MemBlock.Reference(_dhcp_server.ServerIP)))
            {
                // Do not return messages if there is no connection to the remote address
                Address baddr = null;
                try {
                    baddr = _address_resolver.Resolve(ap.TargetProtoAddress);
                } catch (AddressResolutionException ex) {
                    if (ex.Issue != AddressResolutionException.Issues.DoesNotExist)
                    {
                        throw;
                    }
                    // Otherwise nothing to do, mapping doesn't exist...
                }

                if (AppNode.Node.Address.Equals(baddr) || baddr == null)
                {
                    ProtocolLog.WriteIf(IpopLog.Arp, String.Format("No mapping for: {0}",
                                                                   Utils.MemBlockToString(ap.TargetProtoAddress, '.')));
                    return;
                }

                if (!_conn_handler.ContainsAddress(baddr))
                {
                    ProtocolLog.WriteIf(IpopLog.Arp, String.Format(
                                            "No connection to {0} for {1}", baddr,
                                            Utils.MemBlockToString(ap.TargetProtoAddress, '.')));
                    _conn_handler.ConnectTo(baddr);
                    return;
                }
            }

            ProtocolLog.WriteIf(IpopLog.Arp, String.Format("Sending Arp response for: {0}",
                                                           Utils.MemBlockToString(ap.TargetProtoAddress, '.')));

            ArpPacket response = ap.Respond(EthernetPacket.UnicastAddress);

            EthernetPacket res_ep = new EthernetPacket(ap.SenderHWAddress,
                                                       EthernetPacket.UnicastAddress, EthernetPacket.Types.Arp,
                                                       response.ICPacket);

            Ethernet.Send(res_ep.ICPacket);
        }
예제 #9
0
        public void packetTvwDecode(byte [] capPacket, TreeView tvwDecode)
        {
            #region Parse Ethernet Header

            Ethernet802_3 ethernet = new Ethernet802_3(capPacket);

            strSourceMacAddress = ethernet.SourceMACAddress.ToString();
            strDestMacAddress   = ethernet.DestinationMACAddress.ToString();
            strEthernet         = "Ethernet II, Src: " + strSourceMacAddress + ", Dst: " + strDestMacAddress;
            strSrcMac           = "Source: " + strSourceMacAddress;
            strDstMac           = "Destination: " + strDestMacAddress;
            strEthernetType     = "Type: " + ethernet.NetworkProtocol.ToString();
            strData             = "Data: " + ethernet.Data.ToString();

            TreeNode nodeEthernet       = tvwDecode.Nodes.Add(strEthernet);
            TreeNode nodeEthernetDstMac = nodeEthernet.Nodes.Add(strDstMac);
            TreeNode nodeEthernetSrcMac = nodeEthernet.Nodes.Add(strSrcMac);
            TreeNode nodeType           = nodeEthernet.Nodes.Add(strEthernetType);
            TreeNode nodeData           = nodeEthernet.Nodes.Add(strData);

            #region Parse Network Protocol

            switch (ethernet.NetworkProtocol)
            {
            case NetworkLayerProtocol.IP:

                IpV4Packet ip = new IpV4Packet(ethernet.Data);

                strIp        = "Internet Protocol, Src Addr: " + ip.SourceAddress.ToString() + ", Dest Addr: " + ip.DestinationAddress.ToString();
                strIpVersion = "Version: " + ip.Version.ToString();
                int intIpHeaderLengthHex   = ip.HeaderLength;
                int intIpHeaderLengthBytes = intIpHeaderLengthHex * 4;
                strIpHeaderLength   = "Header Length: " + intIpHeaderLengthBytes.ToString() + " bytes";
                strTypeOfService    = "Type of Service: " + ip.TypeOfService.ToString();
                strIpTotalLength    = "Total Length: " + ip.TotalLength.ToString();
                strIpIdentification = "Identification: " + ip.Identification.ToString();
                strIpFlags          = "Flags: " + ip.ControlFlags.ToString();
                strIpFragment       = "Fragment Offset: " + ip.Fragments.ToString();
                strIpTtl            = "Time To Live: " + ip.TimeToLive.ToString();
                strIpProtocol       = "Protocol: " + ip.TransportProtocol.ToString();
                strIpChecksum       = "Header Checksum: " + ip.Checksum.ToString();
                if (ip.Options != null)
                {
                    strIpOptions = "Options: " + ip.Options.ToString();
                }
                if (ip.Padding != null)
                {
                    strIpPadding = "Padding: " + ip.Padding.ToString();
                }

                TreeNode nodeIP               = tvwDecode.Nodes.Add(strIp);
                TreeNode nodeIpVersion        = nodeIP.Nodes.Add(strIpVersion);
                TreeNode nodeIpHeaderLength   = nodeIP.Nodes.Add(strIpHeaderLength);
                TreeNode nodeTypeOfService    = nodeIP.Nodes.Add(strTypeOfService);
                TreeNode nodeIpTotalLength    = nodeIP.Nodes.Add(strIpTotalLength);
                TreeNode nodeIpIdentification = nodeIP.Nodes.Add(strIpIdentification);
                TreeNode nodeIpFlags          = nodeIP.Nodes.Add(strIpFlags);
                TreeNode nodeIpFragment       = nodeIP.Nodes.Add(strIpFragment);
                TreeNode nodeIpTtl            = nodeIP.Nodes.Add(strIpTtl);
                TreeNode nodeIpProtocol       = nodeIP.Nodes.Add(strIpProtocol);
                TreeNode nodeIpChecksum       = nodeIP.Nodes.Add(strIpChecksum);
                TreeNode nodeIpOptions        = null;
                TreeNode nodeIpPadding        = null;
                if (ip.Options != null)
                {
                    nodeIpOptions = nodeIP.Nodes.Add(strIpOptions);
                }
                if (ip.Padding != null)
                {
                    nodeIpPadding = nodeIP.Nodes.Add(strIpPadding);
                }

                //TreeNode nodeData = tvwDecode.Nodes.Add(strData);

                #region Parse Transport Protocol

                switch (ip.TransportProtocol)
                {
                case ProtocolType.Tcp:

                    TcpPacket tcp = new TcpPacket(ip.Data);

                    strTcp             = "Transmission Control Protocol, Src Port: " + tcp.SourcePort.ToString() + ", Dst Port: " + tcp.DestinationPort.ToString() + ", Seq: " + tcp.SequenceNumber.ToString() + ", Ack: " + tcp.AcknowledgmentNumber.ToString();
                    strTcpSrcPort      = "Source port: " + tcp.SourcePort.ToString();
                    strTcpDstPort      = "Destination port: " + tcp.DestinationPort.ToString();
                    strTcpSeq          = "Sequence number: " + tcp.SequenceNumber.ToString();
                    strTcpAck          = "Acknowledgement number: " + tcp.AcknowledgmentNumber.ToString();
                    strTcpOffset       = "Offset: " + tcp.Offset.ToString();
                    strTcpFlags        = "Flags: " + tcp.Flags.ToString();
                    strTcpWindow       = "Window size: " + tcp.Window.ToString();
                    strTcpChecksum     = "Checksum: " + tcp.Checksum.ToString();
                    strTcpUrgetPointer = "Urgent Pointer: " + tcp.UrgentPointer.ToString();
                    if (tcp.Options != null)
                    {
                        strTcpOptions = "Options: " + tcp.Options.ToString();
                    }
                    if (tcp.Padding != null)
                    {
                        strTcpPadding = "Padding: " + tcp.Padding.ToString();
                    }
                    if (tcp.Data != null)
                    {
                        strTcpData = "Data: " + tcp.Data.ToString();
                    }

                    TreeNode nodeTcp             = tvwDecode.Nodes.Add(strTcp);
                    TreeNode nodeTcpSrcPort      = nodeTcp.Nodes.Add(strTcpSrcPort);
                    TreeNode nodeTcpDstPort      = nodeTcp.Nodes.Add(strTcpDstPort);
                    TreeNode nodeTcpSeq          = nodeTcp.Nodes.Add(strTcpSeq);
                    TreeNode nodeTcpAck          = nodeTcp.Nodes.Add(strTcpAck);
                    TreeNode nodeTcpOffset       = nodeTcp.Nodes.Add(strTcpOffset);
                    TreeNode nodeTcpFlags        = nodeTcp.Nodes.Add(strTcpFlags);
                    TreeNode nodeTcpWindow       = nodeTcp.Nodes.Add(strTcpWindow);
                    TreeNode nodeTcpChecksum     = nodeTcp.Nodes.Add(strTcpChecksum);
                    TreeNode nodeTcpUrgetPointer = nodeTcp.Nodes.Add(strTcpUrgetPointer);
                    TreeNode nodeTcpOptions      = null;
                    TreeNode nodeTcpPadding      = null;
                    TreeNode nodeTcpData         = null;
                    if (tcp.Options != null)
                    {
                        nodeTcpOptions = nodeTcp.Nodes.Add(strTcpOptions);
                    }
                    if (tcp.Padding != null)
                    {
                        nodeTcpPadding = nodeTcp.Nodes.Add(strTcpPadding);
                    }
                    if (tcp.Data != null)
                    {
                        nodeTcpData = nodeTcp.Nodes.Add(strTcpData);
                    }
                    break;

                case ProtocolType.Udp:

                    UdpPacket udp = new UdpPacket(ip.Data);

                    strUdp         = "User Datagram Protocol, Src Port: " + udp.SourcePort.ToString() + ", Dst Port: " + udp.DestinationPort.ToString();
                    strUdpSrcPort  = "Source port: " + udp.SourcePort.ToString();
                    strUdpDstPort  = "Destination port: " + udp.DestinationPort.ToString();
                    strUdpLength   = "Length: " + udp.Length.ToString();
                    strUdpChecksum = "Checksum: " + udp.Checksum.ToString();
                    if (udp.Data != null)
                    {
                        strUdpData = "Data: " + udp.Data.ToString();
                    }

                    TreeNode nodeUdp         = tvwDecode.Nodes.Add(strUdp);
                    TreeNode nodeUdpSrcPort  = nodeUdp.Nodes.Add(strUdpSrcPort);
                    TreeNode nodeUdpDstPort  = nodeUdp.Nodes.Add(strUdpDstPort);
                    TreeNode nodeUdpLength   = nodeUdp.Nodes.Add(strUdpLength);
                    TreeNode nodeUdpChecksum = nodeUdp.Nodes.Add(strUdpChecksum);
                    TreeNode nodeUdpData     = null;
                    if (udp.Data != null)
                    {
                        nodeUdpData = nodeUdp.Nodes.Add(strUdpData);
                    }
                    break;

                case ProtocolType.Icmp:

                    IcmpPacket icmp = new IcmpPacket(ip.Data);

                    strIcmp            = "Internet Control Message Protocol";
                    strIcmpMessageType = "Data: " + icmp.MessageType.ToString();
                    strIcmpCode        = "Data: " + icmp.Code.ToString();
                    strIcmpChecksum    = "Data: " + icmp.Checksum.ToString();
                    strIcmpData        = "Data: " + icmp.Data.ToString();

                    TreeNode nodeIcmp            = tvwDecode.Nodes.Add(strIcmp);
                    TreeNode nodeIcmpMessageType = nodeIcmp.Nodes.Add(strIcmpMessageType);
                    TreeNode nodeIcmpCode        = nodeIcmp.Nodes.Add(strIcmpCode);
                    TreeNode nodeIcmpChecksum    = nodeIcmp.Nodes.Add(strIcmpChecksum);
                    TreeNode nodenodeIcmpData    = nodeIcmp.Nodes.Add(strIcmpData);
                    break;
                }

                #endregion

                break;

            case NetworkLayerProtocol.ARP:

                ArpPacket arp = new ArpPacket(ethernet.Data);

                strArp             = "Address Resolution Protocol";
                strArpMediaType    = "Hardware Type: " + arp.MediaType.ToString();
                strArpProtocolType = "Protocol Type: " + arp.Protocol.ToString();
                strArpType         = "Opcode: " + arp.Type.ToString();
                strArpSrcMac       = "Sender MAC Address: " + arp.SourceMACAddress.ToString();
                strArpSrcIp        = "Sender IP Address: " + arp.SourceIPAddress.ToString();
                strArpDstMac       = "Target MAC Address: " + arp.DestinationMACAddress.ToString();
                strArpDstIp        = "Target IP Address: " + arp.DestinationIPAddress.ToString();

                TreeNode nodeArp             = tvwDecode.Nodes.Add(strArp);
                TreeNode nodeMediaType       = nodeArp.Nodes.Add(strArpMediaType);
                TreeNode nodeArpProtocolType = nodeArp.Nodes.Add(strArpProtocolType);
                TreeNode nodeArpType         = nodeArp.Nodes.Add(strArpType);
                TreeNode nodeArpSrcMac       = nodeArp.Nodes.Add(strArpSrcMac);
                TreeNode nodeArpSrcIp        = nodeArp.Nodes.Add(strArpSrcIp);
                TreeNode nodeArpDstMac       = nodeArp.Nodes.Add(strArpDstMac);
                TreeNode nodeArpDstIp        = nodeArp.Nodes.Add(strArpDstIp);
                break;
            }

            #endregion

            #endregion
        }
예제 #10
0
        private void btnStop_Click(object sender, EventArgs e)
        {
            if (driver.Disposed == true)
            {
                return;
            }

            captureThread.Abort();
            driver.CloseDevice();

            for (int packetLoop = 0; packetLoop < packetCount; packetLoop++)
            {
                string sourceIp   = "N/A";
                string sourceMac  = "N/A";
                string sourcePort = "N/A";
                string destIp     = "N/A";
                string destMac    = "N/A";
                string destPort   = "N/A";
                string protocol   = "N/A";

                Ethernet802_3 ethernet = new Ethernet802_3(capturedPackets[packetLoop]);

                sourceMac = ethernet.SourceMACAddress.ToString();
                destMac   = ethernet.DestinationMACAddress.ToString();

                switch (ethernet.NetworkProtocol)
                {
                case NetworkLayerProtocol.IP:
                    IpV4Packet ip = new IpV4Packet(ethernet.Data);

                    sourceIp = ip.SourceAddress.ToString();
                    destIp   = ip.DestinationAddress.ToString();
                    protocol = ip.TransportProtocol.ToString().ToUpper();

                    switch (ip.TransportProtocol)
                    {
                    case ProtocolType.Tcp:
                        TcpPacket tcp = new TcpPacket(ip.Data);

                        sourcePort = tcp.SourcePort.ToString();
                        destPort   = tcp.DestinationPort.ToString();

                        break;

                    case ProtocolType.Udp:
                        UdpPacket udp = new UdpPacket(ip.Data);

                        sourcePort = udp.SourcePort.ToString();
                        destPort   = udp.DestinationPort.ToString();

                        break;

                    case ProtocolType.Icmp:
                        IcmpPacket icmp = new IcmpPacket(ip.Data);
                        break;
                    }
                    break;

                case NetworkLayerProtocol.ARP:
                    ArpPacket arp = new ArpPacket(ethernet.Data);

                    sourceMac = arp.SourceMACAddress.ToString();
                    destMac   = arp.DestinationMACAddress.ToString();
                    sourceIp  = arp.SourceIPAddress.ToString();
                    destIp    = arp.DestinationIPAddress.ToString();
                    protocol  = arp.Protocol.ToString().ToUpper();

                    break;
                }

                string[] items = new string[8];
                items[0] = packetLoop.ToString();
                items[1] = sourceIp;
                items[2] = sourceMac;
                items[3] = sourcePort;
                items[4] = destIp;
                items[5] = destMac;
                items[6] = destPort;
                items[7] = protocol;
                lvwPacketCapture.Items.Add(new ListViewItem(items, 0));
            }
        }
예제 #11
0
        /// <summary>
        /// Probe for active devices on the network
        /// </summary>
        /// <param name="view"></param>
        /// <returns></returns>
        public async static Task ProbeDevices()
        {
            await Task.Run(() =>
            {
                if (AppConfiguration.NetworkSize == 1)
                {
                    for (int ipindex = 1; ipindex <= 255; ipindex++)
                    {
                        if (capturedevice == null || capturedevice.Started == false)
                        {
                            break;
                        }

                        ArpPacket arprequestpacket    = new ArpPacket(ArpOperation.Request, PhysicalAddress.Parse("00-00-00-00-00-00"), IPAddress.Parse(Root + ipindex), capturedevice.MacAddress, myipaddress);
                        EthernetPacket ethernetpacket = new EthernetPacket(capturedevice.MacAddress, PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"), EthernetType.Arp);
                        ethernetpacket.PayloadPacket  = arprequestpacket;
                        capturedevice.SendPacket(ethernetpacket);
                    }
                }

                else if (AppConfiguration.NetworkSize == 2)
                {
                    for (int i = 1; i <= 255; i++)
                    {
                        if (capturedevice == null || capturedevice.Started == false)
                        {
                            break;
                        }

                        for (int j = 1; j <= 255; j++)
                        {
                            if (capturedevice == null || capturedevice.Started == false)
                            {
                                break;
                            }

                            ArpPacket arprequestpacket    = new ArpPacket(ArpOperation.Request, PhysicalAddress.Parse("00-00-00-00-00-00"), IPAddress.Parse(Root + i + '.' + j), capturedevice.MacAddress, myipaddress);
                            EthernetPacket ethernetpacket = new EthernetPacket(capturedevice.MacAddress, PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"), EthernetType.Arp);
                            ethernetpacket.PayloadPacket  = arprequestpacket;
                            capturedevice.SendPacket(ethernetpacket);
                            if (!GatewayCalled)
                            {
                                ArpPacket ArpForGateway        = new ArpPacket(ArpOperation.Request, PhysicalAddress.Parse("00-00-00-00-00-00"), AppConfiguration.GatewayIp, capturedevice.MacAddress, myipaddress);//???
                                EthernetPacket EtherForGateway = new EthernetPacket(capturedevice.MacAddress, PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"), EthernetType.Arp);
                                EtherForGateway.PayloadPacket  = ArpForGateway;
                                capturedevice.SendPacket(EtherForGateway);
                                GatewayCalled = true;
                            }
                        }
                    }
                }

                else if (AppConfiguration.NetworkSize == 3)
                {
                    for (int i = 1; i <= 255; i++)
                    {
                        if (capturedevice == null || capturedevice.Started == false)
                        {
                            break;
                        }

                        for (int j = 1; j <= 255; j++)
                        {
                            if (capturedevice == null || capturedevice.Started == false)
                            {
                                break;
                            }

                            for (int k = 1; k <= 255; k++)
                            {
                                if (capturedevice == null || capturedevice.Started == false)
                                {
                                    break;
                                }

                                ArpPacket arprequestpacket = new ArpPacket(ArpOperation.Request,
                                                                           PhysicalAddress.Parse("00-00-00-00-00-00"),
                                                                           IPAddress.Parse(Root + i + '.' + j + '.' + k), capturedevice.MacAddress,
                                                                           myipaddress);
                                EthernetPacket ethernetpacket = new EthernetPacket(capturedevice.MacAddress,
                                                                                   PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"), EthernetType.Arp);
                                ethernetpacket.PayloadPacket = arprequestpacket;
                                capturedevice.SendPacket(ethernetpacket);
                                if (!GatewayCalled)
                                {
                                    ArpPacket ArpForGateway        = new ArpPacket(ArpOperation.Request, PhysicalAddress.Parse("00-00-00-00-00-00"), AppConfiguration.GatewayIp, capturedevice.MacAddress, myipaddress); //???
                                    EthernetPacket EtherForGateway = new EthernetPacket(capturedevice.MacAddress, PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"), EthernetType.Arp);                                         //???
                                    EtherForGateway.PayloadPacket  = ArpForGateway;
                                    capturedevice.SendPacket(EtherForGateway);
                                    GatewayCalled = true;
                                }
                            }
                        }
                    }
                }
            });
        }
예제 #12
0
        /// <summary>
        /// Populates the list with devices connected on LAN
        /// </summary>
        /// <param name="view">UI controls</param>
        /// <param name="InterfaceFriendlyName"></param>
        public static void StartScan(IView view, string InterfaceFriendlyName)
        {
            #region initialization

            if (capturedevice != null)
            {
                GatewayCalled          = false;
                BackgroundScanDisabled = true;
                capturedevice.StopCapture();
                capturedevice.Close();
                capturedevice = null;
            }
            else
            {
                ClientList   = new Dictionary <IPAddress, PhysicalAddress>();
                Main.Devices = new ConcurrentDictionary <IPAddress, Device>();
            }

            #endregion

            //Get list of interfaces
            CaptureDeviceList capturedevicelist = CaptureDeviceList.Instance;
            //crucial for reflection on any network changes
            capturedevicelist.Refresh();
            capturedevice = (from devicex in capturedevicelist where ((NpcapDevice)devicex).Interface.FriendlyName == InterfaceFriendlyName select devicex).ToList()[0];
            //open device in promiscuous mode with 1000ms timeout
            capturedevice.Open(DeviceMode.Promiscuous, 1000);
            //Arp filter
            capturedevice.Filter = "arp";

            IPAddress myipaddress = AppConfiguration.LocalIp;

            //Probe for active devices on the network
            if (DiscoveryTimer == null)
            {
                StartDescoveryTimer();
            }

            #region Retrieving ARP packets floating around and find out the sender's IP and MAC

            //Scan duration
            long       scanduration = 8000;
            RawCapture rawcapture   = null;

            //Main scanning task
            ScannerTask = Task.Run(() =>
            {
                try
                {
                    Stopwatch stopwatch = new Stopwatch();
                    stopwatch.Start();
                    while ((rawcapture = capturedevice.GetNextPacket()) != null && stopwatch.ElapsedMilliseconds <= scanduration)
                    {
                        Packet packet       = Packet.ParsePacket(rawcapture.LinkLayerType, rawcapture.Data);
                        ArpPacket ArpPacket = packet.Extract <ArpPacket>();
                        if (!ClientList.ContainsKey(ArpPacket.SenderProtocolAddress) && ArpPacket.SenderProtocolAddress.ToString() != "0.0.0.0" && Tools.AreCompatibleIPs(ArpPacket.SenderProtocolAddress, myipaddress, AppConfiguration.NetworkSize))
                        {
                            ClientList.Add(ArpPacket.SenderProtocolAddress, ArpPacket.SenderHardwareAddress);

                            string mac = Tools.GetMACString(ArpPacket.SenderHardwareAddress);
                            string ip  = ArpPacket.SenderProtocolAddress.ToString();
                            var device = new Device
                            {
                                IP           = ArpPacket.SenderProtocolAddress,
                                MAC          = PhysicalAddress.Parse(mac.Replace(":", "")),
                                DeviceName   = "Resolving",
                                ManName      = "Getting information...",
                                DeviceStatus = "Online"
                            };

                            //Add device to UI list
                            view.ListView1.BeginInvoke(new Action(() => { view.ListView1.AddObject(device); }));

                            //Add device to main device list
                            _ = Main.Devices.TryAdd(ArpPacket.SenderProtocolAddress, device);

                            //Get hostname and mac vendor for the current device
                            _ = Task.Run(async() =>
                            {
                                try
                                {
                                    #region Get Hostname

                                    IPHostEntry hostEntry = await Dns.GetHostEntryAsync(ip);
                                    device.DeviceName     = hostEntry?.HostName ?? ip;

                                    #endregion

                                    #region Get MacVendor

                                    var Name       = VendorAPI.GetVendorInfo(mac);
                                    device.ManName = (Name is null) ? "" : Name.data.organization_name;

                                    #endregion

                                    view.ListView1.BeginInvoke(new Action(() => { view.ListView1.UpdateObject(device); }));
                                }
                                catch (Exception ex)
                                {
                                    try
                                    {
                                        if (ex is SocketException)
                                        {
                                            var Name       = VendorAPI.GetVendorInfo(mac);
                                            device.ManName = (Name is null) ? "" : Name.data.organization_name;

                                            view.ListView1.BeginInvoke(new Action(() =>
                                            {
                                                device.DeviceName = ip;
                                                view.ListView1.UpdateObject(device);
                                            }));
                                        }
                                        else
                                        {
                                            view.MainForm.BeginInvoke(
                                                new Action(() =>
                                            {
                                                device.DeviceName = ip;
                                                device.ManName    = "Error";
                                                view.ListView1.UpdateObject(device);
                                            }));
                                        }
                                    }
                                    catch
                                    {
                                    }
                                }
                            });
                        }

                        int percentageprogress = (int)((float)stopwatch.ElapsedMilliseconds / scanduration * 100);

                        view.MainForm.BeginInvoke(new Action(() => view.StatusLabel.Text = "Scanning " + percentageprogress + "%"));
                    }

                    stopwatch.Stop();
                    view.MainForm.BeginInvoke(new Action(() => view.StatusLabel.Text = ClientList.Count.ToString() + " device(s) found"));

                    //Initial scanning is over now we start the background scan.
                    Main.OperationIsInProgress = false;

                    //Start passive monitoring
                    BackgroundScanStart(view);
                }
                catch
                {
                    //Show an error in the UI in case something went wrong
                    try
                    {
                        view.MainForm.BeginInvoke(new Action(() =>
                        {
                            view.StatusLabel.Text = "Error occurred";
                            view.PictureBox.Image = Properties.Resources.color_error;
                        }));
                    }
                    catch { } //Swallow exception when the user closes the app during the scan operation
                }
            });

            #endregion
        }
예제 #13
0
        /// <summary>
        /// Actively monitor ARP packets for signs of new clients after the scanner is done. This method should be called from the StartScan method.
        /// </summary>
        /// <param name="view">UI controls</param>
        public static void BackgroundScanStart(IView view)
        {
            view.MainForm.BeginInvoke(new Action(() => view.StatusLabel.Text = "Starting background scan..."));
            BackgroundScanDisabled = false;

            IPAddress myipaddress = AppConfiguration.LocalIp;

            #region Assign OnPacketArrival event handler and start capturing

            capturedevice.OnPacketArrival += (object sender, CaptureEventArgs e) =>
            {
                if (BackgroundScanDisabled)
                {
                    return;
                }

                Packet packet = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
                if (packet == null)
                {
                    return;
                }

                ArpPacket ArpPacket = packet.Extract <ArpPacket>();

                if (!ClientList.ContainsKey(ArpPacket.SenderProtocolAddress) && ArpPacket.SenderProtocolAddress.ToString() != "0.0.0.0" && Tools.AreCompatibleIPs(ArpPacket.SenderProtocolAddress, myipaddress, AppConfiguration.NetworkSize))
                {
                    ClientList.Add(ArpPacket.SenderProtocolAddress, ArpPacket.SenderHardwareAddress);
                    view.ListView1.BeginInvoke(new Action(() =>
                    {
                        string mac = Tools.GetMACString(ArpPacket.SenderHardwareAddress);
                        string ip  = ArpPacket.SenderProtocolAddress.ToString();
                        var device = new Device
                        {
                            IP           = ArpPacket.SenderProtocolAddress,
                            MAC          = PhysicalAddress.Parse(mac.Replace(":", "")),
                            DeviceName   = "Resolving",
                            ManName      = "Getting information...",
                            DeviceStatus = "Online"
                        };

                        //Add device to list
                        view.ListView1.BeginInvoke(new Action(() => { view.ListView1.AddObject(device); }));

                        //Add device to main device list
                        _ = Main.Devices.TryAdd(ArpPacket.SenderProtocolAddress, device);

                        //Get hostname and mac vendor for the current device
                        _ = Task.Run(async() =>
                        {
                            try
                            {
                                #region Get Hostname

                                IPHostEntry hostEntry = await Dns.GetHostEntryAsync(ip);
                                device.DeviceName     = hostEntry?.HostName ?? ip;

                                #endregion

                                #region Get MacVendor

                                var Name       = VendorAPI.GetVendorInfo(mac);
                                device.ManName = (Name is null) ? "" : Name.data.organization_name;

                                #endregion

                                view.ListView1.BeginInvoke(new Action(() => { view.ListView1.UpdateObject(device); }));
                            }
                            catch (Exception ex)
                            {
                                try
                                {
                                    if (ex is SocketException)
                                    {
                                        var Name       = VendorAPI.GetVendorInfo(mac);
                                        device.ManName = (Name is null) ? "" : Name.data.organization_name;

                                        view.ListView1.BeginInvoke(new Action(() =>
                                        {
                                            device.DeviceName = ip;
                                            view.ListView1.UpdateObject(device);
                                        }));
                                    }
                                    else
                                    {
                                        view.MainForm.BeginInvoke(
                                            new Action(() =>
                                        {
                                            device.DeviceName = ip;
                                            device.ManName    = "Error";
                                            view.ListView1.UpdateObject(device);
                                        }));
                                    }
                                }
                                catch
                                {
                                }
                            }
                        });
                    }));

                    view.MainForm.BeginInvoke(new Action(() => view.StatusLabel.Text = ClientList.Count + " device(s) found"));
                }
                else if (ClientList.ContainsKey(ArpPacket.SenderProtocolAddress))
                {
                    foreach (var Device in Main.Devices)
                    {
                        if (Device.Key.Equals(ArpPacket.SenderProtocolAddress))
                        {
                            Device.Value.TimeSinceLastArp = DateTime.Now;
                            break;
                        }
                    }
                }
            };

            //Start receiving packets
            capturedevice.StartCapture();

            //Update UI state
            view.MainForm.BeginInvoke(new Action(() =>
            {
                view.PictureBox.Image  = NetStalker.Properties.Resources.color_ok;
                view.StatusLabel2.Text = "Ready";
                view.Tile.Enabled      = true;
                view.Tile2.Enabled     = true;
            }));

            if (!LoadingBarCalled)
            {
                CallTheLoadingBar(view);
                view.MainForm.BeginInvoke(new Action(() => view.StatusLabel.Text = "Scanning..."));
            }

            view.MainForm.BeginInvoke(new Action(() => view.StatusLabel.Text = ClientList.Count + " device(s) found"));

            #endregion
        }
예제 #14
0
        /// <summary>
        /// Build an Arp packet for the selected device based on the operation type and send it.
        /// </summary>
        /// <param name="device">The targeted device</param>
        /// <param name="Operation">Operation type</param>
        public static void ConstructAndSendArp(Device device, BROperation Operation)
        {
            if (Operation == BROperation.Spoof)
            {
                ArpPacket ArpPacketForVicSpoof = new ArpPacket(ArpOperation.Request,
                                                               targetHardwareAddress: device.MAC,
                                                               targetProtocolAddress: device.IP,
                                                               senderHardwareAddress: BRDevice.MacAddress,
                                                               senderProtocolAddress: AppConfiguration.GatewayIp);

                EthernetPacket EtherPacketForVicSpoof = new EthernetPacket(
                    sourceHardwareAddress: BRDevice.MacAddress,
                    destinationHardwareAddress: device.MAC,
                    EthernetType.Arp)
                {
                    PayloadPacket = ArpPacketForVicSpoof
                };

                ArpPacket ArpPacketForGatewaySpoof = new ArpPacket(ArpOperation.Request,
                                                                   targetHardwareAddress: AppConfiguration.GatewayMac,
                                                                   targetProtocolAddress: AppConfiguration.GatewayIp,
                                                                   senderHardwareAddress: BRDevice.MacAddress,
                                                                   senderProtocolAddress: device.IP);

                EthernetPacket EtherPacketForGatewaySpoof = new EthernetPacket(
                    sourceHardwareAddress: BRDevice.MacAddress,
                    destinationHardwareAddress: AppConfiguration.GatewayMac,
                    EthernetType.Arp)
                {
                    PayloadPacket = ArpPacketForGatewaySpoof
                };

                BRDevice.SendPacket(EtherPacketForVicSpoof);
                if (device.Redirected)
                {
                    BRDevice.SendPacket(EtherPacketForGatewaySpoof);
                }
            }
            else
            {
                ArpPacket ArpPacketForVicProtection = new ArpPacket(ArpOperation.Response,
                                                                    targetHardwareAddress: BRDevice.MacAddress,
                                                                    targetProtocolAddress: AppConfiguration.LocalIp,
                                                                    senderHardwareAddress: device.MAC,
                                                                    senderProtocolAddress: device.IP);

                EthernetPacket EtherPacketForVicProtection = new EthernetPacket(
                    sourceHardwareAddress: device.MAC,
                    destinationHardwareAddress: BRDevice.MacAddress,
                    EthernetType.Arp)
                {
                    PayloadPacket = ArpPacketForVicProtection
                };

                ArpPacket ArpPacketForGatewayProtection = new ArpPacket(ArpOperation.Response,
                                                                        targetHardwareAddress: BRDevice.MacAddress,
                                                                        targetProtocolAddress: AppConfiguration.LocalIp,
                                                                        senderHardwareAddress: AppConfiguration.GatewayMac,
                                                                        senderProtocolAddress: AppConfiguration.GatewayIp);

                EthernetPacket EtherPacketForGatewayProtection = new EthernetPacket(
                    sourceHardwareAddress: AppConfiguration.GatewayMac,
                    destinationHardwareAddress: BRDevice.MacAddress,
                    EthernetType.Arp)
                {
                    PayloadPacket = ArpPacketForGatewayProtection
                };

                BRDevice.SendPacket(EtherPacketForGatewayProtection);
                BRDevice.SendPacket(EtherPacketForVicProtection);
            }
        }
예제 #15
0
        /* private static int packetIndex = 0;
         * private void Program_OnPacketArrivalAsync(object sender, CaptureEventArgs e)
         * {
         *   if (e.Packet.LinkLayerType == PacketDotNet.LinkLayers.Ethernet)
         *   {
         *       var packet = PacketDotNet.Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
         *       var ethernetPacket = (PacketDotNet.EthernetPacket)packet;
         *
         *       _dispatcher.BeginInvoke(new ThreadStart(delegate
         *       {
         *
         *           _ShowTextBox += (packetIndex +
         *                         e.Packet.Timeval.Date.ToString() +
         *                         e.Packet.Timeval.Date.Millisecond +
         *                         ethernetPacket.SourceHardwareAddress +
         *                         ethernetPacket.DestinationHardwareAddress + "\n");
         *           packetIndex++;
         *       }));
         *       PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ShowTextBox)));
         *   }
         * }*/
        void Program_OnPacketArrivalAsync(object sender, CaptureEventArgs e)
        {
            Task.Run(() => { captureFileWriter.Write(e.Packet); });
            // парсинг всего пакета
            Packet packet = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
            // получение только TCP пакета из всего фрейма
            TcpPacket tcpPacket = (TcpPacket)packet.Extract <TcpPacket>();
            // получение только IP пакета из всего фрейма
            //IpPacket ipPacket = (IpPacket)packet.Extract(typeof(IpPacket));
            // получение только UDP пакета из всего фрейма
            UdpPacket udpPacket = (UdpPacket)packet.Extract <UdpPacket>();
            ArpPacket arpPacket = (ArpPacket)packet.Extract <ArpPacket>();
            //LinuxSLLPacket sllPacket = (LinuxSLLPacket)packet.Extract(typeof(LinuxSLLPacket));
            IcmpV4Packet icmpPacket = (IcmpV4Packet)packet.Extract <IcmpV4Packet>();
            IgmpV2Packet igmpPacket = (IgmpV2Packet)packet.Extract <IgmpV2Packet>();

            DateTime time    = e.Packet.Timeval.Date.ToLocalTime();
            string   StrTime = time.Hour + ":" + time.Minute + ":" + time.Second + ":" + time.Millisecond;
            int      len     = e.Packet.Data.Length;

            // Stream myStream;

            // using (myStream = File.Open(Path.GetTempPath() + "SnifferLogs.pcapng", FileMode.Append, FileAccess.Write))
            //  {
            //StreamWriter myWriter = new StreamWriter(myStream);
            //myWriter.WriteLine(e.Packet);
            //var thread = new Thread(() =>

            /*          Task.Run(() =>
             *        {
             *            //captureFileWriter = new CaptureFileWriterDevice(Path.GetTempPath() + "SnifferLogs.pcapng");
             *            captureFileWriter.Write(e.Packet);
             *            //Thread.Sleep(50);
             *        });*/
            // }

            // using (myStream = File.Open(Path.GetTempPath() + "SnifferLogs.pcapng", FileMode.OpenOrCreate, FileAccess.Read))
            // {
            // StreamReader myReader = new StreamReader(myStream);
            // Console.Write(myReader.ReadToEnd());
            //captureFileReader = new CaptureFileReaderDevice(Path.GetTempPath() + "SnifferLogs.pcapng");

            //captureFileReader = new CaptureFileReaderDevice(Path.GetTempPath() + "SnifferLogs.pcapng");
            _ShowTextBox += (num +
                             e.Packet.Timeval.Date.ToString() +
                             e.Packet.Timeval.Date.Millisecond + "\n");
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ShowTextBox)));

            //_ShowTextBox += myReader.ReadToEnd();
            // }

            /* using (myStream = File.Open(Path.GetTempPath() + "SnifferLogs.pcapng", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
             * {
             *   StreamWriter myWriter = new StreamWriter(myStream);
             *   StreamReader myReader = new StreamReader(myStream);
             *   //_MainCodeBehind.ShowMessage(e.Packet.ToString());
             *   myWriter.WriteLine(e.Packet.ToString());
             *   _ShowTextBox += myReader.ReadLine();
             *   _MainCodeBehind.ShowMessage(myReader.ReadLine());
             *   //captureFileWriter = new CaptureFileWriterDevice(Path.GetTempPath() + "SnifferLogs.pcapng");
             *   //captureFileWriter.Write(e.Packet);
             * }*/


            /* _dispatcher.BeginInvoke(new ThreadStart(delegate
             * {
             *
             *   captureFileWriter.Write(e.Packet);
             *   File.Copy(Path.GetTempPath() + "SnifferLogs.pcapng", Path.GetTempPath() + "SnifferLogs2.pcapng");
             * }));
             * _dispatcher.BeginInvoke(new ThreadStart(delegate
             * {
             *
             *   _ShowTextBox += (num +
             *                 e.Packet.Timeval.Date.ToString() +
             *                 e.Packet.Timeval.Date.Millisecond + "\n");
             * }));*/

            if (tcpPacket != null)
            {
                IPPacket ipPacket = (IPPacket)tcpPacket.ParentPacket;

                Tcp tpck;
                // порт отправителя
                tpck.srcPort = tcpPacket.SourcePort;
                // порт получателя
                tpck.dstPort   = tcpPacket.DestinationPort;
                tpck.seqNumber = tcpPacket.SequenceNumber;       /*значения в десятеричной форме*/
                tpck.ackNumber = tcpPacket.AcknowledgmentNumber;
                tpck.offset    = tcpPacket.DataOffset;
                tpck.flags     = tcpPacket.Flags;
                tpck.CWR       = tcpPacket.CongestionWindowReduced;
                tpck.ECE       = tcpPacket.ExplicitCongestionNotificationEcho;
                tpck.URG       = tcpPacket.Urgent;
                tpck.ACK       = tcpPacket.Acknowledgment;
                tpck.PSH       = tcpPacket.Push;
                tpck.RST       = tcpPacket.Reset;
                tpck.SYN       = tcpPacket.Synchronize;
                tpck.FIN       = tcpPacket.Finished;
                tpck.winSize   = tcpPacket.WindowSize;
                tpck.chksum    = tcpPacket.Checksum;
                tpck.urgpoint  = tcpPacket.UrgentPointer;
                tpck.tdata     = Hexdata(tcpPacket);

                string data = HexToAscii(tcpPacket);
                _dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    Col.Add(new MyTable
                    {
                        Number   = num,
                        Time     = StrTime,
                        Src      = ipPacket.SourceAddress.ToString(),
                        Dst      = ipPacket.DestinationAddress.ToString(),
                        Protocol = "TCP",
                        Length   = len,
                        Info     = Convert.ToString(data)
                    });
                    tpck.pos = num;
                    TcpCol.Add(tpck);
                    num++;
                }));
            }

            if (udpPacket != null)
            {
                IPPacket ipPacket = (IPPacket)udpPacket.ParentPacket;
                Udp      udpk;
                udpk.srcPort = udpPacket.SourcePort;
                udpk.dstPort = udpPacket.DestinationPort;
                udpk.len     = udpPacket.Length;
                udpk.chksum  = udpPacket.Checksum;
                udpk.udata   = Hexdata(udpPacket);

                // данные пакета
                string data = HexToAscii(udpPacket);
                _dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    Col.Add(new MyTable
                    {
                        Number   = num,
                        Time     = StrTime,
                        Src      = ipPacket.SourceAddress.ToString(),
                        Dst      = ipPacket.DestinationAddress.ToString(),
                        Protocol = "UDP",
                        Length   = len,
                        Info     = Convert.ToString(data)
                    });
                    udpk.pos = num;
                    UdpCol.Add(udpk);
                    num++;
                }));
            }

            if (arpPacket != null)
            {
                Arp arpk;
                arpk.hwtype     = arpPacket.HardwareAddressType.ToString();
                arpk.prtype     = arpPacket.ProtocolAddressType.ToString();
                arpk.hwsize     = arpPacket.HardwareAddressLength;
                arpk.prtsize    = arpPacket.ProtocolAddressLength;
                arpk.opcode     = Convert.ToInt16(arpPacket.Operation);
                arpk.sender_mac = arpPacket.SenderHardwareAddress;
                arpk.sender_ip  = arpPacket.SenderProtocolAddress;
                arpk.target_mac = arpPacket.TargetHardwareAddress;
                arpk.target_ip  = arpPacket.TargetProtocolAddress;
                arpk.adata      = Hexdata(arpPacket);

                // данные пакета
                string data = HexToAscii(arpPacket);

                _dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    Col.Add(new MyTable
                    {
                        Number   = num,
                        Time     = StrTime,
                        Src      = arpk.sender_ip.ToString(),
                        Dst      = arpk.target_ip.ToString(),
                        Protocol = "ARP",
                        Length   = len,
                        Info     = Convert.ToString(data)
                    });
                    arpk.pos = num;
                    ArpCol.Add(arpk);
                    num++;
                }));
            }


            if (icmpPacket != null)
            {
                IPPacket ipPacket = (IPPacket)icmpPacket.ParentPacket;
                Icmp     icmpk;
                icmpk.type   = icmpPacket.TypeCode.ToString();
                icmpk.chksum = icmpPacket.Checksum;
                icmpk.seq    = icmpPacket.Sequence;
                icmpk.icdata = Hexdata(icmpPacket);
                // данные пакета
                string data = "";
                for (int i = 0; i < icmpPacket.Data.Count(); i++)
                {
                    data += icmpPacket.Data[i];
                }

                _dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    Col.Add(new MyTable
                    {
                        Number   = num,
                        Time     = StrTime,
                        Src      = ipPacket.SourceAddress.ToString(),
                        Dst      = ipPacket.DestinationAddress.ToString(),
                        Protocol = "ICMPv4",
                        Length   = len,
                        Info     = Convert.ToString(data)
                    });
                    icmpk.pos = num;
                    IcmpCol.Add(icmpk);
                    num++;
                }));
            }

            if (igmpPacket != null)
            {
                IPPacket ipPacket = (IPPacket)igmpPacket.ParentPacket;
                Igmp     igmpk;
                igmpk.type          = igmpPacket.Type.ToString();
                igmpk.max_resp_time = igmpPacket.MaxResponseTime.ToString();
                igmpk.chksum        = igmpPacket.Checksum;
                igmpk.group_addr    = igmpPacket.GroupAddress.ToString();
                igmpk.igdata        = Hexdata(igmpPacket);
                // данные пакета
                string data = HexToAscii(igmpPacket);

                _dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    Col.Add(new MyTable
                    {
                        Number   = num,
                        Time     = StrTime,
                        Src      = ipPacket.SourceAddress.ToString(),
                        Dst      = ipPacket.DestinationAddress.ToString(),
                        Protocol = "IGMPv2",
                        Length   = len,
                        Info     = Convert.ToString(data)
                    });
                    igmpk.pos = num;
                    IgmpCol.Add(igmpk);
                    num++;
                }));
            }
        }