private static void ExtractEthernetPacket(EthernetPacket ether)
        {
            switch (ether.Type)
            {
            case EthernetPacketType.Goose:
                ether.PayloadPacket = new GoosePacket(ether.PayloadData, ether);
                packets.Add(ether.PayloadPacket);
                break;

            case EthernetPacketType.Sv:
                // UNDONE: SV construct
                ether.PayloadPacket = new SvPacket(ether.PayloadData, ether);

                packets.Add(ether.PayloadPacket);

                break;

            case EthernetPacketType.Gse:
                break;

            default:
                // Unknown packet
                break;
            }
        }
示例#2
0
        public Packet Build(EthernetPacket packet, UserSession session)
        {
            var mSrc = packet.SourceHardwareAddress;

            var addressBytes = mSrc.GetAddressBytes();

            //Swap out packet MAC address
            for (var i = 0; i < addressBytes.Length; i++)
            {
                _payload[i] = addressBytes[i];
            }

            for (var i = 0; i < addressBytes.Length; i++)
            {
                _payload[0x46 + i] = addressBytes[i];
            }

            for (var i = 0x2e; i <= 0x32; i++)
            {
                _payload[i] = packet.Bytes[i];
            }

            //Assign an IP address based on last 2 bytes of MAC address on 10.253.x.x domain
            _payload[0x3c] = addressBytes[4];
            _payload[0x3d] = addressBytes[5];

            var p = Packet.ParsePacket(LinkLayers.Ethernet, _payload);

            p.UpdateCalculatedValues();

            //await clients.Client(session.ConnectionId).SendGamePacket(session, p);

            return(p);
        }
示例#3
0
        public void EthernetConstructorFromMacAddresses()
        {
            var srcHwAddressBytes = new Byte[EthernetFields.MacAddressLength];

            for (int i = 0; i < srcHwAddressBytes.Length; i++)
            {
                srcHwAddressBytes[i] = (byte)i;
            }

            var dstHwAddressBytes = new Byte[EthernetFields.MacAddressLength];

            for (int i = 0; i < dstHwAddressBytes.Length; i++)
            {
                dstHwAddressBytes[i] = (byte)(dstHwAddressBytes.Length - i);
            }

            var srcHwAddress   = new PhysicalAddress(srcHwAddressBytes);
            var dstHwAddress   = new PhysicalAddress(dstHwAddressBytes);
            var ethernetPacket = new EthernetPacket(srcHwAddress,
                                                    dstHwAddress,
                                                    EthernetPacketType.None);

            int expectedLength = 14;

            Assert.AreEqual(expectedLength, ethernetPacket.Bytes.Length);
            //TODO: improve this here
            Console.WriteLine("ethernetPacket.ToString() {0}",
                              ethernetPacket.ToString());
        }
示例#4
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());
        }
        private static void PostDashEvent(EthernetPacket packet)
        {
            if (((ARPPacket)packet.PayloadPacket).SenderProtocolAddress.ToString() != "0.0.0.0")
            {
                return;
            }

            var macAddress = packet.SourceHwAddress.ToString();
            var button     = ConfigurationManager.AppSettings.AllKeys.SingleOrDefault(m => m.Contains(macAddress));

            if (button == null)
            {
                return;
            }

            var client = new HttpClient();
            var values = new Dictionary <string, string>
            {
                { "Event", ConfigurationManager.AppSettings[button] },
                { "MacAddress", macAddress },
                { "CreatedOn", DateTime.Now.ToString() }
            };

            var data = new FormUrlEncodedContent(values);

            client.PostAsync("http://localhost:56719/your/api/url/here", data).ContinueWith(task =>
            {
                client.Dispose();
            });
        }
