protected override bool CalculateIsValid()
        {
            if (!base.CalculateIsValid())
            {
                return(false);
            }
            IpV4Datagram ipV4 = this.IpV4;

            if ((int)this.Code == 4)
            {
                return(ipV4.Length == 256);
            }
            switch (ipV4.Protocol)
            {
            case IpV4Protocol.Tcp:
                TcpDatagram tcp = ipV4.Tcp;
                if (tcp.Length >= 20)
                {
                    return(tcp.Length >= tcp.HeaderLength);
                }
                return(false);

            case IpV4Protocol.Udp:
                return(ipV4.Udp.Length >= 8);

            default:
                return(true);
            }
        }
Exemple #2
0
        public void HandlePacket(IPacketProducer source, Packet packet)
        {
            IpV4Datagram ip  = packet.Ethernet.IpV4;
            TcpDatagram  tcp = ip.Tcp;

            var msg = new StringBuilder();

            msg.Append(packet.Timestamp.ToString("hh:mm:ss.fff"));
            msg.Append(" (").Append(packet.Length).Append(") ");
            if (tcp.IsValid)
            {
                msg.Append(ip.Source).Append(":").Append(tcp.SourcePort).Append(" -> ");
                msg.Append(ip.Destination).Append(":").Append(tcp.DestinationPort).Append(' ');
                if (tcp.Http.IsRequest && ((HttpRequestDatagram)tcp.Http).Method != null)
                {
                    var http = (HttpRequestDatagram)tcp.Http;
                    msg.Append(http.Method?.Method ?? "???").Append(' ').Append(http.Uri).Append(' ').Append(http.Version);
                }
                else if (tcp.Http.IsResponse)
                {
                    var http = (HttpResponseDatagram)tcp.Http;
                    msg.Append(http.StatusCode).Append(' ').Append(http.ReasonPhrase);
                }
            }
            else
            {
                msg.Append(ip.Source).Append(" -> ").Append(ip.Destination);
            }
            Console.WriteLine(msg);
        }
        /// <summary>
        /// Valid if the datagram's length is OK, the checksum is correct, the code is in the expected range
        /// and the IPv4 payload contains at least an IPv4 header and the transport header.
        /// If the code is for unsupported transport protocol, the IPv4 payload should contain 256 bytes of the original datagram.
        /// </summary>
        protected override bool CalculateIsValid()
        {
            if (!base.CalculateIsValid())
            {
                return(false);
            }

            IpV4Datagram ip = IpV4;

            if ((IcmpCodeConversionFailed)Code == IcmpCodeConversionFailed.UnsupportedTransportProtocol)
            {
                return(ip.Length == OriginalDatagramLengthForUnsupportedTransportProtocol);
            }

            switch (ip.Protocol)
            {
            case IpV4Protocol.Udp:
                return(ip.Udp.Length >= UdpDatagram.HeaderLength);

            case IpV4Protocol.Tcp:
                TcpDatagram tcp = ip.Tcp;
                return(tcp.Length >= TcpDatagram.HeaderMinimumLength && tcp.Length >= tcp.HeaderLength);

            default:     // Todo: support more protocols
                return(true);
            }
        }
Exemple #4
0
        public static void PacketHandler(Packet packet)
        {
            Console.WriteLine(packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + " Length: " + packet.Length);

            IpV4Datagram ip      = packet.Ethernet.IpV4;
            UdpDatagram  udp     = ip.Udp;
            Datagram     payload = udp.Payload;

            byte[] data = payload.ToArray();
            NAE    nae  = NAEHandler.parseNAEFromPacket(data);
            String msg  = nae.Name + " reported online.";

            NAEHandler.listenFrm.Invoke(NAEHandler.listenFrm.AddNAEDelegate, new object[] { nae });

            if (NAEHandler.mainFrm.notifyIcon.Visible == true)
            {
                NAEHandler.mainFrm.notifyIcon.BalloonTipText = msg;
                NAEHandler.mainFrm.notifyIcon.ShowBalloonTip(500);
            }
            else
            {
                NAEHandler.mainFrm.notifyIcon.Visible        = true;
                NAEHandler.mainFrm.notifyIcon.BalloonTipText = msg;
                NAEHandler.mainFrm.notifyIcon.ShowBalloonTip(500);
                System.Threading.Thread.Sleep(3000);
                NAEHandler.mainFrm.notifyIcon.Visible = false;
            }
        }
Exemple #5
0
        private void MapIpV4Data(IpV4Datagram datagram)
        {
            this.SourceIp      = datagram.Source.ToString();
            this.DestinationIp = datagram.Destination.ToString();

            switch (datagram.Protocol)
            {
            case IpV4Protocol.IpV6:
                this.MapIpV6Data(datagram.IpV6);
                break;

            case IpV4Protocol.Tcp:
                this.MapTcpData(datagram.Tcp);
                break;

            case IpV4Protocol.Udp:
                this.MapUdpData(datagram.Udp);
                break;

            case IpV4Protocol.InternetControlMessageProtocol:
                this.MapIcmpData(datagram.Icmp);
                break;

            case IpV4Protocol.InternetGroupManagementProtocol:
                this.MapIgmpData(datagram.Igmp);
                break;

            default:
                throw new Exception($"Unsupported Protocol. ({datagram.Protocol})");
            }
        }
