Example #1
0
        // tcp
        public void VerifyPacket0(Packet p)
        {
            Console.WriteLine(p.ToString());

            EthernetPacket e = (EthernetPacket)p;

            Assert.AreEqual(PhysicalAddress.Parse("00-13-10-03-71-47"), e.SourceHwAddress);
            Assert.AreEqual(PhysicalAddress.Parse("00-E0-4C-E5-73-AD"), e.DestinationHwAddress);

            IPPacket ip = (IPPacket)p;

            Assert.AreEqual(System.Net.IPAddress.Parse("82.165.240.134"), ip.SourceAddress);
            Assert.AreEqual(System.Net.IPAddress.Parse("192.168.1.221"), ip.DestinationAddress);
            Assert.AreEqual(IPPacket.IPVersions.IPv4, ip.IPVersion);
            Assert.AreEqual(IPProtocol.IPProtocolType.TCP, ip.IPProtocol);
            Assert.AreEqual(254, ip.TimeToLive);
            Assert.AreEqual(0x0df8, ip.ComputeIPChecksum());
            Assert.AreEqual(1176685346, ip.Timeval.Seconds);
            Assert.AreEqual(885259.000, ip.Timeval.MicroSeconds);

            TCPPacket tcp = (TCPPacket)(p);

            Assert.AreEqual(80, tcp.SourcePort);
            Assert.AreEqual(4324, tcp.DestinationPort);
            Assert.IsTrue(tcp.Ack);
            Assert.AreEqual(3536, tcp.WindowSize);
            Assert.AreEqual(0x0df8, tcp.ComputeIPChecksum());
            Assert.AreEqual(0xc835, tcp.ComputeTCPChecksum());
            Assert.AreEqual(0xc835, tcp.Checksum);
            Assert.IsTrue(tcp.ValidTCPChecksum);
        }
Example #2
0
        private void device_PcapOnPacketArrival(object sender, Packet packet)
        {
            if (!(packet is TCPPacket))
            {
                return;
            }

            TCPPacket tcpPacket = (TCPPacket)packet;
            // Creates a key for the dictionary
            TCPConnection connection = new TCPConnection(tcpPacket);

            // create a new entry if the key does not exists and its a new Connection
            if (!sharpPcapDict.ContainsKey(connection) &&
                tcpPacket.Syn && (tcpPacket.DestinationPort == this.dst_port))
            {
                TcpRecon tcpRecon = new TcpRecon(this.ServerStr, this.ClientStr);
                sharpPcapDict.Add(connection, tcpRecon);
                this.connection = tcpRecon;

                // (((ip.src == 192.168.100.150) && (tcp.dstport == 7777) ) || ((ip.src == 78.46.33.43) && (tcp.dstport == 52784)))

                string filter = string.Format("(((ip.src == {0}) && (tcp.dstport == {1})) || ((ip.src == {2}) && (tcp.dstport == {3})))"
                                              , tcpPacket.SourceAddress, tcpPacket.DestinationPort, tcpPacket.DestinationAddress, tcpPacket.SourcePort);

                this.tcpDumpFilter = filter;
                // Geht oder geht nicht??? das is die große Frage ;)
                this.device.PcapSetFilter(filter);
            }

            // Use the TcpRecon class to reconstruct the session
            if (this.sharpPcapDict.ContainsKey(connection))
            {
                sharpPcapDict[connection].ReassemblePacket(tcpPacket);
            }
        }
Example #3
0
        public virtual void TCPData()
        {
            PcapOfflineDevice dev = Pcap.GetPcapOfflineDevice("../../capture_files/tcp_with_extra_bytes.pcap");

            dev.Open();

            Packet p;

            p = dev.GetNextPacket();

            Assert.IsNotNull(p);

            Console.WriteLine(p.GetType());
            Assert.IsTrue(p is TCPPacket);

            TCPPacket t = (TCPPacket)p;

            // even though the packet has 6 bytes of extra data, the ip packet shows a size of
            // 40 and the ip header has a length of 20. The TCP header is also 20 bytes so
            // there should be zero bytes in the TCPData value
            int expectedTcpDataLength = 0;

            Assert.AreEqual(expectedTcpDataLength, t.TCPData.Length);

            dev.Close();
        }
Example #4
0
        private void mFileImportMenu_Click(object pSender, EventArgs pArgs)
        {
            if (mImportDialog.ShowDialog(this) != DialogResult.OK)
            {
                return;
            }
            PcapOfflineDevice device = new PcapOfflineDevice(mImportDialog.FileName);

            device.Open();

            Packet      packet  = null;
            SessionForm session = null;

            while ((packet = device.GetNextPacket()) != null)
            {
                TCPPacket tcpPacket = packet as TCPPacket;
                if (tcpPacket == null)
                {
                    continue;
                }
                if ((tcpPacket.SourcePort < Config.Instance.LowPort || tcpPacket.SourcePort > Config.Instance.HighPort) &&
                    (tcpPacket.DestinationPort < Config.Instance.LowPort || tcpPacket.DestinationPort > Config.Instance.HighPort))
                {
                    continue;
                }
                if (tcpPacket.Syn && !tcpPacket.Ack)
                {
                    session = NewSession(); session.BufferTCPPacket(tcpPacket);
                }
                else if (session.MatchTCPPacket(tcpPacket))
                {
                    session.BufferTCPPacket(tcpPacket);
                }
            }
        }