示例#6
0
        /// <summary>
        ///     设备扫描发包线程。
        /// </summary>
        /// <param name="obj">地址列表。</param>
        private void ScanPacketSendThread(object obj)
        {
            try {
                // 获取当前设备
                var device = DeviceList[CurDevName];

                // 获取地址列表
                var ipAddresses = (List <IPAddress>)obj;

                // 构建包信息
                var ether = new EthernetPacket(device.MacAddress,
                                               new PhysicalAddress(new byte[] { 255, 255, 255, 255, 255, 255 }),
                                               EthernetPacketType.Arp);
                var arp = new ARPPacket(ARPOperation.Request,
                                        new PhysicalAddress(new byte[] { 0, 0, 0, 0, 0, 0 }),
                                        new IPAddress(new byte[] { 0, 0, 0, 0 }),
                                        device.MacAddress,
                                        Ipv4Address)
                {
                    HardwareAddressType = LinkLayers.Ethernet,
                    ProtocolAddressType = EthernetPacketType.IPv4
                };
                ether.PayloadPacket = arp;
                arp.ParentPacket    = ether;

                // 根据目标地址信息发送ARP请求
                foreach (var targetAddress in ipAddresses)
                {
                    arp.TargetProtocolAddress = targetAddress;
                    arp.UpdateCalculatedValues();
                    device.SendPacket(ether);
                }
            }
            catch (ThreadAbortException) { }
        }
示例#7
0
 /// <summary>
 ///     设备扫描分析线程。
 /// </summary>
 private void ScanPacketAnalyzeThread()
 {
     try {
         while (true)
         {
             // 从队列中请求一个数据包
             RawCapture packet;
             if ((packet = NextRawCapture) != null)
             {
                 // 分析数据包中的数据
                 var ether = new EthernetPacket(new ByteArraySegment(packet.Data));
                 var arp   = (ARPPacket)ether.PayloadPacket;
                 lock (_hostList) {
                     if (_hostList.All(item => !item.PhysicalAddress.ToString().Equals(arp.SenderHardwareAddress.ToString())))
                     {
                         // 添加新的主机记录
                         _hostList.Add(new Host(arp.SenderProtocolAddress, arp.SenderHardwareAddress));
                     }
                     else
                     {
                         // 更新已有主机记录
                         _hostList.Find(item => item.PhysicalAddress.ToString().Equals(arp.SenderHardwareAddress.ToString())).IPAddress = arp.SenderProtocolAddress;
                     }
                 }
             }
             else
             {
                 // 队列尚未获得数据,挂起等待
                 Thread.Sleep(100);
             }
         }
     }
     catch (ThreadAbortException) { }
 }
示例#8
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);
        }
        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);
        }
示例#10
0
        // udp
        public void VerifyPacket2(Packet p, RawCapture rawCapture)
        {
            Console.WriteLine(p.ToString());
            EthernetPacket e = (EthernetPacket)p;

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

            var ip = (IpPacket)p.Extract(typeof(IpPacket));

            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(IpVersion.IPv4, ip.Version);
            Assert.AreEqual(IPProtocolType.UDP, ip.Protocol);
            Assert.AreEqual(112, ip.TimeToLive);
            Assert.AreEqual(0xe0a2, ((IPv4Packet)ip).CalculateIPChecksum());
            Assert.AreEqual(1171483602, rawCapture.Timeval.Seconds);
            Assert.AreEqual(578641.000, rawCapture.Timeval.MicroSeconds);

            var udp = (UdpPacket)p.Extract(typeof(UdpPacket));

            Assert.AreEqual(52886, udp.SourcePort);
            Assert.AreEqual(56924, udp.DestinationPort);
            Assert.AreEqual(71, udp.Length);
            Assert.AreEqual(0xc8b8, udp.Checksum);
        }
示例#11
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);
        }
示例#12
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);
        }
示例#13
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);
        }