Exemple #6
0
        /// <summary>
        /// Update ctrl with packet information
        /// Increment frame_id by one
        /// </summary>
        /// <param name="packet">The packet to handle</param>
        /// <param name="frame_id">The frame id, for UI display</param>
        /// <param name="ctrl">The control to display information</param>
        public static void HandlePacket(Packet packet, ref UInt64 frame_id, object[] ctrl)
        {
            EthernetDatagram ethernet = packet.Ethernet;

            if (ethernet == null)
            {
                return;
            }

            switch (ethernet.EtherType)
            {
            case EthernetType.IpV4: {
                IpV4Datagram ip = ethernet.IpV4;
                IPParser.HandleIPV4(packet, ip, ref frame_id, ctrl);
                break;
            }

            case EthernetType.Arp: {
                ArpDatagram arp = ethernet.Arp;
                ArpParser.HandleARP(packet, arp, ref frame_id, ctrl);
                break;
            }

            default:
                break;
            }
        }
Exemple #7
0
        public PPacket(Packet packet, long packetNumber, TimeSpan relativeTime)
        {
            _packet       = packet;
            _packetNumber = packetNumber;
            _relativeTime = relativeTime;
            EthernetDatagram ethernet = packet.Ethernet;

            if (ethernet != null)
            {
                _ethernetType     = ethernet.EtherType;
                _ethernetTypeCode = GetEthernetTypeCode(ethernet.EtherType);
                //_ipv4 = packet.Ethernet.IpV4;
                //if (_ipv4 != null)
                if (ethernet.EtherType == PcapDotNet.Packets.Ethernet.EthernetType.IpV4)
                {
                    _ipv4           = packet.Ethernet.IpV4;
                    _source         = _ipv4.Source;
                    _destination    = _ipv4.Destination;
                    _ipProtocol     = _ipv4.Protocol;
                    _ipProtocolCode = GetIPProtocolCode(_ipv4.Protocol);
                    //_tcp = _ipv4.Tcp;
                    //if (_tcp != null)
                    if (_ipv4.Protocol == IpV4Protocol.Tcp)
                    {
                        _tcp             = _ipv4.Tcp;
                        _sourcePort      = _tcp.SourcePort;
                        _destinationPort = _tcp.DestinationPort;
                    }
                }
            }
        }
Exemple #8
0
        public void ProcessICMP(EthernetDatagram packet)
        {
            IpV4Datagram ip = null;

            if (packet.EtherType == EthernetType.VLanTaggedFrame)
            {
                ip = packet.VLanTaggedFrame.IpV4;
            }
            else
            {
                ip = packet.IpV4;
            }

            IcmpDatagram icmp = ip.Icmp;

            if (icmp.MessageType == IcmpMessageType.Echo && ip.Destination.Equals(_adapter.IP))
            {
                SendIcmpEchoReply(ip.Source, packet.Source, icmp);
            }
            else if (icmp.MessageType == IcmpMessageType.EchoReply)
            {
                if (_current_state == ICMP_STATE.WAIT_ECHO && ip.Source.Equals(_target_ip) && ip.Destination.Equals(_adapter.IP))
                {
                    ushort SequenceNumber = (ushort)(icmp.Variable & 0xFFFF);
                    if (SequenceNumber == _current_icmp_sequence_num)
                    {
                        _ping_echo_wait_handle.Set();
                    }
                }
            }
        }
        private void ProceedResponce(Packet responce)
        {
            IpV4Datagram ipDatagram  = responce.Ethernet.IpV4;
            TcpDatagram  tcpDatagram = ipDatagram.Tcp;

            TcpControlBits bits  = tcpDatagram.ControlBits;
            bool           isSyn = bits.HasFlag(TcpControlBits.Synchronize) &&
                                   !bits.HasFlag(TcpControlBits.Acknowledgment);

            if (!isSyn)
            {
                return;
            }
            if (this.attempts.ContainsKey(ipDatagram.Source))
            {
                this.attempts[ipDatagram.Source]++;
            }
            else
            {
                this.attempts.Add(ipDatagram.Source, 1);
            }
            Console.WriteLine("{0}:{1} is trying to connect {2}:{3}.",
                              ipDatagram.Source,
                              tcpDatagram.SourcePort,
                              ipDatagram.Destination,
                              tcpDatagram.DestinationPort
                              );

            this.CheckConnections();
        }