Example #5
0
        public IPPacket(ref byte[] Packet) : base()
        {
            try {
                Version            = (byte)(Packet[0] >> 4);
                HeaderLength       = (byte)((Packet[0] & 0x0F) * 4);
                TypeOfService      = Packet[1];
                TotalLength        = (ushort)System.Net.IPAddress.NetworkToHostOrder(System.BitConverter.ToInt16(Packet, 2));
                Identification     = (ushort)System.Net.IPAddress.NetworkToHostOrder(System.BitConverter.ToInt16(Packet, 4));
                Flags              = (byte)((Packet[6] & 0xE0) >> 5);
                FragmentOffset     = (ushort)(System.Net.IPAddress.NetworkToHostOrder(System.BitConverter.ToInt16(Packet, 6)) & 0x1FFF);
                TimeToLive         = Packet[8];
                Protocol           = Packet[9];
                HeaderChecksum     = (ushort)(System.Net.IPAddress.NetworkToHostOrder(System.BitConverter.ToInt16(Packet, 10)));
                SourceAddress      = new System.Net.IPAddress(System.BitConverter.ToInt32(Packet, 12) & 0x00000000FFFFFFFF);
                DestinationAddress = new System.Net.IPAddress(System.BitConverter.ToInt32(Packet, 16) & 0x00000000FFFFFFFF);
                PacketData         = new byte[TotalLength - HeaderLength];
                System.Buffer.BlockCopy(Packet, HeaderLength, PacketData, 0, PacketData.Length);
            } catch { }

            switch (Protocol)
            {
            case 1: ICMP = new ICMPPacket(ref PacketData); break;

            case 6: TCP = new TCPPacket(ref PacketData); break;

            case 17: UDP = new UDPPacket(ref PacketData); break;
            }
        }
Example #6
0
        /// <summary>
        /// IPv4 handler.
        /// </summary>
        /// <param name="packetData">Packet data.</param>
        /// <exception cref="sys.ArgumentOutOfRangeException">Thrown on fatal error (contact support).</exception>
        /// <exception cref="sys.IO.IOException">Thrown on IO error.</exception>
        /// <exception cref="sys.ArgumentException">Thrown on fatal error (contact support).</exception>
        /// <exception cref="sys.OverflowException">Thrown if packetData array length is greater than Int32.MaxValue.</exception>
        internal static void IPv4Handler(byte[] packetData)
        {
            var ip_packet = new IPPacket(packetData);

            if (ip_packet.SourceIP == null)
            {
                Global.mDebugger.Send("SourceIP null in IPv4Handler!");
            }
            ARPCache.Update(ip_packet.SourceIP, ip_packet.SourceMAC);

            if ((NetworkStack.AddressMap.ContainsKey(ip_packet.DestinationIP.Hash) == true) ||
                (ip_packet.DestinationIP.address[3] == 255))
            {
                switch (ip_packet.Protocol)
                {
                case 1:
                    ICMPPacket.ICMPHandler(packetData);
                    break;

                case 6:
                    TCPPacket.TCPHandler(packetData);
                    break;

                case 17:
                    UDPPacket.UDPHandler(packetData);
                    break;
                }
            }
            else if (NetworkStack.MACMap.ContainsKey(ip_packet.DestinationMAC.Hash))
            {
                DHCPPacket.DHCPHandler(packetData);
            }
        }
Example #7
0
        public IPPacket(ref byte[] Packet)
            : base()
        {
            try {
                Version = (byte)(Packet[0] >> 4);
                HeaderLength = (byte)((Packet[0] & 0x0F) * 4);
                TypeOfService = Packet[1];
                TotalLength = (ushort)System.Net.IPAddress.NetworkToHostOrder(System.BitConverter.ToInt16(Packet, 2));
                Identification = (ushort)System.Net.IPAddress.NetworkToHostOrder(System.BitConverter.ToInt16(Packet, 4));
                Flags = (byte)((Packet[6] & 0xE0) >> 5);
                FragmentOffset = (ushort)(System.Net.IPAddress.NetworkToHostOrder(System.BitConverter.ToInt16(Packet, 6)) & 0x1FFF);
                TimeToLive = Packet[8];
                Protocol = Packet[9];
                HeaderChecksum = (ushort)(System.Net.IPAddress.NetworkToHostOrder(System.BitConverter.ToInt16(Packet, 10)));
                SourceAddress = new System.Net.IPAddress(System.BitConverter.ToInt32(Packet, 12) & 0x00000000FFFFFFFF);
                DestinationAddress = new System.Net.IPAddress(System.BitConverter.ToInt32(Packet, 16) & 0x00000000FFFFFFFF);
                PacketData = new byte[TotalLength - HeaderLength];
                System.Buffer.BlockCopy(Packet, HeaderLength, PacketData, 0, PacketData.Length);
            } catch { }

            switch (Protocol) {
                case 1: ICMP = new ICMPPacket(ref PacketData); break;
                case 6: TCP = new TCPPacket(ref PacketData); break;
                case 17: UDP = new UDPPacket(ref PacketData); break;
            }
        }
Example #8
0
        // tcp
        public void VerifyPacket1(Packet p)
        {
            Console.WriteLine(p.ToString());

            EthernetPacket e = (EthernetPacket)p;

            Assert.AreEqual("00:16:cf:c9:1e:29", e.SourceHwAddress);
            Assert.AreEqual("00:14:bf:f2:ef:0a", e.DestinationHwAddress);

            IPPacket ip = (IPPacket)p;

            Assert.AreEqual(System.Net.IPAddress.Parse("192.168.1.104"), ip.SourceAddress);
            Assert.AreEqual(System.Net.IPAddress.Parse("86.42.196.13"), ip.DestinationAddress);
            Assert.AreEqual(64, ip.TimeToLive);
            Assert.AreEqual(0x2ff4, ip.ComputeIPChecksum());
            Assert.AreEqual(1171483600, ip.Timeval.Seconds);
            Assert.AreEqual(125234.000, ip.Timeval.MicroSeconds);

            TCPPacket tcp = (TCPPacket)(p);

            Assert.AreEqual(56925, tcp.SourcePort);
            Assert.AreEqual(50199, tcp.DestinationPort);
            Assert.IsTrue(tcp.Ack);
            Assert.IsTrue(tcp.Psh);
            Assert.AreEqual(16666, tcp.WindowSize);
            Assert.AreEqual(0x2ff4, tcp.ComputeIPChecksum());
            Assert.AreEqual(0x9b02, tcp.ComputeTCPChecksum());
            Assert.AreEqual(0x9b02, tcp.Checksum);
            Assert.IsTrue(tcp.ValidTCPChecksum);
        }
