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);
 }
Exemplo n.º 2
0
        public static PortInformation GetPorts(Packet packet, out IPPacket ipPacket, out TcpPacket tcpPacket, out UdpPacket udpPacket)
        {
            ipPacket  = packet.Extract <IPPacket>();
            udpPacket = null;
            tcpPacket = null;

            if (ipPacket == null)
            {
                return(new PortInformation());
            }
            try
            {
                switch (ipPacket.Protocol)
                {
                case ProtocolType.Tcp:
                    tcpPacket = packet.Extract <TcpPacket>();
                    return(tcpPacket == null ? new PortInformation() : new PortInformation(Protocol.Tcp, tcpPacket.DestinationPort, tcpPacket.SourcePort));

                case ProtocolType.Udp:
                    udpPacket = packet.Extract <UdpPacket>();
                    return(udpPacket == null ? new PortInformation() : new PortInformation(Protocol.Udp, udpPacket.DestinationPort, udpPacket.SourcePort));

                default:
                    return(new PortInformation());
                }
            }
            catch (Exception)
            {
                return(new PortInformation());
            }
        }
Exemplo n.º 3
0
        // udp
        public void VerifyPacket2(Packet p)
        {
            Console.WriteLine(p.ToString());
            EthernetPacket e = (EthernetPacket)p;

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

            IPPacket ip = (IPPacket)p;

            Assert.AreEqual(System.Net.IPAddress.Parse("172.210.164.56"), ip.SourceAddress);
            Assert.AreEqual(System.Net.IPAddress.Parse("192.168.1.104"), ip.DestinationAddress);
            Assert.AreEqual(IPPacket.IPVersions.IPv4, ip.IPVersion);
            Assert.AreEqual(IPProtocol.IPProtocolType.UDP, ip.IPProtocol);
            Assert.AreEqual(112, ip.TimeToLive);
            Assert.AreEqual(0xe0a2, ip.ComputeIPChecksum());
            Assert.AreEqual(1171483602, ip.Timeval.Seconds);
            Assert.AreEqual(578641.000, ip.Timeval.MicroSeconds);

            UDPPacket udp = (UDPPacket)(p);

            Assert.AreEqual(52886, udp.SourcePort);
            Assert.AreEqual(56924, udp.DestinationPort);
            Assert.AreEqual(71, udp.UDPLength);
            Assert.AreEqual(0xe0a2, udp.ComputeIPChecksum());
            Assert.AreEqual(0xc8b8, udp.UDPChecksum);
            Assert.AreEqual(0xc8b8, udp.Checksum);
        }
Exemplo n.º 4
0
        private void ExtractPacket(IPPacket packet)
        {
            switch (packet.Protocol)
            {
            case ProtocolType.Tcp:
                var tcpPacket = packet.Extract <TcpPacket>();
                if (tcpPacket != null)
                {
                    DestinationPort = tcpPacket.DestinationPort.ToString();
                    SourcePort      = tcpPacket.SourcePort.ToString();
                }
                break;

            case ProtocolType.Udp:
                var udpPacket = packet.Extract <UdpPacket>();
                if (udpPacket != null)
                {
                    DestinationPort = udpPacket.DestinationPort.ToString();
                    SourcePort      = udpPacket.SourcePort.ToString();
                }
                break;

            case ProtocolType.IcmpV6:
                break;

            default:
                break;
            }
        }
Exemplo n.º 5
0
        public bool SendIGMP(ConnectionKey Key, IPPacket ipPkt)
        {
            Log_Verb("IGMP");
            //lock (sentry)
            //{
            int res = SendFromConnection(Key, ipPkt);

            if (res == 1)
            {
                return(true);
            }
            else if (res == 0)
            {
                return(false);
            }
            else
            {
                Log_Verb("Creating New Connection with key " + Key);
                IGMPSession s = new IGMPSession(Key, adapterIP);
                s.ConnectionClosedEvent += HandleConnectionClosed;
                s.DestIP   = ipPkt.DestinationIP;
                s.SourceIP = dhcpServer.PS2IP;
                if (!connections.TryAdd(Key, s))
                {
                    throw new Exception("Connection Add Failed");
                }
                return(s.Send(ipPkt.Payload));
            }
            //}
        }