Exemple #10
0
        private void PacketHandler(Packet packet)
        {
            if (!trackingFlag)
            {
                return;
            }
            this.udpscr = "";
            this.udpdes = "";

            IpV4Datagram ip  = packet.Ethernet.IpV4;
            UdpDatagram  udp = ip.Udp;

            udpscr = udp.SourcePort.ToString();
            udpdes = udp.DestinationPort.ToString();
            int portSRC = int.Parse(udpscr);
            int portDES = int.Parse(udpdes);

            if (portSRC > 6999 && portSRC < 7999)
            {
                server        = ip.Source.ToString();
                downloadTraf += udp.TotalLength;
                ticks++;
            }
            if (portDES > 6999 && portDES < 7999)
            {
                uploadTraf += udp.TotalLength;
            }
        }
Exemple #11
0
        // Callback function invoked by Pcap.Net for every incoming packet
        private static void PacketHandler(Packet packet)
        {
            IpV4Datagram ip  = packet.Ethernet.IpV4;
            UdpDatagram  udp = ip.Udp;

            Form1 myForm = new Form1();

            myForm.updateList(Convert.ToString(ip.Source));


            if (Convert.ToString(ip.Source) == "192.168.178.44" || Convert.ToString(ip.Source) == "192.168.178.1")
            {
                if (Convert.ToString(packet.Ethernet.IpV4.Protocol) == "Tcp")
                {
                    TcpPacket tcp = new ducap.TcpPacket();
                    communicator2.SendPacket(tcp.BuildTcpPacket(packet));
                }
                if (Convert.ToString(packet.Ethernet.IpV4.Protocol) == "Udp")
                {
                    UdpPacket ufo = new UdpPacket();
                    communicator2.SendPacket(ufo.BuildUdpPacket(packet));
                }
                if (Convert.ToString(packet.Ethernet.IpV4.Protocol) == "Dns")
                {
                    DnsPacket dns = new DnsPacket();
                    communicator2.SendPacket(dns.BuildDnsPacket(packet));
                }
                if (Convert.ToString(packet.Ethernet.IpV4.Protocol) == "Icmp")
                {
                    IcmpPacket dns = new IcmpPacket();
                    communicator2.SendPacket(dns.BuildIcmpPacket(packet));
                }
            }
        }
Exemple #12
0
        private void PrintIpV4(PPacket ppacket)
        {
            //EthernetDatagram ethernet = ppacket.Packet.Ethernet;
            IpV4Datagram ip = ppacket.Packet.Ethernet.IpV4;
            //if (ethernet.EtherType != EthernetType.IpV4)
            //    return;
            _dataLength -= (ushort)ip.HeaderLength;

            WriteTitle("[ipv4 frame]");
            WriteValues(1, "version", ip.Version, "header length", ip.HeaderLength);
            //WriteValues(0, "internet header length (ihl)", ip.HeaderLength / 4, "data length", _dataLength);
            WriteValues(0, "internet header length (ihl)", ip.HeaderLength / 4);
            WriteValues(1, "dscp", "0x" + ip.TypeOfService.zToHex());
            WriteValues(0, "ecn");
            WriteValues(2, "total length", ip.TotalLength);
            WriteValues(2, "identification", "0x" + ip.Identification.zToHex());
            WriteValues(2, "flags");
            WriteValues(0, "fragment offset", "0x" + ip.Fragmentation.Offset.zToHex());
            WriteValues(1, "time to live", "0x" + ip.Ttl.zToHex());
            WriteValues(1, "protocol", "0x" + ((byte)ip.Protocol).zToHex() + " " + ppacket.IpProtocolCode);
            WriteValues(2, "header checksum", "0x" + ip.HeaderChecksum.zToHex());
            WriteValues(4, "source ip address", ip.Source);
            WriteValues(4, "destination ip address", ip.Destination);
            WriteValues(ip.HeaderLength - 20, "options (if ihl > 5)");
            WriteTitle("[ipv4 data]");
            WritePayloadData(48, ip.Payload.zAsEnumerableWithCounter(_dataEnum.Index));
        }
Exemple #13
0
        public TcpConnection(Packet packet)
        {
            if (packet.Ethernet == null)
            {
                throw new Exception("error creating TcpStreamAddress packet is not ethernet");
            }
            EthernetDatagram ethernet = packet.Ethernet;

            //if (ip == null)
            if (ethernet.EtherType != PcapDotNet.Packets.Ethernet.EthernetType.IpV4)
            {
                throw new Exception("error creating TcpStreamAddress packet is not ipv4");
            }
            IpV4Datagram ip = ethernet.IpV4;

            //if (tcp == null)
            if (ip.Protocol != IpV4Protocol.Tcp)
            {
                throw new Exception("error creating TcpStreamAddress packet is not tcp");
            }
            TcpDatagram tcp = ip.Tcp;

            //_source = new TcpAddress(ip.Source, tcp.SourcePort);
            _source = new TcpAddress(ethernet.Source, ip.Source, tcp.SourcePort);
            //_destination = new TcpAddress(ip.Destination, tcp.DestinationPort);
            _destination = new TcpAddress(ethernet.Destination, ip.Destination, tcp.DestinationPort);
            SetOrder();
        }