示例#14
0
        /// <summary>
        /// 截获包基本信息
        /// </summary>
        /// <returns></returns>
        public static DevicePacket ConvertPacketToDevice(this Packet packet)
        {
            DevicePacket devPacket = new DevicePacket();

            devPacket.Protocol = "未知";
            devPacket.DataLen  = packet.Bytes.Length;

            EthernetPacket ethernetPacket = packet.GetPacketType <EthernetPacket>() as EthernetPacket;

            if (ethernetPacket != null)
            {
                devPacket = packet.GetEthernetPacket(ethernetPacket, devPacket);
                return(devPacket);
            }

            #region "暂时不处理协议"

            //PPPPacket ppp = packet.GetPacketType<PPPPacket>();
            //if (ppp != null)
            //{
            //    devPacket.Protocol = "PPP";
            //    devPacket.SourceAddress = "---";
            //    devPacket.DestinationAddress = "---";
            //    devPacket.Desc = $"协议类型:{ppp.Protocol.ToString()}";

            //    return devPacket;
            //}

            #endregion


            return(devPacket);
        }
示例#15
0
        public static void Main(string[] args)
        {
            ushort tcpSourcePort      = 123;
            ushort tcpDestinationPort = 321;
            var    tcpPacket          = new TcpPacket(tcpSourcePort, tcpDestinationPort);

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

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

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

            // and print out the packet to see that it looks just like we wanted it to
            Console.WriteLine(ethernetPacket.ToString());
        }
示例#16
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);
        }
示例#17
0
        public bool Process(Interface sender, ArpPacket arp)
        {
            if (arp.Operation == ArpOperation.Request)
            {
                var arpResponse = new ArpPacket(
                    ArpOperation.Response,
                    arp.SenderHardwareAddress,
                    arp.SenderProtocolAddress,
                    sender.MacAddress,
                    arp.TargetProtocolAddress
                    );

                var ethernetPacket = new EthernetPacket(sender.MacAddress, arp.SenderHardwareAddress, EthernetType.None)
                {
                    PayloadPacket = arpResponse
                };

                sender.Send(ethernetPacket);
            }
            else if (arp.Operation == ArpOperation.Response)
            {
                var record = new ArpRecord(arp.SenderProtocolAddress, arp.SenderHardwareAddress);
                CurrentApp.Logging.Info($"Creating ARP record: {record}");
                return(TryAdd(arp.SenderProtocolAddress, record));
            }

            return(false);
        }
示例#18
0
文件: scan.cs 项目: zezo010/Catch-IDS
        public void ScanDhcp(CaptureEventArgs e, string Interface)
        {
            var mypacket = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
            var udp      = (UdpPacket)mypacket.Extract(typeof(UdpPacket));

            if (udp != null)
            {
                if (udp.DestinationPort == 68)
                {
                    var       DestinationHwAddress = EthernetPacket.GetEncapsulated(mypacket).DestinationHwAddress;
                    var       SourceHwAddress      = EthernetPacket.GetEncapsulated(mypacket).SourceHwAddress;
                    var       DestinationipAddress = IpPacket.GetEncapsulated(mypacket).DestinationAddress;
                    var       SourceipAddress      = IpPacket.GetEncapsulated(mypacket).SourceAddress;
                    ado       a  = new ado();
                    DataTable dt = a.selectmac(SourceHwAddress.ToString(), Interface);
                    // if mac address of router excist that mean he is router
                    if (dt.Rows.Count > 0)
                    {
                        Attack = false;
                    }
                    else
                    {
                        Attack         = true;
                        Attack_data[0] = "DHCP spofing";
                        Attack_data[1] = SourceipAddress.ToString();
                        Attack_data[2] = SourceHwAddress.ToString();
                        Attack_data[3] = DateTime.Now.ToShortTimeString();
                    }
                }
            }
        }
示例#19
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);
            }
        }