Exemplo n.º 6
0
        // tcp
        public void VerifyPacket1(Packet p, RawCapture rawCapture)
        {
            Console.WriteLine(p.ToString());

            EthernetPacket e = (EthernetPacket)p;

            Assert.AreEqual("0016CFC91E29", e.SourceHwAddress.ToString());
            Assert.AreEqual("0014BFF2EF0A", e.DestinationHwAddress.ToString());

            IPPacket ip = (IPPacket)p.PayloadPacket;

            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, ((IPv4Packet)ip).CalculateIPChecksum());
            Assert.AreEqual(1171483600, rawCapture.Timeval.Seconds);
            Assert.AreEqual(125234.000, rawCapture.Timeval.MicroSeconds);

            TcpPacket tcp = (TcpPacket)ip.PayloadPacket;

            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(0x9b02, tcp.CalculateTCPChecksum());
            Assert.AreEqual(0x9b02, tcp.Checksum);
            Assert.IsTrue(tcp.ValidTCPChecksum);
        }
Exemplo n.º 7
0
        private void SendRstPacket(EthernetPacket ethernetPacket, IPPacket ipPacket, TcpPacket tcpPacket)
        {
            var sourceHwAddress       = PhysicalAddress.Parse(ethernetPacket.SourceHwAddress.ToString());
            var sourceAddress         = IPAddress.Parse(ipPacket.SourceAddress.ToString());
            var acknowledgementNumber = tcpPacket.AcknowledgmentNumber;
            var sourcePort            = tcpPacket.SourcePort;

            ethernetPacket.SourceHwAddress      = ethernetPacket.DestinationHwAddress;
            ethernetPacket.DestinationHwAddress = sourceHwAddress;

            ipPacket.SourceAddress      = ipPacket.DestinationAddress;
            ipPacket.DestinationAddress = sourceAddress;

            tcpPacket.Syn = false;
            tcpPacket.Ack = false;
            tcpPacket.Rst = true;
            tcpPacket.AcknowledgmentNumber = tcpPacket.SequenceNumber;
            tcpPacket.SequenceNumber       = acknowledgementNumber;
            tcpPacket.SourcePort           = tcpPacket.DestinationPort;
            tcpPacket.DestinationPort      = sourcePort;
            tcpPacket.Checksum             = tcpPacket.CalculateTCPChecksum();

            ethernetPacket.UpdateCalculatedValues();
            ipPacket.UpdateCalculatedValues();
            tcpPacket.UpdateCalculatedValues();

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

            this.captureDevice.SendPacket(ethernetPacket);
        }
