private 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);

                var 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 != PacketDotNet.ProtocolType.Tcp)
                {
                    continue;
                }
                OnPacketReceived(ipPacket);
            }
        }
        public static EthernetPacket Packet(string ipsrc, string ipdes, int portsrc, int portdes, string macsrc, string macdes, EthernetPacketType packetType)
        {
            TcpPacket tcpPacket = new TcpPacket(ushort.Parse(portsrc.ToString()), ushort.Parse(portdes.ToString())); // ports # TCP Packet

            IPAddress IpSourceAddress      = IPAddress.Parse(ipsrc);
            IPAddress IpDestinationAddress = IPAddress.Parse(ipdes);

            IPv4Packet ipPacket = new IPv4Packet(IpSourceAddress, IpDestinationAddress);// IP addresses # IP Packets

            string SourceMacAddress      = macsrc;
            string DestinationMacAddress = macdes;
            //convert above value to a Physical Address

            PhysicalAddress MACsource      = PhysicalAddress.Parse(SourceMacAddress);
            PhysicalAddress MACdestination = PhysicalAddress.Parse(DestinationMacAddress);

            EthernetPacket eth0Packet = new EthernetPacket(MACsource, MACdestination, packetType); // MAC address # Eth0 Packet

            // this below does Packet construction Encapsulation
            ipPacket.PayloadPacket   = tcpPacket;
            eth0Packet.PayloadPacket = ipPacket;

            Console.WriteLine(eth0Packet.ToString());
            // allows us to retrieve bytes from the packets
            byte[] packetBytes = eth0Packet.Bytes;

            return(eth0Packet);
        }
예제 #3
0
파일: Gfp.cs 프로젝트: zuohuaiyu1205/VOIP
 void AgentBase(IPv4Packet packet, Metadata.BaseMetadata metadata)
 {
     metadata.SourceAddress = packet.SourceAddress.ToString();
     metadata.TargetAddress = packet.DestinationAddress.ToString();
     if (packet.Protocol == ProtocolType.Udp)
     {
         if (packet.PayloadPacket != null)
         {
             UdpPacket udpPacket = packet.PayloadPacket as UdpPacket;
             metadata.SourcePort = udpPacket.SourcePort;
             metadata.TargetPort = udpPacket.DestinationPort;
         }
         metadata.ProtocolName = "UDP";
     }
     else if (packet.Protocol == ProtocolType.Tcp)
     {
         if (packet.PayloadPacket != null)
         {
             TcpPacket tcpPacket = packet.PayloadPacket as TcpPacket;
             metadata.SourcePort = tcpPacket.SourcePort;
             metadata.TargetPort = tcpPacket.DestinationPort;
         }
         metadata.ProtocolName = "TCP";
     }
     else
     {
         metadata.ProtocolName = packet.Protocol.ToString();
     }
     Metadata.MetadataSaver.Instance.Add(metadata);
     //LogHelper.Debug(string.Format("发现{0}协议数据{1}-{2}", packet.Protocol.ToString(), packet.SourceAddress, packet.DestinationAddress));
 }
예제 #4
0
        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.");
        }
        public override async Task PacketReceived(object sender, DataMessageEventArgs eventArgs)
        {
            if (!initialized)
            {
                return;
            }

            var ipv4Packet = IPv4Packet.Parse(eventArgs.Data);

            ipv4Packet.SourceAddress      = GetIpFromPhysicalAddress(GetPhysicalAddressFromId(eventArgs.SourceId));
            ipv4Packet.DestinationAddress = IPAddress.Broadcast;

            var ethernetPacket = new EthernetPacket(GetPhysicalAddressFromId(eventArgs.SourceId),
                                                    new PhysicalAddress(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }), ipv4Packet, EthernetPacket.PacketType.IpV4);

            if (!eventArgs.IsBroadcast)
            {
                ipv4Packet.DestinationAddress     = GetIpFromPhysicalAddress(tapInterface.GetPhysicalAddress());
                ethernetPacket.DestinationAddress = tapInterface.GetPhysicalAddress();
            }

            var packetData = ethernetPacket.ToBytes();

            tapStream.Write(packetData, 0, packetData.Length);
            await Task.Delay(0);
        }
        public void GreIPv4Parsing()
        {
            var dev = new CaptureFileReaderDevice(NUnitSetupClass.CaptureDirectory + "gre_all_options.pcap");

            dev.Open();
            var rawCapture = dev.GetNextPacket();

            dev.Close();

            LinkLayers linkLayers = rawCapture.GetLinkLayers();

            if (linkLayers == LinkLayers.Ethernet)
            {
                Console.WriteLine("Linklayer is ethernet");
                // Linklayer
                Packet p = Packet.ParsePacket(linkLayers, rawCapture.Data);
                Assert.IsNotNull(p);

                // Ethernet
                EthernetPacket eth = p.Extract <EthernetPacket>();
                Assert.IsNotNull(eth);
                if (eth.Type == EthernetType.IPv4)
                {
                    Console.WriteLine("IPv4 inside ethernet");
                    // IPv4
                    IPv4Packet ipv4 = eth.Extract <IPv4Packet>();
                    Assert.IsNotNull(ipv4);
                    if (ipv4.Protocol == ProtocolType.Gre)
                    {
                        Console.WriteLine("GRE inside IPv4");
                        // Gre
                        GrePacket grep = ipv4.Extract <GrePacket>();
                        Assert.IsNotNull(grep);

                        // String output
                        Console.WriteLine(grep.ToString());

                        // Get header
                        if (grep.HasCheckSum)
                        {
                            Console.WriteLine("GRE has checksum flag");
                        }
                        if (grep.HasKey)
                        {
                            Console.WriteLine("GRE has key flag");
                        }
                        if (grep.HasReserved)
                        {
                            Console.WriteLine("GRE has reserved flag");
                        }
                        if (grep.HasSequence)
                        {
                            Console.WriteLine("GRE has sequence flag");
                        }

                        Assert.AreEqual(grep.Protocol, EthernetType.IPv4);
                    }
                }
            }
        }