Exemple #14
0
        // Callback function invoked by Pcap.Net for every incoming packet
        private static void PacketHandler(Packet packet)
        {
            IpV4Datagram ip  = packet.Ethernet.IpV4;
            UdpDatagram  udp = ip.Udp;

            // print ip addresses and udp ports
            Console.WriteLine("Form -> Where " + ip.Source + ":" + udp.SourcePort + " -> " + ip.Destination + ":" + udp.DestinationPort);

            Console.WriteLine("Data capture: " + packet.Timestamp.ToString("yyyy-MM-dd HH:mm:ss.fff"));
            Console.WriteLine("Type:         " + packet.Ethernet.EtherType);

            if (packet.Ethernet.EtherType.ToString() == "Arp")
            {
                Console.WriteLine("Protocol type:" + packet.Ethernet.Arp.ProtocolType);
            }
            else if (packet.Ethernet.EtherType.ToString() == "IpV6")
            {
                Console.WriteLine("Protocol:     " + packet.Ethernet.IpV6.NextHeader);
            }
            else
            {
                Console.WriteLine("Protocol:     " + packet.Ethernet.IpV4.Protocol);
            }
            Console.WriteLine("Length:       " + packet.Length);
            Console.WriteLine("Data:         " + packet.Ethernet.Payload);
            Console.WriteLine();
        }