Exemplo n.º 8
0
        private UInt16 CalcTCPCRC()
        {
            UInt16 crc;

            byte[] tempHeader = new byte[32 + TCP_DataLength + optionsLength];
            for (int b = 0; b < 8; b++)
            {
                tempHeader[b] = mRawData[26 + b];
            }
            tempHeader[9]  = 6;
            tempHeader[10] = (byte)(this.TCP_Length >> 8);
            tempHeader[11] = (byte)(this.TCP_Length & 0xFF);
            for (int b = 0; b < 20 + optionsLength; b++)
            {
                tempHeader[12 + b] = mRawData[this.dataOffset + b];
            }
            for (int b = 0; b < this.TCP_DataLength; b++)
            {
                tempHeader[32 + optionsLength + b] = mRawData[this.tcpDataOffset + b];
            }

            crc = IPPacket.CalcOcCRC(tempHeader, 0, tempHeader.Length);

            return(crc);
        }
        public void Process_PacketBatch_TwoPacket()
        {
            var randomIPNonTcpPacket = IPPacket.RandomPacket(IPVersion.IPv4);

            var randomIPPacket  = IPPacket.RandomPacket(IPVersion.IPv4);
            var randomTCPPacket = TcpPacket.RandomPacket();

            randomIPPacket.PayloadPacket = randomTCPPacket;
            //Arrange
            var posixTimeval  = new PosixTimeval();
            var rawTCPCapture = new RawCapture(LinkLayers.Raw, posixTimeval, randomIPPacket.Bytes);

            var rawNonTCPCapture = new RawCapture(LinkLayers.Raw, posixTimeval, randomIPNonTcpPacket.Bytes);

            var rawPacketBatchRequest =
                new RawPacketBatchRequest(
                    new[] { new RawPacket(rawTCPCapture), new RawPacket(rawNonTCPCapture), new RawPacket(rawTCPCapture) }, 1);

            //Act
            this._rawPacketBatchParserActorRefSUT.Tell(rawPacketBatchRequest);

            //Assert
            this._captureActorTestProbe.ExpectMsg <Frame>(frame => frame.TimestampTicks == posixTimeval.Date.Ticks);
            this._captureActorTestProbe.ExpectMsg <Frame>(frame => frame.TimestampTicks == posixTimeval.Date.Ticks);
            this._captureActorTestProbe.ExpectNoMsg();
        }
Exemplo n.º 10
0
        // tcp
        public void VerifyPacket0(Packet p, RawCapture rawCapture)
        {
            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)e.PayloadPacket;

            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(IPVersion.IPv4, ip.Version);
            Assert.AreEqual(IPProtocolType.TCP, ip.Protocol);
            Assert.AreEqual(254, ip.TimeToLive);
            Assert.AreEqual(0x0df8, ((IPv4Packet)ip).CalculateIPChecksum());
            Assert.AreEqual(1176685346, rawCapture.Timeval.Seconds);
            Assert.AreEqual(885259.000, rawCapture.Timeval.MicroSeconds);

            TcpPacket tcp = (TcpPacket)ip.PayloadPacket;

            Assert.AreEqual(80, tcp.SourcePort);
            Assert.AreEqual(4324, tcp.DestinationPort);
            Assert.IsTrue(tcp.Ack);
            Assert.AreEqual(3536, tcp.WindowSize);
            Assert.AreEqual(0xc835, tcp.CalculateTCPChecksum());
            Console.WriteLine("tcp.Checksum is {0}", tcp.Checksum);
            Assert.AreEqual(0xc835, tcp.Checksum, "tcp.Checksum mismatch");
            Assert.IsTrue(tcp.ValidTCPChecksum);
        }
Exemplo n.º 11
0
        /// <summary>Writes an IPPacket as is to the TAP device.</summary>
        /// <param name="packet">The IPPacket!</param>
        protected virtual void WriteIP(ICopyable packet)
        {
            MemBlock mp = packet as MemBlock;

            if (mp == null)
            {
                mp = MemBlock.Copy(packet);
            }

            IPPacket ipp  = new IPPacket(mp);
            MemBlock dest = null;

            if (!_ip_to_ether.TryGetValue(ipp.DestinationIP, out dest))
            {
                if (ipp.DestinationIP[0] >= 224 && ipp.DestinationIP[0] <= 239)
                {
                    dest = EthernetPacket.GetMulticastEthernetAddress(ipp.DestinationIP);
                }
                else if (ipp.DestinationIP[3] == 255)
                {
                    dest = EthernetPacket.BroadcastAddress;
                }
                else
                {
                    return;
                }
            }

            EthernetPacket res_ep = new EthernetPacket(dest,
                                                       EthernetPacket.UnicastAddress, EthernetPacket.Types.IP, mp);

            Ethernet.Send(res_ep.ICPacket);
        }