예제 #7
0
        void device_OnPacketArrival(object sender, CaptureEventArgs e)
        {
            IPv4Packet ipPacket;

            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;
            }

            var ipData  = ipPacket.BytesHighPerformance;
            var ipData2 = new ArraySegment <byte>(ipData.Bytes, ipData.Offset, ipData.Length);

            OnPacketReceived(ipData2);

            var device = (WinPcapDevice)sender;

            if (device.Statistics.DroppedPackets != _droppedPackets || device.Statistics.InterfaceDroppedPackets != _interfaceDroppedPackets)
            {
                _droppedPackets          = device.Statistics.DroppedPackets;
                _interfaceDroppedPackets = device.Statistics.InterfaceDroppedPackets;
                OnWarning(string.Format("DroppedPackets {0}, InterfaceDroppedPackets {1}", device.Statistics.DroppedPackets, device.Statistics.InterfaceDroppedPackets));
            }
        }
예제 #8
0
        public void TestSend()
        {
            var dst = IPAddress.Parse("8.8.8.8");
            var nic = IpHelper.GetBestInterface(dst);

            Assert.NotNull(nic, "No internet connected interface found");
            var src = nic.GetIPProperties().UnicastAddresses
                      .Select(addr => addr.Address)
                      .FirstOrDefault(addr => addr.AddressFamily == AddressFamily.InterNetwork);
            var ifIndex = nic.GetIPProperties().GetIPv4Properties().Index;

            Console.WriteLine($"Using NIC {nic.Name} [{ifIndex}]");
            Console.WriteLine($"Sending from {src} to {dst}");
            var device = new WinDivertDevice();

            device.Open();
            try
            {
                var udp = new UdpPacket(5000, 5000);
                udp.PayloadData = new byte[100];
                var ip = IPv4Packet.RandomPacket();
                ip.PayloadPacket = udp;

                ip.SourceAddress      = src;
                ip.DestinationAddress = dst;

                device.SendPacket(ip);
            }
            finally
            {
                device.Close();
            }
        }
예제 #9
0
        static void dev_OnPacketArrival(object sender, CaptureEventArgs e)
        {
            Packet packet = IpPacket.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);

            IPv4Packet pv4 = packet.PayloadPacket as IPv4Packet;
            IPv6Packet pv6 = packet.PayloadPacket as IPv6Packet;

            if (pv4 != null)
            {
                total += pv4.TotalLength;
                String src = pv4.SourceAddress.ToString();
                String dst = pv4.DestinationAddress.ToString();

                Console.Out.WriteLine(src + " --> " + dst + "\tlen:" + pv4.TotalLength);
            }

            if (pv6 != null)
            {
                total += pv6.TotalLength;
                String src = pv6.SourceAddress.ToString();
                String dst = pv6.DestinationAddress.ToString();

                Console.Out.WriteLine(src + " --> " + dst + "\tlen:" + pv6.TotalLength);
            }

            //Console.Out.WriteLine(total);
        }
