Ejemplo n.º 1
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;
            }
        }
Ejemplo n.º 2
0
        public void Send(byte[] buffer, int length)
        {
            // make sure that a default destination IPEndpoint has been configured.
            if ((destinationIpAddress == IPv6Any) || (destinationPort == IPPortAny))
            {
                throw new SocketsException("Socket is not connected.");
            }

            UdpDatagram udpDatagram = new UdpDatagram();

            udpDatagram.DestinationPort = destinationPort;
            udpDatagram.SourcePort      = sourcePort;
            udpDatagram.AddPayload(buffer);
            udpDatagram.Checksum = 0;


            IPv6Packet packetUDP = new IPv6Packet();

            packetUDP.SourceAddress      = sourceIpAddress;
            packetUDP.DestinationAddress = destinationIpAddress;
            packetUDP.NextHeader         = IPv6Protocol.Udp;
            packetUDP.Payload            = udpDatagram;
            packetUDP.PayloadLength      = udpDatagram.Length;


            IPv6PseudoHeader ipv6PseudoHeader = new IPv6PseudoHeader(packetUDP.SourceAddress, packetUDP.DestinationAddress, packetUDP.PayloadLength, (byte)packetUDP.NextHeader);
            ushort           checkSum         = ipv6PseudoHeader.GetCheckSum();

            checkSum = NetUtilities.ComputeChecksum(checkSum, udpDatagram.ToBytes(), true);

            udpDatagram.Checksum = checkSum;

            NetworkingInterface.Send(packetUDP.ToBytes());
        }
Ejemplo n.º 3
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;
            }
        }
Ejemplo n.º 4
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));
                }
            }
        }
Ejemplo n.º 5
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();
        }
Ejemplo n.º 6
0
        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);
        }
Ejemplo n.º 7
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) { }
    }
Ejemplo n.º 8
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);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Gets the key for Ethernet frame.
        /// </summary>
        /// <param name="frameBytes">Bytes that contains Ethernet frame.</param>
        /// <returns><see cref="FlowKey"/> for the provided Ethernet frame.</returns>
        public static FlowKey GetKeyForEthernetFrame(byte[] frameBytes)
        {
            var etherType    = EthernetFrame.GetEtherType(frameBytes);
            var etherPayload = EthernetFrame.GetPayloadBytes(frameBytes);

            Span <Byte> ipPayload     = stackalloc byte[0];
            var         protocol      = 0;
            Span <Byte> sourceAddress = stackalloc byte[4];
            Span <Byte> destinAddress = stackalloc byte[4];
            UInt16      sourcePort    = 0;
            UInt16      destinPort    = 0;

            switch (etherType)
            {
            case (ushort)EthernetFrame.EtherTypeEnum.Ipv4:
            {
                sourceAddress = Ipv4Packet.GetSourceAddress(etherPayload);
                destinAddress = Ipv4Packet.GetDestinationAddress(etherPayload);
                ipPayload     = Ipv4Packet.GetPayloadBytes(etherPayload);
                protocol      = Ipv4Packet.GetProtocol(etherPayload);
                break;
            }

            case (ushort)EthernetFrame.EtherTypeEnum.Ipv6:
            {
                sourceAddress = Ipv6Packet.GetSourceAddress(etherPayload);
                destinAddress = Ipv6Packet.GetDestinationAddress(etherPayload);
                ipPayload     = Ipv6Packet.GetPayloadBytes(etherPayload);
                protocol      = Ipv6Packet.GetProtocol(etherPayload);
                break;
            }

            default:
                break;
            }
            switch (protocol)
            {
            case 6:      // TCP
            {
                sourcePort = TcpSegment.GetSourcePort(ipPayload);
                destinPort = TcpSegment.GetDestinationPort(ipPayload);
                break;
            }

            case 17:     // UDP
            {
                sourcePort = UdpDatagram.GetSourcePort(ipPayload);
                destinPort = UdpDatagram.GetDestinationPort(ipPayload);
                break;
            }

            default:
                break;
            }
            // ok we have enough information for creating packet's flow key
            return(FlowKey.Create((byte)protocol, sourceAddress, sourcePort, destinAddress, destinPort));
        }
Ejemplo n.º 10
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.");
                        }
                    }
                }
            }
        }
Ejemplo n.º 11
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);
        }