Exemplo n.º 12
0
        public L3L4ConversationKey(IPPacket sourceIpPacket)
        {
            if (sourceIpPacket == null)
            {
                throw new ArgumentNullException();
            }

            this._l3Key = new L3ConversationKeyStruct(sourceIpPacket);

            var payloadPacket = sourceIpPacket.PayloadPacket;

            switch (payloadPacket)
            {
            case TcpPacket tcpPacket:
                this._l4Key = new L4ConversationKeyStruct(tcpPacket.SourcePort, tcpPacket.DestinationPort, IPProtocolType.TCP);
                break;

            case UdpPacket udpPacket:
                this._l4Key = new L4ConversationKeyStruct(udpPacket.SourcePort, udpPacket.DestinationPort, IPProtocolType.UDP);
                break;

            default:
                throw new ArgumentException($"Unknown transport protocol payload: {payloadPacket}");
            }
        }
Exemplo n.º 13
0
        private static Boolean DissectSourceIpPacket(Frame frame, IPPacket ipPacket)
        {
            frame.SourceAddress      = ipPacket.SourceAddress;
            frame.DestinationAddress = ipPacket.DestinationAddress;
            frame.IpProtocol         = ipPacket.Protocol;

            if (TryDissectFragmentedIpPacket(frame, ipPacket))
            {
                return(true);
            }

            if (TryDissectNonTransportPacket(frame, ipPacket))
            {
                return(true);
            }

            if (TryDissectTransportPacket(frame, ipPacket))
            {
                return(true);
            }

            ;

            return(true);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Prints the packet to output.
        /// </summary>
        /// <param name="time">packet time value</param>
        /// <param name="ipPacket"><see cref="IPPacket"/> class instance which holds IP address of source and destination.</param>
        /// <param name="packet">Packet to print</param>
        public static void Print(DateTime time, IPPacket ipPacket, TransportPacket packet)
        {
            //If packet is empty don't print it
            if (packet == null)
            {
                return;
            }

            var srcHostName  = GetDomainName(ipPacket.SourceAddress);
            var destHostName = GetDomainName(ipPacket.DestinationAddress);

            //Write the packet time source host name : packet > destination host name : port
            Console.WriteLine(
                $"{time.Hour}:{time.Minute}:{time.Second}.{time.Millisecond} {srcHostName} : {packet.SourcePort} > {destHostName} : {packet.DestinationPort}");
            Console.WriteLine();

            uint byteCount = 0;

            //Write header
            PrintPacket(packet.HeaderData, ref byteCount);
            Console.WriteLine();
            //Write payload
            PrintPacket(packet.PayloadData, ref byteCount);
            Console.WriteLine();
        }
Exemplo n.º 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);
     }
 }
Exemplo n.º 16
0
        /// <summary>Called by HandleIPOut if the current packet has a Multicast
        /// address in its destination field.  This sends the multicast packet
        /// to all members of the multicast group stored in the dht.</summary>
        /// <param name="ipp">The IP Packet destined for multicast.</param>
        /// <returns>This returns true since this is implemented.</returns>
        protected override bool HandleMulticast(IPPacket ipp)
        {
            if (!_ipop_config.EnableMulticast)
            {
                return(true);
            }

            WaitCallback wcb = delegate(object o) {
                Hashtable[] results = null;
                try {
                    results = AppNode.Dht.Get(Encoding.UTF8.GetBytes(_ipop_config.IpopNamespace + ".multicast.ipop"));
                } catch {
                    return;
                }
                foreach (Hashtable result in results)
                {
                    try {
                        AHAddress target = (AHAddress)AddressParser.Parse(Encoding.UTF8.GetString((byte[])result["value"]));
                        if (IpopLog.PacketLog.Enabled)
                        {
                            ProtocolLog.Write(IpopLog.PacketLog, String.Format(
                                                  "Brunet destination ID: {0}", target));
                        }
                        SendIP(target, ipp.Packet);
                    }
                    catch {}
                }
            };

            ThreadPool.QueueUserWorkItem(wcb, ipp);
            return(true);
        }