예제 #10
0
        public static Packet BuildDnsReply(IPAddress senderIp, PhysicalAddress senderMac, ushort senderPort, IPAddress targetIp, PhysicalAddress targetMac, ushort targetPort, byte[] requestData, IPAddress answerIP, int vlanId)
        {
            byte[] answerContent = new byte[requestData.Length + 16];
            requestData.CopyTo(answerContent, 0);

            int contentLen = answerContent.Length;

            // DNS Header
            answerContent[2] = 0x81; answerContent[3] = 0x80;                                                                                                        // Flags : 81 80 (Standard Response, No Error)
            answerContent[6] = 0x00; answerContent[7] = 0x01;                                                                                                        // Answer RRs : 1
            // DNS Answer
            answerContent[contentLen - 16] = 0xc0; answerContent[contentLen - 15] = 0x0c;                                                                            // Name : c0 0c
            answerContent[contentLen - 14] = 0x00; answerContent[contentLen - 13] = 0x01;                                                                            // Type : A (Host Address)
            answerContent[contentLen - 12] = 0x00; answerContent[contentLen - 11] = 0x01;                                                                            // Class : IN
            answerContent[contentLen - 10] = 0x00; answerContent[contentLen - 9] = 0x00; answerContent[contentLen - 8] = 0x00; answerContent[contentLen - 7] = 0x05; // 5 (seconds)//0x3c; // Time To Live : 60 (seconds)
            answerContent[contentLen - 6]  = 0x00; answerContent[contentLen - 5] = 0x04;                                                                             // Data Length : 4

            byte[] ipBytes = answerIP.GetAddressBytes();
            answerContent[contentLen - 4] = ipBytes[0];
            answerContent[contentLen - 3] = ipBytes[1];
            answerContent[contentLen - 2] = ipBytes[2];
            answerContent[contentLen - 1] = ipBytes[3];

            EthernetPacket ePacket  = new EthernetPacket(senderMac, targetMac, EthernetPacketType.IpV4);
            IPv4Packet     v4Packet = new IPv4Packet(senderIp, targetIp);
            UdpPacket      uPacket  = new UdpPacket(senderPort, targetPort);

            return(PacketBuilder.BuildPacket(vlanId, ePacket, v4Packet, uPacket, answerContent));
        }
        /**
         * Process packets when they arrive
         */
        private void device_onPacketArrival(Object sender, CaptureEventArgs packet)
        {
            try
            {
                String address = null, protocol = null;

                // Convert the packet data from a byte array to a EthernetPacket instance
                EthernetPacket ethernetPacket = (EthernetPacket)Packet.ParsePacket(packet.Packet.LinkLayerType, packet.Packet.Data);

                // IPv4
                if (ethernetPacket.PayloadPacket is IPv4Packet)
                {
                    IPv4Packet ip = (IPv4Packet)ethernetPacket.PayloadPacket;
                    address  = ip.SourceAddress.ToString();
                    protocol = ip.Protocol.ToString();
                }

                // IPv6
                else if (ethernetPacket.PayloadPacket is IPv6Packet)
                {
                    IPv6Packet ip = (IPv6Packet)ethernetPacket.PayloadPacket;

                    // Convert address to IPv4 since the GeoIP database we're using doesn't support IPv6 lookups
                    address  = ip.SourceAddress.MapToIPv4().ToString();
                    protocol = ip.Protocol.ToString();
                }

                // ARP
                else if (ethernetPacket.PayloadPacket is ARPPacket)
                {
                    ARPPacket arp = (ARPPacket)ethernetPacket.PayloadPacket;
                    address = arp.SenderProtocolAddress.ToString();

                    // Check if this is a gratuitious ARP
                    checkForGratuitiousArp(arp);
                    protocol = "ARP";
                }

                // Other
                else
                {
                    // Don't care about other packet types
                    return;
                }



                // We care about this packet, so the packet counter can increment
                numPackets++;

                // If we haven't processes this IP address yet, add it to the address queue
                if (address != null && !addedAddresses.Contains(address) && !pendingAddresses.ContainsKey(address))
                {
                    pendingAddresses.Add(address, protocol);
                }
            } catch (Exception)
            {
                // Handle issues gracefully
            }
        }