示例#20
0
        // icmpv6
        public void VerifyPacket0(Packet p, RawCapture rawCapture, LinkLayers linkLayer)
        {
            Assert.IsNotNull(p);
            Console.WriteLine(p.ToString());

            Assert.AreEqual(linkLayer, rawCapture.LinkLayerType);

            if (linkLayer == LinkLayers.Ethernet)
            {
                EthernetPacket e = (EthernetPacket)p;
                Assert.AreEqual(PhysicalAddress.Parse("00-A0-CC-D9-41-75"), e.SourceHwAddress);
                Assert.AreEqual(PhysicalAddress.Parse("33-33-00-00-00-02"), e.DestinationHwAddress);
            }

            var ip = (IPPacket)p.Extract(typeof(IPPacket));

            Console.WriteLine("ip {0}", ip.ToString());
            Assert.AreEqual(System.Net.IPAddress.Parse("fe80::2a0:ccff:fed9:4175"), ip.SourceAddress);
            Assert.AreEqual(System.Net.IPAddress.Parse("ff02::2"), ip.DestinationAddress);
            Assert.AreEqual(IPVersion.IPv6, ip.Version);
            Assert.AreEqual(IPProtocolType.ICMPV6, ip.Protocol);
            Assert.AreEqual(16, ip.PayloadPacket.Bytes.Length, "ip.PayloadPacket.Bytes.Length mismatch");
            Assert.AreEqual(255, ip.HopLimit);
            Assert.AreEqual(255, ip.TimeToLive);
            Assert.AreEqual(0x3a, (Byte)ip.NextHeader);
            Console.WriteLine("Failed: ip.ComputeIPChecksum() not implemented.");
            Assert.AreEqual(1221145299, rawCapture.Timeval.Seconds);
            Assert.AreEqual(453568.000, rawCapture.Timeval.MicroSeconds);
        }
示例#21
0
        public void Add(EthernetPacket packet)
        {
            if (packet.TCP == null)
            {
                return;
            }
            TCP_StreamAddress address      = new TCP_StreamAddress(packet);
            TCP_StreamPacket  streamPacket = new TCP_StreamPacket();

            streamPacket.Direction = TCP_Direction.SourceToDestination;
            streamPacket.Address   = address;
            streamPacket.Packet    = packet;
            int        i = Streams.IndexOfKey(address);
            TCP_Stream stream;

            if (i == -1)
            {
                address.StreamNumber = Streams.Count;
                stream = new TCP_Stream(streamPacket);
                Streams.Add(address, stream);
            }
            else
            {
                stream = Streams.Values[i];
                address.StreamNumber = stream.Address.StreamNumber;
            }
            stream.Add(streamPacket);
            Packets.Add(streamPacket);
            packet.gGroupNumber = address.StreamNumber + 1;
        }
示例#22
0
        /// <summary>
        /// Dumps each received packet to a pcap file
        /// </summary>
        private static void device_PcapOnPacketArrival(object sender, SharpPcap.CaptureEventArgs e)
        {
            SyslogMessage msg = null;

            try
            {
                Packet         link     = Packet.ParsePacket(LinkLayers.Ethernet, e.Packet.Data);
                EthernetPacket ethernet = (EthernetPacket)link;
                IpPacket       ip       = (IpPacket)ethernet.PayloadPacket;
                UdpPacket      udp      = (UdpPacket)ip.PayloadPacket;
                msg = new SyslogMessage(udp);
                outputFile.WriteLine(System.Text.Encoding.ASCII.GetString(udp.PayloadData));
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry("SwsyslogService", ex.ToString(), EventLogEntryType.Error);
            }


            // if the output file is ready to write, write the log file ...
            if (msg != null && outputFile.BaseStream.CanWrite)
            {
                //outputFile.WriteLine(msg.ToString());
            }

            _logEntryCount++;
        }