Exemplo n.º 17
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);
        }
Exemplo n.º 18
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);
        }
Exemplo n.º 19
0
 public PacketStatus GetStatus(Packet pkt)
 {
     if (pkt.ContainsLayer(Protocol.IP))
     {
         IPPacket tcppkt = (IPPacket)pkt;
         if (pkt.Outbound && (direction & Direction.OUT) == Direction.OUT)
         {
             if (ips.Contains(tcppkt.DestIP))
             {
                 if (log)
                 {
                     message = " IP packet from " + tcppkt.SourceIP.ToString() + " to " + tcppkt.DestIP.ToString();
                 }
                 return(ps);
             }
         }
         else if (!pkt.Outbound && (direction & Direction.IN) == Direction.IN)
         {
             if (ips.Contains(tcppkt.DestIP))
             {
                 if (log)
                 {
                     message = " IP packet from " + tcppkt.SourceIP.ToString() + " to " + tcppkt.DestIP.ToString();
                 }
                 return(ps);
             }
         }
     }
     return(PacketStatus.UNDETERMINED);
 }
Exemplo n.º 20
0
        public PayloadItem(ProtocolType protocolType, IPPacket sourcePacket, InternetPacket internetPacket, bool clean) : this(protocolType, sourcePacket, clean)
        {
            if (sourcePacket == null)
            {
                Log.Error($"PayloadItem - sourcePacket was null");

                throw new ArgumentNullException(nameof(sourcePacket));
            }

            if (internetPacket == null)
            {
                Log.Error($"PayloadItem - payloadPacket was null");

                throw new ArgumentNullException(nameof(internetPacket));
            }

            DestinationIPAddress = sourcePacket.DestinationAddress.ToString();

            HeaderSize = internetPacket.HeaderData.Length;

            if (internetPacket.PayloadData == null)
            {
                return;
            }

            PayloadSize = internetPacket.PayloadData.Length;

            PacketContent = BitConverter.ToString(internetPacket.PayloadData);
        }
        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));
            }
        }
Exemplo n.º 22
0
        /// <summary>This is used to process a dhcp packet on the node side, that
        /// includes placing data such as the local Brunet Address, Ipop Namespace,
        /// and other optional parameters in our request to the dhcp server.  When
        /// receiving the results, if it is successful, the results are written to
        /// the TAP device.</summary>
        /// <param name="ipp"> The IPPacket that contains the Dhcp Request</param>
        /// <param name="dhcp_params"> an object containing any extra parameters for
        /// the dhcp server</param>
        /// <returns> true on if dhcp is supported.</returns>
        protected virtual bool HandleDhcp(IPPacket ipp)
        {
            UdpPacket  udpp        = new UdpPacket(ipp.Payload);
            DhcpPacket dhcp_packet = new DhcpPacket(udpp.Payload);
            MemBlock   ether_addr  = dhcp_packet.chaddr;

            if (_dhcp_config == null)
            {
                return(true);
            }

            DhcpServer dhcp_server = CheckOutDhcpServer(ether_addr);

            if (dhcp_server == null)
            {
                return(true);
            }

            MemBlock last_ip = null;

            _ether_to_ip.TryGetValue(ether_addr, out last_ip);
            byte[] last_ipb = (last_ip == null) ? null : (byte[])last_ip;

            WaitCallback wcb = delegate(object o) {
                ProtocolLog.WriteIf(IpopLog.DhcpLog, String.Format(
                                        "Attempting Dhcp for: {0}", Utils.MemBlockToString(ether_addr, '.')));

                DhcpPacket rpacket = null;
                try {
                    rpacket = dhcp_server.ProcessPacket(dhcp_packet,
                                                        AppNode.Node.Address.ToString(), last_ipb);
                } catch (Exception e) {
                    ProtocolLog.WriteIf(IpopLog.DhcpLog, e.Message);
                    CheckInDhcpServer(dhcp_server);
                    return;
                }

                /* Check our allocation to see if we're getting a new address */
                MemBlock new_addr = rpacket.yiaddr;
                UpdateMapping(ether_addr, new_addr);

                MemBlock destination_ip = ipp.SourceIP;
                if (destination_ip.Equals(IPPacket.ZeroAddress))
                {
                    destination_ip = IPPacket.BroadcastAddress;
                }

                UdpPacket res_udpp = new UdpPacket(_dhcp_server_port, _dhcp_client_port, rpacket.Packet);
                IPPacket  res_ipp  = new IPPacket(IPPacket.Protocols.Udp, rpacket.siaddr,
                                                  destination_ip, res_udpp.ICPacket);
                EthernetPacket res_ep = new EthernetPacket(ether_addr, EthernetPacket.UnicastAddress,
                                                           EthernetPacket.Types.IP, res_ipp.ICPacket);
                Ethernet.Send(res_ep.ICPacket);
                CheckInDhcpServer(dhcp_server);
            };

            ThreadPool.QueueUserWorkItem(wcb);
            return(true);
        }