예제 #12
0
        /// <summary>
        /// Fires off on a seperate thread when a packet is available
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ProcessPacket(RawCapture incoming)
        {
            try
            {
                Packet         packet = Packet.ParsePacket(LinkLayers.Ethernet, incoming.Data);
                EthernetPacket ethSrc = (EthernetPacket)packet.Extract(typeof(EthernetPacket));
                IPv4Packet     ipSrc  = (IPv4Packet)packet.Extract(typeof(IPv4Packet));

                if (ipSrc.Protocol == IPProtocolType.UDP)
                {
                    UdpPacket udpSrc = (UdpPacket)packet.Extract(typeof(UdpPacket));

                    // From RFC 1002 Section 4.2.1.1
                    // Need to grab the transaction id for the reply
                    UInt16 namedTrnId = BitConverter.ToUInt16(udpSrc.PayloadData, 0);
                    // Looking for Response = query(0), OpCode = Query(0)
                    // 11000000 00000000
                    UInt16 flags = Utility.ReverseUInt16(BitConverter.ToUInt16(udpSrc.PayloadData, 2));
                    if ((flags & 0xc000) == 0)
                    {
                        // Grab the name and make sure it's WPAD
                        string name = Encoding.Default.GetString(udpSrc.PayloadData, 12, 34);
                        if (Utility.DecodeName(name) == WpadHostName)
                        {
                            Logger.AddToInfoView("Received NBNS query for {0} from {1}", WpadHostName, ethSrc.SourceHwAddress);

                            UdpPacket udpDst = new UdpPacket(NetbiosPort, NetbiosPort);
                            udpDst.PayloadData = SetupResponse(namedTrnId, GetDeviceIp(this.Device));

                            IPv4Packet ipDst = new IPv4Packet(GetDeviceIp(this.Device), ipSrc.SourceAddress);
                            ipDst.PayloadPacket = udpDst;

                            udpDst.UpdateCalculatedValues();
                            udpDst.UpdateUDPChecksum();
                            ipDst.UpdateCalculatedValues();
                            ipDst.UpdateIPChecksum();

                            EthernetPacket ethDst = new EthernetPacket(this.Device.MacAddress, ethSrc.SourceHwAddress, EthernetPacketType.IpV4);
                            ethDst.PayloadPacket = ipDst;
                            ethDst.UpdateCalculatedValues();

                            Logger.AddToInfoView("Sending poisoned response for {0}", WpadHostName);
                            this.Device.SendPacket(ethDst.Bytes);
                        }
                    }
                }
                else if (ipSrc.Protocol == IPProtocolType.TCP)
                {
                    TcpPacket tcpSrc = (TcpPacket)packet.Extract(typeof(TcpPacket));
                    if (tcpSrc.Syn)
                    {
                        Logger.AddToInfoView("SYN sent {0}:{1}", ipSrc.DestinationAddress, tcpSrc.SourcePort);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.AddToErrorView("OnPacketArrival", ex);
            }
        }
예제 #13
0
        private bool Route(ref IPv4Packet packet)
        {
            bool done = false;

            EthernetPacket eth_packet = packet.ParentPacket as EthernetPacket;

            foreach (Route route in Routes)
            {
                if (eth_packet.SourceHwAddress.Equals(route.Source.MacAddress) &&
                    (route.SourceIp == null || route.SourceIp.Equals(packet.SourceAddress)) &&
                    (route.DestIp == null || route.DestIp.Equals(packet.DestinationAddress)))
                {
                    if (route.NewSourceIp != null)
                    {
                        packet.SourceAddress       = route.NewSourceIp.IpAddress;
                        eth_packet.SourceHwAddress = route.NewSourceIp.MacAddress;

                        done = true;
                    }

                    if (route.NewDestIp != null)
                    {
                        packet.DestinationAddress       = route.NewDestIp.IpAddress;
                        eth_packet.DestinationHwAddress = route.NewDestIp.MacAddress;

                        done = true;
                    }
                }
            }

            return(done);
        }
예제 #14
0
        private static void sendDhcpRelease(PhysicalAddress pSourceHwAddress, IPAddress pSourceIpAddress, PhysicalAddress pDestinationHwAddress, IPAddress pDestinationIpAddress)
        {
            PhysicalAddress ethernetSourceHwAddress      = pSourceHwAddress;
            PhysicalAddress ethernetDestinationHwAddress = pDestinationHwAddress;

            var ethernetPacket = new EthernetPacket(ethernetSourceHwAddress,
                                                    ethernetDestinationHwAddress,
                                                    EthernetType.None);


            var ipPacket = new IPv4Packet(pSourceIpAddress, pDestinationIpAddress);

            const ushort udpSourcePort      = 68;
            const ushort udpDestinationPort = 67;
            var          udpPacket          = new UdpPacket(udpSourcePort, udpDestinationPort);

            //-- Combine all bytes to single payload
            byte[] payload = buildDhcpReleasePacket(pSourceIpAddress, pSourceHwAddress, pDestinationIpAddress);

            udpPacket.PayloadData        = payload;
            ipPacket.PayloadPacket       = udpPacket;
            ethernetPacket.PayloadPacket = ipPacket;

            device.SendPacket(ethernetPacket);
            Console.WriteLine("DHCP Release successful send to: " + pDestinationIpAddress + " from: " + pDestinationIpAddress + " at: " + DateTime.Now.ToShortTimeString());
        }
예제 #15
0
        static void createPacket()
        {
            Console.Write("Enter name of text file (for example t.txt): ");
            string path    = Console.ReadLine();
            string txtFile = File.ReadAllText(path, Encoding.Default);


            ushort tcpSourcePort      = 123;
            ushort tcpDestinationPort = 321;
            var    tcpPacket          = new TcpPacket(tcpSourcePort, tcpDestinationPort);

            tcpPacket.PayloadData = Encoding.UTF8.GetBytes(txtFile);

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

            var sourceHwAddress      = PhysicalAddress.Parse("90-90-90-90-90-90");
            var destinationHwAddress = PhysicalAddress.Parse("80-80-80-80-80-80");
            var ethernetPacket       = new EthernetPacket(sourceHwAddress, destinationHwAddress, EthernetPacketType.None);

            ipPacket.PayloadPacket       = tcpPacket;
            ethernetPacket.PayloadPacket = ipPacket;
            getPacket(ethernetPacket);
        }
예제 #16
0
        /// <summary>
        /// 使用函数构造UDP数据包
        /// </summary>
        /// <param name="device"></param>
        /// <param name="dst_mac"></param>
        /// <param name="dst_ip"></param>
        /// <param name="src_port"></param>
        /// <param name="dst_port"></param>
        /// <param name="send_data"></param>
        /// <returns></returns>
        private byte[] GenUDPPacket(PcapDevice device, PhysicalAddress dst_mac, IPAddress dst_ip, int src_port,
                                    int dst_port, string send_data)
        {
            // 构造UDP部分数据报
            UdpPacket udp_pkg = new UdpPacket((ushort)src_port, (ushort)dst_port);

            udp_pkg.PayloadData = strToToHexByte(send_data);
            udp_pkg.UpdateCalculatedValues();
            // 构造IP部分数据报
            IPv4Packet ip_pkg = new IPv4Packet(device.Interface.Addresses[1].Addr.ipAddress, dst_ip);

            ip_pkg.Protocol    = IPProtocolType.UDP;
            ip_pkg.Version     = IpVersion.IPv4;
            ip_pkg.PayloadData = udp_pkg.Bytes;
            ip_pkg.TimeToLive  = 10;
            ip_pkg.UpdateCalculatedValues();
            ip_pkg.UpdateIPChecksum();
            // 构造以太网帧
            EthernetPacket net_pkg = new EthernetPacket(device.MacAddress, dst_mac, EthernetPacketType.IpV4);

            net_pkg.Type        = EthernetPacketType.IpV4;
            net_pkg.PayloadData = ip_pkg.Bytes;
            net_pkg.UpdateCalculatedValues();

            return(net_pkg.Bytes);
        }
예제 #17
0
        static byte[] CreatePacket(int packetType = (int)EthernetPacketType.IPv4, int srcPort = 123, int dstPort = 321)
        {
            UInt16 tcpSourcePort      = 123;
            UInt16 tcpDestinationPort = 321;
            var    udpPacket          = new UdpPacket(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       = udpPacket;
            ethernetPacket.PayloadPacket = ipPacket;

            // and print out the packet to see that it looks just like we wanted it to
            byte[] payload = ethernetPacket.Bytes;

            // it can be crc error. but this is just test.
            payload[12] = (byte)(packetType / 0x0100);
            payload[13] = (byte)(packetType % 0x0100);
            return(payload);
        }
예제 #18
0
        public void ChangeValues()
        {
            var packet = IPv4Packet.RandomPacket();

            packet.Id = 12345;
            Assert.AreEqual(12345, packet.Id);
        }
        private 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 (_isInit)
            {
                await s.ReceiveAsync(awaitable);

                var bytesRead = args.BytesTransferred;
                if (bytesRead <= 0)
                {
                    throw new Exception("Raw socket is disconnected");
                }
                IPv4Packet ipPacket;
                try { ipPacket = new IPv4Packet(new ByteArraySegment(args.Buffer, 0, bytesRead)); }
                catch (InvalidOperationException) { continue; }

                if (ipPacket.Version != IpVersion.IPv4 || ipPacket.Protocol != IPProtocolType.TCP)
                {
                    continue;
                }
                OnPacketReceived(ipPacket);
            }
            _socket.Close();
            _socket = null;
        }
예제 #20
0
        private void SendRTPPacket(string sourceSocket, string destinationSocket)
        {
            try
            {
                //logger.Debug("Attempting to send RTP packet from " + sourceSocket + " to " + destinationSocket + ".");
                Log("Attempting to send RTP packet from " + sourceSocket + " to " + destinationSocket + ".");

                IPEndPoint sourceEP = IPSocket.GetIPEndPoint(sourceSocket);
                IPEndPoint destEP   = IPSocket.GetIPEndPoint(destinationSocket);

                RTPPacket rtpPacket = new RTPPacket(80);
                rtpPacket.Header.SequenceNumber = (UInt16)6500;
                rtpPacket.Header.Timestamp      = 100000;

                UDPPacket  udpPacket = new UDPPacket(sourceEP.Port, destEP.Port, rtpPacket.GetBytes());
                IPv4Header ipHeader  = new IPv4Header(ProtocolType.Udp, Crypto.GetRandomInt(6), sourceEP.Address, destEP.Address);
                IPv4Packet ipPacket  = new IPv4Packet(ipHeader, udpPacket.GetBytes());

                byte[] data = ipPacket.GetBytes();

                Socket rawSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
                rawSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1);

                rawSocket.SendTo(data, destEP);
            }
            catch (Exception excp)
            {
                logger.Error("Exception SendRTPPacket. " + excp.Message);
            }
        }
예제 #21
0
 public IPFragmentKey(IPv4Packet ipv4Packet)
 {
     this.SourceAddress      = ipv4Packet.SourceAddress;
     this.DestinationAddress = ipv4Packet.DestinationAddress;
     this.Protocol           = ipv4Packet.Protocol;
     this.IPIdentification   = ipv4Packet.Id;
 }
        public IPv4Packet CreateIPv4Packet(EthernetPacket ethernetHeader)
        {
            int ipv4PacketTotalLength = Int32.Parse(textBoxTotalLength.Text);

            byte[] bytes = new byte[EthernetFields_Fields.ETH_HEADER_LEN + ipv4PacketTotalLength];

            IPv4Packet ipv4Packet = new IPv4Packet(
                EthernetFields_Fields.ETH_HEADER_LEN,
                bytes);

            // Ethernet fields
            ipv4Packet.EthernetHeader = ethernetHeader.Bytes;

            // IP fields
            ipv4Packet.Version            = 4;
            ipv4Packet.IPHeaderLength     = IPv4Fields_Fields.IP_HEADER_LEN;
            ipv4Packet.TypeOfService      = Int32.Parse(textBoxDS.Text);
            ipv4Packet.IPTotalLength      = ipv4PacketTotalLength;
            ipv4Packet.Id                 = 0;
            ipv4Packet.FragmentFlags      = Int32.Parse(textBoxFlags.Text);
            ipv4Packet.FragmentOffset     = 0;
            ipv4Packet.TimeToLive         = Int32.Parse(textBoxTTL.Text);
            ipv4Packet.IPProtocol         = (IPProtocol.IPProtocolType)((DictionaryEntry)comboBoxIPProtocols.SelectedItem).Key;
            ipv4Packet.SourceAddress      = IPAddress.Parse(textBoxSourceAddress.Text);
            ipv4Packet.DestinationAddress = IPAddress.Parse(textBoxDestinationAddress.Text);

            ipv4Packet.ComputeIPChecksum(true);

            ipv4Packet.IPData = GetRandomPacketData(ipv4Packet.IPPayloadLength);

            return(ipv4Packet);
        }
예제 #23
0
        public TempPacketSaveData GetPacket(byte[] payload, int streamId)
        {
            PhysicalAddress emptyAddress = PhysicalAddress.Parse("000000000000");

            PacketDotNet.EthernetPacket etherPacket = new EthernetPacket(emptyAddress, emptyAddress, EthernetType.IPv4);

            bool flip = streamId < 0;

            streamId = Math.Abs(streamId);
            Random r = new Random(streamId);

            IPAddress sourceIp = new IPAddress(r.Next());
            IPAddress destIp   = new IPAddress(r.Next());

            if (flip)
            {
                IPAddress tempAddress = sourceIp;
                sourceIp = destIp;
                destIp   = tempAddress;
            }
            IPv4Packet ipPacket = new IPv4Packet(sourceIp, destIp)
            {
                Protocol = ProtocolType.Udp
            };
            TcpPacket tcpPacket = new TcpPacket(1, 1)
            {
                PayloadData = payload
            };

            ipPacket.PayloadPacket    = tcpPacket;
            etherPacket.PayloadPacket = ipPacket;
            return(new TempPacketSaveData(etherPacket.Bytes, LinkLayerType.Ethernet));
        }
예제 #24
0
파일: Main.cs 프로젝트: dougives/packetnet
        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());
            Console.ReadKey(true);
        }