示例#23
0
        public static Packet BuildArpReply(PhysicalAddress srcMAC, PhysicalAddress dstMAC, IPAddress senderIP, IPAddress targetIP, PhysicalAddress senderMAC, PhysicalAddress targetMAC, int vlanID)
        {
            EthernetPacket ePacket = new EthernetPacket(srcMAC, dstMAC, EthernetPacketType.Arp);
            ARPPacket      aPacket = new ARPPacket(ARPOperation.Response, targetMAC, targetIP, senderMAC, senderIP);

            return(PacketBuilder.BuildPacket(vlanID, ePacket, aPacket));
        }
示例#24
0
        public void VerifyPacket1(Packet p, RawCapture rawCapture, LinkLayers linkLayer)
        {
            Assert.IsNotNull(p);
            Console.WriteLine(p.ToString());

            Assert.AreEqual(linkLayer, rawCapture.LinkLayerType);

            if (linkLayer == LinkLayers.Ethernet)
            {
                EthernetPacket e = (EthernetPacket)p;
                Assert.AreEqual(PhysicalAddress.Parse("F894C22EFAD1"), e.SourceHwAddress);
                Assert.AreEqual(PhysicalAddress.Parse("333300000016"), e.DestinationHwAddress);
            }

            var ip = (IPv6Packet)p.Extract(typeof(IPv6Packet));

            Console.WriteLine("ip {0}", ip.ToString());
            Assert.AreEqual(System.Net.IPAddress.Parse("fe80::d802:3589:15cf:3128"), ip.SourceAddress);
            Assert.AreEqual(System.Net.IPAddress.Parse("ff02::16"), ip.DestinationAddress);
            Assert.AreEqual(IPVersion.IPv6, ip.Version);
            Assert.AreEqual(IPProtocolType.ICMPV6, ip.Protocol);
            Assert.AreEqual(28, ip.PayloadPacket.Bytes.Length, "ip.PayloadPacket.Bytes.Length mismatch");
            Assert.AreEqual(1, ip.HopLimit);
            Assert.AreEqual(1, ip.TimeToLive);
            Assert.AreEqual(0x3a, (Byte)ip.Protocol);
            Console.WriteLine("Failed: ip.ComputeIPChecksum() not implemented.");
            Assert.AreEqual(1543415539, rawCapture.Timeval.Seconds);
            Assert.AreEqual(841441.000, rawCapture.Timeval.MicroSeconds);
            Assert.AreEqual(1, ip.ExtensionHeaders.Count);
            Assert.AreEqual(0, ip.ExtensionHeaders[0].OptionsAndPadding.Length);
        }
示例#25
0
文件: ARPReader.cs 项目: onixion/MAD
        private static void SendRequests()
        {
            Logger.Log("Sending ArpRequest flood..", Logger.MessageType.INFORM);
            uint _hosts = NetworkHelper.GetHosts(subnetMask);

            byte[] _netPartBytes = netAddress.GetAddressBytes();
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(_netPartBytes);
            }
            uint           _netPartInt = BitConverter.ToUInt32(_netPartBytes, 0);
            EthernetPacket _ethpac     = NetworkHelper.CreateArpBasePacket(_dev.MacAddress);

            byte[] _targetBytes = new byte[4];
            for (int i = 1; i < _hosts - 1; i++)
            {
                _targetBytes = BitConverter.GetBytes(_netPartInt + i);
                Array.Resize(ref _targetBytes, 4);
                Array.Reverse(_targetBytes);
                IPAddress _target = new IPAddress(_targetBytes);
                ExecuteRequests(_ethpac, _target);
                if (_window != null)
                {
                    _window.progressBarArpScan.Value = Convert.ToInt16(10 + (((i * 100) / _hosts) * 0.8));
                }
            }
        }
