Beispiel #1
0
        public string scanHost(string host)
        {
            // Parse target IP addr

            LibPcapLiveDevice device   = getDevice();
            IPAddress         targetIP = null;

            bool ok = IPAddress.TryParse(host, out targetIP);

            if (!ok)
            {
                Console.WriteLine("Invalid IP.");
                return("fail");
            }

            // Create a new ARP resolver
            ARP arp = new ARP(device);

            arp.Timeout = new System.TimeSpan(scanDelay); // 100ms

            // Enviar ARP
            var resolvedMacAddress = arp.Resolve(targetIP);

            if (resolvedMacAddress == null)
            {
                return("fail");
            }
            else
            {
                string fmac = formatMac(resolvedMacAddress);
                Console.WriteLine(targetIP + " is at: " + fmac);

                return(fmac);
            }
        }
Beispiel #2
0
        public void TestArpTunnel()
        {
            var nic = TunnelDevice.GetTunnelInterfaces().First();

            using var tapDevice = GetTunnelDevice(nic);
            // Open TAP device first to ensure the virutal device is connected
            tapDevice.Open(DeviceModes.Promiscuous);
            var tapIp = IpHelper.GetIPAddress(nic);

            // we need to provide our own IP and MAC, otherwise OS will ignore its own requests
            var ipBytes = tapIp.GetAddressBytes();

            ipBytes[3]++;
            var testIp  = new IPAddress(ipBytes);
            var testMac = PhysicalAddress.Parse("001122334455");

            PhysicalAddress mac = null;

            for (int i = 0; i < 5; i++)
            {
                mac = ARP.Resolve(tapDevice, tapIp, testIp, testMac, TimeSpan.FromSeconds(1));
                if (mac != null)
                {
                    break;
                }
                // Wait for interface to finish Gratuitous ARP
            }


            Assert.AreEqual(tapDevice.MacAddress, mac);
        }
        public static PhysicalAddress ResolveMac(LibPcapLiveDevice device, IPAddress Instance)
        {
            ARP Resolver = new ARP(device);

            Resolver.Timeout = new TimeSpan(0, 0, 3);
            return(Resolver.Resolve(Instance, getLocaIP(), GetMacAddress()));
        }
Beispiel #4
0
        public static PhysicalAddress ResolveMac(NetworkInterface device, IPAddress Instance)
        {
            ARP Resolver = new ARP((LibPcapLiveDevice)NetworkInstruments.getActiveDevice(device.GetPhysicalAddress()));

            Resolver.Timeout = new TimeSpan(0, 0, 4);
            return(Resolver.Resolve(Instance, getAdapterIPAddress(device), device.GetPhysicalAddress()));
        }
Beispiel #5
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private void sendGratuitousARP() throws java.io.EOFException
        private void sendGratuitousARP()
        {
            EtherFrame frame = new EtherFrame();

            frame.dstMac = new pspNetMacAddress(ANY_MAC_ADDRESS);
            frame.srcMac = MacAddress;
            frame.type   = ETHER_TYPE_ARP;

            ARP arp = new ARP();

            arp.hardwareType          = HARDWARE_TYPE_ETHERNET;
            arp.protocolType          = ETHER_TYPE_IPv4;
            arp.hardwareAddressLength = MAC_ADDRESS_LENGTH;
            arp.protocolAddressLength = IP_ADDRESS_LENGTH;
            arp.operation             = ARP_OPERATION_REQUEST;
            arp.senderHardwareAddress = MacAddress;
            arp.senderProtocolAddress = IpAddress;
            // Set the target hardware address to 00:00:00:00:00:00
            arp.targetHardwareAddress = new pspNetMacAddress();
            arp.targetProtocolAddress = IpAddress;

            NetPacket packet = new NetPacket(EtherFrame.sizeOf() + arp.sizeOf());

            frame.write(packet);
            arp.write(packet);

            sendPacket(packet);
        }
    /*******************************************************************************/

    /* Methods Implemented to Create ARP requests and Replies using the ARP protocol
     * /* header and to set up the required information for the header before returning back to the PC
     * /***********************************************************/
    public Packet Request(string ipsrc, string ipdest)
    {
        //Request packet instantiated in the game
        GameObject reqPack = Instantiate(packetprefab);

        //get ref to packet component
        Packet packet = reqPack.GetComponent <Packet>();

        //create the packet with the ARP ID tag
        packet.CreatePacket("ARP");
        //set info for packet
        packet.internet.setIP(ipdest, "dest");
        packet.internet.setIP(ipsrc, "src");

        //if the device is a PC, get the pc component and return it's MAC address, else get router's MAC
        if (GetComponent <PC>())
        {
            packet.netAccess.setMAC(GetComponent <PC>().MAC, "src");
        }
        else
        {
            packet.netAccess.setMAC(GetComponent <Router>().getMAC(), "src");
        }

        //set destination MAC address to be a broadcast message
        packet.netAccess.setMAC("FF:FF:FF:FF:FF:FF", "dest");

        //Add and fill ARP header with data
        ARP arp = reqPack.AddComponent <ARP>();

        arp.CreateARP("REQUEST", ipdest);

        return(packet);
    }
    public Packet Reply(string ipsrc, string ipdest, string mac)
    {
        GameObject repPack = Instantiate(packetprefab);

        Packet packet = repPack.GetComponent <Packet>();

        packet.CreatePacket("ARP");

        packet.internet.setIP(ipdest, "dest");
        packet.internet.setIP(ipsrc, "src");

        if (GetComponent <PC>())
        {
            packet.netAccess.setMAC(GetComponent <PC>().MAC, "src");
        }
        else
        {
            packet.netAccess.setMAC(GetComponent <Router>().getMAC(), "src");
        }
        //set destination MAC address to be the packet's source MAC provided as a parameter to this method
        packet.netAccess.setMAC(mac, "dest");

        ARP arp = repPack.AddComponent <ARP>();

        arp.CreateARP("REPLY", ipdest);

        return(packet);
    }