Example #9
0
        public static void SendTcpSyn(NetworkDevice dev)
        {
            byte[] bytes = new byte[54];

            TCPPacket tcp = new TCPPacket(lLen, bytes, true);

            //Ethernet fields
            tcp.SourceHwAddress      = dev.MacAddress;                  //Set the source mac of the local device
            tcp.DestinationHwAddress = destMAC;                         //Set the dest MAC of the gateway
            tcp.EthernetProtocol     = EthernetProtocols_Fields.IP;

            //IP fields
            tcp.DestinationAddress = destIP;                                    //The IP of the destination host
            tcp.SourceAddress      = dev.IpAddress;                             //The IP of the local device
            tcp.IPProtocol         = IPProtocols_Fields.TCP;
            tcp.TimeToLive         = 20;
            tcp.Id             = 100;
            tcp.Version        = 4;
            tcp.IPTotalLength  = bytes.Length - lLen;                           //Set the correct IP length
            tcp.IPHeaderLength = IPFields_Fields.IP_HEADER_LEN;

            //TCP fields
            tcp.SourcePort            = sourcePort;                             //The TCP source port
            tcp.DestinationPort       = destPort;                               //The TCP dest port
            tcp.Syn                   = true;                                   //Set the SYN flag on
            tcp.WindowSize            = 555;
            tcp.AcknowledgementNumber = 1000;
            tcp.SequenceNumber        = 1000;
            tcp.TCPHeaderLength       = TCPFields_Fields.TCP_HEADER_LEN;                        //Set the correct TCP header length

            //tcp.SetData( System.Text.Encoding.ASCII.GetBytes("HELLO") );

            //Calculate checksums
            tcp.ComputeIPChecksum();
            tcp.ComputeTCPChecksum();

            dev.PcapOpen(true, 20);

            //Set a filter to capture only replies
            dev.PcapSetFilter("ip src " + destIP + " and ip dst " +
                              dev.IpAddress + " and tcp src port " + destPort + " and tcp dst port " + sourcePort);

            //Send the packet
            Console.Write("Sending packet: " + tcp + "...");
            dev.PcapSendPacket(tcp);
            Console.WriteLine("Packet sent.");

            //Holds the reply
            Packet reply;

            //Wait till you get a reply
            while ((reply = dev.PcapGetNextPacket()) == null)
            {
                ;
            }
            //print the reply
            Console.WriteLine("Reply received: " + reply);

            dev.PcapClose();
        }
Example #10
0
        private void mTimer_Tick(object pSender, EventArgs pArgs)
        {
            Packet packet = null;

            try
            {
                while ((packet = mDevice.GetNextPacket()) != null)
                {
                    TCPPacket   tcpPacket = packet as TCPPacket;
                    SessionForm session   = null;
                    if (tcpPacket.Syn && !tcpPacket.Ack)
                    {
                        session = NewSession();
                    }
                    else
                    {
                        session = Array.Find(MdiChildren, f => (f as SessionForm).MatchTCPPacket(tcpPacket)) as SessionForm;
                    }
                    if (session != null)
                    {
                        session.BufferTCPPacket(tcpPacket);
                    }
                }
            }
            catch { }
        }
Example #11
0
 public PacketStatus GetStatus(Packet pkt)
 {
     if (pkt.ContainsLayer(Protocol.TCP))
     {
         TCPPacket tcppkt = (TCPPacket)pkt;
         if (tcppkt.SYN && !(tcppkt.ACK))
         {
             if (pkt.Outbound && (direction & Direction.OUT) == Direction.OUT)
             {
                 if (log)
                 {
                     message = " TCP packet from " + tcppkt.SourceIP.ToString() + ":" +
                               tcppkt.SourcePort.ToString() + " to " + tcppkt.DestIP.ToString() +
                               ":" + tcppkt.DestPort.ToString();
                 }
                 return(ps);
             }
             else if (!pkt.Outbound && (direction & Direction.IN) == Direction.IN)
             {
                 if (log)
                 {
                     message = " TCP packet from " + tcppkt.SourceIP.ToString() + ":" +
                               tcppkt.SourcePort.ToString() + " to " + tcppkt.DestIP.ToString() + ":" +
                               tcppkt.DestPort.ToString();
                 }
                 return(ps);
             }
         }
     }
     return(PacketStatus.UNDETERMINED);
 }
Example #12
0
        internal static void IPv4Handler(byte[] packetData)
        {
            IPPacket ip_packet = new IPPacket(packetData);

            //[Received] " + ip_packet.ToString()
            if (ip_packet.SourceIP == null)
            {
                //SourceIP null in IPv4Handler!
            }
            ARPCache.Update(ip_packet.SourceIP, ip_packet.SourceMAC);

            if ((NetworkStack.AddressMap.ContainsKey(ip_packet.DestinationIP.Hash) == true) ||
                (ip_packet.DestinationIP.address[3] == 255))
            {
                switch (ip_packet.Protocol)
                {
                case 1:
                    ICMPPacket.ICMPHandler(packetData);
                    break;

                case 6:
                    TCPPacket.TCPHandler(packetData);
                    break;

                case 17:
                    UDPPacket.UDPHandler(packetData);
                    break;
                }
            }
            else if (NetworkStack.MACMap.ContainsKey(ip_packet.DestinationMAC.Hash))
            {
                DHCP.DHCPPacket.DHCPHandler(packetData);
            }
        }