示例#26
0
文件: ARPReader.cs 项目: onixion/MAD
        public static void CheckStart()
        {
            _running = true;
            Logger.Log("Start Checking Devices", Logger.MessageType.INFORM);
            InitInterfaces();
            Thread _listen = new Thread(ListenCheckResponses);

            _listen.Start();
            EthernetPacket _ethpac = NetworkHelper.CreateArpBasePacket(_dev.MacAddress);

            foreach (ModelHost _dummy in ModelHost.hostList)
            {
                _dummy.status = false;
                ExecuteRequests(_dummy.hostIP);
            }
            if (Environment.OSVersion.Platform == PlatformID.Unix)
            {
                Thread.Sleep(5000);
            }
            else
            {
                Thread.Sleep(100);
            }
            DeInitInterfaces();
            _running = false;
        }
示例#27
0
文件: Router.cs 项目: ztxyzu/EvilFOCA
        /// <summary>
        /// Indica si es necesario encapsular el contenido del paquete (ipv6) en Ipv4 para el ataque de mitm slaac
        /// http://www.elladodelmal.com/2012/04/man-in-middle-en-redes-ipv4-por-medio.html
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        private bool EncapsulateIpv6IntoIpv4(Packet p)
        {
            EthernetPacket pEthernet = (EthernetPacket)p;

            if (pEthernet.PayloadPacket is IPv6Packet)
            {
                IPv6Packet ipv6 = (IPv6Packet)pEthernet.PayloadPacket;

                for (int iA = 0; iA < Program.CurrentProject.data.GetAttacks().Count; iA++)
                {
                    if (Program.CurrentProject.data.GetAttacks()[iA].attackStatus == AttackStatus.Attacking &&
                        Program.CurrentProject.data.GetAttacks()[iA].attackType == AttackType.SlaacMitm)
                    {
                        if (pEthernet.DestinationHwAddress.Equals(Program.CurrentProject.data.GetDevice().MacAddress))
                        {
                            if (Program.CurrentProject.data.GetAttacks()[iA] is evilfoca.Data.MitmAttack)
                            {
                                evilfoca.Data.MitmAttack mitm = (evilfoca.Data.MitmAttack)Program.CurrentProject.data.GetAttacks()[iA];
                                if ((ipv6.SourceAddress.Equals(mitm.t1.ip)) && (ipv6.DestinationAddress.Equals(mitm.t2.ip)) ||
                                    (ipv6.DestinationAddress.Equals(mitm.t1.ip)) && (ipv6.SourceAddress.Equals(mitm.t2.ip)))
                                {
                                    return(true);
                                }
                            }
                        }
                    }
                }
            }

            return(false);
        }
示例#28
0
        public void EthernetConstructorFromMacAddresses()
        {
            var srcHwAddressBytes = new byte[EthernetFields.MacAddressLength];

            for (var i = 0; i < srcHwAddressBytes.Length; i++)
            {
                srcHwAddressBytes[i] = (byte)i;
            }

            var dstHwAddressBytes = new byte[EthernetFields.MacAddressLength];

            for (var i = 0; i < dstHwAddressBytes.Length; i++)
            {
                dstHwAddressBytes[i] = (byte)(dstHwAddressBytes.Length - i);
            }

            var srcHwAddress   = new PhysicalAddress(srcHwAddressBytes);
            var dstHwAddress   = new PhysicalAddress(dstHwAddressBytes);
            var ethernetPacket = new EthernetPacket(srcHwAddress,
                                                    dstHwAddress,
                                                    EthernetType.None);

            Assert.AreEqual(14, ethernetPacket.Bytes.Length);
            Assert.AreEqual(srcHwAddress, ethernetPacket.SourceHardwareAddress);
            Assert.AreEqual(dstHwAddress, ethernetPacket.DestinationHardwareAddress);

            ethernetPacket.SourceHardwareAddress      = dstHwAddress;
            ethernetPacket.DestinationHardwareAddress = srcHwAddress;

            Assert.AreEqual(dstHwAddress, ethernetPacket.SourceHardwareAddress);
            Assert.AreEqual(srcHwAddress, ethernetPacket.DestinationHardwareAddress);

            Console.WriteLine("ethernetPacket.ToString() {0}", ethernetPacket);
        }