Beispiel #8
0
        /// <summary>
        /// Finds MAC address of the gateway, when its IP address is in ipOfgateway.
        /// The MAC address is stored in macOfGateway.
        /// </summary>
        /// <returns>
        ///     <c>true</c> if MAC address is found, otherwise <c>false</c>.
        /// </returns>
        protected bool findMACofGateway()
        {
            ARP arp;

            if (ipOfGateway == null)
            {
                return(false);
            }
            //get list of all available interfaces
            SharpPcap.LibPcap.LibPcapLiveDeviceList lldl = SharpPcap.LibPcap.LibPcapLiveDeviceList.Instance;
            //find MAC address of gateway
            foreach (SharpPcap.LibPcap.LibPcapLiveDevice lld in lldl)
            {
                arp = new ARP(lld);
                try
                {
                    macOfGateway = arp.Resolve(ipOfGateway);
                    Console.WriteLine("MAC of gateway: " + macOfGateway.ToString());
                    liveInterface = lld;
                }
                catch (NullReferenceException)
                {
                    continue;
                }
                return(true);
            }
            return(false);
        }
Beispiel #9
0
        public static async Task <AddressSet[]> GetV4ActiveAddressSetOnLan()
        {
            var range  = Util.GetV4AddressRangeOnLan();
            var result = new List <AddressSet>();
            var tasks  = new List <Task>();

            var device = Util.GetDevice(Util.GetLocalPrimaryAddress());

            if (device == null)
            {
                return(result.ToArray());
            }

            await Task.Run(() => {
                foreach (var addr in range)
                {
                    // 下記を並列で実行すると落ちる。
                    // 一つ一つ順次取得するしかない。
                    var arp     = new ARP(device);
                    arp.Timeout = new TimeSpan(3000000); //300msec
                    var mac     = arp.Resolve(addr);
                    if (mac != null)
                    {
                        var addrSet        = new AddressSet();
                        addrSet.IPAddress  = addr;
                        addrSet.MacAddress = mac.GetAddressBytes();
                        result.Add(addrSet);
                    }
                }
            });

            return(result.ToArray());
        }
        private void button1_Click(object sender, EventArgs e)
        {
            WinPcapDevice PcapDevice = WinPcapDeviceList.Instance[comboBox1.SelectedIndex];
            ARP           req        = new ARP((LibPcapLiveDevice)CaptureDeviceList.Instance[comboBox1.SelectedIndex]);

            Console.Out.WriteLine(PcapDevice.Addresses[1]);

            req.Timeout = new System.TimeSpan(1200000);

            IPAddress target = null;

            IPAddress.TryParse(networkText.Text, out target);

            int    retry          = 5;
            string hostMacAddress = null;

            while (retry > 1 && hostMacAddress == null)
            {
                try
                {
                    hostMacAddress = req.Resolve(target).ToString();
                }
                catch { }
                retry -= 1;
            }

            try
            {
                Console.Out.WriteLine(hostMacAddress.ToString());
            }
            catch { }
        }
Beispiel #11
0
        /// <summary>
        /// Initializes networking
        /// </summary>
        private static unsafe void initNetworking()
        {
            // Networking
            Network.Init();
            Route.Init();

            // Networking protocols
            IPV4.Init();
            ICMP.Init();

            // Transport protocols
            UDP.Init();
            TCP.Init();
            ARP.Init();
            DHCP.Init();

            // Network drivers
            E1000.Init();
            PCNet2.Init();
            RTL8139.Init();

            DHCP.Discover();


            //Thread packetHandler = new Thread();
            //packetHandler.Context.CreateNewContext(Util.MethodToPtr(HttpTest), 0, null, true);
            //Tasking.KernelTask.AddThread(packetHandler);
        }
Beispiel #12
0
        public static void Main3(string[] args)
        {
            string ver = Tamir.IPLib.Version.GetVersionString();

            /* Print SharpPcap version */
            Console.WriteLine("SharpPcap {0}, ArpTest.cs", ver);
            Console.WriteLine();

            /* Retrieve the device list */
            PcapDeviceList devices = SharpPcap.GetAllDevices();

            /*If no device exists, print error */
            if (devices.Count < 1)
            {
                Console.WriteLine("No device found on this machine");
                return;
            }

            Console.WriteLine("The following devices are available on this machine:");
            Console.WriteLine("----------------------------------------------------");
            Console.WriteLine();

            int i = 0;

            /* Scan the list printing every entry */
            foreach (PcapDevice dev in devices)
            {
                /* Description */
                Console.WriteLine("{0}) {1}", i, dev.PcapDescription);
                i++;
            }

            Console.WriteLine();
            Console.Write("-- Please choose a device for sending the ARP request: ");
            i = int.Parse(Console.ReadLine());

            string device = devices[i].PcapName;

            String ip = "";

            while (true)
            {
                Console.Write("-- Please enter IP address to be resolved by ARP: ");
                ip = Console.ReadLine();
                if (IPUtil.IsIP(ip))
                {
                    break;
                }
                Console.WriteLine("Bad IP address format, please try again");
            }

            //Create a new ARP resolver
            //(for more info, see:
            //http://www.tamirgal.com/home/SourceView.aspx?Item=SharpPcap&File=ARP.cs)
            ARP arper = new ARP(device);

            //print the resolved address
            Console.WriteLine(ip + " is at: " + arper.Resolve(ip));
        }