Example #13
0
        public void TestChecksums()
        {
            IPPacket.IPVersions[] versions = { IPPacket.IPVersions.IPv4, IPPacket.IPVersions.IPv6 };

            for (int i = 0; i < 10000; i++)
            {
                int len;
                //choose random version
                IPPacket.IPVersions ipver = versions[Rand.Instance.GetInt(0, 1)];
                //choose random len based on version
                if (ipver == IPPacket.IPVersions.IPv4)
                {
                    len = Rand.Instance.GetInt(54, 1500);
                }
                else
                {
                    len = Rand.Instance.GetInt(74, 1500);
                }

                TCPPacket tcp = TCPPacket.RandomPacket(len, ipver);
                //TODO: this test should use a known quantity, a packet recorded and loaded from a file
                Assert.AreEqual(len, tcp.Bytes.Length);
                Assert.IsTrue(tcp.ValidIPChecksum);
                Assert.IsTrue(tcp.ValidTCPChecksum);
            }
        }
Example #14
0
        private Flow GetFlowFromPacket(Packet packet)
        {
            Flow flow;

            if (packet is TCPPacket)
            {
                TCPPacket tcpPacket = (TCPPacket)packet;
                //наполняем атрибуты для TCP пакета
                flow = new Flow(System.Net.IPAddress.Parse(tcpPacket.SourceAddress),
                                (ushort)tcpPacket.SourcePort,
                                System.Net.IPAddress.Parse(tcpPacket.DestinationAddress),
                                (ushort)tcpPacket.DestinationPort, TransportProtocol.TCP);
            }
            else if (packet is UDPPacket)
            {
                UDPPacket udpPacket = (UDPPacket)packet;
                //наполняем атрибуты для UDP пакета
                flow = new Flow(System.Net.IPAddress.Parse(udpPacket.SourceAddress),
                                (ushort)udpPacket.SourcePort,
                                System.Net.IPAddress.Parse(udpPacket.DestinationAddress),
                                (ushort)udpPacket.DestinationPort, TransportProtocol.UDP);
            }
            else
            {
                return(null);
            }
            flow.BytesAB   = (uint)packet.PcapHeader.PacketLength;
            flow.StartTime = packet.Timeval.Date;
            return(flow);
        }
Example #15
0
 void ScanThread()
 {
     for (int x = 0; x < ushort.MaxValue; x++)
     {
         EthPacket e = new EthPacket(60);
         e.FromMac = adapter.InterfaceInformation.GetPhysicalAddress().GetAddressBytes();
         e.ToMac   = PhysicalAddress.Parse("080027465EDE").GetAddressBytes();
         e.Proto   = new byte[2] {
             0x08, 0x00
         };
         IPPacket ip = new IPPacket(e);
         ip.DestIP         = IPAddress.Parse("192.168.1.4");
         ip.SourceIP       = IPAddress.Parse("192.168.1.3");
         ip.NextProtocol   = 0x06;
         ip.TotalLength    = 40;
         ip.HeaderChecksum = ip.GenerateIPChecksum;
         TCPPacket tcp = new TCPPacket(ip);
         tcp.SourcePort     = (ushort)new Random().Next(65534);
         tcp.DestPort       = (ushort)x;
         tcp.SequenceNumber = (uint)new Random().Next();
         tcp.AckNumber      = 0;
         tcp.WindowSize     = 8192;
         tcp.SYN            = true;
         tcp.Checksum       = tcp.GenerateChecksum;
         tcp.Outbound       = true;
         adapter.SendPacket(tcp);
         Thread.Sleep(1);
     }
 }
 public void CollectStatWhenGiven2ip2icmp1tcp5udpPacketsThenCountOfPacketsIsRight() {
     NetworkPacket[] packets = new NetworkPacket[10];
     packets[0] = new IPPacket();
     packets[1] = new IPPacket();
     packets[2] = new ICMPPacket();
     packets[3] = new ICMPPacket();
     packets[4] = new TCPPacket();
     packets[5] = new UDPPacket();
     packets[6] = new UDPPacket();
     packets[7] = new UDPPacket();
     packets[8] = new UDPPacket();
     packets[9] = new UDPPacket();
     Firewall fw = new Firewall(new FilterMock(),
         new DistributorMock());
     CollectStatCommand clltStat = new CollectStatCommand();
     Assert.AreEqual(fw.Statistics["ip"], 0);
     Assert.AreEqual(fw.Statistics["icmp"], 0);
     Assert.AreEqual(fw.Statistics["tcp"], 0);
     Assert.AreEqual(fw.Statistics["udp"], 0);
     Assert.AreEqual(fw.Statistics["total"], 0);
     foreach (var packet in packets) {
         clltStat.DoWithPacket(fw, packet);
     }
     Assert.AreEqual(fw.Statistics["ip"], 2);
     Assert.AreEqual(fw.Statistics["icmp"], 2);
     Assert.AreEqual(fw.Statistics["tcp"], 1);
     Assert.AreEqual(fw.Statistics["udp"], 5);
     Assert.AreEqual(fw.Statistics["total"], 10);
 }
        private static void device_PcapOnPacketArrival(object sender, PcapCaptureEventArgs e)
        {
            if (e.Packet is EthernetPacket)
            {
                EthernetPacket eth = ((EthernetPacket)e.Packet);
                Console.WriteLine("Original Eth packet: " + eth.ToColoredString(false));

                //Manipulate ethernet parameters
                eth.SourceHwAddress      = PhysicalAddress.Parse("00-11-22-33-44-55");
                eth.DestinationHwAddress = PhysicalAddress.Parse("00-99-88-77-66-55");

                if (e.Packet is IPPacket)
                {
                    IPPacket ip = ((IPPacket)e.Packet);
                    Console.WriteLine("Original IP packet: " + ip.ToColoredString(false));

                    //manipulate IP parameters
                    ip.SourceAddress      = System.Net.IPAddress.Parse("1.2.3.4");
                    ip.DestinationAddress = System.Net.IPAddress.Parse("44.33.22.11");
                    ip.TimeToLive         = 11;

                    //Recalculate the IP checksum
                    ip.ComputeIPChecksum();

                    if (ip is TCPPacket)
                    {
                        TCPPacket tcp = ((TCPPacket)ip);
                        Console.WriteLine("Original TCP packet: " + tcp.ToColoredString(false));

                        //manipulate TCP parameters
                        tcp.SourcePort           = 9999;
                        tcp.DestinationPort      = 8888;
                        tcp.Syn                  = !tcp.Syn;
                        tcp.Fin                  = !tcp.Fin;
                        tcp.Ack                  = !tcp.Ack;
                        tcp.WindowSize           = 500;
                        tcp.AcknowledgmentNumber = 800;
                        tcp.SequenceNumber       = 800;

                        //Recalculate the TCP checksum
                        tcp.ComputeTCPChecksum();
                    }

                    if (ip is UDPPacket)
                    {
                        UDPPacket udp = ((UDPPacket)ip);
                        Console.WriteLine("Original UDP packet: " + udp.ToColoredString(false));

                        //manipulate UDP parameters
                        udp.SourcePort      = 9999;
                        udp.DestinationPort = 8888;

                        //Recalculate the UDP checksum
                        udp.ComputeUDPChecksum();
                    }
                }
                Console.WriteLine("Manipulated Eth packet: " + eth.ToColoredString(false));
            }
        }