Ejemplo n.º 12
0
            public Syslog Parse(UdpDatagram receivedPacket)
            {
                if (receivedPacket.Protocol != ProtocolType.Udp)
                {
                    throw new NotSupportedException("Datagrams other than UDP not supported to generate Syslogs.");
                }

                string logMessage = Encoding.ASCII.GetString(receivedPacket.UdpData);

                if (string.IsNullOrWhiteSpace(logMessage))
                {
                    throw new ArgumentException("Incoming UDP datagram contained no Syslog data.");
                }

                var defMatch = this.parser.Match(logMessage);

                if (!defMatch.Success)
                {
                    throw new ArgumentException("Cannot parse the incoming UDP datagram.");
                }

                if (defMatch.Groups.Count < 1)
                {
                    throw new ArgumentException("Only no parsable fields in the incoming Syslog");
                }

                var privalMatch = defMatch.Groups["PRIVAL"].Value.Trim();

                if (string.IsNullOrWhiteSpace(privalMatch))
                {
                    throw new ArgumentException(
                              "Datagram does not contain the correct string indicating the PRIVAL of the Syslog");
                }



                var prival   = int.Parse(privalMatch);
                var severity = (Severity)Enum.ToObject(typeof(Severity), prival & 0x7);
                var facility = (Facility)Enum.ToObject(typeof(Facility), prival >> 3);
                var message  = defMatch.Groups["MESSAGE"].Value.Trim();

                var matches = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

                foreach (var groupName in this.groupNames)
                {
                    var group = defMatch.Groups[groupName];

                    if (group.Success && !string.IsNullOrEmpty(group.Value))
                    {
                        matches[groupName] = group.Value;
                    }
                }

                return(new Syslog(receivedPacket.ReceivedTime, receivedPacket.SourceIpAddress.ToString(), severity, facility, message, matches));
            }
Ejemplo n.º 13
0
        private static void PacketHandler2(Packet packet)
        {
            Console.WriteLine("***************************************************************");
            // 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;
            UdpDatagram  udp = ip.Udp;

            // print ip addresses and udp ports
            Console.WriteLine(ip.Source + ":" + udp.SourcePort + " -> " + ip.Destination + ":" + udp.DestinationPort);
        }
Ejemplo n.º 14
0
        private void PacketHandler(Packet packet)
        {
            IpV4Datagram ip  = packet.Ethernet.IpV4;
            UdpDatagram  udp = ip.Udp;

            if (udp == null || (udp.SourcePort != 5056 && udp.DestinationPort != 5056))
            {
                return;
            }

            photonParser.ReceivePacket(udp.Payload.ToArray());
        }
Ejemplo n.º 15
0
        private void PacketHandler(Packet packet)
        {
            IpV4Datagram ip  = packet.Ethernet.IpV4;
            UdpDatagram  udp = ip.Udp;

            if (udp == null || (udp.SourcePort != GameServerClientPort && udp.DestinationPort != GameServerClientPort))
            {
                return;
            }

            System.Threading.Thread.Sleep(10);
            _photonPackageParser.DeserializeMessageAndCallback(udp);
        }
Ejemplo n.º 16
0
        // Callback function invoked by libpcap for every incoming packet
        private static void InterpretingPacketHandler(Packet packet)
        {
            // print timestamp and length of the packet
            _tr.WriteLine(packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + " length:" + packet.Length);

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

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

            //if (_wr.IsExecutionAborted())
            //    __communicator.Break();
        }
        public static void TestDecoratorDesign()
        {
            AppDatagram appDatagram = new AppDatagram();

            appDatagram.SendData();

            TcpDatagram tcpDatagram = new TcpDatagram(appDatagram);

            tcpDatagram.SendData();

            UdpDatagram udpDatagram = new UdpDatagram(appDatagram);

            udpDatagram.SendData();
        }