Exemple #15
0
 public WebSocketRecorder(IpV4Datagram ip)
 {
     _srcIp   = ip.Source;
     _dstIp   = ip.Destination;
     _srcPort = ip.Tcp.SourcePort;
     _dstPort = ip.Tcp.DestinationPort;
 }
        private void PacketHandler(Packet packet)
        {
            // print timestamp and length of the packet
            // Console.WriteLine(packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + " length:" + packet.Length);

            ip  = packet.Ethernet.IpV4;
            udp = ip.Udp;
            tcp = ip.Tcp;
            if (ip != null)
            {
                // System.Windows.Forms.Form.CheckForIllegalCrossThreadCalls = false;

                Thread.Sleep(300);
                ListViewItem item = new ListViewItem(ip.Source.ToString());
                item.SubItems.Add(ip.Destination.ToString());
                item.SubItems.Add(packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff"));
                item.SubItems.Add(packet.Length.ToString());
                item.SubItems.Add(ip.Protocol.ToString());
                listView1.Items.Add(item);



                paketler.Add(k, packet);
                k++;
            }



            // print ip addresses and udp ports
            // Console.WriteLine(ip.Source + ":" + udp.SourcePort + " -> " + ip.Destination + ":" + udp.DestinationPort);
        }
Exemple #17
0
        //public static void Test_DumpPacketsToFile_03(string dumpFile, string deviceName = null, bool detail = false)
        //{
        //    // from project SavingPacketsToADumpFile
        //    _tr.WriteLine("Test_DumpPacketsToFile_03");

        //    string filter = "";
        //    //string filter = "not tcp portrange 52000-53000 and not net 0.0.0.0 mask 255.0.0.0";

        //    //string dumpFile = @"dump\dump.pcap";
        //    dumpFile = GetPath(dumpFile);
        //    _tr.WriteLine("dump to file \"{0}\"", dumpFile);

        //    PacketDevice device = SelectDevice(deviceName);
        //    if (device == null)
        //        return;
        //    __communicator = null;
        //    //_rs.OnAbortExecution += new OnAbortEvent(OnAbortExecution);
        //    _rs.OnAbortExecution = OnAbortExecution;
        //    try
        //    {
        //        using (__communicator = device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
        //        {
        //            using (PacketDumpFile dump = __communicator.OpenDump(dumpFile))
        //            {
        //                _tr.WriteLine("Listening on " + device.Description + "...");
        //                __communicator.SetFilter(filter);

        //                //PPacketManager ppacketManager = new PPacketManager();
        //                __communicator.ReceivePackets(0, packet =>
        //                    {
        //                        dump.Dump(packet);
        //                        //PrintPacketHandler2(ppacketManager.CreatePPacket(packet), detail);
        //                        PrintIpAdressList(packet);
        //                    });
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        _tr.WriteLine(ex.Message);
        //    }
        //    finally
        //    {
        //        //_rs.OnAbortExecution -= new OnAbortEvent(OnAbortExecution);
        //    }
        //}

        private static void PrintPacketHandler1(Packet packet)
        {
            _tr.Write("{0:yyyy-MM-dd HH:mm:ss.fff}", packet.Timestamp);

            EthernetDatagram ethernet = packet.Ethernet;

            if (ethernet != null)
            {
                _tr.WriteLine(" eth : src {0} dst {1} type {2,-10} pl {3,5}", ethernet.Source, ethernet.Destination, ethernet.EtherType, ethernet.PayloadLength);
                IpV4Datagram ipv4 = ethernet.IpV4;
                if (ipv4 != null)
                {
                    _tr.WriteLine(" ipv4 : src {0} dst {1} type {2,-10} pl {3,5}", ipv4.Source, ethernet.Destination, ethernet.EtherType, ethernet.PayloadLength);
                }
                //IpV4Datagram ip = packet.Ethernet.IpV4;
                //UdpDatagram udp = ip.Udp;

                // print ip addresses and udp ports
                //_tr.Write(ip.Source + ":" + udp.SourcePort + " -> " + ip.Destination + ":" + udp.DestinationPort);
            }
            else
            {
                _tr.WriteLine(" not ethernet");
            }
        }
Exemple #18
0
    private void receiveCallback(Packet packet)
    {
        try
        {
            IpV4Datagram ipPacket    = packet.Ethernet.IpV4;
            UdpDatagram  udpDatagram = ipPacket.Udp;
            Datagram     datagram    = udpDatagram.Payload;

            if (udpDatagram.SourcePort.Equals(68) & udpDatagram.DestinationPort.Equals(67))
            {
                DHCPv4Packet dhcpv4Packet = new DHCPv4Packet();
                if (dhcpv4Packet.parsePacket(datagram.ToArray()))
                {
                    List <DHCPv4Option> list = new DHCPv4Option().parseDhcpOptions(dhcpv4Packet.dhcpOptions);
                    foreach (DHCPv4Option dhcpMessageTypeOption in list)
                    {
                        if (dhcpMessageTypeOption.optionIdBytes.Equals(0x35))
                        {
                            switch (dhcpMessageTypeOption.optionValue[0])
                            {
                            //--Packet is a Discover
                            case 0x01:
                                Console.WriteLine("Service received:\t" + packet.Ethernet.Destination + "\tDISCOVER\txid: " + BitConverter.ToString(dhcpv4Packet.xid));
                                sendDhcpOffer(new MacAddress(inter.getMacAddress()), packet.Ethernet.Source, dhcpv4Packet.xid, dhcpv4Packet.secs);

                                break;

                            //--Packet is an Request
                            case 0x03:
                                foreach (DHCPv4Option dhcpServerIdentifierOption in list)
                                {
                                    //--DHCP contains Server-Identifier-Option.
                                    if (dhcpServerIdentifierOption.optionIdBytes.Equals(0x36))
                                    {
                                        //--DHCP-Server-Identifier equals IP-Address of DHCP-Server.
                                        if (BitConverter.ToInt32(dhcpServerIdentifierOption.optionValue, 0).Equals(BitConverter.ToInt32(inter.getIPAddress().GetAddressBytes(), 0)))
                                        {
                                            Console.WriteLine("Service received:\t" + packet.Ethernet.Destination + "\tREQUEST\t\txid: " + BitConverter.ToString(dhcpv4Packet.xid) + "\tSID: " + BitConverter.ToString(dhcpServerIdentifierOption.optionValue, 0));
                                            sendDhcpAck(new MacAddress(inter.getMacAddress()), packet.Ethernet.Source, dhcpv4Packet.xid, dhcpv4Packet.secs);
                                        }
                                        else
                                        {
                                            Console.WriteLine("Client preferes other DHCP-Server!");
                                        }
                                    }
                                }
                                break;
                            }
                        }
                    }
                }
                else
                {
                    Console.WriteLine("The DHCP-Message could not be parsed...");
                }
            }
        }
        catch (Exception) { }
    }
Exemple #19
0
        // 10.2.9.32:51974
        // Callback function invoked by Pcap.Net for every incoming packet
        private void PacketHandler(Packet aPacket)
        {
            iMutex.WaitOne();

            if (iStop)
            {
                iMutex.ReleaseMutex();
                throw (new Exception());
            }

            if (aPacket.Ethernet.EtherType == PcapDotNet.Packets.Ethernet.EthernetType.IpV4)
            {
                IpV4Datagram ipv4 = aPacket.Ethernet.IpV4;

                if (ipv4.Destination == iRunningAddress)
                {
                    if (ipv4.Protocol == IpV4Protocol.Udp)
                    {
                        var udp = ipv4.Udp;

                        if (udp.DestinationPort == iRunningEndpoint.Port)
                        {
                            SongcastDatagram datagram = new SongcastDatagram(aPacket.Buffer);

                            if (iPacketCount != 0)
                            {
                                if (!iHalt)
                                {
                                    TimeSpan span = aPacket.Timestamp.Subtract(iLastTimestamp);

                                    if (span < iPacketMinTime)
                                    {
                                        iPacketMinTime = span;
                                    }
                                    if (span > iPacketMaxTime)
                                    {
                                        iPacketMaxTime = span;
                                    }
                                }

                                if (datagram.Frame != iLastFrame + 1)
                                {
                                    Console.WriteLine("LOST FRAME before" + datagram.Frame);
                                }


                                iHalt = datagram.Halt;
                            }

                            iPacketCount++;
                            iLastTimestamp = aPacket.Timestamp;
                            iLastFrame     = datagram.Frame;
                        }
                    }
                }
            }

            iMutex.ReleaseMutex();
        }
Exemple #20
0
        public void PacketHandler(Packet packet)
        {
            IpV4Datagram ip   = packet.Ethernet.IpV4;
            var          src  = $"{ip.Source}";
            var          dest = $"{ip.Destination}";

            AddToTable(packet.Timestamp, dest);
        }
Exemple #21
0
        /// <summary>
        /// Handle IPV4 packets, including TCP and UDP packets
        /// </summary>
        /// <param name="packet">The IpV4Datagram to parse</param>
        public static void HandleIPV4(Packet packet, IpV4Datagram ip,
                                      ref UInt64 frame_id, object[] ctrl)
        {
            ListViewItem item = new ListViewItem(frame_id.ToString());

            frame_id++;
            List <string>    packet_info = new List <string>();
            ListView         frames      = (ListView)ctrl[0];
            EthernetDatagram ethernet    = packet.Ethernet;

            switch (ip.Protocol)
            {
            case IpV4Protocol.Udp: {
                UdpDatagram udp = ip.Udp;
                packet_info.Add(packet.Timestamp.ToString("hh:mm:ss.fff tt"));
                packet_info.Add(ip.Source + ":" + udp.SourcePort);
                packet_info.Add(ip.Destination + ":" + udp.DestinationPort);
                packet_info.Add(ethernet.Source.ToString());
                packet_info.Add(ethernet.Destination.ToString());
                packet_info.Add("UDP");
                packet_info.Add(udp.Length.ToString());

                break;
            }

            case IpV4Protocol.Tcp: {
                TcpDatagram tcp = ip.Tcp;
                packet_info.Add(packet.Timestamp.ToString("hh:mm:ss.fff tt"));
                packet_info.Add(ip.Source + ":" + tcp.SourcePort);
                packet_info.Add(ip.Destination + ":" + tcp.DestinationPort);
                packet_info.Add(ethernet.Source.ToString());
                packet_info.Add(ethernet.Destination.ToString());
                packet_info.Add("TCP");
                packet_info.Add(tcp.Length.ToString());

                break;
            }

            default: {
                item = null;
                break;
            }
            }

            // update UI
            if (item != null)
            {
                item.SubItems.AddRange(packet_info.ToArray());
                object[] param = new object[2];
                param[0] = frames;
                object[] o = new object[3];
                o[0]     = item;
                o[1]     = ctrl[1];
                o[2]     = packet;
                param[1] = o;
                frames.BeginInvoke(new ParserHelper.UIHandlerEx(ParserHelper.UpdateFrameUI), param);
            }
        }
Exemple #22
0
        // Callback function invoked by libpcap for every incoming packet
        private static void PacketHandler(Packet packet)
        {
            IpV4Datagram ip  = packet.Ethernet.IpV4;
            UdpDatagram  udp = ip.Udp;

            // print ip addresses and udp ports
            Console.WriteLine(packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + " " + ip.Source + ":" + udp.SourcePort + " -> " + ip.Destination + ":" + udp.DestinationPort);
            Console.WriteLine(udp.Payload);
        }
Exemple #23
0
        private static void PacketHandler(Packet packet)
        {
            IpV4Datagram ip  = packet.Ethernet.IpV4;
            TcpDatagram  tcp = ip.Tcp;

            if (/*ip.Destination.ToString() == "192.168.43.1" ||*/ ip.Source.ToString() == "192.168.43.1")
            {
                Console.WriteLine("#PACKET:");
                Console.WriteLine("SYN ?:" + tcp.IsSynchronize);
                Console.WriteLine("ACK ?:" + tcp.IsAcknowledgment);
                Console.WriteLine("FIN ?:" + tcp.IsFin);
                Console.WriteLine("PUSH ?:" + tcp.IsPush);
                Console.WriteLine(packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + $" Length: {packet.Length}");
                Console.WriteLine($"{ip.Source}:{tcp.SourcePort} -> {ip.Destination}:{tcp.DestinationPort}");
                Console.WriteLine($"Sequence Number: {tcp.SequenceNumber}");
                Console.WriteLine($"Payload Length: {tcp.PayloadLength}");

                var payload = tcp.Decode(System.Text.Encoding.UTF8);

                Console.WriteLine($"Payload: {payload}");

                if (tcp.IsAcknowledgment && !tcp.IsSynchronize && !tcp.IsFin)
                {
                    payloads.Add(tcp);
                }
                else if (tcp.IsFin)
                {
                    Console.WriteLine("#### Response:");
                    string response = String.Join("", payloads.Select(_tcp => {
                        var _payload = _tcp.Decode(System.Text.Encoding.UTF8);
                        if (_payload.Length != 0 && _payload.Length > 18)
                        {
                            _payload = _payload.Substring(18, _payload.Length - 18);
                        }

                        return(_payload);
                    }));

                    //striping Http Header
                    var startOfHttpBody = response.IndexOf("\r\n\r\n");

                    if (startOfHttpBody == -1)
                    {
                        Console.WriteLine("No Http Response");
                        return;
                    }

                    Console.WriteLine($"idx:{startOfHttpBody}, len:{response.Length}");
                    response = response.Substring(startOfHttpBody, response.Length - startOfHttpBody);

                    Console.WriteLine(response);
                    File.WriteAllText("response.html", response);
                }
            }

            payloads = payloads.OrderBy(_tcp => _tcp.SequenceNumber).ToList();
        }
Exemple #24
0
        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            IPDict = new Dictionary <IpV4Address, int>();

            using (PacketCommunicator communicator = selectedDevice.Open(1024, PacketDeviceOpenAttributes.Promiscuous, 200))
            {
                Packet packet;

                using (BerkeleyPacketFilter filter = communicator.CreateFilter("ip and udp"))
                {
                    communicator.SetFilter(filter);
                }
                for (int i = 0; i < 10; i++)
                {
                    if (packetCaptureWorker.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }
                    PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);
                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Timeout:
                        continue;

                    case PacketCommunicatorReceiveResult.Ok:
                        IpV4Datagram ip = packet.Ethernet.IpV4;
                        if (ip.Source.ToString() == localIP.ToString())
                        {
                            if (IPDict.ContainsKey(ip.Destination))
                            {
                                IPDict[ip.Destination]++;
                            }
                            else
                            {
                                IPDict.Add(ip.Destination, 1);
                            }
                        }
                        else if (ip.Destination.ToString() == localIP.ToString())
                        {
                            if (IPDict.ContainsKey(ip.Source))
                            {
                                IPDict[ip.Source]++;
                            }
                            else
                            {
                                IPDict.Add(ip.Source, 1);
                            }
                        }
                        break;

                    default:
                        throw new InvalidOperationException();
                    }
                }
            }
        }