Example #18
0
 /// <summary>
 /// chuck out bad packets
 /// </summary>
 /// <param name="in_packet"></param>
 /// <returns></returns>
 public override PacketMainReturnType interiorMain(ref Packet in_packet)
 {
     try
     {
         LogEvent             le;
         PacketMainReturnType pmr;
         if (in_packet.ContainsLayer(Protocol.TCP))
         {
             // cast the packet and check for SYN/outbound
             TCPPacket packet = (TCPPacket)in_packet;
             if (packet.SYN && packet.Outbound)
             {
                 // check if it's blocked
                 for (int i = 0; i < block_ranges.Count; ++i)
                 {
                     // if its heading towards a blacklisted IP
                     if (block_ranges[i].IsInRange(packet.DestIP))
                     {
                         pmr = PacketMainReturnType.Drop;
                         // check if we should log it
                         if (this.data.logBlocked)
                         {
                             pmr   |= PacketMainReturnType.Log;
                             le     = new LogEvent(String.Format(multistring.GetString("Blocked Outgoing"), packet.DestIP.ToString()), this);
                             le.PMR = PacketMainReturnType.Drop | PacketMainReturnType.Log;
                             LogCenter.Instance.LogEvent(le);
                         }
                         return(pmr);
                     }
                 }
             }
             // check if they want to block incoming packets from these addresses
             // as well.
             if (this.data.blockIncoming && !(packet.Outbound))
             {
                 for (int i = 0; i < block_ranges.Count; ++i)
                 {
                     if (block_ranges[i].IsInRange(packet.SourceIP))
                     {
                         pmr = PacketMainReturnType.Drop;
                         // check if we should log it
                         if (this.data.logBlocked)
                         {
                             pmr |= PacketMainReturnType.Log;
                             le   = new LogEvent(String.Format(multistring.GetString("Blocked Incoming"), packet.SourceIP.ToString()), this);
                             LogCenter.Instance.LogEvent(le);
                         }
                         return(pmr);
                     }
                 }
             }
         }
     }
     catch (Exception e)
     {
         LogCenter.Instance.LogException(e);
     }
     return(PacketMainReturnType.Allow);
 }
Example #19
0
 private async void ClientHandlerTCP(TCPPacket Packet)
 {
     if (Packet.DestIP == "" && Packet.DestPort == 0)
     {
         byte[] buffer = Encapsulate(Packet);
         await mClient.SendAsync(buffer, buffer.Length);
     }
 }
Example #20
0
        /// <summary>
        /// Close down an active connection
        /// </summary>
        public void Close()
        {
            TCPPacket packet = new TCPPacket(connection, connection.LocalSequenceNumber, connection.RemoteSequenceNumber + 1, 0x11, 8192);

            TCPIP.IPv4OutgoingBuffer.AddPacket(packet);

            connection.ConnectionState = TCPConnection.State.TIMEWAIT;
        }
        public void TestTCPConverterFromBytesToObject() {
            byte[] binPacket = new byte[TCPPacket.Size];
            //Source MAC
            binPacket[0] = 0x11;
            binPacket[1] = 0x22;
            binPacket[2] = 0x33;
            binPacket[3] = 0x44;
            binPacket[4] = 0x55;
            binPacket[5] = 0x66;
            //Destination MAC
            binPacket[6] = 0x66;
            binPacket[7] = 0x55;
            binPacket[8] = 0x44;
            binPacket[9] = 0x33;
            binPacket[10] = 0x22;
            binPacket[11] = 0x11;
            //Source IP
            binPacket[12] = 127;
            binPacket[13] = 0;
            binPacket[14] = 0;
            binPacket[15] = 1;
            //Destination IP
            binPacket[16] = 1;
            binPacket[17] = 1;
            binPacket[18] = 1;
            binPacket[19] = 1;
            //Source port
            binPacket[20] = 0x11;
            binPacket[21] = 0x11;
            //Destination port
            binPacket[22] = 0x22;
            binPacket[23] = 0x22;
            //Sequence number
            binPacket[24] = 0x0;
            binPacket[25] = 0x0;
            binPacket[26] = 0x1;
            binPacket[27] = 0x1;
            //Data
            binPacket[28] = 1;
            binPacket[29] = 2;

            TCPPacket packet = new TCPPacket();
            packet.SrcMAC =
               new PhysicalAddress(new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66 });
            packet.DstMAC =
                new PhysicalAddress(new byte[] { 0x66, 0x55, 0x44, 0x33, 0x22, 0x11 });
            packet.SrcIP = new NetworkAddress("127.0.0.1");
            packet.DstIP = new NetworkAddress("1.1.1.1");
            packet.SrcPort = 0x1111;
            packet.DstPort = 0x2222;
            packet.SeqNum = 0x1010000;
            packet.Data[0] = 1;
            packet.Data[1] = 2;

            TCPPacketConverter converter = new TCPPacketConverter();
            TCPPacket convertedPacket = (TCPPacket) converter.ConvertPacket(binPacket);
            Assert.AreEqual(packet, convertedPacket);
        }