예제 #25
0
        private void IPv4(IPv4Packet v4)
        {
            if (IPv4Node == null)
            {
                IPv4Node = new TreeNode();
            }

            IPv4Node.Nodes.Clear();

            IPv4Node.Text = string.Format("Internet Protocol Version 4, Src: {0}, Dst: {1}",
                                          v4.SourceAddress, v4.DestinationAddress);
            IPv4Node.Nodes.Add(string.Format("Version: {0}", v4.Version));
            IPv4Node.Nodes.Add(string.Format("Header Length: {0} bytes", v4.HeaderLength));
            IPv4Node.Nodes.Add(string.Format("Differentiated Services Field: {0}", v4.TypeOfService));
            IPv4Node.Nodes.Add(string.Format("Total Length: {0}", v4.TotalLength));
            IPv4Node.Nodes.Add(string.Format("Identification: {0}", v4.Id));
            IPv4Node.Nodes.Add(string.Format("Flags: {0}", v4.FragmentFlags));
            IPv4Node.Nodes.Add(string.Format("Fragment offset: {0}", v4.FragmentOffset));
            IPv4Node.Nodes.Add(string.Format("Time to live: {0}", v4.TimeToLive));
            IPv4Node.Nodes.Add(string.Format("Protocol: {0}", v4.Protocol));
            IPv4Node.Nodes.Add(string.Format("Header checksum: {0}", v4.Checksum));
            IPv4Node.Nodes.Add(string.Format("Source: {0}", v4.SourceAddress));
            IPv4Node.Nodes.Add(string.Format("Destination: {0}", v4.DestinationAddress));

            tree.Nodes.Add(IPv4Node);
        }
        private async Task DnsReply(ushort transactionId, List <string> labels, ushort id, ushort sourcePort)
        {
            var answerDnsPacket = new DnsPacket(transactionId, 0, 0, new List <DnsPacket.ResourceRecord>
            {
                new DnsPacket.ResourceRecord
                {
                    Class  = 0x0001,
                    Type   = 0x0001,
                    Labels = labels
                }
            }, new List <DnsPacket.ResourceRecord>
            {
                new DnsPacket.ResourceRecord
                {
                    Class  = 0x0001,
                    Type   = 0x0001,
                    TTL    = 30 * 60,
                    Labels = labels,
                    Data   = GetIpFromId(id).GetAddressBytes()
                }
            },
                                                new List <DnsPacket.ResourceRecord>(),
                                                new List <DnsPacket.ResourceRecord>(), DnsPacket.DnsFlags.IsAutorative | DnsPacket.DnsFlags.IsResponse);

            var answerIpV4Packet = new IPv4Packet(GetIpFromId(-1), GetIpFromId(selfId));

            answerIpV4Packet.SetPayloadPacket(new UdpPacket(53, sourcePort,
                                                            answerDnsPacket, answerIpV4Packet));
            var answerEthernetPacket = new EthernetPacket(GetPhysicalAddressFromId(-1),
                                                          GetPhysicalAddressFromId(selfId), answerIpV4Packet, EthernetPacket.PacketType.IpV4);
            var answerData = answerEthernetPacket.ToBytes();
            await tapStream.WriteAsync(answerData, 0, answerData.Length);
        }