Beispiel #13
0
        private PhysicalAddress GetGatewayMAC(string friendlyname)
        {
            var devices = LibPcapLiveDeviceList.Instance;
            var device  = (from devicex in devices where devicex.Interface.FriendlyName == friendlyname select devicex).ToList()[0];
            ARP arper   = new ARP(device);

            return(arper.Resolve(GetGatewayIP(friendlyname)));
        }
Beispiel #14
0
        public void FilterMethods()
        {
            using var device = TestHelper.GetPcapDevice();
            device.Open();

            var filterExpression = "arp";
            var mask             = (uint)0;
            var result           = PcapDevice.CompileFilter(device.PcapHandle, filterExpression, mask, out IntPtr bpfProgram, out string errorString);

            Assert.IsTrue(result);

            var arp           = new ARP(device);
            var destinationIP = new System.Net.IPAddress(new byte[] { 8, 8, 8, 8 });

            // Note: We don't care about the success or failure here
            arp.Resolve(destinationIP);

            // retrieve some packets, looking for the arp
            var header        = IntPtr.Zero;
            var data          = IntPtr.Zero;
            var foundBpfMatch = false;
            var packetsToTry  = 10;
            var sw            = System.Diagnostics.Stopwatch.StartNew();

            while (packetsToTry > 0)
            {
                if (sw.ElapsedMilliseconds > 2000)
                {
                    break;
                }

                var retval = device.GetNextPacketPointers(ref header, ref data);

                if (retval == 1)
                {
                    packetsToTry--;

                    Assert.AreNotEqual(IntPtr.Zero, header);
                    Assert.AreNotEqual(IntPtr.Zero, data);

                    // and test it against the bpf filter to confirm an exception is not thrown
                    Assert.DoesNotThrow(() =>
                    {
                        // we expect a match as we are sending an arp packet
                        if (PcapDevice.RunBpfProgram(bpfProgram, header, data))
                        {
                            foundBpfMatch = true;
                        }
                    }
                                        );
                }
            }

            Assert.IsTrue(foundBpfMatch);

            PcapDevice.FreeBpfProgram(bpfProgram);
        }
        public void CorrectsHType()
        {
            ARP packet = ARPFactory.Instance.Default();

            packet.HType.Should().Be(0); // Just making sure our test is valid.
            packet.SetContainer(EthernetIIFactory.Instance.Default(GenericFactory.Instance.Default()));
            packet.CorrectFields();
            packet.HType.Should().Be(8);
        }
Beispiel #16
0
        public static PhysicalAddress GetMacFromIp(IPAddress p_Ip)
        {
            PhysicalAddress l_Mac = null;

            lock (LibPcapHandler.Instance.lockObj)
            {
                ARP l_Arp = new ARP(LibPcapHandler.Instance.Device);
                l_Mac = l_Arp.Resolve(p_Ip, GetLocalAddr(), GetLocalMac());
            }
            return(l_Mac);
        }
Beispiel #17
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private void processMessageARP(pspsharp.network.protocols.NetPacket packet) throws java.io.EOFException
        private void processMessageARP(NetPacket packet)
        {
            ARP arp = new ARP();

            arp.read(packet);

            if (arp.hardwareType != HARDWARE_TYPE_ETHERNET)
            {
                Console.WriteLine(string.Format("processMessageARP unknown hardwareType=0x{0:X}", arp.hardwareType));
                return;
            }

            if (arp.protocolType != ETHER_TYPE_IPv4)
            {
                Console.WriteLine(string.Format("processMessageARP unknown protocolType=0x{0:X}", arp.protocolType));
                return;
            }

            if (arp.hardwareAddressLength != MAC_ADDRESS_LENGTH)
            {
                Console.WriteLine(string.Format("processMessageARP unknown hardwareAddressLength=0x{0:X}", arp.protocolType));
                return;
            }

            if (arp.protocolAddressLength != IP_ADDRESS_LENGTH)
            {
                Console.WriteLine(string.Format("processMessageARP unknown protocolAddressLength=0x{0:X}", arp.protocolType));
                return;
            }

            if (arp.operation != ARP_OPERATION_REQUEST && arp.operation != ARP_OPERATION_REPLY)
            {
                Console.WriteLine(string.Format("processMessageARP unknown operation=0x{0:X}", arp.operation));
                return;
            }

            //if (log.DebugEnabled)
            {
                Console.WriteLine(string.Format("processMessageARP {0}", arp));
            }

            if (arp.targetHardwareAddress.EmptyMacAddress)
            {
                // A gratuitous ARP message has been received.
                // It is used to announce a new IP address.
                // Send back a gratuitous ARP message to announce ourself.
                sendGratuitousARP();
            }
        }
        public static string ConverToMac(string name, string ip)
        {
            var dev = Get(name);

            if (dev != null)
            {
                ARP arp = new ARP(dev.PcapName);
                //arp.LocalIP = dev.IpAddress;
                //arp.LocalMAC = dev.MacAddress;
                arp.LocalIP  = "192.168.1.130";
                arp.LocalMAC = "D8-CB-8A-96-82-A0";
                return(arp.Resolve(ip));
            }
            return(null);
        }
Beispiel #19
0
        public void TestArp()
        {
            var d   = TestHelper.GetPcapDevice();
            var arp = new ARP(d);

            // timeout should not be null
            Assert.IsNotNull(arp.Timeout);

            // and we can set a timeout
            arp.Timeout = new TimeSpan(0, 0, 2);

            var destinationIP = new System.Net.IPAddress(new byte[] { 8, 8, 8, 8 });

            // Note: We don't care about the success or failure here
            arp.Resolve(destinationIP);
        }
