Beispiel #1
0
        private void PortScanner_PortScanned(object sender, PortScannedArgs e)
        {
            PortInfo portInfo = PortInfo.Parse(e);

            Application.Current.Dispatcher.BeginInvoke(new Action(delegate()
            {
                PortScanResult.Add(portInfo);
            }));

            if (portInfo.Status == PortInfo.PortStatus.Open)
            {
                PortsOpen++;
            }
        }
Beispiel #2
0
        /// <summary>
        /// Begins the connection attempt via TCP.
        /// </summary>
        public void AttemptTcpConnectionToPort()
        {
            try
            {
                TcpClient client = new TcpClient {
                    ExclusiveAddressUse = false
                };
                client.Connect(EndPointName, Port);
                client.Close();

                PortScanResult?.Invoke(this, new PortScanResultEventArgs(EndPointName, Port, PortTypes.Tcp));
            }
            catch (SocketException)
            {
            }
        }
Beispiel #3
0
        public async Task <List <PortScanResult> > PortScan(PortScanInput portScanInput, IPortClient portClient)
        {
            var result           = new BlockingCollection <PortScanResult>();
            var mergedInput      = MergePortScanInput(portScanInput);
            var addressPortPairs = mergedInput.ChunkInto(portScanInput.Workers);

            await AsyncHelper.ForEach(addressPortPairs, async (addressPortPair, token) =>
            {
                foreach (var pair in addressPortPair)
                {
                    if (token.IsCancellationRequested)
                    {
                        break;
                    }

                    var portResultEntry = await IsPortOpen(new PortInput
                    {
                        Address = pair.Address,
                        Retries = portScanInput.Retries,
                        Timeout = portScanInput.Timeout,
                        Port    = pair.Port
                    }, portClient);

                    var addressResult = result.FirstOrDefault(r => r.Address == pair.Address);
                    if (addressResult == null)
                    {
                        var portResult = new PortScanResult
                        {
                            Address = pair.Address,
                        };
                        portResult.Results.Add(portResultEntry);
                        result.Add(portResult);
                    }
                    else
                    {
                        addressResult.Results.Add(portResultEntry);
                    }
                    OnPortScanned(pair.Address, portResultEntry);
                }
            }, portScanInput.CancellationToken);

            var finalResult = result.ToList();

            OnPortsScanComplete(finalResult);
            return(finalResult);
        }
Beispiel #4
0
        private async void StartScan()
        {
            DisplayStatusMessage = false;
            StatusMessage        = string.Empty;

            IsScanRunning = true;
            PreparingScan = true;

            // Measure the time
            StartTime = DateTime.Now;
            stopwatch.Start();
            dispatcherTimer.Tick    += DispatcherTimer_Tick;
            dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 100);
            dispatcherTimer.Start();
            EndTime = null;

            PortScanResult.Clear();
            PortsOpen = 0;

            cancellationTokenSource = new CancellationTokenSource();

            string[] hosts = Hostname.Split(';');

            List <Tuple <IPAddress, string> > hostData = new List <Tuple <IPAddress, string> >();

            for (int i = 0; i < hosts.Length; i++)
            {
                string host     = hosts[i].Trim();
                string hostname = string.Empty;
                IPAddress.TryParse(host, out IPAddress ipAddress);

                try
                {
                    // Resolve DNS
                    // Try to resolve the hostname
                    if (ipAddress == null)
                    {
                        IPHostEntry ipHostEntry = await Dns.GetHostEntryAsync(host);

                        foreach (IPAddress ip in ipHostEntry.AddressList)
                        {
                            if (ip.AddressFamily == AddressFamily.InterNetwork && SettingsManager.Current.PortScanner_ResolveHostnamePreferIPv4)
                            {
                                ipAddress = ip;
                                continue;
                            }
                            else if (ip.AddressFamily == AddressFamily.InterNetworkV6 && !SettingsManager.Current.PortScanner_ResolveHostnamePreferIPv4)
                            {
                                ipAddress = ip;
                                continue;
                            }
                        }

                        // Fallback --> If we could not resolve our prefered ip protocol
                        if (ipAddress == null)
                        {
                            foreach (IPAddress ip in ipHostEntry.AddressList)
                            {
                                ipAddress = ip;
                                continue;
                            }
                        }

                        hostname = host;
                    }
                    else
                    {
                        try
                        {
                            IPHostEntry ipHostEntry = await Dns.GetHostEntryAsync(ipAddress);

                            hostname = ipHostEntry.HostName;
                        }
                        catch { }
                    }
                }
                catch (SocketException) // This will catch DNS resolve errors
                {
                    if (!string.IsNullOrEmpty(StatusMessage))
                    {
                        StatusMessage += Environment.NewLine;
                    }

                    StatusMessage       += string.Format(Application.Current.Resources["String_CouldNotResolveHostnameFor"] as string, host);
                    DisplayStatusMessage = true;

                    continue;
                }

                hostData.Add(Tuple.Create(ipAddress, hostname));
            }

            if (hostData.Count == 0)
            {
                StatusMessage       += Environment.NewLine + Application.Current.Resources["String_NothingToDoCheckYourInput"] as string;
                DisplayStatusMessage = true;

                ScanFinished();

                return;
            }

            int[] ports = await PortRangeHelper.ConvertPortRangeToIntArrayAsync(Ports);

            try
            {
                PortsToScan  = ports.Length * hostData.Count;
                PortsScanned = 0;

                PreparingScan = false;

                HostnameHistory = new List <string>(HistoryListHelper.Modify(HostnameHistory, Hostname, SettingsManager.Current.Application_HistoryListEntries));
                PortsHistory    = new List <string>(HistoryListHelper.Modify(PortsHistory, Ports, SettingsManager.Current.Application_HistoryListEntries));

                PortScannerOptions portScannerOptions = new PortScannerOptions
                {
                    Threads    = SettingsManager.Current.PortScanner_Threads,
                    ShowClosed = SettingsManager.Current.PortScanner_ShowClosed,
                    Timeout    = SettingsManager.Current.PortScanner_Timeout
                };

                PortScanner portScanner = new PortScanner();
                portScanner.PortScanned     += PortScanner_PortScanned;
                portScanner.ScanComplete    += PortScanner_ScanComplete;
                portScanner.ProgressChanged += PortScanner_ProgressChanged;
                portScanner.UserHasCanceled += PortScanner_UserHasCanceled;

                portScanner.ScanAsync(hostData, ports, portScannerOptions, cancellationTokenSource.Token);
            }

            catch (Exception ex) // This will catch any exception
            {
                StatusMessage        = ex.Message;
                DisplayStatusMessage = true;

                ScanFinished();
            }
        }