Example #22
0
 public void TestChecksums()
 {
     for (int i = 0; i < 10000; i++)
     {
         TCPPacket tcp = TCPPacket.RandomPacket();
         Assert.IsTrue(tcp.ValidIPChecksum);
         Assert.IsTrue(tcp.ValidTCPChecksum);
     }
 }
        private static void device_PcapOnPacketArrival(object sender, Tamir.IPLib.Packets.Packet packet)
        {
            if (packet is EthernetPacket)
            {
                EthernetPacket eth = ((EthernetPacket)packet);
                Console.WriteLine("Original packet: " + eth.ToColoredString(false));

                //Manipulate ethernet parameters
                eth.SourceHwAddress      = "00:11:22:33:44:55";
                eth.DestinationHwAddress = "00:99:88:77:66:55";

                if (packet is IPPacket)
                {
                    IPPacket ip = ((IPPacket)packet);

                    //manipulate IP parameters
                    ip.SourceAddress      = "1.2.3.4";
                    ip.DestinationAddress = "44.33.22.11";
                    ip.TimeToLive         = 11;

                    //Recalculate the IP checksum
                    ip.ComputeIPChecksum();

                    if (ip is TCPPacket)
                    {
                        TCPPacket tcp = ((TCPPacket)ip);

                        //manipulate TCP parameters
                        tcp.SourcePort            = 9999;
                        tcp.DestinationPort       = 8888;
                        tcp.Syn                   = !tcp.Syn;
                        tcp.Fin                   = !tcp.Fin;
                        tcp.Ack                   = !tcp.Ack;
                        tcp.WindowSize            = 500;
                        tcp.AcknowledgementNumber = 800;
                        tcp.SequenceNumber        = 800;

                        //Recalculate the TCP checksum
                        tcp.ComputeTCPChecksum();
                    }

                    if (ip is UDPPacket)
                    {
                        UDPPacket udp = ((UDPPacket)ip);

                        //manipulate UDP parameters
                        udp.SourcePort      = 9999;
                        udp.DestinationPort = 8888;

                        //Recalculate the UDP checksum
                        udp.ComputeUDPChecksum();
                    }
                }
                Console.WriteLine("Manipulated packet: " + eth.ToColoredString(false));
            }
        }
        private void buttonInject_Click(object sender, EventArgs e)
        {
            bool isEthernetHeaderCorrect =
                ethernetHeaderUserControl.ValidateUserInput();
            bool isIPv4HeaderCorrect =
                iPv4HeaderUserControl.ValidateUserInput();
            bool isTcpHeaderCorrect =
                tcpHeaderUserControl.ValidateUserInput();
            bool isDeviceChosen =
                chooseDeviceUserControl.ValidateChosenDevice();

            if (!isEthernetHeaderCorrect ||
                !isIPv4HeaderCorrect ||
                !isTcpHeaderCorrect ||
                !isDeviceChosen)
            {
                return;
            }

            EthernetPacket ethernetHeader =
                ethernetHeaderUserControl.CreateEthernetPacket(0);

            IPv4Packet ipv4Packet =
                iPv4HeaderUserControl.CreateIPv4Packet(ethernetHeader);

            TCPPacket tcpPacket =
                tcpHeaderUserControl.CreateTcpPacket(ipv4Packet);

            PcapDevice device = chooseDeviceUserControl.Device;

            bool isDeviceOpenedInThisForm = false;

            try
            {
                if (!device.Opened)
                {
                    device.Open();
                    isDeviceOpenedInThisForm = true;
                }

                // Send the packet out the network device
                device.SendPacket(tcpPacket);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (isDeviceOpenedInThisForm)
                {
                    device.Close();
                }
            }
        }
Example #25
0
        private void device_PcapOnPacketArrival(object sender, Packet packet)
        {
            if (!(packet is TCPPacket))
            {
                return;
            }

            TCPPacket tcpPacket = (TCPPacket)packet;
            // Creates a key for the dictionary
            TCPConnection c = new TCPConnection(tcpPacket);

            // Todo: gescheiter Filter
            if (!(c.DestinationPort == port || c.SourcePort == port))
            {
                return;
            }

            // create a new entry if the key does not exists
            if (!sharpPcapDict.ContainsKey(c) && !this.gotLock)
            {
                TcpRecon.TcpRecon tcpRecon = new TcpRecon.TcpRecon(this.serverStr, this.clientStr);
                sharpPcapDict.Add(c, tcpRecon);
                this.gotLock = true;
            }

            // Use the TcpRecon class to reconstruct the session
            if (this.sharpPcapDict.ContainsKey(c))
            {
                sharpPcapDict[c].ReassemblePacket(tcpPacket);
            }

            L2Packet l2packet = null;


            while (this.clientStr.MorePackets())
            {
                l2packet = this.gameSniffer.handlePacket(this.clientStr.ReadPacket(), false);
                if (l2packet != null)
                {
                    this.packetContainer.AddPacket(l2packet);
                    l2packet.PacketNo = this.count++;
                }
            }
            while (this.serverStr.MorePackets())
            {
                l2packet = this.gameSniffer.handlePacket(this.serverStr.ReadPacket(), true);
                if (l2packet != null)
                {
                    this.packetContainer.AddPacket(l2packet);
                    l2packet.PacketNo = this.count++;
                }
            }
        }