Beispiel #20
0
        public static arpResult Resolve(System.Net.IPAddress dest, LibPcapLiveDevice dev = null)
        {
            if (dev == null)
            {
                dev = device.directLinkDevice(dest);
            }
            ARP       arper = new ARP(dev);
            Stopwatch sw    = Stopwatch.StartNew();

            System.Net.NetworkInformation.PhysicalAddress mac = arper.Resolve(dest);
            sw.Stop();
            long ms = sw.ElapsedMilliseconds;

            return(new arpResult {
                dest = dest, mac = mac, elapsedMs = ms
            });
        }
Beispiel #21
0
        public IList <IPAddress> GetLanIpAddresses()
        {
            var packets           = new List <PcapDotNet.Packets.Packet>();
            var ipAddressesToScan = this.device.Addresses.Where(x => x.Addr.sa_family == 2).SelectMany(x => this.GetIpAddresses(x.Addr, x.Netmask)).ToList();

            this.OnPacketArrival += this.ReceivedNewPacket;
            this.StartCapture("arp");
            var arp = new ARP(this.device);

            var ethernetLayer = new EthernetLayer()
            {
                Source      = new MacAddress(this.MacAddress),
                Destination = new MacAddress("FF:FF:FF:FF:FF:FF"),
                EtherType   = EthernetType.Arp,
            };

            foreach (var ipAddressToScan in ipAddressesToScan)
            {
                var arpLayer = new ArpLayer()
                {
                    Operation             = ArpOperation.Request,
                    ProtocolType          = EthernetType.IpV4,
                    SenderHardwareAddress = new ReadOnlyCollection <byte>(PhysicalAddress.Parse(this.MacAddress.Replace(":", "-")).GetAddressBytes()),
                    SenderProtocolAddress = new ReadOnlyCollection <byte>(this.IpAddress.GetAddressBytes()),
                    TargetHardwareAddress = new ReadOnlyCollection <byte>(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }),
                    TargetProtocolAddress = new ReadOnlyCollection <byte>(ipAddressToScan.GetAddressBytes()),
                };

                var packetBuilder = new PacketBuilder(ethernetLayer, arpLayer);
                packets.Add(packetBuilder.Build(DateTime.Now));
            }

            foreach (var packet in packets)
            {
                this.SendPacket(packet.Buffer);
                Thread.Sleep(100);
            }

            Thread.Sleep(1000);

            this.StopCapture();
            this.OnPacketArrival -= this.ReceivedNewPacket;

            return(this.onlineIpAddresses.Keys.ToList());
        }
Beispiel #22
0
        protected override void Run()
        {
            EndIp = NetUtils.GetNextIP(EndIp);

            ARP arp = new ARP(Device);

            arp.Timeout = new TimeSpan(0, 0, 0, 0, 200);

            do
            {
                if (StopAsked)
                {
                    break;
                }

                var physicalAddress = arp.Resolve(current_ip);

                if (physicalAddress == null)
                {
                    continue;
                }

                Host host = new Host();
                host.IpAddress  = current_ip;
                host.MacAddress = physicalAddress;

                if (ResolveHostname)
                {
                    string nom = string.Empty;
                    try { nom = System.Net.Dns.GetHostEntry(host.IpAddress).HostName; } catch { }

                    if (nom != host.IpAddress.ToString())
                    {
                        host.Name = nom;
                    }
                }

                HostFind?.Invoke(this, new HostEventArgs()
                {
                    Host = host
                });
            } while (!(current_ip = NetUtils.GetNextIP(current_ip)).Equals(EndIp));
        }
Beispiel #23
0
        private static string GetMacFromIp(IPAddress targetIP)
        {
            // Create a new ARP resolver
            ARP arp = new ARP(device);

            arp.Timeout = new System.TimeSpan(scanDelay);

            // Enviar ARP
            var resolvedMacAddress = arp.Resolve(targetIP);

            if (resolvedMacAddress == null)
            {
                return("fail");
            }
            else
            {
                string fmac = resolvedMacAddress.ToString(); // formatMac(resolvedMacAddress);
                //Console.WriteLine(targetIP + " is at: " + fmac);

                return(fmac);
            }
        }
Beispiel #24
0
        /// <summary>
        /// Gets the arp.
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception">ParametersDAO.GetARP</exception>

        public OutARP GetARP()
        {
            string connectionString = DataBaseHelper.GetConnectionString("DLG");
            OutARP response         = new OutARP();
            var    ora = new OracleServer(connectionString);

            ARP        arp;
            List <ARP> list    = new List <ARP>();
            string     command = string.Empty;

            try
            {
                command = " SELECT  NIT, NOMBRE, CODIGO_MINISTERIO  FROM BBS_WFC_PAR_ARP where nit> 0 ";
                var rdr = ora.ExecuteCommand(command);

                while (rdr.Read())
                {
                    arp                 = new ARP();
                    arp.arpNIT          = DBNull.Value.Equals(rdr["NIT"]) ? string.Empty : rdr["NIT"].ToString();
                    arp.arpName         = DBNull.Value.Equals(rdr["NOMBRE"]) ? string.Empty : rdr["NOMBRE"].ToString();
                    arp.arpCodeMinistry = DBNull.Value.Equals(rdr["CODIGO_MINISTERIO"]) ? string.Empty : rdr["CODIGO_MINISTERIO"].ToString();
                    list.Add(arp);
                }
                rdr.Close();
                response.lstARP           = list;
                response.msg              = new Response();
                response.msg.errorCode    = "200";
                response.msg.errorMessage = "OK";
            }
            catch (Exception ex)
            {
                throw new Exception("ParametersDAO.GetARP", ex);
            }
            finally
            {
                ora.Dispose();
            }
            return(response);
        }
        private void butARPRequest_Click(object sender, System.EventArgs e)
        {
            System.Net.IPAddress ip;

            if (!System.Net.IPAddress.TryParse(textBoxIP.Text, out ip))
            {
                MessageBox.Show("Incorrect IP adress format");
            }
            else
            {
                ARP arper             = new ARP(_device);
                var resolvedMacAdress = arper.Resolve(ip);
                if (resolvedMacAdress == null)
                {
                    MessageBox.Show("No mac address found for this ip", "Info");
                }
                else
                {
                    textBoxMACadr.Text = resolvedMacAdress.ToString();
                }
            }
        }