Ejemplo n.º 18
0
        private void GetIpProtocol(Packet packet, PacketInfo info)
        {
            switch (packet.Ethernet.IpV4.Protocol)
            {
            case IpV4Protocol.InternetControlMessageProtocol:
                IcmpDatagram icmp = packet.Ethernet.IpV4.Icmp;
                if (icmp != null)
                {
                    info.Protocol        = "ICMP";
                    info.Info            = "Echo (ping)";
                    info.Layers.ICMPInfo = $"Checksum: {icmp.Checksum}";
                }
                break;

            case IpV4Protocol.Tcp:
                var tcp = packet.Ethernet.IpV4.Tcp;
                info.Protocol = "TCP";
                info.Info     = $"{tcp.SourcePort} → {tcp.DestinationPort} [{GetFlags(tcp)}] " +
                                $"Seq={tcp.SequenceNumber} Win={tcp.Window} Len={tcp.Length}";
                /////////////// HTTP Request//////////////////
                var header = tcp.Http.Header;
                if (header != null)
                {
                    info.Protocol        = "HTTP";
                    info.Layers.HTTPInfo = "Header: " + header;
                }
                /////////////// TCP Layer//////////////////
                info.Layers.TCPInfo = $"Source Port: {tcp.SourcePort}\nDestination Port: {tcp.DestinationPort}" +
                                      $"\nSequence number: {tcp.SequenceNumber}\nNext sequence number: {tcp.NextSequenceNumber}" +
                                      $"\nAcknowledgement number: {tcp.AcknowledgmentNumber}\nHeader Length: {tcp.HeaderLength}" +
                                      $"\nWindow size value: {tcp.Window}\nChecksum: {tcp.Checksum}";
                break;

            case IpV4Protocol.Udp:
                UdpDatagram udp = packet.Ethernet.IpV4.Udp;
                info.Protocol       = "UDP";
                info.Info           = $"{udp.SourcePort} → {udp.DestinationPort} Len={udp.Length}";
                info.Layers.UDPInfo = $"Source Port: {udp.SourcePort}\nDestination Port: {udp.DestinationPort}" +
                                      $"\nLength: {udp.TotalLength}\nChecksum: {udp.Checksum}";
                break;

            case IpV4Protocol.InternetControlMessageProtocolForIpV6:
                info.Protocol = "ICMPv6";
                break;

            default:
                break;
            }
        }
Ejemplo n.º 19
0
        //[DataMember]
        //public int http_header_bytes { get; set; }

        public CustomPacket(Packet packet)
        {
            IpV4Datagram ip  = packet.Ethernet.IpV4;
            UdpDatagram  udp = ip.Udp;
            TcpDatagram  tcp = ip.Tcp;

            ip_lenght         = ip.Length;
            ip_header_lenght  = ip.RealHeaderLength;
            ip_total_lenght   = ip.TotalLength;
            ip_ttl            = ip.Ttl;
            ip_service_type   = ip.TypeOfService;
            ip_header_version = ip.Version;

            udp_check_sum      = udp.Checksum;
            udp_dst_port       = udp.DestinationPort;
            udp_cs_is_optional = udp.IsChecksumOptional;
            udp_is_valid       = udp.IsValid;
            udp_scr_port       = udp.SourcePort;
            udp_total_length   = udp.TotalLength;

            tcp_check_sum      = tcp.Checksum;
            tcp_dst_port       = tcp.DestinationPort;
            tcp_header_lenght  = tcp.HeaderLength;
            tcp_is_ack         = tcp.IsAcknowledgment;
            tcp_cs_is_optional = tcp.IsChecksumOptional;
            tcp_is_cw_reduced  = tcp.IsCongestionWindowReduced;
            tcp_is_ecne        = tcp.IsExplicitCongestionNotificationEcho;
            tcp_is_nonce_sum   = tcp.IsNonceSum;
            tcp_is_fin         = tcp.IsFin;
            tcp_is_push        = tcp.IsPush;
            tcp_is_reset       = tcp.IsReset;
            tcp_is_syn         = tcp.IsSynchronize;
            tcp_is_urgent      = tcp.IsUrgent;
            tcp_is_valid       = tcp.IsValid;
            tcp_lenght         = tcp.Length;
            tcp_upointer       = tcp.UrgentPointer;
            tcp_window         = tcp.Window;

            if (tcp.Http != null)
            {
                http_is_request  = tcp.Http.IsRequest;
                http_is_response = tcp.Http.IsResponse;
            }
            else
            {
                http_is_request  = false;
                http_is_response = false;
            }
        }