Exemplo n.º 23
0
        public PacketWrapper(int id, RawCapture p)
        {
            this.id = id;
            Packet pac = Packet.ParsePacket(p.LinkLayerType, p.Data);

            tcpPacket = pac.Extract <TcpPacket>();
            ipPacket  = pac.Extract <IPPacket>();
        }
Exemplo n.º 24
0
 public ICMPIPHeaderReply(ref byte[] Packet) : base()
 {
     try {
         Data = new byte[Packet.Length - 4];
         System.Buffer.BlockCopy(Packet, 4, Data, 0, Data.Length);
         IP = new IPPacket(ref Data);
     } catch { }
 }
Exemplo n.º 25
0
 /// <summary>
 /// This method handles multicast packets (not yet implemented)
 /// </summary>
 /// <param name="ipp">A multicast packet to be processed</param>
 /// <returns></returns>
 protected override bool HandleMulticast(IPPacket ipp)
 {
     foreach (Address addr in _marad.mcast_addr)
     {
         SendIP(addr, ipp.Packet);
     }
     return(true);
 }
Exemplo n.º 26
0
        /// <summary>
        /// Generate the hash of an ip and tcp packet
        /// </summary>
        /// <param name="ip">
        /// A <see cref="IpPacket"/>
        /// </param>
        /// <param name="tcp">
        /// A <see cref="TcpPacket"/>
        /// </param>
        /// <returns>
        /// A <see cref="System.Int32"/>
        /// </returns>
        public static int GenerateConnectionHash(IPPacket ip, TcpPacket tcp)
        {
            int hash = ip.SourceAddress.GetHashCode() ^
                       ip.DestinationAddress.GetHashCode() ^
                       tcp.SourcePort.GetHashCode() ^
                       tcp.DestinationPort.GetHashCode();

            return(hash);
        }