Beispiel #5
0
        private async void StartScan()
        {
            DisplayStatusMessage = false;
            StatusMessage        = string.Empty;

            IsScanRunning = true;
            PreparingScan = true;

            // Measure the time
            StartTime = DateTime.Now;
            stopwatch.Start();
            dispatcherTimer.Tick    += DispatcherTimer_Tick;
            dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 100);
            dispatcherTimer.Start();
            EndTime = null;

            PortScanResult.Clear();
            PortsOpen = 0;

            // Change the tab title (not nice, but it works)
            Window window = Application.Current.Windows.OfType <Window>().FirstOrDefault(x => x.IsActive);

            if (window != null)
            {
                foreach (TabablzControl tabablzControl in VisualTreeHelper.FindVisualChildren <TabablzControl>(window))
                {
                    tabablzControl.Items.OfType <DragablzTabItem>().First(x => x.ID == _tabId).Header = Host;
                }
            }

            cancellationTokenSource = new CancellationTokenSource();

            string[] hosts = Host.Split(';');

            List <Tuple <IPAddress, string> > hostData = new List <Tuple <IPAddress, string> >();

            for (int i = 0; i < hosts.Length; i++)
            {
                string host     = hosts[i].Trim();
                string hostname = string.Empty;
                IPAddress.TryParse(host, out IPAddress ipAddress);

                try
                {
                    // Resolve DNS
                    // Try to resolve the hostname
                    if (ipAddress == null)
                    {
                        IPHostEntry ipHostEntry = await Dns.GetHostEntryAsync(host);

                        foreach (IPAddress ip in ipHostEntry.AddressList)
                        {
                            if (ip.AddressFamily == AddressFamily.InterNetwork && SettingsManager.Current.PortScanner_ResolveHostnamePreferIPv4)
                            {
                                ipAddress = ip;
                                continue;
                            }
                            else if (ip.AddressFamily == AddressFamily.InterNetworkV6 && !SettingsManager.Current.PortScanner_ResolveHostnamePreferIPv4)
                            {
                                ipAddress = ip;
                                continue;
                            }
                        }

                        // Fallback --> If we could not resolve our prefered ip protocol
                        if (ipAddress == null)
                        {
                            foreach (IPAddress ip in ipHostEntry.AddressList)
                            {
                                ipAddress = ip;
                                continue;
                            }
                        }

                        hostname = host;
                    }
                    else
                    {
                        try
                        {
                            IPHostEntry ipHostEntry = await Dns.GetHostEntryAsync(ipAddress);

                            hostname = ipHostEntry.HostName;
                        }
                        catch { }
                    }
                }
                catch (SocketException) // This will catch DNS resolve errors
                {
                    if (!string.IsNullOrEmpty(StatusMessage))
                    {
                        StatusMessage += Environment.NewLine;
                    }

                    StatusMessage       += string.Format(LocalizationManager.GetStringByKey("String_CouldNotResolveHostnameFor"), host);
                    DisplayStatusMessage = true;

                    continue;
                }

                hostData.Add(Tuple.Create(ipAddress, hostname));
            }

            if (hostData.Count == 0)
            {
                StatusMessage       += Environment.NewLine + LocalizationManager.GetStringByKey("String_NothingToDoCheckYourInput");
                DisplayStatusMessage = true;

                ScanFinished();

                return;
            }

            int[] ports = await PortRangeHelper.ConvertPortRangeToIntArrayAsync(Port);

            try
            {
                PortsToScan  = ports.Length * hostData.Count;
                PortsScanned = 0;

                PreparingScan = false;

                AddHostToHistory(Host);
                AddPortToHistory(Port);

                PortScannerOptions portScannerOptions = new PortScannerOptions
                {
                    Threads    = SettingsManager.Current.PortScanner_Threads,
                    ShowClosed = SettingsManager.Current.PortScanner_ShowClosed,
                    Timeout    = SettingsManager.Current.PortScanner_Timeout
                };

                PortScanner portScanner = new PortScanner();
                portScanner.PortScanned     += PortScanner_PortScanned;
                portScanner.ScanComplete    += PortScanner_ScanComplete;
                portScanner.ProgressChanged += PortScanner_ProgressChanged;
                portScanner.UserHasCanceled += PortScanner_UserHasCanceled;

                portScanner.ScanAsync(hostData, ports, portScannerOptions, cancellationTokenSource.Token);
            }

            catch (Exception ex) // This will catch any exception
            {
                StatusMessage        = ex.Message;
                DisplayStatusMessage = true;

                ScanFinished();
            }
        }