Ejemplo n.º 20
0
        public static SnmpDatagram TryParseSnmpDatagram(this UdpDatagram udpDatagram)
        {
            try
            {
                var transportObject = udpDatagram.TransportObject;
                var datagram        = udpDatagram.UdpData.ToSnmpDatagram();
                udpDatagram.TransportObject = datagram;

                return(datagram);
            }
            catch
            {
                return(default(SnmpDatagram));
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Receives packet's datagram
        /// </summary>
        /// <returns>Tcp or Udp</returns>
        public static TransportDatagram GetDatagram(this Packet packet)
        {
            IpV4Datagram ip = packet.Ethernet.IpV4;

            if (ip.Protocol == IpV4Protocol.Tcp)
            {
                TcpDatagram tcp = ip.Tcp;
                return(tcp);
            }
            else
            {
                UdpDatagram udp = ip.Udp;
                return(udp);
            }
        }
Ejemplo n.º 22
0
        public void TestInitialize()
        {
            var integerVarBind = new VarBind(
                new ObjectIdentifier("1.3.6.1.4.1.1.1.1"),
                5L,
                new Asn1TagInfo(Asn1Tag.Integer, ConstructType.Primitive, Asn1Class.Universal));

            var sysUpTime = new VarBind(new ObjectIdentifier("1.3.6.1.2.1.1.3.0"),
                                        506009u,
                                        new Asn1TagInfo(Asn1SnmpTag.TimeTicks));

            var trapVb = new VarBind(new ObjectIdentifier("1.3.6.1.6.3.1.1.4.1.0"),
                                     new ObjectIdentifier("1.3.6.1.4.1.500.12"),
                                     new Asn1TagInfo(Asn1Tag.ObjectIdentifier, ConstructType.Primitive, Asn1Class.Universal));

            var extraneousVb = new VarBind(new ObjectIdentifier("1.3.6.1.6.3.1.1.42.42.42.0"),
                                           8938ul,
                                           new Asn1TagInfo(Asn1SnmpTag.Counter64));

            var packet = new SnmpDatagram(
                PduType.SNMPv2Trap,
                SnmpVersion.V2C,
                "Community",
                50000,
                SnmpErrorStatus.NoError,
                0,
                new[] { sysUpTime, trapVb, integerVarBind, extraneousVb });

            var encoded = packet.ToSnmpEncodedByteArray();

            var ipPacket = new IpPacket(
                NetworkInterfaceComponent.IPv4,
                Byte.MaxValue,
                Byte.MaxValue,
                Byte.MaxValue,
                UInt16.MaxValue,
                UInt16.MaxValue,
                Byte.MaxValue,
                UInt16.MaxValue,
                Byte.MaxValue,
                ProtocolType.Udp,
                IPAddress.Parse("1.1.1.1"),
                IPAddress.Parse("2.2.2.2"),
                new byte[0],
                new byte[0]);

            this.fakeTrapUdp = new UdpDatagram(ipPacket, 10, 10, (ushort)(encoded.Length + 8), encoded);
        }
Ejemplo n.º 23
0
        private void PrintPacketInfo(Packet packet)
        {
            IpV4Datagram ip  = packet.Ethernet.IpV4;
            UdpDatagram  udp = ip.Udp;

            if (!ip.Destination.ToString().Contains("192"))
            {
                string server = ip.Destination + ":" + udp.DestinationPort;
                ConsoleMsg.Write($"Connected to game server : {server}", ConsoleMsg.Type.Info, true);
                if (!String.IsNullOrEmpty(Constants.DiscordWebHook))
                {
                    Webhook.SendMessage(PlayerName, server);
                }
                pm.Break();
            }
        }
Ejemplo n.º 24
0
        public void TestSyslogCustomParserParsing()
        {
            var testprival = "<140>";
            var severity   = (Severity)Enum.ToObject(typeof(Severity), 140 & 0x7);
            var facility   = (Facility)Enum.ToObject(typeof(Facility), 140 >> 3);

            var testmessage = "A message with any pri-val";
            var testString  = testprival + testmessage;

            var udData = new ArraySegment <byte>(Encoding.ASCII.GetBytes(testString));

            var pHeader = new IpPacketHeader(
                IPAddress.Parse("127.0.0.1"),
                IPAddress.Parse("127.0.0.1"),
                false,
                4,
                0,
                0,
                (ushort)(udData.Array.Length + 20 + 8),
                0,
                0,
                0,
                255,
                0
                );


            var         udHeader = new UdpDatagramHeader(16, 16, (ushort)udData.Array.Length, 0);
            UdpDatagram ud       = new UdpDatagram()
            {
                UdpDatagramHeader = udHeader,
                UdpData           = udData,
                PacketHeader      = pHeader,
                ReceivedTime      = DateTimeOffset.UtcNow
            };

            var customParser = new Regex(@"(?<WithAny>with\sany)", RegexOptions.ExplicitCapture);
            var sysparser    = new SyslogParser(customParser);
            var sys          = sysparser.Parse(ud);

            Assert.IsNotNull(sys);
            Assert.AreEqual(testmessage, sys.Message);
            Assert.AreEqual(severity, sys.LogSeverity);
            Assert.AreEqual(facility, sys.LogFacility);
            Assert.AreEqual("with any", sys.NamedCollectedMatches["WithAny"]);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// asynchronous execution of an RPC request
        /// </summary>
        public IRpcRequest <TResp> Request <TReq, TResp>(call_body callBody, TReq reqArgs)
        {
            RpcRequest <TResp> handler = null;

            try
            {
                handler = NewHandler <TResp>();

                rpc_msg reqHeader = new rpc_msg()
                {
                    xid  = handler.Xid,
                    body = new body()
                    {
                        mtype = msg_type.CALL,
                        cbody = callBody
                    }
                };

                UdpDatagram dtg = new UdpDatagram();
                Writer      w   = Toolkit.CreateWriter(dtg);
                w.Write(reqHeader);
                w.Write(reqArgs);

                byte[] outBuff = dtg.ToArray();

                //Log.Trace(() => "sending byte dump: " + outBuff.ToDisplay());

                handler.OutBuff = outBuff;

                EqueueSend(handler);

                //lock (_sync)
                //	_sendingHandlers.Enqueue(handler);
                //_client.BeginSend(outBuff, outBuff.Length, _ep, handler.DatagramSended, null);
            }
            catch (Exception ex)
            {
                if (handler == null)
                {
                    handler = new RpcRequest <TResp>(null, 0);
                }
                ThreadPool.QueueUserWorkItem((o) => handler.Except(ex));
            }

            return(handler);
        }
Ejemplo n.º 26
0
        public void HandleUdpDatagram(IPv4Datagram datagram)
        {
            UdpDatagram  packet = datagram.HandleUdpDatagram();
            ListViewItem item   = new ListViewItem(count.ToString());

            item.SubItems.Add(datagram.SourceName);
            item.SubItems.Add(packet.SourcePort.ToString() + "  " + consts.GetTcpPorts(packet.SourcePort));
            item.SubItems.Add(datagram.DestinationName);
            item.SubItems.Add(packet.DestinationPort.ToString() + "  " + consts.GetTcpPorts(packet.DestinationPort));
            item.SubItems.Add(datagram.Identification.ToString());
            lstwUdp.Items.Add(item);

            packets.Add(GetHashString(), datagram);

            count++;
            lblCount.Text = count.ToString();
            this.Update();
        }
Ejemplo n.º 27
0
        public PDU(UdpDatagram datagram)
        {
            _udp = datagram;
            MemoryStream        stream  = new MemoryStream(datagram.UdpData);
            BasicEncodingReader _reader = new BasicEncodingReader(stream);

            Asn1Type seqType   = _reader.ReadType();
            int      seqLength = _reader.ReadLength();

            Version   = _reader.ReadInteger();
            Community = _reader.ReadOctetString();

            Asn1Type t = _reader.ReadType();

            PduType = (PduType)(t.Byte & 0x1F);
            if (PduType == Snmp.PduType.Trap)
            {
                throw new NotImplementedException("SNMP v1 traps are not yet implemented");
            }

            int len = _reader.ReadLength();

            RequestId   = _reader.ReadInteger();
            ErrorStatus = _reader.ReadInteger();
            ErrorIndex  = _reader.ReadInteger();

            Asn1Type type = _reader.ReadType();

            if (type.Class != Asn1Class.Universal && type.Tag != Asn1Tag.Sequence)
            {
                throw new Exception("Sequence expected");
            }

            int length = _reader.ReadLength();

            VarBinds = new SortedDictionary <string, object>();
            var list = _reader.ReadConstructedType(length);

            foreach (List <object> seq in list)
            {
                string oid = (string)seq[0];
                VarBinds.Add(oid, seq[1]);
            }
        }
Ejemplo n.º 28
0
        public void TestMethod1()
        {
            //bytes are in Network Order
            byte[] sampleUdpBytes      = { 0x45, 0x00, 0x00, 0x4e, 0x70, 0x3a, 0x00, 0x00, 0x80, 0x11, 0xaa, 0x2a, 0x0a, 0x78, 0x85, 0x4b, 0x0a, 0x78, 0x85, 0xff, 0x00, 0x89, 0x00, 0x89, 0x00, 0x3a, 0x12, 0x55, 0x8a, 0x6a, 0x01, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x46, 0x48, 0x46, 0x41, 0x45, 0x42, 0x45, 0x45, 0x43, 0x41, 0x43, 0x41, 0x43, 0x41, 0x43, 0x41, 0x43, 0x41, 0x43, 0x41, 0x43, 0x41, 0x43, 0x41, 0x43, 0x41, 0x43, 0x41, 0x43, 0x41, 0x41, 0x41, 0x00, 0x00, 0x20, 0x00, 0x01 };
            byte[] sampleIpHeaderBytes = { 0x45, 0x00, 0x00, 0x4e, 0x70, 0x3a, 0x00, 0x00, 0x80, 0x11, 0xaa, 0x2a, 0x0a, 0x78, 0x85, 0x4b, 0x0a, 0x78, 0x85, 0xff };
            //byte[] sampleIpHeaderBytesNoCkSum = { 0x45, 0x00, 0x00, 0x4e, 0x70, 0x3a, 0x00, 0x00, 0x80, 0x11, 0x00, 0x00, 0x0a, 0x78, 0x85, 0x4b, 0x0a, 0x78, 0x85, 0xff };
            byte[] sampleIpCksumBytes  = { 0xaa, 0x2a };
            byte[] sampleUdpCksumBytes = { 0x12, 0x55 };

            var testDatagram = new UdpDatagram(sampleUdpBytes);

            //Preserved the ip checksum correctly in the object
            var IpVerify = (ushort)IPAddress.NetworkToHostOrder((short)BitConverter.ToUInt16(sampleIpCksumBytes, 0));

            Assert.AreEqual(testDatagram.PacketHeaderChecksum, IpVerify);

            //Preserved the udp checksum correctly in the object
            var UdpVerify = (ushort)IPAddress.NetworkToHostOrder((short)BitConverter.ToUInt16(sampleUdpCksumBytes, 0));

            Assert.AreEqual(testDatagram.UdpCheckSum, UdpVerify);

            //Ip header in transform from object to wire-bytes is correct
            var IpHeaderVerify = testDatagram.PacketHeaderToWireBytes();

            Assert.IsTrue(IpHeaderVerify.SequenceEqual(sampleIpHeaderBytes));

            //checksum on header should be zero if header has the correct checksum in it.
            var IpHeaderCk = NetworkTransformExtentions.GetInternetChecksum(IpHeaderVerify);

            Assert.AreEqual(0, IpHeaderCk);

            //Udp check is correct
            var UdpCk = (ushort)IPAddress.NetworkToHostOrder((short)testDatagram.GetUdpCheckSum());

            Assert.AreEqual(UdpVerify, UdpCk);

            //the whole datagram is right
            var datagramCheck = testDatagram.ToWirebytes();

            Assert.IsTrue(datagramCheck.SequenceEqual(sampleUdpBytes));
        }
Ejemplo n.º 29
0
        private void PacketHandler(Packet packet)
        {
            IpV4Datagram ip  = packet.Ethernet.IpV4;
            UdpDatagram  udp = ip.Udp;

            if (udp == null || (udp.SourcePort != 5056 && udp.DestinationPort != 5056 &&
                                udp.SourcePort != 5055 && udp.DestinationPort != 5055))
            {
                return;
            }

            try
            {
                photonParser.ReceivePacket(udp.Payload.ToArray());
            }
            catch (Exception e)
            {
                // Don't crash when we can't parse the packet
                Console.WriteLine(e);
            }
        }
Ejemplo n.º 30
0
        private void _read()
        {
            switch (Protocol)
            {
            case ProtocolEnum.Ipv6Nonxt: {
                _body = new NoNextHeader(m_io, this, m_root);
                break;
            }

            case ProtocolEnum.Ipv4: {
                _body = new Ipv4Packet(m_io);
                break;
            }

            case ProtocolEnum.Udp: {
                _body = new UdpDatagram(m_io);
                break;
            }

            case ProtocolEnum.Icmp: {
                _body = new IcmpPacket(m_io);
                break;
            }

            case ProtocolEnum.Hopopt: {
                _body = new OptionHopByHop(m_io, this, m_root);
                break;
            }

            case ProtocolEnum.Ipv6: {
                _body = new Ipv6Packet(m_io);
                break;
            }

            case ProtocolEnum.Tcp: {
                _body = new TcpSegment(m_io);
                break;
            }
            }
        }
Ejemplo n.º 31
0
        public void TestSyslogCustomParserParsing()
        {
            var testprival = "<140>";
            var severity = (Severity)Enum.ToObject(typeof(Severity), 140 & 0x7);
            var facility = (Facility)Enum.ToObject(typeof(Facility), 140 >> 3);

            var testmessage = "A message with any pri-val";
            var testString = testprival + testmessage;

            var udData = new ArraySegment<byte>(Encoding.ASCII.GetBytes(testString));

            var pHeader = new IpPacketHeader(
                IPAddress.Parse("127.0.0.1"),
                IPAddress.Parse("127.0.0.1"),
                false,
                4,
                0,
                0,
                (ushort)(udData.Array.Length + 20 + 8),
                0,
                0,
                0,
                255,
                0
                );

            var udHeader = new UdpDatagramHeader(16, 16, (ushort)udData.Array.Length, 0);
            UdpDatagram ud = new UdpDatagram()
            {
                @UdpDatagramHeader = udHeader,
                UdpData = udData,
                PacketHeader = pHeader,
                ReceivedTime = DateTimeOffset.UtcNow
            };

            var customParser = new Regex(@"(?<WithAny>with\sany)", RegexOptions.ExplicitCapture);
            var sysparser = new SyslogParser(customParser);
            var sys = sysparser.Parse(ud);

            Assert.IsNotNull(sys);
            Assert.AreEqual(testmessage, sys.Message);
            Assert.AreEqual(severity, sys.LogSeverity);
            Assert.AreEqual(facility, sys.LogFacility);
            Assert.AreEqual("with any", sys.NamedCollectedMatches["WithAny"]);
        }
Ejemplo n.º 32
0
        public void TestInitialize()
        {
            var integerVarBind = new VarBind(
                new ObjectIdentifier("1.3.6.1.4.1.1.1.1"),
                5L,
                new Asn1TagInfo(Asn1Tag.Integer, ConstructType.Primitive, Asn1Class.Universal));

            var sysUpTime = new VarBind(new ObjectIdentifier("1.3.6.1.2.1.1.3.0"),
                506009u,
                new Asn1TagInfo(Asn1SnmpTag.TimeTicks));

            var trapVb = new VarBind(new ObjectIdentifier("1.3.6.1.6.3.1.1.4.1.0"),
                new ObjectIdentifier("1.3.6.1.4.1.500.12"),
                new Asn1TagInfo(Asn1Tag.ObjectIdentifier, ConstructType.Primitive, Asn1Class.Universal));

            var extraneousVb = new VarBind(new ObjectIdentifier("1.3.6.1.6.3.1.1.42.42.42.0"),
                8938ul,
                new Asn1TagInfo(Asn1SnmpTag.Counter64));

            this.snmpDatagram = new SnmpDatagramV2C(
                DateTimeOffset.MinValue,
                "1.1.1.1",
                new SnmpHeader(SnmpVersion.V2C, "Community"),
                new[] { sysUpTime, trapVb, integerVarBind, extraneousVb },
                PduType.SNMPv2Trap,
                50000,
                SnmpErrorStatus.NoError,
                0);

            var encoded = this.snmpDatagram.ToSnmpEncodedByteArray();

            this.fakeTrapUdp = new UdpDatagram
            {
                UdpData = encoded.AsByteArraySegment(),
                PacketHeader = new IpPacketHeader(IPAddress.Parse("1.1.1.1"), IPAddress.Parse("2.2.2.2"), false, 1, 1, 1, 1, 1, 1, 1, 1, 1)
            };
        }