Example #26
0
        public void IPDataSet()
        {
            TCPPacket p = TCPPacket.RandomPacket(IPPacket.IPVersions.IPv4);

            p.IPTotalLength = 100;
            Assert.AreEqual(100, p.IPTotalLength);
            Assert.AreEqual(80, p.IPPayloadLength);

            p.IPPayloadLength = 200;
            Assert.AreEqual(200, p.IPPayloadLength);
            Assert.AreEqual(220, p.IPTotalLength);
        }
Example #27
0
        void IPSender(IPPacket ip)
        {
            //Thread.Sleep(1000);
            TCPPacket   tcpUp = (TCPPacket)ip.oProtocolContent;
            List <byte> tx    = pppDataTransferConvert.IPDataEncode(ip);

            //while (Com.DsrHolding) ;
            //while (!Com.CtsHolding) ;
            Com.Write(tx.ToArray(), 0, tx.Count);
            OnIPProcLog("编号:" + tcpUp.InitialSeqNumber.ToString(), (int)ATCommandLogType.Tx);
            OnIPProcLog("回应编号:" + tcpUp.AckSeqNumber.ToString(), (int)ATCommandLogType.Tx);
            OnIPProcLog("标志:" + tcpUp.TCPFlags.ToString("X2"), (int)ATCommandLogType.Tx);
        }
 void GivenTcpPacketWithDstPort9999AndOtherTcpPacket() {
     tcpPackets = new TCPPacket[2];
     TCPPacket packetWithPortDstIs9999 = new TCPPacket();
     TCPPacket otherPacket = new TCPPacket();
     packetWithPortDstIs9999.DstPort = 9999;
     packetWithPortDstIs9999.SrcIP = new NetworkAddress("1.2.3.4");
     packetWithPortDstIs9999.DstIP = new NetworkAddress("4.3.2.1");
     otherPacket.SrcIP = new NetworkAddress("1.2.3.4");
     otherPacket.DstIP = new NetworkAddress("4.3.2.1");
     otherPacket.DstPort = 1234;
     tcpPackets[0] = packetWithPortDstIs9999;
     tcpPackets[1] = otherPacket;
 }
Example #29
0
//         void IPSender(IPPacket ip,bool b7E)
//         {
//             //Thread.Sleep(1000);
//             TCPPacket tcpUp = (TCPPacket)ip.oProtocolContent;
//             List<byte> tx = pppDataTransferConvert.IPDataEncode(ip);
//             if (!b7E)
//                 tx.RemoveAt(0);
//             while (Com.DsrHolding) ;
//             while (!Com.CtsHolding) ;
//             Com.Write(tx.ToArray(), 0, tx.Count);
//             communicationDebugForm.ExternShowTx(tx);
//             communicationDebugForm.ExternShowTx("编号:" + tcpUp.InitialSeqNumber.ToString());
//             communicationDebugForm.ExternShowTx("回应编号:" + tcpUp.AckSeqNumber.ToString());
//             communicationDebugForm.ExternShowTx("标志:" + tcpUp.TCPFlags.ToString("X2"));
//         }
        IPPacket NewIPPacket()
        {
            IPPacket ip = new IPPacket(ourIP, dIP);

            ip.Identification = IPID++;
            ip.Protocol       = 0x06;
            TCPPacket tcp = (TCPPacket)ip.oProtocolContent;

            tcp.SourcePort      = ourPort;
            tcp.DastinationPort = dPort;
            //tcp.InitialSeqNumber = TCPSeqNum;
            return(ip);
        }