Beispiel #6
0
        /// <summary>
        /// Conducts a port scan of specified ComputerNames on specified ports and reports open ports.
        /// </summary>
        /// <param name="ComputerNames">ComputerNames to port scan.</param>
        /// <param name="Ports">Ports to scan.</param>
        /// <param name="Ping">Optional switch. If true, pings the ComputerNames to ensure each is up before port scanning.</param>
        /// <param name="Timeout">Timeout (in milliseconds) before a port is considered down.</param>
        /// <param name="Threads">Number of threads with which to portscan simultaneously</param>
        /// <returns>List of PortScanResults</returns>
        public static CoreSploitResultList <PortScanResult> PortScan(IList <string> ComputerNames, IList <int> Ports,
                                                                     bool Ping = true, int Timeout = 250, int Threads = 100)
        {
            IList <string> scanAddresses = Utilities.ConvertCidrToIPs(ComputerNames).Distinct().ToList();
            IList <int>    scanPorts     = Ports.Where(P => P > 1 && P < 65536).Distinct().ToList();

            if (Ping)
            {
                CoreSploitResultList <PingResult> pingResults = Network.Ping(scanAddresses, Timeout, Threads);
                scanAddresses = pingResults.Where(PR => PR.IsUp).Select(PR => PR.ComputerName).ToList();
            }

            IList <PortScanResult> portScanResults = new List <PortScanResult>();

            using (CountdownEvent waiter = new CountdownEvent(scanAddresses.Count * Ports.Count))
            {
                object portScanResultsLock = new object();
                int    runningThreads      = 0;
                foreach (string ComputerName in scanAddresses)
                {
                    foreach (int Port in scanPorts)
                    {
                        TcpClient client = null;
                        if (!Utilities.IsIP(ComputerName))
                        {
                            client = new TcpClient();
                        }
                        else
                        {
                            IPAddress.TryParse(ComputerName, out IPAddress address);
                            client = new TcpClient(address.AddressFamily);
                        }

                        PortScanResult portScanResult = new PortScanResult(ComputerName, Port, true);
                        while (runningThreads >= Threads)
                        {
#warning this may not work properly -scottie
                            waiter.Wait();
                            runningThreads--;
                        }

                        IAsyncResult asyncResult = client.BeginConnect(ComputerName, Port, new AsyncCallback((state) =>
                        {
                            try
                            {
                                client.EndConnect(state);
                                client.Close();
                            }
                            catch
                            {
                                portScanResult.IsOpen = false;
                            }

                            if (portScanResult.IsOpen)
                            {
                                lock (portScanResultsLock)
                                {
                                    portScanResults.Add(portScanResult);
                                }
                            }

                            ((CountdownEvent)state.AsyncState).Signal();
                        }), waiter);
                        runningThreads++;
                    }
                }

                waiter.Wait(Timeout * scanAddresses.Count * Ports.Count);
            }

            CoreSploitResultList <PortScanResult> results = new CoreSploitResultList <PortScanResult>();
            results.AddRange(portScanResults);

            return(results);
        }