Beispiel #26
0
        static public void spoof(string host)
        {
            LibPcapLiveDevice device = getDevice();
            IPAddress         ip     = IPAddress.Parse(host);

            // Create a new ARP resolver
            ARP arp = new ARP(device);

            arp.Timeout = new System.TimeSpan(scanDelay * 2); // 100ms

            // Preparar ip y mac fake, solo para spoofing
            IPAddress local_ip;

            IPAddress.TryParse("192.168.1.1", out local_ip);

            PhysicalAddress mac;

            mac = PhysicalAddress.Parse("11-22-33-44-55-66");

            // Enviar ARP

            for (int i = 0; i < 10000; i++)
            {
                try
                {
                    arp.Resolve(ip, local_ip, mac);
                }
                catch (Exception e)
                {
                    MessageBox.Show(ip + " stopped responding: " + e.Message);
                    return;
                }

                System.Threading.Thread.Sleep(5000); // 5 sec
            }

            return;
        }
Beispiel #27
0
        /// <summary>
        /// 実行する
        /// </summary>
        public List <ScanResponse> Execute()
        {
            var ret = new List <ScanResponse>();
            // デバイス変換
            var device = _captureDevice as NpcapDevice;

            if (device == null)
            {
                throw new InvalidCastException(string.Format("デバイス {0} を NpcapDevice に変換できません", device.Description));
            }

            // 送信元IPアドレス
            var srcIPAddress = GetIPv4(device);

            // SYNスキャン
            foreach (var request in _scanRequests)
            {
                // 送信先MACアドレス
                var arp = new ARP(device);
                var targetMacAddress = arp.Resolve(request.IPAddress);

                if (targetMacAddress == null)
                {
                    ret.Add(new ScanResponse()
                    {
                        IPAddress = request.IPAddress,
                        Port      = request.Port,
                        Status    = PortStatus.UnResolved
                    });
                    continue;
                    //throw new InvalidOperationException(string.Format("アドレス {0} を ARP 解決できません", request.IPAddress.ToString()));
                }

                // TCPヘッダ生成
                var tcpPacket = new TcpPacket(1024, request.Port);
                tcpPacket.Synchronize = !tcpPacket.Synchronize;
                tcpPacket.WindowSize  = 4096;

                // IPヘッダ生成
                var ipPacket = new IPv4Packet(srcIPAddress, request.IPAddress);

                // Ehternetヘッダ生成
                var ethernetPacket = new EthernetPacket(device.Interface.MacAddress, targetMacAddress, EthernetType.None);

                // TCPパケット生成
                ipPacket.PayloadPacket = tcpPacket;
                tcpPacket.UpdateTcpChecksum();
                ethernetPacket.PayloadPacket = ipPacket;
                ipPacket.UpdateIPChecksum();

                for (int retryCount = 0; retryCount < _maxRetryCount; retryCount++)
                {
                    // オープン
                    device.Open(DeviceMode.Normal, 1000);
                    // フィルタセット
                    device.Filter = "src host " + request.IPAddress + " and src port " + request.Port + " and (tcp[13] & 18 != 0) or (tcp[13] & 4 != 0)";

                    try
                    {
                        // TCPパケット送信
                        device.SendPacket(ethernetPacket);

                        // 受信パケット取得
                        var rawpacket = device.GetNextPacket();

                        if (rawpacket == null)
                        {
                            if ((retryCount + 1) >= _maxRetryCount)
                            {
                                ret.Add(new ScanResponse()
                                {
                                    IPAddress = request.IPAddress,
                                    Port      = request.Port,
                                    Status    = PortStatus.Timeout
                                });
                                break;
                            }
                            continue;
                        }
                        else
                        {
                            // SYN/ACKフラグが立っていたら、open判定
                            // RSTフラグが立っていたらclosed判定
                            var response = Packet.ParsePacket(rawpacket.LinkLayerType, rawpacket.Data);
                            if (response is EthernetPacket eth)
                            {
                                var ip = response.Extract <IPPacket>();
                                if (ip != null)
                                {
                                    var tcp = response.Extract <TcpPacket>();
                                    if (tcp != null)
                                    {
                                        if (tcp.Acknowledgment && tcp.Synchronize)
                                        {
                                            ret.Add(new ScanResponse()
                                            {
                                                IPAddress = request.IPAddress,
                                                Port      = request.Port,
                                                Status    = PortStatus.Open
                                            });
                                        }
                                        else if (tcp.Reset)
                                        {
                                            ret.Add(new ScanResponse()
                                            {
                                                IPAddress = request.IPAddress,
                                                Port      = request.Port,
                                                Status    = PortStatus.Closed
                                            });
                                        }
                                        else
                                        {
                                            ret.Add(new ScanResponse()
                                            {
                                                IPAddress = request.IPAddress,
                                                Port      = request.Port,
                                                Status    = PortStatus.UnKnown
                                            });
                                        }
                                    }
                                }
                            }
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    finally
                    {
                        if (device.Opened)
                        {
                            device.Close();
                        }
                    }
                }
            }
            return(ret);
        }
Beispiel #28
0
        public bool connect(IPEndPoint ipEnd, int port)
        {
            int lLen = EthernetFields_Fields.ETH_HEADER_LEN;
            //SYN packet creation
            #region Various Initializations
            ARP arper = new ARP();
            var bytes = new byte[54];
            var tcp = new TCPPacket(lLen, bytes, true) { IPVersion = IPPacket.IPVersions.IPv4 };
            #endregion

            #region Ethernet Fields
            tcp.SourceHwAddress = _dev.Interface.MacAddress;
            arper.DeviceName = _dev.Name;
            arper.LocalIP = _dev.Interface.Addresses[1].Addr.ipAddress;
            arper.LocalMAC = _dev.Interface.MacAddress;
            //MAC address of gateway is provided by arp protocol
            tcp.DestinationHwAddress = arper.Resolve(_gatewayAddr,_dev.Name);
            tcp.EthernetProtocol = EthernetPacket.EtherType.IP;
            #endregion

            #region IP Fields

            tcp.DestinationAddress = ipEnd.Address;
            tcp.SourceAddress = _dev.Interface.Addresses[1].Addr.ipAddress;
            tcp.IPProtocol = IPProtocol.IPProtocolType.TCP;
            tcp.TimeToLive = 20;
            tcp.ipv4.Id = 100;
            tcp.ipv4.IPTotalLength = bytes.Length - lLen;
            tcp.ipv4.IPHeaderLength = IPv4Fields_Fields.IP_HEADER_LEN;
            #endregion

            #region TCP Fields
            tcp.SourcePort = 2222;
            tcp.DestinationPort = port;
            tcp.Syn = true;
            tcp.WindowSize = 555;
            tcp.SequenceNumber = 0;
            tcp.TCPHeaderLength = TCPFields_Fields.TCP_HEADER_LEN;
            #endregion

            //Headers checksum calculations
            tcp.ipv4.ComputeIPChecksum();
            tcp.ComputeTCPChecksum();

            _dev.Open(false, 20);
            _dev.SetFilter("ip src " + tcp.DestinationAddress + " and tcp src port " + tcp.DestinationPort + " and tcp dst port " + tcp.SourcePort);

            //Send the packet
            Console.Write("Sending SYN packet: " + tcp + "...");
            _dev.SendPacket(tcp);
            Console.WriteLine("SYN Packet sent.");
            TCPPacket reply = null;
            var watch = new Stopwatch();
            bool received = false;
            watch.Start();
            //Condition including timeout check.
            while (watch.ElapsedMilliseconds < _timeout && received != true)
            {
                if ((reply = (TCPPacket) _dev.GetNextPacket()) != null)
                {
                    Console.WriteLine("SYN ACK Reply received: " + reply);
                    received = true;
                }
            }
            //A reply hasn't returned
            if (!received)
            {
                _dev.Close();
                throw new Exception("TIME_OUT");
            }
            //Remote host reported closed connection
            if (reply.Rst)
            {
                _dev.Close();
                throw new Exception("CLOSED");
            }
            //Remote host reported opened connection
            if (reply.Ack)
            {
                tcp.Syn = false;
                tcp.Rst = true;
                tcp.WindowSize = 0;
                tcp.ipv4.ComputeIPChecksum();
                tcp.ComputeTCPChecksum();
                Console.Write("Sending RST packet: " + tcp + "...");
                _dev.SendPacket(tcp);
                Console.WriteLine("RST Packet sent.");
                _dev.Close();
            }

            return true;
        }
Beispiel #29
0
        public static void Main(string[] args)
        {
            // Print SharpPcap version
            string ver = SharpPcap.Version.VersionString;
            Console.WriteLine("SharpPcap {0}, Example2.ArpResolve.cs\n", ver);

            // Retrieve the device list
            var devices = CaptureDeviceList.Instance;

            // If no devices were found print an error
            if(devices.Count < 1)
            {
                Console.WriteLine("No devices were found on this machine");
                return;
            }

            Console.WriteLine("The following devices are available on this machine:");
            Console.WriteLine("----------------------------------------------------");
            Console.WriteLine();

            int i = 0;

            // Print out the available devices
            foreach(var dev in devices)
            {
                Console.WriteLine("{0}) {1} {2}", i, dev.Name, dev.Description);
                i++;
            }

            Console.WriteLine();
            Console.Write("-- Please choose a device for sending the ARP request: ");
            i = int.Parse( Console.ReadLine() );

            string device = devices[i].Name;

            System.Net.IPAddress ip;

            // loop until a valid ip address is parsed
            while(true)
            {
                Console.Write("-- Please enter IP address to be resolved by ARP: ");
                if(System.Net.IPAddress.TryParse(Console.ReadLine(), out ip))
                    break;
                Console.WriteLine("Bad IP address format, please try again");
            }

            // Create a new ARP resolver
            ARP arper = new ARP(device);

            // print the resolved address or indicate that none was found
            var resolvedMacAddress = arper.Resolve(ip);
            if(resolvedMacAddress == null)
            {
                Console.WriteLine("Timeout, no mac address found for ip of " + ip);
            } else
            {
                Console.WriteLine(ip + " is at: " + arper.Resolve(ip));
            }
        }
Beispiel #30
0
        //发送ARP广播,返回192.168局域网中其他计算机的ARP相应数据包
        public static ArrayList ARPBroadcast(LivePcapDevice device)
        {
            ArrayList       tmpArrayList = new ArrayList();
            PhysicalAddress localMAC     = device.Interface.MacAddress;
            //这是我们伪造的一个IP
            IPAddress srcIP     = IPAddress.Parse("192.168.3.3");
            String    arpFilter = "arp and ether dst " + localMAC.ToString();

            //open the device with 20ms timeout
            device.Open(DeviceMode.Normal, 20);
            device.Filter = arpFilter;
            IPAddress destIP;

            SharpPcap.ARP tmpArp = new ARP();
            //发送65535个数据包耗时30秒,这30秒内到达的数据包由网卡缓存
            for (int i = 0; i < 256; i++)
            {
                for (int j = 0; j < 256; j++)
                {
                    destIP = IPAddress.Parse("192.168." + i.ToString() + "." + j.ToString());
                    //request是Packet类型
                    var request = tmpArp.BuildRequest(destIP, localMAC, srcIP);
                    //发送数据包到网络中
                    device.SendPacket(request);
                }
            }
            DateTime StartTime = DateTime.Now;
            DateTime endTime   = StartTime.AddSeconds(5);

            PacketDotNet.ARPPacket arpPacket = null;
            //接收5秒钟数据包,然后闪人
            while (DateTime.Now <= endTime)
            {
                var reply = device.GetNextPacket();
                if (reply == null)
                {
                    continue;
                }
                var packet = PacketDotNet.Packet.ParsePacket(reply);
                arpPacket = PacketDotNet.ARPPacket.GetEncapsulated(packet);
                if (arpPacket == null)
                {
                    continue;
                }
                else
                {
                    //exists判断是否ARP回应包存在重复
                    bool exists = false;
                    foreach (Object obj in tmpArrayList)
                    {
                        ARPPacket tmp = (ARPPacket)obj;
                        if (arpPacket.SenderHardwareAddress == tmp.SenderHardwareAddress)
                        {
                            exists = true;
                            break;
                        }
                    }
                    if (exists == false)
                    {
                        tmpArrayList.Add(arpPacket);
                    }
                }
            }
            device.Close();
            return(tmpArrayList);
        }
        public ScanMessage Connect(IPEndPoint ipEndPoint)
        {
            // SYN packet creation

            //MAC address of gateway is provided by arp protocol
            ARP arper = new ARP(device.Name);
            arper.LocalIP = device.Interface.Addresses[0].Addr.ipAddress;
            arper.LocalMAC = device.Interface.MacAddress;
            PhysicalAddress gatewayHwAddress = arper.Resolve(gatewayAddress);

            EthernetPacket ethernetHeader = new EthernetPacket(
                device.Interface.MacAddress,
                gatewayHwAddress,
                EthernetPacketType.IPv4,
                null);

            byte[] content = new byte[
                EthernetFields_Fields.ETH_HEADER_LEN +
                IPv4Fields_Fields.IP_HEADER_LEN +
                TCPFields_Fields.TCP_HEADER_LEN];

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

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

            // IP fields
            ipv4Packet.Version = 4;
            ipv4Packet.IPHeaderLength = IPv4Fields_Fields.IP_HEADER_LEN;
            ipv4Packet.IPTotalLength = content.Length - EthernetFields_Fields.ETH_HEADER_LEN;
            ipv4Packet.Id = 100;
            ipv4Packet.TimeToLive = 20;
            ipv4Packet.IPProtocol = IPProtocol.IPProtocolType.TCP;
            ipv4Packet.SourceAddress = device.Interface.Addresses[0].Addr.ipAddress;
            ipv4Packet.DestinationAddress = ipEndPoint.Address;

            ipv4Packet.ComputeIPChecksum(true);

            TCPPacket tcpPacket = new TCPPacket(
                EthernetFields_Fields.ETH_HEADER_LEN,
                content);

            // TCP fields
            tcpPacket.SourcePort = 2222;
            tcpPacket.DestinationPort = ipEndPoint.Port;
            tcpPacket.SequenceNumber = 1000;
            tcpPacket.AcknowledgmentNumber = 1000;
            tcpPacket.Syn = true;
            tcpPacket.TCPHeaderLength = TCPFields_Fields.TCP_HEADER_LEN;
            tcpPacket.WindowSize = 555;

            // Calculate checksum
            tcpPacket.ComputeTCPChecksum(true);

            try
            {
                device.Open(false, 20);

                device.SetFilter(String.Format("ip src {0} and tcp src port {1} and tcp dst port {2}",
                    tcpPacket.DestinationAddress,
                    tcpPacket.DestinationPort,
                    tcpPacket.SourcePort));

                // Send the packet
                device.SendPacket(tcpPacket);

                TCPPacket replyPacket = null;
                bool replyReceived = false;

                Stopwatch watch = new Stopwatch();
                watch.Start();

                // Condition including timeout check.
                while (watch.ElapsedMilliseconds < timeout && replyReceived != true)
                {
                    if ((replyPacket = (TCPPacket)device.GetNextPacket()) != null)
                    {
                        replyReceived = true;
                    }
                }

                if (!replyReceived) // A reply hasn't been received
                {
                    return ScanMessage.Timeout;
                }
                else if (replyPacket.Rst) // Remote host reset the connection
                {
                    return ScanMessage.PortClosed;
                }
                else if (replyPacket.Ack) // Remote host replied with a TCP packet
                {
                    tcpPacket.Syn = false;
                    tcpPacket.Rst = true;
                    tcpPacket.WindowSize = 0;
                    tcpPacket.ComputeTCPChecksum(true);
                    device.SendPacket(tcpPacket);

                    return ScanMessage.PortOpened;
                }
                else
                {
                    return ScanMessage.Unknown;
                }
            }
            catch (Exception)
            {
                return ScanMessage.Unknown;
            }
            finally
            {
                device.Close();
            }
        }
Beispiel #32
0
        public static void Main(string[] args)
        {
            // Print SharpPcap version
            string ver = SharpPcap.Version.VersionString;

            Console.WriteLine("SharpPcap {0}, Example2.ArpResolve.cs\n", ver);

            // Retrieve the device list
            var devices = LibPcapLiveDeviceList.Instance;

            // If no devices were found print an error
            if (devices.Count < 1)
            {
                Console.WriteLine("No devices were found on this machine");
                return;
            }

            Console.WriteLine("The following devices are available on this machine:");
            Console.WriteLine("----------------------------------------------------");
            Console.WriteLine();

            int i = 0;

            // Print out the available devices
            foreach (var dev in devices)
            {
                Console.WriteLine("{0}) {1} {2}", i, dev.Name, dev.Description);
                i++;
            }

            Console.WriteLine();
            Console.Write("-- Please choose a device for sending the ARP request: ");
            i = int.Parse(Console.ReadLine());

            var device = devices[i];

            System.Net.IPAddress ip;

            // loop until a valid ip address is parsed
            while (true)
            {
                Console.Write("-- Please enter IP address to be resolved by ARP: ");
                if (System.Net.IPAddress.TryParse(Console.ReadLine(), out ip))
                {
                    break;
                }
                Console.WriteLine("Bad IP address format, please try again");
            }

            // Create a new ARP resolver
            ARP arper = new ARP(device);

            // print the resolved address or indicate that none was found
            var resolvedMacAddress = arper.Resolve(ip);

            if (resolvedMacAddress == null)
            {
                Console.WriteLine("Timeout, no mac address found for ip of " + ip);
            }
            else
            {
                Console.WriteLine(ip + " is at: " + arper.Resolve(ip));
            }
        }
Beispiel #33
0
        public bool connect(IPEndPoint ipEnd, int port)
        {
            int lLen = EthernetFields_Fields.ETH_HEADER_LEN;

            //SYN packet creation
            #region Various Initializations
            ARP arper = new ARP();
            var bytes = new byte[54];
            var tcp   = new TCPPacket(lLen, bytes, true)
            {
                IPVersion = IPPacket.IPVersions.IPv4
            };
            #endregion

            #region Ethernet Fields
            tcp.SourceHwAddress = _dev.Interface.MacAddress;
            arper.DeviceName    = _dev.Name;
            arper.LocalIP       = _dev.Interface.Addresses[1].Addr.ipAddress;
            arper.LocalMAC      = _dev.Interface.MacAddress;
            //MAC address of gateway is provided by arp protocol
            tcp.DestinationHwAddress = arper.Resolve(_gatewayAddr, _dev.Name);
            tcp.EthernetProtocol     = EthernetPacket.EtherType.IP;
            #endregion

            #region IP Fields

            tcp.DestinationAddress  = ipEnd.Address;
            tcp.SourceAddress       = _dev.Interface.Addresses[1].Addr.ipAddress;
            tcp.IPProtocol          = IPProtocol.IPProtocolType.TCP;
            tcp.TimeToLive          = 20;
            tcp.ipv4.Id             = 100;
            tcp.ipv4.IPTotalLength  = bytes.Length - lLen;
            tcp.ipv4.IPHeaderLength = IPv4Fields_Fields.IP_HEADER_LEN;
            #endregion

            #region TCP Fields
            tcp.SourcePort      = 2222;
            tcp.DestinationPort = port;
            tcp.Syn             = true;
            tcp.WindowSize      = 555;
            tcp.SequenceNumber  = 0;
            tcp.TCPHeaderLength = TCPFields_Fields.TCP_HEADER_LEN;
            #endregion

            //Headers checksum calculations
            tcp.ipv4.ComputeIPChecksum();
            tcp.ComputeTCPChecksum();

            _dev.Open(false, 20);
            _dev.SetFilter("ip src " + tcp.DestinationAddress + " and tcp src port " + tcp.DestinationPort + " and tcp dst port " + tcp.SourcePort);

            //Send the packet
            Console.Write("Sending SYN packet: " + tcp + "...");
            _dev.SendPacket(tcp);
            Console.WriteLine("SYN Packet sent.");
            TCPPacket reply    = null;
            var       watch    = new Stopwatch();
            bool      received = false;
            watch.Start();
            //Condition including timeout check.
            while (watch.ElapsedMilliseconds < _timeout && received != true)
            {
                if ((reply = (TCPPacket)_dev.GetNextPacket()) != null)
                {
                    Console.WriteLine("SYN ACK Reply received: " + reply);
                    received = true;
                }
            }
            //A reply hasn't returned
            if (!received)
            {
                _dev.Close();
                throw new Exception("TIME_OUT");
            }
            //Remote host reported closed connection
            if (reply.Rst)
            {
                _dev.Close();
                throw new Exception("CLOSED");
            }
            //Remote host reported opened connection
            if (reply.Ack)
            {
                tcp.Syn        = false;
                tcp.Rst        = true;
                tcp.WindowSize = 0;
                tcp.ipv4.ComputeIPChecksum();
                tcp.ComputeTCPChecksum();
                Console.Write("Sending RST packet: " + tcp + "...");
                _dev.SendPacket(tcp);
                Console.WriteLine("RST Packet sent.");
                _dev.Close();
            }

            return(true);
        }
Beispiel #34
0
        internal static void ARPCache_Update(ARP.ARPReply_EthernetIPv4 arp_reply)
        {
            ensureQueueExists();
            //foreach (BufferEntry entry in queue)
            for (int e = 0; e < queue.Count; e++)
            {
                BufferEntry entry = queue[e];
                if (entry.Status == BufferEntry.EntryStatus.ARP_SENT)
                {
                    if (entry.Packet.DestinationIP.CompareTo(arp_reply.SenderIP) == 0)
                    {
                        entry.Packet.DestinationMAC = arp_reply.SenderMAC;

                        entry.Status = BufferEntry.EntryStatus.JUST_SEND;
                    }
                }
                else if (entry.Status == BufferEntry.EntryStatus.ROUTE_ARP_SENT)
                {
                    if (entry.nextHop.CompareTo(arp_reply.SenderIP) == 0)
                    {
                        entry.Packet.DestinationMAC = arp_reply.SenderMAC;

                        entry.Status = BufferEntry.EntryStatus.JUST_SEND;
                    }
                }
            }
        }