예제 #27
0
        public static Frame CreateFromIpPacket(IPv4Packet ipPacket, Int64 timestamp)
        {
            var frame = CreateFrameBase(timestamp, ipPacket);

            frame.IsValid = DissectSourceIpPacket(frame, ipPacket);
            return(frame);
        }
예제 #28
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);
        }
예제 #29
0
            public SendPacket(DateTime dateTime, IPv4Packet ipv4)
            {
                UdpPacket udp = (UdpPacket)ipv4.PayloadPacket;

                Date        = dateTime;
                PayLoad     = udp.PayloadData;
                Destination = new IPEndPoint(ipv4.DestinationAddress, udp.DestinationPort);
            }
예제 #30
0
        public static Packet BuildDHCPDiscoverPacket(IPAddress srcIP, PhysicalAddress srcMAC, int vlanID)
        {
            EthernetPacket ePacket = new EthernetPacket(srcMAC, NetAddress.BroadcastMAC, EthernetPacketType.IpV4);
            IPv4Packet     iPacket = new IPv4Packet(srcIP, IPAddress.Broadcast);
            UdpPacket      uPacket = new UdpPacket(68, 67);

            return(PacketBuilder.BuildPacket(vlanID, ePacket, iPacket, uPacket, GetDHCPDiscoverPacketData(srcMAC)));
        }