Exemplo n.º 27
0
        public void BinarySerialization()
        {
            var dev = new CaptureFileReaderDevice("../../CaptureFiles/tcp.pcap");

            dev.Open();

            RawCapture rawCapture;
            Boolean    foundip = false;

            while ((rawCapture = dev.GetNextPacket()) != null)
            {
                Packet p  = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data);
                var    ip = (IPPacket)p.Extract(typeof(IPPacket));
                if (ip == null)
                {
                    continue;
                }
                foundip = true;

                var             memoryStream = new MemoryStream();
                BinaryFormatter serializer   = new BinaryFormatter();
                serializer.Serialize(memoryStream, ip);

                memoryStream.Seek(0, SeekOrigin.Begin);
                BinaryFormatter deserializer = new BinaryFormatter();
                IPPacket        fromFile     = (IPPacket)deserializer.Deserialize(memoryStream);

                Assert.AreEqual(ip.Bytes, fromFile.Bytes);
                Assert.AreEqual(ip.BytesHighPerformance.Bytes, fromFile.BytesHighPerformance.Bytes);
                Assert.AreEqual(ip.BytesHighPerformance.BytesLength, fromFile.BytesHighPerformance.BytesLength);
                Assert.AreEqual(ip.BytesHighPerformance.Length, fromFile.BytesHighPerformance.Length);
                Assert.AreEqual(ip.BytesHighPerformance.NeedsCopyForActualBytes, fromFile.BytesHighPerformance.NeedsCopyForActualBytes);
                Assert.AreEqual(ip.BytesHighPerformance.Offset, fromFile.BytesHighPerformance.Offset);
                Assert.AreEqual(ip.Color, fromFile.Color);
                Assert.AreEqual(ip.HeaderData, fromFile.HeaderData);
                Assert.AreEqual(ip.PayloadData, fromFile.PayloadData);
                Assert.AreEqual(ip.DestinationAddress, fromFile.DestinationAddress);
                Assert.AreEqual(ip.HeaderLength, fromFile.HeaderLength);
                Assert.AreEqual(ip.HopLimit, fromFile.HopLimit);
                Assert.AreEqual(ip.NextHeader, fromFile.NextHeader);
                Assert.AreEqual(ip.PayloadLength, fromFile.PayloadLength);
                Assert.AreEqual(ip.Protocol, fromFile.Protocol);
                Assert.AreEqual(ip.SourceAddress, fromFile.SourceAddress);
                Assert.AreEqual(ip.TimeToLive, fromFile.TimeToLive);
                Assert.AreEqual(ip.TotalLength, fromFile.TotalLength);
                Assert.AreEqual(ip.Version, fromFile.Version);

                //Method Invocations to make sure that a deserialized packet does not cause
                //additional errors.

                ip.PrintHex();
                ip.UpdateCalculatedValues();
            }

            dev.Close();
            Assert.IsTrue(foundip, "Capture file contained no ip packets");
        }
        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));
            }
        }
Exemplo n.º 29
0
Arquivo: HTTP.cs Projeto: wyrover/ospy
        private HTTPMessage ParseNode(TransactionNode httpNode, bool isRequest)
        {
            IPPacket pkt = httpNode.Slices[0].Packet;

            HTTPMessage msg = new HTTPMessage(httpNode.Index, pkt.Direction, pkt.Timestamp);

            if (isRequest)
            {
                msg.HeadlineText = String.Format("{0} {1} {2}", httpNode["Verb"], httpNode["Argument"], httpNode["Protocol"]);
            }
            else
            {
                msg.HeadlineText = String.Format("{0} {1}", httpNode["Protocol"], httpNode["Result"]);
            }

            TransactionNode headersNode = httpNode.FindChild("Headers", false);

            if (headersNode != null)
            {
                foreach (string name in headersNode.FieldNames)
                {
                    msg.AddHeaderField(name, headersNode.Fields[name]);
                }
            }

            TransactionNode bodyNode = httpNode.FindChild("Body", false);

            if (bodyNode != null)
            {
                if (bodyNode.Fields.ContainsKey("XML"))
                {
                    string         body;
                    XmlHighlighter highlighter = new XmlHighlighter(XmlHighlightColorScheme.VisualizationScheme);

                    XmlUtils.PrettyPrint((string)bodyNode["XML"], out body, highlighter);

                    msg.BodyText = body;

                    highlighter.HighlightRichTextBox(msg.BodyBox);
                }
                else if (bodyNode.Fields.ContainsKey("HTML"))
                {
                    msg.BodyText = (string)bodyNode["HTML"];
                }
                else if (bodyNode.Fields.ContainsKey("Raw"))
                {
                    msg.SetBodyFromPreviewData((byte[])bodyNode.Fields["Raw"], 512);
                }
                else
                {
                    msg.BodyText = String.Format("{0} unhandled", bodyNode.FieldNames[0]);
                }
            }

            return(msg);
        }