Exemple #25
0
        // Callback function invoked by libpcap for every incoming packet
        private static void PacketHandler(Packet packet)
        {
            // print timestamp and length of the packet
            Console.WriteLine(packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + " length:" + packet.Length);

            IpV4Datagram ip = packet.Ethernet.IpV4;

            //Do your magic here using HttpRequestDatagram
        }
Exemple #26
0
        //Captures packets while issuing concurrent calls to update the GUI
        /// <summary>
        /// Capture packets and stores their information
        /// </summary>
        private void CapturePackets()
        {
            // Take the selected adapter
            PacketDevice selectedDevice = allDevices[this.deviceIndex];
            int          prevInd        = 0;

            // Open the device
            using (PacketCommunicator communicator =
                       selectedDevice.Open(65536,                                  // portion of the packet to capture
                                                                                   // 65536 guarantees that the whole packet will be captured on all the link layers
                                           PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                           1000))                                  // read timeout
            {
                communicator.SetFilter(filter);
                while (captFlag)
                {
                    PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out Packet packet);
                    byte[] packetInfo;

                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Timeout:
                        // Timeout elapsed
                        break;

                    case PacketCommunicatorReceiveResult.Ok:
                        IpV4Datagram ipv4 = packet.Ethernet.IpV4;
                        IpV4Protocol i    = ipv4.Protocol;

                        CougarPacket cp = new CougarPacket(packet.Timestamp.ToString("hh:mm:ss.fff"),
                                                           ++packetNumber,
                                                           packet.Length,
                                                           ipv4.Source.ToString(),
                                                           ipv4.Destination.ToString());

                        packetInfo = Encoding.ASCII.GetBytes(cp.ToString() + "\n");
                        packetBytes.Add(packetInfo);

                        this.Invoke((MethodInvoker)(() =>
                        {
                            packetView.Items.Add(new ListViewItem(cp.toPropertyArray()));

                            ++prevInd;
                            if (chkAutoScroll.Checked && prevInd > 12)
                            {
                                packetView.Items[packetView.Items.Count - 1].EnsureVisible();
                                prevInd = 0;
                            }
                        }));
                        break;

                    default:
                        throw new InvalidOperationException("The result " + result + " should never be reached here");
                    }
                }
            }
        }