Example #30
0
        private static void device_PcapOnPacketArrival(object sender, Packet packet)
        {
            try
            {
                if (packet is TCPPacket)
                {
                    L2Packet l2packet = null;

                    TCPPacket etherFrame = (TCPPacket)packet;
                    if (etherFrame.Data.Length != 0 && etherFrame.SourcePort == 2106 &&
                        etherFrame.Ack && etherFrame.Psh)    // packet contains data and is from port 2106
                    {
                        l2packet = client.handlePacket(etherFrame.Data, true);
                    }
                    else if (etherFrame.Data.Length != 0 && etherFrame.SourcePort == 7777 &&
                             etherFrame.Ack && etherFrame.Psh)
                    {
                        //TCPPacket tcpP = reAss.processPacket(etherFrame);
                        // if (tcpP != null)
                        gpHandler.handlePacket(etherFrame.Data);

                        while (gpHandler.BufferQueue.Count > 0)
                        {
                            l2packet = game.handlePacket(gpHandler.BufferQueue.Dequeue(), true);
                        }
                        if (clientPort == 0)
                        {
                            clientPort = etherFrame.DestinationPort;
                        }
                    }
                    else if (etherFrame.Data.Length != 0 && etherFrame.SourcePort == clientPort &&
                             etherFrame.Ack && etherFrame.Psh)
                    {
                        cpHandler.handlePacket(etherFrame.Data);
                        while (cpHandler.BufferQueue.Count > 0)
                        {
                            l2packet = game.handlePacket(cpHandler.BufferQueue.Dequeue(), false);
                        }
                    }

                    if (l2packet != null)
                    {
                        Console.Out.WriteLine("Packet is " + l2packet.ToString());
                    }
                }
            }
            catch (Exception e)
            {
                Console.Out.WriteLine(e.StackTrace);
            }
        }
        private void FilterAndProcessPacket(byte[] buffer)
        {
            try {
                var ipPacket = new IPPacket(buffer);

                if (ipPacket.IsValid && ipPacket.Protocol == ProtocolType.Tcp)
                {
                    var tcpPacket = new TCPPacket(ipPacket.Data);

                    if (!tcpPacket.IsValid)
                    {
                        return;
                    }

                    if (!tcpPacket.Flags.HasFlag(TCPFlags.ACK | TCPFlags.PSH))
                    {
                        return;
                    }

                    var sourceEndPoint      = new IPEndPoint(ipPacket.SourceIPAddress, tcpPacket.SourcePort);
                    var destinationEndPoint = new IPEndPoint(ipPacket.DestinationIPAddress, tcpPacket.DestinationPort);
                    var connection          = new Connection()
                    {
                        localEndPoint = sourceEndPoint, remoteEndPoint = destinationEndPoint
                    };
                    var reverseConnection = new Connection()
                    {
                        localEndPoint = destinationEndPoint, remoteEndPoint = sourceEndPoint
                    };

                    if (!(connections.Contains(connection) || connections.Contains(reverseConnection)))
                    {
                        return;
                    }

                    if (!connections.Contains(reverseConnection))
                    {
                        return;
                    }

                    lock (lockAnalyse)
                    {
                        AnalyseFFXIVPacket(tcpPacket.Payload);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Write(LogType.Error, "l-network-error-filtering-packet", ex);
            }
        }
        // The callback function for the SharpPcap library
        private void device_PcapOnPacketArrival(object sender, Packet packet)
        {
            if (packet is UDPPacket)
            {
                HandleDNS(packet);
                return;
            }

            if (!(packet is TCPPacket))
            {
                return;
            }

            TCPPacket  tcpPacket = (TCPPacket)packet;
            Connection c         = new Connection(tcpPacket);
            TcpRecon   recon     = null;

            if (!sharpPcapDict.ContainsKey(c))
            {
                c.generateFileName(outDir);
                recon = new TcpRecon(c.fileName);
                recon.LastSourcePort = tcpPacket.SourcePort;
                sharpPcapDict.Add(c, recon);
                if (!IPExists("tcp: " + tcpPacket.DestinationAddress))
                {
                    ips.Add("tcp: " + tcpPacket.DestinationAddress);
                }
                if (!IPExists("tcp: " + tcpPacket.SourceAddress))
                {
                    ips.Add("tcp: " + tcpPacket.SourceAddress);
                }
                owner.Invoke(NewStream, recon);
            }
            else
            {
                recon = sharpPcapDict[c];
            }

            recon.ReassemblePacket(tcpPacket);                    //can contain fragments and out of order packets

            if (recon.PacketWritten)                              //reassembly/reordering complete data was saved this time..
            {
                if (recon.LastSourcePort != tcpPacket.SourcePort) //previous entry is now complete so lets add it.
                {
                    AddNewNode(recon);
                    recon.LastSourcePort = tcpPacket.SourcePort;
                }
            }
        }
Example #33
0
 internal void BufferTCPPacket(TCPPacket pTCPPacket)
 {
     if (pTCPPacket.Fin || pTCPPacket.Rst)
     {
         mTerminated = true;
         Text       += " (Terminated)";
         return;
     }
     if (pTCPPacket.Syn && !pTCPPacket.Ack)
     {
         mLocalPort        = (ushort)pTCPPacket.SourcePort;
         mRemotePort       = (ushort)pTCPPacket.DestinationPort;
         mOutboundSequence = (uint)(pTCPPacket.SequenceNumber + 1);
         Text = "Port " + mLocalPort.ToString();
         return;
     }
     if (pTCPPacket.Syn && pTCPPacket.Ack)
     {
         mInboundSequence = (uint)(pTCPPacket.SequenceNumber + 1); return;
     }
     if (pTCPPacket.PayloadDataLength == 0)
     {
         return;
     }
     if (!gotKey)
     {
         byte[] tcpData = pTCPPacket.TCPData;
         if (BitConverter.ToUInt16(tcpData, 1) != 0x0807)
         {
             this.Close();
             mInboundSequence += (uint)tcpData.Length; //not valid xorkey
             return;
         }
         ushort xorKey = BitConverter.ToUInt16(tcpData, 3);
         mOutboundStream   = new FiestaStream(true, xorKey);
         mInboundStream    = new FiestaStream(false, 0);
         gotKey            = true;
         mInboundSequence += (uint)tcpData.Length;
         return;
     }
     if (pTCPPacket.SourcePort == mLocalPort)
     {
         ProcessTCPPacket(pTCPPacket, ref mOutboundSequence, mOutboundBuffer, mOutboundStream);                                      //process fromclient
     }
     else
     {
         ProcessTCPPacket(pTCPPacket, ref mInboundSequence, mInboundBuffer, mInboundStream);  //process fromserver
     }
 }
Example #34
0
        public void TCPDataIPv4()
        {
            String s = "-++++=== HELLLLOOO ===++++-";

            byte[] data = System.Text.Encoding.UTF8.GetBytes(s);

            //create random pkt
            TCPPacket p = TCPPacket.RandomPacket(IPPacket.IPVersions.IPv4);

            //replace pkt's data with our string
            p.TCPData = data;

            //sanity check
            Assert.AreEqual(s, System.Text.Encoding.Default.GetString(p.TCPData));
        }
 public void TestCopyTCPPackets() {
     TCPPacket packetSrc = new TCPPacket();
     TCPPacket packetDst = new TCPPacket();
     packetSrc.SrcMAC =
         new PhysicalAddress(new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66 });
     packetSrc.DstMAC =
         new PhysicalAddress(new byte[] { 0x66, 0x55, 0x44, 0x33, 0x22, 0x11 });
     packetSrc.SrcIP = new NetworkAddress("127.0.0.1");
     packetSrc.DstIP = new NetworkAddress("1.1.1.1");
     packetSrc.DstPort = 1234;
     packetSrc.SrcPort = 123;
     packetSrc.SeqNum = 32414;
     packetSrc.Data[0] = 1;
     packetSrc.Data[1] = 2;
     packetSrc.Copy(packetDst);
     Assert.AreEqual(packetSrc, packetDst);
     Assert.AreNotSame(packetSrc, packetDst);
 }