Exemplo n.º 30
0
        private static Boolean TryDissectNonTransportPacket(Frame frame, IPPacket ipPacket)
        {
            if (ipPacket.PayloadPacket is TransportPacket)
            {
                return(false);
            }

            frame.L7Payload = ipPacket.PayloadData;
            return(false);
        }
Exemplo n.º 31
0
        public ParsedPacket(IPPacket packet, int srcPort, int dstPort, string payloadData)
        {
            IsTCP           = packet.Protocol == ProtocolType.Tcp;
            HeaderSize      = packet.HeaderLength;
            TotalPacketSize = packet.TotalPacketLength;

            SrcPort = srcPort;
            DstPort = dstPort;
            Payload = payloadData.Replace("-", string.Empty);
        }
 void GivenIpPacketWithSrcIpIs127_0_0_1AndIpPacketWithOtherAddrs() {
     ipPackets = new IPPacket[2];
     IPPacket packetWithIPSrc127_0_0_1 = new IPPacket();
     IPPacket otherPacket = new IPPacket();
     otherPacket.SrcIP = new NetworkAddress("1.2.3.4");
     otherPacket.DstIP = new NetworkAddress("4.3.2.1");
     packetWithIPSrc127_0_0_1.SrcIP = new NetworkAddress("127.0.0.1");
     packetWithIPSrc127_0_0_1.DstIP = new NetworkAddress("4.3.2.1");
     ipPackets[0] = packetWithIPSrc127_0_0_1;
     ipPackets[1] = otherPacket;
 }
Exemplo n.º 33
0
 public void TestCopyIPPackets() {
     IPPacket ipPacketSrc = new IPPacket();
     IPPacket ipPacketDst = new IPPacket();
     ipPacketSrc.SrcMAC =
         new PhysicalAddress(new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66 });
     ipPacketSrc.DstMAC = 
         new PhysicalAddress(new byte[] { 0x66, 0x55, 0x44, 0x33, 0x22, 0x11 });
     ipPacketSrc.SrcIP = new NetworkAddress("127.0.0.1");
     ipPacketSrc.DstIP = new NetworkAddress("1.1.1.1");
     ipPacketSrc.Copy(ipPacketDst);
     Assert.AreEqual(ipPacketDst, ipPacketSrc);
     Assert.AreNotSame(ipPacketDst, ipPacketSrc);
 }
        public void TestIPConverterFromBytesToObject() {
            byte[] binPacket = new byte[IPPacket.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;

            IPPacket packet = new IPPacket();
            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");

            IPPacketConverter converter = new IPPacketConverter();
            IPPacket convertedPacket = (IPPacket)converter.ConvertPacket(binPacket);
            Assert.AreEqual(packet, convertedPacket);
        }
Exemplo n.º 35
0
 public ICMPIPHeaderReply(ref byte[] Packet)
     : base()
 {
     try {
         Data = new byte[Packet.Length - 4];
         System.Buffer.BlockCopy(Packet, 4, Data, 0, Data.Length);
         IP = new IPPacket(ref Data);
     } catch { }
 }
 void GivenIPPacketWithSrcIP192_168_0_1() {
     packetWithSrcIP192_168_0_1 = new IPPacket();
     packetWithSrcIP192_168_0_1.SrcIP = new NetworkAddress("192.168.0.1");
     packetWithSrcIP192_168_0_1.DstIP = new NetworkAddress("2.3.4.1");    
 }
 void GivenIPPacketWithDstIp1_0_0_5() {
     packetWithDstIP1_0_0_5 = new IPPacket();
     packetWithDstIP1_0_0_5.SrcIP = new NetworkAddress("5.2.8.6");
     packetWithDstIP1_0_0_5.DstIP = new NetworkAddress("1.0.0.5");
 }
 void GivenOtherIpPacket() {
     otherPacket = new IPPacket();
     otherPacket.SrcIP = new NetworkAddress("1.2.3.4");
     otherPacket.DstIP = new NetworkAddress("4.3.2.1");
 }