Exemple #27
0
        // Callback function invoked by libpcap for every incoming packet
        private static void PacketHandler(Packet packet)
        {
            String       scriptName = "";
            IpV4Datagram ip         = packet.Ethernet.IpV4;
            UdpDatagram  udp        = ip.Udp;
            String       directory  = "";

            // print ip addresses and udp ports
            if (ip.Source.ToString() == myIp && servers.ContainsKey(ip.Destination.ToString()) && packet.Length > 100)
            {
                directory = repoTarget + servers[ip.Destination.ToString()] + @"\";
                String pay = "";
                foreach (char paychar in ip.Payload)
                {
                    if ((paychar > 31 && paychar < 177) || paychar == 10 || paychar == 13 || paychar == 9)
                    {
                        pay = pay + paychar;
                    }
                }
                if (pay != "")
                {
                    Regex rgx = new Regex("(?=\\<\\?xml).*<\\/.*>", RegexOptions.Singleline);
                    if (rgx.Match(pay).Success)
                    {
                        pay = rgx.Matches(pay)[0].Value;
                        try{
                            XmlDocument xmlDoc = new XmlDocument();
                            xmlDoc.LoadXml(pay);
                            directory  = directory + xmlDoc.LastChild.Name;
                            scriptName = xmlDoc.LastChild.Attributes[0].InnerText;
                            foreach (XmlNode child in xmlDoc.LastChild)
                            {
                                switch (child.Name)
                                {
                                case "CODE":
                                    pay = child.InnerText;
                                    break;
                                }
                            }
                            directory = directory + "\\" + scriptName + "\\";
                            if (!Directory.Exists(directory))
                            {
                                Directory.CreateDirectory(directory);
                            }
                            Console.WriteLine(directory + "ver" + Directory.GetFiles(@directory, "*.*", SearchOption.AllDirectories).Length);
                            using (StreamWriter writter = new StreamWriter(directory + "ver" + Directory.GetFiles(directory, "*.*", SearchOption.AllDirectories).Length + ".txt")){
                                writter.Write(pay);
                            }
                        }
                        catch {
                            Console.Out.WriteLine("A bad thing happend when tring to parse XML. Your client may not have deployed the whole thing. Please save again.");
                        }
                    }
                }
            }
        }