예제 #31
0
    public static Packet CreatePacket(Param param)
    {
        Packet ret = null;

        //create layer 4
        if (param.packetType == Param.PacketType.TCP)
        {
            TcpPacket tcpPacket = new TcpPacket(param.sPort, param.dPort);
            tcpPacket.AllFlags = param.tcpFlag;
            if (param.dIP.ToString().Contains("."))
            {
                IPv4Packet ipPacket = new IPv4Packet(param.sIP, param.dIP);
                if (param.IPv4Frag) { ipPacket.FragmentFlags = (int)1; }
                ret = new EthernetPacket(param.sMAC, param.dMAC, EthernetPacketType.IpV4);
                ipPacket.PayloadPacket = tcpPacket;
                tcpPacket.PayloadData = param.payload;
                ret.PayloadPacket = ipPacket;
                ipPacket.UpdateCalculatedValues();
                ipPacket.UpdateIPChecksum();
                tcpPacket.Checksum = (ushort)tcpPacket.CalculateTCPChecksum();
            }
            else
            {
                IPv6Packet ipPacket = new IPv6Packet(param.sIP, param.dIP);
                ret = new EthernetPacket(param.sMAC, param.dMAC, EthernetPacketType.IpV6);
                ipPacket.PayloadPacket = tcpPacket;
                tcpPacket.PayloadData = param.payload;
                ret.PayloadPacket = ipPacket;
            }

        }
        else if (param.packetType == Param.PacketType.UDP)
        {
            UdpPacket udpPacket = new UdpPacket(param.sPort, param.dPort);
            if (param.dIP.ToString().Contains("."))
            {
                IPv4Packet ipPacket = new IPv4Packet(param.sIP, param.dIP);
                if (param.IPv4Frag) { ipPacket.FragmentFlags = (int)1; }
                ret = new EthernetPacket(param.sMAC, param.dMAC, EthernetPacketType.IpV4);
                ipPacket.PayloadPacket = udpPacket;
                udpPacket.PayloadData = param.payload;
                udpPacket.UpdateUDPChecksum();
                ipPacket.PayloadLength = (ushort)(ipPacket.PayloadLength + param.payload.Length);
                ipPacket.UpdateIPChecksum();
                ret.PayloadPacket = ipPacket;
            }
            else
            {
                IPv6Packet ipPacket = new IPv6Packet(param.sIP, param.dIP);
                ret = new EthernetPacket(param.sMAC, param.dMAC, EthernetPacketType.IpV6);
                ipPacket.PayloadPacket = udpPacket;
                udpPacket.PayloadData = param.payload;
                udpPacket.UpdateUDPChecksum();
                ipPacket.PayloadLength = (ushort)(ipPacket.PayloadLength + param.payload.Length);
                ret.PayloadPacket = ipPacket;
            }
        }
        else if (param.packetType == Param.PacketType.ICMP)
        {
            ICMPv4Packet icmpPacket = new ICMPv4Packet(new ByteArraySegment(new byte[32]));
            if (param.type != 0 && param.code != 0)
            {
                icmpPacket.TypeCode = (ICMPv4TypeCodes)((param.type * 256) + (param.code));
            }
            else if (param.type != 0)
            {
                icmpPacket.TypeCode = (ICMPv4TypeCodes)((param.type * 256));
            }
            else
            {
                icmpPacket.TypeCode = ICMPv4TypeCodes.EchoRequest;
            }

            IPv4Packet ipPacket = new IPv4Packet(param.sIP, param.dIP);
            if (param.IPv4Frag) { ipPacket.FragmentFlags = (int)1; }
            ipPacket.PayloadPacket = icmpPacket;
            ipPacket.Checksum = ipPacket.CalculateIPChecksum();
            ret = new EthernetPacket(param.sMAC, param.dMAC, EthernetPacketType.IpV4);
            ret.PayloadPacket = ipPacket;
        }
        else if (param.packetType == Param.PacketType.ICMPv6)
        {
            ICMPv6Packet icmpv6Packet = CreateICMPv6Packet(param);
            IPv6Packet ipPacket = new IPv6Packet(param.sIP, param.dIP);
            ipPacket.PayloadPacket = icmpv6Packet;
            ret = new EthernetPacket(param.sMAC, param.dMAC, EthernetPacketType.IpV6);
            ret.PayloadPacket = ipPacket;
        }
        else if (param.packetType == Param.PacketType.IP)
        {
            if (param.dIP.ToString().Contains("."))
            {
                ret = new EthernetPacket(param.sMAC, param.dMAC, EthernetPacketType.IpV4);
                IPv4Packet ipPacket = new IPv4Packet(param.sIP, param.dIP);
                if (param.IPv4Frag) { ipPacket.FragmentFlags = (int)1; }
                ipPacket.Protocol = param.IPProtocol;
                ipPacket.PayloadData = param.payload;
                ipPacket.UpdateCalculatedValues();
                ret.PayloadPacket = ipPacket;
                ipPacket.UpdateIPChecksum();
            }
            else
            {
                ret = new EthernetPacket(param.sMAC, param.dMAC, EthernetPacketType.IpV6);

                //if extension headers were not specified, just put the payload
                if (param.ExtentionHeader.Count == 0)
                {
                    IPv6Packet ipPacket = new IPv6Packet(param.sIP, param.dIP);
                    ipPacket.Protocol = param.IPProtocol;
                    ipPacket.PayloadData = param.payload;
                    ipPacket.PayloadLength = (ushort)param.payload.Length;
                    ipPacket.UpdateCalculatedValues();
                    ret.PayloadPacket = ipPacket;
                }
                else
                {
                    ret = PacketFactory.CreateEHPacket(param, (EthernetPacket)ret);
                }
                ret.UpdateCalculatedValues();
            }
        }
        else if (param.packetType == Param.PacketType.EtherType)
        {
            ret = new EthernetPacket(param.sMAC, param.dMAC, param.EtherTypeProtocol);
            byte[] etherBuffer = (new byte[64]);
            var payload = new byte[etherBuffer.Length + (param.payload).Length];
            etherBuffer.CopyTo(payload, 0);
            (param.payload).CopyTo(payload, etherBuffer.Length);
            ret.PayloadData = payload;
            ret.UpdateCalculatedValues();
        }

        return ret;
    }
