/// <summary> /// Execute a process on a remote system using the WMI Win32_Process.Create method. /// </summary> /// <param name="ComputerNames">ComputerNames of remote systems to execute process.</param> /// <param name="Command">Command to execute on remote system.</param> /// <param name="Username">Username to authenticate as to the remote system.</param> /// <param name="Password">Password to authenticate the user.</param> /// <returns>Bool. True if execution succeeds, false otherwise.</returns> public static SharpSploitResultList <WmiExecuteResult> WMIExecute(List <string> ComputerNames, string Command, string Username, string Password) { SharpSploitResultList <WmiExecuteResult> results = new SharpSploitResultList <WmiExecuteResult>(); results.AddRange(ComputerNames.Select(CN => WMIExecute(CN, Command, Username, Password))); return(results); }
/// <summary> /// Gets a directory listing of a directory. /// </summary> /// <param name="Path">The path of the directory to get a listing of.</param> /// <returns>SharpSploitResultList of FileSystemEntryResults.</returns> public static SharpSploitResultList <FileSystemEntryResult> GetDirectoryListing(string Path) { SharpSploitResultList <FileSystemEntryResult> results = new SharpSploitResultList <FileSystemEntryResult>(); foreach (string dir in Directory.GetDirectories(Path)) { DirectoryInfo dirInfo = new DirectoryInfo(dir); results.Add(new FileSystemEntryResult { Name = dirInfo.FullName, Length = 0, CreationTimeUtc = dirInfo.CreationTimeUtc, LastAccessTimeUtc = dirInfo.LastAccessTimeUtc, LastWriteTimeUtc = dirInfo.LastWriteTimeUtc }); } foreach (string file in Directory.GetFiles(Path)) { FileInfo fileInfo = new FileInfo(file); results.Add(new FileSystemEntryResult { Name = fileInfo.FullName, Length = fileInfo.Length, CreationTimeUtc = fileInfo.CreationTimeUtc, LastAccessTimeUtc = fileInfo.LastAccessTimeUtc, LastWriteTimeUtc = fileInfo.LastWriteTimeUtc }); } return(results); }
public override void Run(Dictionary <String, Parameter> RunParams) { List <string> targets = Proccessing.GetTargets(RunParams); if (targets.Count > 0) { SharpSploitResultList <Network.PortScanResult> scan = Network.PortScan(targets, 445, true); foreach (Network.PortScanResult scanResult in scan) { if (scanResult.IsOpen) { ServiceController serviceController = new ServiceController("Spooler", scanResult.ComputerName); try { serviceController.ServiceHandle.Close(); Printing.Success($"Admin access to {scanResult.ComputerName}"); } catch { Printing.Error($"No access to {scanResult.ComputerName}"); } } else { Printing.Error($"Port {scanResult.Port} is not open on {scanResult.ComputerName}"); } } } else { Printing.Error("Need to specify a ComputerName or IPAddress"); } }
public void TestPortScanCidrThreaded() { List <string> hosts = new List <string> { "127.0.0.1", "8.8.8.8/24" }; List <int> ports = new List <int> { 80, 443, 445 }; SharpSploitResultList <Network.PortScanResult> results1 = Network.PortScan(hosts, ports, true, 8000, 120); SharpSploitResultList <Network.PortScanResult> results2 = Network.PortScan(hosts, ports, true, 10000, 1); Assert.IsNotNull(results1); Assert.IsNotNull(results2); Assert.AreEqual(results1.Count, results2.Count); Assert.AreEqual(results1.Where(R => R.IsOpen).Count(), results2.Where(R => R.IsOpen).Count()); Assert.AreEqual(String.Join(",", results1.Select(R => R.ComputerName).OrderBy(C => C).ToArray()), String.Join(",", results2.Select(R => R.ComputerName).OrderBy(C => C).ToArray())); results1.AddRange(results2); foreach (Network.PortScanResult result in results1) { Assert.IsNotNull(result); Assert.AreNotEqual(result.ComputerName, ""); Assert.IsInstanceOfType(result.ComputerName, typeof(string)); Assert.IsInstanceOfType(result.IsOpen, typeof(bool)); } }
public void TestPing() { SharpSploitResultList <Network.PingResult> results = Network.Ping("127.0.0.1"); Assert.IsNotNull(results); Assert.AreEqual(results.Count, 1); Assert.AreEqual(results[0].ComputerName, "127.0.0.1"); Assert.IsTrue(results[0].IsUp); }
public void TestDumpDns() { SharpSploitResultList <Dns.DnsResult> hosts = Dns.DumpDns(System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain().FindDomainController().Name); Assert.IsTrue(hosts.Count > 0); foreach (Dns.DnsResult host in hosts) { Assert.IsTrue(!string.IsNullOrEmpty(host.IP) || host.Tombstoned == true); } }
public void TestGetDirectoryListing() { SharpSploitResultList <Host.FileSystemEntryResult> results = Host.GetDirectoryListing(); Assert.IsNotNull(results); foreach (Host.FileSystemEntryResult result in results) { Assert.IsNotNull(result); Assert.AreNotEqual(result.Name, ""); } }
/// <summary> /// Gets a list of running processes on the system. /// </summary> /// <returns>List of ProcessResults.</returns> public static SharpSploitResultList <ProcessResult> GetProcessList() { Process[] processes = Process.GetProcesses(); SharpSploitResultList <ProcessResult> results = new SharpSploitResultList <ProcessResult>(); foreach (Process process in processes) { results.Add(new ProcessResult(process.Id, 0, process.ProcessName)); } return(results); }
public void TestGetDrives() { SharpSploitResultList <Host.DriveInfoResult> results = Host.GetDrives(); Assert.IsNotNull(results); Assert.IsTrue(results.Count > 0); foreach (Host.DriveInfoResult result in results) { Assert.IsNotNull(result); Assert.AreNotEqual(result.Name, ""); } }
public void TestPingNullOrEmpty() { List <string> hosts1 = new List <string> { }; List <string> hosts2 = new List <string> { "" }; List <string> hosts3 = new List <string> { "", "" }; List <string> hosts4 = new List <string> { "123", "a", "1.2.3", "300.1.1.1", "1921.121.1.1/28" }; List <string> hosts5 = null; List <string> hosts6 = new List <string> { null }; List <string> hosts7 = new List <string> { null, null, null, null, "127.0.0.1" }; SharpSploitResultList <Network.PingResult> results1 = Network.Ping(hosts1); SharpSploitResultList <Network.PingResult> results2 = Network.Ping(hosts2); SharpSploitResultList <Network.PingResult> results3 = Network.Ping(hosts3); SharpSploitResultList <Network.PingResult> results4 = Network.Ping(hosts4); try { SharpSploitResultList <Network.PingResult> results5 = Network.Ping(hosts5); Assert.Fail(); } catch (NullReferenceException) { } SharpSploitResultList <Network.PingResult> results6 = Network.Ping(hosts6); SharpSploitResultList <Network.PingResult> results7 = Network.Ping(hosts7); Assert.IsNotNull(results1); Assert.IsNotNull(results2); Assert.IsNotNull(results3); Assert.IsNotNull(results4); Assert.IsNotNull(results6); Assert.IsNotNull(results7); Assert.AreEqual(0, results1.Count); Assert.AreEqual(0, results2.Count); Assert.AreEqual(0, results3.Count); Assert.AreEqual(0, results4.Count); Assert.AreEqual(0, results6.Count); Assert.AreEqual(1, results7.Count); Assert.AreEqual("127.0.0.1", results7[0].ComputerName); Assert.IsTrue(results7[0].IsUp); }
public void TestChangeCurrentDirectory() { SharpSploitResultList <Host.FileSystemEntryResult> results1 = Host.GetDirectoryListing(); string dir1 = Host.GetCurrentDirectory(); Host.ChangeCurrentDirectory(".."); string dir2 = Host.GetCurrentDirectory(); Assert.AreNotEqual(dir1, dir2); SharpSploitResultList <Host.FileSystemEntryResult> results2 = Host.GetDirectoryListing(); Assert.AreNotEqual(results1, results2); }
public void TestPortScan() { List <int> ports = new List <int> { 80, 443, 445 }; SharpSploitResultList <Network.PortScanResult> results = Network.PortScan("127.0.0.1", ports); Assert.IsNotNull(results); Assert.AreEqual(1, results.Count); Assert.AreEqual("127.0.0.1", results[0].ComputerName); Assert.AreEqual(445, results[0].Port); Assert.IsTrue(results[0].IsOpen); }
public void TestChangeCurrentDirectoryNull() { SharpSploitResultList <Host.FileSystemEntryResult> results1 = Host.GetDirectoryListing(); string dir1 = Host.GetCurrentDirectory(); Host.ChangeCurrentDirectory(null); string dir2 = Host.GetCurrentDirectory(); Assert.AreEqual(dir1, dir2); SharpSploitResultList <Host.FileSystemEntryResult> results2 = Host.GetDirectoryListing(); Assert.AreEqual(results1.FormatList(), results2.FormatList()); }
/// <summary> /// Gets a list of running processes on the system. /// </summary> /// <returns>List of ProcessResults.</returns> public static SharpSploitResultList <ProcessResult> GetProcessList() { var processorArchitecture = GetArchitecture(); Process[] processes = Process.GetProcesses().OrderBy(P => P.Id).ToArray(); SharpSploitResultList <ProcessResult> results = new SharpSploitResultList <ProcessResult>(); foreach (Process process in processes) { int processId = process.Id; int parentProcessId = GetParentProcess(process); string processName = process.ProcessName; string processPath = string.Empty; int sessionId = process.SessionId; string processOwner = GetProcessOwner(process); Win32.Kernel32.Platform processArch = Win32.Kernel32.Platform.Unknown; if (parentProcessId != 0) { try { processPath = process.MainModule.FileName; } catch (System.ComponentModel.Win32Exception) { } } if (processorArchitecture == Win32.Kernel32.Platform.x64) { processArch = IsWow64(process) ? Win32.Kernel32.Platform.x86 : Win32.Kernel32.Platform.x64; } else if (processorArchitecture == Win32.Kernel32.Platform.x86) { processArch = Win32.Kernel32.Platform.x86; } else if (processorArchitecture == Win32.Kernel32.Platform.IA64) { processArch = Win32.Kernel32.Platform.x86; } results.Add(new ProcessResult { Pid = processId, Ppid = parentProcessId, Name = processName, Path = processPath, SessionID = sessionId, Owner = processOwner, Architecture = processArch }); } return(results); }
/// <summary> /// Gets a directory listing of the current working directory. /// </summary> /// <returns>List of FileSystemEntryResults.</returns> public static SharpSploitResultList <FileSystemEntryResult> GetDirectoryListing() { SharpSploitResultList <FileSystemEntryResult> results = new SharpSploitResultList <FileSystemEntryResult>(); foreach (string dir in Directory.GetDirectories(GetCurrentDirectory())) { results.Add(new FileSystemEntryResult(dir)); } foreach (string file in Directory.GetFiles(GetCurrentDirectory())) { results.Add(new FileSystemEntryResult(file)); } return(results); }
public void TestProcessList() { SharpSploitResultList <Host.ProcessResult> results = Host.GetProcessList(); Assert.IsNotNull(results); Assert.IsTrue(results.Count > 10); foreach (Host.ProcessResult result in results) { Assert.IsNotNull(result); Assert.AreNotEqual(result.Name, ""); Assert.IsInstanceOfType(result.Pid, typeof(int)); Assert.IsInstanceOfType(result.Ppid, typeof(int)); } }
/// <summary> /// Gets a list of running processes on the system. /// </summary> /// <returns>List of ProcessResults.</returns> public static SharpSploitResultList <ProcessResult> GetProcessList() { Process[] processes = Process.GetProcesses(); SharpSploitResultList <ProcessResult> results = new SharpSploitResultList <ProcessResult>(); foreach (Process process in processes) { var search = new ManagementObjectSearcher("root\\CIMV2", string.Format("SELECT ParentProcessId FROM Win32_Process WHERE ProcessId = {0}", process.Id)); var pidresult = search.Get().GetEnumerator(); pidresult.MoveNext(); var parentId = (uint)pidresult.Current["ParentProcessId"]; results.Add(new ProcessResult(process.Id, Convert.ToInt32(parentId), process.ProcessName)); } return(results); }
/// <summary> /// Gets a list of active Reverse Port Forwards. /// </summary> /// <returns>A SharpSploitResultList of ReversePortFwdResult</returns> /// <author>Daniel Duggan (@_RastaMouse)</author> public static SharpSploitResultList <ReversePortFwdResult> GetReversePortForwards() { SharpSploitResultList <ReversePortFwdResult> reversePortForwards = new SharpSploitResultList <ReversePortFwdResult>(); foreach (ReversePortForward rportfwd in _reversePortForwards) { reversePortForwards.Add(new ReversePortFwdResult { BindAddresses = rportfwd.BindAddress.ToString(), BindPort = rportfwd.BindPort, ForwardAddress = rportfwd.ForwardAddress.ToString(), ForwardPort = rportfwd.ForwardPort }); } return(reversePortForwards); }
private static SharpSploitResultList <DaclResult> GetDaclResults(FileSystemSecurity SecurityEntry) { SharpSploitResultList <DaclResult> results = new SharpSploitResultList <DaclResult>(); foreach (FileSystemAccessRule ace in SecurityEntry.GetAccessRules(true, true, typeof(NTAccount))) { results.Add(new DaclResult { IdentityReference = ace.IdentityReference.Value, AccessControlType = ace.AccessControlType, FileSystemRights = ace.FileSystemRights, IsInherited = ace.IsInherited, InheritanceFlags = ace.InheritanceFlags, PropagationFlags = ace.PropagationFlags }); } return(results); }
public override CommandOutput Execute(Dictionary <string, string> Parameters = null) { CommandOutput output = new CommandOutput(); try { string computerName = Parameters["ComputerName"]; List <string> computerNames = new List <string>(); int timeout = 250; int threads = 25; if (computerName.Contains(",")) { computerNames = computerName.Split(',').ToList(); } else { computerNames.Add(computerName); } if (Parameters.ContainsKey("Timeout")) { timeout = Int32.Parse(Parameters["Timeout"]); } if (Parameters.ContainsKey("Threads")) { threads = Int32.Parse(Parameters["Threads"]); } SharpSploitResultList <Network.PingResult> results = Network.Ping(computerNames, timeout, threads); output.Message = JsonConvert.SerializeObject(results); output.Success = true; output.Complete = true; } catch (Exception e) { output.Complete = true; output.Success = false; output.Message = e.Message; } return(output); }
public void TestPingList() { List <string> hosts = new List <string> { "127.0.0.1", "8.8.8.8", "1.1.1.1", "google.com", "192.168.200.1" }; SharpSploitResultList <Network.PingResult> results = Network.Ping(hosts, 10000); Assert.IsNotNull(results); Assert.AreEqual(4, results.Count); Assert.AreEqual(4, results.Where(R => R.IsUp).ToList().Count); foreach (Network.PingResult result in results) { Assert.IsNotNull(result); Assert.AreNotEqual(result.ComputerName, ""); Assert.IsInstanceOfType(result.ComputerName, typeof(string)); Assert.IsInstanceOfType(result.IsUp, typeof(bool)); } }
/// <summary> /// Pings specified ComputerNames to identify live systems. /// </summary> /// <param name="ComputerNames">ComputerNames to ping.</param> /// <param name="Timeout">Timeout (in milliseconds) before a ComputerName is considered down.</param> /// <param name="Threads">Number of threads with which to ping simultaneously</param> /// <returns></returns> public static SharpSploitResultList <PingResult> Ping(IList <string> ComputerNames, int Timeout = 250, int Threads = 100) { IList <string> pingAddresses = Utilities.ConvertCidrToIPs(ComputerNames).Distinct().ToList(); SharpSploitResultList <PingResult> pingResults = new SharpSploitResultList <PingResult>(); using (CountdownEvent waiter = new CountdownEvent(pingAddresses.Count)) { object pingResultsLock = new object(); int runningThreads = 0; foreach (string ComputerName in pingAddresses) { Ping ping = new Ping(); PingResult pingResult = new PingResult(ComputerName, true); ping.PingCompleted += new PingCompletedEventHandler((sender, e) => { if (e.Reply != null && e.Reply.Status == IPStatus.Success) { lock (pingResultsLock) { pingResults.Add(pingResult); } } ((CountdownEvent)e.UserState).Signal(); }); while (runningThreads >= Threads) { waiter.WaitOne(); runningThreads--; } try { ping.SendAsync(ComputerName, Timeout, waiter); runningThreads++; } catch { } } waiter.Wait(Timeout * pingAddresses.Count); } return(pingResults); }
/// <summary> /// Get all services on a remote computer. /// </summary> /// <param name="ComputerName">The ComputerName of the remote machine.</param> /// <returns>A SharpSploitResultList of ServiceResults. NULL if none found.</returns> /// <author>Daniel Duggan (@_RastaMouse)</author> public static SharpSploitResultList <ServiceResult> GetServices(string ComputerName) { try { SharpSploitResultList <ServiceResult> results = new SharpSploitResultList <ServiceResult>(); IEnumerable <ServiceController> services = ServiceController.GetServices(ComputerName).OrderBy(S => S.ServiceName); foreach (ServiceController service in services) { results.Add(new ServiceResult { ServiceName = service.ServiceName, DisplayName = service.DisplayName, Status = service.Status, CanStop = service.CanStop }); service.Dispose(); } return(results); } catch (Win32Exception) { return(null); } catch (InvalidOperationException) { return(null); } }
public void TestPortScanList() { List <string> hosts = new List <string> { "127.0.0.1", "8.8.8.8", "1.1.1.1", "google.com", "192.168.200.1" }; List <int> ports = new List <int> { 80, 443, 445 }; SharpSploitResultList <Network.PortScanResult> results = Network.PortScan(hosts, ports, true, 1000, 300); Assert.IsNotNull(results); Assert.AreEqual(4, results.Count); Assert.AreEqual(4, results.Where(R => R.IsOpen).Count()); foreach (Network.PortScanResult result in results) { Assert.IsNotNull(result); Assert.IsInstanceOfType(result.ComputerName, typeof(string)); Assert.AreNotEqual("", result.ComputerName); Assert.IsTrue(ports.Contains(result.Port)); } }
/// <summary> /// Gets information about current drives. /// </summary> /// <returns>SharpSploitResultList of DriveInfoResults</returns> public static SharpSploitResultList <DriveInfoResult> GetDrives() { SharpSploitResultList <DriveInfoResult> results = new SharpSploitResultList <DriveInfoResult>(); DriveInfo[] drives = DriveInfo.GetDrives(); foreach (DriveInfo drive in drives) { DriveInfoResult info = new DriveInfoResult { Name = drive.Name, Type = drive.DriveType }; if (drive.IsReady) { info.Label = drive.VolumeLabel; info.Format = drive.DriveFormat; info.Capacity = Utilities.ConvertFileLengthForDisplay(drive.TotalSize); info.FreeSpace = Utilities.ConvertFileLengthForDisplay(drive.AvailableFreeSpace); } results.Add(info); } return(results); }
/// <summary> /// Query specified domain controller via ldap and extrat hosts name list from dns, than perform a dns lookup to resolve ips. . /// </summary> /// <author>@b4rtik</author> /// <param name="DomainController">DomainController to query.</param> /// <returns>List of PortScanResults</returns> /// <remarks> /// based on /// Getting in the zone dumping active directory dns with adidnsdump /// https://dirkjanm.io/getting-in-the-zone-dumping-active-directory-dns-with-adidnsdump/ /// by @_dirkjan /// </remarks> public static SharpSploitResultList <DnsResult> DumpDns(string DomainController) { SharpSploitResultList <DnsResult> results = new SharpSploitResultList <DnsResult>(); try { string rootDn = "DC=DomainDnsZones"; string domain_local = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName; string domain_path = ""; foreach (string domain_path_r in domain_local.Split('.')) { domain_path += ",DC=" + domain_path_r; } rootDn += domain_path; DirectoryEntry rootEntry = new DirectoryEntry("LDAP://" + DomainController + "/" + rootDn); rootEntry.AuthenticationType = AuthenticationTypes.Delegation; DirectorySearcher searcher = new DirectorySearcher(rootEntry); //find domains var queryFormat = "(&(objectClass=DnsZone)(!(DC=*arpa))(!(DC=RootDNSServers)))"; searcher.Filter = queryFormat; searcher.SearchScope = SearchScope.Subtree; foreach (SearchResult result in searcher.FindAll()) { String domain = (result.Properties["DC"].Count > 0 ? result.Properties["DC"][0].ToString() : string.Empty); Console.WriteLine(); Console.WriteLine("Domain: {0}", domain); Console.WriteLine(); DirectoryEntry rootEntry_d = new DirectoryEntry("LDAP://" + DomainController + "/DC=" + result.Properties["DC"][0].ToString() + ",CN=microsoftdns," + rootDn); rootEntry_d.AuthenticationType = AuthenticationTypes.Delegation; DirectorySearcher searcher_h = new DirectorySearcher(rootEntry_d); //find hosts queryFormat = "(&(!(objectClass=DnsZone))(!(DC=@))(!(DC=*arpa))(!(DC=*DNSZones)))"; searcher_h.Filter = queryFormat; searcher_h.SearchScope = SearchScope.Subtree; foreach (SearchResult result_h in searcher_h.FindAll()) { String target = ""; if (result_h.Properties["DC"].Count > 0) { target = result_h.Properties["DC"][0].ToString(); } else { //Hidden entry String path = result_h.Path; target = (path.Substring(path.IndexOf("LDAP://" + DomainController + "/"), path.IndexOf(","))).Split('=')[1]; } DnsResult dnsentry = new DnsResult(DomainName: domain, ComputerName: target); if (!target.EndsWith(".")) { target += "." + domain; } bool tombstoned = result_h.Properties["dNSTombstoned"].Count > 0 ? (bool)result_h.Properties["dNSTombstoned"][0] : false; dnsentry.Tombstoned = tombstoned; if (!tombstoned) { try { IPHostEntry hostInfo = System.Net.Dns.GetHostEntry(target); foreach (IPAddress result_ip in hostInfo.AddressList) { dnsentry.IP = result_ip.ToString(); results.Add(dnsentry); } } catch (Exception) { } } else { results.Add(dnsentry); } } } } catch (Exception e) { Console.WriteLine("Error retriving data : {0}", e.Message); } return(results); }
public void TestPortScanNullOrEmpty() { List <string> hosts1 = new List <string> { }; List <string> hosts2 = new List <string> { "" }; List <string> hosts3 = new List <string> { "", "" }; List <string> hosts4 = new List <string> { "123", "a", "1.2.3", "300.1.1.1", "1921.121.1.1/28" }; List <string> hosts5 = null; List <string> hosts6 = new List <string> { null }; List <string> hosts7 = new List <string> { null, null, null, null, "127.0.0.1" }; List <int> ports1 = new List <int> { }; List <int> ports2 = new List <int> { 0 }; List <int> ports3 = new List <int> { 0, 0 }; List <int> ports4 = new List <int> { 12345678, -123, 0, 1, -1 }; List <int> ports5 = null; List <int> ports6 = new List <int> { 0 }; List <int> ports7 = new List <int> { 0, 0, 0, 0, 445 }; SharpSploitResultList <Network.PortScanResult> results1 = Network.PortScan(hosts1, ports1); SharpSploitResultList <Network.PortScanResult> results2 = Network.PortScan(hosts2, ports2); SharpSploitResultList <Network.PortScanResult> results3 = Network.PortScan(hosts3, ports3); SharpSploitResultList <Network.PortScanResult> results4 = Network.PortScan(hosts4, ports4); try { SharpSploitResultList <Network.PortScanResult> results5 = Network.PortScan(hosts5, ports5); Assert.Fail(); } catch (NullReferenceException) { } SharpSploitResultList <Network.PortScanResult> results6 = Network.PortScan(hosts6, ports6); SharpSploitResultList <Network.PortScanResult> results7 = Network.PortScan(hosts7, ports7); Assert.IsNotNull(results1); Assert.IsNotNull(results2); Assert.IsNotNull(results3); Assert.IsNotNull(results4); Assert.IsNotNull(results6); Assert.IsNotNull(results7); Assert.AreEqual(0, results1.Count); Assert.AreEqual(0, results2.Count); Assert.AreEqual(0, results3.Count); Assert.AreEqual(0, results4.Count); Assert.AreEqual(0, results6.Count); Assert.AreEqual(1, results7.Count); Assert.AreEqual("127.0.0.1", results7[0].ComputerName); Assert.IsTrue(results7[0].IsOpen); }
/// <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 SharpSploitResultList <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) { SharpSploitResultList <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) { waiter.WaitOne(Timeout); 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); } SharpSploitResultList <PortScanResult> results = new SharpSploitResultList <PortScanResult>(); results.AddRange(portScanResults); return(results); }
public override CommandOutput Execute(Dictionary <string, string> Parameters = null) { CommandOutput output = new CommandOutput(); try { string computerName = Parameters["ComputerName"]; string portsParam = Parameters["Port"]; List <string> portStrings = new List <string>(); List <string> computerNames = new List <string>(); List <int> ports = new List <int>(); bool ping = true; int timeout = 250; int threads = 100; if (computerName.Contains(",")) { computerNames = computerName.Split(',').ToList(); } else { computerNames.Add(computerName); } if (portsParam.Contains(",")) { portStrings = portsParam.Split(',').ToList(); } else { portStrings.Add(portsParam); } foreach (string portString in portStrings) { ports.Add(Int32.Parse(portString)); } if (Parameters.ContainsKey("Timeout")) { timeout = Int32.Parse(Parameters["Timeout"]); } if (Parameters.ContainsKey("Threads")) { threads = Int32.Parse(Parameters["Threads"]); } if (Parameters.ContainsKey("Ping")) { ping = Boolean.Parse(Parameters["Ping"]); } SharpSploitResultList <Network.PortScanResult> results = Network.PortScan(computerNames, ports, ping, timeout); output.Message = JsonConvert.SerializeObject(results); output.Success = true; output.Complete = true; } catch (Exception e) { output.Complete = true; output.Success = false; output.Message = e.Message; } return(output); }