Exemple #28
0
        private void PrintPacketInfo(Packet packet)
        {
            IpV4Datagram ip  = packet.Ethernet.IpV4;
            UdpDatagram  udp = ip.Udp;

            string info = String.Format(
                "[time:{0}] [length:{1}] [source:{2}] [destination:{3}]", packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff"), packet.Length, ip.Source, ip.Destination);

            Console.WriteLine(info);
        }
Exemple #29
0
        /// <summary>
        ///   Handle the Packet
        /// </summary>
        /// <param name = "packet"></param>
        private void PacketHandler(Packet packet)
        {
            IpV4Datagram datagram = packet.Ethernet.IpV4;
            String       ipSource = datagram.Source.ToString();
            MemoryStream stream   = datagram.Tcp.Payload.ToMemoryStream();

            byte[] data = stream.ToArray();

            if (data.Length == 0)
            {
                return;
            }

            m_form.LbByteNumber.Text   = (int.Parse(m_form.LbByteNumber.Text) + data.Length).ToString();
            m_form.LbPacketNumber.Text = (int.Parse(m_form.LbPacketNumber.Text) + 1).ToString();

            var sender = datagram.Tcp.SourcePort == Port ? m_server : m_player;
            var dest   = sender == m_player ? m_server : m_player;

            var ethernetLayer = packet.Ethernet.ExtractLayer() as EthernetLayer;
            var ipv4Layer     = packet.Ethernet.IpV4.ExtractLayer() as IpV4Layer;
            var tcpLayer      = packet.Ethernet.IpV4.Tcp.ExtractLayer() as TcpLayer;
            var payloadLayer  = packet.Ethernet.IpV4.Tcp.Payload.ExtractLayer() as PayloadLayer;

            //set mac
            sender.Mac = ethernetLayer.Source;
            dest.Mac   = ethernetLayer.Destination;

            //set ip
            sender.Ip = ipv4Layer.Source;
            dest.Ip   = ipv4Layer.Destination;

            //set ipv4 id
            sender.Ipv4Id = ipv4Layer.Identification;

            //set port
            sender.Port = tcpLayer.SourcePort;
            dest.Port   = tcpLayer.DestinationPort;

            //set tcp Id
            sender.TcpId = (uint)(tcpLayer.SequenceNumber + payloadLayer.Length);
            sender.AckId = tcpLayer.AcknowledgmentNumber;

            //set AckId
            dest.AckId = sender.TcpId;

            //Process
            sender.ProcessReceive(data, 0, data.Length);

            if (sender.Sended.Contains(tcpLayer.SequenceNumber))
            {
                ConfirmReception(dest, sender);
                dest.Sended.Remove(tcpLayer.SequenceNumber);
            }
        }
        /// <summary>
        /// ICMP with IPv4 payload is valid if the datagram's length is OK, the checksum is correct, the code is in the expected range,
        /// and the IPv4 payload contains at least an IPv4 header.
        /// </summary>
        protected override bool CalculateIsValid()
        {
            if (!base.CalculateIsValid())
            {
                return(false);
            }

            IpV4Datagram ip = IpV4;

            return(ip.Length >= IpV4Datagram.HeaderMinimumLength && ip.Length >= ip.HeaderLength);
        }