diff --git a/winPEAS/winPEASexe/winPEAS/ApplicationInfo.cs b/winPEAS/winPEASexe/winPEAS/ApplicationInfo.cs index a1a1c49..f67ab94 100755 --- a/winPEAS/winPEASexe/winPEAS/ApplicationInfo.cs +++ b/winPEAS/winPEASexe/winPEAS/ApplicationInfo.cs @@ -9,6 +9,7 @@ using System.Text; using System.Text.RegularExpressions; using Microsoft.Win32; using Microsoft.Win32.TaskScheduler; +using winPEAS.Utils; namespace winPEAS { @@ -83,12 +84,12 @@ namespace winPEAS results.Concat(results2).ToDictionary(kvp => kvp.Key, kvp => kvp.Value); //Get from Uninstall - string[] subkeys = MyUtils.GetRegSubkeys("HKLM", @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"); + string[] subkeys = RegistryHelper.GetRegSubkeys("HKLM", @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"); if (subkeys != null) { foreach (string app in subkeys) { - string installLocation = MyUtils.GetRegValue("HKLM", String.Format(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{0}", app), "InstallLocation"); + string installLocation = RegistryHelper.GetRegValue("HKLM", String.Format(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{0}", app), "InstallLocation"); if (String.IsNullOrEmpty(installLocation)) continue; @@ -114,12 +115,12 @@ namespace winPEAS } } - subkeys = MyUtils.GetRegSubkeys("HKLM", @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"); + subkeys = RegistryHelper.GetRegSubkeys("HKLM", @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"); if (subkeys != null) { foreach (string app in subkeys) { - string installLocation = MyUtils.GetRegValue("HKLM", String.Format(@"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\{0}", app), "InstallLocation"); + string installLocation = RegistryHelper.GetRegValue("HKLM", String.Format(@"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\{0}", app), "InstallLocation"); if (String.IsNullOrEmpty(installLocation)) continue; @@ -241,7 +242,7 @@ namespace winPEAS //Add the keyvalues inside autorunLocationsKeys to autorunLocations foreach (List autorunLocationKey in autorunLocationsKeys) { - List subkeys = MyUtils.GetRegSubkeys(autorunLocationKey[0], autorunLocationKey[1]).ToList(); + List subkeys = RegistryHelper.GetRegSubkeys(autorunLocationKey[0], autorunLocationKey[1]).ToList(); foreach (String keyname in subkeys) { string clsid_name = keyname; @@ -259,7 +260,7 @@ namespace winPEAS //Read registry and get values foreach (List autorunLocation in autorunLocations) { - Dictionary settings = MyUtils.GetRegValues(autorunLocation[0], autorunLocation[1]); + Dictionary settings = RegistryHelper.GetRegValues(autorunLocation[0], autorunLocation[1]); if ((settings != null) && (settings.Count != 0)) { foreach (KeyValuePair kvp in settings) @@ -320,7 +321,7 @@ namespace winPEAS //Check the autoruns that depends on CLSIDs foreach (List autorunLocation in autorunLocationsKeysCLSIDs) { - List CLSIDs = MyUtils.GetRegSubkeys(autorunLocation[0], autorunLocation[1]).ToList(); + List CLSIDs = RegistryHelper.GetRegSubkeys(autorunLocation[0], autorunLocation[1]).ToList(); foreach (String clsid in CLSIDs) { string reg = autorunLocation[1] + "\\" + clsid; diff --git a/winPEAS/winPEASexe/winPEAS/Beaprint.cs b/winPEAS/winPEASexe/winPEAS/Beaprint.cs index f99f94f..d7a3d35 100755 --- a/winPEAS/winPEASexe/winPEAS/Beaprint.cs +++ b/winPEAS/winPEASexe/winPEAS/Beaprint.cs @@ -171,6 +171,12 @@ namespace winPEAS GrayPrint(" ================================================================================================="); System.Console.WriteLine(); } + + public static void PrintException(string message) + { + GrayPrint($" [X] Exception: {message}"); + } + public static void AnsiPrint(string to_print, Dictionary ansi_colors_regexp) { if (to_print.Trim().Length > 0) diff --git a/winPEAS/winPEASexe/winPEAS/FastSearch/FileSearcher/FileSearcher.cs b/winPEAS/winPEASexe/winPEAS/FastSearch/FileSearcher/FileSearcher.cs index e35b851..14e607e 100644 --- a/winPEAS/winPEASexe/winPEAS/FastSearch/FileSearcher/FileSearcher.cs +++ b/winPEAS/winPEASexe/winPEAS/FastSearch/FileSearcher/FileSearcher.cs @@ -74,15 +74,15 @@ namespace FastSearchLibrary return new List(); } - catch (UnauthorizedAccessException ex) + catch (UnauthorizedAccessException) { return new List(); } - catch (PathTooLongException ex) + catch (PathTooLongException) { return new List(); } - catch (DirectoryNotFoundException ex) + catch (DirectoryNotFoundException) { return new List(); } @@ -90,7 +90,7 @@ namespace FastSearchLibrary return GetStartDirectories(directories[0].FullName, files, pattern); } - static public List GetFiles(string folder, string pattern = "*") + public static List GetFiles(string folder, string pattern = "*") { DirectoryInfo dirInfo; DirectoryInfo[] directories; @@ -102,15 +102,15 @@ namespace FastSearchLibrary if (directories.Length == 0) return new List(dirInfo.GetFiles(pattern)); } - catch (UnauthorizedAccessException ex) + catch (UnauthorizedAccessException) { return new List(); } - catch (PathTooLongException ex) + catch (PathTooLongException) { return new List(); } - catch (DirectoryNotFoundException ex) + catch (DirectoryNotFoundException) { return new List(); } @@ -126,13 +126,13 @@ namespace FastSearchLibrary { result.AddRange(dirInfo.GetFiles(pattern)); } - catch (UnauthorizedAccessException ex) + catch (UnauthorizedAccessException) { } - catch (PathTooLongException ex) + catch (PathTooLongException) { } - catch (DirectoryNotFoundException ex) + catch (DirectoryNotFoundException) { } diff --git a/winPEAS/winPEASexe/winPEAS/InterestingFiles.cs b/winPEAS/winPEASexe/winPEAS/InterestingFiles.cs index 38cb01c..0da067c 100755 --- a/winPEAS/winPEASexe/winPEAS/InterestingFiles.cs +++ b/winPEAS/winPEASexe/winPEAS/InterestingFiles.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.IO; +using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Cryptography; @@ -9,41 +10,36 @@ using System.Xml; namespace winPEAS { - class InterestingFiles - { - private InterestingFiles() {} + static class InterestingFiles + { public static List GetUnattendedInstallFiles() - { //From SharpUP - List results = new List(); + { + //From SharpUP + var results = new List(); try { - string windir = System.Environment.GetEnvironmentVariable("windir"); - string[] SearchLocations = + var winDir = System.Environment.GetEnvironmentVariable("windir"); + string[] searchLocations = { - String.Format("{0}\\sysprep\\sysprep.xml", windir), - String.Format("{0}\\sysprep\\sysprep.inf", windir), - String.Format("{0}\\sysprep.inf", windir), - String.Format("{0}\\Panther\\Unattended.xml", windir), - String.Format("{0}\\Panther\\Unattend.xml", windir), - String.Format("{0}\\Panther\\Unattend\\Unattend.xml", windir), - String.Format("{0}\\Panther\\Unattend\\Unattended.xml", windir), - String.Format("{0}\\System32\\Sysprep\\unattend.xml", windir), - String.Format("{0}\\System32\\Sysprep\\Panther\\unattend.xml", windir), - String.Format("{0}\\..\\unattend.xml", windir), - String.Format("{0}\\..\\unattend.inf", windir), + $"{winDir}\\sysprep\\sysprep.xml", + $"{winDir}\\sysprep\\sysprep.inf", + $"{winDir}\\sysprep.inf", + $"{winDir}\\Panther\\Unattended.xml", + $"{winDir}\\Panther\\Unattend.xml", + $"{winDir}\\Panther\\Unattend\\Unattend.xml", + $"{winDir}\\Panther\\Unattend\\Unattended.xml", + $"{winDir}\\System32\\Sysprep\\unattend.xml", + $"{winDir}\\System32\\Sysprep\\Panther\\unattend.xml", + $"{winDir}\\..\\unattend.xml", + $"{winDir}\\..\\unattend.inf", }; - foreach (string SearchLocation in SearchLocations) - { - if (System.IO.File.Exists(SearchLocation)) - results.Add(SearchLocation); - - } + results.AddRange(searchLocations.Where(System.IO.File.Exists)); } catch (Exception ex) - { - Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); + { + Beaprint.PrintException(ex.Message); } return results; } @@ -51,81 +47,78 @@ namespace winPEAS public static List ExtractUnattenededPwd(string path) { List results = new List(); - try { + + try + { string text = File.ReadAllText(path); text = text.Replace("\n", ""); text = text.Replace("\r", ""); Regex regex = new Regex(@".*"); - foreach (Match match in regex.Matches(text)) - results.Add(match.Value); + foreach (Match match in regex.Matches(text)) + { + results.Add(match.Value); + } } catch (Exception ex) { - Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); + Beaprint.PrintException(ex.Message); } + return results; } public static List GetSAMBackups() - { //From SharpUP - List results = new List(); + { + //From SharpUP + var results = new List(); try { - string systemRoot = System.Environment.GetEnvironmentVariable("SystemRoot"); - string[] SearchLocations = + string systemRoot = Environment.GetEnvironmentVariable("SystemRoot"); + string[] searchLocations = { - String.Format(@"{0}\repair\SAM", systemRoot), - String.Format(@"{0}\System32\config\RegBack\SAM", systemRoot), - //String.Format(@"{0}\System32\config\SAM", systemRoot), - String.Format(@"{0}\repair\SYSTEM", systemRoot), - //String.Format(@"{0}\System32\config\SYSTEM", systemRoot), - String.Format(@"{0}\System32\config\RegBack\SYSTEM", systemRoot), + $@"{systemRoot}\repair\SAM", + $@"{systemRoot}\System32\config\RegBack\SAM", + //$@"{0}\System32\config\SAM" + $@"{systemRoot}\repair\SYSTEM", + //$@"{0}\System32\config\SYSTEM", systemRoot), + $@"{systemRoot}\System32\config\RegBack\SYSTEM", }; - foreach (string SearchLocation in SearchLocations) - { - if (System.IO.File.Exists(SearchLocation)) - results.Add(SearchLocation); - - } + results.AddRange(searchLocations.Where(searchLocation => System.IO.File.Exists(searchLocation))); } catch (Exception ex) { - Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); + Beaprint.PrintException(ex.Message); } return results; } public static List GetMcAfeeSitelistFiles() - { //From SharpUP + { + //From SharpUP List results = new List(); try { string drive = System.Environment.GetEnvironmentVariable("SystemDrive"); - string[] SearchLocations = + string[] searchLocations = { - String.Format("{0}\\Program Files\\", drive), - String.Format("{0}\\Program Files (x86)\\", drive), - String.Format("{0}\\Documents and Settings\\", drive), - String.Format("{0}\\Users\\", drive) + $"{drive}\\Program Files\\", + $"{drive}\\Program Files (x86)\\", + $"{drive}\\Documents and Settings\\", + $"{drive}\\Users\\", }; - foreach (string SearchLocation in SearchLocations) - { - List files = MyUtils.FindFiles(SearchLocation, "SiteList.xml"); - - foreach (string file in files) - results.Add(file); - - } + results.AddRange( + searchLocations.SelectMany( + searchLocation => MyUtils.FindFiles(searchLocation, "SiteList.xml"))); } catch (Exception ex) { - Console.WriteLine(String.Format(" [X] Exception: {0}", ex.Message)); + Beaprint.PrintException(ex.Message); } return results; } @@ -146,7 +139,7 @@ namespace winPEAS } allUsers += "\\Microsoft\\Group Policy\\History"; // look only in the GPO cache folder - List files = MyUtils.FindFiles(allUsers, "*.xml"); + List files = MyUtils.FindFiles(allUsers, "*.xml"); // files will contain all XML files foreach (string file in files) @@ -354,36 +347,36 @@ namespace winPEAS } catch (Exception ex) { - Console.WriteLine(String.Format(" [X] Exception: {0}", ex.Message)); + Beaprint.PrintException(ex.Message); } return results; } - public static string DecryptGPP(string cpassword) - { //From SharpUP - int mod = cpassword.Length % 4; + public static string DecryptGPP(string cPassword) + { + //From SharpUP + int mod = cPassword.Length % 4; switch (mod) { case 1: - cpassword = cpassword.Substring(0, cpassword.Length - 1); + cPassword = cPassword.Substring(0, cPassword.Length - 1); break; case 2: - cpassword += "".PadLeft(4 - mod, '='); + cPassword += "".PadLeft(4 - mod, '='); break; case 3: - cpassword += "".PadLeft(4 - mod, '='); - break; - default: + cPassword += "".PadLeft(4 - mod, '='); break; } - byte[] base64decoded = Convert.FromBase64String(cpassword); + byte[] base64decoded = Convert.FromBase64String(cPassword); AesCryptoServiceProvider aesObject = new AesCryptoServiceProvider(); - byte[] aesKey = { 0x4e, 0x99, 0x06, 0xe8, 0xfc, 0xb6, 0x6c, 0xc9, 0xfa, 0xf4, 0x93, 0x10, 0x62, 0x0f, 0xfe, 0xe8, 0xf4, 0x96, 0xe8, 0x06, 0xcc, 0x05, 0x79, 0x90, 0x20, 0x9b, 0x09, 0xa4, 0x33, 0xb6, 0x6c, 0x1b }; + byte[] aesKey = { 0x4e, 0x99, 0x06, 0xe8, 0xfc, 0xb6, 0x6c, 0xc9, 0xfa, 0xf4, 0x93, 0x10, 0x62, 0x0f, + 0xfe, 0xe8, 0xf4, 0x96, 0xe8, 0x06, 0xcc, 0x05, 0x79, 0x90, 0x20, 0x9b, 0x09, 0xa4, 0x33, 0xb6, 0x6c, 0x1b }; byte[] aesIV = new byte[aesObject.IV.Length]; aesObject.IV = aesIV; @@ -405,7 +398,7 @@ namespace winPEAS if (MyUtils.IsHighIntegrity()) { - string searchPath = String.Format("{0}\\Users\\", Environment.GetEnvironmentVariable("SystemDrive")); + string searchPath = $"{Environment.GetEnvironmentVariable("SystemDrive")}\\Users\\"; List files = MyUtils.FindFiles(searchPath, patterns); @@ -438,6 +431,33 @@ namespace winPEAS return results; } + private static object InvokeMemberMethod(object target, string name, object[] args = null) + { + if (target == null) throw new ArgumentNullException(nameof(target)); + + object result = InvokeMember(target, name, BindingFlags.InvokeMethod, args); + + return result; + } + + private static object InvokeMemberProperty(object target, string name, object[] args = null) + { + if (target == null) throw new ArgumentNullException(nameof(target)); + + object result = InvokeMember(target, name, BindingFlags.GetProperty, args); + + return result; + } + + private static object InvokeMember(object target, string name, BindingFlags invokeAttr, object[] args = null) + { + if (target == null) throw new ArgumentNullException(nameof(target)); + + object result = target.GetType().InvokeMember(name, invokeAttr, null, target, args); + + return result; + } + public static List> GetRecycleBin() { List> results = new List>(); @@ -452,37 +472,37 @@ namespace winPEAS // Shell COM object GUID Type shell = Type.GetTypeFromCLSID(new Guid("13709620-C279-11CE-A49E-444553540000")); - Object shellObj = Activator.CreateInstance(shell); + object shellObj = Activator.CreateInstance(shell); // namespace for recycle bin == 10 - https://msdn.microsoft.com/en-us/library/windows/desktop/bb762494(v=vs.85).aspx - Object recycle = shellObj.GetType().InvokeMember("Namespace", BindingFlags.InvokeMethod, null, shellObj, new object[] { 10 }); + object recycle = InvokeMemberMethod(shellObj, "Namespace", new object[] { 10 }); // grab all the deletes items - Object items = recycle.GetType().InvokeMember("Items", BindingFlags.InvokeMethod, null, recycle, null); + object items = InvokeMemberMethod(recycle, "Items"); // grab the number of deleted items - Object count = items.GetType().InvokeMember("Count", BindingFlags.GetProperty, null, items, null); + object count = InvokeMemberProperty(items, "Count"); int deletedCount = Int32.Parse(count.ToString()); // iterate through each item for (int i = 0; i < deletedCount; i++) { // grab the specific deleted item - Object item = items.GetType().InvokeMember("Item", BindingFlags.InvokeMethod, null, items, new object[] { i }); - Object DateDeleted = item.GetType().InvokeMember("ExtendedProperty", BindingFlags.InvokeMethod, null, item, new object[] { "System.Recycle.DateDeleted" }); - DateTime modifiedDate = DateTime.Parse(DateDeleted.ToString()); + object item = InvokeMemberMethod(items, "Item", new object[] { i }); + object dateDeleted = InvokeMemberMethod(item, "ExtendedProperty", new object[] { "System.Recycle.DateDeleted" }); + DateTime modifiedDate = DateTime.Parse(dateDeleted.ToString()); if (modifiedDate > startTime) { // additional extended properties from https://blogs.msdn.microsoft.com/oldnewthing/20140421-00/?p=1183 - Object Name = item.GetType().InvokeMember("Name", BindingFlags.GetProperty, null, item, null); - Object Path = item.GetType().InvokeMember("Path", BindingFlags.GetProperty, null, item, null); - Object Size = item.GetType().InvokeMember("Size", BindingFlags.GetProperty, null, item, null); - Object DeletedFrom = item.GetType().InvokeMember("ExtendedProperty", BindingFlags.InvokeMethod, null, item, new object[] { "System.Recycle.DeletedFrom" }); + object name = InvokeMemberProperty(item, "Name"); + object path = InvokeMemberProperty(item, "Path"); + object size = InvokeMemberProperty(item, "Size"); + object deletedFrom = InvokeMemberMethod(item, "ExtendedProperty", new object[] { "System.Recycle.DeletedFrom" }); results.Add(new Dictionary() { - { "Name", String.Format("{0}", Name) }, - { "Path", String.Format("{0}", Path) }, - { "Size", String.Format("{0}", Size) }, - { "Deleted from", String.Format("{0}", DeletedFrom) }, - { "Date Deleted", String.Format("{0}", DateDeleted) } + { "Name", name.ToString() }, + { "Path", path.ToString() }, + { "Size", size.ToString() }, + { "Deleted from", deletedFrom.ToString() }, + { "Date Deleted", dateDeleted.ToString() } }); } Marshal.ReleaseComObject(item); diff --git a/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Chrome.cs b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Chrome.cs new file mode 100644 index 0000000..a465271 --- /dev/null +++ b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Chrome.cs @@ -0,0 +1,172 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.RegularExpressions; +using System.Web.Script.Serialization; + +namespace winPEAS.KnownFileCreds +{ + static class Chrome + { + public static Dictionary GetChromeDbs() + { + Dictionary results = new Dictionary(); + // checks if Chrome has a history database + try + { + if (MyUtils.IsHighIntegrity()) + { + string userFolder = String.Format("{0}\\Users\\", Environment.GetEnvironmentVariable("SystemDrive")); + string[] dirs = Directory.GetDirectories(userFolder); + foreach (string dir in dirs) + { + string[] parts = dir.Split('\\'); + string userName = parts[parts.Length - 1]; + if (!(dir.EndsWith("Public") || dir.EndsWith("Default") || dir.EndsWith("Default User") || dir.EndsWith("All Users"))) + { + string userChromeCookiesPath = String.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Cookies", dir); + if (System.IO.File.Exists(userChromeCookiesPath)) + results["userChromeCookiesPath"] = userChromeCookiesPath; + + string userChromeLoginDataPath = String.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Login Data", dir); + if (System.IO.File.Exists(userChromeLoginDataPath)) + results["userChromeLoginDataPath"] = userChromeLoginDataPath; + } + } + } + else + { + string userChromeCookiesPath = String.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Cookies", System.Environment.GetEnvironmentVariable("USERPROFILE")); + if (System.IO.File.Exists(userChromeCookiesPath)) + results["userChromeCookiesPath"] = userChromeCookiesPath; + + string userChromeLoginDataPath = String.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Login Data", System.Environment.GetEnvironmentVariable("USERPROFILE")); + if (System.IO.File.Exists(userChromeLoginDataPath)) + results["userChromeLoginDataPath"] = userChromeLoginDataPath; + } + } + catch (Exception ex) + { + Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); + } + return results; + } + + public static List ParseChromeHistory(string path) + { + List results = new List(); + + // parses a Chrome history file via regex + if (System.IO.File.Exists(path)) + { + Regex historyRegex = new Regex(@"(http|ftp|https|file)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?"); + + try + { + using (StreamReader r = new StreamReader(path)) + { + string line; + while ((line = r.ReadLine()) != null) + { + Match m = historyRegex.Match(line); + if (m.Success) + { + results.Add(m.Groups[0].ToString().Trim()); + } + } + } + } + catch (System.IO.IOException exception) + { + Console.WriteLine("\r\n [x] IO exception, history file likely in use (i.e. Browser is likely running): ", exception.Message); + } + catch (Exception ex) + { + Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); + } + } + return results; + } + + public static Dictionary> GetChromeHistBook() + { + Dictionary> results = new Dictionary>() + { + { "history", new List() }, + { "bookarks", new List() }, + }; + try + { + if (MyUtils.IsHighIntegrity()) + { + Console.WriteLine("\r\n\r\n=== Chrome (All Users) ==="); + + string userFolder = String.Format("{0}\\Users\\", Environment.GetEnvironmentVariable("SystemDrive")); + string[] dirs = Directory.GetDirectories(userFolder); + foreach (string dir in dirs) + { + string[] parts = dir.Split('\\'); + if (!(dir.EndsWith("Public") || dir.EndsWith("Default") || dir.EndsWith("Default User") || dir.EndsWith("All Users"))) + { + string userChromeHistoryPath = String.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\History", dir); + results["history"] = ParseChromeHistory(userChromeHistoryPath); + + string userChromeBookmarkPath = String.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Bookmarks", dir); + results["bookmarks"] = ParseChromeBookmarks(userChromeBookmarkPath); + } + } + } + else + { + string userChromeHistoryPath = String.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\History", System.Environment.GetEnvironmentVariable("USERPROFILE")); + results["history"] = ParseChromeHistory(userChromeHistoryPath); + + string userChromeBookmarkPath = String.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Bookmarks", System.Environment.GetEnvironmentVariable("USERPROFILE")); + + results["bookmarks"] = ParseChromeBookmarks(userChromeBookmarkPath); + } + } + catch (Exception ex) + { + Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); + } + return results; + } + + private static List ParseChromeBookmarks(string path) + { + List results = new List(); + // parses a Chrome bookmarks + if (System.IO.File.Exists(path)) + { + try + { + string contents = System.IO.File.ReadAllText(path); + + // reference: http://www.tomasvera.com/programming/using-javascriptserializer-to-parse-json-objects/ + JavaScriptSerializer json = new JavaScriptSerializer(); + Dictionary deserialized = json.Deserialize>(contents); + Dictionary roots = (Dictionary)deserialized["roots"]; + Dictionary bookmark_bar = (Dictionary)roots["bookmark_bar"]; + System.Collections.ArrayList children = (System.Collections.ArrayList)bookmark_bar["children"]; + + foreach (Dictionary entry in children) + { + //Console.WriteLine(" Name: {0}", entry["name"].ToString().Trim()); + if (entry.ContainsKey("url")) + results.Add(entry["url"].ToString().Trim()); + } + } + catch (System.IO.IOException exception) + { + Console.WriteLine("\r\n [x] IO exception, Bookmarks file likely in use (i.e. Chrome is likely running).", exception.Message); + } + catch (Exception ex) + { + Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); + } + } + return results; + } + } +} diff --git a/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Firefox.cs b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Firefox.cs new file mode 100644 index 0000000..392e6dc --- /dev/null +++ b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Firefox.cs @@ -0,0 +1,145 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.RegularExpressions; + +namespace winPEAS.KnownFileCreds +{ + static class Firefox + { + public static List GetFirefoxDbs() + { + List results = new List(); + // checks if Firefox has a history database + try + { + if (MyUtils.IsHighIntegrity()) + { + string userFolder = String.Format("{0}\\Users\\", Environment.GetEnvironmentVariable("SystemDrive")); + string[] dirs = Directory.GetDirectories(userFolder); + foreach (string dir in dirs) + { + string[] parts = dir.Split('\\'); + string userName = parts[parts.Length - 1]; + if (!(dir.EndsWith("Public") || dir.EndsWith("Default") || dir.EndsWith("Default User") || dir.EndsWith("All Users"))) + { + string userFirefoxBasePath = String.Format("{0}\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\", dir); + if (System.IO.Directory.Exists(userFirefoxBasePath)) + { + string[] directories = Directory.GetDirectories(userFirefoxBasePath); + foreach (string directory in directories) + { + string firefoxCredentialFile3 = String.Format("{0}\\{1}", directory, "key3.db"); + if (System.IO.File.Exists(firefoxCredentialFile3)) + results.Add(firefoxCredentialFile3); + + string firefoxCredentialFile4 = String.Format("{0}\\{1}", directory, "key4.db"); + if (System.IO.File.Exists(firefoxCredentialFile4)) + results.Add(firefoxCredentialFile3); + } + } + } + } + } + else + { + string userName = Environment.GetEnvironmentVariable("USERNAME"); + string userFirefoxBasePath = String.Format("{0}\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\", System.Environment.GetEnvironmentVariable("USERPROFILE")); + + if (System.IO.Directory.Exists(userFirefoxBasePath)) + { + string[] directories = Directory.GetDirectories(userFirefoxBasePath); + foreach (string directory in directories) + { + string firefoxCredentialFile3 = String.Format("{0}\\{1}", directory, "key3.db"); + if (System.IO.File.Exists(firefoxCredentialFile3)) + results.Add(firefoxCredentialFile3); + + string firefoxCredentialFile4 = String.Format("{0}\\{1}", directory, "key4.db"); + if (System.IO.File.Exists(firefoxCredentialFile4)) + results.Add(firefoxCredentialFile4); + } + } + } + } + catch (Exception ex) + { + Beaprint.PrintException(ex.Message); + } + + return results; + } + + public static List GetFirefoxHistory() + { + List results = new List(); + try + { + if (MyUtils.IsHighIntegrity()) + { + string userFolder = String.Format("{0}\\Users\\", Environment.GetEnvironmentVariable("SystemDrive")); + string[] dirs = Directory.GetDirectories(userFolder); + foreach (string dir in dirs) + { + string[] parts = dir.Split('\\'); + if (!(dir.EndsWith("Public") || dir.EndsWith("Default") || dir.EndsWith("Default User") || dir.EndsWith("All Users"))) + { + string userFirefoxBasePath = String.Format("{0}\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\", dir); + results = ParseFirefoxHistory(userFirefoxBasePath); + } + } + } + else + { + string userFirefoxBasePath = String.Format("{0}\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\", System.Environment.GetEnvironmentVariable("USERPROFILE")); + results = ParseFirefoxHistory(userFirefoxBasePath); + } + } + catch (Exception ex) + { + Beaprint.PrintException(ex.Message); + } + return results; + } + + private static List ParseFirefoxHistory(string path) + { + List results = new List(); + // parses a Firefox history file via regex + if (Directory.Exists(path)) + { + string[] directories = Directory.GetDirectories(path); + foreach (string directory in directories) + { + string firefoxHistoryFile = String.Format("{0}\\{1}", directory, "places.sqlite"); + Regex historyRegex = new Regex(@"(http|ftp|https|file)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?"); + + try + { + using (StreamReader r = new StreamReader(firefoxHistoryFile)) + { + string line; + while ((line = r.ReadLine()) != null) + { + Match m = historyRegex.Match(line); + if (m.Success) + { + results.Add(m.Groups[0].ToString().Trim()); + } + } + } + } + catch (IOException exception) + { + Console.WriteLine("\r\n [x] IO exception, places.sqlite file likely in use (i.e. Firefox is likely running).", exception.Message); + } + catch (Exception ex) + { + Beaprint.PrintException(ex.Message); + } + } + } + return results; + } + } +} diff --git a/winPEAS/winPEASexe/winPEAS/KnownFileCreds/InternetExplorer.cs b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/InternetExplorer.cs new file mode 100644 index 0000000..818d52e --- /dev/null +++ b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/InternetExplorer.cs @@ -0,0 +1,205 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using Microsoft.Win32; +using winPEAS.Utils; + +namespace winPEAS.KnownFileCreds +{ + static class InternetExplorer + { + public static Dictionary> GetIEHistFav() + { + int lastDays = 90; + Dictionary> results = new Dictionary>() + { + { "history", new List() }, + { "favorites", new List() }, + }; + + DateTime startTime = System.DateTime.Now.AddDays(-lastDays); + + try + { + if (MyUtils.IsHighIntegrity()) + { + string[] SIDs = Registry.Users.GetSubKeyNames(); + foreach (string SID in SIDs) + { + if (SID.StartsWith("S-1-5") && !SID.EndsWith("_Classes")) + { + Dictionary settings = RegistryHelper.GetRegValues("HKU", String.Format("{0}\\SOFTWARE\\Microsoft\\Internet Explorer\\TypedURLs", SID)); + if ((settings != null) && (settings.Count > 1)) + { + foreach (KeyValuePair kvp in settings) + { + byte[] timeBytes = RegistryHelper.GetRegValueBytes("HKU", String.Format("{0}\\SOFTWARE\\Microsoft\\Internet Explorer\\TypedURLsTime", SID), kvp.Key.ToString().Trim()); + if (timeBytes != null) + { + long timeLong = (long)(BitConverter.ToInt64(timeBytes, 0)); + DateTime urlTime = DateTime.FromFileTime(timeLong); + if (urlTime > startTime) + { + results["history"].Add(kvp.Value.ToString().Trim()); + } + } + } + } + } + } + + string userFolder = String.Format("{0}\\Users\\", Environment.GetEnvironmentVariable("SystemDrive")); + string[] dirs = Directory.GetDirectories(userFolder); + foreach (string dir in dirs) + { + string[] parts = dir.Split('\\'); + string userName = parts[parts.Length - 1]; + if (!(dir.EndsWith("Public") || dir.EndsWith("Default") || dir.EndsWith("Default User") || dir.EndsWith("All Users"))) + { + string userIEBookmarkPath = String.Format("{0}\\Favorites\\", dir); + + if (Directory.Exists(userIEBookmarkPath)) + { + string[] bookmarkPaths = Directory.GetFiles(userIEBookmarkPath, "*.url", SearchOption.AllDirectories); + if (bookmarkPaths.Length != 0) + { + foreach (string bookmarkPath in bookmarkPaths) + { + using (StreamReader rdr = new StreamReader(bookmarkPath)) + { + string line; + string url = ""; + while ((line = rdr.ReadLine()) != null) + { + if (line.StartsWith("URL=", StringComparison.InvariantCultureIgnoreCase)) + { + if (line.Length > 4) + url = line.Substring(4); + break; + } + } + results["history"].Add(url.ToString().Trim()); + } + } + } + } + } + } + } + else + { + Dictionary settings = RegistryHelper.GetRegValues("HKCU", "SOFTWARE\\Microsoft\\Internet Explorer\\TypedURLs"); + if ((settings != null) && (settings.Count != 0)) + { + foreach (KeyValuePair kvp in settings) + { + byte[] timeBytes = RegistryHelper.GetRegValueBytes("HKCU", "SOFTWARE\\Microsoft\\Internet Explorer\\TypedURLsTime", kvp.Key.ToString().Trim()); + if (timeBytes != null) + { + long timeLong = (long)(BitConverter.ToInt64(timeBytes, 0)); + DateTime urlTime = DateTime.FromFileTime(timeLong); + if (urlTime > startTime) + { + results["history"].Add(kvp.Value.ToString().Trim()); + } + } + } + } + + string userIEBookmarkPath = String.Format("{0}\\Favorites\\", System.Environment.GetEnvironmentVariable("USERPROFILE")); + + string[] bookmarkPaths = Directory.GetFiles(userIEBookmarkPath, "*.url", SearchOption.AllDirectories); + + foreach (string bookmarkPath in bookmarkPaths) + { + using (StreamReader rdr = new StreamReader(bookmarkPath)) + { + string line; + string url = ""; + while ((line = rdr.ReadLine()) != null) + { + if (line.StartsWith("URL=", StringComparison.InvariantCultureIgnoreCase)) + { + if (line.Length > 4) + url = line.Substring(4); + break; + } + } + results["favorites"].Add(url.ToString().Trim()); + } + } + } + } + catch (Exception ex) + { + Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex)); + } + return results; + } + + + public static List GetCurrentIETabs() + { + List results = new List(); + // Lists currently open Internet Explorer tabs, via COM + // Notes: + // https://searchcode.com/codesearch/view/9859954/ + // https://gist.github.com/yizhang82/a1268d3ea7295a8a1496e01d60ada816 + + try + { + // Shell.Application COM GUID + Type shell = Type.GetTypeFromCLSID(new Guid("13709620-C279-11CE-A49E-444553540000")); + + // actually instantiate the Shell.Application COM object + Object shellObj = Activator.CreateInstance(shell); + + // grab all the current windows + Object windows = shellObj.GetType().InvokeMember("Windows", BindingFlags.InvokeMethod, null, shellObj, null); + + // grab the open tab count + Object openTabs = windows.GetType().InvokeMember("Count", BindingFlags.GetProperty, null, windows, null); + int openTabsCount = Int32.Parse(openTabs.ToString()); + + for (int i = 0; i < openTabsCount; i++) + { + // grab the acutal tab + Object item = windows.GetType().InvokeMember("Item", BindingFlags.InvokeMethod, null, windows, new object[] { i }); + try + { + // extract the tab properties + Object locationName = item.GetType().InvokeMember("LocationName", BindingFlags.GetProperty, null, item, null); + Object locationURL = item.GetType().InvokeMember("LocationUrl", BindingFlags.GetProperty, null, item, null); + + // ensure we have a site address + if (Regex.IsMatch(locationURL.ToString(), @"(^https?://.+)|(^ftp://)")) + { + results.Add(String.Format("{0}", locationURL)); + } + Marshal.ReleaseComObject(item); + item = null; + } + catch + { + // + } + } + Marshal.ReleaseComObject(windows); + windows = null; + Marshal.ReleaseComObject(shellObj); + shellObj = null; + } + catch (Exception ex) + { + Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex)); + } + return results; + } + } +} diff --git a/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Kerberos/Helpers.cs b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Kerberos/Helpers.cs new file mode 100644 index 0000000..57057d0 --- /dev/null +++ b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Kerberos/Helpers.cs @@ -0,0 +1,134 @@ +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; +using winPEAS.KnownFileCreds.Kerberos.structs; + +namespace winPEAS.KnownFileCreds.Kerberos +{ + static class Helpers + { + [DllImport("secur32.dll", SetLastError = true)] + public static extern int + LsaRegisterLogonProcess(LSA_STRING_IN LogonProcessName, out IntPtr LsaHandle, out ulong SecurityMode); + + [DllImport("advapi32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool + OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle); + + [DllImport("advapi32.dll")] + public extern static bool + DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle); + + [DllImport("advapi32.dll", SetLastError = true)] + public static extern bool + ImpersonateLoggedOnUser(IntPtr hToken); + + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool + CloseHandle(IntPtr hObject); + + [DllImport("advapi32.dll", SetLastError = true)] + public static extern bool + RevertToSelf(); + + [DllImport("Secur32.dll", SetLastError = false)] + public static extern uint LsaEnumerateLogonSessions(out UInt64 LogonSessionCount, out IntPtr LogonSessionList); + + [DllImport("Secur32.dll", SetLastError = false)] + public static extern uint LsaGetLogonSessionData(IntPtr luid, out IntPtr ppLogonSessionData); + + [DllImport("secur32.dll", SetLastError = false)] + public static extern int LsaLookupAuthenticationPackage([In] IntPtr LsaHandle, [In] ref LSA_STRING_IN PackageName, [Out] out int AuthenticationPackage); + + [DllImport("secur32.dll", SetLastError = false)] + public static extern int LsaCallAuthenticationPackage(IntPtr LsaHandle, int AuthenticationPackage, ref KERB_QUERY_TKT_CACHE_REQUEST ProtocolSubmitBuffer, int SubmitBufferLength, out IntPtr ProtocolReturnBuffer, out int ReturnBufferLength, out int ProtocolStatus); + + [DllImport("secur32.dll", SetLastError = false)] + public static extern uint LsaFreeReturnBuffer(IntPtr buffer); + [DllImport("secur32.dll", SetLastError = false)] + public static extern int LsaConnectUntrusted([Out] out IntPtr LsaHandle); + + [DllImport("secur32.dll", SetLastError = false)] + public static extern int LsaDeregisterLogonProcess([In] IntPtr LsaHandle); + + [DllImport("secur32.dll", EntryPoint = "LsaCallAuthenticationPackage", SetLastError = false)] + public static extern int LsaCallAuthenticationPackage_KERB_RETRIEVE_TKT(IntPtr LsaHandle, int AuthenticationPackage, ref KERB_RETRIEVE_TKT_REQUEST ProtocolSubmitBuffer, int SubmitBufferLength, out IntPtr ProtocolReturnBuffer, out int ReturnBufferLength, out int ProtocolStatus); + + + public static IntPtr LsaRegisterLogonProcessHelper() + { + // helper that establishes a connection to the LSA server and verifies that the caller is a logon application + // used for Kerberos ticket enumeration + + string logonProcessName = "User32LogonProcesss"; + LSA_STRING_IN LSAString; + IntPtr lsaHandle = IntPtr.Zero; + UInt64 securityMode = 0; + + LSAString.Length = (ushort)logonProcessName.Length; + LSAString.MaximumLength = (ushort)(logonProcessName.Length + 1); + LSAString.Buffer = logonProcessName; + + int ret = LsaRegisterLogonProcess(LSAString, out lsaHandle, out securityMode); + + return lsaHandle; + } + + public static bool GetSystem() + { + // helper to elevate to SYSTEM for Kerberos ticket enumeration via token impersonation + + if (MyUtils.IsHighIntegrity()) + { + IntPtr hToken = IntPtr.Zero; + + // Open winlogon's token with TOKEN_DUPLICATE accesss so ca can make a copy of the token with DuplicateToken + Process[] processes = Process.GetProcessesByName("winlogon"); + IntPtr handle = processes[0].Handle; + + // TOKEN_DUPLICATE = 0x0002 + bool success = OpenProcessToken(handle, 0x0002, out hToken); + if (!success) + { + //Console.WriteLine("OpenProcessToken failed!"); + return false; + } + + // make a copy of the NT AUTHORITY\SYSTEM token from winlogon + // 2 == SecurityImpersonation + IntPtr hDupToken = IntPtr.Zero; + success = DuplicateToken(hToken, 2, ref hDupToken); + if (!success) + { + //Console.WriteLine("DuplicateToken failed!"); + return false; + } + + success = ImpersonateLoggedOnUser(hDupToken); + if (!success) + { + //Console.WriteLine("ImpersonateLoggedOnUser failed!"); + return false; + } + + // clean up the handles we created + CloseHandle(hToken); + CloseHandle(hDupToken); + + string name = System.Security.Principal.WindowsIdentity.GetCurrent().Name; + if (name != "NT AUTHORITY\\SYSTEM") + { + return false; + } + + return true; + } + else + { + return false; + } + } + } +} diff --git a/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Kerberos/Kerberos.cs b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Kerberos/Kerberos.cs new file mode 100644 index 0000000..026889b --- /dev/null +++ b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Kerberos/Kerberos.cs @@ -0,0 +1,569 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using winPEAS.KnownFileCreds.Kerberos.enums; +using winPEAS.KnownFileCreds.Kerberos.structs; + +namespace winPEAS.KnownFileCreds.Kerberos +{ + static class Kerberos + { + public static List> ListKerberosTickets() + { + if (MyUtils.IsHighIntegrity()) + { + return ListKerberosTicketsAllUsers(); + } + else + { + return ListKerberosTicketsCurrentUser(); + } + } + + public static List> ListKerberosTicketsAllUsers() + { + List> results = new List>(); + // adapted partially from Vincent LE TOUX' work + // https://github.com/vletoux/MakeMeEnterpriseAdmin/blob/master/MakeMeEnterpriseAdmin.ps1#L2939-L2950 + // and https://www.dreamincode.net/forums/topic/135033-increment-memory-pointer-issue/ + // also Jared Atkinson's work at https://github.com/Invoke-IR/ACE/blob/master/ACE-Management/PS-ACE/Scripts/ACE_Get-KerberosTicketCache.ps1 + + IntPtr hLsa = Helpers.LsaRegisterLogonProcessHelper(); + int totalTicketCount = 0; + + // if the original call fails then it is likely we don't have SeTcbPrivilege + // to get SeTcbPrivilege we can Impersonate a NT AUTHORITY\SYSTEM Token + if (hLsa == IntPtr.Zero) + { + Helpers.GetSystem(); + // should now have the proper privileges to get a Handle to LSA + hLsa = Helpers.LsaRegisterLogonProcessHelper(); + // we don't need our NT AUTHORITY\SYSTEM Token anymore so we can revert to our original token + Helpers.RevertToSelf(); + } + + try + { + // first return all the logon sessions + + DateTime systime = new DateTime(1601, 1, 1, 0, 0, 0, 0); //win32 systemdate + UInt64 count; + IntPtr luidPtr = IntPtr.Zero; + IntPtr iter = luidPtr; + + uint ret = Helpers.LsaEnumerateLogonSessions(out count, out luidPtr); // get an array of pointers to LUIDs + + for (ulong i = 0; i < count; i++) + { + IntPtr sessionData; + ret = Helpers.LsaGetLogonSessionData(luidPtr, out sessionData); + SECURITY_LOGON_SESSION_DATA data = (SECURITY_LOGON_SESSION_DATA)Marshal.PtrToStructure(sessionData, typeof(SECURITY_LOGON_SESSION_DATA)); + + // if we have a valid logon + if (data.PSiD != IntPtr.Zero) + { + // user session data + string username = Marshal.PtrToStringUni(data.Username.Buffer).Trim(); + System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(data.PSiD); + string domain = Marshal.PtrToStringUni(data.LoginDomain.Buffer).Trim(); + string authpackage = Marshal.PtrToStringUni(data.AuthenticationPackage.Buffer).Trim(); + SECURITY_LOGON_TYPE logonType = (SECURITY_LOGON_TYPE)data.LogonType; + DateTime logonTime = systime.AddTicks((long)data.LoginTime); + string logonServer = Marshal.PtrToStringUni(data.LogonServer.Buffer).Trim(); + string dnsDomainName = Marshal.PtrToStringUni(data.DnsDomainName.Buffer).Trim(); + string upn = Marshal.PtrToStringUni(data.Upn.Buffer).Trim(); + + // now we want to get the tickets for this logon ID + string name = "kerberos"; + LSA_STRING_IN LSAString; + LSAString.Length = (ushort)name.Length; + LSAString.MaximumLength = (ushort)(name.Length + 1); + LSAString.Buffer = name; + + IntPtr ticketPointer = IntPtr.Zero; + IntPtr ticketsPointer = IntPtr.Zero; + DateTime sysTime = new DateTime(1601, 1, 1, 0, 0, 0, 0); + int authPack; + int returnBufferLength = 0; + int protocalStatus = 0; + int retCode; + + KERB_QUERY_TKT_CACHE_REQUEST tQuery = new KERB_QUERY_TKT_CACHE_REQUEST(); + KERB_QUERY_TKT_CACHE_RESPONSE tickets = new KERB_QUERY_TKT_CACHE_RESPONSE(); + KERB_TICKET_CACHE_INFO ticket; + + // obtains the unique identifier for the kerberos authentication package. + retCode = Helpers.LsaLookupAuthenticationPackage(hLsa, ref LSAString, out authPack); + + // input object for querying the ticket cache for a specific logon ID + LUID userLogonID = new LUID(); + userLogonID.LowPart = data.LoginID.LowPart; + userLogonID.HighPart = 0; + tQuery.LogonId = userLogonID; + tQuery.MessageType = KERB_PROTOCOL_MESSAGE_TYPE.KerbQueryTicketCacheMessage; + + // query LSA, specifying we want the ticket cache + retCode = Helpers.LsaCallAuthenticationPackage(hLsa, authPack, ref tQuery, Marshal.SizeOf(tQuery), out ticketPointer, out returnBufferLength, out protocalStatus); + + /*Console.WriteLine("\r\n UserName : {0}", username); + Console.WriteLine(" Domain : {0}", domain); + Console.WriteLine(" LogonId : {0}", data.LoginID.LowPart); + Console.WriteLine(" UserSID : {0}", sid.AccountDomainSid); + Console.WriteLine(" AuthenticationPackage : {0}", authpackage); + Console.WriteLine(" LogonType : {0}", logonType); + Console.WriteLine(" LogonType : {0}", logonTime); + Console.WriteLine(" LogonServer : {0}", logonServer); + Console.WriteLine(" LogonServerDNSDomain : {0}", dnsDomainName); + Console.WriteLine(" UserPrincipalName : {0}\r\n", upn);*/ + + if (ticketPointer != IntPtr.Zero) + { + // parse the returned pointer into our initial KERB_QUERY_TKT_CACHE_RESPONSE structure + tickets = (KERB_QUERY_TKT_CACHE_RESPONSE)Marshal.PtrToStructure((System.IntPtr)ticketPointer, typeof(KERB_QUERY_TKT_CACHE_RESPONSE)); + int count2 = tickets.CountOfTickets; + + if (count2 != 0) + { + Console.WriteLine(" [*] Enumerated {0} ticket(s):\r\n", count2); + totalTicketCount += count2; + // get the size of the structures we're iterating over + Int32 dataSize = Marshal.SizeOf(typeof(KERB_TICKET_CACHE_INFO)); + + for (int j = 0; j < count2; j++) + { + // iterate through the structures + IntPtr currTicketPtr = (IntPtr)(long)((ticketPointer.ToInt64() + (int)(8 + j * dataSize))); + + // parse the new ptr to the appropriate structure + ticket = (KERB_TICKET_CACHE_INFO)Marshal.PtrToStructure(currTicketPtr, typeof(KERB_TICKET_CACHE_INFO)); + + // extract our fields + string serverName = Marshal.PtrToStringUni(ticket.ServerName.Buffer, ticket.ServerName.Length / 2); + string realmName = Marshal.PtrToStringUni(ticket.RealmName.Buffer, ticket.RealmName.Length / 2); + DateTime startTime = DateTime.FromFileTime(ticket.StartTime); + DateTime endTime = DateTime.FromFileTime(ticket.EndTime); + DateTime renewTime = DateTime.FromFileTime(ticket.RenewTime); + string encryptionType = ((KERB_ENCRYPTION_TYPE)ticket.EncryptionType).ToString(); + string ticketFlags = ((KERB_TICKET_FLAGS)ticket.TicketFlags).ToString(); + + results.Add(new Dictionary() + { + { "UserPrincipalName", upn }, + { "serverName", serverName }, + { "RealmName", realmName }, + { "StartTime", String.Format("{0}", startTime) }, + { "EndTime", String.Format("{0}", endTime) }, + { "RenewTime", String.Format("{0}", renewTime) }, + { "EncryptionType", encryptionType }, + { "TicketFlags", ticketFlags }, + }); + } + } + } + } + // move the pointer forward + luidPtr = (IntPtr)((long)luidPtr.ToInt64() + Marshal.SizeOf(typeof(LUID))); + Helpers.LsaFreeReturnBuffer(sessionData); + } + Helpers.LsaFreeReturnBuffer(luidPtr); + + // disconnect from LSA + Helpers.LsaDeregisterLogonProcess(hLsa); + } + catch (Exception ex) + { + Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); + } + return results; + } + + public static List> ListKerberosTicketsCurrentUser() + { + List> results = new List>(); + // adapted partially from Vincent LE TOUX' work + // https://github.com/vletoux/MakeMeEnterpriseAdmin/blob/master/MakeMeEnterpriseAdmin.ps1#L2939-L2950 + // and https://www.dreamincode.net/forums/topic/135033-increment-memory-pointer-issue/ + // also Jared Atkinson's work at https://github.com/Invoke-IR/ACE/blob/master/ACE-Management/PS-ACE/Scripts/ACE_Get-KerberosTicketCache.ps1 + + try + { + string name = "kerberos"; + LSA_STRING_IN LSAString; + LSAString.Length = (ushort)name.Length; + LSAString.MaximumLength = (ushort)(name.Length + 1); + LSAString.Buffer = name; + + IntPtr ticketPointer = IntPtr.Zero; + IntPtr ticketsPointer = IntPtr.Zero; + DateTime sysTime = new DateTime(1601, 1, 1, 0, 0, 0, 0); + int authPack; + int returnBufferLength = 0; + int protocalStatus = 0; + IntPtr lsaHandle; + int retCode; + + // If we want to look at tickets from a session other than our own + // then we need to use LsaRegisterLogonProcess instead of LsaConnectUntrusted + retCode = Helpers.LsaConnectUntrusted(out lsaHandle); + + KERB_QUERY_TKT_CACHE_REQUEST tQuery = new KERB_QUERY_TKT_CACHE_REQUEST(); + KERB_QUERY_TKT_CACHE_RESPONSE tickets = new KERB_QUERY_TKT_CACHE_RESPONSE(); + KERB_TICKET_CACHE_INFO ticket; + + // obtains the unique identifier for the kerberos authentication package. + retCode = Helpers.LsaLookupAuthenticationPackage(lsaHandle, ref LSAString, out authPack); + + // input object for querying the ticket cache (https://docs.microsoft.com/en-us/windows/desktop/api/ntsecapi/ns-ntsecapi-_kerb_query_tkt_cache_request) + tQuery.LogonId = new LUID(); + tQuery.MessageType = KERB_PROTOCOL_MESSAGE_TYPE.KerbQueryTicketCacheMessage; + + // query LSA, specifying we want the ticket cache + retCode = Helpers.LsaCallAuthenticationPackage(lsaHandle, authPack, ref tQuery, Marshal.SizeOf(tQuery), out ticketPointer, out returnBufferLength, out protocalStatus); + + // parse the returned pointer into our initial KERB_QUERY_TKT_CACHE_RESPONSE structure + tickets = (KERB_QUERY_TKT_CACHE_RESPONSE)Marshal.PtrToStructure((System.IntPtr)ticketPointer, typeof(KERB_QUERY_TKT_CACHE_RESPONSE)); + int count = tickets.CountOfTickets; + + // get the size of the structures we're iterating over + Int32 dataSize = Marshal.SizeOf(typeof(KERB_TICKET_CACHE_INFO)); + + for (int i = 0; i < count; i++) + { + // iterate through the structures + IntPtr currTicketPtr = (IntPtr)(long)((ticketPointer.ToInt64() + (int)(8 + i * dataSize))); + + // parse the new ptr to the appropriate structure + ticket = (KERB_TICKET_CACHE_INFO)Marshal.PtrToStructure(currTicketPtr, typeof(KERB_TICKET_CACHE_INFO)); + + // extract our fields + string serverName = Marshal.PtrToStringUni(ticket.ServerName.Buffer, ticket.ServerName.Length / 2); + string realmName = Marshal.PtrToStringUni(ticket.RealmName.Buffer, ticket.RealmName.Length / 2); + DateTime startTime = DateTime.FromFileTime(ticket.StartTime); + DateTime endTime = DateTime.FromFileTime(ticket.EndTime); + DateTime renewTime = DateTime.FromFileTime(ticket.RenewTime); + string encryptionType = ((KERB_ENCRYPTION_TYPE)ticket.EncryptionType).ToString(); + string ticketFlags = ((KERB_TICKET_FLAGS)ticket.TicketFlags).ToString(); + + results.Add(new Dictionary() + { + { "serverName", serverName }, + { "RealmName", realmName }, + { "StartTime", String.Format("{0}", startTime) }, + { "EndTime", String.Format("{0}", endTime) }, + { "RenewTime", String.Format("{0}", renewTime) }, + { "EncryptionType", encryptionType }, + { "TicketFlags", ticketFlags }, + }); + } + + // disconnect from LSA + Helpers.LsaDeregisterLogonProcess(lsaHandle); + } + catch (Exception ex) + { + Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); + } + return results; + } + + public static List> GetKerberosTGTData() + { + if (MyUtils.IsHighIntegrity()) + { + return ListKerberosTGTDataAllUsers(); + } + else + { + return ListKerberosTGTDataCurrentUser(); + } + } + + public static List> ListKerberosTGTDataAllUsers() + { + List> results = new List>(); + // adapted partially from Vincent LE TOUX' work + // https://github.com/vletoux/MakeMeEnterpriseAdmin/blob/master/MakeMeEnterpriseAdmin.ps1#L2939-L2950 + // and https://www.dreamincode.net/forums/topic/135033-increment-memory-pointer-issue/ + // also Jared Atkinson's work at https://github.com/Invoke-IR/ACE/blob/master/ACE-Management/PS-ACE/Scripts/ACE_Get-KerberosTicketCache.ps1 + + IntPtr hLsa = Helpers.LsaRegisterLogonProcessHelper(); + int totalTicketCount = 0; + + // if the original call fails then it is likely we don't have SeTcbPrivilege + // to get SeTcbPrivilege we can Impersonate a NT AUTHORITY\SYSTEM Token + if (hLsa == IntPtr.Zero) + { + Helpers.GetSystem(); + // should now have the proper privileges to get a Handle to LSA + hLsa = Helpers.LsaRegisterLogonProcessHelper(); + // we don't need our NT AUTHORITY\SYSTEM Token anymore so we can revert to our original token + Helpers.RevertToSelf(); + } + + try + { + // first return all the logon sessions + + DateTime systime = new DateTime(1601, 1, 1, 0, 0, 0, 0); //win32 systemdate + UInt64 count; + IntPtr luidPtr = IntPtr.Zero; + IntPtr iter = luidPtr; + + uint ret = Helpers.LsaEnumerateLogonSessions(out count, out luidPtr); // get an array of pointers to LUIDs + + for (ulong i = 0; i < count; i++) + { + IntPtr sessionData; + ret = Helpers.LsaGetLogonSessionData(luidPtr, out sessionData); + SECURITY_LOGON_SESSION_DATA data = (SECURITY_LOGON_SESSION_DATA)Marshal.PtrToStructure(sessionData, typeof(SECURITY_LOGON_SESSION_DATA)); + + // if we have a valid logon + if (data.PSiD != IntPtr.Zero) + { + // user session data + string username = Marshal.PtrToStringUni(data.Username.Buffer).Trim(); + System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(data.PSiD); + string domain = Marshal.PtrToStringUni(data.LoginDomain.Buffer).Trim(); + string authpackage = Marshal.PtrToStringUni(data.AuthenticationPackage.Buffer).Trim(); + SECURITY_LOGON_TYPE logonType = (SECURITY_LOGON_TYPE)data.LogonType; + DateTime logonTime = systime.AddTicks((long)data.LoginTime); + string logonServer = Marshal.PtrToStringUni(data.LogonServer.Buffer).Trim(); + string dnsDomainName = Marshal.PtrToStringUni(data.DnsDomainName.Buffer).Trim(); + string upn = Marshal.PtrToStringUni(data.Upn.Buffer).Trim(); + + // now we want to get the tickets for this logon ID + string name = "kerberos"; + LSA_STRING_IN LSAString; + LSAString.Length = (ushort)name.Length; + LSAString.MaximumLength = (ushort)(name.Length + 1); + LSAString.Buffer = name; + + IntPtr responsePointer = IntPtr.Zero; + int authPack; + int returnBufferLength = 0; + int protocalStatus = 0; + int retCode; + + KERB_RETRIEVE_TKT_REQUEST tQuery = new KERB_RETRIEVE_TKT_REQUEST(); + KERB_RETRIEVE_TKT_RESPONSE response = new KERB_RETRIEVE_TKT_RESPONSE(); + + // obtains the unique identifier for the kerberos authentication package. + retCode = Helpers.LsaLookupAuthenticationPackage(hLsa, ref LSAString, out authPack); + + // input object for querying the TGT for a specific logon ID (https://docs.microsoft.com/en-us/windows/desktop/api/ntsecapi/ns-ntsecapi-_kerb_retrieve_tkt_request) + LUID userLogonID = new LUID(); + userLogonID.LowPart = data.LoginID.LowPart; + userLogonID.HighPart = 0; + tQuery.LogonId = userLogonID; + tQuery.MessageType = KERB_PROTOCOL_MESSAGE_TYPE.KerbRetrieveTicketMessage; + // indicate we want kerb creds yo' + tQuery.CacheOptions = KERB_CACHE_OPTIONS.KERB_RETRIEVE_TICKET_AS_KERB_CRED; + + // query LSA, specifying we want the the TGT data + retCode = Helpers.LsaCallAuthenticationPackage_KERB_RETRIEVE_TKT(hLsa, authPack, ref tQuery, Marshal.SizeOf(tQuery), out responsePointer, out returnBufferLength, out protocalStatus); + + if ((retCode) == 0 && (responsePointer != IntPtr.Zero)) + { + /*Console.WriteLine("\r\n UserName : {0}", username); + Console.WriteLine(" Domain : {0}", domain); + Console.WriteLine(" LogonId : {0}", data.LoginID.LowPart); + Console.WriteLine(" UserSID : {0}", sid.AccountDomainSid); + Console.WriteLine(" AuthenticationPackage : {0}", authpackage); + Console.WriteLine(" LogonType : {0}", logonType); + Console.WriteLine(" LogonType : {0}", logonTime); + Console.WriteLine(" LogonServer : {0}", logonServer); + Console.WriteLine(" LogonServerDNSDomain : {0}", dnsDomainName); + Console.WriteLine(" UserPrincipalName : {0}", upn);*/ + + // parse the returned pointer into our initial KERB_RETRIEVE_TKT_RESPONSE structure + response = (KERB_RETRIEVE_TKT_RESPONSE)Marshal.PtrToStructure((System.IntPtr)responsePointer, typeof(KERB_RETRIEVE_TKT_RESPONSE)); + + KERB_EXTERNAL_NAME serviceNameStruct = (KERB_EXTERNAL_NAME)Marshal.PtrToStructure(response.Ticket.ServiceName, typeof(KERB_EXTERNAL_NAME)); + string serviceName = Marshal.PtrToStringUni(serviceNameStruct.Names.Buffer, serviceNameStruct.Names.Length / 2).Trim(); + + string targetName = ""; + if (response.Ticket.TargetName != IntPtr.Zero) + { + KERB_EXTERNAL_NAME targetNameStruct = (KERB_EXTERNAL_NAME)Marshal.PtrToStructure(response.Ticket.TargetName, typeof(KERB_EXTERNAL_NAME)); + targetName = Marshal.PtrToStringUni(targetNameStruct.Names.Buffer, targetNameStruct.Names.Length / 2).Trim(); + } + + KERB_EXTERNAL_NAME clientNameStruct = (KERB_EXTERNAL_NAME)Marshal.PtrToStructure(response.Ticket.ClientName, typeof(KERB_EXTERNAL_NAME)); + string clientName = Marshal.PtrToStringUni(clientNameStruct.Names.Buffer, clientNameStruct.Names.Length / 2).Trim(); + + string domainName = Marshal.PtrToStringUni(response.Ticket.DomainName.Buffer, response.Ticket.DomainName.Length / 2).Trim(); + string targetDomainName = Marshal.PtrToStringUni(response.Ticket.TargetDomainName.Buffer, response.Ticket.TargetDomainName.Length / 2).Trim(); + string altTargetDomainName = Marshal.PtrToStringUni(response.Ticket.AltTargetDomainName.Buffer, response.Ticket.AltTargetDomainName.Length / 2).Trim(); + + // extract the session key + KERB_ENCRYPTION_TYPE sessionKeyType = (KERB_ENCRYPTION_TYPE)response.Ticket.SessionKey.KeyType; + Int32 sessionKeyLength = response.Ticket.SessionKey.Length; + byte[] sessionKey = new byte[sessionKeyLength]; + Marshal.Copy(response.Ticket.SessionKey.Value, sessionKey, 0, sessionKeyLength); + string base64SessionKey = Convert.ToBase64String(sessionKey); + + DateTime keyExpirationTime = DateTime.FromFileTime(response.Ticket.KeyExpirationTime); + DateTime startTime = DateTime.FromFileTime(response.Ticket.StartTime); + DateTime endTime = DateTime.FromFileTime(response.Ticket.EndTime); + DateTime renewUntil = DateTime.FromFileTime(response.Ticket.RenewUntil); + Int64 timeSkew = response.Ticket.TimeSkew; + Int32 encodedTicketSize = response.Ticket.EncodedTicketSize; + + string ticketFlags = ((KERB_TICKET_FLAGS)response.Ticket.TicketFlags).ToString(); + + // extract the TGT and base64 encode it + byte[] encodedTicket = new byte[encodedTicketSize]; + Marshal.Copy(response.Ticket.EncodedTicket, encodedTicket, 0, encodedTicketSize); + string base64TGT = Convert.ToBase64String(encodedTicket); + + results.Add(new Dictionary() + { + { "UserPrincipalName", upn }, + { "ServiceName", serviceName }, + { "TargetName", targetName }, + { "ClientName", clientName }, + { "DomainName", domainName }, + { "TargetDomainName", targetDomainName }, + { "SessionKeyType", String.Format("{0}", sessionKeyType) }, + { "Base64SessionKey", base64SessionKey }, + { "KeyExpirationTime", String.Format("{0}", keyExpirationTime) }, + { "TicketFlags", ticketFlags }, + { "StartTime", String.Format("{0}", startTime) }, + { "EndTime", String.Format("{0}", endTime) }, + { "RenewUntil", String.Format("{0}", renewUntil) }, + { "TimeSkew", String.Format("{0}", timeSkew) }, + { "EncodedTicketSize", String.Format("{0}", encodedTicketSize) }, + { "Base64EncodedTicket", base64TGT }, + }); + totalTicketCount++; + } + } + luidPtr = (IntPtr)((long)luidPtr.ToInt64() + Marshal.SizeOf(typeof(LUID))); + //move the pointer forward + Helpers.LsaFreeReturnBuffer(sessionData); + //free the SECURITY_LOGON_SESSION_DATA memory in the struct + } + Helpers.LsaFreeReturnBuffer(luidPtr); //free the array of LUIDs + + // disconnect from LSA + Helpers.LsaDeregisterLogonProcess(hLsa); + } + catch (Exception ex) + { + Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); + } + return results; + } + public static List> ListKerberosTGTDataCurrentUser() + { + List> results = new List>(); + // adapted partially from Vincent LE TOUX' work + // https://github.com/vletoux/MakeMeEnterpriseAdmin/blob/master/MakeMeEnterpriseAdmin.ps1#L2939-L2950 + // and https://www.dreamincode.net/forums/topic/135033-increment-memory-pointer-issue/ + // also Jared Atkinson's work at https://github.com/Invoke-IR/ACE/blob/master/ACE-Management/PS-ACE/Scripts/ACE_Get-KerberosTicketCache.ps1 + + try + { + string name = "kerberos"; + LSA_STRING_IN LSAString; + LSAString.Length = (ushort)name.Length; + LSAString.MaximumLength = (ushort)(name.Length + 1); + LSAString.Buffer = name; + + IntPtr responsePointer = IntPtr.Zero; + int authPack; + int returnBufferLength = 0; + int protocalStatus = 0; + IntPtr lsaHandle; + int retCode; + + // If we want to look at tickets from a session other than our own + // then we need to use LsaRegisterLogonProcess instead of LsaConnectUntrusted + retCode = Helpers.LsaConnectUntrusted(out lsaHandle); + + KERB_RETRIEVE_TKT_REQUEST tQuery = new KERB_RETRIEVE_TKT_REQUEST(); + KERB_RETRIEVE_TKT_RESPONSE response = new KERB_RETRIEVE_TKT_RESPONSE(); + + // obtains the unique identifier for the kerberos authentication package. + retCode = Helpers.LsaLookupAuthenticationPackage(lsaHandle, ref LSAString, out authPack); + + // input object for querying the TGT (https://docs.microsoft.com/en-us/windows/desktop/api/ntsecapi/ns-ntsecapi-_kerb_retrieve_tkt_request) + tQuery.LogonId = new LUID(); + tQuery.MessageType = KERB_PROTOCOL_MESSAGE_TYPE.KerbRetrieveTicketMessage; + // indicate we want kerb creds yo' + //tQuery.CacheOptions = KERB_CACHE_OPTIONS.KERB_RETRIEVE_TICKET_AS_KERB_CRED; + + // query LSA, specifying we want the the TGT data + retCode = Helpers.LsaCallAuthenticationPackage_KERB_RETRIEVE_TKT(lsaHandle, authPack, ref tQuery, Marshal.SizeOf(tQuery), out responsePointer, out returnBufferLength, out protocalStatus); + + // parse the returned pointer into our initial KERB_RETRIEVE_TKT_RESPONSE structure + response = (KERB_RETRIEVE_TKT_RESPONSE)Marshal.PtrToStructure((System.IntPtr)responsePointer, typeof(KERB_RETRIEVE_TKT_RESPONSE)); + + KERB_EXTERNAL_NAME serviceNameStruct = (KERB_EXTERNAL_NAME)Marshal.PtrToStructure(response.Ticket.ServiceName, typeof(KERB_EXTERNAL_NAME)); + string serviceName = Marshal.PtrToStringUni(serviceNameStruct.Names.Buffer, serviceNameStruct.Names.Length / 2).Trim(); + + string targetName = ""; + if (response.Ticket.TargetName != IntPtr.Zero) + { + KERB_EXTERNAL_NAME targetNameStruct = (KERB_EXTERNAL_NAME)Marshal.PtrToStructure(response.Ticket.TargetName, typeof(KERB_EXTERNAL_NAME)); + targetName = Marshal.PtrToStringUni(targetNameStruct.Names.Buffer, targetNameStruct.Names.Length / 2).Trim(); + } + + KERB_EXTERNAL_NAME clientNameStruct = (KERB_EXTERNAL_NAME)Marshal.PtrToStructure(response.Ticket.ClientName, typeof(KERB_EXTERNAL_NAME)); + string clientName = Marshal.PtrToStringUni(clientNameStruct.Names.Buffer, clientNameStruct.Names.Length / 2).Trim(); + + string domainName = Marshal.PtrToStringUni(response.Ticket.DomainName.Buffer, response.Ticket.DomainName.Length / 2).Trim(); + string targetDomainName = Marshal.PtrToStringUni(response.Ticket.TargetDomainName.Buffer, response.Ticket.TargetDomainName.Length / 2).Trim(); + string altTargetDomainName = Marshal.PtrToStringUni(response.Ticket.AltTargetDomainName.Buffer, response.Ticket.AltTargetDomainName.Length / 2).Trim(); + + // extract the session key + KERB_ENCRYPTION_TYPE sessionKeyType = (KERB_ENCRYPTION_TYPE)response.Ticket.SessionKey.KeyType; + Int32 sessionKeyLength = response.Ticket.SessionKey.Length; + byte[] sessionKey = new byte[sessionKeyLength]; + Marshal.Copy(response.Ticket.SessionKey.Value, sessionKey, 0, sessionKeyLength); + string base64SessionKey = Convert.ToBase64String(sessionKey); + + DateTime keyExpirationTime = DateTime.FromFileTime(response.Ticket.KeyExpirationTime); + DateTime startTime = DateTime.FromFileTime(response.Ticket.StartTime); + DateTime endTime = DateTime.FromFileTime(response.Ticket.EndTime); + DateTime renewUntil = DateTime.FromFileTime(response.Ticket.RenewUntil); + Int64 timeSkew = response.Ticket.TimeSkew; + Int32 encodedTicketSize = response.Ticket.EncodedTicketSize; + + string ticketFlags = ((KERB_TICKET_FLAGS)response.Ticket.TicketFlags).ToString(); + + // extract the TGT and base64 encode it + byte[] encodedTicket = new byte[encodedTicketSize]; + Marshal.Copy(response.Ticket.EncodedTicket, encodedTicket, 0, encodedTicketSize); + string base64TGT = Convert.ToBase64String(encodedTicket); + + results.Add(new Dictionary() + { + { "ServiceName", serviceName }, + { "TargetName", targetName }, + { "ClientName", clientName }, + { "DomainName", domainName }, + { "TargetDomainName", targetDomainName }, + { "SessionKeyType", String.Format("{0}", sessionKeyType) }, + { "Base64SessionKey", base64SessionKey }, + { "KeyExpirationTime", String.Format("{0}", keyExpirationTime) }, + { "TicketFlags", ticketFlags }, + { "StartTime", String.Format("{0}", startTime) }, + { "EndTime", String.Format("{0}", endTime) }, + { "RenewUntil", String.Format("{0}", renewUntil) }, + { "TimeSkew", String.Format("{0}", timeSkew) }, + { "EncodedTicketSize", String.Format("{0}", encodedTicketSize) }, + { "Base64EncodedTicket", base64TGT }, + }); + + // disconnect from LSA + Helpers.LsaDeregisterLogonProcess(lsaHandle); + } + catch (Exception ex) + { + Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); + } + return results; + } + } +} diff --git a/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Kerberos/enums/enums.cs b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Kerberos/enums/enums.cs new file mode 100644 index 0000000..34c68a7 --- /dev/null +++ b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Kerberos/enums/enums.cs @@ -0,0 +1,121 @@ +using System; + +namespace winPEAS.KnownFileCreds.Kerberos.enums +{ + + public enum SECURITY_LOGON_TYPE : uint + { + Interactive = 2, // logging on interactively. + Network, // logging using a network. + Batch, // logon for a batch process. + Service, // logon for a service account. + Proxy, // Not supported. + Unlock, // Tattempt to unlock a workstation. + NetworkCleartext, // network logon with cleartext credentials + NewCredentials, // caller can clone its current token and specify new credentials for outbound connections + RemoteInteractive, // terminal server session that is both remote and interactive + CachedInteractive, // attempt to use the cached credentials without going out across the network + CachedRemoteInteractive,// same as RemoteInteractive, except used internally for auditing purposes + CachedUnlock // attempt to unlock a workstation + } + public enum KERB_ENCRYPTION_TYPE : UInt32 + { + reserved0 = 0, + des_cbc_crc = 1, + des_cbc_md4 = 2, + des_cbc_md5 = 3, + reserved1 = 4, + des3_cbc_md5 = 5, + reserved2 = 6, + des3_cbc_sha1 = 7, + dsaWithSHA1_CmsOID = 9, + md5WithRSAEncryption_CmsOID = 10, + sha1WithRSAEncryption_CmsOID = 11, + rc2CBC_EnvOID = 12, + rsaEncryption_EnvOID = 13, + rsaES_OAEP_ENV_OID = 14, + des_ede3_cbc_Env_OID = 15, + des3_cbc_sha1_kd = 16, + aes128_cts_hmac_sha1_96 = 17, + aes256_cts_hmac_sha1_96 = 18, + aes128_cts_hmac_sha256_128 = 19, + aes256_cts_hmac_sha384_192 = 20, + rc4_hmac = 23, + rc4_hmac_exp = 24, + camellia128_cts_cmac = 25, + camellia256_cts_cmac = 26, + subkey_keymaterial = 65 + } + [Flags] + public enum KERB_TICKET_FLAGS : UInt32 + { + reserved = 2147483648, + forwardable = 0x40000000, + forwarded = 0x20000000, + proxiable = 0x10000000, + proxy = 0x08000000, + may_postdate = 0x04000000, + postdated = 0x02000000, + invalid = 0x01000000, + renewable = 0x00800000, + initial = 0x00400000, + pre_authent = 0x00200000, + hw_authent = 0x00100000, + ok_as_delegate = 0x00040000, + name_canonicalize = 0x00010000, + //cname_in_pa_data = 0x00040000, + enc_pa_rep = 0x00010000, + reserved1 = 0x00000001 + } + + + + [Flags] + public enum KERB_CACHE_OPTIONS : UInt64 + { + KERB_RETRIEVE_TICKET_DEFAULT = 0x0, + KERB_RETRIEVE_TICKET_DONT_USE_CACHE = 0x1, + KERB_RETRIEVE_TICKET_USE_CACHE_ONLY = 0x2, + KERB_RETRIEVE_TICKET_USE_CREDHANDLE = 0x4, + KERB_RETRIEVE_TICKET_AS_KERB_CRED = 0x8, + KERB_RETRIEVE_TICKET_WITH_SEC_CRED = 0x10, + KERB_RETRIEVE_TICKET_CACHE_TICKET = 0x20, + KERB_RETRIEVE_TICKET_MAX_LIFETIME = 0x40, + } + + public enum KERB_PROTOCOL_MESSAGE_TYPE : UInt32 + { + KerbDebugRequestMessage = 0, + KerbQueryTicketCacheMessage = 1, + KerbChangeMachinePasswordMessage = 2, + KerbVerifyPacMessage = 3, + KerbRetrieveTicketMessage = 4, + KerbUpdateAddressesMessage = 5, + KerbPurgeTicketCacheMessage = 6, + KerbChangePasswordMessage = 7, + KerbRetrieveEncodedTicketMessage = 8, + KerbDecryptDataMessage = 9, + KerbAddBindingCacheEntryMessage = 10, + KerbSetPasswordMessage = 11, + KerbSetPasswordExMessage = 12, + KerbVerifyCredentialsMessage = 13, + KerbQueryTicketCacheExMessage = 14, + KerbPurgeTicketCacheExMessage = 15, + KerbRefreshSmartcardCredentialsMessage = 16, + KerbAddExtraCredentialsMessage = 17, + KerbQuerySupplementalCredentialsMessage = 18, + KerbTransferCredentialsMessage = 19, + KerbQueryTicketCacheEx2Message = 20, + KerbSubmitTicketMessage = 21, + KerbAddExtraCredentialsExMessage = 22, + KerbQueryKdcProxyCacheMessage = 23, + KerbPurgeKdcProxyCacheMessage = 24, + KerbQueryTicketCacheEx3Message = 25, + KerbCleanupMachinePkinitCredsMessage = 26, + KerbAddBindingCacheEntryExMessage = 27, + KerbQueryBindingCacheMessage = 28, + KerbPurgeBindingCacheMessage = 29, + KerbQueryDomainExtendedPoliciesMessage = 30, + KerbQueryS4U2ProxyCacheMessage = 31 + } +} diff --git a/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Kerberos/structs/structs.cs b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Kerberos/structs/structs.cs new file mode 100644 index 0000000..ebfbdc3 --- /dev/null +++ b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Kerberos/structs/structs.cs @@ -0,0 +1,134 @@ +using System; +using System.Runtime.InteropServices; +using winPEAS.KnownFileCreds.Kerberos.enums; + +namespace winPEAS.KnownFileCreds.Kerberos.structs +{ + [StructLayout(LayoutKind.Sequential)] + public struct KERB_QUERY_TKT_CACHE_REQUEST + { + public KERB_PROTOCOL_MESSAGE_TYPE MessageType; + public LUID LogonId; + } + + [StructLayout(LayoutKind.Sequential)] + public struct LUID + { + public uint LowPart; + public int HighPart; + } + + [StructLayout(LayoutKind.Sequential)] + public struct LSA_STRING_IN + { + public UInt16 Length; + public UInt16 MaximumLength; + public string Buffer; + } + [StructLayout(LayoutKind.Sequential)] + public struct LSA_STRING_OUT + { + public UInt16 Length; + public UInt16 MaximumLength; + public IntPtr Buffer; + } + + [StructLayout(LayoutKind.Sequential)] + public struct SECURITY_LOGON_SESSION_DATA + { + public UInt32 Size; + public LUID LoginID; + public LSA_STRING_OUT Username; + public LSA_STRING_OUT LoginDomain; + public LSA_STRING_OUT AuthenticationPackage; + public UInt32 LogonType; + public UInt32 Session; + public IntPtr PSiD; + public UInt64 LoginTime; + public LSA_STRING_OUT LogonServer; + public LSA_STRING_OUT DnsDomainName; + public LSA_STRING_OUT Upn; + } + + [StructLayout(LayoutKind.Sequential)] + public struct KERB_QUERY_TKT_CACHE_RESPONSE + { + public KERB_PROTOCOL_MESSAGE_TYPE MessageType; + public int CountOfTickets; + // public KERB_TICKET_CACHE_INFO[] Tickets; + public IntPtr Tickets; + } + [StructLayout(LayoutKind.Sequential)] + public struct KERB_TICKET_CACHE_INFO + { + public LSA_STRING_OUT ServerName; + public LSA_STRING_OUT RealmName; + public Int64 StartTime; + public Int64 EndTime; + public Int64 RenewTime; + public Int32 EncryptionType; + public UInt32 TicketFlags; + } + [StructLayout(LayoutKind.Sequential)] + public struct KERB_RETRIEVE_TKT_RESPONSE + { + public KERB_EXTERNAL_TICKET Ticket; + } + [StructLayout(LayoutKind.Sequential)] + public struct KERB_CRYPTO_KEY + { + public Int32 KeyType; + public Int32 Length; + public IntPtr Value; + } + [StructLayout(LayoutKind.Sequential)] + public struct KERB_EXTERNAL_TICKET + { + public IntPtr ServiceName; + public IntPtr TargetName; + public IntPtr ClientName; + public LSA_STRING_OUT DomainName; + public LSA_STRING_OUT TargetDomainName; + public LSA_STRING_OUT AltTargetDomainName; + public KERB_CRYPTO_KEY SessionKey; + public UInt32 TicketFlags; + public UInt32 Flags; + public Int64 KeyExpirationTime; + public Int64 StartTime; + public Int64 EndTime; + public Int64 RenewUntil; + public Int64 TimeSkew; + public Int32 EncodedTicketSize; + public IntPtr EncodedTicket; + } + + [StructLayout(LayoutKind.Sequential)] + public struct KERB_RETRIEVE_TKT_REQUEST + { + public KERB_PROTOCOL_MESSAGE_TYPE MessageType; + public LUID LogonId; + public LSA_STRING_IN TargetName; + public UInt64 TicketFlags; + public KERB_CACHE_OPTIONS CacheOptions; + public Int64 EncryptionType; + public SECURITY_HANDLE CredentialsHandle; + } + + [StructLayout(LayoutKind.Sequential)] + public struct SECURITY_HANDLE + { + public IntPtr LowPart; + public IntPtr HighPart; + public SECURITY_HANDLE(int dummy) + { + LowPart = HighPart = IntPtr.Zero; + } + }; + [StructLayout(LayoutKind.Sequential)] + public struct KERB_EXTERNAL_NAME + { + public Int16 NameType; + public UInt16 NameCount; + public LSA_STRING_OUT Names; + } +} diff --git a/winPEAS/winPEASexe/winPEAS/KnownFileCreds/KnownFileCredsInfo.cs b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/KnownFileCredsInfo.cs new file mode 100644 index 0000000..c319b51 --- /dev/null +++ b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/KnownFileCredsInfo.cs @@ -0,0 +1,591 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Text; +using System.Text.RegularExpressions; +using Microsoft.Win32; +using winPEAS.Utils; + +namespace winPEAS.KnownFileCreds +{ + static class KnownFileCredsInfo + { + public static Dictionary GetRecentRunCommands() + { + Dictionary results = new Dictionary(); + // lists recently run commands via the RunMRU registry key + if (MyUtils.IsHighIntegrity()) + { + string[] SIDs = Registry.Users.GetSubKeyNames(); + foreach (string SID in SIDs) + { + if (SID.StartsWith("S-1-5") && !SID.EndsWith("_Classes")) + results = RegistryHelper.GetRegValues("HKU", String.Format("{0}\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RunMRU", SID)); + } + } + else + { + results = RegistryHelper.GetRegValues("HKCU", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RunMRU"); + } + return results; + } + + public static List> ListCloudCreds() + { + List> results = new List>(); + // checks for various cloud credential files (AWS, Microsoft Azure, and Google Compute) + // adapted from https://twitter.com/cmaddalena's SharpCloud project (https://github.com/chrismaddalena/SharpCloud/) + try + { + if (MyUtils.IsHighIntegrity()) + { + string userFolder = String.Format("{0}\\Users\\", Environment.GetEnvironmentVariable("SystemDrive")); + string[] dirs = Directory.GetDirectories(userFolder); + foreach (string dir in dirs) + { + string[] parts = dir.Split('\\'); + string userName = parts[parts.Length - 1]; + if (!(dir.EndsWith("Public") || dir.EndsWith("Default") || dir.EndsWith("Default User") || dir.EndsWith("All Users"))) + { + string awsKeyFile = String.Format("{0}\\.aws\\credentials", dir); + if (System.IO.File.Exists(awsKeyFile)) + { + DateTime lastAccessed = System.IO.File.GetLastAccessTime(awsKeyFile); + DateTime lastModified = System.IO.File.GetLastWriteTime(awsKeyFile); + long size = new System.IO.FileInfo(awsKeyFile).Length; + results.Add(new Dictionary() { + { "file", awsKeyFile }, + { "Description", "AWS credentials file" }, + { "Accessed", String.Format("{0}", lastAccessed) }, + { "Modified", String.Format("{0}", lastModified) }, + { "Size", String.Format("{0}", size) } + }); + } + string computeCredsDb = String.Format("{0}\\AppData\\Roaming\\gcloud\\credentials.db", dir); + if (System.IO.File.Exists(computeCredsDb)) + { + DateTime lastAccessed = System.IO.File.GetLastAccessTime(computeCredsDb); + DateTime lastModified = System.IO.File.GetLastWriteTime(computeCredsDb); + long size = new System.IO.FileInfo(computeCredsDb).Length; + results.Add(new Dictionary() { + { "file", computeCredsDb }, + { "Description", "GC Compute creds" }, + { "Accessed", String.Format("{0}", lastAccessed) }, + { "Modified", String.Format("{0}", lastModified) }, + { "Size", String.Format("{0}", size) } + }); + } + string computeLegacyCreds = String.Format("{0}\\AppData\\Roaming\\gcloud\\legacy_credentials", dir); + if (System.IO.File.Exists(computeLegacyCreds)) + { + DateTime lastAccessed = System.IO.File.GetLastAccessTime(computeLegacyCreds); + DateTime lastModified = System.IO.File.GetLastWriteTime(computeLegacyCreds); + long size = new System.IO.FileInfo(computeLegacyCreds).Length; + results.Add(new Dictionary() { + { "file", computeLegacyCreds }, + { "Description", "GC Compute creds legacy" }, + { "Accessed", String.Format("{0}", lastAccessed) }, + { "Modified", String.Format("{0}", lastModified) }, + { "Size", String.Format("{0}", size) } + }); + } + string computeAccessTokensDb = String.Format("{0}\\AppData\\Roaming\\gcloud\\access_tokens.db", dir); + if (System.IO.File.Exists(computeAccessTokensDb)) + { + DateTime lastAccessed = System.IO.File.GetLastAccessTime(computeAccessTokensDb); + DateTime lastModified = System.IO.File.GetLastWriteTime(computeAccessTokensDb); + long size = new System.IO.FileInfo(computeAccessTokensDb).Length; + results.Add(new Dictionary() { + { "file", computeAccessTokensDb }, + { "Description", "GC Compute tokens" }, + { "Accessed", String.Format("{0}", lastAccessed) }, + { "Modified", String.Format("{0}", lastModified) }, + { "Size", String.Format("{0}", size) } + }); + } + string azureTokens = String.Format("{0}\\.azure\\accessTokens.json", dir); + if (System.IO.File.Exists(azureTokens)) + { + DateTime lastAccessed = System.IO.File.GetLastAccessTime(azureTokens); + DateTime lastModified = System.IO.File.GetLastWriteTime(azureTokens); + long size = new System.IO.FileInfo(azureTokens).Length; + results.Add(new Dictionary() { + { "file", azureTokens }, + { "Description", "Azure tokens" }, + { "Accessed", String.Format("{0}", lastAccessed) }, + { "Modified", String.Format("{0}", lastModified) }, + { "Size", String.Format("{0}", size) } + }); + } + string azureProfile = String.Format("{0}\\.azure\\azureProfile.json", dir); + if (System.IO.File.Exists(azureProfile)) + { + DateTime lastAccessed = System.IO.File.GetLastAccessTime(azureProfile); + DateTime lastModified = System.IO.File.GetLastWriteTime(azureProfile); + long size = new System.IO.FileInfo(azureProfile).Length; + results.Add(new Dictionary() { + { "file", azureProfile }, + { "Description", "Azure profile" }, + { "Accessed", String.Format("{0}", lastAccessed) }, + { "Modified", String.Format("{0}", lastModified) }, + { "Size", String.Format("{0}", size) } + }); + } + } + } + } + else + { + string awsKeyFile = String.Format("{0}\\.aws\\credentials", System.Environment.GetEnvironmentVariable("USERPROFILE")); + if (System.IO.File.Exists(awsKeyFile)) + { + DateTime lastAccessed = System.IO.File.GetLastAccessTime(awsKeyFile); + DateTime lastModified = System.IO.File.GetLastWriteTime(awsKeyFile); + long size = new System.IO.FileInfo(awsKeyFile).Length; + results.Add(new Dictionary() { + { "file", awsKeyFile }, + { "Description", "AWS keys file" }, + { "Accessed", String.Format("{0}", lastAccessed) }, + { "Modified", String.Format("{0}", lastModified) }, + { "Size", String.Format("{0}", size) } + }); + } + string computeCredsDb = String.Format("{0}\\AppData\\Roaming\\gcloud\\credentials.db", System.Environment.GetEnvironmentVariable("USERPROFILE")); + if (System.IO.File.Exists(computeCredsDb)) + { + DateTime lastAccessed = System.IO.File.GetLastAccessTime(computeCredsDb); + DateTime lastModified = System.IO.File.GetLastWriteTime(computeCredsDb); + long size = new System.IO.FileInfo(computeCredsDb).Length; + results.Add(new Dictionary() { + { "file", computeCredsDb }, + { "Description", "GC Compute creds" }, + { "Accessed", String.Format("{0}", lastAccessed) }, + { "Modified", String.Format("{0}", lastModified) }, + { "Size", String.Format("{0}", size) } + }); + } + string computeLegacyCreds = String.Format("{0}\\AppData\\Roaming\\gcloud\\legacy_credentials", System.Environment.GetEnvironmentVariable("USERPROFILE")); + if (System.IO.File.Exists(computeLegacyCreds)) + { + DateTime lastAccessed = System.IO.File.GetLastAccessTime(computeLegacyCreds); + DateTime lastModified = System.IO.File.GetLastWriteTime(computeLegacyCreds); + long size = new System.IO.FileInfo(computeLegacyCreds).Length; + results.Add(new Dictionary() { + { "file", computeLegacyCreds }, + { "Description", "GC Compute creds legacy" }, + { "Accessed", String.Format("{0}", lastAccessed) }, + { "Modified", String.Format("{0}", lastModified) }, + { "Size", String.Format("{0}", size) } + }); + } + string computeAccessTokensDb = String.Format("{0}\\AppData\\Roaming\\gcloud\\access_tokens.db", System.Environment.GetEnvironmentVariable("USERPROFILE")); + if (System.IO.File.Exists(computeAccessTokensDb)) + { + DateTime lastAccessed = System.IO.File.GetLastAccessTime(computeAccessTokensDb); + DateTime lastModified = System.IO.File.GetLastWriteTime(computeAccessTokensDb); + long size = new System.IO.FileInfo(computeAccessTokensDb).Length; + results.Add(new Dictionary() { + { "file", computeAccessTokensDb }, + { "Description", "GC Compute tokens" }, + { "Accessed", String.Format("{0}", lastAccessed) }, + { "Modified", String.Format("{0}", lastModified) }, + { "Size", String.Format("{0}", size) } + }); + } + string azureTokens = String.Format("{0}\\.azure\\accessTokens.json", System.Environment.GetEnvironmentVariable("USERPROFILE")); + if (System.IO.File.Exists(azureTokens)) + { + DateTime lastAccessed = System.IO.File.GetLastAccessTime(azureTokens); + DateTime lastModified = System.IO.File.GetLastWriteTime(azureTokens); + long size = new System.IO.FileInfo(azureTokens).Length; + results.Add(new Dictionary() { + { "file", azureTokens }, + { "Description", "Azure tokens" }, + { "Accessed", String.Format("{0}", lastAccessed) }, + { "Modified", String.Format("{0}", lastModified) }, + { "Size", String.Format("{0}", size) } + }); + } + string azureProfile = String.Format("{0}\\.azure\\azureProfile.json", System.Environment.GetEnvironmentVariable("USERPROFILE")); + if (System.IO.File.Exists(azureProfile)) + { + DateTime lastAccessed = System.IO.File.GetLastAccessTime(azureProfile); + DateTime lastModified = System.IO.File.GetLastWriteTime(azureProfile); + long size = new System.IO.FileInfo(azureProfile).Length; + results.Add(new Dictionary() { + { "file", azureProfile }, + { "Description", "Azure profile" }, + { "Accessed", String.Format("{0}", lastAccessed) }, + { "Modified", String.Format("{0}", lastModified) }, + { "Size", String.Format("{0}", size) } + }); + } + } + } + catch (Exception ex) + { + Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex)); + } + return results; + } + + + public static List> GetRecentFiles() + { + // parses recent file shortcuts via COM + List> results = new List>(); + int lastDays = 7; + DateTime startTime = System.DateTime.Now.AddDays(-lastDays); + + try + { + // WshShell COM object GUID + Type shell = Type.GetTypeFromCLSID(new Guid("F935DC22-1CF0-11d0-ADB9-00C04FD58A0B")); + Object shellObj = Activator.CreateInstance(shell); + + if (MyUtils.IsHighIntegrity()) + { + string userFolder = String.Format("{0}\\Users\\", Environment.GetEnvironmentVariable("SystemDrive")); + string[] dirs = Directory.GetDirectories(userFolder); + foreach (string dir in dirs) + { + string[] parts = dir.Split('\\'); + string userName = parts[parts.Length - 1]; + + if (!(dir.EndsWith("Public") || dir.EndsWith("Default") || dir.EndsWith("Default User") || dir.EndsWith("All Users"))) + { + string recentPath = String.Format("{0}\\AppData\\Roaming\\Microsoft\\Windows\\Recent\\", dir); + try + { + string[] recentFiles = Directory.GetFiles(recentPath, "*.lnk", SearchOption.AllDirectories); + + if (recentFiles.Length != 0) + { + Console.WriteLine(" {0} :\r\n", userName); + foreach (string recentFile in recentFiles) + { + DateTime lastAccessed = System.IO.File.GetLastAccessTime(recentFile); + + if (lastAccessed > startTime) + { + // invoke the WshShell com object, creating a shortcut to then extract the TargetPath from + Object shortcut = shellObj.GetType().InvokeMember("CreateShortcut", BindingFlags.InvokeMethod, null, shellObj, new object[] { recentFile }); + Object TargetPath = shortcut.GetType().InvokeMember("TargetPath", BindingFlags.GetProperty, null, shortcut, new object[] { }); + + if (TargetPath.ToString().Trim() != "") + { + results.Add(new Dictionary() + { + { "Target", TargetPath.ToString() }, + { "Accessed", String.Format("{0}", lastAccessed) } + }); + } + Marshal.ReleaseComObject(shortcut); + shortcut = null; + } + } + } + } + catch { } + } + } + } + else + { + string recentPath = String.Format("{0}\\Microsoft\\Windows\\Recent\\", System.Environment.GetEnvironmentVariable("APPDATA")); + + string[] recentFiles = Directory.GetFiles(recentPath, "*.lnk", SearchOption.AllDirectories); + + foreach (string recentFile in recentFiles) + { + // old method (needed interop dll) + //WshShell shell = new WshShell(); + //IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(recentFile); + + DateTime lastAccessed = System.IO.File.GetLastAccessTime(recentFile); + + if (lastAccessed > startTime) + { + // invoke the WshShell com object, creating a shortcut to then extract the TargetPath from + Object shortcut = shellObj.GetType().InvokeMember("CreateShortcut", BindingFlags.InvokeMethod, null, shellObj, new object[] { recentFile }); + Object TargetPath = shortcut.GetType().InvokeMember("TargetPath", BindingFlags.GetProperty, null, shortcut, new object[] { }); + if (TargetPath.ToString().Trim() != "") + { + results.Add(new Dictionary() + { + { "Target", TargetPath.ToString() }, + { "Accessed", String.Format("{0}", lastAccessed) } + }); + } + Marshal.ReleaseComObject(shortcut); + shortcut = null; + } + } + } + // release the WshShell COM object + Marshal.ReleaseComObject(shellObj); + shellObj = null; + } + catch (Exception ex) + { + Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex)); + } + return results; + } + + public static List> ListMasterKeys() + { + List> results = new List>(); + // lists any found DPAPI master keys + try + { + if (MyUtils.IsHighIntegrity()) + { + string userFolder = String.Format("{0}\\Users\\", Environment.GetEnvironmentVariable("SystemDrive")); + string[] dirs = Directory.GetDirectories(userFolder); + foreach (string dir in dirs) + { + string[] parts = dir.Split('\\'); + string userName = parts[parts.Length - 1]; + if (!(dir.EndsWith("Public") || dir.EndsWith("Default") || dir.EndsWith("Default User") || dir.EndsWith("All Users"))) + { + List userDPAPIBasePaths = new List(); + userDPAPIBasePaths.Add(String.Format("{0}\\AppData\\Roaming\\Microsoft\\Protect\\", System.Environment.GetEnvironmentVariable("USERPROFILE"))); + userDPAPIBasePaths.Add(String.Format("{0}\\AppData\\Local\\Microsoft\\Protect\\", System.Environment.GetEnvironmentVariable("USERPROFILE"))); + + foreach (string userDPAPIBasePath in userDPAPIBasePaths) + { + if (System.IO.Directory.Exists(userDPAPIBasePath)) + { + string[] directories = Directory.GetDirectories(userDPAPIBasePath); + foreach (string directory in directories) + { + string[] files = Directory.GetFiles(directory); + + foreach (string file in files) + { + if (Regex.IsMatch(file, @"[0-9A-Fa-f]{8}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{12}")) + { + DateTime lastAccessed = System.IO.File.GetLastAccessTime(file); + DateTime lastModified = System.IO.File.GetLastWriteTime(file); + string fileName = System.IO.Path.GetFileName(file); + results.Add(new Dictionary() + { + { "MasterKey", file }, + { "Accessed", String.Format("{0}", lastAccessed) }, + { "Modified", String.Format("{0}", lastModified) }, + }); + } + } + } + } + } + } + } + } + else + { + string userName = Environment.GetEnvironmentVariable("USERNAME"); + List userDPAPIBasePaths = new List(); + userDPAPIBasePaths.Add(String.Format("{0}\\AppData\\Roaming\\Microsoft\\Protect\\", System.Environment.GetEnvironmentVariable("USERPROFILE"))); + userDPAPIBasePaths.Add(String.Format("{0}\\AppData\\Local\\Microsoft\\Protect\\", System.Environment.GetEnvironmentVariable("USERPROFILE"))); + + foreach (string userDPAPIBasePath in userDPAPIBasePaths) + { + if (System.IO.Directory.Exists(userDPAPIBasePath)) + { + string[] directories = Directory.GetDirectories(userDPAPIBasePath); + foreach (string directory in directories) + { + string[] files = Directory.GetFiles(directory); + + foreach (string file in files) + { + if (Regex.IsMatch(file, @"[0-9A-Fa-f]{8}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{12}")) + { + DateTime lastAccessed = System.IO.File.GetLastAccessTime(file); + DateTime lastModified = System.IO.File.GetLastWriteTime(file); + string fileName = System.IO.Path.GetFileName(file); + results.Add(new Dictionary() + { + { "MasterKey", file }, + { "Accessed", String.Format("{0}", lastAccessed) }, + { "Modified", String.Format("{0}", lastModified) }, + }); + } + } + } + } + } + } + } + catch (Exception ex) + { + Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); + } + return results; + } + + public static List> GetCredFiles() + { + List> results = new List>(); + // lists any found files in Local\Microsoft\Credentials\* + try + { + if (MyUtils.IsHighIntegrity()) + { + string userFolder = String.Format("{0}\\Users\\", Environment.GetEnvironmentVariable("SystemDrive")); + string[] dirs = Directory.GetDirectories(userFolder); + + foreach (string dir in dirs) + { + string[] parts = dir.Split('\\'); + string userName = parts[parts.Length - 1]; + if (!(dir.EndsWith("Public") || dir.EndsWith("Default") || dir.EndsWith("Default User") || dir.EndsWith("All Users"))) + { + List userCredFilePaths = new List(); + userCredFilePaths.Add(String.Format("{0}\\AppData\\Local\\Microsoft\\Credentials\\", dir)); + userCredFilePaths.Add(String.Format("{0}\\AppData\\Roaming\\Microsoft\\Credentials\\", dir)); + + foreach (string userCredFilePath in userCredFilePaths) + { + if (System.IO.Directory.Exists(userCredFilePath)) + { + string[] systemFiles = Directory.GetFiles(userCredFilePath); + if ((systemFiles != null) && (systemFiles.Length != 0)) + { + foreach (string file in systemFiles) + { + DateTime lastAccessed = System.IO.File.GetLastAccessTime(file); + DateTime lastModified = System.IO.File.GetLastWriteTime(file); + long size = new System.IO.FileInfo(file).Length; + string fileName = System.IO.Path.GetFileName(file); + + // jankily parse the bytes to extract the credential type and master key GUID + // reference- https://github.com/gentilkiwi/mimikatz/blob/3d8be22fff9f7222f9590aa007629e18300cf643/modules/kull_m_dpapi.h#L24-L54 + byte[] credentialArray = File.ReadAllBytes(file); + byte[] guidMasterKeyArray = new byte[16]; + Array.Copy(credentialArray, 36, guidMasterKeyArray, 0, 16); + Guid guidMasterKey = new Guid(guidMasterKeyArray); + + byte[] stringLenArray = new byte[16]; + Array.Copy(credentialArray, 56, stringLenArray, 0, 4); + int descLen = BitConverter.ToInt32(stringLenArray, 0); + + byte[] descBytes = new byte[descLen]; + Array.Copy(credentialArray, 60, descBytes, 0, descLen - 4); + + string desc = Encoding.Unicode.GetString(descBytes); + results.Add(new Dictionary() + { + { "CredFile", file }, + { "Description", desc }, + { "MasterKey", String.Format("{0}", guidMasterKey) }, + { "Accessed", String.Format("{0}", lastAccessed) }, + { "Modified", String.Format("{0}", lastModified) }, + { "Size", String.Format("{0}", size) }, + }); + } + } + } + } + } + } + + string systemFolder = String.Format("{0}\\System32\\config\\systemprofile\\AppData\\Local\\Microsoft\\Credentials", Environment.GetEnvironmentVariable("SystemRoot")); + string[] files = Directory.GetFiles(systemFolder); + if ((files != null) && (files.Length != 0)) + { + foreach (string file in files) + { + DateTime lastAccessed = System.IO.File.GetLastAccessTime(file); + DateTime lastModified = System.IO.File.GetLastWriteTime(file); + long size = new System.IO.FileInfo(file).Length; + string fileName = System.IO.Path.GetFileName(file); + + // jankily parse the bytes to extract the credential type and master key GUID + // reference- https://github.com/gentilkiwi/mimikatz/blob/3d8be22fff9f7222f9590aa007629e18300cf643/modules/kull_m_dpapi.h#L24-L54 + byte[] credentialArray = File.ReadAllBytes(file); + byte[] guidMasterKeyArray = new byte[16]; + Array.Copy(credentialArray, 36, guidMasterKeyArray, 0, 16); + Guid guidMasterKey = new Guid(guidMasterKeyArray); + + byte[] stringLenArray = new byte[16]; + Array.Copy(credentialArray, 56, stringLenArray, 0, 4); + int descLen = BitConverter.ToInt32(stringLenArray, 0); + + byte[] descBytes = new byte[descLen]; + Array.Copy(credentialArray, 60, descBytes, 0, descLen - 4); + + string desc = Encoding.Unicode.GetString(descBytes); + results.Add(new Dictionary() + { + { "CredFile", file }, + { "Description", desc }, + { "MasterKey", String.Format("{0}", guidMasterKey) }, + { "Accessed", String.Format("{0}", lastAccessed) }, + { "Modified", String.Format("{0}", lastModified) }, + { "Size", String.Format("{0}", size) }, + }); + } + } + } + else + { + string userName = Environment.GetEnvironmentVariable("USERNAME"); + List userCredFilePaths = new List(); + userCredFilePaths.Add(String.Format("{0}\\AppData\\Local\\Microsoft\\Credentials\\", System.Environment.GetEnvironmentVariable("USERPROFILE"))); + userCredFilePaths.Add(String.Format("{0}\\AppData\\Roaming\\Microsoft\\Credentials\\", System.Environment.GetEnvironmentVariable("USERPROFILE"))); + + foreach (string userCredFilePath in userCredFilePaths) + { + if (System.IO.Directory.Exists(userCredFilePath)) + { + string[] files = Directory.GetFiles(userCredFilePath); + + foreach (string file in files) + { + DateTime lastAccessed = System.IO.File.GetLastAccessTime(file); + DateTime lastModified = System.IO.File.GetLastWriteTime(file); + long size = new System.IO.FileInfo(file).Length; + string fileName = System.IO.Path.GetFileName(file); + + // jankily parse the bytes to extract the credential type and master key GUID + // reference- https://github.com/gentilkiwi/mimikatz/blob/3d8be22fff9f7222f9590aa007629e18300cf643/modules/kull_m_dpapi.h#L24-L54 + byte[] credentialArray = File.ReadAllBytes(file); + byte[] guidMasterKeyArray = new byte[16]; + Array.Copy(credentialArray, 36, guidMasterKeyArray, 0, 16); + Guid guidMasterKey = new Guid(guidMasterKeyArray); + + byte[] stringLenArray = new byte[16]; + Array.Copy(credentialArray, 56, stringLenArray, 0, 4); + int descLen = BitConverter.ToInt32(stringLenArray, 0); + + byte[] descBytes = new byte[descLen]; + Array.Copy(credentialArray, 60, descBytes, 0, descLen - 4); + + string desc = Encoding.Unicode.GetString(descBytes); + results.Add(new Dictionary() + { + { "CredFile", file }, + { "Description", desc }, + { "MasterKey", String.Format("{0}", guidMasterKey) }, + { "Accessed", String.Format("{0}", lastAccessed) }, + { "Modified", String.Format("{0}", lastModified) }, + { "Size", String.Format("{0}", size) }, + }); + } + } + } + } + } + catch (Exception ex) + { + Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); + } + return results; + } + } +} diff --git a/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Putty.cs b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Putty.cs new file mode 100644 index 0000000..ca8bcd4 --- /dev/null +++ b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Putty.cs @@ -0,0 +1,144 @@ +using System; +using System.Collections.Generic; +using Microsoft.Win32; +using winPEAS.Utils; + +namespace winPEAS.KnownFileCreds +{ + static class Putty + { + public static List> GetPuttySessions() + { + List> results = new List>(); + // extracts saved putty sessions and basic configs (via the registry) + if (MyUtils.IsHighIntegrity()) + { + Console.WriteLine("\r\n\r\n=== Putty Saved Session Information (All Users) ===\r\n"); + + string[] SIDs = Registry.Users.GetSubKeyNames(); + foreach (string SID in SIDs) + { + if (SID.StartsWith("S-1-5") && !SID.EndsWith("_Classes")) + { + string[] subKeys = RegistryHelper.GetRegSubkeys("HKU", String.Format("{0}\\Software\\SimonTatham\\PuTTY\\Sessions\\", SID)); + + foreach (string sessionName in subKeys) + { + Dictionary putty_sess = new Dictionary() + { + { "User SID", SID }, + { "SessionName", sessionName }, + { "HostName", "" }, + { "PortNumber", ""}, + { "UserName", "" }, + { "PublicKeyFile", "" }, + { "PortForwardings", "" }, + { "ConnectionSharing", "" }, + { "ProxyPassword", "" }, + { "ProxyUsername", "" }, + }; + + string[] keys = + { + "HostName", + "PortNumber", + "UserName", + "PublicKeyFile", + "PortForwardings", + "ConnectionSharing", + "ProxyPassword", + "ProxyUsername", + }; + + foreach (string key in keys) + putty_sess[key] = RegistryHelper.GetRegValue("HKU", String.Format("{0}\\Software\\SimonTatham\\PuTTY\\Sessions\\{1}", SID, sessionName), key); + + results.Add(putty_sess); + } + } + } + } + else + { + string[] subKeys = RegistryHelper.GetRegSubkeys("HKCU", "Software\\SimonTatham\\PuTTY\\Sessions\\"); + foreach (string sessionName in subKeys) + { + Dictionary putty_sess = new Dictionary() + { + { "SessionName", sessionName }, + { "HostName", "" }, + { "PortNumber", "" }, + { "UserName", "" }, + { "PublicKeyFile", "" }, + { "PortForwardings", "" }, + { "ConnectionSharing", "" }, + { "ProxyPassword", "" }, + { "ProxyUsername", "" }, + }; + + string[] keys = + { + "HostName", + "PortNumber", + "UserName", + "PublicKeyFile", + "PortForwardings", + "ConnectionSharing", + "ProxyPassword", + "ProxyUsername", + }; + + foreach (string key in keys) + putty_sess[key] = RegistryHelper.GetRegValue("HKCU", String.Format("Software\\SimonTatham\\PuTTY\\Sessions\\{0}", sessionName), key); + + results.Add(putty_sess); + } + } + return results; + } + + + public static List> ListPuttySSHHostKeys() + { + List> results = new List>(); + // extracts saved putty host keys (via the registry) + if (MyUtils.IsHighIntegrity()) + { + Console.WriteLine("\r\n\r\n=== Putty SSH Host Hosts (All Users) ===\r\n"); + + string[] SIDs = Registry.Users.GetSubKeyNames(); + foreach (string SID in SIDs) + { + if (SID.StartsWith("S-1-5") && !SID.EndsWith("_Classes")) + { + Dictionary hostKeys = RegistryHelper.GetRegValues("HKU", String.Format("{0}\\Software\\SimonTatham\\PuTTY\\SshHostKeys\\", SID)); + if ((hostKeys != null) && (hostKeys.Count != 0)) + { + Dictionary putty_ssh = new Dictionary(); + putty_ssh["UserSID"] = SID; + foreach (KeyValuePair kvp in hostKeys) + { + putty_ssh[kvp.Key] = ""; //Looks like only matters the key name, not the value + } + results.Add(putty_ssh); + } + } + } + } + else + { + Dictionary hostKeys = RegistryHelper.GetRegValues("HKCU", "Software\\SimonTatham\\PuTTY\\SshHostKeys\\"); + if ((hostKeys != null) && (hostKeys.Count != 0)) + { + Dictionary putty_ssh = new Dictionary(); + foreach (KeyValuePair kvp in hostKeys) + { + putty_ssh[kvp.Key] = ""; //Looks like only matters the key name, not the value + } + results.Add(putty_ssh); + } + } + return results; + } + } +} diff --git a/winPEAS/winPEASexe/winPEAS/KnownFileCreds/RemoteDesktop.cs b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/RemoteDesktop.cs new file mode 100644 index 0000000..b921add --- /dev/null +++ b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/RemoteDesktop.cs @@ -0,0 +1,146 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml; +using Microsoft.Win32; +using winPEAS.Utils; + +namespace winPEAS.KnownFileCreds +{ + static class RemoteDesktop + { + public static List> GetSavedRDPConnections() + { + List> results = new List>(); + //shows saved RDP connections, including username hints (if present) + if (MyUtils.IsHighIntegrity()) + { + string[] SIDs = Registry.Users.GetSubKeyNames(); + foreach (string SID in SIDs) + { + if (SID.StartsWith("S-1-5") && !SID.EndsWith("_Classes")) + { + string[] subkeys = RegistryHelper.GetRegSubkeys("HKU", String.Format("{0}\\Software\\Microsoft\\Terminal Server Client\\Servers", SID)); + if (subkeys != null) + { + //Console.WriteLine("\r\n\r\n=== Saved RDP Connection Information ({0}) ===", SID); + foreach (string host in subkeys) + { + string usernameHint = RegistryHelper.GetRegValue("HKCU", String.Format("Software\\Microsoft\\Terminal Server Client\\Servers\\{0}", host), "UsernameHint"); + Dictionary rdp_info = new Dictionary() { + { "SID", SID }, + { "Host", host }, + { "Username Hint", usernameHint }, + }; + results.Add(rdp_info); + } + } + } + } + } + else + { + string[] subkeys = RegistryHelper.GetRegSubkeys("HKCU", "Software\\Microsoft\\Terminal Server Client\\Servers"); + if (subkeys != null) + { + foreach (string host in subkeys) + { + string usernameHint = RegistryHelper.GetRegValue("HKCU", String.Format("Software\\Microsoft\\Terminal Server Client\\Servers\\{0}", host), "UsernameHint"); + Dictionary rdp_info = new Dictionary() { + { "SID", "" }, + { "Host", host }, + { "Username Hint", usernameHint }, + }; + results.Add(rdp_info); + } + } + } + return results; + } + + public static List> GetRDCManFiles() + { + List> results = new List>(); + // lists any found files in Local\Microsoft\Credentials\* + try + { + if (MyUtils.IsHighIntegrity()) + { + string userFolder = String.Format("{0}\\Users\\", Environment.GetEnvironmentVariable("SystemDrive")); + string[] dirs = Directory.GetDirectories(userFolder); + + foreach (string dir in dirs) + { + string[] parts = dir.Split('\\'); + string userName = parts[parts.Length - 1]; + if (!(dir.EndsWith("Public") || dir.EndsWith("Default") || dir.EndsWith("Default User") || dir.EndsWith("All Users"))) + { + string userRDManFile = String.Format("{0}\\AppData\\Local\\Microsoft\\Remote Desktop Connection Manager\\RDCMan.settings", dir); + if (System.IO.File.Exists(userRDManFile)) + { + XmlDocument xmlDoc = new XmlDocument(); + xmlDoc.Load(userRDManFile); + + // grab the recent RDG files + XmlNodeList filesToOpen = xmlDoc.GetElementsByTagName("FilesToOpen"); + XmlNodeList items = filesToOpen[0].ChildNodes; + XmlNode node = items[0]; + + DateTime lastAccessed = System.IO.File.GetLastAccessTime(userRDManFile); + DateTime lastModified = System.IO.File.GetLastWriteTime(userRDManFile); + Dictionary rdg = new Dictionary(){ + { "RDCManFile", userRDManFile }, + { "Accessed", String.Format("{0}", lastAccessed) }, + { "Modified", String.Format("{0}", lastModified) }, + { ".RDG Files", "" }, + }; + + foreach (XmlNode rdgFile in items) + rdg[".RDG Files"] += rdgFile.InnerText; + + results.Add(rdg); + } + } + } + } + else + { + string userName = Environment.GetEnvironmentVariable("USERNAME"); + string userRDManFile = String.Format("{0}\\AppData\\Local\\Microsoft\\Remote Desktop Connection Manager\\RDCMan.settings", System.Environment.GetEnvironmentVariable("USERPROFILE")); + + if (System.IO.File.Exists(userRDManFile)) + { + XmlDocument xmlDoc = new XmlDocument(); + xmlDoc.Load(userRDManFile); + + // grab the recent RDG files + XmlNodeList filesToOpen = xmlDoc.GetElementsByTagName("FilesToOpen"); + XmlNodeList items = filesToOpen[0].ChildNodes; + XmlNode node = items[0]; + + DateTime lastAccessed = System.IO.File.GetLastAccessTime(userRDManFile); + DateTime lastModified = System.IO.File.GetLastWriteTime(userRDManFile); + Dictionary rdg = new Dictionary(){ + { "RDCManFile", userRDManFile }, + { "Accessed", String.Format("{0}", lastAccessed) }, + { "Modified", String.Format("{0}", lastModified) }, + { ".RDG Files", "" }, + }; + + foreach (XmlNode rdgFile in items) + rdg[".RDG Files"] += rdgFile.InnerText; + results.Add(rdg); + } + } + } + catch (Exception ex) + { + Beaprint.PrintException(ex.Message); + } + return results; + } + } +} diff --git a/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Vault/VaultCli.cs b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Vault/VaultCli.cs new file mode 100644 index 0000000..2683831 --- /dev/null +++ b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Vault/VaultCli.cs @@ -0,0 +1,252 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Runtime.InteropServices; +using winPEAS.KnownFileCreds.Vault.structs; + +namespace winPEAS.KnownFileCreds.Vault +{ + public static class VaultCli + { + // pulled directly from @djhohnstein's SharpWeb project: https://github.com/djhohnstein/SharpWeb/blob/master/Edge/SharpEdge.cs + + [DllImport("vaultcli.dll")] + public extern static Int32 VaultOpenVault(ref Guid vaultGuid, UInt32 offset, ref IntPtr vaultHandle); + + [DllImport("vaultcli.dll")] + public extern static Int32 VaultEnumerateVaults(Int32 offset, ref Int32 vaultCount, ref IntPtr vaultGuid); + + [DllImport("vaultcli.dll")] + public extern static Int32 VaultEnumerateItems(IntPtr vaultHandle, Int32 chunkSize, ref Int32 vaultItemCount, ref IntPtr vaultItem); + + [DllImport("vaultcli.dll", EntryPoint = "VaultGetItem")] + public extern static Int32 VaultGetItem_WIN8(IntPtr vaultHandle, ref Guid schemaId, IntPtr pResourceElement, IntPtr pIdentityElement, IntPtr pPackageSid, IntPtr zero, Int32 arg6, ref IntPtr passwordVaultPtr); + + [DllImport("vaultcli.dll", EntryPoint = "VaultGetItem")] + public extern static Int32 VaultGetItem_WIN7(IntPtr vaultHandle, ref Guid schemaId, IntPtr pResourceElement, IntPtr pIdentityElement, IntPtr zero, Int32 arg5, ref IntPtr passwordVaultPtr); + + public static List> DumpVault() + { + List> results = new List>(); + + try + { + // pulled directly from @djhohnstein's SharpWeb project: https://github.com/djhohnstein/SharpWeb/blob/master/Edge/SharpEdge.cs + var OSVersion = Environment.OSVersion.Version; + var OSMajor = OSVersion.Major; + var OSMinor = OSVersion.Minor; + + Type VAULT_ITEM; + + if (OSMajor >= 6 && OSMinor >= 2) + { + VAULT_ITEM = typeof(VAULT_ITEM_WIN8); + } + else + { + VAULT_ITEM = typeof(VAULT_ITEM_WIN7); + } + + Int32 vaultCount = 0; + IntPtr vaultGuidPtr = IntPtr.Zero; + var result = VaultCli.VaultEnumerateVaults(0, ref vaultCount, ref vaultGuidPtr); + + //var result = CallVaultEnumerateVaults(VaultEnum, 0, ref vaultCount, ref vaultGuidPtr); + + if ((int)result != 0) + { + Console.WriteLine(" [ERROR] Unable to enumerate vaults. Error (0x" + result.ToString() + ")"); + return results; + } + + // Create dictionary to translate Guids to human readable elements + IntPtr guidAddress = vaultGuidPtr; + Dictionary vaultSchema = new Dictionary(); + vaultSchema.Add(new Guid("2F1A6504-0641-44CF-8BB5-3612D865F2E5"), "Windows Secure Note"); + vaultSchema.Add(new Guid("3CCD5499-87A8-4B10-A215-608888DD3B55"), "Windows Web Password Credential"); + vaultSchema.Add(new Guid("154E23D0-C644-4E6F-8CE6-5069272F999F"), "Windows Credential Picker Protector"); + vaultSchema.Add(new Guid("4BF4C442-9B8A-41A0-B380-DD4A704DDB28"), "Web Credentials"); + vaultSchema.Add(new Guid("77BC582B-F0A6-4E15-4E80-61736B6F3B29"), "Windows Credentials"); + vaultSchema.Add(new Guid("E69D7838-91B5-4FC9-89D5-230D4D4CC2BC"), "Windows Domain Certificate Credential"); + vaultSchema.Add(new Guid("3E0E35BE-1B77-43E7-B873-AED901B6275B"), "Windows Domain Password Credential"); + vaultSchema.Add(new Guid("3C886FF3-2669-4AA2-A8FB-3F6759A77548"), "Windows Extended Credential"); + vaultSchema.Add(new Guid("00000000-0000-0000-0000-000000000000"), null); + + for (int i = 0; i < vaultCount; i++) + { + + // Open vault block + object vaultGuidString = System.Runtime.InteropServices.Marshal.PtrToStructure(guidAddress, typeof(Guid)); + Guid vaultGuid = new Guid(vaultGuidString.ToString()); + guidAddress = (IntPtr)(guidAddress.ToInt64() + System.Runtime.InteropServices.Marshal.SizeOf(typeof(Guid))); + IntPtr vaultHandle = IntPtr.Zero; + string vaultType; + if (vaultSchema.ContainsKey(vaultGuid)) + { + vaultType = vaultSchema[vaultGuid]; + } + else + { + vaultType = vaultGuid.ToString(); + } + result = VaultCli.VaultOpenVault(ref vaultGuid, (UInt32)0, ref vaultHandle); + if (result != 0) + { + Console.WriteLine("Unable to open the following vault: " + vaultType + ". Error: 0x" + result.ToString()); + continue; + } + // Vault opened successfully! Continue. + + // Fetch all items within Vault + int vaultItemCount = 0; + IntPtr vaultItemPtr = IntPtr.Zero; + result = VaultCli.VaultEnumerateItems(vaultHandle, 512, ref vaultItemCount, ref vaultItemPtr); + if (result != 0) + { + Console.WriteLine("Unable to enumerate vault items from the following vault: " + vaultType + ". Error 0x" + result.ToString()); + continue; + } + var structAddress = vaultItemPtr; + if (vaultItemCount > 0) + { + // For each vault item... + for (int j = 1; j <= vaultItemCount; j++) + { + Dictionary vault_cred = new Dictionary() { + { "GUID", String.Format("{0}", vaultGuid) }, + { "Type", vaultType }, + { "Resource", "" }, + { "Identity", "" }, + { "PacakgeSid", "" }, + { "Credential", "" }, + { "Last Modified", "" }, + { "Error", "" } + }; + + // Begin fetching vault item... + var currentItem = System.Runtime.InteropServices.Marshal.PtrToStructure(structAddress, VAULT_ITEM); + structAddress = (IntPtr)(structAddress.ToInt64() + System.Runtime.InteropServices.Marshal.SizeOf(VAULT_ITEM)); + + IntPtr passwordVaultItem = IntPtr.Zero; + // Field Info retrieval + FieldInfo schemaIdInfo = currentItem.GetType().GetField("SchemaId"); + Guid schemaId = new Guid(schemaIdInfo.GetValue(currentItem).ToString()); + FieldInfo pResourceElementInfo = currentItem.GetType().GetField("pResourceElement"); + IntPtr pResourceElement = (IntPtr)pResourceElementInfo.GetValue(currentItem); + FieldInfo pIdentityElementInfo = currentItem.GetType().GetField("pIdentityElement"); + IntPtr pIdentityElement = (IntPtr)pIdentityElementInfo.GetValue(currentItem); + FieldInfo dateTimeInfo = currentItem.GetType().GetField("LastModified"); + UInt64 lastModified = (UInt64)dateTimeInfo.GetValue(currentItem); + + IntPtr pPackageSid = IntPtr.Zero; + if (OSMajor >= 6 && OSMinor >= 2) + { + // Newer versions have package sid + FieldInfo pPackageSidInfo = currentItem.GetType().GetField("pPackageSid"); + pPackageSid = (IntPtr)pPackageSidInfo.GetValue(currentItem); + result = VaultCli.VaultGetItem_WIN8(vaultHandle, ref schemaId, pResourceElement, pIdentityElement, pPackageSid, IntPtr.Zero, 0, ref passwordVaultItem); + } + else + { + result = VaultCli.VaultGetItem_WIN7(vaultHandle, ref schemaId, pResourceElement, pIdentityElement, IntPtr.Zero, 0, ref passwordVaultItem); + } + + if (result != 0) + { + vault_cred["Error"] = "Occured while retrieving vault item. Error: 0x" + result.ToString(); + continue; + } + object passwordItem = System.Runtime.InteropServices.Marshal.PtrToStructure(passwordVaultItem, VAULT_ITEM); + FieldInfo pAuthenticatorElementInfo = passwordItem.GetType().GetField("pAuthenticatorElement"); + IntPtr pAuthenticatorElement = (IntPtr)pAuthenticatorElementInfo.GetValue(passwordItem); + // Fetch the credential from the authenticator element + object cred = GetVaultElementValue(pAuthenticatorElement); + object packageSid = null; + if (pPackageSid != IntPtr.Zero && pPackageSid != null) + { + packageSid = GetVaultElementValue(pPackageSid); + } + if (cred != null) // Indicates successful fetch + { + object resource = GetVaultElementValue(pResourceElement); + if (resource != null) + { + vault_cred["Resource"] = String.Format("{0}", resource); + } + object identity = GetVaultElementValue(pIdentityElement); + if (identity != null) + { + vault_cred["Identity"] = String.Format("{0}", identity); + } + if (packageSid != null) + { + vault_cred["PacakgeSid"] = String.Format("{0}", packageSid); + } + vault_cred["Credential"] = String.Format("{0}", cred); + vault_cred["Last Modified"] = String.Format("{0}", System.DateTime.FromFileTimeUtc((long)lastModified)); + results.Add(vault_cred); + } + } + } + } + } + catch (Exception ex) + { + Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); + } + return results; + } + + private static object GetVaultElementValue(IntPtr vaultElementPtr) + { + // Helper function to extract the ItemValue field from a VAULT_ITEM_ELEMENT struct + // pulled directly from @djhohnstein's SharpWeb project: https://github.com/djhohnstein/SharpWeb/blob/master/Edge/SharpEdge.cs + object results; + object partialElement = System.Runtime.InteropServices.Marshal.PtrToStructure(vaultElementPtr, typeof(VAULT_ITEM_ELEMENT)); + FieldInfo partialElementInfo = partialElement.GetType().GetField("Type"); + var partialElementType = partialElementInfo.GetValue(partialElement); + + IntPtr elementPtr = (IntPtr)(vaultElementPtr.ToInt64() + 16); + switch ((int)partialElementType) + { + case 7: // VAULT_ELEMENT_TYPE == String; These are the plaintext passwords! + IntPtr StringPtr = System.Runtime.InteropServices.Marshal.ReadIntPtr(elementPtr); + results = System.Runtime.InteropServices.Marshal.PtrToStringUni(StringPtr); + break; + case 0: // VAULT_ELEMENT_TYPE == bool + results = System.Runtime.InteropServices.Marshal.ReadByte(elementPtr); + results = (bool)results; + break; + case 1: // VAULT_ELEMENT_TYPE == Short + results = System.Runtime.InteropServices.Marshal.ReadInt16(elementPtr); + break; + case 2: // VAULT_ELEMENT_TYPE == Unsigned Short + results = System.Runtime.InteropServices.Marshal.ReadInt16(elementPtr); + break; + case 3: // VAULT_ELEMENT_TYPE == Int + results = System.Runtime.InteropServices.Marshal.ReadInt32(elementPtr); + break; + case 4: // VAULT_ELEMENT_TYPE == Unsigned Int + results = System.Runtime.InteropServices.Marshal.ReadInt32(elementPtr); + break; + case 5: // VAULT_ELEMENT_TYPE == Double + results = System.Runtime.InteropServices.Marshal.PtrToStructure(elementPtr, typeof(Double)); + break; + case 6: // VAULT_ELEMENT_TYPE == GUID + results = System.Runtime.InteropServices.Marshal.PtrToStructure(elementPtr, typeof(Guid)); + break; + case 12: // VAULT_ELEMENT_TYPE == Sid + IntPtr sidPtr = System.Runtime.InteropServices.Marshal.ReadIntPtr(elementPtr); + var sidObject = new System.Security.Principal.SecurityIdentifier(sidPtr); + results = sidObject.Value; + break; + default: + /* Several VAULT_ELEMENT_TYPES are currently unimplemented according to + * Lord Graeber. Thus we do not implement them. */ + results = null; + break; + } + return results; + } + } +} diff --git a/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Vault/enums/VAULT_ELEMENT_TYPE.cs b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Vault/enums/VAULT_ELEMENT_TYPE.cs new file mode 100644 index 0000000..c8df2b5 --- /dev/null +++ b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Vault/enums/VAULT_ELEMENT_TYPE.cs @@ -0,0 +1,23 @@ +using System; + +namespace winPEAS.KnownFileCreds.Vault.enums +{ + public enum VAULT_ELEMENT_TYPE : Int32 + { + Undefined = -1, + Boolean = 0, + Short = 1, + UnsignedShort = 2, + Int = 3, + UnsignedInt = 4, + Double = 5, + Guid = 6, + String = 7, + ByteArray = 8, + TimeStamp = 9, + ProtectedArray = 10, + Attribute = 11, + Sid = 12, + Last = 13 + } +} diff --git a/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Vault/enums/VAULT_SCHEMA_ELEMENT_ID.cs b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Vault/enums/VAULT_SCHEMA_ELEMENT_ID.cs new file mode 100644 index 0000000..a30b2a9 --- /dev/null +++ b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Vault/enums/VAULT_SCHEMA_ELEMENT_ID.cs @@ -0,0 +1,16 @@ +using System; + +namespace winPEAS.KnownFileCreds.Vault.enums +{ + public enum VAULT_SCHEMA_ELEMENT_ID : Int32 + { + Illegal = 0, + Resource = 1, + Identity = 2, + Authenticator = 3, + Tag = 4, + PackageSid = 5, + AppStart = 100, + AppEnd = 10000 + } +} diff --git a/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Vault/structs/VAULT_ITEM_ELEMENT.cs b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Vault/structs/VAULT_ITEM_ELEMENT.cs new file mode 100644 index 0000000..46d917a --- /dev/null +++ b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Vault/structs/VAULT_ITEM_ELEMENT.cs @@ -0,0 +1,14 @@ +using System.Runtime.InteropServices; +using winPEAS.KnownFileCreds.Vault.enums; + +namespace winPEAS.KnownFileCreds.Vault.structs +{ + [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi)] + public struct VAULT_ITEM_ELEMENT + { + [FieldOffset(0)] + public VAULT_SCHEMA_ELEMENT_ID SchemaElementId; + [FieldOffset(8)] + public VAULT_ELEMENT_TYPE Type; + } +} diff --git a/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Vault/structs/VAULT_ITEM_WIN7.cs b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Vault/structs/VAULT_ITEM_WIN7.cs new file mode 100644 index 0000000..877eeed --- /dev/null +++ b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Vault/structs/VAULT_ITEM_WIN7.cs @@ -0,0 +1,19 @@ +using System; +using System.Runtime.InteropServices; + +namespace winPEAS.KnownFileCreds.Vault.structs +{ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct VAULT_ITEM_WIN7 + { + public Guid SchemaId; + public IntPtr pszCredentialFriendlyName; + public IntPtr pResourceElement; + public IntPtr pIdentityElement; + public IntPtr pAuthenticatorElement; + public UInt64 LastModified; + public UInt32 dwFlags; + public UInt32 dwPropertiesCount; + public IntPtr pPropertyElements; + } +} diff --git a/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Vault/structs/VAULT_ITEM_WIN8.cs b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Vault/structs/VAULT_ITEM_WIN8.cs new file mode 100644 index 0000000..94b2240 --- /dev/null +++ b/winPEAS/winPEASexe/winPEAS/KnownFileCreds/Vault/structs/VAULT_ITEM_WIN8.cs @@ -0,0 +1,20 @@ +using System; +using System.Runtime.InteropServices; + +namespace winPEAS.KnownFileCreds.Vault.structs +{ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct VAULT_ITEM_WIN8 + { + public Guid SchemaId; + public IntPtr pszCredentialFriendlyName; + public IntPtr pResourceElement; + public IntPtr pIdentityElement; + public IntPtr pAuthenticatorElement; + public IntPtr pPackageSid; + public UInt64 LastModified; + public UInt32 dwFlags; + public UInt32 dwPropertiesCount; + public IntPtr pPropertyElements; + } +} diff --git a/winPEAS/winPEASexe/winPEAS/KnownFileCredsInfo.cs b/winPEAS/winPEASexe/winPEAS/KnownFileCredsInfo.cs deleted file mode 100755 index 6f09b6d..0000000 --- a/winPEAS/winPEASexe/winPEAS/KnownFileCredsInfo.cs +++ /dev/null @@ -1,2578 +0,0 @@ -using Microsoft.Win32; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Reflection; -using System.Runtime.InteropServices; -using System.Text; -using System.Text.RegularExpressions; -using System.Web.Script.Serialization; -using System.Xml; - - -namespace winPEAS -{ - class KnownFileCredsInfo - { - - private KnownFileCredsInfo() { } - public static List GetFirefoxDbs() - { - List results = new List(); - // checks if Firefox has a history database - try - { - if (MyUtils.IsHighIntegrity()) - { - string userFolder = String.Format("{0}\\Users\\", Environment.GetEnvironmentVariable("SystemDrive")); - string[] dirs = Directory.GetDirectories(userFolder); - foreach (string dir in dirs) - { - string[] parts = dir.Split('\\'); - string userName = parts[parts.Length - 1]; - if (!(dir.EndsWith("Public") || dir.EndsWith("Default") || dir.EndsWith("Default User") || dir.EndsWith("All Users"))) - { - string userFirefoxBasePath = String.Format("{0}\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\", dir); - if (System.IO.Directory.Exists(userFirefoxBasePath)) - { - string[] directories = Directory.GetDirectories(userFirefoxBasePath); - foreach (string directory in directories) - { - string firefoxCredentialFile3 = String.Format("{0}\\{1}", directory, "key3.db"); - if (System.IO.File.Exists(firefoxCredentialFile3)) - results.Add(firefoxCredentialFile3); - - string firefoxCredentialFile4 = String.Format("{0}\\{1}", directory, "key4.db"); - if (System.IO.File.Exists(firefoxCredentialFile4)) - results.Add(firefoxCredentialFile3); - } - } - } - } - } - else - { - string userName = Environment.GetEnvironmentVariable("USERNAME"); - string userFirefoxBasePath = String.Format("{0}\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\", System.Environment.GetEnvironmentVariable("USERPROFILE")); - - if (System.IO.Directory.Exists(userFirefoxBasePath)) - { - string[] directories = Directory.GetDirectories(userFirefoxBasePath); - foreach (string directory in directories) - { - string firefoxCredentialFile3 = String.Format("{0}\\{1}", directory, "key3.db"); - if (System.IO.File.Exists(firefoxCredentialFile3)) - results.Add(firefoxCredentialFile3); - - string firefoxCredentialFile4 = String.Format("{0}\\{1}", directory, "key4.db"); - if (System.IO.File.Exists(firefoxCredentialFile4)) - results.Add(firefoxCredentialFile4); - } - } - } - } - catch (Exception ex) - { - Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); - } - - return results; - } - - - public static List ParseFirefoxHistory(string path) - { - List results = new List(); - // parses a Firefox history file via regex - if (System.IO.Directory.Exists(path)) - { - string[] directories = Directory.GetDirectories(path); - foreach (string directory in directories) - { - string firefoxHistoryFile = String.Format("{0}\\{1}", directory, "places.sqlite"); - Regex historyRegex = new Regex(@"(http|ftp|https|file)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?"); - - try - { - using (StreamReader r = new StreamReader(firefoxHistoryFile)) - { - string line; - while ((line = r.ReadLine()) != null) - { - Match m = historyRegex.Match(line); - if (m.Success) - results.Add(m.Groups[0].ToString().Trim()); - } - } - } - catch (System.IO.IOException exception) - { - Console.WriteLine("\r\n [x] IO exception, places.sqlite file likely in use (i.e. Firefox is likely running).", exception.Message); - } - catch (Exception ex) - { - Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); - } - } - } - return results; - } - - public static List GetFirefoxHistory() - { - List results = new List(); - try - { - if (MyUtils.IsHighIntegrity()) - { - string userFolder = String.Format("{0}\\Users\\", Environment.GetEnvironmentVariable("SystemDrive")); - string[] dirs = Directory.GetDirectories(userFolder); - foreach (string dir in dirs) - { - string[] parts = dir.Split('\\'); - if (!(dir.EndsWith("Public") || dir.EndsWith("Default") || dir.EndsWith("Default User") || dir.EndsWith("All Users"))) - { - string userFirefoxBasePath = String.Format("{0}\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\", dir); - results = ParseFirefoxHistory(userFirefoxBasePath); - } - } - } - else - { - string userFirefoxBasePath = String.Format("{0}\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\", System.Environment.GetEnvironmentVariable("USERPROFILE")); - results = ParseFirefoxHistory(userFirefoxBasePath); - } - } - catch (Exception ex) - { - Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); - } - return results; - } - - public static Dictionary GetChromeDbs() - { - Dictionary results = new Dictionary(); - // checks if Chrome has a history database - try - { - if (MyUtils.IsHighIntegrity()) - { - string userFolder = String.Format("{0}\\Users\\", Environment.GetEnvironmentVariable("SystemDrive")); - string[] dirs = Directory.GetDirectories(userFolder); - foreach (string dir in dirs) - { - string[] parts = dir.Split('\\'); - string userName = parts[parts.Length - 1]; - if (!(dir.EndsWith("Public") || dir.EndsWith("Default") || dir.EndsWith("Default User") || dir.EndsWith("All Users"))) - { - string userChromeCookiesPath = String.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Cookies", dir); - if (System.IO.File.Exists(userChromeCookiesPath)) - results["userChromeCookiesPath"] = userChromeCookiesPath; - - string userChromeLoginDataPath = String.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Login Data", dir); - if (System.IO.File.Exists(userChromeLoginDataPath)) - results["userChromeLoginDataPath"] = userChromeLoginDataPath; - } - } - } - else - { - string userChromeCookiesPath = String.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Cookies", System.Environment.GetEnvironmentVariable("USERPROFILE")); - if (System.IO.File.Exists(userChromeCookiesPath)) - results["userChromeCookiesPath"] = userChromeCookiesPath; - - string userChromeLoginDataPath = String.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Login Data", System.Environment.GetEnvironmentVariable("USERPROFILE")); - if (System.IO.File.Exists(userChromeLoginDataPath)) - results["userChromeLoginDataPath"] = userChromeLoginDataPath; - } - } - catch (Exception ex) - { - Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); - } - return results; - } - - - - public static List ParseChromeHistory(string path) - { - List results = new List(); - - // parses a Chrome history file via regex - if (System.IO.File.Exists(path)) - { - Regex historyRegex = new Regex(@"(http|ftp|https|file)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?"); - - try - { - using (StreamReader r = new StreamReader(path)) - { - string line; - while ((line = r.ReadLine()) != null) - { - Match m = historyRegex.Match(line); - if (m.Success) - { - results.Add(m.Groups[0].ToString().Trim()); - } - } - } - } - catch (System.IO.IOException exception) - { - Console.WriteLine("\r\n [x] IO exception, history file likely in use (i.e. Browser is likely running): ", exception.Message); - } - catch (Exception ex) - { - Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); - } - } - return results; - } - - - public static List ParseChromeBookmarks(string path) - { - List results = new List(); - // parses a Chrome bookmarks - if (System.IO.File.Exists(path)) - { - try - { - string contents = System.IO.File.ReadAllText(path); - - // reference: http://www.tomasvera.com/programming/using-javascriptserializer-to-parse-json-objects/ - JavaScriptSerializer json = new JavaScriptSerializer(); - Dictionary deserialized = json.Deserialize>(contents); - Dictionary roots = (Dictionary)deserialized["roots"]; - Dictionary bookmark_bar = (Dictionary)roots["bookmark_bar"]; - System.Collections.ArrayList children = (System.Collections.ArrayList)bookmark_bar["children"]; - - foreach (Dictionary entry in children) - { - //Console.WriteLine(" Name: {0}", entry["name"].ToString().Trim()); - if (entry.ContainsKey("url")) - results.Add(entry["url"].ToString().Trim()); - } - } - catch (System.IO.IOException exception) - { - Console.WriteLine("\r\n [x] IO exception, Bookmarks file likely in use (i.e. Chrome is likely running).", exception.Message); - } - catch (Exception ex) - { - Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); - } - } - return results; - } - - - public static Dictionary> GetChromeHistBook() - { - Dictionary> results = new Dictionary>() - { - { "history", new List() }, - { "bookarks", new List() }, - }; - try - { - if (MyUtils.IsHighIntegrity()) - { - Console.WriteLine("\r\n\r\n=== Chrome (All Users) ==="); - - string userFolder = String.Format("{0}\\Users\\", Environment.GetEnvironmentVariable("SystemDrive")); - string[] dirs = Directory.GetDirectories(userFolder); - foreach (string dir in dirs) - { - string[] parts = dir.Split('\\'); - if (!(dir.EndsWith("Public") || dir.EndsWith("Default") || dir.EndsWith("Default User") || dir.EndsWith("All Users"))) - { - string userChromeHistoryPath = String.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\History", dir); - results["history"] = ParseChromeHistory(userChromeHistoryPath); - - string userChromeBookmarkPath = String.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Bookmarks", dir); - results["bookmarks"] = ParseChromeBookmarks(userChromeBookmarkPath); - } - } - } - else - { - string userChromeHistoryPath = String.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\History", System.Environment.GetEnvironmentVariable("USERPROFILE")); - results["history"] = ParseChromeHistory(userChromeHistoryPath); - - string userChromeBookmarkPath = String.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Bookmarks", System.Environment.GetEnvironmentVariable("USERPROFILE")); - - results["bookmarks"] = ParseChromeBookmarks(userChromeBookmarkPath); - } - } - catch (Exception ex) - { - Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); - } - return results; - } - - - - public static Dictionary> GetIEHistFav() - { - int lastDays = 90; - Dictionary> results = new Dictionary>() - { - { "history", new List() }, - { "favorites", new List() }, - }; - - DateTime startTime = System.DateTime.Now.AddDays(-lastDays); - - try - { - if (MyUtils.IsHighIntegrity()) - { - string[] SIDs = Registry.Users.GetSubKeyNames(); - foreach (string SID in SIDs) - { - if (SID.StartsWith("S-1-5") && !SID.EndsWith("_Classes")) - { - Dictionary settings = MyUtils.GetRegValues("HKU", String.Format("{0}\\SOFTWARE\\Microsoft\\Internet Explorer\\TypedURLs", SID)); - if ((settings != null) && (settings.Count > 1)) - { - foreach (KeyValuePair kvp in settings) - { - byte[] timeBytes = MyUtils.GetRegValueBytes("HKU", String.Format("{0}\\SOFTWARE\\Microsoft\\Internet Explorer\\TypedURLsTime", SID), kvp.Key.ToString().Trim()); - if (timeBytes != null) - { - long timeLong = (long)(BitConverter.ToInt64(timeBytes, 0)); - DateTime urlTime = DateTime.FromFileTime(timeLong); - if (urlTime > startTime) - { - results["history"].Add(kvp.Value.ToString().Trim()); - } - } - } - } - } - } - - string userFolder = String.Format("{0}\\Users\\", Environment.GetEnvironmentVariable("SystemDrive")); - string[] dirs = Directory.GetDirectories(userFolder); - foreach (string dir in dirs) - { - string[] parts = dir.Split('\\'); - string userName = parts[parts.Length - 1]; - if (!(dir.EndsWith("Public") || dir.EndsWith("Default") || dir.EndsWith("Default User") || dir.EndsWith("All Users"))) - { - string userIEBookmarkPath = String.Format("{0}\\Favorites\\", dir); - - if (Directory.Exists(userIEBookmarkPath)) - { - string[] bookmarkPaths = Directory.GetFiles(userIEBookmarkPath, "*.url", SearchOption.AllDirectories); - if (bookmarkPaths.Length != 0) - { - foreach (string bookmarkPath in bookmarkPaths) - { - using (StreamReader rdr = new StreamReader(bookmarkPath)) - { - string line; - string url = ""; - while ((line = rdr.ReadLine()) != null) - { - if (line.StartsWith("URL=", StringComparison.InvariantCultureIgnoreCase)) - { - if (line.Length > 4) - url = line.Substring(4); - break; - } - } - results["history"].Add(url.ToString().Trim()); - } - } - } - } - } - } - } - else - { - Dictionary settings = MyUtils.GetRegValues("HKCU", "SOFTWARE\\Microsoft\\Internet Explorer\\TypedURLs"); - if ((settings != null) && (settings.Count != 0)) - { - foreach (KeyValuePair kvp in settings) - { - byte[] timeBytes = MyUtils.GetRegValueBytes("HKCU", "SOFTWARE\\Microsoft\\Internet Explorer\\TypedURLsTime", kvp.Key.ToString().Trim()); - if (timeBytes != null) - { - long timeLong = (long)(BitConverter.ToInt64(timeBytes, 0)); - DateTime urlTime = DateTime.FromFileTime(timeLong); - if (urlTime > startTime) - { - results["history"].Add(kvp.Value.ToString().Trim()); - } - } - } - } - - string userIEBookmarkPath = String.Format("{0}\\Favorites\\", System.Environment.GetEnvironmentVariable("USERPROFILE")); - - string[] bookmarkPaths = Directory.GetFiles(userIEBookmarkPath, "*.url", SearchOption.AllDirectories); - - foreach (string bookmarkPath in bookmarkPaths) - { - using (StreamReader rdr = new StreamReader(bookmarkPath)) - { - string line; - string url = ""; - while ((line = rdr.ReadLine()) != null) - { - if (line.StartsWith("URL=", StringComparison.InvariantCultureIgnoreCase)) - { - if (line.Length > 4) - url = line.Substring(4); - break; - } - } - results["favorites"].Add(url.ToString().Trim()); - } - } - } - } - catch (Exception ex) - { - Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex)); - } - return results; - } - - - public static List GetCurrentIETabs() - { - List results = new List(); - // Lists currently open Internet Explorer tabs, via COM - // Notes: - // https://searchcode.com/codesearch/view/9859954/ - // https://gist.github.com/yizhang82/a1268d3ea7295a8a1496e01d60ada816 - - try - { - // Shell.Application COM GUID - Type shell = Type.GetTypeFromCLSID(new Guid("13709620-C279-11CE-A49E-444553540000")); - - // actually instantiate the Shell.Application COM object - Object shellObj = Activator.CreateInstance(shell); - - // grab all the current windows - Object windows = shellObj.GetType().InvokeMember("Windows", BindingFlags.InvokeMethod, null, shellObj, null); - - // grab the open tab count - Object openTabs = windows.GetType().InvokeMember("Count", BindingFlags.GetProperty, null, windows, null); - int openTabsCount = Int32.Parse(openTabs.ToString()); - - for (int i = 0; i < openTabsCount; i++) - { - // grab the acutal tab - Object item = windows.GetType().InvokeMember("Item", BindingFlags.InvokeMethod, null, windows, new object[] { i }); - try - { - // extract the tab properties - Object locationName = item.GetType().InvokeMember("LocationName", BindingFlags.GetProperty, null, item, null); - Object locationURL = item.GetType().InvokeMember("LocationUrl", BindingFlags.GetProperty, null, item, null); - - // ensure we have a site address - if (Regex.IsMatch(locationURL.ToString(), @"(^https?://.+)|(^ftp://)")) - { - results.Add(String.Format("{0}", locationURL)); - } - Marshal.ReleaseComObject(item); - item = null; - } - catch - { - // - } - } - Marshal.ReleaseComObject(windows); - windows = null; - Marshal.ReleaseComObject(shellObj); - shellObj = null; - } - catch (Exception ex) - { - Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex)); - } - return results; - } - - - public static class VaultCli - { - // pulled directly from @djhohnstein's SharpWeb project: https://github.com/djhohnstein/SharpWeb/blob/master/Edge/SharpEdge.cs - public enum VAULT_ELEMENT_TYPE : Int32 - { - Undefined = -1, - Boolean = 0, - Short = 1, - UnsignedShort = 2, - Int = 3, - UnsignedInt = 4, - Double = 5, - Guid = 6, - String = 7, - ByteArray = 8, - TimeStamp = 9, - ProtectedArray = 10, - Attribute = 11, - Sid = 12, - Last = 13 - } - - public enum VAULT_SCHEMA_ELEMENT_ID : Int32 - { - Illegal = 0, - Resource = 1, - Identity = 2, - Authenticator = 3, - Tag = 4, - PackageSid = 5, - AppStart = 100, - AppEnd = 10000 - } - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] - public struct VAULT_ITEM_WIN8 - { - public Guid SchemaId; - public IntPtr pszCredentialFriendlyName; - public IntPtr pResourceElement; - public IntPtr pIdentityElement; - public IntPtr pAuthenticatorElement; - public IntPtr pPackageSid; - public UInt64 LastModified; - public UInt32 dwFlags; - public UInt32 dwPropertiesCount; - public IntPtr pPropertyElements; - } - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] - public struct VAULT_ITEM_WIN7 - { - public Guid SchemaId; - public IntPtr pszCredentialFriendlyName; - public IntPtr pResourceElement; - public IntPtr pIdentityElement; - public IntPtr pAuthenticatorElement; - public UInt64 LastModified; - public UInt32 dwFlags; - public UInt32 dwPropertiesCount; - public IntPtr pPropertyElements; - } - - [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi)] - public struct VAULT_ITEM_ELEMENT - { - [FieldOffset(0)] - public VAULT_SCHEMA_ELEMENT_ID SchemaElementId; - [FieldOffset(8)] - public VAULT_ELEMENT_TYPE Type; - } - - [DllImport("vaultcli.dll")] - public extern static Int32 VaultOpenVault(ref Guid vaultGuid, UInt32 offset, ref IntPtr vaultHandle); - - [DllImport("vaultcli.dll")] - public extern static Int32 VaultEnumerateVaults(Int32 offset, ref Int32 vaultCount, ref IntPtr vaultGuid); - - [DllImport("vaultcli.dll")] - public extern static Int32 VaultEnumerateItems(IntPtr vaultHandle, Int32 chunkSize, ref Int32 vaultItemCount, ref IntPtr vaultItem); - - [DllImport("vaultcli.dll", EntryPoint = "VaultGetItem")] - public extern static Int32 VaultGetItem_WIN8(IntPtr vaultHandle, ref Guid schemaId, IntPtr pResourceElement, IntPtr pIdentityElement, IntPtr pPackageSid, IntPtr zero, Int32 arg6, ref IntPtr passwordVaultPtr); - - [DllImport("vaultcli.dll", EntryPoint = "VaultGetItem")] - public extern static Int32 VaultGetItem_WIN7(IntPtr vaultHandle, ref Guid schemaId, IntPtr pResourceElement, IntPtr pIdentityElement, IntPtr zero, Int32 arg5, ref IntPtr passwordVaultPtr); - - } - - - public static object GetVaultElementValue(IntPtr vaultElementPtr) - { - // Helper function to extract the ItemValue field from a VAULT_ITEM_ELEMENT struct - // pulled directly from @djhohnstein's SharpWeb project: https://github.com/djhohnstein/SharpWeb/blob/master/Edge/SharpEdge.cs - object results; - object partialElement = System.Runtime.InteropServices.Marshal.PtrToStructure(vaultElementPtr, typeof(VaultCli.VAULT_ITEM_ELEMENT)); - FieldInfo partialElementInfo = partialElement.GetType().GetField("Type"); - var partialElementType = partialElementInfo.GetValue(partialElement); - - IntPtr elementPtr = (IntPtr)(vaultElementPtr.ToInt64() + 16); - switch ((int)partialElementType) - { - case 7: // VAULT_ELEMENT_TYPE == String; These are the plaintext passwords! - IntPtr StringPtr = System.Runtime.InteropServices.Marshal.ReadIntPtr(elementPtr); - results = System.Runtime.InteropServices.Marshal.PtrToStringUni(StringPtr); - break; - case 0: // VAULT_ELEMENT_TYPE == bool - results = System.Runtime.InteropServices.Marshal.ReadByte(elementPtr); - results = (bool)results; - break; - case 1: // VAULT_ELEMENT_TYPE == Short - results = System.Runtime.InteropServices.Marshal.ReadInt16(elementPtr); - break; - case 2: // VAULT_ELEMENT_TYPE == Unsigned Short - results = System.Runtime.InteropServices.Marshal.ReadInt16(elementPtr); - break; - case 3: // VAULT_ELEMENT_TYPE == Int - results = System.Runtime.InteropServices.Marshal.ReadInt32(elementPtr); - break; - case 4: // VAULT_ELEMENT_TYPE == Unsigned Int - results = System.Runtime.InteropServices.Marshal.ReadInt32(elementPtr); - break; - case 5: // VAULT_ELEMENT_TYPE == Double - results = System.Runtime.InteropServices.Marshal.PtrToStructure(elementPtr, typeof(Double)); - break; - case 6: // VAULT_ELEMENT_TYPE == GUID - results = System.Runtime.InteropServices.Marshal.PtrToStructure(elementPtr, typeof(Guid)); - break; - case 12: // VAULT_ELEMENT_TYPE == Sid - IntPtr sidPtr = System.Runtime.InteropServices.Marshal.ReadIntPtr(elementPtr); - var sidObject = new System.Security.Principal.SecurityIdentifier(sidPtr); - results = sidObject.Value; - break; - default: - /* Several VAULT_ELEMENT_TYPES are currently unimplemented according to - * Lord Graeber. Thus we do not implement them. */ - results = null; - break; - } - return results; - } - - public static List> DumpVault() - { - List> results = new List>(); - - try - { - // pulled directly from @djhohnstein's SharpWeb project: https://github.com/djhohnstein/SharpWeb/blob/master/Edge/SharpEdge.cs - var OSVersion = Environment.OSVersion.Version; - var OSMajor = OSVersion.Major; - var OSMinor = OSVersion.Minor; - - Type VAULT_ITEM; - - if (OSMajor >= 6 && OSMinor >= 2) - { - VAULT_ITEM = typeof(VaultCli.VAULT_ITEM_WIN8); - } - else - { - VAULT_ITEM = typeof(VaultCli.VAULT_ITEM_WIN7); - } - - Int32 vaultCount = 0; - IntPtr vaultGuidPtr = IntPtr.Zero; - var result = VaultCli.VaultEnumerateVaults(0, ref vaultCount, ref vaultGuidPtr); - - //var result = CallVaultEnumerateVaults(VaultEnum, 0, ref vaultCount, ref vaultGuidPtr); - - if ((int)result != 0) - { - Console.WriteLine(" [ERROR] Unable to enumerate vaults. Error (0x" + result.ToString() + ")"); - return results; - } - - // Create dictionary to translate Guids to human readable elements - IntPtr guidAddress = vaultGuidPtr; - Dictionary vaultSchema = new Dictionary(); - vaultSchema.Add(new Guid("2F1A6504-0641-44CF-8BB5-3612D865F2E5"), "Windows Secure Note"); - vaultSchema.Add(new Guid("3CCD5499-87A8-4B10-A215-608888DD3B55"), "Windows Web Password Credential"); - vaultSchema.Add(new Guid("154E23D0-C644-4E6F-8CE6-5069272F999F"), "Windows Credential Picker Protector"); - vaultSchema.Add(new Guid("4BF4C442-9B8A-41A0-B380-DD4A704DDB28"), "Web Credentials"); - vaultSchema.Add(new Guid("77BC582B-F0A6-4E15-4E80-61736B6F3B29"), "Windows Credentials"); - vaultSchema.Add(new Guid("E69D7838-91B5-4FC9-89D5-230D4D4CC2BC"), "Windows Domain Certificate Credential"); - vaultSchema.Add(new Guid("3E0E35BE-1B77-43E7-B873-AED901B6275B"), "Windows Domain Password Credential"); - vaultSchema.Add(new Guid("3C886FF3-2669-4AA2-A8FB-3F6759A77548"), "Windows Extended Credential"); - vaultSchema.Add(new Guid("00000000-0000-0000-0000-000000000000"), null); - - for (int i = 0; i < vaultCount; i++) - { - - // Open vault block - object vaultGuidString = System.Runtime.InteropServices.Marshal.PtrToStructure(guidAddress, typeof(Guid)); - Guid vaultGuid = new Guid(vaultGuidString.ToString()); - guidAddress = (IntPtr)(guidAddress.ToInt64() + System.Runtime.InteropServices.Marshal.SizeOf(typeof(Guid))); - IntPtr vaultHandle = IntPtr.Zero; - string vaultType; - if (vaultSchema.ContainsKey(vaultGuid)) - { - vaultType = vaultSchema[vaultGuid]; - } - else - { - vaultType = vaultGuid.ToString(); - } - result = VaultCli.VaultOpenVault(ref vaultGuid, (UInt32)0, ref vaultHandle); - if (result != 0) - { - Console.WriteLine("Unable to open the following vault: " + vaultType + ". Error: 0x" + result.ToString()); - continue; - } - // Vault opened successfully! Continue. - - // Fetch all items within Vault - int vaultItemCount = 0; - IntPtr vaultItemPtr = IntPtr.Zero; - result = VaultCli.VaultEnumerateItems(vaultHandle, 512, ref vaultItemCount, ref vaultItemPtr); - if (result != 0) - { - Console.WriteLine("Unable to enumerate vault items from the following vault: " + vaultType + ". Error 0x" + result.ToString()); - continue; - } - var structAddress = vaultItemPtr; - if (vaultItemCount > 0) - { - // For each vault item... - for (int j = 1; j <= vaultItemCount; j++) - { - Dictionary vault_cred = new Dictionary() { - { "GUID", String.Format("{0}", vaultGuid) }, - { "Type", vaultType }, - { "Resource", "" }, - { "Identity", "" }, - { "PacakgeSid", "" }, - { "Credential", "" }, - { "Last Modified", "" }, - { "Error", "" } - }; - - // Begin fetching vault item... - var currentItem = System.Runtime.InteropServices.Marshal.PtrToStructure(structAddress, VAULT_ITEM); - structAddress = (IntPtr)(structAddress.ToInt64() + System.Runtime.InteropServices.Marshal.SizeOf(VAULT_ITEM)); - - IntPtr passwordVaultItem = IntPtr.Zero; - // Field Info retrieval - FieldInfo schemaIdInfo = currentItem.GetType().GetField("SchemaId"); - Guid schemaId = new Guid(schemaIdInfo.GetValue(currentItem).ToString()); - FieldInfo pResourceElementInfo = currentItem.GetType().GetField("pResourceElement"); - IntPtr pResourceElement = (IntPtr)pResourceElementInfo.GetValue(currentItem); - FieldInfo pIdentityElementInfo = currentItem.GetType().GetField("pIdentityElement"); - IntPtr pIdentityElement = (IntPtr)pIdentityElementInfo.GetValue(currentItem); - FieldInfo dateTimeInfo = currentItem.GetType().GetField("LastModified"); - UInt64 lastModified = (UInt64)dateTimeInfo.GetValue(currentItem); - - IntPtr pPackageSid = IntPtr.Zero; - if (OSMajor >= 6 && OSMinor >= 2) - { - // Newer versions have package sid - FieldInfo pPackageSidInfo = currentItem.GetType().GetField("pPackageSid"); - pPackageSid = (IntPtr)pPackageSidInfo.GetValue(currentItem); - result = VaultCli.VaultGetItem_WIN8(vaultHandle, ref schemaId, pResourceElement, pIdentityElement, pPackageSid, IntPtr.Zero, 0, ref passwordVaultItem); - } - else - { - result = VaultCli.VaultGetItem_WIN7(vaultHandle, ref schemaId, pResourceElement, pIdentityElement, IntPtr.Zero, 0, ref passwordVaultItem); - } - - if (result != 0) - { - vault_cred["Error"] = "Occured while retrieving vault item. Error: 0x" + result.ToString(); - continue; - } - object passwordItem = System.Runtime.InteropServices.Marshal.PtrToStructure(passwordVaultItem, VAULT_ITEM); - FieldInfo pAuthenticatorElementInfo = passwordItem.GetType().GetField("pAuthenticatorElement"); - IntPtr pAuthenticatorElement = (IntPtr)pAuthenticatorElementInfo.GetValue(passwordItem); - // Fetch the credential from the authenticator element - object cred = GetVaultElementValue(pAuthenticatorElement); - object packageSid = null; - if (pPackageSid != IntPtr.Zero && pPackageSid != null) - { - packageSid = GetVaultElementValue(pPackageSid); - } - if (cred != null) // Indicates successful fetch - { - object resource = GetVaultElementValue(pResourceElement); - if (resource != null) - { - vault_cred["Resource"] = String.Format("{0}", resource); - } - object identity = GetVaultElementValue(pIdentityElement); - if (identity != null) - { - vault_cred["Identity"] = String.Format("{0}", identity); - } - if (packageSid != null) - { - vault_cred["PacakgeSid"] = String.Format("{0}", packageSid); - } - vault_cred["Credential"] = String.Format("{0}", cred); - vault_cred["Last Modified"] = String.Format("{0}", System.DateTime.FromFileTimeUtc((long)lastModified)); - results.Add(vault_cred); - } - } - } - } - } - catch(Exception ex) - { - Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); - } - return results; - } - - - public static List> GetSavedRDPConnections() - { - List> results = new List>(); - //shows saved RDP connections, including username hints (if present) - if (MyUtils.IsHighIntegrity()) - { - string[] SIDs = Registry.Users.GetSubKeyNames(); - foreach (string SID in SIDs) - { - if (SID.StartsWith("S-1-5") && !SID.EndsWith("_Classes")) - { - string[] subkeys = MyUtils.GetRegSubkeys("HKU", String.Format("{0}\\Software\\Microsoft\\Terminal Server Client\\Servers", SID)); - if (subkeys != null) - { - //Console.WriteLine("\r\n\r\n=== Saved RDP Connection Information ({0}) ===", SID); - foreach (string host in subkeys) - { - string usernameHint = MyUtils.GetRegValue("HKCU", String.Format("Software\\Microsoft\\Terminal Server Client\\Servers\\{0}", host), "UsernameHint"); - Dictionary rdp_info = new Dictionary() { - { "SID", SID }, - { "Host", host }, - { "Username Hint", usernameHint }, - }; - results.Add(rdp_info); - } - } - } - } - } - else - { - string[] subkeys = MyUtils.GetRegSubkeys("HKCU", "Software\\Microsoft\\Terminal Server Client\\Servers"); - if (subkeys != null) - { - foreach (string host in subkeys) - { - string usernameHint = MyUtils.GetRegValue("HKCU", String.Format("Software\\Microsoft\\Terminal Server Client\\Servers\\{0}", host), "UsernameHint"); - Dictionary rdp_info = new Dictionary() { - { "SID", "" }, - { "Host", host }, - { "Username Hint", usernameHint }, - }; - results.Add(rdp_info); - } - } - } - return results; - } - - public static Dictionary GetRecentRunCommands() - { - Dictionary results = new Dictionary(); - // lists recently run commands via the RunMRU registry key - if (MyUtils.IsHighIntegrity()) - { - string[] SIDs = Registry.Users.GetSubKeyNames(); - foreach (string SID in SIDs) - { - if (SID.StartsWith("S-1-5") && !SID.EndsWith("_Classes")) - results = MyUtils.GetRegValues("HKU", String.Format("{0}\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RunMRU", SID)); - } - } - else - { - results = MyUtils.GetRegValues("HKCU", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RunMRU"); - } - return results; - } - - public static List> GetPuttySessions() - { - List> results = new List>(); - // extracts saved putty sessions and basic configs (via the registry) - if (MyUtils.IsHighIntegrity()) - { - Console.WriteLine("\r\n\r\n=== Putty Saved Session Information (All Users) ===\r\n"); - - string[] SIDs = Registry.Users.GetSubKeyNames(); - foreach (string SID in SIDs) - { - if (SID.StartsWith("S-1-5") && !SID.EndsWith("_Classes")) - { - string[] subKeys = MyUtils.GetRegSubkeys("HKU", String.Format("{0}\\Software\\SimonTatham\\PuTTY\\Sessions\\", SID)); - - foreach (string sessionName in subKeys) - { - Dictionary putty_sess = new Dictionary() - { - { "User SID", SID }, - { "SessionName", sessionName }, - { "HostName", "" }, - { "PortNumber", ""}, - { "UserName", "" }, - { "PublicKeyFile", "" }, - { "PortForwardings", "" }, - { "ConnectionSharing", "" }, - { "ProxyPassword", "" }, - { "ProxyUsername", "" }, - }; - - string[] keys = - { - "HostName", - "PortNumber", - "UserName", - "PublicKeyFile", - "PortForwardings", - "ConnectionSharing", - "ProxyPassword", - "ProxyUsername", - }; - - foreach (string key in keys) - putty_sess[key] = MyUtils.GetRegValue("HKU", String.Format("{0}\\Software\\SimonTatham\\PuTTY\\Sessions\\{1}", SID, sessionName), key); - - results.Add(putty_sess); - } - } - } - } - else - { - string[] subKeys = MyUtils.GetRegSubkeys("HKCU", "Software\\SimonTatham\\PuTTY\\Sessions\\"); - foreach (string sessionName in subKeys) - { - Dictionary putty_sess = new Dictionary() - { - { "SessionName", sessionName }, - { "HostName", "" }, - { "PortNumber", "" }, - { "UserName", "" }, - { "PublicKeyFile", "" }, - { "PortForwardings", "" }, - { "ConnectionSharing", "" }, - { "ProxyPassword", "" }, - { "ProxyUsername", "" }, - }; - - string[] keys = - { - "HostName", - "PortNumber", - "UserName", - "PublicKeyFile", - "PortForwardings", - "ConnectionSharing", - "ProxyPassword", - "ProxyUsername", - }; - - foreach (string key in keys) - putty_sess[key] = MyUtils.GetRegValue("HKCU", String.Format("Software\\SimonTatham\\PuTTY\\Sessions\\{0}", sessionName), key); - - results.Add(putty_sess); - } - } - return results; - } - - - public static List> ListPuttySSHHostKeys() - { - List> results = new List>(); - // extracts saved putty host keys (via the registry) - if (MyUtils.IsHighIntegrity()) - { - Console.WriteLine("\r\n\r\n=== Putty SSH Host Hosts (All Users) ===\r\n"); - - string[] SIDs = Registry.Users.GetSubKeyNames(); - foreach (string SID in SIDs) - { - if (SID.StartsWith("S-1-5") && !SID.EndsWith("_Classes")) - { - Dictionary hostKeys = MyUtils.GetRegValues("HKU", String.Format("{0}\\Software\\SimonTatham\\PuTTY\\SshHostKeys\\", SID)); - if ((hostKeys != null) && (hostKeys.Count != 0)) - { - Dictionary putty_ssh = new Dictionary(); - putty_ssh["UserSID"] = SID; - foreach (KeyValuePair kvp in hostKeys) - { - putty_ssh[kvp.Key] = ""; //Looks like only matters the key name, not the value - } - results.Add(putty_ssh); - } - } - } - } - else - { - Dictionary hostKeys = MyUtils.GetRegValues("HKCU", "Software\\SimonTatham\\PuTTY\\SshHostKeys\\"); - if ((hostKeys != null) && (hostKeys.Count != 0)) - { - Dictionary putty_ssh = new Dictionary(); - foreach (KeyValuePair kvp in hostKeys) - { - putty_ssh[kvp.Key] = ""; //Looks like only matters the key name, not the value - } - results.Add(putty_ssh); - } - } - return results; - } - - public static List> ListCloudCreds() - { - List> results = new List>(); - // checks for various cloud credential files (AWS, Microsoft Azure, and Google Compute) - // adapted from https://twitter.com/cmaddalena's SharpCloud project (https://github.com/chrismaddalena/SharpCloud/) - try - { - if (MyUtils.IsHighIntegrity()) - { - string userFolder = String.Format("{0}\\Users\\", Environment.GetEnvironmentVariable("SystemDrive")); - string[] dirs = Directory.GetDirectories(userFolder); - foreach (string dir in dirs) - { - string[] parts = dir.Split('\\'); - string userName = parts[parts.Length - 1]; - if (!(dir.EndsWith("Public") || dir.EndsWith("Default") || dir.EndsWith("Default User") || dir.EndsWith("All Users"))) - { - string awsKeyFile = String.Format("{0}\\.aws\\credentials", dir); - if (System.IO.File.Exists(awsKeyFile)) - { - DateTime lastAccessed = System.IO.File.GetLastAccessTime(awsKeyFile); - DateTime lastModified = System.IO.File.GetLastWriteTime(awsKeyFile); - long size = new System.IO.FileInfo(awsKeyFile).Length; - results.Add(new Dictionary() { - { "file", awsKeyFile }, - { "Description", "AWS credentials file" }, - { "Accessed", String.Format("{0}", lastAccessed) }, - { "Modified", String.Format("{0}", lastModified) }, - { "Size", String.Format("{0}", size) } - }); - } - string computeCredsDb = String.Format("{0}\\AppData\\Roaming\\gcloud\\credentials.db", dir); - if (System.IO.File.Exists(computeCredsDb)) - { - DateTime lastAccessed = System.IO.File.GetLastAccessTime(computeCredsDb); - DateTime lastModified = System.IO.File.GetLastWriteTime(computeCredsDb); - long size = new System.IO.FileInfo(computeCredsDb).Length; - results.Add(new Dictionary() { - { "file", computeCredsDb }, - { "Description", "GC Compute creds" }, - { "Accessed", String.Format("{0}", lastAccessed) }, - { "Modified", String.Format("{0}", lastModified) }, - { "Size", String.Format("{0}", size) } - }); - } - string computeLegacyCreds = String.Format("{0}\\AppData\\Roaming\\gcloud\\legacy_credentials", dir); - if (System.IO.File.Exists(computeLegacyCreds)) - { - DateTime lastAccessed = System.IO.File.GetLastAccessTime(computeLegacyCreds); - DateTime lastModified = System.IO.File.GetLastWriteTime(computeLegacyCreds); - long size = new System.IO.FileInfo(computeLegacyCreds).Length; - results.Add(new Dictionary() { - { "file", computeLegacyCreds }, - { "Description", "GC Compute creds legacy" }, - { "Accessed", String.Format("{0}", lastAccessed) }, - { "Modified", String.Format("{0}", lastModified) }, - { "Size", String.Format("{0}", size) } - }); - } - string computeAccessTokensDb = String.Format("{0}\\AppData\\Roaming\\gcloud\\access_tokens.db", dir); - if (System.IO.File.Exists(computeAccessTokensDb)) - { - DateTime lastAccessed = System.IO.File.GetLastAccessTime(computeAccessTokensDb); - DateTime lastModified = System.IO.File.GetLastWriteTime(computeAccessTokensDb); - long size = new System.IO.FileInfo(computeAccessTokensDb).Length; - results.Add(new Dictionary() { - { "file", computeAccessTokensDb }, - { "Description", "GC Compute tokens" }, - { "Accessed", String.Format("{0}", lastAccessed) }, - { "Modified", String.Format("{0}", lastModified) }, - { "Size", String.Format("{0}", size) } - }); - } - string azureTokens = String.Format("{0}\\.azure\\accessTokens.json", dir); - if (System.IO.File.Exists(azureTokens)) - { - DateTime lastAccessed = System.IO.File.GetLastAccessTime(azureTokens); - DateTime lastModified = System.IO.File.GetLastWriteTime(azureTokens); - long size = new System.IO.FileInfo(azureTokens).Length; - results.Add(new Dictionary() { - { "file", azureTokens }, - { "Description", "Azure tokens" }, - { "Accessed", String.Format("{0}", lastAccessed) }, - { "Modified", String.Format("{0}", lastModified) }, - { "Size", String.Format("{0}", size) } - }); - } - string azureProfile = String.Format("{0}\\.azure\\azureProfile.json", dir); - if (System.IO.File.Exists(azureProfile)) - { - DateTime lastAccessed = System.IO.File.GetLastAccessTime(azureProfile); - DateTime lastModified = System.IO.File.GetLastWriteTime(azureProfile); - long size = new System.IO.FileInfo(azureProfile).Length; - results.Add(new Dictionary() { - { "file", azureProfile }, - { "Description", "Azure profile" }, - { "Accessed", String.Format("{0}", lastAccessed) }, - { "Modified", String.Format("{0}", lastModified) }, - { "Size", String.Format("{0}", size) } - }); - } - } - } - } - else - { - string awsKeyFile = String.Format("{0}\\.aws\\credentials", System.Environment.GetEnvironmentVariable("USERPROFILE")); - if (System.IO.File.Exists(awsKeyFile)) - { - DateTime lastAccessed = System.IO.File.GetLastAccessTime(awsKeyFile); - DateTime lastModified = System.IO.File.GetLastWriteTime(awsKeyFile); - long size = new System.IO.FileInfo(awsKeyFile).Length; - results.Add(new Dictionary() { - { "file", awsKeyFile }, - { "Description", "AWS keys file" }, - { "Accessed", String.Format("{0}", lastAccessed) }, - { "Modified", String.Format("{0}", lastModified) }, - { "Size", String.Format("{0}", size) } - }); - } - string computeCredsDb = String.Format("{0}\\AppData\\Roaming\\gcloud\\credentials.db", System.Environment.GetEnvironmentVariable("USERPROFILE")); - if (System.IO.File.Exists(computeCredsDb)) - { - DateTime lastAccessed = System.IO.File.GetLastAccessTime(computeCredsDb); - DateTime lastModified = System.IO.File.GetLastWriteTime(computeCredsDb); - long size = new System.IO.FileInfo(computeCredsDb).Length; - results.Add(new Dictionary() { - { "file", computeCredsDb }, - { "Description", "GC Compute creds" }, - { "Accessed", String.Format("{0}", lastAccessed) }, - { "Modified", String.Format("{0}", lastModified) }, - { "Size", String.Format("{0}", size) } - }); - } - string computeLegacyCreds = String.Format("{0}\\AppData\\Roaming\\gcloud\\legacy_credentials", System.Environment.GetEnvironmentVariable("USERPROFILE")); - if (System.IO.File.Exists(computeLegacyCreds)) - { - DateTime lastAccessed = System.IO.File.GetLastAccessTime(computeLegacyCreds); - DateTime lastModified = System.IO.File.GetLastWriteTime(computeLegacyCreds); - long size = new System.IO.FileInfo(computeLegacyCreds).Length; - results.Add(new Dictionary() { - { "file", computeLegacyCreds }, - { "Description", "GC Compute creds legacy" }, - { "Accessed", String.Format("{0}", lastAccessed) }, - { "Modified", String.Format("{0}", lastModified) }, - { "Size", String.Format("{0}", size) } - }); - } - string computeAccessTokensDb = String.Format("{0}\\AppData\\Roaming\\gcloud\\access_tokens.db", System.Environment.GetEnvironmentVariable("USERPROFILE")); - if (System.IO.File.Exists(computeAccessTokensDb)) - { - DateTime lastAccessed = System.IO.File.GetLastAccessTime(computeAccessTokensDb); - DateTime lastModified = System.IO.File.GetLastWriteTime(computeAccessTokensDb); - long size = new System.IO.FileInfo(computeAccessTokensDb).Length; - results.Add(new Dictionary() { - { "file", computeAccessTokensDb }, - { "Description", "GC Compute tokens" }, - { "Accessed", String.Format("{0}", lastAccessed) }, - { "Modified", String.Format("{0}", lastModified) }, - { "Size", String.Format("{0}", size) } - }); - } - string azureTokens = String.Format("{0}\\.azure\\accessTokens.json", System.Environment.GetEnvironmentVariable("USERPROFILE")); - if (System.IO.File.Exists(azureTokens)) - { - DateTime lastAccessed = System.IO.File.GetLastAccessTime(azureTokens); - DateTime lastModified = System.IO.File.GetLastWriteTime(azureTokens); - long size = new System.IO.FileInfo(azureTokens).Length; - results.Add(new Dictionary() { - { "file", azureTokens }, - { "Description", "Azure tokens" }, - { "Accessed", String.Format("{0}", lastAccessed) }, - { "Modified", String.Format("{0}", lastModified) }, - { "Size", String.Format("{0}", size) } - }); - } - string azureProfile = String.Format("{0}\\.azure\\azureProfile.json", System.Environment.GetEnvironmentVariable("USERPROFILE")); - if (System.IO.File.Exists(azureProfile)) - { - DateTime lastAccessed = System.IO.File.GetLastAccessTime(azureProfile); - DateTime lastModified = System.IO.File.GetLastWriteTime(azureProfile); - long size = new System.IO.FileInfo(azureProfile).Length; - results.Add(new Dictionary() { - { "file", azureProfile }, - { "Description", "Azure profile" }, - { "Accessed", String.Format("{0}", lastAccessed) }, - { "Modified", String.Format("{0}", lastModified) }, - { "Size", String.Format("{0}", size) } - }); - } - } - } - catch (Exception ex) - { - Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex)); - } - return results; - } - - - public static List> GetRecentFiles() - { - // parses recent file shortcuts via COM - List> results = new List>(); - int lastDays = 7; - DateTime startTime = System.DateTime.Now.AddDays(-lastDays); - - try - { - // WshShell COM object GUID - Type shell = Type.GetTypeFromCLSID(new Guid("F935DC22-1CF0-11d0-ADB9-00C04FD58A0B")); - Object shellObj = Activator.CreateInstance(shell); - - if (MyUtils.IsHighIntegrity()) - { - string userFolder = String.Format("{0}\\Users\\", Environment.GetEnvironmentVariable("SystemDrive")); - string[] dirs = Directory.GetDirectories(userFolder); - foreach (string dir in dirs) - { - string[] parts = dir.Split('\\'); - string userName = parts[parts.Length - 1]; - - if (!(dir.EndsWith("Public") || dir.EndsWith("Default") || dir.EndsWith("Default User") || dir.EndsWith("All Users"))) - { - string recentPath = String.Format("{0}\\AppData\\Roaming\\Microsoft\\Windows\\Recent\\", dir); - try - { - string[] recentFiles = Directory.GetFiles(recentPath, "*.lnk", SearchOption.AllDirectories); - - if (recentFiles.Length != 0) - { - Console.WriteLine(" {0} :\r\n", userName); - foreach (string recentFile in recentFiles) - { - DateTime lastAccessed = System.IO.File.GetLastAccessTime(recentFile); - - if (lastAccessed > startTime) - { - // invoke the WshShell com object, creating a shortcut to then extract the TargetPath from - Object shortcut = shellObj.GetType().InvokeMember("CreateShortcut", BindingFlags.InvokeMethod, null, shellObj, new object[] { recentFile }); - Object TargetPath = shortcut.GetType().InvokeMember("TargetPath", BindingFlags.GetProperty, null, shortcut, new object[] { }); - - if (TargetPath.ToString().Trim() != "") - { - results.Add(new Dictionary() - { - { "Target", TargetPath.ToString() }, - { "Accessed", String.Format("{0}", lastAccessed) } - }); - } - Marshal.ReleaseComObject(shortcut); - shortcut = null; - } - } - } - } - catch { } - } - } - } - else - { - string recentPath = String.Format("{0}\\Microsoft\\Windows\\Recent\\", System.Environment.GetEnvironmentVariable("APPDATA")); - - string[] recentFiles = Directory.GetFiles(recentPath, "*.lnk", SearchOption.AllDirectories); - - foreach (string recentFile in recentFiles) - { - // old method (needed interop dll) - //WshShell shell = new WshShell(); - //IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(recentFile); - - DateTime lastAccessed = System.IO.File.GetLastAccessTime(recentFile); - - if (lastAccessed > startTime) - { - // invoke the WshShell com object, creating a shortcut to then extract the TargetPath from - Object shortcut = shellObj.GetType().InvokeMember("CreateShortcut", BindingFlags.InvokeMethod, null, shellObj, new object[] { recentFile }); - Object TargetPath = shortcut.GetType().InvokeMember("TargetPath", BindingFlags.GetProperty, null, shortcut, new object[] { }); - if (TargetPath.ToString().Trim() != "") - { - results.Add(new Dictionary() - { - { "Target", TargetPath.ToString() }, - { "Accessed", String.Format("{0}", lastAccessed) } - }); - } - Marshal.ReleaseComObject(shortcut); - shortcut = null; - } - } - } - // release the WshShell COM object - Marshal.ReleaseComObject(shellObj); - shellObj = null; - } - catch (Exception ex) - { - Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex)); - } - return results; - } - - public static List> ListMasterKeys() - { - List> results = new List>(); - // lists any found DPAPI master keys - try - { - if (MyUtils.IsHighIntegrity()) - { - string userFolder = String.Format("{0}\\Users\\", Environment.GetEnvironmentVariable("SystemDrive")); - string[] dirs = Directory.GetDirectories(userFolder); - foreach (string dir in dirs) - { - string[] parts = dir.Split('\\'); - string userName = parts[parts.Length - 1]; - if (!(dir.EndsWith("Public") || dir.EndsWith("Default") || dir.EndsWith("Default User") || dir.EndsWith("All Users"))) - { - List userDPAPIBasePaths = new List(); - userDPAPIBasePaths.Add(String.Format("{0}\\AppData\\Roaming\\Microsoft\\Protect\\", System.Environment.GetEnvironmentVariable("USERPROFILE"))); - userDPAPIBasePaths.Add(String.Format("{0}\\AppData\\Local\\Microsoft\\Protect\\", System.Environment.GetEnvironmentVariable("USERPROFILE"))); - - foreach (string userDPAPIBasePath in userDPAPIBasePaths) - { - if (System.IO.Directory.Exists(userDPAPIBasePath)) - { - string[] directories = Directory.GetDirectories(userDPAPIBasePath); - foreach (string directory in directories) - { - string[] files = Directory.GetFiles(directory); - - foreach (string file in files) - { - if (Regex.IsMatch(file, @"[0-9A-Fa-f]{8}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{12}")) - { - DateTime lastAccessed = System.IO.File.GetLastAccessTime(file); - DateTime lastModified = System.IO.File.GetLastWriteTime(file); - string fileName = System.IO.Path.GetFileName(file); - results.Add(new Dictionary() - { - { "MasterKey", file }, - { "Accessed", String.Format("{0}", lastAccessed) }, - { "Modified", String.Format("{0}", lastModified) }, - }); - } - } - } - } - } - } - } - } - else - { - string userName = Environment.GetEnvironmentVariable("USERNAME"); - List userDPAPIBasePaths = new List(); - userDPAPIBasePaths.Add(String.Format("{0}\\AppData\\Roaming\\Microsoft\\Protect\\", System.Environment.GetEnvironmentVariable("USERPROFILE"))); - userDPAPIBasePaths.Add(String.Format("{0}\\AppData\\Local\\Microsoft\\Protect\\", System.Environment.GetEnvironmentVariable("USERPROFILE"))); - - foreach (string userDPAPIBasePath in userDPAPIBasePaths) - { - if (System.IO.Directory.Exists(userDPAPIBasePath)) - { - string[] directories = Directory.GetDirectories(userDPAPIBasePath); - foreach (string directory in directories) - { - string[] files = Directory.GetFiles(directory); - - foreach (string file in files) - { - if (Regex.IsMatch(file, @"[0-9A-Fa-f]{8}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{12}")) - { - DateTime lastAccessed = System.IO.File.GetLastAccessTime(file); - DateTime lastModified = System.IO.File.GetLastWriteTime(file); - string fileName = System.IO.Path.GetFileName(file); - results.Add(new Dictionary() - { - { "MasterKey", file }, - { "Accessed", String.Format("{0}", lastAccessed) }, - { "Modified", String.Format("{0}", lastModified) }, - }); - } - } - } - } - } - } - } - catch (Exception ex) - { - Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); - } - return results; - } - - - public static List> GetCredFiles() - { - List> results = new List>(); - // lists any found files in Local\Microsoft\Credentials\* - try - { - if (MyUtils.IsHighIntegrity()) - { - string userFolder = String.Format("{0}\\Users\\", Environment.GetEnvironmentVariable("SystemDrive")); - string[] dirs = Directory.GetDirectories(userFolder); - - foreach (string dir in dirs) - { - string[] parts = dir.Split('\\'); - string userName = parts[parts.Length - 1]; - if (!(dir.EndsWith("Public") || dir.EndsWith("Default") || dir.EndsWith("Default User") || dir.EndsWith("All Users"))) - { - List userCredFilePaths = new List(); - userCredFilePaths.Add(String.Format("{0}\\AppData\\Local\\Microsoft\\Credentials\\", dir)); - userCredFilePaths.Add(String.Format("{0}\\AppData\\Roaming\\Microsoft\\Credentials\\", dir)); - - foreach (string userCredFilePath in userCredFilePaths) - { - if (System.IO.Directory.Exists(userCredFilePath)) - { - string[] systemFiles = Directory.GetFiles(userCredFilePath); - if ((systemFiles != null) && (systemFiles.Length != 0)) - { - foreach (string file in systemFiles) - { - DateTime lastAccessed = System.IO.File.GetLastAccessTime(file); - DateTime lastModified = System.IO.File.GetLastWriteTime(file); - long size = new System.IO.FileInfo(file).Length; - string fileName = System.IO.Path.GetFileName(file); - - // jankily parse the bytes to extract the credential type and master key GUID - // reference- https://github.com/gentilkiwi/mimikatz/blob/3d8be22fff9f7222f9590aa007629e18300cf643/modules/kull_m_dpapi.h#L24-L54 - byte[] credentialArray = File.ReadAllBytes(file); - byte[] guidMasterKeyArray = new byte[16]; - Array.Copy(credentialArray, 36, guidMasterKeyArray, 0, 16); - Guid guidMasterKey = new Guid(guidMasterKeyArray); - - byte[] stringLenArray = new byte[16]; - Array.Copy(credentialArray, 56, stringLenArray, 0, 4); - int descLen = BitConverter.ToInt32(stringLenArray, 0); - - byte[] descBytes = new byte[descLen]; - Array.Copy(credentialArray, 60, descBytes, 0, descLen - 4); - - string desc = Encoding.Unicode.GetString(descBytes); - results.Add(new Dictionary() - { - { "CredFile", file }, - { "Description", desc }, - { "MasterKey", String.Format("{0}", guidMasterKey) }, - { "Accessed", String.Format("{0}", lastAccessed) }, - { "Modified", String.Format("{0}", lastModified) }, - { "Size", String.Format("{0}", size) }, - }); - } - } - } - } - } - } - - string systemFolder = String.Format("{0}\\System32\\config\\systemprofile\\AppData\\Local\\Microsoft\\Credentials", Environment.GetEnvironmentVariable("SystemRoot")); - string[] files = Directory.GetFiles(systemFolder); - if ((files != null) && (files.Length != 0)) - { - foreach (string file in files) - { - DateTime lastAccessed = System.IO.File.GetLastAccessTime(file); - DateTime lastModified = System.IO.File.GetLastWriteTime(file); - long size = new System.IO.FileInfo(file).Length; - string fileName = System.IO.Path.GetFileName(file); - - // jankily parse the bytes to extract the credential type and master key GUID - // reference- https://github.com/gentilkiwi/mimikatz/blob/3d8be22fff9f7222f9590aa007629e18300cf643/modules/kull_m_dpapi.h#L24-L54 - byte[] credentialArray = File.ReadAllBytes(file); - byte[] guidMasterKeyArray = new byte[16]; - Array.Copy(credentialArray, 36, guidMasterKeyArray, 0, 16); - Guid guidMasterKey = new Guid(guidMasterKeyArray); - - byte[] stringLenArray = new byte[16]; - Array.Copy(credentialArray, 56, stringLenArray, 0, 4); - int descLen = BitConverter.ToInt32(stringLenArray, 0); - - byte[] descBytes = new byte[descLen]; - Array.Copy(credentialArray, 60, descBytes, 0, descLen - 4); - - string desc = Encoding.Unicode.GetString(descBytes); - results.Add(new Dictionary() - { - { "CredFile", file }, - { "Description", desc }, - { "MasterKey", String.Format("{0}", guidMasterKey) }, - { "Accessed", String.Format("{0}", lastAccessed) }, - { "Modified", String.Format("{0}", lastModified) }, - { "Size", String.Format("{0}", size) }, - }); - } - } - } - else - { - string userName = Environment.GetEnvironmentVariable("USERNAME"); - List userCredFilePaths = new List(); - userCredFilePaths.Add(String.Format("{0}\\AppData\\Local\\Microsoft\\Credentials\\", System.Environment.GetEnvironmentVariable("USERPROFILE"))); - userCredFilePaths.Add(String.Format("{0}\\AppData\\Roaming\\Microsoft\\Credentials\\", System.Environment.GetEnvironmentVariable("USERPROFILE"))); - - foreach (string userCredFilePath in userCredFilePaths) - { - if (System.IO.Directory.Exists(userCredFilePath)) - { - string[] files = Directory.GetFiles(userCredFilePath); - - foreach (string file in files) - { - DateTime lastAccessed = System.IO.File.GetLastAccessTime(file); - DateTime lastModified = System.IO.File.GetLastWriteTime(file); - long size = new System.IO.FileInfo(file).Length; - string fileName = System.IO.Path.GetFileName(file); - - // jankily parse the bytes to extract the credential type and master key GUID - // reference- https://github.com/gentilkiwi/mimikatz/blob/3d8be22fff9f7222f9590aa007629e18300cf643/modules/kull_m_dpapi.h#L24-L54 - byte[] credentialArray = File.ReadAllBytes(file); - byte[] guidMasterKeyArray = new byte[16]; - Array.Copy(credentialArray, 36, guidMasterKeyArray, 0, 16); - Guid guidMasterKey = new Guid(guidMasterKeyArray); - - byte[] stringLenArray = new byte[16]; - Array.Copy(credentialArray, 56, stringLenArray, 0, 4); - int descLen = BitConverter.ToInt32(stringLenArray, 0); - - byte[] descBytes = new byte[descLen]; - Array.Copy(credentialArray, 60, descBytes, 0, descLen - 4); - - string desc = Encoding.Unicode.GetString(descBytes); - results.Add(new Dictionary() - { - { "CredFile", file }, - { "Description", desc }, - { "MasterKey", String.Format("{0}", guidMasterKey) }, - { "Accessed", String.Format("{0}", lastAccessed) }, - { "Modified", String.Format("{0}", lastModified) }, - { "Size", String.Format("{0}", size) }, - }); - } - } - } - } - } - catch (Exception ex) - { - Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); - } - return results; - } - - - public static List> GetRDCManFiles() - { - List> results = new List>(); - // lists any found files in Local\Microsoft\Credentials\* - try - { - if (MyUtils.IsHighIntegrity()) - { - string userFolder = String.Format("{0}\\Users\\", Environment.GetEnvironmentVariable("SystemDrive")); - string[] dirs = Directory.GetDirectories(userFolder); - - foreach (string dir in dirs) - { - string[] parts = dir.Split('\\'); - string userName = parts[parts.Length - 1]; - if (!(dir.EndsWith("Public") || dir.EndsWith("Default") || dir.EndsWith("Default User") || dir.EndsWith("All Users"))) - { - string userRDManFile = String.Format("{0}\\AppData\\Local\\Microsoft\\Remote Desktop Connection Manager\\RDCMan.settings", dir); - if (System.IO.File.Exists(userRDManFile)) - { - XmlDocument xmlDoc = new XmlDocument(); - xmlDoc.Load(userRDManFile); - - // grab the recent RDG files - XmlNodeList filesToOpen = xmlDoc.GetElementsByTagName("FilesToOpen"); - XmlNodeList items = filesToOpen[0].ChildNodes; - XmlNode node = items[0]; - - DateTime lastAccessed = System.IO.File.GetLastAccessTime(userRDManFile); - DateTime lastModified = System.IO.File.GetLastWriteTime(userRDManFile); - Dictionary rdg = new Dictionary(){ - { "RDCManFile", userRDManFile }, - { "Accessed", String.Format("{0}", lastAccessed) }, - { "Modified", String.Format("{0}", lastModified) }, - { ".RDG Files", "" }, - }; - - foreach (XmlNode rdgFile in items) - rdg[".RDG Files"] += rdgFile.InnerText; - - results.Add(rdg); - } - } - } - } - else - { - string userName = Environment.GetEnvironmentVariable("USERNAME"); - string userRDManFile = String.Format("{0}\\AppData\\Local\\Microsoft\\Remote Desktop Connection Manager\\RDCMan.settings", System.Environment.GetEnvironmentVariable("USERPROFILE")); - - if (System.IO.File.Exists(userRDManFile)) - { - XmlDocument xmlDoc = new XmlDocument(); - xmlDoc.Load(userRDManFile); - - // grab the recent RDG files - XmlNodeList filesToOpen = xmlDoc.GetElementsByTagName("FilesToOpen"); - XmlNodeList items = filesToOpen[0].ChildNodes; - XmlNode node = items[0]; - - DateTime lastAccessed = System.IO.File.GetLastAccessTime(userRDManFile); - DateTime lastModified = System.IO.File.GetLastWriteTime(userRDManFile); - Dictionary rdg = new Dictionary(){ - { "RDCManFile", userRDManFile }, - { "Accessed", String.Format("{0}", lastAccessed) }, - { "Modified", String.Format("{0}", lastModified) }, - { ".RDG Files", "" }, - }; - - foreach (XmlNode rdgFile in items) - rdg[".RDG Files"] += rdgFile.InnerText; - results.Add(rdg); - } - } - } - catch (Exception ex) - { - Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); - } - return results; - } - - - [DllImport("advapi32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - static extern bool OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle); - - [DllImport("secur32.dll", SetLastError = true)] - public static extern int LsaRegisterLogonProcess(LSA_STRING_IN LogonProcessName, out IntPtr LsaHandle, out ulong SecurityMode); - - [DllImport("advapi32.dll")] - public extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle); - - [DllImport("advapi32.dll", SetLastError = true)] - static extern bool ImpersonateLoggedOnUser(IntPtr hToken); - - [DllImport("kernel32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - static extern bool CloseHandle(IntPtr hObject); - - [DllImport("advapi32.dll", SetLastError = true)] - static extern bool RevertToSelf(); - - [DllImport("Secur32.dll", SetLastError = false)] - private static extern uint LsaEnumerateLogonSessions(out UInt64 LogonSessionCount, out IntPtr LogonSessionList); - - [DllImport("Secur32.dll", SetLastError = false)] - private static extern uint LsaGetLogonSessionData(IntPtr luid, out IntPtr ppLogonSessionData); - - [DllImport("secur32.dll", SetLastError = false)] - public static extern int LsaLookupAuthenticationPackage([In] IntPtr LsaHandle, [In] ref LSA_STRING_IN PackageName, [Out] out int AuthenticationPackage); - - [DllImport("secur32.dll", SetLastError = false)] - private static extern int LsaCallAuthenticationPackage(IntPtr LsaHandle, int AuthenticationPackage, ref KERB_QUERY_TKT_CACHE_REQUEST ProtocolSubmitBuffer, int SubmitBufferLength, out IntPtr ProtocolReturnBuffer, out int ReturnBufferLength, out int ProtocolStatus); - - [DllImport("secur32.dll", SetLastError = false)] - private static extern uint LsaFreeReturnBuffer(IntPtr buffer); - [DllImport("secur32.dll", SetLastError = false)] - private static extern int LsaConnectUntrusted([Out] out IntPtr LsaHandle); - - [DllImport("secur32.dll", SetLastError = false)] - private static extern int LsaDeregisterLogonProcess([In] IntPtr LsaHandle); - - [DllImport("secur32.dll", EntryPoint = "LsaCallAuthenticationPackage", SetLastError = false)] - private static extern int LsaCallAuthenticationPackage_KERB_RETRIEVE_TKT(IntPtr LsaHandle, int AuthenticationPackage, ref KERB_RETRIEVE_TKT_REQUEST ProtocolSubmitBuffer, int SubmitBufferLength, out IntPtr ProtocolReturnBuffer, out int ReturnBufferLength, out int ProtocolStatus); - - - [StructLayout(LayoutKind.Sequential)] - public struct LSA_STRING_IN - { - public UInt16 Length; - public UInt16 MaximumLength; - public string Buffer; - } - [StructLayout(LayoutKind.Sequential)] - public struct LSA_STRING_OUT - { - public UInt16 Length; - public UInt16 MaximumLength; - public IntPtr Buffer; - } - [StructLayout(LayoutKind.Sequential)] - protected struct LUID - { - public uint LowPart; - public int HighPart; - } - [StructLayout(LayoutKind.Sequential)] - private struct SECURITY_LOGON_SESSION_DATA - { - public UInt32 Size; - public LUID LoginID; - public LSA_STRING_OUT Username; - public LSA_STRING_OUT LoginDomain; - public LSA_STRING_OUT AuthenticationPackage; - public UInt32 LogonType; - public UInt32 Session; - public IntPtr PSiD; - public UInt64 LoginTime; - public LSA_STRING_OUT LogonServer; - public LSA_STRING_OUT DnsDomainName; - public LSA_STRING_OUT Upn; - } - [StructLayout(LayoutKind.Sequential)] - private struct KERB_QUERY_TKT_CACHE_REQUEST - { - public KERB_PROTOCOL_MESSAGE_TYPE MessageType; - public LUID LogonId; - } - public enum KERB_PROTOCOL_MESSAGE_TYPE : UInt32 - { - KerbDebugRequestMessage = 0, - KerbQueryTicketCacheMessage = 1, - KerbChangeMachinePasswordMessage = 2, - KerbVerifyPacMessage = 3, - KerbRetrieveTicketMessage = 4, - KerbUpdateAddressesMessage = 5, - KerbPurgeTicketCacheMessage = 6, - KerbChangePasswordMessage = 7, - KerbRetrieveEncodedTicketMessage = 8, - KerbDecryptDataMessage = 9, - KerbAddBindingCacheEntryMessage = 10, - KerbSetPasswordMessage = 11, - KerbSetPasswordExMessage = 12, - KerbVerifyCredentialsMessage = 13, - KerbQueryTicketCacheExMessage = 14, - KerbPurgeTicketCacheExMessage = 15, - KerbRefreshSmartcardCredentialsMessage = 16, - KerbAddExtraCredentialsMessage = 17, - KerbQuerySupplementalCredentialsMessage = 18, - KerbTransferCredentialsMessage = 19, - KerbQueryTicketCacheEx2Message = 20, - KerbSubmitTicketMessage = 21, - KerbAddExtraCredentialsExMessage = 22, - KerbQueryKdcProxyCacheMessage = 23, - KerbPurgeKdcProxyCacheMessage = 24, - KerbQueryTicketCacheEx3Message = 25, - KerbCleanupMachinePkinitCredsMessage = 26, - KerbAddBindingCacheEntryExMessage = 27, - KerbQueryBindingCacheMessage = 28, - KerbPurgeBindingCacheMessage = 29, - KerbQueryDomainExtendedPoliciesMessage = 30, - KerbQueryS4U2ProxyCacheMessage = 31 - } - [StructLayout(LayoutKind.Sequential)] - private struct KERB_QUERY_TKT_CACHE_RESPONSE - { - public KERB_PROTOCOL_MESSAGE_TYPE MessageType; - public int CountOfTickets; - // public KERB_TICKET_CACHE_INFO[] Tickets; - public IntPtr Tickets; - } - [StructLayout(LayoutKind.Sequential)] - public struct KERB_TICKET_CACHE_INFO - { - public LSA_STRING_OUT ServerName; - public LSA_STRING_OUT RealmName; - public Int64 StartTime; - public Int64 EndTime; - public Int64 RenewTime; - public Int32 EncryptionType; - public UInt32 TicketFlags; - } - [StructLayout(LayoutKind.Sequential)] - private struct KERB_RETRIEVE_TKT_RESPONSE - { - public KERB_EXTERNAL_TICKET Ticket; - } - [StructLayout(LayoutKind.Sequential)] - private struct KERB_CRYPTO_KEY - { - public Int32 KeyType; - public Int32 Length; - public IntPtr Value; - } - [StructLayout(LayoutKind.Sequential)] - private struct KERB_EXTERNAL_TICKET - { - public IntPtr ServiceName; - public IntPtr TargetName; - public IntPtr ClientName; - public LSA_STRING_OUT DomainName; - public LSA_STRING_OUT TargetDomainName; - public LSA_STRING_OUT AltTargetDomainName; - public KERB_CRYPTO_KEY SessionKey; - public UInt32 TicketFlags; - public UInt32 Flags; - public Int64 KeyExpirationTime; - public Int64 StartTime; - public Int64 EndTime; - public Int64 RenewUntil; - public Int64 TimeSkew; - public Int32 EncodedTicketSize; - public IntPtr EncodedTicket; - } - [StructLayout(LayoutKind.Sequential)] - private struct KERB_RETRIEVE_TKT_REQUEST - { - public KERB_PROTOCOL_MESSAGE_TYPE MessageType; - public LUID LogonId; - public LSA_STRING_IN TargetName; - public UInt64 TicketFlags; - public KERB_CACHE_OPTIONS CacheOptions; - public Int64 EncryptionType; - public SECURITY_HANDLE CredentialsHandle; - } - [StructLayout(LayoutKind.Sequential)] - public struct SECURITY_HANDLE - { - public IntPtr LowPart; - public IntPtr HighPart; - public SECURITY_HANDLE(int dummy) - { - LowPart = HighPart = IntPtr.Zero; - } - }; - [StructLayout(LayoutKind.Sequential)] - private struct KERB_EXTERNAL_NAME - { - public Int16 NameType; - public UInt16 NameCount; - public LSA_STRING_OUT Names; - } - [Flags] - private enum KERB_CACHE_OPTIONS : UInt64 - { - KERB_RETRIEVE_TICKET_DEFAULT = 0x0, - KERB_RETRIEVE_TICKET_DONT_USE_CACHE = 0x1, - KERB_RETRIEVE_TICKET_USE_CACHE_ONLY = 0x2, - KERB_RETRIEVE_TICKET_USE_CREDHANDLE = 0x4, - KERB_RETRIEVE_TICKET_AS_KERB_CRED = 0x8, - KERB_RETRIEVE_TICKET_WITH_SEC_CRED = 0x10, - KERB_RETRIEVE_TICKET_CACHE_TICKET = 0x20, - KERB_RETRIEVE_TICKET_MAX_LIFETIME = 0x40, - } - - private enum SECURITY_LOGON_TYPE : uint - { - Interactive = 2, // logging on interactively. - Network, // logging using a network. - Batch, // logon for a batch process. - Service, // logon for a service account. - Proxy, // Not supported. - Unlock, // Tattempt to unlock a workstation. - NetworkCleartext, // network logon with cleartext credentials - NewCredentials, // caller can clone its current token and specify new credentials for outbound connections - RemoteInteractive, // terminal server session that is both remote and interactive - CachedInteractive, // attempt to use the cached credentials without going out across the network - CachedRemoteInteractive,// same as RemoteInteractive, except used internally for auditing purposes - CachedUnlock // attempt to unlock a workstation - } - public enum KERB_ENCRYPTION_TYPE : UInt32 - { - reserved0 = 0, - des_cbc_crc = 1, - des_cbc_md4 = 2, - des_cbc_md5 = 3, - reserved1 = 4, - des3_cbc_md5 = 5, - reserved2 = 6, - des3_cbc_sha1 = 7, - dsaWithSHA1_CmsOID = 9, - md5WithRSAEncryption_CmsOID = 10, - sha1WithRSAEncryption_CmsOID = 11, - rc2CBC_EnvOID = 12, - rsaEncryption_EnvOID = 13, - rsaES_OAEP_ENV_OID = 14, - des_ede3_cbc_Env_OID = 15, - des3_cbc_sha1_kd = 16, - aes128_cts_hmac_sha1_96 = 17, - aes256_cts_hmac_sha1_96 = 18, - aes128_cts_hmac_sha256_128 = 19, - aes256_cts_hmac_sha384_192 = 20, - rc4_hmac = 23, - rc4_hmac_exp = 24, - camellia128_cts_cmac = 25, - camellia256_cts_cmac = 26, - subkey_keymaterial = 65 - } - [Flags] - public enum KERB_TICKET_FLAGS : UInt32 - { - reserved = 2147483648, - forwardable = 0x40000000, - forwarded = 0x20000000, - proxiable = 0x10000000, - proxy = 0x08000000, - may_postdate = 0x04000000, - postdated = 0x02000000, - invalid = 0x01000000, - renewable = 0x00800000, - initial = 0x00400000, - pre_authent = 0x00200000, - hw_authent = 0x00100000, - ok_as_delegate = 0x00040000, - name_canonicalize = 0x00010000, - //cname_in_pa_data = 0x00040000, - enc_pa_rep = 0x00010000, - reserved1 = 0x00000001 - } - public static IntPtr LsaRegisterLogonProcessHelper() - { - // helper that establishes a connection to the LSA server and verifies that the caller is a logon application - // used for Kerberos ticket enumeration - - string logonProcessName = "User32LogonProcesss"; - LSA_STRING_IN LSAString; - IntPtr lsaHandle = IntPtr.Zero; - UInt64 securityMode = 0; - - LSAString.Length = (ushort)logonProcessName.Length; - LSAString.MaximumLength = (ushort)(logonProcessName.Length + 1); - LSAString.Buffer = logonProcessName; - - int ret = LsaRegisterLogonProcess(LSAString, out lsaHandle, out securityMode); - - return lsaHandle; - } - - public static bool GetSystem() - { - // helper to elevate to SYSTEM for Kerberos ticket enumeration via token impersonation - - if (MyUtils.IsHighIntegrity()) - { - IntPtr hToken = IntPtr.Zero; - - // Open winlogon's token with TOKEN_DUPLICATE accesss so ca can make a copy of the token with DuplicateToken - Process[] processes = Process.GetProcessesByName("winlogon"); - IntPtr handle = processes[0].Handle; - - // TOKEN_DUPLICATE = 0x0002 - bool success = OpenProcessToken(handle, 0x0002, out hToken); - if (!success) - { - //Console.WriteLine("OpenProcessToken failed!"); - return false; - } - - // make a copy of the NT AUTHORITY\SYSTEM token from winlogon - // 2 == SecurityImpersonation - IntPtr hDupToken = IntPtr.Zero; - success = DuplicateToken(hToken, 2, ref hDupToken); - if (!success) - { - //Console.WriteLine("DuplicateToken failed!"); - return false; - } - - success = ImpersonateLoggedOnUser(hDupToken); - if (!success) - { - //Console.WriteLine("ImpersonateLoggedOnUser failed!"); - return false; - } - - // clean up the handles we created - CloseHandle(hToken); - CloseHandle(hDupToken); - - string name = System.Security.Principal.WindowsIdentity.GetCurrent().Name; - if (name != "NT AUTHORITY\\SYSTEM") - { - return false; - } - - return true; - } - else - { - return false; - } - } - - public static List> ListKerberosTickets() - { - if (MyUtils.IsHighIntegrity()) - { - return ListKerberosTicketsAllUsers(); - } - else - { - return ListKerberosTicketsCurrentUser(); - } - } - - public static List> ListKerberosTicketsAllUsers() - { - List> results = new List>(); - // adapted partially from Vincent LE TOUX' work - // https://github.com/vletoux/MakeMeEnterpriseAdmin/blob/master/MakeMeEnterpriseAdmin.ps1#L2939-L2950 - // and https://www.dreamincode.net/forums/topic/135033-increment-memory-pointer-issue/ - // also Jared Atkinson's work at https://github.com/Invoke-IR/ACE/blob/master/ACE-Management/PS-ACE/Scripts/ACE_Get-KerberosTicketCache.ps1 - - IntPtr hLsa = LsaRegisterLogonProcessHelper(); - int totalTicketCount = 0; - - // if the original call fails then it is likely we don't have SeTcbPrivilege - // to get SeTcbPrivilege we can Impersonate a NT AUTHORITY\SYSTEM Token - if (hLsa == IntPtr.Zero) - { - GetSystem(); - // should now have the proper privileges to get a Handle to LSA - hLsa = LsaRegisterLogonProcessHelper(); - // we don't need our NT AUTHORITY\SYSTEM Token anymore so we can revert to our original token - RevertToSelf(); - } - - try - { - // first return all the logon sessions - - DateTime systime = new DateTime(1601, 1, 1, 0, 0, 0, 0); //win32 systemdate - UInt64 count; - IntPtr luidPtr = IntPtr.Zero; - IntPtr iter = luidPtr; - - uint ret = LsaEnumerateLogonSessions(out count, out luidPtr); // get an array of pointers to LUIDs - - for (ulong i = 0; i < count; i++) - { - IntPtr sessionData; - ret = LsaGetLogonSessionData(luidPtr, out sessionData); - SECURITY_LOGON_SESSION_DATA data = (SECURITY_LOGON_SESSION_DATA)Marshal.PtrToStructure(sessionData, typeof(SECURITY_LOGON_SESSION_DATA)); - - // if we have a valid logon - if (data.PSiD != IntPtr.Zero) - { - // user session data - string username = Marshal.PtrToStringUni(data.Username.Buffer).Trim(); - System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(data.PSiD); - string domain = Marshal.PtrToStringUni(data.LoginDomain.Buffer).Trim(); - string authpackage = Marshal.PtrToStringUni(data.AuthenticationPackage.Buffer).Trim(); - SECURITY_LOGON_TYPE logonType = (SECURITY_LOGON_TYPE)data.LogonType; - DateTime logonTime = systime.AddTicks((long)data.LoginTime); - string logonServer = Marshal.PtrToStringUni(data.LogonServer.Buffer).Trim(); - string dnsDomainName = Marshal.PtrToStringUni(data.DnsDomainName.Buffer).Trim(); - string upn = Marshal.PtrToStringUni(data.Upn.Buffer).Trim(); - - // now we want to get the tickets for this logon ID - string name = "kerberos"; - LSA_STRING_IN LSAString; - LSAString.Length = (ushort)name.Length; - LSAString.MaximumLength = (ushort)(name.Length + 1); - LSAString.Buffer = name; - - IntPtr ticketPointer = IntPtr.Zero; - IntPtr ticketsPointer = IntPtr.Zero; - DateTime sysTime = new DateTime(1601, 1, 1, 0, 0, 0, 0); - int authPack; - int returnBufferLength = 0; - int protocalStatus = 0; - int retCode; - - KERB_QUERY_TKT_CACHE_REQUEST tQuery = new KERB_QUERY_TKT_CACHE_REQUEST(); - KERB_QUERY_TKT_CACHE_RESPONSE tickets = new KERB_QUERY_TKT_CACHE_RESPONSE(); - KERB_TICKET_CACHE_INFO ticket; - - // obtains the unique identifier for the kerberos authentication package. - retCode = LsaLookupAuthenticationPackage(hLsa, ref LSAString, out authPack); - - // input object for querying the ticket cache for a specific logon ID - LUID userLogonID = new LUID(); - userLogonID.LowPart = data.LoginID.LowPart; - userLogonID.HighPart = 0; - tQuery.LogonId = userLogonID; - tQuery.MessageType = KERB_PROTOCOL_MESSAGE_TYPE.KerbQueryTicketCacheMessage; - - // query LSA, specifying we want the ticket cache - retCode = LsaCallAuthenticationPackage(hLsa, authPack, ref tQuery, Marshal.SizeOf(tQuery), out ticketPointer, out returnBufferLength, out protocalStatus); - - /*Console.WriteLine("\r\n UserName : {0}", username); - Console.WriteLine(" Domain : {0}", domain); - Console.WriteLine(" LogonId : {0}", data.LoginID.LowPart); - Console.WriteLine(" UserSID : {0}", sid.AccountDomainSid); - Console.WriteLine(" AuthenticationPackage : {0}", authpackage); - Console.WriteLine(" LogonType : {0}", logonType); - Console.WriteLine(" LogonType : {0}", logonTime); - Console.WriteLine(" LogonServer : {0}", logonServer); - Console.WriteLine(" LogonServerDNSDomain : {0}", dnsDomainName); - Console.WriteLine(" UserPrincipalName : {0}\r\n", upn);*/ - - if (ticketPointer != IntPtr.Zero) - { - // parse the returned pointer into our initial KERB_QUERY_TKT_CACHE_RESPONSE structure - tickets = (KERB_QUERY_TKT_CACHE_RESPONSE)Marshal.PtrToStructure((System.IntPtr)ticketPointer, typeof(KERB_QUERY_TKT_CACHE_RESPONSE)); - int count2 = tickets.CountOfTickets; - - if (count2 != 0) - { - Console.WriteLine(" [*] Enumerated {0} ticket(s):\r\n", count2); - totalTicketCount += count2; - // get the size of the structures we're iterating over - Int32 dataSize = Marshal.SizeOf(typeof(KERB_TICKET_CACHE_INFO)); - - for (int j = 0; j < count2; j++) - { - // iterate through the structures - IntPtr currTicketPtr = (IntPtr)(long)((ticketPointer.ToInt64() + (int)(8 + j * dataSize))); - - // parse the new ptr to the appropriate structure - ticket = (KERB_TICKET_CACHE_INFO)Marshal.PtrToStructure(currTicketPtr, typeof(KERB_TICKET_CACHE_INFO)); - - // extract our fields - string serverName = Marshal.PtrToStringUni(ticket.ServerName.Buffer, ticket.ServerName.Length / 2); - string realmName = Marshal.PtrToStringUni(ticket.RealmName.Buffer, ticket.RealmName.Length / 2); - DateTime startTime = DateTime.FromFileTime(ticket.StartTime); - DateTime endTime = DateTime.FromFileTime(ticket.EndTime); - DateTime renewTime = DateTime.FromFileTime(ticket.RenewTime); - string encryptionType = ((KERB_ENCRYPTION_TYPE)ticket.EncryptionType).ToString(); - string ticketFlags = ((KERB_TICKET_FLAGS)ticket.TicketFlags).ToString(); - - results.Add(new Dictionary() - { - { "UserPrincipalName", upn }, - { "serverName", serverName }, - { "RealmName", realmName }, - { "StartTime", String.Format("{0}", startTime) }, - { "EndTime", String.Format("{0}", endTime) }, - { "RenewTime", String.Format("{0}", renewTime) }, - { "EncryptionType", encryptionType }, - { "TicketFlags", ticketFlags }, - }); - } - } - } - } - // move the pointer forward - luidPtr = (IntPtr)((long)luidPtr.ToInt64() + Marshal.SizeOf(typeof(LUID))); - LsaFreeReturnBuffer(sessionData); - } - LsaFreeReturnBuffer(luidPtr); - - // disconnect from LSA - LsaDeregisterLogonProcess(hLsa); - } - catch (Exception ex) - { - Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); - } - return results; - } - - public static List> ListKerberosTicketsCurrentUser() - { - List> results = new List>(); - // adapted partially from Vincent LE TOUX' work - // https://github.com/vletoux/MakeMeEnterpriseAdmin/blob/master/MakeMeEnterpriseAdmin.ps1#L2939-L2950 - // and https://www.dreamincode.net/forums/topic/135033-increment-memory-pointer-issue/ - // also Jared Atkinson's work at https://github.com/Invoke-IR/ACE/blob/master/ACE-Management/PS-ACE/Scripts/ACE_Get-KerberosTicketCache.ps1 - - try - { - string name = "kerberos"; - LSA_STRING_IN LSAString; - LSAString.Length = (ushort)name.Length; - LSAString.MaximumLength = (ushort)(name.Length + 1); - LSAString.Buffer = name; - - IntPtr ticketPointer = IntPtr.Zero; - IntPtr ticketsPointer = IntPtr.Zero; - DateTime sysTime = new DateTime(1601, 1, 1, 0, 0, 0, 0); - int authPack; - int returnBufferLength = 0; - int protocalStatus = 0; - IntPtr lsaHandle; - int retCode; - - // If we want to look at tickets from a session other than our own - // then we need to use LsaRegisterLogonProcess instead of LsaConnectUntrusted - retCode = LsaConnectUntrusted(out lsaHandle); - - KERB_QUERY_TKT_CACHE_REQUEST tQuery = new KERB_QUERY_TKT_CACHE_REQUEST(); - KERB_QUERY_TKT_CACHE_RESPONSE tickets = new KERB_QUERY_TKT_CACHE_RESPONSE(); - KERB_TICKET_CACHE_INFO ticket; - - // obtains the unique identifier for the kerberos authentication package. - retCode = LsaLookupAuthenticationPackage(lsaHandle, ref LSAString, out authPack); - - // input object for querying the ticket cache (https://docs.microsoft.com/en-us/windows/desktop/api/ntsecapi/ns-ntsecapi-_kerb_query_tkt_cache_request) - tQuery.LogonId = new LUID(); - tQuery.MessageType = KERB_PROTOCOL_MESSAGE_TYPE.KerbQueryTicketCacheMessage; - - // query LSA, specifying we want the ticket cache - retCode = LsaCallAuthenticationPackage(lsaHandle, authPack, ref tQuery, Marshal.SizeOf(tQuery), out ticketPointer, out returnBufferLength, out protocalStatus); - - // parse the returned pointer into our initial KERB_QUERY_TKT_CACHE_RESPONSE structure - tickets = (KERB_QUERY_TKT_CACHE_RESPONSE)Marshal.PtrToStructure((System.IntPtr)ticketPointer, typeof(KERB_QUERY_TKT_CACHE_RESPONSE)); - int count = tickets.CountOfTickets; - - // get the size of the structures we're iterating over - Int32 dataSize = Marshal.SizeOf(typeof(KERB_TICKET_CACHE_INFO)); - - for (int i = 0; i < count; i++) - { - // iterate through the structures - IntPtr currTicketPtr = (IntPtr)(long)((ticketPointer.ToInt64() + (int)(8 + i * dataSize))); - - // parse the new ptr to the appropriate structure - ticket = (KERB_TICKET_CACHE_INFO)Marshal.PtrToStructure(currTicketPtr, typeof(KERB_TICKET_CACHE_INFO)); - - // extract our fields - string serverName = Marshal.PtrToStringUni(ticket.ServerName.Buffer, ticket.ServerName.Length / 2); - string realmName = Marshal.PtrToStringUni(ticket.RealmName.Buffer, ticket.RealmName.Length / 2); - DateTime startTime = DateTime.FromFileTime(ticket.StartTime); - DateTime endTime = DateTime.FromFileTime(ticket.EndTime); - DateTime renewTime = DateTime.FromFileTime(ticket.RenewTime); - string encryptionType = ((KERB_ENCRYPTION_TYPE)ticket.EncryptionType).ToString(); - string ticketFlags = ((KERB_TICKET_FLAGS)ticket.TicketFlags).ToString(); - - results.Add(new Dictionary() - { - { "serverName", serverName }, - { "RealmName", realmName }, - { "StartTime", String.Format("{0}", startTime) }, - { "EndTime", String.Format("{0}", endTime) }, - { "RenewTime", String.Format("{0}", renewTime) }, - { "EncryptionType", encryptionType }, - { "TicketFlags", ticketFlags }, - }); - } - - // disconnect from LSA - LsaDeregisterLogonProcess(lsaHandle); - } - catch (Exception ex) - { - Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); - } - return results; - } - - public static List> GetKerberosTGTData() - { - if (MyUtils.IsHighIntegrity()) - { - return ListKerberosTGTDataAllUsers(); - } - else - { - return ListKerberosTGTDataCurrentUser(); - } - } - - public static List> ListKerberosTGTDataAllUsers() - { - List> results = new List>(); - // adapted partially from Vincent LE TOUX' work - // https://github.com/vletoux/MakeMeEnterpriseAdmin/blob/master/MakeMeEnterpriseAdmin.ps1#L2939-L2950 - // and https://www.dreamincode.net/forums/topic/135033-increment-memory-pointer-issue/ - // also Jared Atkinson's work at https://github.com/Invoke-IR/ACE/blob/master/ACE-Management/PS-ACE/Scripts/ACE_Get-KerberosTicketCache.ps1 - - IntPtr hLsa = LsaRegisterLogonProcessHelper(); - int totalTicketCount = 0; - - // if the original call fails then it is likely we don't have SeTcbPrivilege - // to get SeTcbPrivilege we can Impersonate a NT AUTHORITY\SYSTEM Token - if (hLsa == IntPtr.Zero) - { - GetSystem(); - // should now have the proper privileges to get a Handle to LSA - hLsa = LsaRegisterLogonProcessHelper(); - // we don't need our NT AUTHORITY\SYSTEM Token anymore so we can revert to our original token - RevertToSelf(); - } - - try - { - // first return all the logon sessions - - DateTime systime = new DateTime(1601, 1, 1, 0, 0, 0, 0); //win32 systemdate - UInt64 count; - IntPtr luidPtr = IntPtr.Zero; - IntPtr iter = luidPtr; - - uint ret = LsaEnumerateLogonSessions(out count, out luidPtr); // get an array of pointers to LUIDs - - for (ulong i = 0; i < count; i++) - { - IntPtr sessionData; - ret = LsaGetLogonSessionData(luidPtr, out sessionData); - SECURITY_LOGON_SESSION_DATA data = (SECURITY_LOGON_SESSION_DATA)Marshal.PtrToStructure(sessionData, typeof(SECURITY_LOGON_SESSION_DATA)); - - // if we have a valid logon - if (data.PSiD != IntPtr.Zero) - { - // user session data - string username = Marshal.PtrToStringUni(data.Username.Buffer).Trim(); - System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(data.PSiD); - string domain = Marshal.PtrToStringUni(data.LoginDomain.Buffer).Trim(); - string authpackage = Marshal.PtrToStringUni(data.AuthenticationPackage.Buffer).Trim(); - SECURITY_LOGON_TYPE logonType = (SECURITY_LOGON_TYPE)data.LogonType; - DateTime logonTime = systime.AddTicks((long)data.LoginTime); - string logonServer = Marshal.PtrToStringUni(data.LogonServer.Buffer).Trim(); - string dnsDomainName = Marshal.PtrToStringUni(data.DnsDomainName.Buffer).Trim(); - string upn = Marshal.PtrToStringUni(data.Upn.Buffer).Trim(); - - // now we want to get the tickets for this logon ID - string name = "kerberos"; - LSA_STRING_IN LSAString; - LSAString.Length = (ushort)name.Length; - LSAString.MaximumLength = (ushort)(name.Length + 1); - LSAString.Buffer = name; - - IntPtr responsePointer = IntPtr.Zero; - int authPack; - int returnBufferLength = 0; - int protocalStatus = 0; - int retCode; - - KERB_RETRIEVE_TKT_REQUEST tQuery = new KERB_RETRIEVE_TKT_REQUEST(); - KERB_RETRIEVE_TKT_RESPONSE response = new KERB_RETRIEVE_TKT_RESPONSE(); - - // obtains the unique identifier for the kerberos authentication package. - retCode = LsaLookupAuthenticationPackage(hLsa, ref LSAString, out authPack); - - // input object for querying the TGT for a specific logon ID (https://docs.microsoft.com/en-us/windows/desktop/api/ntsecapi/ns-ntsecapi-_kerb_retrieve_tkt_request) - LUID userLogonID = new LUID(); - userLogonID.LowPart = data.LoginID.LowPart; - userLogonID.HighPart = 0; - tQuery.LogonId = userLogonID; - tQuery.MessageType = KERB_PROTOCOL_MESSAGE_TYPE.KerbRetrieveTicketMessage; - // indicate we want kerb creds yo' - tQuery.CacheOptions = KERB_CACHE_OPTIONS.KERB_RETRIEVE_TICKET_AS_KERB_CRED; - - // query LSA, specifying we want the the TGT data - retCode = LsaCallAuthenticationPackage_KERB_RETRIEVE_TKT(hLsa, authPack, ref tQuery, Marshal.SizeOf(tQuery), out responsePointer, out returnBufferLength, out protocalStatus); - - if ((retCode) == 0 && (responsePointer != IntPtr.Zero)) - { - /*Console.WriteLine("\r\n UserName : {0}", username); - Console.WriteLine(" Domain : {0}", domain); - Console.WriteLine(" LogonId : {0}", data.LoginID.LowPart); - Console.WriteLine(" UserSID : {0}", sid.AccountDomainSid); - Console.WriteLine(" AuthenticationPackage : {0}", authpackage); - Console.WriteLine(" LogonType : {0}", logonType); - Console.WriteLine(" LogonType : {0}", logonTime); - Console.WriteLine(" LogonServer : {0}", logonServer); - Console.WriteLine(" LogonServerDNSDomain : {0}", dnsDomainName); - Console.WriteLine(" UserPrincipalName : {0}", upn);*/ - - // parse the returned pointer into our initial KERB_RETRIEVE_TKT_RESPONSE structure - response = (KERB_RETRIEVE_TKT_RESPONSE)Marshal.PtrToStructure((System.IntPtr)responsePointer, typeof(KERB_RETRIEVE_TKT_RESPONSE)); - - KERB_EXTERNAL_NAME serviceNameStruct = (KERB_EXTERNAL_NAME)Marshal.PtrToStructure(response.Ticket.ServiceName, typeof(KERB_EXTERNAL_NAME)); - string serviceName = Marshal.PtrToStringUni(serviceNameStruct.Names.Buffer, serviceNameStruct.Names.Length / 2).Trim(); - - string targetName = ""; - if (response.Ticket.TargetName != IntPtr.Zero) - { - KERB_EXTERNAL_NAME targetNameStruct = (KERB_EXTERNAL_NAME)Marshal.PtrToStructure(response.Ticket.TargetName, typeof(KERB_EXTERNAL_NAME)); - targetName = Marshal.PtrToStringUni(targetNameStruct.Names.Buffer, targetNameStruct.Names.Length / 2).Trim(); - } - - KERB_EXTERNAL_NAME clientNameStruct = (KERB_EXTERNAL_NAME)Marshal.PtrToStructure(response.Ticket.ClientName, typeof(KERB_EXTERNAL_NAME)); - string clientName = Marshal.PtrToStringUni(clientNameStruct.Names.Buffer, clientNameStruct.Names.Length / 2).Trim(); - - string domainName = Marshal.PtrToStringUni(response.Ticket.DomainName.Buffer, response.Ticket.DomainName.Length / 2).Trim(); - string targetDomainName = Marshal.PtrToStringUni(response.Ticket.TargetDomainName.Buffer, response.Ticket.TargetDomainName.Length / 2).Trim(); - string altTargetDomainName = Marshal.PtrToStringUni(response.Ticket.AltTargetDomainName.Buffer, response.Ticket.AltTargetDomainName.Length / 2).Trim(); - - // extract the session key - KERB_ENCRYPTION_TYPE sessionKeyType = (KERB_ENCRYPTION_TYPE)response.Ticket.SessionKey.KeyType; - Int32 sessionKeyLength = response.Ticket.SessionKey.Length; - byte[] sessionKey = new byte[sessionKeyLength]; - Marshal.Copy(response.Ticket.SessionKey.Value, sessionKey, 0, sessionKeyLength); - string base64SessionKey = Convert.ToBase64String(sessionKey); - - DateTime keyExpirationTime = DateTime.FromFileTime(response.Ticket.KeyExpirationTime); - DateTime startTime = DateTime.FromFileTime(response.Ticket.StartTime); - DateTime endTime = DateTime.FromFileTime(response.Ticket.EndTime); - DateTime renewUntil = DateTime.FromFileTime(response.Ticket.RenewUntil); - Int64 timeSkew = response.Ticket.TimeSkew; - Int32 encodedTicketSize = response.Ticket.EncodedTicketSize; - - string ticketFlags = ((KERB_TICKET_FLAGS)response.Ticket.TicketFlags).ToString(); - - // extract the TGT and base64 encode it - byte[] encodedTicket = new byte[encodedTicketSize]; - Marshal.Copy(response.Ticket.EncodedTicket, encodedTicket, 0, encodedTicketSize); - string base64TGT = Convert.ToBase64String(encodedTicket); - - results.Add(new Dictionary() - { - { "UserPrincipalName", upn }, - { "ServiceName", serviceName }, - { "TargetName", targetName }, - { "ClientName", clientName }, - { "DomainName", domainName }, - { "TargetDomainName", targetDomainName }, - { "SessionKeyType", String.Format("{0}", sessionKeyType) }, - { "Base64SessionKey", base64SessionKey }, - { "KeyExpirationTime", String.Format("{0}", keyExpirationTime) }, - { "TicketFlags", ticketFlags }, - { "StartTime", String.Format("{0}", startTime) }, - { "EndTime", String.Format("{0}", endTime) }, - { "RenewUntil", String.Format("{0}", renewUntil) }, - { "TimeSkew", String.Format("{0}", timeSkew) }, - { "EncodedTicketSize", String.Format("{0}", encodedTicketSize) }, - { "Base64EncodedTicket", base64TGT }, - }); - totalTicketCount++; - } - } - luidPtr = (IntPtr)((long)luidPtr.ToInt64() + Marshal.SizeOf(typeof(LUID))); - //move the pointer forward - LsaFreeReturnBuffer(sessionData); - //free the SECURITY_LOGON_SESSION_DATA memory in the struct - } - LsaFreeReturnBuffer(luidPtr); //free the array of LUIDs - - // disconnect from LSA - LsaDeregisterLogonProcess(hLsa); - } - catch (Exception ex) - { - Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); - } - return results; - } - public static List> ListKerberosTGTDataCurrentUser() - { - List> results = new List>(); - // adapted partially from Vincent LE TOUX' work - // https://github.com/vletoux/MakeMeEnterpriseAdmin/blob/master/MakeMeEnterpriseAdmin.ps1#L2939-L2950 - // and https://www.dreamincode.net/forums/topic/135033-increment-memory-pointer-issue/ - // also Jared Atkinson's work at https://github.com/Invoke-IR/ACE/blob/master/ACE-Management/PS-ACE/Scripts/ACE_Get-KerberosTicketCache.ps1 - - try - { - string name = "kerberos"; - LSA_STRING_IN LSAString; - LSAString.Length = (ushort)name.Length; - LSAString.MaximumLength = (ushort)(name.Length + 1); - LSAString.Buffer = name; - - IntPtr responsePointer = IntPtr.Zero; - int authPack; - int returnBufferLength = 0; - int protocalStatus = 0; - IntPtr lsaHandle; - int retCode; - - // If we want to look at tickets from a session other than our own - // then we need to use LsaRegisterLogonProcess instead of LsaConnectUntrusted - retCode = LsaConnectUntrusted(out lsaHandle); - - KERB_RETRIEVE_TKT_REQUEST tQuery = new KERB_RETRIEVE_TKT_REQUEST(); - KERB_RETRIEVE_TKT_RESPONSE response = new KERB_RETRIEVE_TKT_RESPONSE(); - - // obtains the unique identifier for the kerberos authentication package. - retCode = LsaLookupAuthenticationPackage(lsaHandle, ref LSAString, out authPack); - - // input object for querying the TGT (https://docs.microsoft.com/en-us/windows/desktop/api/ntsecapi/ns-ntsecapi-_kerb_retrieve_tkt_request) - tQuery.LogonId = new LUID(); - tQuery.MessageType = KERB_PROTOCOL_MESSAGE_TYPE.KerbRetrieveTicketMessage; - // indicate we want kerb creds yo' - //tQuery.CacheOptions = KERB_CACHE_OPTIONS.KERB_RETRIEVE_TICKET_AS_KERB_CRED; - - // query LSA, specifying we want the the TGT data - retCode = LsaCallAuthenticationPackage_KERB_RETRIEVE_TKT(lsaHandle, authPack, ref tQuery, Marshal.SizeOf(tQuery), out responsePointer, out returnBufferLength, out protocalStatus); - - // parse the returned pointer into our initial KERB_RETRIEVE_TKT_RESPONSE structure - response = (KERB_RETRIEVE_TKT_RESPONSE)Marshal.PtrToStructure((System.IntPtr)responsePointer, typeof(KERB_RETRIEVE_TKT_RESPONSE)); - - KERB_EXTERNAL_NAME serviceNameStruct = (KERB_EXTERNAL_NAME)Marshal.PtrToStructure(response.Ticket.ServiceName, typeof(KERB_EXTERNAL_NAME)); - string serviceName = Marshal.PtrToStringUni(serviceNameStruct.Names.Buffer, serviceNameStruct.Names.Length / 2).Trim(); - - string targetName = ""; - if (response.Ticket.TargetName != IntPtr.Zero) - { - KERB_EXTERNAL_NAME targetNameStruct = (KERB_EXTERNAL_NAME)Marshal.PtrToStructure(response.Ticket.TargetName, typeof(KERB_EXTERNAL_NAME)); - targetName = Marshal.PtrToStringUni(targetNameStruct.Names.Buffer, targetNameStruct.Names.Length / 2).Trim(); - } - - KERB_EXTERNAL_NAME clientNameStruct = (KERB_EXTERNAL_NAME)Marshal.PtrToStructure(response.Ticket.ClientName, typeof(KERB_EXTERNAL_NAME)); - string clientName = Marshal.PtrToStringUni(clientNameStruct.Names.Buffer, clientNameStruct.Names.Length / 2).Trim(); - - string domainName = Marshal.PtrToStringUni(response.Ticket.DomainName.Buffer, response.Ticket.DomainName.Length / 2).Trim(); - string targetDomainName = Marshal.PtrToStringUni(response.Ticket.TargetDomainName.Buffer, response.Ticket.TargetDomainName.Length / 2).Trim(); - string altTargetDomainName = Marshal.PtrToStringUni(response.Ticket.AltTargetDomainName.Buffer, response.Ticket.AltTargetDomainName.Length / 2).Trim(); - - // extract the session key - KERB_ENCRYPTION_TYPE sessionKeyType = (KERB_ENCRYPTION_TYPE)response.Ticket.SessionKey.KeyType; - Int32 sessionKeyLength = response.Ticket.SessionKey.Length; - byte[] sessionKey = new byte[sessionKeyLength]; - Marshal.Copy(response.Ticket.SessionKey.Value, sessionKey, 0, sessionKeyLength); - string base64SessionKey = Convert.ToBase64String(sessionKey); - - DateTime keyExpirationTime = DateTime.FromFileTime(response.Ticket.KeyExpirationTime); - DateTime startTime = DateTime.FromFileTime(response.Ticket.StartTime); - DateTime endTime = DateTime.FromFileTime(response.Ticket.EndTime); - DateTime renewUntil = DateTime.FromFileTime(response.Ticket.RenewUntil); - Int64 timeSkew = response.Ticket.TimeSkew; - Int32 encodedTicketSize = response.Ticket.EncodedTicketSize; - - string ticketFlags = ((KERB_TICKET_FLAGS)response.Ticket.TicketFlags).ToString(); - - // extract the TGT and base64 encode it - byte[] encodedTicket = new byte[encodedTicketSize]; - Marshal.Copy(response.Ticket.EncodedTicket, encodedTicket, 0, encodedTicketSize); - string base64TGT = Convert.ToBase64String(encodedTicket); - - results.Add(new Dictionary() - { - { "ServiceName", serviceName }, - { "TargetName", targetName }, - { "ClientName", clientName }, - { "DomainName", domainName }, - { "TargetDomainName", targetDomainName }, - { "SessionKeyType", String.Format("{0}", sessionKeyType) }, - { "Base64SessionKey", base64SessionKey }, - { "KeyExpirationTime", String.Format("{0}", keyExpirationTime) }, - { "TicketFlags", ticketFlags }, - { "StartTime", String.Format("{0}", startTime) }, - { "EndTime", String.Format("{0}", endTime) }, - { "RenewUntil", String.Format("{0}", renewUntil) }, - { "TimeSkew", String.Format("{0}", timeSkew) }, - { "EncodedTicketSize", String.Format("{0}", encodedTicketSize) }, - { "Base64EncodedTicket", base64TGT }, - }); - - // disconnect from LSA - LsaDeregisterLogonProcess(lsaHandle); - } - catch (Exception ex) - { - Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); - } - return results; - } - } -} diff --git a/winPEAS/winPEASexe/winPEAS/MyUtils.cs b/winPEAS/winPEASexe/winPEAS/MyUtils.cs index 6a5983c..d3f9363 100755 --- a/winPEAS/winPEASexe/winPEAS/MyUtils.cs +++ b/winPEAS/winPEASexe/winPEAS/MyUtils.cs @@ -11,6 +11,7 @@ using System.Security.AccessControl; using System.Runtime.InteropServices; using System.Threading; using FastSearchLibrary; +using winPEAS.Utils; namespace winPEAS { @@ -95,159 +96,12 @@ namespace winPEAS //By default local return ""; } - - - /////////////////////////////////////////// - /// Interf. for Keys and Values in Reg. /// - /////////////////////////////////////////// - /// Functions related to obtain keys and values from the registry - /// Some parts adapted from Seatbelt - public static string GetRegValue(string hive, string path, string value) - { - // returns a single registry value under the specified path in the specified hive (HKLM/HKCU) - string regKeyValue = ""; - if (hive == "HKCU") - { - var regKey = Registry.CurrentUser.OpenSubKey(path); - if (regKey != null) - { - regKeyValue = String.Format("{0}", regKey.GetValue(value)); - } - return regKeyValue; - } - else if (hive == "HKU") - { - var regKey = Registry.Users.OpenSubKey(path); - if (regKey != null) - { - regKeyValue = String.Format("{0}", regKey.GetValue(value)); - } - return regKeyValue; - } - else - { - var regKey = Registry.LocalMachine.OpenSubKey(path); - if (regKey != null) - { - regKeyValue = String.Format("{0}", regKey.GetValue(value)); - } - return regKeyValue; - } - } - - public static Dictionary GetRegValues(string hive, string path) - { - // returns all registry values under the specified path in the specified hive (HKLM/HKCU) - Dictionary keyValuePairs = null; - try - { - if (hive == "HKCU") - { - using (var regKeyValues = Registry.CurrentUser.OpenSubKey(path)) - { - if (regKeyValues != null) - { - var valueNames = regKeyValues.GetValueNames(); - keyValuePairs = valueNames.ToDictionary(name => name, regKeyValues.GetValue); - } - } - } - else if (hive == "HKU") - { - using (var regKeyValues = Registry.Users.OpenSubKey(path)) - { - if (regKeyValues != null) - { - var valueNames = regKeyValues.GetValueNames(); - keyValuePairs = valueNames.ToDictionary(name => name, regKeyValues.GetValue); - } - } - } - else - { - using (var regKeyValues = Registry.LocalMachine.OpenSubKey(path)) - { - if (regKeyValues != null) - { - var valueNames = regKeyValues.GetValueNames(); - keyValuePairs = valueNames.ToDictionary(name => name, regKeyValues.GetValue); - } - } - } - return keyValuePairs; - } - catch - { - return null; - } - } - - public static byte[] GetRegValueBytes(string hive, string path, string value) - { - // returns a byte array of single registry value under the specified path in the specified hive (HKLM/HKCU) - byte[] regKeyValue = null; - if (hive == "HKCU") - { - var regKey = Registry.CurrentUser.OpenSubKey(path); - if (regKey != null) - { - regKeyValue = (byte[])regKey.GetValue(value); - } - return regKeyValue; - } - else if (hive == "HKU") - { - var regKey = Registry.Users.OpenSubKey(path); - if (regKey != null) - { - regKeyValue = (byte[])regKey.GetValue(value); - } - return regKeyValue; - } - else - { - var regKey = Registry.LocalMachine.OpenSubKey(path); - if (regKey != null) - { - regKeyValue = (byte[])regKey.GetValue(value); - } - return regKeyValue; - } - } - - public static string[] GetRegSubkeys(string hive, string path) - { - // returns an array of the subkeys names under the specified path in the specified hive (HKLM/HKCU/HKU) - try - { - Microsoft.Win32.RegistryKey myKey = null; - if (hive == "HKLM") - { - myKey = Registry.LocalMachine.OpenSubKey(path); - } - else if (hive == "HKU") - { - myKey = Registry.Users.OpenSubKey(path); - } - else - { - myKey = Registry.CurrentUser.OpenSubKey(path); - } - String[] subkeyNames = myKey.GetSubKeyNames(); - return myKey.GetSubKeyNames(); - } - catch - { - return new string[0]; - } - } - + public static string GetCLSIDBinPath(string CLSID) { - return GetRegValue("HKLM", @"SOFTWARE\Classes\CLSID\" + CLSID + @"\InprocServer32", ""); //To get the default object you need to use an empty string + return RegistryHelper.GetRegValue("HKLM", @"SOFTWARE\Classes\CLSID\" + CLSID + @"\InprocServer32", ""); //To get the default object you need to use an empty string } - /////////////////////////////////// //////// Check Permissions //////// /////////////////////////////////// diff --git a/winPEAS/winPEASexe/winPEAS/NativeWifiApi/Interop.cs b/winPEAS/winPEASexe/winPEAS/NativeWifiApi/Interop.cs new file mode 100644 index 0000000..e827a88 --- /dev/null +++ b/winPEAS/winPEASexe/winPEAS/NativeWifiApi/Interop.cs @@ -0,0 +1,1333 @@ +using System; +using System.ComponentModel; +using System.Diagnostics; +using System.Net.NetworkInformation; +using System.Runtime.InteropServices; +using System.Text; + +namespace winPEAS.NativeWifiApi +{ + public static class Wlan + { + #region P/Invoke API + /// + /// Defines various opcodes used to set and query parameters for an interface. + /// + /// + /// Corresponds to the native WLAN_INTF_OPCODE type. + /// + public enum WlanIntfOpcode + { + /// + /// Opcode used to set or query whether auto config is enabled. + /// + AutoconfEnabled = 1, + /// + /// Opcode used to set or query whether background scan is enabled. + /// + BackgroundScanEnabled, + /// + /// Opcode used to set or query the media streaming mode of the driver. + /// + MediaStreamingMode, + /// + /// Opcode used to set or query the radio state. + /// + RadioState, + /// + /// Opcode used to set or query the BSS type of the interface. + /// + BssType, + /// + /// Opcode used to query the state of the interface. + /// + InterfaceState, + /// + /// Opcode used to query information about the current connection of the interface. + /// + CurrentConnection, + /// + /// Opcose used to query the current channel on which the wireless interface is operating. + /// + ChannelNumber, + /// + /// Opcode used to query the supported auth/cipher pairs for infrastructure mode. + /// + SupportedInfrastructureAuthCipherPairs, + /// + /// Opcode used to query the supported auth/cipher pairs for ad hoc mode. + /// + SupportedAdhocAuthCipherPairs, + /// + /// Opcode used to query the list of supported country or region strings. + /// + SupportedCountryOrRegionStringList, + /// + /// Opcode used to set or query the current operation mode of the wireless interface. + /// + CurrentOperationMode, + /// + /// Opcode used to query driver statistics. + /// + Statistics = 0x10000101, + /// + /// Opcode used to query the received signal strength. + /// + RSSI, + SecurityStart = 0x20010000, + SecurityEnd = 0x2fffffff, + IhvStart = 0x30000000, + IhvEnd = 0x3fffffff + } + + /// + /// Specifies the origin of automatic configuration (auto config) settings. + /// + /// + /// Corresponds to the native WLAN_OPCODE_VALUE_TYPE type. + /// + public enum WlanOpcodeValueType + { + /// + /// The auto config settings were queried, but the origin of the settings was not determined. + /// + QueryOnly = 0, + /// + /// The auto config settings were set by group policy. + /// + SetByGroupPolicy = 1, + /// + /// The auto config settings were set by the user. + /// + SetByUser = 2, + /// + /// The auto config settings are invalid. + /// + Invalid = 3 + } + + public const uint WLAN_CLIENT_VERSION_XP_SP2 = 1; + public const uint WLAN_CLIENT_VERSION_LONGHORN = 2; + + public const uint WLAN_MAX_NAME_LENGTH = 256; + + [DllImport("wlanapi.dll")] + public static extern int WlanOpenHandle( + [In] UInt32 clientVersion, + [In, Out] IntPtr pReserved, + [Out] out UInt32 negotiatedVersion, + [Out] out IntPtr clientHandle); + + [DllImport("wlanapi.dll")] + public static extern int WlanCloseHandle( + [In] IntPtr clientHandle, + [In, Out] IntPtr pReserved); + + [DllImport("wlanapi.dll")] + public static extern int WlanEnumInterfaces( + [In] IntPtr clientHandle, + [In, Out] IntPtr pReserved, + [Out] out IntPtr ppInterfaceList); + + /// + /// Defines flags passed to . + /// + [Flags] + public enum WlanGetAvailableNetworkFlags + { + /// + /// No additional flags + /// + None = 0, + /// + /// Include all ad-hoc network profiles in the available network list, including profiles that are not visible. + /// + IncludeAllAdhocProfiles = 0x00000001, + /// + /// Include all hidden network profiles in the available network list, including profiles that are not visible. + /// + IncludeAllManualHiddenProfiles = 0x00000002 + } + + /// + /// Contains various flags for the network. + /// + [Flags] + public enum WlanAvailableNetworkFlags + { + /// + /// This network is currently connected. + /// + Connected = 0x00000001, + /// + /// There is a profile for this network. + /// + HasProfile = 0x00000002 + } + + [DllImport("wlanapi.dll")] + public static extern int WlanGetAvailableNetworkList( + [In] IntPtr clientHandle, + [In, MarshalAs(UnmanagedType.LPStruct)] Guid interfaceGuid, + [In] WlanGetAvailableNetworkFlags flags, + [In, Out] IntPtr reservedPtr, + [Out] out IntPtr availableNetworkListPtr); + + [Flags] + public enum WlanProfileFlags + { + // When getting profiles, the absence of the "User" or "GroupPolicy" flags implies that the profile + // is an "AllUser" profile. This can also be viewed as having no flag -- hence "None" and "AllUser" + // are equivalent + None = 0, + AllUser = 0, + GroupPolicy = 1, + User = 2, + GetPlaintextKey = 4 + } + + /// + /// Defines the access mask of an all-user profile. + /// + [Flags] + public enum WlanAccess + { + /// + /// The user can view profile permissions. + /// + ReadAccess = 0x00020000 | 0x0001, + /// + /// The user has read access, and the user can also connect to and disconnect from a network using the profile. + /// + ExecuteAccess = ReadAccess | 0x0020, + /// + /// The user has execute access and the user can also modify and delete permissions associated with a profile. + /// + WriteAccess = ReadAccess | ExecuteAccess | 0x0002 | 0x00010000 | 0x00040000 + } + + /// Not supported on Windows XP SP2: must be a null reference. + [DllImport("wlanapi.dll")] + public static extern int WlanGetProfile( + [In] IntPtr clientHandle, + [In, MarshalAs(UnmanagedType.LPStruct)] Guid interfaceGuid, + [In, MarshalAs(UnmanagedType.LPWStr)] string profileName, + [In] IntPtr pReserved, + [Out] out IntPtr profileXml, + [Out, Optional] out WlanProfileFlags flags, + [Out, Optional] out WlanAccess grantedAccess); + + [DllImport("wlanapi.dll")] + public static extern int WlanGetProfileList( + [In] IntPtr clientHandle, + [In, MarshalAs(UnmanagedType.LPStruct)] Guid interfaceGuid, + [In] IntPtr pReserved, + [Out] out IntPtr profileList + ); + + [DllImport("wlanapi.dll")] + public static extern void WlanFreeMemory(IntPtr pMemory); + + [DllImport("wlanapi.dll")] + public static extern int WlanReasonCodeToString( + [In] WlanReasonCode reasonCode, + [In] int bufferSize, + [In, Out] StringBuilder stringBuffer, + IntPtr pReserved + ); + + /// + /// Specifies where the notification comes from. + /// + [Flags] + public enum WlanNotificationSource + { + None = 0, + /// + /// All notifications, including those generated by the 802.1X module. + /// + All = 0X0000FFFF, + /// + /// Notifications generated by the auto configuration module. + /// + ACM = 0X00000008, + /// + /// Notifications generated by MSM. + /// + MSM = 0X00000010, + /// + /// Notifications generated by the security module. + /// + Security = 0X00000020, + /// + /// Notifications generated by independent hardware vendors (IHV). + /// + IHV = 0X00000040 + } + + /// + /// Indicates the type of an ACM () notification. + /// + /// + /// The enumeration identifiers correspond to the native wlan_notification_acm_ identifiers. + /// On Windows XP SP2, only the ConnectionComplete and Disconnected notifications are available. + /// + public enum WlanNotificationCodeAcm + { + AutoconfEnabled = 1, + AutoconfDisabled, + BackgroundScanEnabled, + BackgroundScanDisabled, + BssTypeChange, + PowerSettingChange, + ScanComplete, + ScanFail, + ConnectionStart, + ConnectionComplete, + ConnectionAttemptFail, + FilterListChange, + InterfaceArrival, + InterfaceRemoval, + ProfileChange, + ProfileNameChange, + ProfilesExhausted, + NetworkNotAvailable, + NetworkAvailable, + Disconnecting, + Disconnected, + AdhocNetworkStateChange + } + + /// + /// Indicates the type of an MSM () notification. + /// + /// + /// The enumeration identifiers correspond to the native wlan_notification_msm_ identifiers. + /// + public enum WlanNotificationCodeMsm + { + Associating = 1, + Associated, + Authenticating, + Connected, + RoamingStart, + RoamingEnd, + RadioStateChange, + SignalQualityChange, + Disassociating, + Disconnected, + PeerJoin, + PeerLeave, + AdapterRemoval, + AdapterOperationModeChange + } + + /// + /// Contains information provided when registering for notifications. + /// + /// + /// Corresponds to the native WLAN_NOTIFICATION_DATA type. + /// + [StructLayout(LayoutKind.Sequential)] + public struct WlanNotificationData + { + /// + /// Specifies where the notification comes from. + /// + /// + /// On Windows XP SP2, this field must be set to , or . + /// + public WlanNotificationSource notificationSource; + /// + /// Indicates the type of notification. The value of this field indicates what type of associated data will be present in . + /// + public int notificationCode; + /// + /// Indicates which interface the notification is for. + /// + public Guid interfaceGuid; + /// + /// Specifies the size of , in bytes. + /// + public int dataSize; + /// + /// Pointer to additional data needed for the notification, as indicated by . + /// + public IntPtr dataPtr; + } + + /// + /// Defines the callback function which accepts WLAN notifications. + /// + public delegate void WlanNotificationCallbackDelegate(ref WlanNotificationData notificationData, IntPtr context); + + /// + /// Defines connection parameter flags. + /// + [Flags] + public enum WlanConnectionFlags + { + /// + /// Connect to the destination network even if the destination is a hidden network. A hidden network does not broadcast its SSID. Do not use this flag if the destination network is an ad-hoc network. + /// If the profile specified by is not null, then this flag is ignored and the nonBroadcast profile element determines whether to connect to a hidden network. + /// + HiddenNetwork = 0x00000001, + /// + /// Do not form an ad-hoc network. Only join an ad-hoc network if the network already exists. Do not use this flag if the destination network is an infrastructure network. + /// + AdhocJoinOnly = 0x00000002, + /// + /// Ignore the privacy bit when connecting to the network. Ignoring the privacy bit has the effect of ignoring whether packets are encryption and ignoring the method of encryption used. Only use this flag when connecting to an infrastructure network using a temporary profile. + /// + IgnorePrivacyBit = 0x00000004, + /// + /// Exempt EAPOL traffic from encryption and decryption. This flag is used when an application must send EAPOL traffic over an infrastructure network that uses Open authentication and WEP encryption. This flag must not be used to connect to networks that require 802.1X authentication. This flag is only valid when is set to . Avoid using this flag whenever possible. + /// + EapolPassthrough = 0x00000008 + } + + /// + /// Defines flags returned in + /// + [Flags] + public enum WlanConnectionNotificationFlags + { + /// + /// Indicates that an adhoc network is formed. + /// + AdhocNetworkFormed = 0x00000001, + /// + /// Indicates that the connection uses a per-user profile owned by the console user. Non-console users will not be able to see the profile in their profile list. + /// + ConsoleUserProfile = 0x00000004 + } + + /// + /// Specifies the parameters used when using the function. + /// + /// + /// Corresponds to the native WLAN_CONNECTION_PARAMETERS type. + /// + [StructLayout(LayoutKind.Sequential)] + public struct WlanConnectionParameters + { + /// + /// Specifies the mode of connection. + /// + public WlanConnectionMode wlanConnectionMode; + /// + /// Specifies the profile being used for the connection. + /// The contents of the field depend on the : + /// + /// + /// Value of + /// Contents of the profile string + /// + /// + /// + /// The name of the profile used for the connection. + /// + /// + /// + /// The XML representation of the profile used for the connection. + /// + /// + /// , or + /// null + /// + /// + /// + [MarshalAs(UnmanagedType.LPWStr)] + public string profile; + /// + /// Pointer to a structure that specifies the SSID of the network to connect to. + /// This field is optional. When set to null, all SSIDs in the profile will be tried. + /// This field must not be null if is set to or . + /// + public IntPtr dot11SsidPtr; + /// + /// Pointer to a structure that contains the list of basic service set (BSS) identifiers desired for the connection. + /// + /// + /// On Windows XP SP2, must be set to null. + /// + public IntPtr desiredBssidListPtr; + /// + /// A value that indicates the BSS type of the network. If a profile is provided, this BSS type must be the same as the one in the profile. + /// + public Dot11BssType dot11BssType; + /// + /// Specifies ocnnection parameters. + /// + /// + /// On Windows XP SP2, must be set to 0. + /// + public WlanConnectionFlags flags; + } + + [DllImport("wlanapi.dll")] + public static extern int WlanConnect( + [In] IntPtr clientHandle, + [In, MarshalAs(UnmanagedType.LPStruct)] Guid interfaceGuid, + [In] ref WlanConnectionParameters connectionParameters, + IntPtr pReserved); + + [DllImport("wlanapi.dll")] + public static extern int WlanGetNetworkBssList( + [In] IntPtr clientHandle, + [In, MarshalAs(UnmanagedType.LPStruct)] Guid interfaceGuid, + [In] IntPtr dot11SsidInt, + [In] Dot11BssType dot11BssType, + [In] bool securityEnabled, + IntPtr reservedPtr, + [Out] out IntPtr wlanBssList + ); + + [StructLayout(LayoutKind.Sequential)] + internal struct WlanBssListHeader + { + internal uint totalSize; + internal uint numberOfItems; + } + + /// + /// Contains information about a basic service set (BSS). + /// + [StructLayout(LayoutKind.Sequential)] + public struct WlanBssEntry + { + /// + /// Contains the SSID of the access point (AP) associated with the BSS. + /// + public Dot11Ssid dot11Ssid; + /// + /// The identifier of the PHY on which the AP is operating. + /// + public uint phyId; + /// + /// Contains the BSS identifier. + /// + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)] + public byte[] dot11Bssid; + /// + /// Specifies whether the network is infrastructure or ad hoc. + /// + public Dot11BssType dot11BssType; + public Dot11PhyType dot11BssPhyType; + /// + /// The received signal strength in dBm. + /// + public int rssi; + /// + /// The link quality reported by the driver. Ranges from 0-100. + /// + public uint linkQuality; + /// + /// If 802.11d is not implemented, the network interface card (NIC) must set this field to TRUE. If 802.11d is implemented (but not necessarily enabled), the NIC must set this field to TRUE if the BSS operation complies with the configured regulatory domain. + /// + public bool inRegDomain; + /// + /// Contains the beacon interval value from the beacon packet or probe response. + /// + public ushort beaconPeriod; + /// + /// The timestamp from the beacon packet or probe response. + /// + public ulong timestamp; + /// + /// The host timestamp value when the beacon or probe response is received. + /// + public ulong hostTimestamp; + /// + /// The capability value from the beacon packet or probe response. + /// + public ushort capabilityInformation; + /// + /// The frequency of the center channel, in kHz. + /// + public uint chCenterFrequency; + /// + /// Contains the set of data transfer rates supported by the BSS. + /// + public WlanRateSet wlanRateSet; + /// + /// Offset of the information element (IE) data blob. + /// + public uint ieOffset; + /// + /// Size of the IE data blob, in bytes. + /// + public uint ieSize; + } + + /// + /// Contains the set of supported data rates. + /// + [StructLayout(LayoutKind.Sequential)] + public struct WlanRateSet + { + /// + /// The length, in bytes, of . + /// + private uint rateSetLength; + /// + /// An array of supported data transfer rates. + /// If the rate is a basic rate, the first bit of the rate value is set to 1. + /// A basic rate is the data transfer rate that all stations in a basic service set (BSS) can use to receive frames from the wireless medium. + /// + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 126)] + private ushort[] rateSet; + } + + /// + /// Represents an error occuring during WLAN operations which indicate their failure via a . + /// + public class WlanException : Exception + { + private WlanReasonCode reasonCode; + + WlanException(WlanReasonCode reasonCode) + { + this.reasonCode = reasonCode; + } + + /// + /// Gets the WLAN reason code. + /// + /// The WLAN reason code. + public WlanReasonCode ReasonCode + { + get { return reasonCode; } + } + + /// + /// Gets a message that describes the reason code. + /// + /// + /// The error message that explains the reason for the exception, or an empty string(""). + public override string Message + { + get + { + StringBuilder sb = new StringBuilder(1024); + if (WlanReasonCodeToString(reasonCode, sb.Capacity, sb, IntPtr.Zero) == 0) + return sb.ToString(); + else + return string.Empty; + } + } + } + + // TODO: .NET-ify the WlanReasonCode enum (naming convention + docs). + + /// + /// Specifies reasons for a failure of a WLAN operation. + /// + /// + /// To get the WLAN API native reason code identifiers, prefix the identifiers with WLAN_REASON_CODE_. + /// + public enum WlanReasonCode + { + Success = 0, + // general codes + UNKNOWN = 0x10000 + 1, + + RANGE_SIZE = 0x10000, + BASE = 0x10000 + RANGE_SIZE, + + // range for Auto Config + // + AC_BASE = 0x10000 + RANGE_SIZE, + AC_CONNECT_BASE = (AC_BASE + RANGE_SIZE / 2), + AC_END = (AC_BASE + RANGE_SIZE - 1), + + // range for profile manager + // it has profile adding failure reason codes, but may not have + // connection reason codes + // + PROFILE_BASE = 0x10000 + (7 * RANGE_SIZE), + PROFILE_CONNECT_BASE = (PROFILE_BASE + RANGE_SIZE / 2), + PROFILE_END = (PROFILE_BASE + RANGE_SIZE - 1), + + // range for MSM + // + MSM_BASE = 0x10000 + (2 * RANGE_SIZE), + MSM_CONNECT_BASE = (MSM_BASE + RANGE_SIZE / 2), + MSM_END = (MSM_BASE + RANGE_SIZE - 1), + + // range for MSMSEC + // + MSMSEC_BASE = 0x10000 + (3 * RANGE_SIZE), + MSMSEC_CONNECT_BASE = (MSMSEC_BASE + RANGE_SIZE / 2), + MSMSEC_END = (MSMSEC_BASE + RANGE_SIZE - 1), + + // AC network incompatible reason codes + // + NETWORK_NOT_COMPATIBLE = (AC_BASE + 1), + PROFILE_NOT_COMPATIBLE = (AC_BASE + 2), + + // AC connect reason code + // + NO_AUTO_CONNECTION = (AC_CONNECT_BASE + 1), + NOT_VISIBLE = (AC_CONNECT_BASE + 2), + GP_DENIED = (AC_CONNECT_BASE + 3), + USER_DENIED = (AC_CONNECT_BASE + 4), + BSS_TYPE_NOT_ALLOWED = (AC_CONNECT_BASE + 5), + IN_FAILED_LIST = (AC_CONNECT_BASE + 6), + IN_BLOCKED_LIST = (AC_CONNECT_BASE + 7), + SSID_LIST_TOO_LONG = (AC_CONNECT_BASE + 8), + CONNECT_CALL_FAIL = (AC_CONNECT_BASE + 9), + SCAN_CALL_FAIL = (AC_CONNECT_BASE + 10), + NETWORK_NOT_AVAILABLE = (AC_CONNECT_BASE + 11), + PROFILE_CHANGED_OR_DELETED = (AC_CONNECT_BASE + 12), + KEY_MISMATCH = (AC_CONNECT_BASE + 13), + USER_NOT_RESPOND = (AC_CONNECT_BASE + 14), + + // Profile validation errors + // + INVALID_PROFILE_SCHEMA = (PROFILE_BASE + 1), + PROFILE_MISSING = (PROFILE_BASE + 2), + INVALID_PROFILE_NAME = (PROFILE_BASE + 3), + INVALID_PROFILE_TYPE = (PROFILE_BASE + 4), + INVALID_PHY_TYPE = (PROFILE_BASE + 5), + MSM_SECURITY_MISSING = (PROFILE_BASE + 6), + IHV_SECURITY_NOT_SUPPORTED = (PROFILE_BASE + 7), + IHV_OUI_MISMATCH = (PROFILE_BASE + 8), + // IHV OUI not present but there is IHV settings in profile + IHV_OUI_MISSING = (PROFILE_BASE + 9), + // IHV OUI is present but there is no IHV settings in profile + IHV_SETTINGS_MISSING = (PROFILE_BASE + 10), + // both/conflict MSMSec and IHV security settings exist in profile + CONFLICT_SECURITY = (PROFILE_BASE + 11), + // no IHV or MSMSec security settings in profile + SECURITY_MISSING = (PROFILE_BASE + 12), + INVALID_BSS_TYPE = (PROFILE_BASE + 13), + INVALID_ADHOC_CONNECTION_MODE = (PROFILE_BASE + 14), + NON_BROADCAST_SET_FOR_ADHOC = (PROFILE_BASE + 15), + AUTO_SWITCH_SET_FOR_ADHOC = (PROFILE_BASE + 16), + AUTO_SWITCH_SET_FOR_MANUAL_CONNECTION = (PROFILE_BASE + 17), + IHV_SECURITY_ONEX_MISSING = (PROFILE_BASE + 18), + PROFILE_SSID_INVALID = (PROFILE_BASE + 19), + TOO_MANY_SSID = (PROFILE_BASE + 20), + + // MSM network incompatible reasons + // + UNSUPPORTED_SECURITY_SET_BY_OS = (MSM_BASE + 1), + UNSUPPORTED_SECURITY_SET = (MSM_BASE + 2), + BSS_TYPE_UNMATCH = (MSM_BASE + 3), + PHY_TYPE_UNMATCH = (MSM_BASE + 4), + DATARATE_UNMATCH = (MSM_BASE + 5), + + // MSM connection failure reasons, to be defined + // failure reason codes + // + // user called to disconnect + USER_CANCELLED = (MSM_CONNECT_BASE + 1), + // got disconnect while associating + ASSOCIATION_FAILURE = (MSM_CONNECT_BASE + 2), + // timeout for association + ASSOCIATION_TIMEOUT = (MSM_CONNECT_BASE + 3), + // pre-association security completed with failure + PRE_SECURITY_FAILURE = (MSM_CONNECT_BASE + 4), + // fail to start post-association security + START_SECURITY_FAILURE = (MSM_CONNECT_BASE + 5), + // post-association security completed with failure + SECURITY_FAILURE = (MSM_CONNECT_BASE + 6), + // security watchdog timeout + SECURITY_TIMEOUT = (MSM_CONNECT_BASE + 7), + // got disconnect from driver when roaming + ROAMING_FAILURE = (MSM_CONNECT_BASE + 8), + // failed to start security for roaming + ROAMING_SECURITY_FAILURE = (MSM_CONNECT_BASE + 9), + // failed to start security for adhoc-join + ADHOC_SECURITY_FAILURE = (MSM_CONNECT_BASE + 10), + // got disconnection from driver + DRIVER_DISCONNECTED = (MSM_CONNECT_BASE + 11), + // driver operation failed + DRIVER_OPERATION_FAILURE = (MSM_CONNECT_BASE + 12), + // Ihv service is not available + IHV_NOT_AVAILABLE = (MSM_CONNECT_BASE + 13), + // Response from ihv timed out + IHV_NOT_RESPONDING = (MSM_CONNECT_BASE + 14), + // Timed out waiting for driver to disconnect + DISCONNECT_TIMEOUT = (MSM_CONNECT_BASE + 15), + // An internal error prevented the operation from being completed. + INTERNAL_FAILURE = (MSM_CONNECT_BASE + 16), + // UI Request timed out. + UI_REQUEST_TIMEOUT = (MSM_CONNECT_BASE + 17), + // Roaming too often, post security is not completed after 5 times. + TOO_MANY_SECURITY_ATTEMPTS = (MSM_CONNECT_BASE + 18), + + // MSMSEC reason codes + // + + MSMSEC_MIN = MSMSEC_BASE, + + // Key index specified is not valid + MSMSEC_PROFILE_INVALID_KEY_INDEX = (MSMSEC_BASE + 1), + // Key required, PSK present + MSMSEC_PROFILE_PSK_PRESENT = (MSMSEC_BASE + 2), + // Invalid key length + MSMSEC_PROFILE_KEY_LENGTH = (MSMSEC_BASE + 3), + // Invalid PSK length + MSMSEC_PROFILE_PSK_LENGTH = (MSMSEC_BASE + 4), + // No auth/cipher specified + MSMSEC_PROFILE_NO_AUTH_CIPHER_SPECIFIED = (MSMSEC_BASE + 5), + // Too many auth/cipher specified + MSMSEC_PROFILE_TOO_MANY_AUTH_CIPHER_SPECIFIED = (MSMSEC_BASE + 6), + // Profile contains duplicate auth/cipher + MSMSEC_PROFILE_DUPLICATE_AUTH_CIPHER = (MSMSEC_BASE + 7), + // Profile raw data is invalid (1x or key data) + MSMSEC_PROFILE_RAWDATA_INVALID = (MSMSEC_BASE + 8), + // Invalid auth/cipher combination + MSMSEC_PROFILE_INVALID_AUTH_CIPHER = (MSMSEC_BASE + 9), + // 802.1x disabled when it's required to be enabled + MSMSEC_PROFILE_ONEX_DISABLED = (MSMSEC_BASE + 10), + // 802.1x enabled when it's required to be disabled + MSMSEC_PROFILE_ONEX_ENABLED = (MSMSEC_BASE + 11), + MSMSEC_PROFILE_INVALID_PMKCACHE_MODE = (MSMSEC_BASE + 12), + MSMSEC_PROFILE_INVALID_PMKCACHE_SIZE = (MSMSEC_BASE + 13), + MSMSEC_PROFILE_INVALID_PMKCACHE_TTL = (MSMSEC_BASE + 14), + MSMSEC_PROFILE_INVALID_PREAUTH_MODE = (MSMSEC_BASE + 15), + MSMSEC_PROFILE_INVALID_PREAUTH_THROTTLE = (MSMSEC_BASE + 16), + // PreAuth enabled when PMK cache is disabled + MSMSEC_PROFILE_PREAUTH_ONLY_ENABLED = (MSMSEC_BASE + 17), + // Capability matching failed at network + MSMSEC_CAPABILITY_NETWORK = (MSMSEC_BASE + 18), + // Capability matching failed at NIC + MSMSEC_CAPABILITY_NIC = (MSMSEC_BASE + 19), + // Capability matching failed at profile + MSMSEC_CAPABILITY_PROFILE = (MSMSEC_BASE + 20), + // Network does not support specified discovery type + MSMSEC_CAPABILITY_DISCOVERY = (MSMSEC_BASE + 21), + // Passphrase contains invalid character + MSMSEC_PROFILE_PASSPHRASE_CHAR = (MSMSEC_BASE + 22), + // Key material contains invalid character + MSMSEC_PROFILE_KEYMATERIAL_CHAR = (MSMSEC_BASE + 23), + // Wrong key type specified for the auth/cipher pair + MSMSEC_PROFILE_WRONG_KEYTYPE = (MSMSEC_BASE + 24), + // "Mixed cell" suspected (AP not beaconing privacy, we have privacy enabled profile) + MSMSEC_MIXED_CELL = (MSMSEC_BASE + 25), + // Auth timers or number of timeouts in profile is incorrect + MSMSEC_PROFILE_AUTH_TIMERS_INVALID = (MSMSEC_BASE + 26), + // Group key update interval in profile is incorrect + MSMSEC_PROFILE_INVALID_GKEY_INTV = (MSMSEC_BASE + 27), + // "Transition network" suspected, trying legacy 802.11 security + MSMSEC_TRANSITION_NETWORK = (MSMSEC_BASE + 28), + // Key contains characters which do not map to ASCII + MSMSEC_PROFILE_KEY_UNMAPPED_CHAR = (MSMSEC_BASE + 29), + // Capability matching failed at profile (auth not found) + MSMSEC_CAPABILITY_PROFILE_AUTH = (MSMSEC_BASE + 30), + // Capability matching failed at profile (cipher not found) + MSMSEC_CAPABILITY_PROFILE_CIPHER = (MSMSEC_BASE + 31), + + // Failed to queue UI request + MSMSEC_UI_REQUEST_FAILURE = (MSMSEC_CONNECT_BASE + 1), + // 802.1x authentication did not start within configured time + MSMSEC_AUTH_START_TIMEOUT = (MSMSEC_CONNECT_BASE + 2), + // 802.1x authentication did not complete within configured time + MSMSEC_AUTH_SUCCESS_TIMEOUT = (MSMSEC_CONNECT_BASE + 3), + // Dynamic key exchange did not start within configured time + MSMSEC_KEY_START_TIMEOUT = (MSMSEC_CONNECT_BASE + 4), + // Dynamic key exchange did not succeed within configured time + MSMSEC_KEY_SUCCESS_TIMEOUT = (MSMSEC_CONNECT_BASE + 5), + // Message 3 of 4 way handshake has no key data (RSN/WPA) + MSMSEC_M3_MISSING_KEY_DATA = (MSMSEC_CONNECT_BASE + 6), + // Message 3 of 4 way handshake has no IE (RSN/WPA) + MSMSEC_M3_MISSING_IE = (MSMSEC_CONNECT_BASE + 7), + // Message 3 of 4 way handshake has no Group Key (RSN) + MSMSEC_M3_MISSING_GRP_KEY = (MSMSEC_CONNECT_BASE + 8), + // Matching security capabilities of IE in M3 failed (RSN/WPA) + MSMSEC_PR_IE_MATCHING = (MSMSEC_CONNECT_BASE + 9), + // Matching security capabilities of Secondary IE in M3 failed (RSN) + MSMSEC_SEC_IE_MATCHING = (MSMSEC_CONNECT_BASE + 10), + // Required a pairwise key but AP configured only group keys + MSMSEC_NO_PAIRWISE_KEY = (MSMSEC_CONNECT_BASE + 11), + // Message 1 of group key handshake has no key data (RSN/WPA) + MSMSEC_G1_MISSING_KEY_DATA = (MSMSEC_CONNECT_BASE + 12), + // Message 1 of group key handshake has no group key + MSMSEC_G1_MISSING_GRP_KEY = (MSMSEC_CONNECT_BASE + 13), + // AP reset secure bit after connection was secured + MSMSEC_PEER_INDICATED_INSECURE = (MSMSEC_CONNECT_BASE + 14), + // 802.1x indicated there is no authenticator but profile requires 802.1x + MSMSEC_NO_AUTHENTICATOR = (MSMSEC_CONNECT_BASE + 15), + // Plumbing settings to NIC failed + MSMSEC_NIC_FAILURE = (MSMSEC_CONNECT_BASE + 16), + // Operation was cancelled by caller + MSMSEC_CANCELLED = (MSMSEC_CONNECT_BASE + 17), + // Key was in incorrect format + MSMSEC_KEY_FORMAT = (MSMSEC_CONNECT_BASE + 18), + // Security downgrade detected + MSMSEC_DOWNGRADE_DETECTED = (MSMSEC_CONNECT_BASE + 19), + // PSK mismatch suspected + MSMSEC_PSK_MISMATCH_SUSPECTED = (MSMSEC_CONNECT_BASE + 20), + // Forced failure because connection method was not secure + MSMSEC_FORCED_FAILURE = (MSMSEC_CONNECT_BASE + 21), + // ui request couldn't be queued or user pressed cancel + MSMSEC_SECURITY_UI_FAILURE = (MSMSEC_CONNECT_BASE + 22), + + MSMSEC_MAX = MSMSEC_END + } + + /// + /// Indicates the state of an interface. + /// + /// + /// Corresponds to the native WLAN_INTERFACE_STATE type. + /// + public enum WlanInterfaceState + { + /// + /// The interface is not ready to operate. + /// + NotReady = 0, + /// + /// The interface is connected to a network. + /// + Connected = 1, + /// + /// The interface is the first node in an ad hoc network. No peer has connected. + /// + AdHocNetworkFormed = 2, + /// + /// The interface is disconnecting from the current network. + /// + Disconnecting = 3, + /// + /// The interface is not connected to any network. + /// + Disconnected = 4, + /// + /// The interface is attempting to associate with a network. + /// + Associating = 5, + /// + /// Auto configuration is discovering the settings for the network. + /// + Discovering = 6, + /// + /// The interface is in the process of authenticating. + /// + Authenticating = 7 + } + + /// + /// Contains the SSID of an interface. + /// + public struct Dot11Ssid + { + /// + /// The length, in bytes, of the array. + /// + public uint SSIDLength; + /// + /// The SSID. + /// + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] + public byte[] SSID; + } + + /// + /// Defines an 802.11 PHY and media type. + /// + /// + /// Corresponds to the native DOT11_PHY_TYPE type. + /// + public enum Dot11PhyType : uint + { + /// + /// Specifies an unknown or uninitialized PHY type. + /// + Unknown = 0, + /// + /// Specifies any PHY type. + /// + Any = Unknown, + /// + /// Specifies a frequency-hopping spread-spectrum (FHSS) PHY. Bluetooth devices can use FHSS or an adaptation of FHSS. + /// + FHSS = 1, + /// + /// Specifies a direct sequence spread spectrum (DSSS) PHY. + /// + DSSS = 2, + /// + /// Specifies an infrared (IR) baseband PHY. + /// + IrBaseband = 3, + /// + /// Specifies an orthogonal frequency division multiplexing (OFDM) PHY. 802.11a devices can use OFDM. + /// + OFDM = 4, + /// + /// Specifies a high-rate DSSS (HRDSSS) PHY. + /// + HRDSSS = 5, + /// + /// Specifies an extended rate PHY (ERP). 802.11g devices can use ERP. + /// + ERP = 6, + /// + /// Specifies the start of the range that is used to define PHY types that are developed by an independent hardware vendor (IHV). + /// + IHV_Start = 0x80000000, + /// + /// Specifies the end of the range that is used to define PHY types that are developed by an independent hardware vendor (IHV). + /// + IHV_End = 0xffffffff + } + + /// + /// Defines a basic service set (BSS) network type. + /// + /// + /// Corresponds to the native DOT11_BSS_TYPE type. + /// + public enum Dot11BssType + { + /// + /// Specifies an infrastructure BSS network. + /// + Infrastructure = 1, + /// + /// Specifies an independent BSS (IBSS) network. + /// + Independent = 2, + /// + /// Specifies either infrastructure or IBSS network. + /// + Any = 3 + } + + /// + /// Contains association attributes for a connection + /// + /// + /// Corresponds to the native WLAN_ASSOCIATION_ATTRIBUTES type. + /// + [StructLayout(LayoutKind.Sequential)] + public struct WlanAssociationAttributes + { + /// + /// The SSID of the association. + /// + public Dot11Ssid dot11Ssid; + /// + /// Specifies whether the network is infrastructure or ad hoc. + /// + public Dot11BssType dot11BssType; + /// + /// The BSSID of the association. + /// + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)] + public byte[] dot11Bssid; + /// + /// The physical type of the association. + /// + public Dot11PhyType dot11PhyType; + /// + /// The position of the value in the structure containing the list of PHY types. + /// + public uint dot11PhyIndex; + /// + /// A percentage value that represents the signal quality of the network. + /// This field contains a value between 0 and 100. + /// A value of 0 implies an actual RSSI signal strength of -100 dbm. + /// A value of 100 implies an actual RSSI signal strength of -50 dbm. + /// You can calculate the RSSI signal strength value for values between 1 and 99 using linear interpolation. + /// + public uint wlanSignalQuality; + /// + /// The receiving rate of the association. + /// + public uint rxRate; + /// + /// The transmission rate of the association. + /// + public uint txRate; + + /// + /// Gets the BSSID of the associated access point. + /// + /// The BSSID. + public PhysicalAddress Dot11Bssid + { + get { return new PhysicalAddress(dot11Bssid); } + } + } + + /// + /// Defines the mode of connection. + /// + /// + /// Corresponds to the native WLAN_CONNECTION_MODE type. + /// + public enum WlanConnectionMode + { + /// + /// A profile will be used to make the connection. + /// + Profile = 0, + /// + /// A temporary profile will be used to make the connection. + /// + TemporaryProfile, + /// + /// Secure discovery will be used to make the connection. + /// + DiscoverySecure, + /// + /// Unsecure discovery will be used to make the connection. + /// + DiscoveryUnsecure, + /// + /// A connection will be made automatically, generally using a persistent profile. + /// + Auto, + /// + /// Not used. + /// + Invalid + } + + /// + /// Defines a wireless LAN authentication algorithm. + /// + /// + /// Corresponds to the native DOT11_AUTH_ALGORITHM type. + /// + public enum Dot11AuthAlgorithm : uint + { + /// + /// Specifies an IEEE 802.11 Open System authentication algorithm. + /// + IEEE80211_Open = 1, + /// + /// Specifies an 802.11 Shared Key authentication algorithm that requires the use of a pre-shared Wired Equivalent Privacy (WEP) key for the 802.11 authentication. + /// + IEEE80211_SharedKey = 2, + /// + /// Specifies a Wi-Fi Protected Access (WPA) algorithm. IEEE 802.1X port authentication is performed by the supplicant, authenticator, and authentication server. Cipher keys are dynamically derived through the authentication process. + /// This algorithm is valid only for BSS types of . + /// When the WPA algorithm is enabled, the 802.11 station will associate only with an access point whose beacon or probe responses contain the authentication suite of type 1 (802.1X) within the WPA information element (IE). + /// + WPA = 3, + /// + /// Specifies a WPA algorithm that uses preshared keys (PSK). IEEE 802.1X port authentication is performed by the supplicant and authenticator. Cipher keys are dynamically derived through a preshared key that is used on both the supplicant and authenticator. + /// This algorithm is valid only for BSS types of . + /// When the WPA PSK algorithm is enabled, the 802.11 station will associate only with an access point whose beacon or probe responses contain the authentication suite of type 2 (preshared key) within the WPA IE. + /// + WPA_PSK = 4, + /// + /// This value is not supported. + /// + WPA_None = 5, + /// + /// Specifies an 802.11i Robust Security Network Association (RSNA) algorithm. WPA2 is one such algorithm. IEEE 802.1X port authentication is performed by the supplicant, authenticator, and authentication server. Cipher keys are dynamically derived through the authentication process. + /// This algorithm is valid only for BSS types of . + /// When the RSNA algorithm is enabled, the 802.11 station will associate only with an access point whose beacon or probe responses contain the authentication suite of type 1 (802.1X) within the RSN IE. + /// + RSNA = 6, + /// + /// Specifies an 802.11i RSNA algorithm that uses PSK. IEEE 802.1X port authentication is performed by the supplicant and authenticator. Cipher keys are dynamically derived through a preshared key that is used on both the supplicant and authenticator. + /// This algorithm is valid only for BSS types of . + /// When the RSNA PSK algorithm is enabled, the 802.11 station will associate only with an access point whose beacon or probe responses contain the authentication suite of type 2(preshared key) within the RSN IE. + /// + RSNA_PSK = 7, + /// + /// Indicates the start of the range that specifies proprietary authentication algorithms that are developed by an IHV. + /// + /// + /// This enumerator is valid only when the miniport driver is operating in Extensible Station (ExtSTA) mode. + /// + IHV_Start = 0x80000000, + /// + /// Indicates the end of the range that specifies proprietary authentication algorithms that are developed by an IHV. + /// + /// + /// This enumerator is valid only when the miniport driver is operating in Extensible Station (ExtSTA) mode. + /// + IHV_End = 0xffffffff + } + + /// + /// Defines a cipher algorithm for data encryption and decryption. + /// + /// + /// Corresponds to the native DOT11_CIPHER_ALGORITHM type. + /// + public enum Dot11CipherAlgorithm : uint + { + /// + /// Specifies that no cipher algorithm is enabled or supported. + /// + None = 0x00, + /// + /// Specifies a Wired Equivalent Privacy (WEP) algorithm, which is the RC4-based algorithm that is specified in the 802.11-1999 standard. This enumerator specifies the WEP cipher algorithm with a 40-bit cipher key. + /// + WEP40 = 0x01, + /// + /// Specifies a Temporal Key Integrity Protocol (TKIP) algorithm, which is the RC4-based cipher suite that is based on the algorithms that are defined in the WPA specification and IEEE 802.11i-2004 standard. This cipher also uses the Michael Message Integrity Code (MIC) algorithm for forgery protection. + /// + TKIP = 0x02, + /// + /// Specifies an AES-CCMP algorithm, as specified in the IEEE 802.11i-2004 standard and RFC 3610. Advanced Encryption Standard (AES) is the encryption algorithm defined in FIPS PUB 197. + /// + CCMP = 0x04, + /// + /// Specifies a WEP cipher algorithm with a 104-bit cipher key. + /// + WEP104 = 0x05, + /// + /// Specifies a Robust Security Network (RSN) Use Group Key cipher suite. For more information about the Use Group Key cipher suite, refer to Clause 7.3.2.9.1 of the IEEE 802.11i-2004 standard. + /// + WPA_UseGroup = 0x100, + /// + /// Specifies a Wifi Protected Access (WPA) Use Group Key cipher suite. For more information about the Use Group Key cipher suite, refer to Clause 7.3.2.9.1 of the IEEE 802.11i-2004 standard. + /// + RSN_UseGroup = 0x100, + /// + /// Specifies a WEP cipher algorithm with a cipher key of any length. + /// + WEP = 0x101, + /// + /// Specifies the start of the range that is used to define proprietary cipher algorithms that are developed by an independent hardware vendor (IHV). + /// + IHV_Start = 0x80000000, + /// + /// Specifies the end of the range that is used to define proprietary cipher algorithms that are developed by an IHV. + /// + IHV_End = 0xffffffff + } + + /// + /// Defines the security attributes for a wireless connection. + /// + /// + /// Corresponds to the native WLAN_SECURITY_ATTRIBUTES type. + /// + [StructLayout(LayoutKind.Sequential)] + public struct WlanSecurityAttributes + { + /// + /// Indicates whether security is enabled for this connection. + /// + [MarshalAs(UnmanagedType.Bool)] + public bool securityEnabled; + [MarshalAs(UnmanagedType.Bool)] + public bool oneXEnabled; + /// + /// The authentication algorithm. + /// + public Dot11AuthAlgorithm dot11AuthAlgorithm; + /// + /// The cipher algorithm. + /// + public Dot11CipherAlgorithm dot11CipherAlgorithm; + } + + /// + /// Defines the attributes of a wireless connection. + /// + /// + /// Corresponds to the native WLAN_CONNECTION_ATTRIBUTES type. + /// + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + public struct WlanConnectionAttributes + { + /// + /// The state of the interface. + /// + public WlanInterfaceState isState; + /// + /// The mode of the connection. + /// + public WlanConnectionMode wlanConnectionMode; + /// + /// The name of the profile used for the connection. Profile names are case-sensitive. + /// + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = (int)WLAN_MAX_NAME_LENGTH)] + public string profileName; + /// + /// The attributes of the association. + /// + public WlanAssociationAttributes wlanAssociationAttributes; + /// + /// The security attributes of the connection. + /// + public WlanSecurityAttributes wlanSecurityAttributes; + } + + /// + /// Contains information about a LAN interface. + /// + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + public struct WlanInterfaceInfo + { + /// + /// The GUID of the interface. + /// + public Guid interfaceGuid; + /// + /// The description of the interface. + /// + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = (int)WLAN_MAX_NAME_LENGTH)] + public string interfaceDescription; + /// + /// The current state of the interface. + /// + public WlanInterfaceState isState; + } + + /// + /// The header of the list returned by . + /// + [StructLayout(LayoutKind.Sequential)] + internal struct WlanInterfaceInfoListHeader + { + public uint numberOfItems; + public uint index; + } + + /// + /// The header of the list returned by . + /// + [StructLayout(LayoutKind.Sequential)] + internal struct WlanProfileInfoListHeader + { + public uint numberOfItems; + public uint index; + } + + /// + /// Contains basic information about a profile. + /// + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + public struct WlanProfileInfo + { + /// + /// The name of the profile. This value may be the name of a domain if the profile is for provisioning. Profile names are case-sensitive. + /// + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = (int)WLAN_MAX_NAME_LENGTH)] + public string profileName; + /// + /// Profile flags. + /// + public WlanProfileFlags profileFlags; + } + + #endregion + + /// + /// Helper method to wrap calls to Native WiFi API methods. + /// If the method falls, throws an exception containing the error code. + /// + /// The error code. + [DebuggerStepThrough] + internal static void ThrowIfError(int win32ErrorCode) + { + if (win32ErrorCode != 0) + throw new Win32Exception(win32ErrorCode); + } + } +} diff --git a/winPEAS/winPEASexe/winPEAS/NativeWifiApi/WlanClient.cs b/winPEAS/winPEASexe/winPEAS/NativeWifiApi/WlanClient.cs new file mode 100644 index 0000000..23958b6 --- /dev/null +++ b/winPEAS/winPEASexe/winPEAS/NativeWifiApi/WlanClient.cs @@ -0,0 +1,231 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Threading; + +namespace winPEAS.NativeWifiApi +{ + class WlanClient + { + public class WlanInterface + { + private WlanClient client; + private Wlan.WlanInterfaceInfo info; + + #region Event queue + + private bool queueEvents; + private AutoResetEvent eventQueueFilled = new AutoResetEvent(false); + private Queue eventQueue = new Queue(); + + #endregion + + internal WlanInterface(WlanClient client, Wlan.WlanInterfaceInfo info) + { + this.client = client; + this.info = info; + } + + + /// + /// Converts a pointer to a BSS list (header + entries) to an array of BSS entries. + /// + /// A pointer to a BSS list's header. + /// An array of BSS entries. + private Wlan.WlanBssEntry[] ConvertBssListPtr(IntPtr bssListPtr) + { + Wlan.WlanBssListHeader bssListHeader = (Wlan.WlanBssListHeader)Marshal.PtrToStructure(bssListPtr, typeof(Wlan.WlanBssListHeader)); + long bssListIt = bssListPtr.ToInt64() + Marshal.SizeOf(typeof(Wlan.WlanBssListHeader)); + Wlan.WlanBssEntry[] bssEntries = new Wlan.WlanBssEntry[bssListHeader.numberOfItems]; + for (int i = 0; i < bssListHeader.numberOfItems; ++i) + { + bssEntries[i] = (Wlan.WlanBssEntry)Marshal.PtrToStructure(new IntPtr(bssListIt), typeof(Wlan.WlanBssEntry)); + bssListIt += Marshal.SizeOf(typeof(Wlan.WlanBssEntry)); + } + return bssEntries; + } + + /// + /// Retrieves the basic service sets (BSS) list of all available networks. + /// + public Wlan.WlanBssEntry[] GetNetworkBssList() + { + IntPtr bssListPtr; + Wlan.ThrowIfError( + Wlan.WlanGetNetworkBssList(client.clientHandle, info.interfaceGuid, IntPtr.Zero, Wlan.Dot11BssType.Any, false, IntPtr.Zero, out bssListPtr)); + try + { + return ConvertBssListPtr(bssListPtr); + } + finally + { + Wlan.WlanFreeMemory(bssListPtr); + } + } + + /// + /// Retrieves the basic service sets (BSS) list of the specified network. + /// + /// Specifies the SSID of the network from which the BSS list is requested. + /// Indicates the BSS type of the network. + /// Indicates whether security is enabled on the network. + public Wlan.WlanBssEntry[] GetNetworkBssList(Wlan.Dot11Ssid ssid, Wlan.Dot11BssType bssType, bool securityEnabled) + { + IntPtr ssidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ssid)); + Marshal.StructureToPtr(ssid, ssidPtr, false); + try + { + IntPtr bssListPtr; + Wlan.ThrowIfError( + Wlan.WlanGetNetworkBssList(client.clientHandle, info.interfaceGuid, ssidPtr, bssType, securityEnabled, IntPtr.Zero, out bssListPtr)); + try + { + return ConvertBssListPtr(bssListPtr); + } + finally + { + Wlan.WlanFreeMemory(bssListPtr); + } + } + finally + { + Marshal.FreeHGlobal(ssidPtr); + } + } + + /// + /// Gets the profile's XML specification. + /// + /// The name of the profile. + /// Whether the password should be unencrypted in the returned XML. By default this is false and the password is left encrypted. + /// The XML document. + public string GetProfileXml(string profileName, bool unencryptedPassword = true) + { + IntPtr profileXmlPtr; + Wlan.WlanProfileFlags flags = unencryptedPassword ? Wlan.WlanProfileFlags.GetPlaintextKey : Wlan.WlanProfileFlags.None; + Wlan.WlanAccess access; + Wlan.ThrowIfError( + Wlan.WlanGetProfile(client.clientHandle, info.interfaceGuid, profileName, IntPtr.Zero, out profileXmlPtr, out flags, + out access)); + try + { + return Marshal.PtrToStringUni(profileXmlPtr); + } + finally + { + Wlan.WlanFreeMemory(profileXmlPtr); + } + } + + /// + /// Gets the information of all profiles on this interface. + /// + /// The profiles information. + public Wlan.WlanProfileInfo[] GetProfiles() + { + IntPtr profileListPtr; + Wlan.ThrowIfError( + Wlan.WlanGetProfileList(client.clientHandle, info.interfaceGuid, IntPtr.Zero, out profileListPtr)); + try + { + Wlan.WlanProfileInfoListHeader header = (Wlan.WlanProfileInfoListHeader)Marshal.PtrToStructure(profileListPtr, typeof(Wlan.WlanProfileInfoListHeader)); + Wlan.WlanProfileInfo[] profileInfos = new Wlan.WlanProfileInfo[header.numberOfItems]; + long profileListIterator = profileListPtr.ToInt64() + Marshal.SizeOf(header); + for (int i = 0; i < header.numberOfItems; ++i) + { + Wlan.WlanProfileInfo profileInfo = (Wlan.WlanProfileInfo)Marshal.PtrToStructure(new IntPtr(profileListIterator), typeof(Wlan.WlanProfileInfo)); + profileInfos[i] = profileInfo; + profileListIterator += Marshal.SizeOf(profileInfo); + } + return profileInfos; + } + finally + { + Wlan.WlanFreeMemory(profileListPtr); + } + } + + /// + /// Enqueues a notification event to be processed serially. + /// + private void EnqueueEvent(object queuedEvent) + { + lock (eventQueue) + eventQueue.Enqueue(queuedEvent); + eventQueueFilled.Set(); + } + } + + private IntPtr clientHandle; + private uint negotiatedVersion; + private Wlan.WlanNotificationCallbackDelegate wlanNotificationCallback; + + private Dictionary ifaces = new Dictionary(); + + public WlanClient() + { + Wlan.ThrowIfError( + Wlan.WlanOpenHandle(Wlan.WLAN_CLIENT_VERSION_XP_SP2, IntPtr.Zero, out negotiatedVersion, out clientHandle)); + } + + ~WlanClient() + { + Wlan.WlanCloseHandle(clientHandle, IntPtr.Zero); + } + + /// + /// Gets the WLAN interfaces. + /// + /// The WLAN interfaces. + public WlanInterface[] Interfaces + { + get + { + IntPtr ifaceList; + Wlan.ThrowIfError( + Wlan.WlanEnumInterfaces(clientHandle, IntPtr.Zero, out ifaceList)); + try + { + Wlan.WlanInterfaceInfoListHeader header = + (Wlan.WlanInterfaceInfoListHeader)Marshal.PtrToStructure(ifaceList, typeof(Wlan.WlanInterfaceInfoListHeader)); + Int64 listIterator = ifaceList.ToInt64() + Marshal.SizeOf(header); + WlanInterface[] interfaces = new WlanInterface[header.numberOfItems]; + List currentIfaceGuids = new List(); + for (int i = 0; i < header.numberOfItems; ++i) + { + Wlan.WlanInterfaceInfo info = + (Wlan.WlanInterfaceInfo)Marshal.PtrToStructure(new IntPtr(listIterator), typeof(Wlan.WlanInterfaceInfo)); + listIterator += Marshal.SizeOf(info); + WlanInterface wlanIface; + currentIfaceGuids.Add(info.interfaceGuid); + if (ifaces.ContainsKey(info.interfaceGuid)) + wlanIface = ifaces[info.interfaceGuid]; + else + wlanIface = new WlanInterface(this, info); + interfaces[i] = wlanIface; + ifaces[info.interfaceGuid] = wlanIface; + } + + // Remove stale interfaces + Queue deadIfacesGuids = new Queue(); + foreach (Guid ifaceGuid in ifaces.Keys) + { + if (!currentIfaceGuids.Contains(ifaceGuid)) + deadIfacesGuids.Enqueue(ifaceGuid); + } + while (deadIfacesGuids.Count != 0) + { + Guid deadIfaceGuid = deadIfacesGuids.Dequeue(); + ifaces.Remove(deadIfaceGuid); + } + + return interfaces; + } + finally + { + Wlan.WlanFreeMemory(ifaceList); + } + } + } + } +} diff --git a/winPEAS/winPEASexe/winPEAS/NetworkInfo.cs b/winPEAS/winPEASexe/winPEAS/NetworkInfo.cs index 0c7e61e..1156e0b 100755 --- a/winPEAS/winPEASexe/winPEAS/NetworkInfo.cs +++ b/winPEAS/winPEASexe/winPEAS/NetworkInfo.cs @@ -369,7 +369,7 @@ namespace winPEAS current_perm = Convert.ToInt32(result.Properties["ReturnValue"].Value); perm_str = MyUtils.PermInt2Str(current_perm); } - catch (ManagementException me) + catch (ManagementException) { perm_str = ""; //no permissions are set on the share } diff --git a/winPEAS/winPEASexe/winPEAS/ProcessesInfo.cs b/winPEAS/winPEASexe/winPEAS/ProcessInfo/DefensiveProcesses.cs old mode 100755 new mode 100644 similarity index 81% rename from winPEAS/winPEASexe/winPEAS/ProcessesInfo.cs rename to winPEAS/winPEASexe/winPEAS/ProcessInfo/DefensiveProcesses.cs index 556b054..a29e7bc --- a/winPEAS/winPEASexe/winPEAS/ProcessesInfo.cs +++ b/winPEAS/winPEASexe/winPEAS/ProcessInfo/DefensiveProcesses.cs @@ -1,793 +1,667 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Management; -using System.Runtime.InteropServices; -using System.Security.Principal; -using System.Text.RegularExpressions; - -namespace winPEAS -{ - class ProcessesInfo - { - public static Hashtable defensiveProcesses = new Hashtable() - { - {"mcshield.exe" , "McAfee AV"}, - {"windefend.exe" , "Windows Defender AV"}, - {"MSASCui.exe" , "Windows Defender AV"}, - {"MSASCuiL.exe" , "Windows Defender AV"}, - {"msmpeng.exe" , "Windows Defender AV"}, - {"msmpsvc.exe" , "Windows Defender AV"}, - {"WRSA.exe" , "WebRoot AV"}, - {"savservice.exe" , "Sophos AV"}, - {"TMCCSF.exe" , "Trend Micro AV"}, - {"symantec antivirus.exe" , "Symantec AV"}, - {"mbae.exe" , "MalwareBytes Anti-Exploit"}, - {"parity.exe" , "Bit9 application whitelisting"}, - {"cb.exe" , "Carbon Black behavioral analysis"}, - {"bds-vision.exe" , "BDS Vision behavioral analysis"}, - {"Triumfant.exe" , "Triumfant behavioral analysis"}, - {"CSFalcon.exe" , "CrowdStrike Falcon EDR"}, - {"ossec.exe" , "OSSEC intrusion detection"}, - {"TmPfw.exe" , "Trend Micro firewall"}, - {"dgagent.exe" , "Verdasys Digital Guardian DLP"}, - {"kvoop.exe" , " DLP process" }, - {"AAWTray.exe" , ""}, - {"ackwin32.exe" , ""}, - {"Ad-Aware.exe" , ""}, - {"adaware.exe" , ""}, - {"advxdwin.exe" , ""}, - {"agentsvr.exe" , ""}, - {"agentw.exe" , ""}, - {"alertsvc.exe" , ""}, - {"alevir.exe" , ""}, - {"alogserv.exe" , ""}, - {"amon9x.exe" , ""}, - {"anti-trojan.exe" , ""}, - {"antivirus.exe" , ""}, - {"ants.exe" , ""}, - {"apimonitor.exe" , ""}, - {"aplica32.exe" , ""}, - {"apvxdwin.exe" , ""}, - {"arr.exe" , ""}, - {"atcon.exe" , ""}, - {"atguard.exe" , ""}, - {"atro55en.exe" , ""}, - {"atupdater.exe" , ""}, - {"atwatch.exe" , ""}, - {"au.exe" , ""}, - {"aupdate.exe" , ""}, - {"auto-protect.nav80try.exe", ""}, - {"autodown.exe" , ""}, - {"autoruns.exe" , ""}, - {"autorunsc.exe" , ""}, - {"autotrace.exe" , ""}, - {"autoupdate.exe" , ""}, - {"avconsol.exe" , ""}, - {"ave32.exe" , ""}, - {"avgcc32.exe" , ""}, - {"avgctrl.exe" , ""}, - {"avgemc.exe" , ""}, - {"avgnt.exe" , ""}, - {"avgrsx.exe" , ""}, - {"avgserv.exe" , ""}, - {"avgserv9.exe" , ""}, - {"avguard.exe" , ""}, - {"avgwdsvc.exe" , ""}, - {"avgui.exe" , ""}, - {"avgw.exe" , ""}, - {"avkpop.exe" , ""}, - {"avkserv.exe" , ""}, - {"avkservice.exe" , ""}, - {"avkwctl9.exe" , ""}, - {"avltmain.exe" , ""}, - {"avnt.exe" , ""}, - {"avp.exe" , ""}, - {"avp32.exe" , ""}, - {"avpcc.exe" , ""}, - {"avpdos32.exe" , ""}, - {"avpm.exe" , ""}, - {"avptc32.exe" , ""}, - {"avpupd.exe" , ""}, - {"avsched32.exe" , ""}, - {"avsynmgr.exe" , ""}, - {"avwin.exe" , ""}, - {"avwin95.exe" , ""}, - {"avwinnt.exe" , ""}, - {"avwupd.exe" , ""}, - {"avwupd32.exe" , ""}, - {"avwupsrv.exe" , ""}, - {"avxmonitor9x.exe" , ""}, - {"avxmonitornt.exe" , ""}, - {"avxquar.exe" , ""}, - {"backweb.exe" , ""}, - {"bargains.exe" , ""}, - {"bd_professional.exe" , ""}, - {"beagle.exe" , ""}, - {"belt.exe" , ""}, - {"bidef.exe" , ""}, - {"bidserver.exe" , ""}, - {"bipcp.exe" , ""}, - {"bipcpevalsetup.exe" , ""}, - {"bisp.exe" , ""}, - {"blackd.exe" , ""}, - {"blackice.exe" , ""}, - {"blink.exe" , ""}, - {"blss.exe" , ""}, - {"bootconf.exe" , ""}, - {"bootwarn.exe" , ""}, - {"borg2.exe" , ""}, - {"bpc.exe" , ""}, - {"brasil.exe" , ""}, - {"bs120.exe" , ""}, - {"bundle.exe" , ""}, - {"bvt.exe" , ""}, - {"ccapp.exe" , ""}, - {"ccevtmgr.exe" , ""}, - {"ccpxysvc.exe" , ""}, - {"ccSvcHst.exe" , ""}, - {"cdp.exe" , ""}, - {"cfd.exe" , ""}, - {"cfgwiz.exe" , ""}, - {"cfiadmin.exe" , ""}, - {"cfiaudit.exe" , ""}, - {"cfinet.exe" , ""}, - {"cfinet32.exe" , ""}, - {"claw95.exe" , ""}, - {"claw95cf.exe" , ""}, - {"clean.exe" , ""}, - {"cleaner.exe" , ""}, - {"cleaner3.exe" , ""}, - {"cleanpc.exe" , ""}, - {"cleanup.exe" , ""}, - {"click.exe" , ""}, - {"cmdagent.exe" , ""}, - {"cmesys.exe" , ""}, - {"cmgrdian.exe" , ""}, - {"cmon016.exe" , ""}, - {"connectionmonitor.exe" , ""}, - {"cpd.exe" , ""}, - {"cpf9x206.exe" , ""}, - {"cpfnt206.exe" , ""}, - {"ctrl.exe" , ""}, - {"cv.exe" , ""}, - {"cwnb181.exe" , ""}, - {"cwntdwmo.exe" , ""}, - {"CylanceUI.exe" , ""}, - {"CyProtect.exe" , ""}, - {"CyUpdate.exe" , ""}, - {"cyserver.exe" , ""}, - {"cytray.exe" , ""}, - {"CyveraService.exe" , ""}, - {"datemanager.exe" , ""}, - {"dcomx.exe" , ""}, - {"defalert.exe" , ""}, - {"defscangui.exe" , ""}, - {"defwatch.exe" , ""}, - {"deputy.exe" , ""}, - {"divx.exe" , ""}, - {"dgprompt.exe" , ""}, - {"DgService.exe" , ""}, - {"dllcache.exe" , ""}, - {"dllreg.exe" , ""}, - {"doors.exe" , ""}, - {"dpf.exe" , ""}, - {"dpfsetup.exe" , ""}, - {"dpps2.exe" , ""}, - {"drwatson.exe" , ""}, - {"drweb32.exe" , ""}, - {"drwebupw.exe" , ""}, - {"dssagent.exe" , ""}, - {"dumpcap.exe" , ""}, - {"dvp95.exe" , ""}, - {"dvp95_0.exe" , ""}, - {"ecengine.exe" , ""}, - {"efpeadm.exe" , ""}, - {"egui.exe" , ""}, - {"ekrn.exe" , ""}, - {"emet_agent.exe" , ""}, - {"emet_service.exe" , ""}, - {"emsw.exe" , ""}, - {"engineserver.exe" , ""}, - {"ent.exe" , ""}, - {"esafe.exe" , ""}, - {"escanhnt.exe" , ""}, - {"escanv95.exe" , ""}, - {"espwatch.exe" , ""}, - {"ethereal.exe" , ""}, - {"etrustcipe.exe" , ""}, - {"evpn.exe" , ""}, - {"exantivirus-cnet.exe" , ""}, - {"exe.avxw.exe" , ""}, - {"expert.exe" , ""}, - {"explore.exe" , ""}, - {"f-agnt95.exe" , ""}, - {"f-prot.exe" , ""}, - {"f-prot95.exe" , ""}, - {"f-stopw.exe" , ""}, - {"fameh32.exe" , ""}, - {"fast.exe" , ""}, - {"fch32.exe" , ""}, - {"fcagswd.exe" , "McAfee DLP Agent"}, - {"fcags.exe" , "McAfee DLP Agent"}, - {"fih32.exe" , ""}, - {"findviru.exe" , ""}, - {"firesvc.exe" , "McAfee Host Intrusion Prevention"}, - {"firetray.exe" , ""}, - {"firewall.exe" , ""}, - {"fnrb32.exe" , ""}, - {"fp-win.exe" , ""}, - {"fp-win_trial.exe" , ""}, - {"fprot.exe" , ""}, - {"frameworkservice.exe" , ""}, - {"frminst.exe" , ""}, - {"frw.exe" , ""}, - {"fsaa.exe" , ""}, - {"fsav.exe" , ""}, - {"fsav32.exe" , ""}, - {"fsav530stbyb.exe" , ""}, - {"fsav530wtbyb.exe" , ""}, - {"fsav95.exe" , ""}, - {"fsgk32.exe" , ""}, - {"fsm32.exe" , ""}, - {"fsma32.exe" , ""}, - {"fsmb32.exe" , ""}, - {"gator.exe" , ""}, - {"gbmenu.exe" , ""}, - {"gbpoll.exe" , ""}, - {"generics.exe" , ""}, - {"gmt.exe" , ""}, - {"guard.exe" , ""}, - {"guarddog.exe" , ""}, - {"hacktracersetup.exe" , ""}, - {"hbinst.exe" , ""}, - {"hbsrv.exe" , ""}, - {"HijackThis.exe" , ""}, - {"hipsvc.exe" , ""}, - {"HipMgmt.exe" , "McAfee Host Intrusion Protection"}, - {"hotactio.exe" , ""}, - {"hotpatch.exe" , ""}, - {"htlog.exe" , ""}, - {"htpatch.exe" , ""}, - {"hwpe.exe" , ""}, - {"hxdl.exe" , ""}, - {"hxiul.exe" , ""}, - {"iamapp.exe" , ""}, - {"iamserv.exe" , ""}, - {"iamstats.exe" , ""}, - {"ibmasn.exe" , ""}, - {"ibmavsp.exe" , ""}, - {"icload95.exe" , ""}, - {"icloadnt.exe" , ""}, - {"icmon.exe" , ""}, - {"icsupp95.exe" , ""}, - {"icsuppnt.exe" , ""}, - {"idle.exe" , ""}, - {"iedll.exe" , ""}, - {"iedriver.exe" , ""}, - {"iface.exe" , ""}, - {"ifw2000.exe" , ""}, - {"inetlnfo.exe" , ""}, - {"infus.exe" , ""}, - {"infwin.exe" , ""}, - {"init.exe" , ""}, - {"intdel.exe" , ""}, - {"intren.exe" , ""}, - {"iomon98.exe" , ""}, - {"istsvc.exe" , ""}, - {"jammer.exe" , ""}, - {"jdbgmrg.exe" , ""}, - {"jedi.exe" , ""}, - {"kavlite40eng.exe" , ""}, - {"kavpers40eng.exe" , ""}, - {"kavpf.exe" , ""}, - {"kazza.exe" , ""}, - {"keenvalue.exe" , ""}, - {"kerio-pf-213-en-win.exe" , ""}, - {"kerio-wrl-421-en-win.exe" , ""}, - {"kerio-wrp-421-en-win.exe" , ""}, - {"kernel32.exe" , ""}, - {"KeyPass.exe" , ""}, - {"killprocesssetup161.exe" , ""}, - {"launcher.exe" , ""}, - {"ldnetmon.exe" , ""}, - {"ldpro.exe" , ""}, - {"ldpromenu.exe" , ""}, - {"ldscan.exe" , ""}, - {"lnetinfo.exe" , ""}, - {"loader.exe" , ""}, - {"localnet.exe" , ""}, - {"lockdown.exe" , ""}, - {"lockdown2000.exe" , ""}, - {"lookout.exe" , ""}, - {"lordpe.exe" , ""}, - {"lsetup.exe" , ""}, - {"luall.exe" , ""}, - {"luau.exe" , ""}, - {"lucomserver.exe" , ""}, - {"luinit.exe" , ""}, - {"luspt.exe" , ""}, - {"mapisvc32.exe" , ""}, - {"masvc.exe" , "McAfee Agent"}, - {"mbamservice.exe" , ""}, - {"mcafeefire.exe" , ""}, - {"mcagent.exe" , ""}, - {"mcmnhdlr.exe" , ""}, - {"mcscript.exe" , ""}, - {"mcscript_inuse.exe" , ""}, - {"mctool.exe" , ""}, - {"mctray.exe" , ""}, - {"mcupdate.exe" , ""}, - {"mcvsrte.exe" , ""}, - {"mcvsshld.exe" , ""}, - {"md.exe" , ""}, - {"mfeann.exe" , "McAfee VirusScan Enterprise"}, - {"mfemactl.exe" , "McAfee VirusScan Enterprise"}, - {"mfevtps.exe" , ""}, - {"mfin32.exe" , ""}, - {"mfw2en.exe" , ""}, - {"mfweng3.02d30.exe" , ""}, - {"mgavrtcl.exe" , ""}, - {"mgavrte.exe" , ""}, - {"mghtml.exe" , ""}, - {"mgui.exe" , ""}, - {"minilog.exe" , ""}, - {"minionhost.exe" , ""}, - {"mmod.exe" , ""}, - {"monitor.exe" , ""}, - {"moolive.exe" , ""}, - {"mostat.exe" , ""}, - {"mpfagent.exe" , ""}, - {"mpfservice.exe" , ""}, - {"mpftray.exe" , ""}, - {"mrflux.exe" , ""}, - {"msapp.exe" , ""}, - {"msbb.exe" , ""}, - {"msblast.exe" , ""}, - {"mscache.exe" , ""}, - {"msccn32.exe" , ""}, - {"mscman.exe" , ""}, - {"msconfig.exe" , ""}, - {"msdm.exe" , ""}, - {"msdos.exe" , ""}, - {"msiexec16.exe" , ""}, - {"msinfo32.exe" , ""}, - {"mslaugh.exe" , ""}, - {"msmgt.exe" , ""}, - {"msmsgri32.exe" , ""}, - {"MsSense.exe" , "Microsoft Defender ATP"}, - {"mssmmc32.exe" , ""}, - {"mssys.exe" , ""}, - {"msvxd.exe" , ""}, - {"mu0311ad.exe" , ""}, - {"mwatch.exe" , ""}, - {"n32scanw.exe" , ""}, - {"naprdmgr.exe" , ""}, - {"nav.exe" , ""}, - {"navap.navapsvc.exe" , ""}, - {"navapsvc.exe" , ""}, - {"navapw32.exe" , ""}, - {"navdx.exe" , ""}, - {"navlu32.exe" , ""}, - {"navnt.exe" , ""}, - {"navstub.exe" , ""}, - {"navw32.exe" , ""}, - {"navwnt.exe" , ""}, - {"nc2000.exe" , ""}, - {"ncinst4.exe" , ""}, - {"ndd32.exe" , ""}, - {"neomonitor.exe" , ""}, - {"neowatchlog.exe" , ""}, - {"netarmor.exe" , ""}, - {"netd32.exe" , ""}, - {"netinfo.exe" , ""}, - {"netmon.exe" , ""}, - {"netscanpro.exe" , ""}, - {"netspyhunter-1.2.exe" , ""}, - {"netstat.exe" , ""}, - {"netutils.exe" , ""}, - {"nisserv.exe" , ""}, - {"nisum.exe" , ""}, - {"nmain.exe" , ""}, - {"nod32.exe" , ""}, - {"normist.exe" , ""}, - {"norton_internet_secu_3.0_407.exe" , ""}, - {"notstart.exe" , ""}, - {"npf40_tw_98_nt_me_2k.exe" , ""}, - {"npfmessenger.exe" , ""}, - {"nprotect.exe" , ""}, - {"npscheck.exe" , ""}, - {"npssvc.exe" , ""}, - {"nsched32.exe" , ""}, - {"nssys32.exe" , ""}, - {"nstask32.exe" , ""}, - {"nsupdate.exe" , ""}, - {"nt.exe" , ""}, - {"ntrtscan.exe" , ""}, - {"ntvdm.exe" , ""}, - {"ntxconfig.exe" , ""}, - {"nui.exe" , ""}, - {"nupgrade.exe" , ""}, - {"nvarch16.exe" , ""}, - {"nvc95.exe" , ""}, - {"nvsvc32.exe" , ""}, - {"nwinst4.exe" , ""}, - {"nwservice.exe" , ""}, - {"nwtool16.exe" , ""}, - {"nxlog.exe" , ""}, - {"ollydbg.exe" , ""}, - {"onsrvr.exe" , ""}, - {"optimize.exe" , ""}, - {"ostronet.exe" , ""}, - {"osqueryd.exe" , ""}, - {"otfix.exe" , ""}, - {"outpost.exe" , ""}, - {"outpostinstall.exe" , ""}, - {"outpostproinstall.exe" , ""}, - {"padmin.exe" , ""}, - {"panixk.exe" , ""}, - {"patch.exe" , ""}, - {"pavcl.exe" , ""}, - {"pavproxy.exe" , ""}, - {"pavsched.exe" , ""}, - {"pavw.exe" , ""}, - {"pccwin98.exe" , ""}, - {"pcfwallicon.exe" , ""}, - {"pcip10117_0.exe" , ""}, - {"pcscan.exe" , ""}, - {"pdsetup.exe" , ""}, - {"periscope.exe" , ""}, - {"persfw.exe" , ""}, - {"perswf.exe" , ""}, - {"pf2.exe" , ""}, - {"pfwadmin.exe" , ""}, - {"pgmonitr.exe" , ""}, - {"pingscan.exe" , ""}, - {"platin.exe" , ""}, - {"pop3trap.exe" , ""}, - {"poproxy.exe" , ""}, - {"popscan.exe" , ""}, - {"portdetective.exe" , ""}, - {"portmonitor.exe" , ""}, - {"powerscan.exe" , ""}, - {"ppinupdt.exe" , ""}, - {"pptbc.exe" , ""}, - {"ppvstop.exe" , ""}, - {"prizesurfer.exe" , ""}, - {"prmt.exe" , ""}, - {"prmvr.exe" , ""}, - {"procdump.exe" , ""}, - {"processmonitor.exe" , ""}, - {"procexp.exe" , ""}, - {"procexp64.exe" , ""}, - {"procexplorerv1.0.exe" , ""}, - {"procmon.exe" , ""}, - {"programauditor.exe" , ""}, - {"proport.exe" , ""}, - {"protectx.exe" , ""}, - {"pspf.exe" , ""}, - {"purge.exe" , ""}, - {"qconsole.exe" , ""}, - {"qserver.exe" , ""}, - {"rapapp.exe" , ""}, - {"rav7.exe" , ""}, - {"rav7win.exe" , ""}, - {"rav8win32eng.exe" , ""}, - {"ray.exe" , ""}, - {"rb32.exe" , ""}, - {"rcsync.exe" , ""}, - {"realmon.exe" , ""}, - {"reged.exe" , ""}, - {"regedit.exe" , ""}, - {"regedt32.exe" , ""}, - {"rescue.exe" , ""}, - {"rescue32.exe" , ""}, - {"rrguard.exe" , ""}, - {"rtvscan.exe" , ""}, - {"rtvscn95.exe" , ""}, - {"rulaunch.exe" , ""}, - {"run32dll.exe" , ""}, - {"rundll.exe" , ""}, - {"rundll16.exe" , ""}, - {"ruxdll32.exe" , ""}, - {"safeweb.exe" , ""}, - {"sahagent.exescan32.exe" , ""}, - {"save.exe" , ""}, - {"savenow.exe" , ""}, - {"sbserv.exe" , ""}, - {"scam32.exe" , ""}, - {"scan32.exe" , ""}, - {"scan95.exe" , ""}, - {"scanpm.exe" , ""}, - {"scrscan.exe" , ""}, - {"SentinelOne.exe" , ""}, - {"serv95.exe" , ""}, - {"setupvameeval.exe" , ""}, - {"setup_flowprotector_us.exe", ""}, - {"sfc.exe" , ""}, - {"sgssfw32.exe" , ""}, - {"sh.exe" , ""}, - {"shellspyinstall.exe" , ""}, - {"shn.exe" , ""}, - {"showbehind.exe" , ""}, - {"shstat.exe" , "McAfee VirusScan Enterprise"}, - {"SISIDSService.exe" , ""}, - {"SISIPSUtil.exe" , ""}, - {"smc.exe" , ""}, - {"sms.exe" , ""}, - {"smss32.exe" , ""}, - {"soap.exe" , ""}, - {"sofi.exe" , ""}, - {"sperm.exe" , ""}, - {"splunk.exe" , "Splunk"}, - {"splunkd.exe" , "Splunk"}, - {"splunk-admon.exe" , "Splunk"}, - {"splunk-powershell.exe" , "Splunk"}, - {"splunk-winevtlog.exe" , "Splunk"}, - {"spf.exe" , ""}, - {"sphinx.exe" , ""}, - {"spoler.exe" , ""}, - {"spoolcv.exe" , ""}, - {"spoolsv32.exe" , ""}, - {"spyxx.exe" , ""}, - {"srexe.exe" , ""}, - {"srng.exe" , ""}, - {"ss3edit.exe" , ""}, - {"ssgrate.exe" , ""}, - {"ssg_4104.exe" , ""}, - {"st2.exe" , ""}, - {"start.exe" , ""}, - {"stcloader.exe" , ""}, - {"supftrl.exe" , ""}, - {"support.exe" , ""}, - {"supporter5.exe" , ""}, - {"svchostc.exe" , ""}, - {"svchosts.exe" , ""}, - {"sweep95.exe" , ""}, - {"sweepnet.sweepsrv.sys.swnetsup.exe", ""}, - {"symproxysvc.exe" , ""}, - {"symtray.exe" , ""}, - {"sysedit.exe" , ""}, - {"sysmon.exe" , "Sysinternals Sysmon"}, - {"sysupd.exe" , ""}, - {"TaniumClient.exe" , "Tanium"}, - {"taskmg.exe" , ""}, - {"taskmo.exe" , ""}, - {"taumon.exe" , ""}, - {"tbmon.exe" , ""}, - {"tbscan.exe" , ""}, - {"tc.exe" , ""}, - {"tca.exe" , ""}, - {"tcm.exe" , ""}, - {"tcpview.exe" , ""}, - {"tds-3.exe" , ""}, - {"tds2-98.exe" , ""}, - {"tds2-nt.exe" , ""}, - {"teekids.exe" , ""}, - {"tfak.exe" , ""}, - {"tfak5.exe" , ""}, - {"tgbob.exe" , ""}, - {"titanin.exe" , ""}, - {"titaninxp.exe" , ""}, - {"tlaservice.exe" , ""}, - {"tlaworker.exe" , ""}, - {"tracert.exe" , ""}, - {"trickler.exe" , ""}, - {"trjscan.exe" , ""}, - {"trjsetup.exe" , ""}, - {"trojantrap3.exe" , ""}, - {"tsadbot.exe" , ""}, - {"tshark.exe" , ""}, - {"tvmd.exe" , ""}, - {"tvtmd.exe" , ""}, - {"udaterui.exe" , ""}, - {"undoboot.exe" , ""}, - {"updat.exe" , ""}, - {"update.exe" , ""}, - {"updaterui.exe" , ""}, - {"upgrad.exe" , ""}, - {"utpost.exe" , ""}, - {"vbcmserv.exe" , ""}, - {"vbcons.exe" , ""}, - {"vbust.exe" , ""}, - {"vbwin9x.exe" , ""}, - {"vbwinntw.exe" , ""}, - {"vcsetup.exe" , ""}, - {"vet32.exe" , ""}, - {"vet95.exe" , ""}, - {"vettray.exe" , ""}, - {"vfsetup.exe" , ""}, - {"vir-help.exe" , ""}, - {"virusmdpersonalfirewall.exe", ""}, - {"vnlan300.exe" , ""}, - {"vnpc3000.exe" , ""}, - {"vpc32.exe" , ""}, - {"vpc42.exe" , ""}, - {"vpfw30s.exe" , ""}, - {"vptray.exe" , ""}, - {"vscan40.exe" , ""}, - {"vscenu6.02d30.exe" , ""}, - {"vsched.exe" , ""}, - {"vsecomr.exe" , ""}, - {"vshwin32.exe" , ""}, - {"vsisetup.exe" , ""}, - {"vsmain.exe" , ""}, - {"vsmon.exe" , ""}, - {"vsstat.exe" , ""}, - {"vstskmgr.exe" , "McAfee VirusScan Enterprise"}, - {"vswin9xe.exe" , ""}, - {"vswinntse.exe" , ""}, - {"vswinperse.exe" , ""}, - {"w32dsm89.exe" , ""}, - {"w9x.exe" , ""}, - {"watchdog.exe" , ""}, - {"webdav.exe" , ""}, - {"webscanx.exe" , ""}, - {"webtrap.exe" , ""}, - {"wfindv32.exe" , ""}, - {"whoswatchingme.exe" , ""}, - {"wimmun32.exe" , ""}, - {"win-bugsfix.exe" , ""}, - {"win32.exe" , ""}, - {"win32us.exe" , ""}, - {"winactive.exe" , ""}, - {"window.exe" , ""}, - {"windows.exe" , ""}, - {"wininetd.exe" , ""}, - {"wininitx.exe" , ""}, - {"winlogin.exe" , ""}, - {"winmain.exe" , ""}, - {"winnet.exe" , ""}, - {"winppr32.exe" , ""}, - {"winrecon.exe" , ""}, - {"winservn.exe" , ""}, - {"winssk32.exe" , ""}, - {"winstart.exe" , ""}, - {"winstart001.exe" , ""}, - {"wintsk32.exe" , ""}, - {"winupdate.exe" , ""}, - {"wireshark.exe" , ""}, - {"wkufind.exe" , ""}, - {"wnad.exe" , ""}, - {"wnt.exe" , ""}, - {"wradmin.exe" , ""}, - {"wrctrl.exe" , ""}, - {"wsbgate.exe" , ""}, - {"wupdater.exe" , ""}, - {"wupdt.exe" , ""}, - {"wyvernworksfirewall.exe" , ""}, - {"xagt.exe" , ""}, - {"xpf202en.exe" , ""}, - {"zapro.exe" , ""}, - {"zapsetup3001.exe" , ""}, - {"zatutor.exe" , ""}, - /*{"zonalm2601" , ""}, These names (ending in .exe) are detected by AVs - {"zonealarm" , ""}, - {"_avp32" , ""}, - {"_avpcc" , ""}, - {"rshell" , ""}, - {"_avpms" , ""}*/ - }; - - // TODO: cyberark? other password managers? - public static Hashtable interestingProcesses = new Hashtable() - { - {"CmRcService.exe" , "Configuration Manager Remote Control Service"}, - {"ftp.exe" , "Misc. FTP client"}, - {"LMIGuardian.exe" , "LogMeIn Reporter"}, - {"LogMeInSystray.exe" , "LogMeIn System Tray"}, - {"RaMaint.exe" , "LogMeIn maintenance sevice"}, - {"mmc.exe" , "Microsoft Management Console"}, - {"putty.exe" , "Putty SSH client"}, - {"pscp.exe" , "Putty SCP client"}, - {"psftp.exe" , "Putty SFTP client"}, - {"puttytel.exe" , "Putty Telnet client"}, - {"plink.exe" , "Putty CLI client"}, - {"pageant.exe" , "Putty SSH auth agent"}, - {"kitty.exe" , "Kitty SSH client"}, - {"telnet.exe" , "Misc. Telnet client"}, - {"SecureCRT.exe" , "SecureCRT SSH/Telnet client"}, - {"TeamViewer.exe" , "TeamViewer"}, - {"tv_x64.exe" , "TeamViewer x64 remote control"}, - {"tv_w32.exe" , "TeamViewer x86 remote control"}, - {"keepass.exe" , "KeePass password vault"}, - {"mstsc.exe" , "Microsoft RDP client"}, - {"vnc.exe" , "Possible VNC client"}, - {"powershell.exe" , "PowerShell host process"}, - {"cmd.exe" , "Command Prompt"}, - }; - - [DllImport("advapi32.dll", SetLastError = true)] - private static extern bool OpenProcessToken(IntPtr ProcessHandle, uint DesiredAccess, out IntPtr TokenHandle); - [DllImport("kernel32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool CloseHandle(IntPtr hObject); - private static string GetProcU(Process p) - { - IntPtr pHandle = IntPtr.Zero; - try - { - OpenProcessToken(p.Handle, 8, out pHandle); - WindowsIdentity WI = new WindowsIdentity(pHandle); - String uSEr = WI.Name; - return uSEr.Contains(@"\") ? uSEr.Substring(uSEr.IndexOf(@"\") + 1) : uSEr; - } - catch - { - return null; - } - finally - { - if (pHandle != IntPtr.Zero) - { - CloseHandle(pHandle); - } - } - } - - - // - - // TODO: check out https://github.com/harleyQu1nn/AggressorScripts/blob/master/ProcessColor.cna#L10 - public static List> GetProcInfo() - { - List> f_results = new List>(); - try - { - var wmiQueRyStr = "SELECT ProcessId, ExecutablePath, CommandLine FROM Win32_Process"; - using (var srcher = new ManagementObjectSearcher(wmiQueRyStr)) - using (var reslts = srcher.Get()) - { - var queRy = from p in Process.GetProcesses() - join mo in reslts.Cast() - on p.Id equals (int)(uint)mo["ProcessId"] - select new - { - Proc = p, - Pth = (string)mo["ExecutablePath"], - CommLine = (string)mo["CommandLine"], - Owner = GetProcU(p), //Needed inside the next foreach - }; - - foreach (var itm in queRy) - { - if (itm.Pth != null) - { - string companyName = ""; - string isDotNet = ""; - try - { - FileVersionInfo myFileVerInfo = FileVersionInfo.GetVersionInfo(itm.Pth); - //compName = myFileVerInfo.CompanyName; - isDotNet = MyUtils.CheckIfDotNet(itm.Pth) ? "isDotNet" : ""; - } - catch - { - // Not enough privileges - } - if ((String.IsNullOrEmpty(companyName)) || (!Regex.IsMatch(companyName, @"^Microsoft.*", RegexOptions.IgnoreCase))) - { - Dictionary to_add = new Dictionary(); - to_add["Name"] = itm.Proc.ProcessName; - to_add["ProcessID"] = itm.Proc.Id.ToString(); - to_add["ExecutablePath"] = itm.Pth; - to_add["Product"] = companyName; - to_add["Owner"] = itm.Owner == null ? "" : itm.Owner; - to_add["isDotNet"] = isDotNet; - to_add["CommandLine"] = itm.CommLine; - f_results.Add(to_add); - } - } - } - } - } - catch (Exception ex) - { - Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); - } - return f_results; - } - } -} +using System.Collections.Generic; + +namespace winPEAS.ProcessInfo +{ + static class DefensiveProcesses + { + public static Dictionary Definitions = new Dictionary() + { + {"mcshield.exe" , "McAfee AV"}, + {"windefend.exe" , "Windows Defender AV"}, + {"MSASCui.exe" , "Windows Defender AV"}, + {"MSASCuiL.exe" , "Windows Defender AV"}, + {"msmpeng.exe" , "Windows Defender AV"}, + {"msmpsvc.exe" , "Windows Defender AV"}, + {"WRSA.exe" , "WebRoot AV"}, + {"savservice.exe" , "Sophos AV"}, + {"TMCCSF.exe" , "Trend Micro AV"}, + {"symantec antivirus.exe" , "Symantec AV"}, + {"mbae.exe" , "MalwareBytes Anti-Exploit"}, + {"parity.exe" , "Bit9 application whitelisting"}, + {"cb.exe" , "Carbon Black behavioral analysis"}, + {"bds-vision.exe" , "BDS Vision behavioral analysis"}, + {"Triumfant.exe" , "Triumfant behavioral analysis"}, + {"CSFalcon.exe" , "CrowdStrike Falcon EDR"}, + {"ossec.exe" , "OSSEC intrusion detection"}, + {"TmPfw.exe" , "Trend Micro firewall"}, + {"dgagent.exe" , "Verdasys Digital Guardian DLP"}, + {"kvoop.exe" , " DLP process" }, + {"AAWTray.exe" , ""}, + {"ackwin32.exe" , ""}, + {"Ad-Aware.exe" , ""}, + {"adaware.exe" , ""}, + {"advxdwin.exe" , ""}, + {"agentsvr.exe" , ""}, + {"agentw.exe" , ""}, + {"alertsvc.exe" , ""}, + {"alevir.exe" , ""}, + {"alogserv.exe" , ""}, + {"amon9x.exe" , ""}, + {"anti-trojan.exe" , ""}, + {"antivirus.exe" , ""}, + {"ants.exe" , ""}, + {"apimonitor.exe" , ""}, + {"aplica32.exe" , ""}, + {"apvxdwin.exe" , ""}, + {"arr.exe" , ""}, + {"atcon.exe" , ""}, + {"atguard.exe" , ""}, + {"atro55en.exe" , ""}, + {"atupdater.exe" , ""}, + {"atwatch.exe" , ""}, + {"au.exe" , ""}, + {"aupdate.exe" , ""}, + {"auto-protect.nav80try.exe", ""}, + {"autodown.exe" , ""}, + {"autoruns.exe" , ""}, + {"autorunsc.exe" , ""}, + {"autotrace.exe" , ""}, + {"autoupdate.exe" , ""}, + {"avconsol.exe" , ""}, + {"ave32.exe" , ""}, + {"avgcc32.exe" , ""}, + {"avgctrl.exe" , ""}, + {"avgemc.exe" , ""}, + {"avgnt.exe" , ""}, + {"avgrsx.exe" , ""}, + {"avgserv.exe" , ""}, + {"avgserv9.exe" , ""}, + {"avguard.exe" , ""}, + {"avgwdsvc.exe" , ""}, + {"avgui.exe" , ""}, + {"avgw.exe" , ""}, + {"avkpop.exe" , ""}, + {"avkserv.exe" , ""}, + {"avkservice.exe" , ""}, + {"avkwctl9.exe" , ""}, + {"avltmain.exe" , ""}, + {"avnt.exe" , ""}, + {"avp.exe" , ""}, + {"avp32.exe" , ""}, + {"avpcc.exe" , ""}, + {"avpdos32.exe" , ""}, + {"avpm.exe" , ""}, + {"avptc32.exe" , ""}, + {"avpupd.exe" , ""}, + {"avsched32.exe" , ""}, + {"avsynmgr.exe" , ""}, + {"avwin.exe" , ""}, + {"avwin95.exe" , ""}, + {"avwinnt.exe" , ""}, + {"avwupd.exe" , ""}, + {"avwupd32.exe" , ""}, + {"avwupsrv.exe" , ""}, + {"avxmonitor9x.exe" , ""}, + {"avxmonitornt.exe" , ""}, + {"avxquar.exe" , ""}, + {"backweb.exe" , ""}, + {"bargains.exe" , ""}, + {"bd_professional.exe" , ""}, + {"beagle.exe" , ""}, + {"belt.exe" , ""}, + {"bidef.exe" , ""}, + {"bidserver.exe" , ""}, + {"bipcp.exe" , ""}, + {"bipcpevalsetup.exe" , ""}, + {"bisp.exe" , ""}, + {"blackd.exe" , ""}, + {"blackice.exe" , ""}, + {"blink.exe" , ""}, + {"blss.exe" , ""}, + {"bootconf.exe" , ""}, + {"bootwarn.exe" , ""}, + {"borg2.exe" , ""}, + {"bpc.exe" , ""}, + {"brasil.exe" , ""}, + {"bs120.exe" , ""}, + {"bundle.exe" , ""}, + {"bvt.exe" , ""}, + {"ccapp.exe" , ""}, + {"ccevtmgr.exe" , ""}, + {"ccpxysvc.exe" , ""}, + {"ccSvcHst.exe" , ""}, + {"cdp.exe" , ""}, + {"cfd.exe" , ""}, + {"cfgwiz.exe" , ""}, + {"cfiadmin.exe" , ""}, + {"cfiaudit.exe" , ""}, + {"cfinet.exe" , ""}, + {"cfinet32.exe" , ""}, + {"claw95.exe" , ""}, + {"claw95cf.exe" , ""}, + {"clean.exe" , ""}, + {"cleaner.exe" , ""}, + {"cleaner3.exe" , ""}, + {"cleanpc.exe" , ""}, + {"cleanup.exe" , ""}, + {"click.exe" , ""}, + {"cmdagent.exe" , ""}, + {"cmesys.exe" , ""}, + {"cmgrdian.exe" , ""}, + {"cmon016.exe" , ""}, + {"connectionmonitor.exe" , ""}, + {"cpd.exe" , ""}, + {"cpf9x206.exe" , ""}, + {"cpfnt206.exe" , ""}, + {"ctrl.exe" , ""}, + {"cv.exe" , ""}, + {"cwnb181.exe" , ""}, + {"cwntdwmo.exe" , ""}, + {"CylanceUI.exe" , ""}, + {"CyProtect.exe" , ""}, + {"CyUpdate.exe" , ""}, + {"cyserver.exe" , ""}, + {"cytray.exe" , ""}, + {"CyveraService.exe" , ""}, + {"datemanager.exe" , ""}, + {"dcomx.exe" , ""}, + {"defalert.exe" , ""}, + {"defscangui.exe" , ""}, + {"defwatch.exe" , ""}, + {"deputy.exe" , ""}, + {"divx.exe" , ""}, + {"dgprompt.exe" , ""}, + {"DgService.exe" , ""}, + {"dllcache.exe" , ""}, + {"dllreg.exe" , ""}, + {"doors.exe" , ""}, + {"dpf.exe" , ""}, + {"dpfsetup.exe" , ""}, + {"dpps2.exe" , ""}, + {"drwatson.exe" , ""}, + {"drweb32.exe" , ""}, + {"drwebupw.exe" , ""}, + {"dssagent.exe" , ""}, + {"dumpcap.exe" , ""}, + {"dvp95.exe" , ""}, + {"dvp95_0.exe" , ""}, + {"ecengine.exe" , ""}, + {"efpeadm.exe" , ""}, + {"egui.exe" , ""}, + {"ekrn.exe" , ""}, + {"emet_agent.exe" , ""}, + {"emet_service.exe" , ""}, + {"emsw.exe" , ""}, + {"engineserver.exe" , ""}, + {"ent.exe" , ""}, + {"esafe.exe" , ""}, + {"escanhnt.exe" , ""}, + {"escanv95.exe" , ""}, + {"espwatch.exe" , ""}, + {"ethereal.exe" , ""}, + {"etrustcipe.exe" , ""}, + {"evpn.exe" , ""}, + {"exantivirus-cnet.exe" , ""}, + {"exe.avxw.exe" , ""}, + {"expert.exe" , ""}, + {"explore.exe" , ""}, + {"f-agnt95.exe" , ""}, + {"f-prot.exe" , ""}, + {"f-prot95.exe" , ""}, + {"f-stopw.exe" , ""}, + {"fameh32.exe" , ""}, + {"fast.exe" , ""}, + {"fch32.exe" , ""}, + {"fcagswd.exe" , "McAfee DLP Agent"}, + {"fcags.exe" , "McAfee DLP Agent"}, + {"fih32.exe" , ""}, + {"findviru.exe" , ""}, + {"firesvc.exe" , "McAfee Host Intrusion Prevention"}, + {"firetray.exe" , ""}, + {"firewall.exe" , ""}, + {"fnrb32.exe" , ""}, + {"fp-win.exe" , ""}, + {"fp-win_trial.exe" , ""}, + {"fprot.exe" , ""}, + {"frameworkservice.exe" , ""}, + {"frminst.exe" , ""}, + {"frw.exe" , ""}, + {"fsaa.exe" , ""}, + {"fsav.exe" , ""}, + {"fsav32.exe" , ""}, + {"fsav530stbyb.exe" , ""}, + {"fsav530wtbyb.exe" , ""}, + {"fsav95.exe" , ""}, + {"fsgk32.exe" , ""}, + {"fsm32.exe" , ""}, + {"fsma32.exe" , ""}, + {"fsmb32.exe" , ""}, + {"gator.exe" , ""}, + {"gbmenu.exe" , ""}, + {"gbpoll.exe" , ""}, + {"generics.exe" , ""}, + {"gmt.exe" , ""}, + {"guard.exe" , ""}, + {"guarddog.exe" , ""}, + {"hacktracersetup.exe" , ""}, + {"hbinst.exe" , ""}, + {"hbsrv.exe" , ""}, + {"HijackThis.exe" , ""}, + {"hipsvc.exe" , ""}, + {"HipMgmt.exe" , "McAfee Host Intrusion Protection"}, + {"hotactio.exe" , ""}, + {"hotpatch.exe" , ""}, + {"htlog.exe" , ""}, + {"htpatch.exe" , ""}, + {"hwpe.exe" , ""}, + {"hxdl.exe" , ""}, + {"hxiul.exe" , ""}, + {"iamapp.exe" , ""}, + {"iamserv.exe" , ""}, + {"iamstats.exe" , ""}, + {"ibmasn.exe" , ""}, + {"ibmavsp.exe" , ""}, + {"icload95.exe" , ""}, + {"icloadnt.exe" , ""}, + {"icmon.exe" , ""}, + {"icsupp95.exe" , ""}, + {"icsuppnt.exe" , ""}, + {"idle.exe" , ""}, + {"iedll.exe" , ""}, + {"iedriver.exe" , ""}, + {"iface.exe" , ""}, + {"ifw2000.exe" , ""}, + {"inetlnfo.exe" , ""}, + {"infus.exe" , ""}, + {"infwin.exe" , ""}, + {"init.exe" , ""}, + {"intdel.exe" , ""}, + {"intren.exe" , ""}, + {"iomon98.exe" , ""}, + {"istsvc.exe" , ""}, + {"jammer.exe" , ""}, + {"jdbgmrg.exe" , ""}, + {"jedi.exe" , ""}, + {"kavlite40eng.exe" , ""}, + {"kavpers40eng.exe" , ""}, + {"kavpf.exe" , ""}, + {"kazza.exe" , ""}, + {"keenvalue.exe" , ""}, + {"kerio-pf-213-en-win.exe" , ""}, + {"kerio-wrl-421-en-win.exe" , ""}, + {"kerio-wrp-421-en-win.exe" , ""}, + {"kernel32.exe" , ""}, + {"KeyPass.exe" , ""}, + {"killprocesssetup161.exe" , ""}, + {"launcher.exe" , ""}, + {"ldnetmon.exe" , ""}, + {"ldpro.exe" , ""}, + {"ldpromenu.exe" , ""}, + {"ldscan.exe" , ""}, + {"lnetinfo.exe" , ""}, + {"loader.exe" , ""}, + {"localnet.exe" , ""}, + {"lockdown.exe" , ""}, + {"lockdown2000.exe" , ""}, + {"lookout.exe" , ""}, + {"lordpe.exe" , ""}, + {"lsetup.exe" , ""}, + {"luall.exe" , ""}, + {"luau.exe" , ""}, + {"lucomserver.exe" , ""}, + {"luinit.exe" , ""}, + {"luspt.exe" , ""}, + {"mapisvc32.exe" , ""}, + {"masvc.exe" , "McAfee Agent"}, + {"mbamservice.exe" , ""}, + {"mcafeefire.exe" , ""}, + {"mcagent.exe" , ""}, + {"mcmnhdlr.exe" , ""}, + {"mcscript.exe" , ""}, + {"mcscript_inuse.exe" , ""}, + {"mctool.exe" , ""}, + {"mctray.exe" , ""}, + {"mcupdate.exe" , ""}, + {"mcvsrte.exe" , ""}, + {"mcvsshld.exe" , ""}, + {"md.exe" , ""}, + {"mfeann.exe" , "McAfee VirusScan Enterprise"}, + {"mfemactl.exe" , "McAfee VirusScan Enterprise"}, + {"mfevtps.exe" , ""}, + {"mfin32.exe" , ""}, + {"mfw2en.exe" , ""}, + {"mfweng3.02d30.exe" , ""}, + {"mgavrtcl.exe" , ""}, + {"mgavrte.exe" , ""}, + {"mghtml.exe" , ""}, + {"mgui.exe" , ""}, + {"minilog.exe" , ""}, + {"minionhost.exe" , ""}, + {"mmod.exe" , ""}, + {"monitor.exe" , ""}, + {"moolive.exe" , ""}, + {"mostat.exe" , ""}, + {"mpfagent.exe" , ""}, + {"mpfservice.exe" , ""}, + {"mpftray.exe" , ""}, + {"mrflux.exe" , ""}, + {"msapp.exe" , ""}, + {"msbb.exe" , ""}, + {"msblast.exe" , ""}, + {"mscache.exe" , ""}, + {"msccn32.exe" , ""}, + {"mscman.exe" , ""}, + {"msconfig.exe" , ""}, + {"msdm.exe" , ""}, + {"msdos.exe" , ""}, + {"msiexec16.exe" , ""}, + {"msinfo32.exe" , ""}, + {"mslaugh.exe" , ""}, + {"msmgt.exe" , ""}, + {"msmsgri32.exe" , ""}, + {"MsSense.exe" , "Microsoft Defender ATP"}, + {"mssmmc32.exe" , ""}, + {"mssys.exe" , ""}, + {"msvxd.exe" , ""}, + {"mu0311ad.exe" , ""}, + {"mwatch.exe" , ""}, + {"n32scanw.exe" , ""}, + {"naprdmgr.exe" , ""}, + {"nav.exe" , ""}, + {"navap.navapsvc.exe" , ""}, + {"navapsvc.exe" , ""}, + {"navapw32.exe" , ""}, + {"navdx.exe" , ""}, + {"navlu32.exe" , ""}, + {"navnt.exe" , ""}, + {"navstub.exe" , ""}, + {"navw32.exe" , ""}, + {"navwnt.exe" , ""}, + {"nc2000.exe" , ""}, + {"ncinst4.exe" , ""}, + {"ndd32.exe" , ""}, + {"neomonitor.exe" , ""}, + {"neowatchlog.exe" , ""}, + {"netarmor.exe" , ""}, + {"netd32.exe" , ""}, + {"netinfo.exe" , ""}, + {"netmon.exe" , ""}, + {"netscanpro.exe" , ""}, + {"netspyhunter-1.2.exe" , ""}, + {"netstat.exe" , ""}, + {"netutils.exe" , ""}, + {"nisserv.exe" , ""}, + {"nisum.exe" , ""}, + {"nmain.exe" , ""}, + {"nod32.exe" , ""}, + {"normist.exe" , ""}, + {"norton_internet_secu_3.0_407.exe" , ""}, + {"notstart.exe" , ""}, + {"npf40_tw_98_nt_me_2k.exe" , ""}, + {"npfmessenger.exe" , ""}, + {"nprotect.exe" , ""}, + {"npscheck.exe" , ""}, + {"npssvc.exe" , ""}, + {"nsched32.exe" , ""}, + {"nssys32.exe" , ""}, + {"nstask32.exe" , ""}, + {"nsupdate.exe" , ""}, + {"nt.exe" , ""}, + {"ntrtscan.exe" , ""}, + {"ntvdm.exe" , ""}, + {"ntxconfig.exe" , ""}, + {"nui.exe" , ""}, + {"nupgrade.exe" , ""}, + {"nvarch16.exe" , ""}, + {"nvc95.exe" , ""}, + {"nvsvc32.exe" , ""}, + {"nwinst4.exe" , ""}, + {"nwservice.exe" , ""}, + {"nwtool16.exe" , ""}, + {"nxlog.exe" , ""}, + {"ollydbg.exe" , ""}, + {"onsrvr.exe" , ""}, + {"optimize.exe" , ""}, + {"ostronet.exe" , ""}, + {"osqueryd.exe" , ""}, + {"otfix.exe" , ""}, + {"outpost.exe" , ""}, + {"outpostinstall.exe" , ""}, + {"outpostproinstall.exe" , ""}, + {"padmin.exe" , ""}, + {"panixk.exe" , ""}, + {"patch.exe" , ""}, + {"pavcl.exe" , ""}, + {"pavproxy.exe" , ""}, + {"pavsched.exe" , ""}, + {"pavw.exe" , ""}, + {"pccwin98.exe" , ""}, + {"pcfwallicon.exe" , ""}, + {"pcip10117_0.exe" , ""}, + {"pcscan.exe" , ""}, + {"pdsetup.exe" , ""}, + {"periscope.exe" , ""}, + {"persfw.exe" , ""}, + {"perswf.exe" , ""}, + {"pf2.exe" , ""}, + {"pfwadmin.exe" , ""}, + {"pgmonitr.exe" , ""}, + {"pingscan.exe" , ""}, + {"platin.exe" , ""}, + {"pop3trap.exe" , ""}, + {"poproxy.exe" , ""}, + {"popscan.exe" , ""}, + {"portdetective.exe" , ""}, + {"portmonitor.exe" , ""}, + {"powerscan.exe" , ""}, + {"ppinupdt.exe" , ""}, + {"pptbc.exe" , ""}, + {"ppvstop.exe" , ""}, + {"prizesurfer.exe" , ""}, + {"prmt.exe" , ""}, + {"prmvr.exe" , ""}, + {"procdump.exe" , ""}, + {"processmonitor.exe" , ""}, + {"procexp.exe" , ""}, + {"procexp64.exe" , ""}, + {"procexplorerv1.0.exe" , ""}, + {"procmon.exe" , ""}, + {"programauditor.exe" , ""}, + {"proport.exe" , ""}, + {"protectx.exe" , ""}, + {"pspf.exe" , ""}, + {"purge.exe" , ""}, + {"qconsole.exe" , ""}, + {"qserver.exe" , ""}, + {"rapapp.exe" , ""}, + {"rav7.exe" , ""}, + {"rav7win.exe" , ""}, + {"rav8win32eng.exe" , ""}, + {"ray.exe" , ""}, + {"rb32.exe" , ""}, + {"rcsync.exe" , ""}, + {"realmon.exe" , ""}, + {"reged.exe" , ""}, + {"regedit.exe" , ""}, + {"regedt32.exe" , ""}, + {"rescue.exe" , ""}, + {"rescue32.exe" , ""}, + {"rrguard.exe" , ""}, + {"rtvscan.exe" , ""}, + {"rtvscn95.exe" , ""}, + {"rulaunch.exe" , ""}, + {"run32dll.exe" , ""}, + {"rundll.exe" , ""}, + {"rundll16.exe" , ""}, + {"ruxdll32.exe" , ""}, + {"safeweb.exe" , ""}, + {"sahagent.exescan32.exe" , ""}, + {"save.exe" , ""}, + {"savenow.exe" , ""}, + {"sbserv.exe" , ""}, + {"scam32.exe" , ""}, + {"scan32.exe" , ""}, + {"scan95.exe" , ""}, + {"scanpm.exe" , ""}, + {"scrscan.exe" , ""}, + {"SentinelOne.exe" , ""}, + {"serv95.exe" , ""}, + {"setupvameeval.exe" , ""}, + {"setup_flowprotector_us.exe", ""}, + {"sfc.exe" , ""}, + {"sgssfw32.exe" , ""}, + {"sh.exe" , ""}, + {"shellspyinstall.exe" , ""}, + {"shn.exe" , ""}, + {"showbehind.exe" , ""}, + {"shstat.exe" , "McAfee VirusScan Enterprise"}, + {"SISIDSService.exe" , ""}, + {"SISIPSUtil.exe" , ""}, + {"smc.exe" , ""}, + {"sms.exe" , ""}, + {"smss32.exe" , ""}, + {"soap.exe" , ""}, + {"sofi.exe" , ""}, + {"sperm.exe" , ""}, + {"splunk.exe" , "Splunk"}, + {"splunkd.exe" , "Splunk"}, + {"splunk-admon.exe" , "Splunk"}, + {"splunk-powershell.exe" , "Splunk"}, + {"splunk-winevtlog.exe" , "Splunk"}, + {"spf.exe" , ""}, + {"sphinx.exe" , ""}, + {"spoler.exe" , ""}, + {"spoolcv.exe" , ""}, + {"spoolsv32.exe" , ""}, + {"spyxx.exe" , ""}, + {"srexe.exe" , ""}, + {"srng.exe" , ""}, + {"ss3edit.exe" , ""}, + {"ssgrate.exe" , ""}, + {"ssg_4104.exe" , ""}, + {"st2.exe" , ""}, + {"start.exe" , ""}, + {"stcloader.exe" , ""}, + {"supftrl.exe" , ""}, + {"support.exe" , ""}, + {"supporter5.exe" , ""}, + {"svchostc.exe" , ""}, + {"svchosts.exe" , ""}, + {"sweep95.exe" , ""}, + {"sweepnet.sweepsrv.sys.swnetsup.exe", ""}, + {"symproxysvc.exe" , ""}, + {"symtray.exe" , ""}, + {"sysedit.exe" , ""}, + {"sysmon.exe" , "Sysinternals Sysmon"}, + {"sysupd.exe" , ""}, + {"TaniumClient.exe" , "Tanium"}, + {"taskmg.exe" , ""}, + {"taskmo.exe" , ""}, + {"taumon.exe" , ""}, + {"tbmon.exe" , ""}, + {"tbscan.exe" , ""}, + {"tc.exe" , ""}, + {"tca.exe" , ""}, + {"tcm.exe" , ""}, + {"tcpview.exe" , ""}, + {"tds-3.exe" , ""}, + {"tds2-98.exe" , ""}, + {"tds2-nt.exe" , ""}, + {"teekids.exe" , ""}, + {"tfak.exe" , ""}, + {"tfak5.exe" , ""}, + {"tgbob.exe" , ""}, + {"titanin.exe" , ""}, + {"titaninxp.exe" , ""}, + {"tlaservice.exe" , ""}, + {"tlaworker.exe" , ""}, + {"tracert.exe" , ""}, + {"trickler.exe" , ""}, + {"trjscan.exe" , ""}, + {"trjsetup.exe" , ""}, + {"trojantrap3.exe" , ""}, + {"tsadbot.exe" , ""}, + {"tshark.exe" , ""}, + {"tvmd.exe" , ""}, + {"tvtmd.exe" , ""}, + {"udaterui.exe" , ""}, + {"undoboot.exe" , ""}, + {"updat.exe" , ""}, + {"update.exe" , ""}, + {"updaterui.exe" , ""}, + {"upgrad.exe" , ""}, + {"utpost.exe" , ""}, + {"vbcmserv.exe" , ""}, + {"vbcons.exe" , ""}, + {"vbust.exe" , ""}, + {"vbwin9x.exe" , ""}, + {"vbwinntw.exe" , ""}, + {"vcsetup.exe" , ""}, + {"vet32.exe" , ""}, + {"vet95.exe" , ""}, + {"vettray.exe" , ""}, + {"vfsetup.exe" , ""}, + {"vir-help.exe" , ""}, + {"virusmdpersonalfirewall.exe", ""}, + {"vnlan300.exe" , ""}, + {"vnpc3000.exe" , ""}, + {"vpc32.exe" , ""}, + {"vpc42.exe" , ""}, + {"vpfw30s.exe" , ""}, + {"vptray.exe" , ""}, + {"vscan40.exe" , ""}, + {"vscenu6.02d30.exe" , ""}, + {"vsched.exe" , ""}, + {"vsecomr.exe" , ""}, + {"vshwin32.exe" , ""}, + {"vsisetup.exe" , ""}, + {"vsmain.exe" , ""}, + {"vsmon.exe" , ""}, + {"vsstat.exe" , ""}, + {"vstskmgr.exe" , "McAfee VirusScan Enterprise"}, + {"vswin9xe.exe" , ""}, + {"vswinntse.exe" , ""}, + {"vswinperse.exe" , ""}, + {"w32dsm89.exe" , ""}, + {"w9x.exe" , ""}, + {"watchdog.exe" , ""}, + {"webdav.exe" , ""}, + {"webscanx.exe" , ""}, + {"webtrap.exe" , ""}, + {"wfindv32.exe" , ""}, + {"whoswatchingme.exe" , ""}, + {"wimmun32.exe" , ""}, + {"win-bugsfix.exe" , ""}, + {"win32.exe" , ""}, + {"win32us.exe" , ""}, + {"winactive.exe" , ""}, + {"window.exe" , ""}, + {"windows.exe" , ""}, + {"wininetd.exe" , ""}, + {"wininitx.exe" , ""}, + {"winlogin.exe" , ""}, + {"winmain.exe" , ""}, + {"winnet.exe" , ""}, + {"winppr32.exe" , ""}, + {"winrecon.exe" , ""}, + {"winservn.exe" , ""}, + {"winssk32.exe" , ""}, + {"winstart.exe" , ""}, + {"winstart001.exe" , ""}, + {"wintsk32.exe" , ""}, + {"winupdate.exe" , ""}, + {"wireshark.exe" , ""}, + {"wkufind.exe" , ""}, + {"wnad.exe" , ""}, + {"wnt.exe" , ""}, + {"wradmin.exe" , ""}, + {"wrctrl.exe" , ""}, + {"wsbgate.exe" , ""}, + {"wupdater.exe" , ""}, + {"wupdt.exe" , ""}, + {"wyvernworksfirewall.exe" , ""}, + {"xagt.exe" , ""}, + {"xpf202en.exe" , ""}, + {"zapro.exe" , ""}, + {"zapsetup3001.exe" , ""}, + {"zatutor.exe" , ""}, + /*{"zonalm2601" , ""}, These names (ending in .exe) are detected by AVs + {"zonealarm" , ""}, + {"_avp32" , ""}, + {"_avpcc" , ""}, + {"rshell" , ""}, + {"_avpms" , ""}*/ + }; + + } +} diff --git a/winPEAS/winPEASexe/winPEAS/ProcessInfo/InterestingProcesses.cs b/winPEAS/winPEASexe/winPEAS/ProcessInfo/InterestingProcesses.cs new file mode 100644 index 0000000..e888a80 --- /dev/null +++ b/winPEAS/winPEASexe/winPEAS/ProcessInfo/InterestingProcesses.cs @@ -0,0 +1,34 @@ +using System.Collections.Generic; + +namespace winPEAS.ProcessInfo +{ + static class InterestingProcesses + { + public static Dictionary Definitions = new Dictionary() + { + {"CmRcService.exe" , "Configuration Manager Remote Control Service"}, + {"ftp.exe" , "Misc. FTP client"}, + {"LMIGuardian.exe" , "LogMeIn Reporter"}, + {"LogMeInSystray.exe" , "LogMeIn System Tray"}, + {"RaMaint.exe" , "LogMeIn maintenance sevice"}, + {"mmc.exe" , "Microsoft Management Console"}, + {"putty.exe" , "Putty SSH client"}, + {"pscp.exe" , "Putty SCP client"}, + {"psftp.exe" , "Putty SFTP client"}, + {"puttytel.exe" , "Putty Telnet client"}, + {"plink.exe" , "Putty CLI client"}, + {"pageant.exe" , "Putty SSH auth agent"}, + {"kitty.exe" , "Kitty SSH client"}, + {"telnet.exe" , "Misc. Telnet client"}, + {"SecureCRT.exe" , "SecureCRT SSH/Telnet client"}, + {"TeamViewer.exe" , "TeamViewer"}, + {"tv_x64.exe" , "TeamViewer x64 remote control"}, + {"tv_w32.exe" , "TeamViewer x86 remote control"}, + {"keepass.exe" , "KeePass password vault"}, + {"mstsc.exe" , "Microsoft RDP client"}, + {"vnc.exe" , "Possible VNC client"}, + {"powershell.exe" , "PowerShell host process"}, + {"cmd.exe" , "Command Prompt"}, + }; + } +} diff --git a/winPEAS/winPEASexe/winPEAS/ProcessInfo/ProcessesInfo.cs b/winPEAS/winPEASexe/winPEAS/ProcessInfo/ProcessesInfo.cs new file mode 100644 index 0000000..5af0852 --- /dev/null +++ b/winPEAS/winPEASexe/winPEAS/ProcessInfo/ProcessesInfo.cs @@ -0,0 +1,102 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Management; +using System.Runtime.InteropServices; +using System.Security.Principal; +using System.Text.RegularExpressions; + +namespace winPEAS +{ + class ProcessesInfo + { + [DllImport("advapi32.dll", SetLastError = true)] + private static extern bool OpenProcessToken(IntPtr ProcessHandle, uint DesiredAccess, out IntPtr TokenHandle); + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool CloseHandle(IntPtr hObject); + private static string GetProcU(Process p) + { + IntPtr pHandle = IntPtr.Zero; + try + { + OpenProcessToken(p.Handle, 8, out pHandle); + WindowsIdentity WI = new WindowsIdentity(pHandle); + String uSEr = WI.Name; + return uSEr.Contains(@"\") ? uSEr.Substring(uSEr.IndexOf(@"\") + 1) : uSEr; + } + catch + { + return null; + } + finally + { + if (pHandle != IntPtr.Zero) + { + CloseHandle(pHandle); + } + } + } + + // TODO: check out https://github.com/harleyQu1nn/AggressorScripts/blob/master/ProcessColor.cna#L10 + public static List> GetProcInfo() + { + List> f_results = new List>(); + try + { + var wmiQueRyStr = "SELECT ProcessId, ExecutablePath, CommandLine FROM Win32_Process"; + using (var srcher = new ManagementObjectSearcher(wmiQueRyStr)) + using (var reslts = srcher.Get()) + { + var queRy = from p in Process.GetProcesses() + join mo in reslts.Cast() + on p.Id equals (int)(uint)mo["ProcessId"] + select new + { + Proc = p, + Pth = (string)mo["ExecutablePath"], + CommLine = (string)mo["CommandLine"], + Owner = GetProcU(p), //Needed inside the next foreach + }; + + foreach (var itm in queRy) + { + if (itm.Pth != null) + { + string companyName = ""; + string isDotNet = ""; + try + { + FileVersionInfo myFileVerInfo = FileVersionInfo.GetVersionInfo(itm.Pth); + //compName = myFileVerInfo.CompanyName; + isDotNet = MyUtils.CheckIfDotNet(itm.Pth) ? "isDotNet" : ""; + } + catch + { + // Not enough privileges + } + if ((String.IsNullOrEmpty(companyName)) || (!Regex.IsMatch(companyName, @"^Microsoft.*", RegexOptions.IgnoreCase))) + { + Dictionary to_add = new Dictionary(); + to_add["Name"] = itm.Proc.ProcessName; + to_add["ProcessID"] = itm.Proc.Id.ToString(); + to_add["ExecutablePath"] = itm.Pth; + to_add["Product"] = companyName; + to_add["Owner"] = itm.Owner == null ? "" : itm.Owner; + to_add["isDotNet"] = isDotNet; + to_add["CommandLine"] = itm.CommLine; + f_results.Add(to_add); + } + } + } + } + } + catch (Exception ex) + { + Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); + } + return f_results; + } + } +} diff --git a/winPEAS/winPEASexe/winPEAS/Program.cs b/winPEAS/winPEASexe/winPEAS/Program.cs index 8dd3374..5cfee25 100755 --- a/winPEAS/winPEASexe/winPEAS/Program.cs +++ b/winPEAS/winPEASexe/winPEAS/Program.cs @@ -5,6 +5,13 @@ using System.Management; using System.Text.RegularExpressions; using System.Security.Principal; using System.Diagnostics; +using System.Xml; +using winPEAS.KnownFileCreds; +using winPEAS.KnownFileCreds.Kerberos; +using winPEAS.KnownFileCreds.Vault; +using winPEAS.NativeWifiApi; +using winPEAS.ProcessInfo; +using winPEAS.Utils; namespace winPEAS { @@ -108,7 +115,7 @@ namespace winPEAS try { Beaprint.GrayPrint(" - Creating active users list..."); - paint_activeUsers = String.Join("|", UserInfo.GetMachineUsers(true, false, false, false, false)); + paint_activeUsers = string.Join("|", UserInfo.GetMachineUsers(true, false, false, false, false)); paint_activeUsers_no_Administrator = paint_activeUsers.Replace("|Administrator", "").Replace("Administrator|", "").Replace("Administrator", ""); } catch (Exception ex) @@ -119,7 +126,7 @@ namespace winPEAS try { Beaprint.GrayPrint(" - Creating disabled users list..."); - paint_disabledUsers = String.Join("|", UserInfo.GetMachineUsers(false, true, false, false, false)); + paint_disabledUsers = string.Join("|", UserInfo.GetMachineUsers(false, true, false, false, false)); paint_disabledUsers_no_Administrator = paint_disabledUsers.Replace("|Administrator", "").Replace("Administrator|", "").Replace("Administrator", ""); } catch (Exception ex) @@ -127,12 +134,12 @@ namespace winPEAS Beaprint.GrayPrint("Error while creating disabled users list: " + ex); } - //paint_lockoutUsers = String.Join("|", UserInfo.GetMachineUsers(false, false, true, false, false)); + //paint_lockoutUsers = string.Join("|", UserInfo.GetMachineUsers(false, false, true, false, false)); try { Beaprint.GrayPrint(" - Admin users list..."); - paint_adminUsers = String.Join("|", UserInfo.GetMachineUsers(false, false, false, true, false)); + paint_adminUsers = string.Join("|", UserInfo.GetMachineUsers(false, false, false, true, false)); } catch (Exception ex) { @@ -144,7 +151,7 @@ namespace winPEAS { try { - if (MyUtils.GetRegValue("HKCU", "CONSOLE", "VirtualTerminalLevel") == "" && MyUtils.GetRegValue("HKCU", "CONSOLE", "VirtualTerminalLevel") == "") + if (RegistryHelper.GetRegValue("HKCU", "CONSOLE", "VirtualTerminalLevel") == "" && RegistryHelper.GetRegValue("HKCU", "CONSOLE", "VirtualTerminalLevel") == "") System.Console.WriteLine(@"ANSI color bit for Windows is not set. If you are execcuting this from a Windows terminal inside the host you should run 'REG ADD HKCU\Console /v VirtualTerminalLevel /t REG_DWORD /d 1' and then start a new CMD"); } catch(Exception ex) @@ -186,7 +193,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -205,7 +212,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -235,7 +242,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -250,7 +257,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -265,7 +272,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -284,7 +291,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -292,7 +299,7 @@ namespace winPEAS { Beaprint.MainPrint("Wdigest"); Beaprint.LinkPrint("https://book.hacktricks.xyz/windows/stealing-credentials/credentials-protections#wdigest", "If enabled, plain-text crds could be stored in LSASS"); - string useLogonCredential = MyUtils.GetRegValue("HKLM", @"SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest", "UseLogonCredential"); + string useLogonCredential = RegistryHelper.GetRegValue("HKLM", @"SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest", "UseLogonCredential"); if (useLogonCredential == "1") Beaprint.BadPrint(" Wdigest is active"); else @@ -303,7 +310,7 @@ namespace winPEAS { Beaprint.MainPrint("LSA Protection"); Beaprint.LinkPrint("https://book.hacktricks.xyz/windows/stealing-credentials/credentials-protections#lsa-protection", "If enabled, a driver is needed to read LSASS memory (If Secure Boot or UEFI, RunAsPPL cannot be disabled by deleting the registry key)"); - string useLogonCredential = MyUtils.GetRegValue("HKLM", @"SYSTEM\CurrentControlSet\Control\LSA", "RunAsPPL"); + string useLogonCredential = RegistryHelper.GetRegValue("HKLM", @"SYSTEM\CurrentControlSet\Control\LSA", "RunAsPPL"); if (useLogonCredential == "1") Beaprint.GoodPrint(" LSA Protection is active"); else @@ -314,7 +321,7 @@ namespace winPEAS { Beaprint.MainPrint("Credentials Guard"); Beaprint.LinkPrint("https://book.hacktricks.xyz/windows/stealing-credentials/credentials-protections#credential-guard", "If enabled, a driver is needed to read LSASS memory"); - string lsaCfgFlags = MyUtils.GetRegValue("HKLM", @"System\CurrentControlSet\Control\LSA", "LsaCfgFlags"); + string lsaCfgFlags = RegistryHelper.GetRegValue("HKLM", @"System\CurrentControlSet\Control\LSA", "LsaCfgFlags"); if (lsaCfgFlags == "1") { System.Console.WriteLine(" Please, note that this only checks the LsaCfgFlags key value. This is not enough to enable Credentials Guard (but it's a strong indicator)."); @@ -333,8 +340,8 @@ namespace winPEAS { Beaprint.MainPrint("Cached Creds"); Beaprint.LinkPrint("https://book.hacktricks.xyz/windows/stealing-credentials/credentials-protections#cached-credentials", "If > 0, credentials will be cached in the registry and accessible by SYSTEM user"); - string cachedlogonscount = MyUtils.GetRegValue("HKLM", @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon", "CACHEDLOGONSCOUNT"); - if (!String.IsNullOrEmpty(cachedlogonscount)) + string cachedlogonscount = RegistryHelper.GetRegValue("HKLM", @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon", "CACHEDLOGONSCOUNT"); + if (!string.IsNullOrEmpty(cachedlogonscount)) { int clc = Int16.Parse(cachedlogonscount); if (clc > 0) @@ -359,7 +366,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -378,7 +385,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -401,7 +408,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -418,15 +425,15 @@ namespace winPEAS foreach (Dictionary drive in SystemInfo.GetDrivesInfo()) { - string drive_permissions = String.Join(", ", MyUtils.GetPermissionsFolder(drive["Name"], currentUserSIDs)); - string dToPrint = String.Format(" {0} (Type: {1})", drive["Name"], drive["Type"]); - if (!String.IsNullOrEmpty(drive["Volume label"])) + string drive_permissions = string.Join(", ", MyUtils.GetPermissionsFolder(drive["Name"], currentUserSIDs)); + string dToPrint = string.Format(" {0} (Type: {1})", drive["Name"], drive["Type"]); + if (!string.IsNullOrEmpty(drive["Volume label"])) dToPrint += "(Volume label: "+ drive["Volume label"] + ")"; - if (!String.IsNullOrEmpty(drive["Filesystem"])) + if (!string.IsNullOrEmpty(drive["Filesystem"])) dToPrint += "(Filesystem: "+ drive["Filesystem"] + ")"; - if (!String.IsNullOrEmpty(drive["Available space"])) + if (!string.IsNullOrEmpty(drive["Available space"])) dToPrint += "(Available space: "+ (((Int64.Parse(drive["Available space"]) / 1024) / 1024) / 1024).ToString() + " GB)"; if (drive_permissions.Length > 0) @@ -437,7 +444,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -456,7 +463,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -489,7 +496,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -501,8 +508,8 @@ namespace winPEAS Beaprint.LinkPrint("https://book.hacktricks.xyz/windows/windows-local-privilege-escalation#wsus"); string path = "Software\\Policies\\Microsoft\\Windows\\WindowsUpdate"; string path2 = "Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU"; - string HKLM_WSUS = MyUtils.GetRegValue("HKLM", path, "WUServer"); - string using_HKLM_WSUS = MyUtils.GetRegValue("HKLM", path, "UseWUServer"); + string HKLM_WSUS = RegistryHelper.GetRegValue("HKLM", path, "WUServer"); + string using_HKLM_WSUS = RegistryHelper.GetRegValue("HKLM", path, "UseWUServer"); if (HKLM_WSUS.Contains("http://")) { Beaprint.BadPrint(" WSUS is using http: " + HKLM_WSUS); @@ -516,7 +523,7 @@ namespace winPEAS } else { - if (String.IsNullOrEmpty(HKLM_WSUS)) + if (string.IsNullOrEmpty(HKLM_WSUS)) Beaprint.NotFoundPrint(); else Beaprint.GoodPrint(" WSUS value: " + HKLM_WSUS); @@ -524,7 +531,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -535,8 +542,8 @@ namespace winPEAS Beaprint.MainPrint("Checking AlwaysInstallElevated"); Beaprint.LinkPrint("https://book.hacktricks.xyz/windows/windows-local-privilege-escalation#alwaysinstallelevated"); string path = "Software\\Policies\\Microsoft\\Windows\\Installer"; - string HKLM_AIE = MyUtils.GetRegValue("HKLM", path, "AlwaysInstallElevated"); - string HKCU_AIE = MyUtils.GetRegValue("HKCU", path, "AlwaysInstallElevated"); + string HKLM_AIE = RegistryHelper.GetRegValue("HKLM", path, "AlwaysInstallElevated"); + string HKCU_AIE = RegistryHelper.GetRegValue("HKCU", path, "AlwaysInstallElevated"); if (HKLM_AIE == "1") Beaprint.BadPrint(" AlwaysInstallElevated set to 1 in HKLM!"); if (HKCU_AIE == "1") @@ -546,7 +553,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -622,16 +629,16 @@ namespace winPEAS { if (g.Key == WindowsIdentity.GetCurrent().User.ToString()) continue; - currentGroupsNames.Add(String.IsNullOrEmpty(g.Value) ? g.Key : g.Value); + currentGroupsNames.Add(string.IsNullOrEmpty(g.Value) ? g.Key : g.Value); } - Beaprint.AnsiPrint(" Current groups: " + String.Join(", ", currentGroupsNames), colorsU()); + Beaprint.AnsiPrint(" Current groups: " + string.Join(", ", currentGroupsNames), colorsU()); Beaprint.PrintLineSeparator(); Beaprint.ListPrint(users_grps, colorsU()); } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -646,7 +653,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -656,7 +663,7 @@ namespace winPEAS { Beaprint.MainPrint("Clipboard text"); string clipb = UserInfo.GetClipboardText(); - if (String.IsNullOrEmpty(clipb)) + if (string.IsNullOrEmpty(clipb)) Beaprint.BadPrint(clipb); else { @@ -672,7 +679,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -687,7 +694,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -700,17 +707,17 @@ namespace winPEAS if (rdp_sessions.Count > 0) { string format = " {0,-10}{1,-15}{2,-15}{3,-25}{4,-10}{5}"; - string header = String.Format(format, "SessID", "pSessionName", "pUserName", "pDomainName", "State", "SourceIP"); + string header = string.Format(format, "SessID", "pSessionName", "pUserName", "pDomainName", "State", "SourceIP"); Beaprint.GrayPrint(header); foreach (Dictionary rdp_ses in rdp_sessions) - Beaprint.AnsiPrint(String.Format(format, rdp_ses["SessionID"], rdp_ses["pSessionName"], rdp_ses["pUserName"], rdp_ses["pDomainName"], rdp_ses["State"], rdp_ses["SourceIP"]), colorsU()); + Beaprint.AnsiPrint(string.Format(format, rdp_ses["SessionID"], rdp_ses["pSessionName"], rdp_ses["pUserName"], rdp_ses["pDomainName"], rdp_ses["State"], rdp_ses["SourceIP"]), colorsU()); } else Beaprint.NotFoundPrint(); } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -724,7 +731,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -736,7 +743,7 @@ namespace winPEAS List user_folders = UserInfo.GetUsersFolders(); foreach (string ufold in user_folders) { - string perms = String.Join(", ", MyUtils.GetPermissionsFolder(ufold, currentUserSIDs)); + string perms = string.Join(", ", MyUtils.GetPermissionsFolder(ufold, currentUserSIDs)); if (perms.Length > 0) Beaprint.BadPrint(" " + ufold + " : " + perms); else @@ -745,7 +752,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -760,14 +767,14 @@ namespace winPEAS { foreach (KeyValuePair entry in autologon) { - if (!String.IsNullOrEmpty(entry.Value)) + if (!string.IsNullOrEmpty(entry.Value)) { if (!ban) { Beaprint.BadPrint(" Some AutoLogon credentials were found!!"); ban = true; } - Beaprint.AnsiPrint(String.Format(" {0,-30}: {1}", entry.Key, entry.Value), colorsU()); + Beaprint.AnsiPrint(string.Format(" {0,-30}: {1}", entry.Key, entry.Value), colorsU()); } } if (!ban) @@ -778,7 +785,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -793,7 +800,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -833,16 +840,20 @@ namespace winPEAS { "Possible DLL Hijacking.*", Beaprint.ansi_color_bad }, }; - if (ProcessesInfo.defensiveProcesses.ContainsKey(proc_info["Name"])) + if (DefensiveProcesses.Definitions.ContainsKey(proc_info["Name"])) { - if (!String.IsNullOrEmpty(ProcessesInfo.defensiveProcesses[proc_info["Name"]].ToString())) - proc_info["Product"] = ProcessesInfo.defensiveProcesses[proc_info["Name"]].ToString(); + if (!string.IsNullOrEmpty(DefensiveProcesses.Definitions[proc_info["Name"]])) + { + proc_info["Product"] = DefensiveProcesses.Definitions[proc_info["Name"]]; + } colorsP[proc_info["Product"]] = Beaprint.ansi_color_good; } - else if (ProcessesInfo.interestingProcesses.ContainsKey(proc_info["Name"])) + else if (InterestingProcesses.Definitions.ContainsKey(proc_info["Name"])) { - if (!String.IsNullOrEmpty(ProcessesInfo.defensiveProcesses[proc_info["Name"]].ToString())) - proc_info["Product"] = ProcessesInfo.interestingProcesses[proc_info["Name"]].ToString(); + if (!string.IsNullOrEmpty(InterestingProcesses.Definitions[proc_info["Name"]].ToString())) + { + proc_info["Product"] = InterestingProcesses.Definitions[proc_info["Name"]].ToString(); + } colorsP[proc_info["Product"]] = Beaprint.ansi_color_bad; } @@ -868,13 +879,13 @@ namespace winPEAS formString += "\n "+ Beaprint.ansi_color_gray + "Command Line: {9}"; - Beaprint.AnsiPrint(String.Format(formString, proc_info["Name"], proc_info["ProcessID"], proc_info["ExecutablePath"], proc_info["Product"], proc_info["Owner"], proc_info["isDotNet"], String.Join(", ", file_rights), dir_rights.Count > 0 ? Path.GetDirectoryName(proc_info["ExecutablePath"]) : "", String.Join(", ", dir_rights), proc_info["CommandLine"]), colorsP); + Beaprint.AnsiPrint(string.Format(formString, proc_info["Name"], proc_info["ProcessID"], proc_info["ExecutablePath"], proc_info["Product"], proc_info["Owner"], proc_info["isDotNet"], string.Join(", ", file_rights), dir_rights.Count > 0 ? Path.GetDirectoryName(proc_info["ExecutablePath"]) : "", string.Join(", ", dir_rights), proc_info["CommandLine"]), colorsP); Beaprint.PrintLineSeparator(); } } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(ex.Message); } } @@ -897,7 +908,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } @@ -964,7 +975,7 @@ namespace winPEAS { service_info["PathName"].Replace("\\", "\\\\").Replace("(", "\\(").Replace(")", "\\)").Replace("]", "\\]").Replace("[", "\\[").Replace("?", "\\?").Replace("+","\\+"), (file_rights.Count > 0 || dir_rights.Count > 0 || no_quotes_and_space) ? Beaprint.ansi_color_bad : Beaprint.ansi_color_good }, }; - Beaprint.AnsiPrint(String.Format(formString, service_info["Name"], service_info["CompanyName"], service_info["DisplayName"], service_info["PathName"], service_info["StartMode"], service_info["State"], service_info["isDotNet"], "No quotes and Space detected", String.Join(", ", file_rights), dir_rights.Count > 0 ? Path.GetDirectoryName(service_info["FilteredPath"]) : "", String.Join(", ", dir_rights), service_info["Description"]), colorsS); + Beaprint.AnsiPrint(string.Format(formString, service_info["Name"], service_info["CompanyName"], service_info["DisplayName"], service_info["PathName"], service_info["StartMode"], service_info["State"], service_info["isDotNet"], "No quotes and Space detected", string.Join(", ", file_rights), dir_rights.Count > 0 ? Path.GetDirectoryName(service_info["FilteredPath"]) : "", string.Join(", ", dir_rights), service_info["Description"]), colorsS); } Beaprint.PrintLineSeparator(); @@ -972,7 +983,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -997,7 +1008,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1019,13 +1030,13 @@ namespace winPEAS else { foreach (Dictionary writeServReg in regPerms) - Beaprint.AnsiPrint(String.Format(" {0} ({1})", writeServReg["Path"], writeServReg["Permissions"]), colorsWR); + Beaprint.AnsiPrint(string.Format(" {0} ({1})", writeServReg["Path"], writeServReg["Permissions"]), colorsWR); } } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1038,7 +1049,7 @@ namespace winPEAS Dictionary path_dllhijacking = ServicesInfo.GetPathDLLHijacking(); foreach (KeyValuePair entry in path_dllhijacking) { - if (String.IsNullOrEmpty(entry.Value)) + if (string.IsNullOrEmpty(entry.Value)) Beaprint.GoodPrint(" " + entry.Key); else Beaprint.BadPrint(" (DLL Hijacking) " + entry.Key + ": " + entry.Value); @@ -1046,7 +1057,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1077,7 +1088,7 @@ namespace winPEAS if (permsFile.Count > 0) { Beaprint.BadPrint(" " + title); - Beaprint.BadPrint(" FilePermissions: " + String.Join(",", permsFile)); + Beaprint.BadPrint(" FilePermissions: " + string.Join(",", permsFile)); } else Beaprint.GoodPrint(" " + title); @@ -1085,12 +1096,12 @@ namespace winPEAS if (permsFolder.Count > 0) { Beaprint.BadPrint(" Possible DLL Hijacking, folder is writable: " + MyUtils.GetFolderFromString(title)); - Beaprint.BadPrint(" FolderPermissions: " + String.Join(",", permsFile)); + Beaprint.BadPrint(" FolderPermissions: " + string.Join(",", permsFile)); } } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1104,26 +1115,26 @@ namespace winPEAS string format = " ==> {0} ({1})"; foreach (KeyValuePair> app in InstalledAppsPerms) { - if (String.IsNullOrEmpty(app.Value.ToString())) //If empty, nothing found, is good + if (string.IsNullOrEmpty(app.Value.ToString())) //If empty, nothing found, is good Beaprint.GoodPrint(app.Key); else //Then, we need to look deeper { //Checkeamos si la carpeta (que va a existir como subvalor dentro de si misma) debe ser good - if (String.IsNullOrEmpty(app.Value[app.Key])) + if (string.IsNullOrEmpty(app.Value[app.Key])) Beaprint.GoodPrint(" " + app.Key); else { - Beaprint.BadPrint(String.Format(" {0}({1})", app.Key, app.Value[app.Key])); + Beaprint.BadPrint(string.Format(" {0}({1})", app.Key, app.Value[app.Key])); app.Value[app.Key] = ""; //So no reprinted later } //Check the rest of the values to see if we have something to print in red (permissions) foreach (KeyValuePair subfolder in app.Value) { - if (!String.IsNullOrEmpty(subfolder.Value)) - Beaprint.BadPrint(String.Format(format, subfolder.Key, subfolder.Value)); + if (!string.IsNullOrEmpty(subfolder.Value)) + Beaprint.BadPrint(string.Format(format, subfolder.Key, subfolder.Value)); } } } @@ -1139,7 +1150,7 @@ namespace winPEAS } catch { - //Beaprint.GrayPrint(String.Format("{0}",ex)); + //Beaprint.GrayPrint(string.Format("{0}",ex)); } } @@ -1160,42 +1171,42 @@ namespace winPEAS { "(Unquoted and Space detected)", Beaprint.ansi_color_bad }, { "(PATH Injection)", Beaprint.ansi_color_bad }, { "RegPerms: .*", Beaprint.ansi_color_bad }, - { (app["Folder"].Length > 0) ? app["Folder"].Replace("\\", "\\\\").Replace("(", "\\(").Replace(")", "\\)").Replace("]", "\\]").Replace("[", "\\[").Replace("?", "\\?").Replace("+","\\+") : "ouigyevb2uivydi2u3id2ddf3", !String.IsNullOrEmpty(app["interestingFolderRights"]) ? Beaprint.ansi_color_bad : Beaprint.ansi_color_good }, - { (app["File"].Length > 0) ? app["File"].Replace("\\", "\\\\").Replace("(", "\\(").Replace(")", "\\)").Replace("]", "\\]").Replace("[", "\\[").Replace("?", "\\?").Replace("+","\\+") : "adu8v298hfubibuidiy2422r", !String.IsNullOrEmpty(app["interestingFileRights"]) ? Beaprint.ansi_color_bad : Beaprint.ansi_color_good }, + { (app["Folder"].Length > 0) ? app["Folder"].Replace("\\", "\\\\").Replace("(", "\\(").Replace(")", "\\)").Replace("]", "\\]").Replace("[", "\\[").Replace("?", "\\?").Replace("+","\\+") : "ouigyevb2uivydi2u3id2ddf3", !string.IsNullOrEmpty(app["interestingFolderRights"]) ? Beaprint.ansi_color_bad : Beaprint.ansi_color_good }, + { (app["File"].Length > 0) ? app["File"].Replace("\\", "\\\\").Replace("(", "\\(").Replace(")", "\\)").Replace("]", "\\]").Replace("[", "\\[").Replace("?", "\\?").Replace("+","\\+") : "adu8v298hfubibuidiy2422r", !string.IsNullOrEmpty(app["interestingFileRights"]) ? Beaprint.ansi_color_bad : Beaprint.ansi_color_good }, { (app["Reg"].Length > 0) ? app["Reg"].Replace("\\", "\\\\").Replace("(", "\\(").Replace(")", "\\)").Replace("]", "\\]").Replace("[", "\\[").Replace("?", "\\?").Replace("+","\\+") : "o8a7eduia37ibduaunbf7a4g7ukdhk4ua", (app["RegPermissions"].Length > 0) ? Beaprint.ansi_color_bad : Beaprint.ansi_color_good }, }; string line = ""; - if (!String.IsNullOrEmpty(app["Reg"])) + if (!string.IsNullOrEmpty(app["Reg"])) line += "\n RegPath: " + app["Reg"]; if (app["RegPermissions"].Length > 0) line += "\n RegPerms: " + app["RegPermissions"]; - if (!String.IsNullOrEmpty(app["RegKey"])) + if (!string.IsNullOrEmpty(app["RegKey"])) line += "\n Key: " + app["RegKey"]; - if (!String.IsNullOrEmpty(app["Folder"])) + if (!string.IsNullOrEmpty(app["Folder"])) line += "\n Folder: " + app["Folder"]; else { - if (!String.IsNullOrEmpty(app["Reg"])) + if (!string.IsNullOrEmpty(app["Reg"])) line += "\n Folder: None (PATH Injection)"; } - if (!String.IsNullOrEmpty(app["interestingFolderRights"])) + if (!string.IsNullOrEmpty(app["interestingFolderRights"])) { line += "\n FolderPerms: " + app["interestingFolderRights"]; } string filepath_mod = app["File"].Replace("\"", "").Replace("'", ""); - if (!String.IsNullOrEmpty(app["File"])) + if (!string.IsNullOrEmpty(app["File"])) line += "\n File: " + filepath_mod; if (app["isUnquotedSpaced"].ToLower() == "true") line += " (Unquoted and Space detected)"; - if (!String.IsNullOrEmpty(app["interestingFileRights"])) + if (!string.IsNullOrEmpty(app["interestingFileRights"])) line += "\n FilePerms: " + app["interestingFileRights"]; Beaprint.AnsiPrint(line, colorsA); @@ -1204,7 +1215,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1225,9 +1236,9 @@ namespace winPEAS formString += "\n Permissions file: {3}"; if (dir_rights.Count > 0) formString += "\n Permissions folder(DLL Hijacking): {4}"; - if (!String.IsNullOrEmpty(sapp["Trigger"])) + if (!string.IsNullOrEmpty(sapp["Trigger"])) formString += "\n Trigger: {5}"; - if (String.IsNullOrEmpty(sapp["Description"])) + if (string.IsNullOrEmpty(sapp["Description"])) formString += "\n {6}"; Dictionary colorsS = new Dictionary() @@ -1235,13 +1246,13 @@ namespace winPEAS { "Permissions.*", Beaprint.ansi_color_bad }, { sapp["Action"].Replace("\\", "\\\\").Replace("(", "\\(").Replace(")", "\\)").Replace("]", "\\]").Replace("[", "\\[").Replace("?", "\\?").Replace("+","\\+"), (file_rights.Count > 0 || dir_rights.Count > 0) ? Beaprint.ansi_color_bad : Beaprint.ansi_color_good }, }; - Beaprint.AnsiPrint(String.Format(formString, sapp["Author"], sapp["Name"], sapp["Action"], String.Join(", ", file_rights), String.Join(", ", dir_rights), sapp["Trigger"], sapp["Description"]), colorsS); + Beaprint.AnsiPrint(string.Format(formString, sapp["Author"], sapp["Name"], sapp["Action"], string.Join(", ", file_rights), string.Join(", ", dir_rights), sapp["Trigger"], sapp["Description"]), colorsS); Beaprint.PrintLineSeparator(); } } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1272,7 +1283,7 @@ namespace winPEAS if (dir_rights.Count > 0) formString += "\n Permissions folder(DLL Hijacking): {5}"; - Beaprint.AnsiPrint(String.Format(formString, driver.Value.ProductName, driver.Value.ProductVersion, driver.Value.CompanyName, path_driver, String.Join(", ", file_rights), String.Join(", ", dir_rights)), colorsD); + Beaprint.AnsiPrint(string.Format(formString, driver.Value.ProductName, driver.Value.ProductVersion, driver.Value.CompanyName, path_driver, string.Join(", ", file_rights), string.Join(", ", dir_rights)), colorsD); //If vuln, end with separator if ((file_rights.Count > 0) || (dir_rights.Count > 0)) @@ -1282,7 +1293,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1315,7 +1326,7 @@ namespace winPEAS List> shares = NetworkInfo.GetNetworkShares("127.0.0.1"); foreach(Dictionary share in shares) { - string line = String.Format(" {0} (" + Beaprint.ansi_color_gray + "Path: {1}" + Beaprint.NOCOLOR + ")", share["Name"], share["Path"]); + string line = string.Format(" {0} (" + Beaprint.ansi_color_gray + "Path: {1}" + Beaprint.NOCOLOR + ")", share["Name"], share["Path"]); if (share["Permissions"].Length > 0) line += " -- Permissions: " + share["Permissions"]; Beaprint.AnsiPrint(line, colorsN); @@ -1323,7 +1334,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1341,7 +1352,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1361,12 +1372,12 @@ namespace winPEAS if (card["arp"].Length > 1) formString += "\n " + Beaprint.ansi_color_gray + "Known hosts:" + Beaprint.NOCOLOR + "\n{6}"; - System.Console.WriteLine(String.Format(formString, card["Name"], card["PysicalAddr"], card["IPs"], card["Netmasks"].Replace(", 0.0.0.0", ""), card["Gateways"], card["DNSs"], card["arp"])); + System.Console.WriteLine(string.Format(formString, card["Name"], card["PysicalAddr"], card["IPs"], card["Netmasks"].Replace(", 0.0.0.0", ""), card["Gateways"], card["DNSs"], card["arp"])); } } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1391,12 +1402,12 @@ namespace winPEAS if (conn[0].Contains("UDP") && conn[1].Contains("[::]:") && (conn[1].Split(']')[1].Length > 4)) continue; //Delete useless UDP listening ports - Beaprint.AnsiPrint(String.Format(" {0,-10}{1,-23}{2,-23}{3}", conn[0], conn[1], conn[2], conn[3]), colorsN); + Beaprint.AnsiPrint(string.Format(" {0,-10}{1,-23}{2,-23}{3}", conn[0], conn[1], conn[2], conn[3]), colorsN); } } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1414,13 +1425,13 @@ namespace winPEAS Beaprint.AnsiPrint(" Current Profiles: " + NetworkInfo.GetFirewallProfiles(), colorsN); foreach (KeyValuePair entry in NetworkInfo.GetFirewallBooleans()) - Beaprint.AnsiPrint(String.Format(" {0,-23}: {1}", entry.Key, entry.Value), colorsN); + Beaprint.AnsiPrint(string.Format(" {0,-23}: {1}", entry.Key, entry.Value), colorsN); Beaprint.GrayPrint(" DENY rules:"); foreach (Dictionary rule in NetworkInfo.GetFirewallRules()) { - string file_perms = String.Join(", ", MyUtils.GetPermissionsFile(rule["AppName"], currentUserSIDs)); - string folder_perms = String.Join(", ", MyUtils.GetPermissionsFolder(rule["AppName"], currentUserSIDs)); + string file_perms = string.Join(", ", MyUtils.GetPermissionsFile(rule["AppName"], currentUserSIDs)); + string folder_perms = string.Join(", ", MyUtils.GetPermissionsFolder(rule["AppName"], currentUserSIDs)); string formString = " ({0}){1}[{2}]: {3} {4} {5} from {6} --> {7}"; if (file_perms.Length > 0) formString += "\n File Permissions: {8}"; @@ -1435,12 +1446,12 @@ namespace winPEAS { "File Permissions.*|Folder Permissions.*", Beaprint.ansi_color_bad }, { rule["AppName"].Replace("\\", "\\\\").Replace("(", "\\(").Replace(")", "\\)").Replace("]", "\\]").Replace("[", "\\[").Replace("?", "\\?").Replace("+","\\+"), (file_perms.Length > 0 || folder_perms.Length > 0) ? Beaprint.ansi_color_bad : Beaprint.ansi_color_good }, }; - Beaprint.AnsiPrint(String.Format(formString, rule["Profiles"], rule["Name"], rule["AppName"], rule["Action"], rule["Protocol"], rule["Direction"], rule["Direction"] == "IN" ? rule["Local"] : rule["Remote"], rule["Direction"] == "IN" ? rule["Remote"] : rule["Local"], file_perms, folder_perms, rule["Description"]), colorsN); + Beaprint.AnsiPrint(string.Format(formString, rule["Profiles"], rule["Name"], rule["AppName"], rule["Action"], rule["Protocol"], rule["Direction"], rule["Direction"] == "IN" ? rule["Local"] : rule["Remote"], rule["Direction"] == "IN" ? rule["Remote"] : rule["Local"], file_perms, folder_perms, rule["Description"]), colorsN); } } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1449,14 +1460,14 @@ namespace winPEAS try { Beaprint.MainPrint("DNS cached --limit 70--"); - Beaprint.GrayPrint(String.Format(" {0,-38}{1,-38}{2}", "Entry", "Name", "Data")); + Beaprint.GrayPrint(string.Format(" {0,-38}{1,-38}{2}", "Entry", "Name", "Data")); List> DNScache = NetworkInfo.GetDNSCache(); foreach (Dictionary entry in DNScache.GetRange(0, DNScache.Count <= 70 ? DNScache.Count : 70)) - System.Console.WriteLine(String.Format(" {0,-38}{1,-38}{2}", entry["Entry"], entry["Name"], entry["Data"])); + System.Console.WriteLine(string.Format(" {0,-38}{1,-38}{2}", entry["Entry"], entry["Name"], entry["Data"])); } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1483,7 +1494,7 @@ namespace winPEAS { Beaprint.MainPrint("Checking Windows Vault"); Beaprint.LinkPrint("https://book.hacktricks.xyz/windows/windows-local-privilege-escalation#credentials-manager-windows-vault"); - List> vault_creds = KnownFileCredsInfo.DumpVault(); + List> vault_creds = VaultCli.DumpVault(); Dictionary colorsC = new Dictionary() { @@ -1493,7 +1504,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1520,7 +1531,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1531,18 +1542,18 @@ namespace winPEAS { Beaprint.MainPrint("Saved RDP connections"); - List> rdps_info = KnownFileCredsInfo.GetSavedRDPConnections(); + List> rdps_info = RemoteDesktop.GetSavedRDPConnections(); if (rdps_info.Count > 0) - System.Console.WriteLine(String.Format(" {0,-20}{1,-55}{2}", "Host", "Username Hint", "User SID")); + System.Console.WriteLine(string.Format(" {0,-20}{1,-55}{2}", "Host", "Username Hint", "User SID")); else Beaprint.NotFoundPrint(); foreach (Dictionary rdp_info in rdps_info) - System.Console.WriteLine(String.Format(" {0,-20}{1,-55}{2}", rdp_info["Host"], rdp_info["Username Hint"], rdp_info["SID"])); + System.Console.WriteLine(string.Format(" {0,-20}{1,-55}{2}", rdp_info["Host"], rdp_info["Username Hint"], rdp_info["SID"])); } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1556,7 +1567,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1579,7 +1590,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1596,7 +1607,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1606,14 +1617,14 @@ namespace winPEAS { Beaprint.MainPrint("Checking for RDCMan Settings Files"); Beaprint.LinkPrint("https://book.hacktricks.xyz/windows/windows-local-privilege-escalation#remote-desktop-credential-manager", "Dump credentials from Remote Desktop Connection Manager"); - List> rdc_files = KnownFileCredsInfo.GetRDCManFiles(); + List> rdc_files = RemoteDesktop.GetRDCManFiles(); Beaprint.DictPrint(rdc_files, false); if (rdc_files.Count != 0) Beaprint.InfoPrint("Follow the provided link for further instructions in how to decrypt the .rdg file"); } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1623,12 +1634,12 @@ namespace winPEAS { Beaprint.MainPrint("Looking for kerberos tickets"); Beaprint.LinkPrint("https://book.hacktricks.xyz/pentesting/pentesting-kerberos-88"); - List> kerberos_tckts = KnownFileCredsInfo.ListKerberosTickets(); + List> kerberos_tckts = Kerberos.ListKerberosTickets(); Beaprint.DictPrint(kerberos_tckts, false); } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1637,12 +1648,12 @@ namespace winPEAS try { Beaprint.MainPrint("Looking for kerberos TGT tickets"); - List> kerberos_tgts = KnownFileCredsInfo.GetKerberosTGTData(); + List> kerberos_tgts = Kerberos.GetKerberosTGTData(); Beaprint.DictPrint(kerberos_tgts, false); } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1665,14 +1676,32 @@ namespace winPEAS } else { - Beaprint.GrayPrint(" This function is not yet implemented."); - Beaprint.InfoPrint("If you want to list saved Wifis connections you can list the using 'netsh wlan show profile'"); - Beaprint.InfoPrint("If you want to get the clear-text password use 'netsh wlan show profile key=clear'"); + foreach (var iface in new WlanClient().Interfaces) + { + foreach (var profile in iface.GetProfiles()) + { + var xml = iface.GetProfileXml(profile.profileName); + + XmlDocument xDoc = new XmlDocument(); + xDoc.LoadXml(xml); + + var keyMaterial = xDoc.GetElementsByTagName("keyMaterial"); + if (keyMaterial.Count > 0) + { + string password = keyMaterial[0].InnerText; + + Beaprint.BadPrint($" found Wifi password for SSID: '{profile.profileName}', password: '{password}' "); + } + } + } + //Beaprint.GrayPrint(" This function is not yet implemented."); + //Beaprint.InfoPrint("If you want to list saved Wifis connections you can list the using 'netsh wlan show profile'"); + //Beaprint.InfoPrint("If you want to get the clear-text password use 'netsh wlan show profile key=clear'"); } } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1689,7 +1718,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1706,7 +1735,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1738,7 +1767,7 @@ namespace winPEAS { Beaprint.MainPrint("Looking for Firefox DBs"); Beaprint.LinkPrint("https://book.hacktricks.xyz/windows/windows-local-privilege-escalation#browsers-history"); - List firefoxDBs = KnownFileCredsInfo.GetFirefoxDbs(); + List firefoxDBs = Firefox.GetFirefoxDbs(); if (firefoxDBs.Count > 0) { foreach (string firefoxDB in firefoxDBs) //No Beaprints because line needs red @@ -1753,7 +1782,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1763,7 +1792,7 @@ namespace winPEAS { Beaprint.MainPrint("Looking for GET credentials in Firefox history"); Beaprint.LinkPrint("https://book.hacktricks.xyz/windows/windows-local-privilege-escalation#browsers-history"); - List firefoxHist = KnownFileCredsInfo.GetFirefoxHistory(); + List firefoxHist = Firefox.GetFirefoxHistory(); if (firefoxHist.Count > 0) { Dictionary colorsB = new Dictionary() @@ -1783,7 +1812,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1793,7 +1822,7 @@ namespace winPEAS { Beaprint.MainPrint("Looking for Chrome DBs"); Beaprint.LinkPrint("https://book.hacktricks.xyz/windows/windows-local-privilege-escalation#browsers-history"); - Dictionary chromeDBs = KnownFileCredsInfo.GetChromeDbs(); + Dictionary chromeDBs = Chrome.GetChromeDbs(); if (chromeDBs.ContainsKey("userChromeCookiesPath")) { Beaprint.BadPrint(" Chrome cookies database exists at " + chromeDBs["userChromeCookiesPath"]); @@ -1811,7 +1840,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1821,7 +1850,7 @@ namespace winPEAS { Beaprint.MainPrint("Looking for GET credentials in Chrome history"); Beaprint.LinkPrint("https://book.hacktricks.xyz/windows/windows-local-privilege-escalation#browsers-history"); - Dictionary> chromeHistBook = KnownFileCredsInfo.GetChromeHistBook(); + Dictionary> chromeHistBook = Chrome.GetChromeHistBook(); List history = chromeHistBook["history"]; List bookmarks = chromeHistBook["bookmarks"]; @@ -1848,7 +1877,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1858,7 +1887,7 @@ namespace winPEAS { Beaprint.MainPrint("Current IE tabs"); Beaprint.LinkPrint("https://book.hacktricks.xyz/windows/windows-local-privilege-escalation#browsers-history"); - List urls = KnownFileCredsInfo.GetCurrentIETabs(); + List urls = InternetExplorer.GetCurrentIETabs(); Dictionary colorsB = new Dictionary() { @@ -1868,7 +1897,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1878,7 +1907,7 @@ namespace winPEAS { Beaprint.MainPrint("Looking for GET credentials in IE history"); Beaprint.LinkPrint("https://book.hacktricks.xyz/windows/windows-local-privilege-escalation#browsers-history"); - Dictionary> chromeHistBook = KnownFileCredsInfo.GetIEHistFav(); + Dictionary> chromeHistBook = InternetExplorer.GetIEHistFav(); List history = chromeHistBook["history"]; List favorites = chromeHistBook["favorites"]; @@ -1901,7 +1930,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1926,7 +1955,7 @@ namespace winPEAS try { Beaprint.MainPrint("Putty Sessions"); - List> putty_sess = KnownFileCredsInfo.GetPuttySessions(); + List> putty_sess = Putty.GetPuttySessions(); Dictionary colorF = new Dictionary() { @@ -1936,7 +1965,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1945,7 +1974,7 @@ namespace winPEAS try { Beaprint.MainPrint("Putty SSH Host keys"); - List> putty_sess = KnownFileCredsInfo.ListPuttySSHHostKeys(); + List> putty_sess = Putty.ListPuttySSHHostKeys(); Dictionary colorF = new Dictionary() { { ".*", Beaprint.ansi_color_bad }, @@ -1954,7 +1983,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1965,7 +1994,7 @@ namespace winPEAS Beaprint.MainPrint("SSH keys in registry"); Beaprint.LinkPrint("https://book.hacktricks.xyz/windows/windows-local-privilege-escalation#ssh-keys-in-registry", "If you find anything here, follow the link to learn how to decrypt the SSH keys"); - string[] ssh_reg = MyUtils.GetRegSubkeys("HKCU", @"OpenSSH\Agent\Keys"); + string[] ssh_reg = RegistryHelper.GetRegSubkeys("HKCU", @"OpenSSH\Agent\Keys"); if (ssh_reg.Length == 0) Beaprint.NotFoundPrint(); else @@ -1976,7 +2005,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -1992,7 +2021,7 @@ namespace winPEAS foreach (Dictionary cc in could_creds) { string formString = " {0} ({1})\n Accessed:{2} -- Size:{3}"; - Beaprint.BadPrint(String.Format(formString, cc["file"], cc["Description"], cc["Accessed"], cc["Size"] )); + Beaprint.BadPrint(string.Format(formString, cc["file"], cc["Description"], cc["Accessed"], cc["Size"] )); System.Console.WriteLine(""); } } @@ -2001,7 +2030,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -2016,12 +2045,12 @@ namespace winPEAS { List pwds = InterestingFiles.ExtractUnattenededPwd(path); Beaprint.BadPrint(" "+path); - System.Console.WriteLine(String.Join("\n", pwds)); + System.Console.WriteLine(string.Join("\n", pwds)); } } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -2037,7 +2066,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -2053,7 +2082,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -2078,7 +2107,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -2092,18 +2121,18 @@ namespace winPEAS Beaprint.MainPrint("Looking for possible regs with creds"); Beaprint.LinkPrint("https://book.hacktricks.xyz/windows/windows-local-privilege-escalation#inside-the-registry"); - string winVNC4 = MyUtils.GetRegValue("HKLM", @"SOFTWARE\RealVNC\WinVNC4", "passwword"); - if (!String.IsNullOrEmpty(winVNC4.Trim())) + string winVNC4 = RegistryHelper.GetRegValue("HKLM", @"SOFTWARE\RealVNC\WinVNC4", "passwword"); + if (!string.IsNullOrEmpty(winVNC4.Trim())) Beaprint.BadPrint(winVNC4); foreach (string reg_hkcu in pass_reg_hkcu) - Beaprint.DictPrint(MyUtils.GetRegValues("HKLM", reg_hkcu), false); + Beaprint.DictPrint(RegistryHelper.GetRegValues("HKLM", reg_hkcu), false); foreach (string reg_hklm in pass_reg_hklm) - Beaprint.DictPrint(MyUtils.GetRegValues("HKLM", reg_hklm), false); + Beaprint.DictPrint(RegistryHelper.GetRegValues("HKLM", reg_hklm), false); } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -2121,7 +2150,7 @@ namespace winPEAS Beaprint.MainPrint("Looking for possible password files in users homes"); Beaprint.LinkPrint("https://book.hacktricks.xyz/windows/windows-local-privilege-escalation#credentials-inside-files"); - string searchPath = String.Format("{0}\\", Environment.GetEnvironmentVariable("SystemDrive") + "\\Users"); + string searchPath = string.Format("{0}\\", Environment.GetEnvironmentVariable("SystemDrive") + "\\Users"); List files_paths = MyUtils.FindFiles(searchPath, patterns); foreach (string file_path in files_paths) { @@ -2143,7 +2172,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -2176,7 +2205,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -2196,7 +2225,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -2210,7 +2239,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } @@ -2237,7 +2266,7 @@ namespace winPEAS } catch (Exception ex) { - Beaprint.GrayPrint(String.Format("{0}", ex)); + Beaprint.GrayPrint(string.Format("{0}", ex)); } } diff --git a/winPEAS/winPEASexe/winPEAS/ServicesInfo.cs b/winPEAS/winPEASexe/winPEAS/ServicesInfo.cs index 77b88fb..d04fb3f 100755 --- a/winPEAS/winPEASexe/winPEAS/ServicesInfo.cs +++ b/winPEAS/winPEASexe/winPEAS/ServicesInfo.cs @@ -11,6 +11,7 @@ using System.ServiceProcess; using System.Reflection; using System.Security.AccessControl; using System.Runtime.InteropServices; +using winPEAS.Utils; namespace winPEAS { @@ -41,7 +42,7 @@ namespace winPEAS companyName = myFileVersionInfo.CompanyName; isDotNet = MyUtils.CheckIfDotNet(binaryPath) ? "isDotNet" : ""; } - catch (Exception ex) + catch (Exception) { // Not enough privileges } @@ -76,9 +77,9 @@ namespace winPEAS try { - foreach (string key in MyUtils.GetRegSubkeys("HKLM", @"SYSTEM\CurrentControlSet\Services")) + foreach (string key in RegistryHelper.GetRegSubkeys("HKLM", @"SYSTEM\CurrentControlSet\Services")) { - Dictionary key_values = MyUtils.GetRegValues("HKLM", @"SYSTEM\CurrentControlSet\Services\" + key); + Dictionary key_values = RegistryHelper.GetRegValues("HKLM", @"SYSTEM\CurrentControlSet\Services\" + key); if (key_values.ContainsKey("DisplayName") && key_values.ContainsKey("ImagePath")) { @@ -94,7 +95,7 @@ namespace winPEAS companyName = myFileVersionInfo.CompanyName; isDotNet = MyUtils.CheckIfDotNet(binaryPath) ? "isDotNet" : ""; } - catch (Exception ex) + catch (Exception) { // Not enough privileges } @@ -231,7 +232,7 @@ namespace winPEAS } } - catch (Exception ex) + catch (Exception) { //Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); } @@ -280,7 +281,7 @@ namespace winPEAS try { // grabbed from the registry instead of System.Environment.GetEnvironmentVariable to prevent false positives - string path = MyUtils.GetRegValue("HKLM", "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment", "Path"); + string path = RegistryHelper.GetRegValue("HKLM", "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment", "Path"); if (String.IsNullOrEmpty(path)) path = Environment.GetEnvironmentVariable("PATH"); diff --git a/winPEAS/winPEASexe/winPEAS/SystemInfo.cs b/winPEAS/winPEASexe/winPEAS/SystemInfo.cs index a5409a9..d319401 100755 --- a/winPEAS/winPEASexe/winPEAS/SystemInfo.cs +++ b/winPEAS/winPEASexe/winPEAS/SystemInfo.cs @@ -6,6 +6,7 @@ using System.Management; using System.Net; using System.Net.NetworkInformation; using System.Windows.Forms; +using winPEAS.Utils; namespace winPEAS { @@ -48,12 +49,12 @@ namespace winPEAS Dictionary results = new Dictionary(); try { - string ProductName = MyUtils.GetRegValue("HKLM", "Software\\Microsoft\\Windows NT\\CurrentVersion", "ProductName"); - string EditionID = MyUtils.GetRegValue("HKLM", "Software\\Microsoft\\Windows NT\\CurrentVersion", "EditionID"); - string ReleaseId = MyUtils.GetRegValue("HKLM", "Software\\Microsoft\\Windows NT\\CurrentVersion", "ReleaseId"); - string BuildBranch = MyUtils.GetRegValue("HKLM", "Software\\Microsoft\\Windows NT\\CurrentVersion", "BuildBranch"); - string CurrentMajorVersionNumber = MyUtils.GetRegValue("HKLM", "Software\\Microsoft\\Windows NT\\CurrentVersion", "CurrentMajorVersionNumber"); - string CurrentVersion = MyUtils.GetRegValue("HKLM", "Software\\Microsoft\\Windows NT\\CurrentVersion", "CurrentVersion"); + string ProductName = RegistryHelper.GetRegValue("HKLM", "Software\\Microsoft\\Windows NT\\CurrentVersion", "ProductName"); + string EditionID = RegistryHelper.GetRegValue("HKLM", "Software\\Microsoft\\Windows NT\\CurrentVersion", "EditionID"); + string ReleaseId = RegistryHelper.GetRegValue("HKLM", "Software\\Microsoft\\Windows NT\\CurrentVersion", "ReleaseId"); + string BuildBranch = RegistryHelper.GetRegValue("HKLM", "Software\\Microsoft\\Windows NT\\CurrentVersion", "BuildBranch"); + string CurrentMajorVersionNumber = RegistryHelper.GetRegValue("HKLM", "Software\\Microsoft\\Windows NT\\CurrentVersion", "CurrentMajorVersionNumber"); + string CurrentVersion = RegistryHelper.GetRegValue("HKLM", "Software\\Microsoft\\Windows NT\\CurrentVersion", "CurrentVersion"); bool isHighIntegrity = MyUtils.IsHighIntegrity(); @@ -148,7 +149,7 @@ namespace winPEAS string whitelistpaths = ""; try { - whitelistpaths = String.Join("\n ", MyUtils.GetRegValues("HKLM", @"SOFTWARE\Microsoft\Windows Defender\Exclusions\Paths").Keys); + whitelistpaths = String.Join("\n ", RegistryHelper.GetRegValues("HKLM", @"SOFTWARE\Microsoft\Windows Defender\Exclusions\Paths").Keys); ManagementObjectSearcher wmiData = new ManagementObjectSearcher(@"root\SecurityCenter2", "SELECT * FROM AntiVirusProduct"); ManagementObjectCollection data = wmiData.Get(); @@ -176,7 +177,7 @@ namespace winPEAS try { - string ConsentPromptBehaviorAdmin = MyUtils.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", "ConsentPromptBehaviorAdmin"); + string ConsentPromptBehaviorAdmin = RegistryHelper.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", "ConsentPromptBehaviorAdmin"); switch (ConsentPromptBehaviorAdmin) { case "0": @@ -202,13 +203,13 @@ namespace winPEAS break; } - string EnableLUA = MyUtils.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", "EnableLUA"); + string EnableLUA = RegistryHelper.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", "EnableLUA"); results["EnableLUA"] = EnableLUA; - string LocalAccountTokenFilterPolicy = MyUtils.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", "LocalAccountTokenFilterPolicy"); + string LocalAccountTokenFilterPolicy = RegistryHelper.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", "LocalAccountTokenFilterPolicy"); results["LocalAccountTokenFilterPolicy"] = LocalAccountTokenFilterPolicy; - string FilterAdministratorToken = MyUtils.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", "FilterAdministratorToken"); + string FilterAdministratorToken = RegistryHelper.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", "FilterAdministratorToken"); results["FilterAdministratorToken"] = FilterAdministratorToken; } catch (Exception ex) @@ -225,18 +226,18 @@ namespace winPEAS try { - results["PowerShell v2 Version"] = MyUtils.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\PowerShell\\1\\PowerShellEngine", "PowerShellVersion"); - results["PowerShell v5 Version"] = MyUtils.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\PowerShell\\3\\PowerShellEngine", "PowerShellVersion"); + results["PowerShell v2 Version"] = RegistryHelper.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\PowerShell\\1\\PowerShellEngine", "PowerShellVersion"); + results["PowerShell v5 Version"] = RegistryHelper.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\PowerShell\\3\\PowerShellEngine", "PowerShellVersion"); results["Transcription Settings"] = ""; results["Module Logging Settings"] = ""; results["Scriptblock Logging Settings"] = ""; results["PS history file"] = ""; results["PS history size"] = ""; - Dictionary transcriptionSettingsCU = MyUtils.GetRegValues("HKCU", + Dictionary transcriptionSettingsCU = RegistryHelper.GetRegValues("HKCU", "SOFTWARE\\Policies\\Microsoft\\Windows\\PowerShell\\Transcription"); if ((transcriptionSettingsCU == null) || (transcriptionSettingsCU.Count == 0)) - transcriptionSettingsCU = MyUtils.GetRegValues("HKCU", @"HKLM\SOFTWARE\Wow6432Node\Policies\Microsoft\Windows\PowerShell\Transcription"); + transcriptionSettingsCU = RegistryHelper.GetRegValues("HKCU", @"HKLM\SOFTWARE\Wow6432Node\Policies\Microsoft\Windows\PowerShell\Transcription"); if ((transcriptionSettingsCU != null) && (transcriptionSettingsCU.Count != 0)) { @@ -246,10 +247,10 @@ namespace winPEAS } } - Dictionary transcriptionSettingsLM = MyUtils.GetRegValues("HKLM", + Dictionary transcriptionSettingsLM = RegistryHelper.GetRegValues("HKLM", "SOFTWARE\\Policies\\Microsoft\\Windows\\PowerShell\\Transcription"); if ((transcriptionSettingsLM == null) || (transcriptionSettingsLM.Count == 0)) - transcriptionSettingsLM = MyUtils.GetRegValues("HKLM", @"HKLM\SOFTWARE\Wow6432Node\Policies\Microsoft\Windows\PowerShell\Transcription"); + transcriptionSettingsLM = RegistryHelper.GetRegValues("HKLM", @"HKLM\SOFTWARE\Wow6432Node\Policies\Microsoft\Windows\PowerShell\Transcription"); if ((transcriptionSettingsLM != null) && (transcriptionSettingsLM.Count != 0)) { @@ -259,9 +260,9 @@ namespace winPEAS } } - Dictionary moduleLoggingSettingsLM = MyUtils.GetRegValues("HKLM", "SOFTWARE\\Policies\\Microsoft\\Windows\\PowerShell\\ModuleLogging"); + Dictionary moduleLoggingSettingsLM = RegistryHelper.GetRegValues("HKLM", "SOFTWARE\\Policies\\Microsoft\\Windows\\PowerShell\\ModuleLogging"); if ((moduleLoggingSettingsLM == null) || (moduleLoggingSettingsLM.Count == 0)) - moduleLoggingSettingsLM = MyUtils.GetRegValues("HKLM", @"SOFTWARE\Wow6432Node\Policies\Microsoft\Windows\PowerShell\ModuleLogging"); + moduleLoggingSettingsLM = RegistryHelper.GetRegValues("HKLM", @"SOFTWARE\Wow6432Node\Policies\Microsoft\Windows\PowerShell\ModuleLogging"); if ((moduleLoggingSettingsLM != null) && (moduleLoggingSettingsLM.Count != 0)) { @@ -271,9 +272,9 @@ namespace winPEAS } } - Dictionary moduleLoggingSettingsCU = MyUtils.GetRegValues("HKCU", "SOFTWARE\\Policies\\Microsoft\\Windows\\PowerShell\\ModuleLogging"); + Dictionary moduleLoggingSettingsCU = RegistryHelper.GetRegValues("HKCU", "SOFTWARE\\Policies\\Microsoft\\Windows\\PowerShell\\ModuleLogging"); if ((moduleLoggingSettingsCU == null) || (moduleLoggingSettingsCU.Count == 0)) - moduleLoggingSettingsCU = MyUtils.GetRegValues("HKCU", @"SOFTWARE\Wow6432Node\Policies\Microsoft\Windows\PowerShell\ModuleLogging"); + moduleLoggingSettingsCU = RegistryHelper.GetRegValues("HKCU", @"SOFTWARE\Wow6432Node\Policies\Microsoft\Windows\PowerShell\ModuleLogging"); if ((moduleLoggingSettingsCU != null) && (moduleLoggingSettingsCU.Count != 0)) { @@ -283,9 +284,9 @@ namespace winPEAS } } - Dictionary scriptBlockSettingsLM = MyUtils.GetRegValues("HKLM", "SOFTWARE\\Policies\\Microsoft\\Windows\\PowerShell\\ScriptBlockLogging"); + Dictionary scriptBlockSettingsLM = RegistryHelper.GetRegValues("HKLM", "SOFTWARE\\Policies\\Microsoft\\Windows\\PowerShell\\ScriptBlockLogging"); if ((scriptBlockSettingsLM == null) || (scriptBlockSettingsLM.Count == 0)) - scriptBlockSettingsLM = MyUtils.GetRegValues("HKLM", @"SOFTWARE\Wow6432Node\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging"); + scriptBlockSettingsLM = RegistryHelper.GetRegValues("HKLM", @"SOFTWARE\Wow6432Node\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging"); if ((scriptBlockSettingsLM != null) && (scriptBlockSettingsLM.Count != 0)) { @@ -295,9 +296,9 @@ namespace winPEAS } } - Dictionary scriptBlockSettingsCU = MyUtils.GetRegValues("HKCU", "SOFTWARE\\Policies\\Microsoft\\Windows\\PowerShell\\ScriptBlockLogging"); + Dictionary scriptBlockSettingsCU = RegistryHelper.GetRegValues("HKCU", "SOFTWARE\\Policies\\Microsoft\\Windows\\PowerShell\\ScriptBlockLogging"); if ((scriptBlockSettingsCU == null) || (scriptBlockSettingsCU.Count == 0)) - scriptBlockSettingsCU = MyUtils.GetRegValues("HKCU", @"SOFTWARE\Wow6432Node\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging"); + scriptBlockSettingsCU = RegistryHelper.GetRegValues("HKCU", @"SOFTWARE\Wow6432Node\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging"); if ((scriptBlockSettingsCU != null) && (scriptBlockSettingsCU.Count != 0)) { @@ -331,7 +332,7 @@ namespace winPEAS Dictionary results = new Dictionary(); try { - Dictionary settings = MyUtils.GetRegValues("HKLM", "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System\\Audit"); + Dictionary settings = RegistryHelper.GetRegValues("HKLM", "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System\\Audit"); if ((settings != null) && (settings.Count != 0)) { foreach (KeyValuePair kvp in settings) @@ -361,7 +362,7 @@ namespace winPEAS Dictionary results = new Dictionary(); try { - Dictionary settings = MyUtils.GetRegValues("HKLM", "Software\\Policies\\Microsoft\\Windows\\EventLog\\EventForwarding\\SubscriptionManager"); + Dictionary settings = RegistryHelper.GetRegValues("HKLM", "Software\\Policies\\Microsoft\\Windows\\EventLog\\EventForwarding\\SubscriptionManager"); if ((settings != null) && (settings.Count != 0)) { foreach (KeyValuePair kvp in settings) @@ -391,15 +392,15 @@ namespace winPEAS Dictionary results = new Dictionary(); try { - string AdmPwdEnabled = MyUtils.GetRegValue("HKLM", "Software\\Policies\\Microsoft Services\\AdmPwd", "AdmPwdEnabled"); + string AdmPwdEnabled = RegistryHelper.GetRegValue("HKLM", "Software\\Policies\\Microsoft Services\\AdmPwd", "AdmPwdEnabled"); if (AdmPwdEnabled != "") { results["LAPS Enabled"] = AdmPwdEnabled; - results["LAPS Admin Account Name"] = MyUtils.GetRegValue("HKLM", "Software\\Policies\\Microsoft Services\\AdmPwd", "AdminAccountName"); - results["LAPS Password Complexity"] = MyUtils.GetRegValue("HKLM", "Software\\Policies\\Microsoft Services\\AdmPwd", "PasswordComplexity"); - results["LAPS Password Length"] = MyUtils.GetRegValue("HKLM", "Software\\Policies\\Microsoft Services\\AdmPwd", "PasswordLength"); - results["LAPS Expiration Protection Enabled"] = MyUtils.GetRegValue("HKLM", "Software\\Policies\\Microsoft Services\\AdmPwd", "PwdExpirationProtectionEnabled"); + results["LAPS Admin Account Name"] = RegistryHelper.GetRegValue("HKLM", "Software\\Policies\\Microsoft Services\\AdmPwd", "AdminAccountName"); + results["LAPS Password Complexity"] = RegistryHelper.GetRegValue("HKLM", "Software\\Policies\\Microsoft Services\\AdmPwd", "PasswordComplexity"); + results["LAPS Password Length"] = RegistryHelper.GetRegValue("HKLM", "Software\\Policies\\Microsoft Services\\AdmPwd", "PasswordLength"); + results["LAPS Expiration Protection Enabled"] = RegistryHelper.GetRegValue("HKLM", "Software\\Policies\\Microsoft Services\\AdmPwd", "PwdExpirationProtectionEnabled"); } else { @@ -435,7 +436,7 @@ namespace winPEAS Dictionary result = new Dictionary(); try { - Dictionary settings = MyUtils.GetRegValues("HKLM", "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment"); + Dictionary settings = RegistryHelper.GetRegValues("HKLM", "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment"); if ((settings != null) && (settings.Count != 0)) { foreach (KeyValuePair kvp in settings) @@ -456,7 +457,7 @@ namespace winPEAS Dictionary results = new Dictionary(); try { - Dictionary proxySettings = MyUtils.GetRegValues(root_reg, "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"); + Dictionary proxySettings = RegistryHelper.GetRegValues(root_reg, "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"); if ((proxySettings != null) && (proxySettings.Count != 0)) { foreach (KeyValuePair kvp in proxySettings) diff --git a/winPEAS/winPEASexe/winPEAS/UserInfo.cs b/winPEAS/winPEASexe/winPEAS/UserInfo.cs index b0c22ea..f8b1522 100755 --- a/winPEAS/winPEASexe/winPEAS/UserInfo.cs +++ b/winPEAS/winPEASexe/winPEAS/UserInfo.cs @@ -6,6 +6,7 @@ using System.Security.Principal; using System.Runtime.InteropServices; using System.Windows.Forms; using System.Text.RegularExpressions; +using winPEAS.Utils; //Configuring Fody: https://tech.trailmax.info/2014/01/bundling-all-your-assemblies-into-one-or-alternative-to-ilmerge/ //I have also created the folder Costura32 and Costura64 with the respective Dlls of Colorful.Console @@ -962,12 +963,12 @@ namespace winPEAS { Dictionary results = new Dictionary(); - results["DefaultDomainName"] = MyUtils.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", "DefaultDomainName"); - results["DefaultUserName"] = MyUtils.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", "DefaultUserName"); - results["DefaultPassword"] = MyUtils.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", "DefaultPassword"); - results["AltDefaultDomainName"] = MyUtils.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", "AltDefaultDomainName"); - results["AltDefaultUserName"] = MyUtils.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", "AltDefaultUserName"); - results["AltDefaultPassword"] = MyUtils.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", "AltDefaultPassword"); + results["DefaultDomainName"] = RegistryHelper.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", "DefaultDomainName"); + results["DefaultUserName"] = RegistryHelper.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", "DefaultUserName"); + results["DefaultPassword"] = RegistryHelper.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", "DefaultPassword"); + results["AltDefaultDomainName"] = RegistryHelper.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", "AltDefaultDomainName"); + results["AltDefaultUserName"] = RegistryHelper.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", "AltDefaultUserName"); + results["AltDefaultPassword"] = RegistryHelper.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", "AltDefaultPassword"); return results; } diff --git a/winPEAS/winPEASexe/winPEAS/Utils/RegistryHelper.cs b/winPEAS/winPEASexe/winPEAS/Utils/RegistryHelper.cs new file mode 100644 index 0000000..eb9874d --- /dev/null +++ b/winPEAS/winPEASexe/winPEAS/Utils/RegistryHelper.cs @@ -0,0 +1,155 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.Win32; + +namespace winPEAS.Utils +{ + static class RegistryHelper + { + /////////////////////////////////////////// + /// Interf. for Keys and Values in Reg. /// + /////////////////////////////////////////// + /// Functions related to obtain keys and values from the registry + /// Some parts adapted from Seatbelt + public static string GetRegValue(string hive, string path, string value) + { + // returns a single registry value under the specified path in the specified hive (HKLM/HKCU) + string regKeyValue = ""; + if (hive == "HKCU") + { + var regKey = Registry.CurrentUser.OpenSubKey(path); + if (regKey != null) + { + regKeyValue = String.Format("{0}", regKey.GetValue(value)); + } + return regKeyValue; + } + else if (hive == "HKU") + { + var regKey = Registry.Users.OpenSubKey(path); + if (regKey != null) + { + regKeyValue = String.Format("{0}", regKey.GetValue(value)); + } + return regKeyValue; + } + else + { + var regKey = Registry.LocalMachine.OpenSubKey(path); + if (regKey != null) + { + regKeyValue = String.Format("{0}", regKey.GetValue(value)); + } + return regKeyValue; + } + } + + public static Dictionary GetRegValues(string hive, string path) + { + // returns all registry values under the specified path in the specified hive (HKLM/HKCU) + Dictionary keyValuePairs = null; + try + { + if (hive == "HKCU") + { + using (var regKeyValues = Registry.CurrentUser.OpenSubKey(path)) + { + if (regKeyValues != null) + { + var valueNames = regKeyValues.GetValueNames(); + keyValuePairs = valueNames.ToDictionary(name => name, regKeyValues.GetValue); + } + } + } + else if (hive == "HKU") + { + using (var regKeyValues = Registry.Users.OpenSubKey(path)) + { + if (regKeyValues != null) + { + var valueNames = regKeyValues.GetValueNames(); + keyValuePairs = valueNames.ToDictionary(name => name, regKeyValues.GetValue); + } + } + } + else + { + using (var regKeyValues = Registry.LocalMachine.OpenSubKey(path)) + { + if (regKeyValues != null) + { + var valueNames = regKeyValues.GetValueNames(); + keyValuePairs = valueNames.ToDictionary(name => name, regKeyValues.GetValue); + } + } + } + return keyValuePairs; + } + catch + { + return null; + } + } + + public static byte[] GetRegValueBytes(string hive, string path, string value) + { + // returns a byte array of single registry value under the specified path in the specified hive (HKLM/HKCU) + byte[] regKeyValue = null; + if (hive == "HKCU") + { + var regKey = Registry.CurrentUser.OpenSubKey(path); + if (regKey != null) + { + regKeyValue = (byte[])regKey.GetValue(value); + } + return regKeyValue; + } + else if (hive == "HKU") + { + var regKey = Registry.Users.OpenSubKey(path); + if (regKey != null) + { + regKeyValue = (byte[])regKey.GetValue(value); + } + return regKeyValue; + } + else + { + var regKey = Registry.LocalMachine.OpenSubKey(path); + if (regKey != null) + { + regKeyValue = (byte[])regKey.GetValue(value); + } + return regKeyValue; + } + } + + public static string[] GetRegSubkeys(string hive, string path) + { + // returns an array of the subkeys names under the specified path in the specified hive (HKLM/HKCU/HKU) + try + { + RegistryKey myKey = null; + if (hive == "HKLM") + { + myKey = Registry.LocalMachine.OpenSubKey(path); + } + else if (hive == "HKU") + { + myKey = Registry.Users.OpenSubKey(path); + } + else + { + myKey = Registry.CurrentUser.OpenSubKey(path); + } + String[] subkeyNames = myKey.GetSubKeyNames(); + return myKey.GetSubKeyNames(); + } + catch + { + return new string[0]; + } + } + } +} diff --git a/winPEAS/winPEASexe/winPEAS/Wifi.cs b/winPEAS/winPEASexe/winPEAS/Wifi.cs index 15c232f..e5c5ced 100644 --- a/winPEAS/winPEASexe/winPEAS/Wifi.cs +++ b/winPEAS/winPEASexe/winPEAS/Wifi.cs @@ -1,5 +1,8 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; +using System.Management; using System.Text.RegularExpressions; + namespace winPEAS { class Wifi @@ -50,6 +53,5 @@ namespace winPEAS return password; } - } } diff --git a/winPEAS/winPEASexe/winPEAS/winPEAS.csproj b/winPEAS/winPEASexe/winPEAS/winPEAS.csproj index cfed4aa..554f598 100755 --- a/winPEAS/winPEASexe/winPEAS/winPEAS.csproj +++ b/winPEAS/winPEASexe/winPEAS/winPEAS.csproj @@ -109,10 +109,27 @@ - + + + + + + + + + + + + + + + + - + + + @@ -158,6 +175,7 @@ + @@ -175,6 +193,8 @@ + +