예제 #32
0
        public void SendRTPPacket(string sourceSocket, string destinationSocket)
        {
            try
            {
                //logger.Debug("Attempting to send RTP packet from " + sourceSocket + " to " + destinationSocket + ".");
                FireLogEvent("Attempting to send RTP packet from " + sourceSocket + " to " + destinationSocket + ".");
                
                IPEndPoint sourceEP = IPSocket.GetIPEndPoint(sourceSocket);
                IPEndPoint destEP = IPSocket.GetIPEndPoint(destinationSocket);

                RTPPacket rtpPacket = new RTPPacket(80);
                rtpPacket.Header.SequenceNumber = (UInt16)6500;
                rtpPacket.Header.Timestamp = 100000;

                UDPPacket udpPacket = new UDPPacket(sourceEP.Port, destEP.Port, rtpPacket.GetBytes());
                IPv4Header ipHeader = new IPv4Header(ProtocolType.Udp, Crypto.GetRandomInt(6), sourceEP.Address, destEP.Address);
                IPv4Packet ipPacket = new IPv4Packet(ipHeader, udpPacket.GetBytes());

                byte[] data = ipPacket.GetBytes();

                Socket rawSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
                rawSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1);

                rawSocket.SendTo(data, destEP);
            }
            catch (Exception excp)
            {
                logger.Error("Exception SendRTPPacket. " + excp.Message);
            }
        }