示例#29
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
            };
            UdpPacket udpPacket = new UdpPacket(1, 1)
            {
                PayloadData = payload
            };

            ipPacket.PayloadPacket    = udpPacket;
            etherPacket.PayloadPacket = ipPacket;
            return(new TempPacketSaveData(etherPacket.Bytes, LinkLayerType.Ethernet));
        }
        /**
         * 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
            }
        }
示例#31
0
    //terrible hack to get extension headers working
    private static EthernetPacket CreateEHPacket(Param param, EthernetPacket ret)
    {
        IPv6Packet ipPacket = new IPv6Packet(param.sIP, param.dIP);
        ipPacket.Protocol = (IPProtocolType)param.ExtentionHeader[0];
        param.ExtentionHeader.RemoveAt(0);

        //need to find out what is the last packet so that we can decide on the length of the packet
        IPProtocolType endEH = param.ExtentionHeader[param.ExtentionHeader.Count - 1];
        int lastHeaderLength = 0;
        switch (endEH)
        {
            case IPProtocolType.TCP:
                lastHeaderLength = 20;
                break;
            case IPProtocolType.UDP:
                lastHeaderLength = 8;
                break;
            case IPProtocolType.ICMP:
                lastHeaderLength = 8;
                break;
            default:
                lastHeaderLength = 64;
                break;
        }

        //calculate the Extension header size
        int EHSize = 0;
        foreach (IPProtocolType eh in param.ExtentionHeader)
        {
            if (eh == IPProtocolType.FRAGMENT)
            {
                EHSize += 8;
            }
            else
            {
                EHSize += 24;
            }
        }

        if (ipPacket.Protocol == IPProtocolType.FRAGMENT)
        {
            EHSize -= 16;
        }

        byte[] tempPayload = new byte[EHSize + param.payload.Length + lastHeaderLength];
        param.payload.CopyTo(tempPayload, EHSize + lastHeaderLength);

        int loc = 0;
        byte previous = (byte)ipPacket.Protocol;
        foreach (byte eh in param.ExtentionHeader)
        {
            tempPayload.SetValue((byte)eh, loc);
            tempPayload.SetValue((byte)2, loc + 1);
            if ((IPProtocolType)previous == IPProtocolType.FRAGMENT)
            {
                loc += 8;
            }
            else
            {
                loc += 24;
            }
            previous = eh;
        }

        //set the port if the last EH is tcp or udp
        if (endEH == IPProtocolType.TCP || endEH == IPProtocolType.UDP)
        {
            //set the port numbers
            tempPayload.SetValue((byte)(param.sPort >> 8), loc);
            tempPayload.SetValue((byte)param.sPort, loc + 1);
            tempPayload.SetValue((byte)(param.dPort >> 8), loc + 2);
            tempPayload.SetValue((byte)param.dPort, loc + 3);
        }
        if (endEH == IPProtocolType.TCP)
        {
            tempPayload.SetValue((byte)0x50, loc + 12);
        }
        else if (endEH == IPProtocolType.UDP)
        {
            //set the length of the payload
            Int16 length = (Int16)(lastHeaderLength + param.payload.Length);
            BitConverter.GetBytes(length).CopyTo(tempPayload, loc + 5);
            tempPayload.SetValue((byte)0x12, loc + 6);
            tempPayload.SetValue((byte)0x34, loc + 7);
        }

        //set the tcp flags if they are TCP
        if (endEH == IPProtocolType.TCP)
        {
            tempPayload.SetValue((byte)param.tcpFlag, loc + 13);
        }

        ipPacket.PayloadData = tempPayload;
        ipPacket.PayloadLength = (ushort)tempPayload.Length;
        ipPacket.UpdateCalculatedValues();
        ret.PayloadPacket = ipPacket;
        return ret;
    }
示例#32
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;
    }