- cleanup

- fixed using on IDisposables
This commit is contained in:
makikvues 2021-01-25 23:52:29 +01:00
parent 24754e374f
commit 27e8867236
9 changed files with 223 additions and 153 deletions

View File

@ -14,15 +14,16 @@ namespace winPEAS._3rdParty.Watson
{
using (var searcher = new ManagementObjectSearcher(@"root\cimv2", "SELECT HotFixID FROM Win32_QuickFixEngineering"))
{
var hotFixes = searcher.Get();
foreach (var hotFix in hotFixes)
using (var hotFixes = searcher.Get())
{
var line = hotFix["HotFixID"].ToString().Remove(0, 2);
if (int.TryParse(line, out int kb))
foreach (var hotFix in hotFixes)
{
KbList.Add(kb);
var line = hotFix["HotFixID"].ToString().Remove(0, 2);
if (int.TryParse(line, out int kb))
{
KbList.Add(kb);
}
}
}
}
@ -41,13 +42,14 @@ namespace winPEAS._3rdParty.Watson
{
using (var searcher = new ManagementObjectSearcher(@"root\cimv2", "SELECT BuildNumber FROM Win32_OperatingSystem"))
{
var collection = searcher.Get();
foreach (var num in collection)
using (var collection = searcher.Get())
{
if (int.TryParse(num["BuildNumber"] as string, out int buildNumber))
foreach (var num in collection)
{
return buildNumber;
if (int.TryParse(num["BuildNumber"] as string, out int buildNumber))
{
return buildNumber;
}
}
}
}

View File

@ -264,7 +264,7 @@ namespace winPEAS.Checks
colors);
Beaprint.PrintLineSeparator();
}
catch (Exception e) { }
catch (Exception) { }
}
}
else
@ -272,7 +272,7 @@ namespace winPEAS.Checks
Beaprint.GoodPrint(" WSL - no installed Linux distributions found.");
}
}
catch (Exception e) { }
catch (Exception) { }
}
}
@ -513,24 +513,30 @@ namespace winPEAS.Checks
foreach (var file in files)
{
FileAttributes attr = File.GetAttributes(file.FullPath);
if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
try
{
List<string> dirRights = PermissionsHelper.GetPermissionsFolder(file.FullPath, Checks.CurrentUserSiDs, isOnlyWriteOrEquivalentCheck: true);
if (dirRights.Count > 0)
FileAttributes attr = File.GetAttributes(file.FullPath);
if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
{
Beaprint.BadPrint($" Folder Permissions \"{file.FullPath}\": " + string.Join(",", dirRights));
List<string> dirRights = PermissionsHelper.GetPermissionsFolder(file.FullPath, Checks.CurrentUserSiDs, isOnlyWriteOrEquivalentCheck: true);
if (dirRights.Count > 0)
{
Beaprint.BadPrint($" Folder Permissions \"{file.FullPath}\": " + string.Join(",", dirRights));
}
}
else
{
List<string> fileRights = PermissionsHelper.GetPermissionsFile(file.FullPath, Checks.CurrentUserSiDs, isOnlyWriteOrEquivalentCheck: true);
if (fileRights.Count > 0)
{
Beaprint.BadPrint($" File Permissions \"{file.FullPath}\": " + string.Join(",", fileRights));
}
}
}
else
catch (Exception)
{
List<string> fileRights = PermissionsHelper.GetPermissionsFile(file.FullPath, Checks.CurrentUserSiDs, isOnlyWriteOrEquivalentCheck: true);
if (fileRights.Count > 0)
{
Beaprint.BadPrint($" File Permissions \"{file.FullPath}\": " + string.Join(",", fileRights));
}
}
}
@ -637,8 +643,8 @@ namespace winPEAS.Checks
Beaprint.BadPrint($" {file.FullPath}");
}
}
catch (PathTooLongException ex) { }
catch (Exception ex)
catch (PathTooLongException) { }
catch (Exception)
{
// & other exceptions
}
@ -656,12 +662,14 @@ namespace winPEAS.Checks
@"c:\esupport",
@"c:\perflogs",
@"c:\programdata",
@"c:\program files(x86)",
@"c:\program files (x86)",
@"c:\program files",
@"c:\windows",
@"c:\windows.old",
};
var currentUserDir = @$"{systemDrive}users\{Environment.GetEnvironmentVariable("USERNAME")}".ToLower();
var allowedExtensions = new HashSet<string>()
{
".bat",
@ -669,20 +677,35 @@ namespace winPEAS.Checks
".ps1"
};
var files = SearchHelper.GetFilesFast(systemDrive, "*", excludedDirs);
var files = SearchHelper.GetFilesFast(systemDrive, "*", excludedDirs);
foreach (var file in files)
{
if (file.Extension != null && allowedExtensions.Contains(file.Extension.ToLower()))
try
{
// check the file permissions
List<string> fileRights = PermissionsHelper.GetPermissionsFile(file.FullPath, Checks.CurrentUserSiDs, isOnlyWriteOrEquivalentCheck: true);
if (fileRights.Count > 0)
if (file.Extension != null && allowedExtensions.Contains(file.Extension.ToLower()))
{
Beaprint.BadPrint($" File Permissions \"{file.FullPath}\": " + string.Join(",", fileRights));
// check the file permissions
List<string> fileRights = PermissionsHelper.GetPermissionsFile(file.FullPath, Checks.CurrentUserSiDs, isOnlyWriteOrEquivalentCheck: true);
if (fileRights.Count > 0)
{
string log = $" File Permissions \"{file.FullPath}\": " + string.Join(",", fileRights);
if (file.FullPath.ToLower().StartsWith(currentUserDir))
{
Beaprint.NoColorPrint(log);
}
else
{
Beaprint.BadPrint(log);
}
}
}
}
catch (Exception)
{
}
}
}
}

View File

@ -354,9 +354,8 @@ namespace winPEAS.Helpers.AppLocker
return true;
}
}
catch (Exception e)
catch (Exception)
{
// unauthorized access ?
}
return false;

View File

@ -83,6 +83,10 @@ namespace winPEAS.Helpers.Search
{
return new List<FileInfo>();
}
catch (Exception)
{
return new List<FileInfo>();
}
List<FileInfo> result = new List<FileInfo>();
@ -104,6 +108,9 @@ namespace winPEAS.Helpers.Search
catch (DirectoryNotFoundException)
{
}
catch (Exception)
{
}
return result;
}
@ -151,6 +158,10 @@ namespace winPEAS.Helpers.Search
{
return new List<DirectoryInfo>();
}
catch (Exception)
{
return new List<DirectoryInfo>();
}
return GetStartDirectories(directories[0].FullName, files, pattern);
}

View File

@ -355,7 +355,7 @@ namespace winPEAS.Info.ApplicationInfo
}
}
}
catch (Exception e)
catch (Exception)
{
}
@ -381,7 +381,7 @@ namespace winPEAS.Info.ApplicationInfo
});
}
}
catch (Exception e)
catch (Exception)
{
}
}
@ -408,7 +408,7 @@ namespace winPEAS.Info.ApplicationInfo
{ "isUnquotedSpaced", "" }
});
}
catch (Exception e)
catch (Exception)
{
}
}
@ -422,24 +422,25 @@ namespace winPEAS.Info.ApplicationInfo
try
{
SelectQuery query = new SelectQuery("Win32_StartupCommand");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
using (ManagementObjectCollection win32_startup = searcher.Get())
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
{
foreach (ManagementObject startup in win32_startup)
using (ManagementObjectCollection win32_startup = searcher.Get())
{
string command = startup["command"].ToString();
command = Environment.ExpandEnvironmentVariables(string.Format("{0}", command));
string filepath = MyUtils.GetExecutableFromPath(command);
if (!string.IsNullOrEmpty(filepath))
foreach (ManagementObject startup in win32_startup)
{
string filepathCleaned = filepath.Replace("'", "").Replace("\"", "");
string command = startup["command"].ToString();
command = Environment.ExpandEnvironmentVariables(string.Format("{0}", command));
string filepath = MyUtils.GetExecutableFromPath(command);
try
if (!string.IsNullOrEmpty(filepath))
{
string folder = Path.GetDirectoryName(filepathCleaned);
results.Add(new Dictionary<string, string>()
string filepathCleaned = filepath.Replace("'", "").Replace("\"", "");
try
{
string folder = Path.GetDirectoryName(filepathCleaned);
results.Add(new Dictionary<string, string>()
{
{"Reg", ""},
{"RegKey", "From WMIC"},
@ -457,9 +458,10 @@ namespace winPEAS.Info.ApplicationInfo
},
{"isUnquotedSpaced", MyUtils.CheckQuoteAndSpace(command).ToString()}
});
}
catch (Exception)
{
}
catch (Exception)
{
}
}
}
}
@ -511,7 +513,7 @@ namespace winPEAS.Info.ApplicationInfo
});
}
}
catch (Exception e)
catch (Exception)
{
}
}

View File

@ -269,20 +269,22 @@ namespace winPEAS.Info.NetworkInfo
List<Dictionary<string, string>> results = new List<Dictionary<string, string>>();
try
{
ManagementObjectSearcher wmiData = new ManagementObjectSearcher(@"root\standardcimv2", "SELECT * FROM MSFT_DNSClientCache");
ManagementObjectCollection data = wmiData.Get();
foreach (ManagementObject result in data)
using (ManagementObjectSearcher wmiData = new ManagementObjectSearcher(@"root\standardcimv2", "SELECT * FROM MSFT_DNSClientCache"))
{
Dictionary<string, string> dnsEntry = new Dictionary<string, string>();
string entry = $"{result["Entry"]}";
string name = $"{result["Name"]}";
string dataDns = $"{result["Data"]}";
dnsEntry["Entry"] = (entry.Length > 33) ? "..." + result["Entry"].ToString().Substring(entry.Length - 32) : entry;
dnsEntry["Name"] = (name.Length > 33) ? "..." + name.Substring(name.Length - 32) : name;
dnsEntry["Data"] = (dataDns.Length > 33) ? "..." + dataDns.Substring(dataDns.Length - 32) : dataDns;
results.Add(dnsEntry);
using (ManagementObjectCollection data = wmiData.Get())
{
foreach (ManagementObject result in data)
{
Dictionary<string, string> dnsEntry = new Dictionary<string, string>();
string entry = $"{result["Entry"]}";
string name = $"{result["Name"]}";
string dataDns = $"{result["Data"]}";
dnsEntry["Entry"] = (entry.Length > 33) ? "..." + result["Entry"].ToString().Substring(entry.Length - 32) : entry;
dnsEntry["Name"] = (name.Length > 33) ? "..." + name.Substring(name.Length - 32) : name;
dnsEntry["Data"] = (dataDns.Length > 33) ? "..." + dataDns.Substring(dataDns.Length - 32) : dataDns;
results.Add(dnsEntry);
}
}
}
}
catch (ManagementException ex) when (ex.ErrorCode == ManagementStatus.InvalidNamespace)

View File

@ -25,42 +25,45 @@ namespace winPEAS.Info.ServicesInfo
try
{
ManagementObjectSearcher wmiData = new ManagementObjectSearcher(@"root\cimv2", "SELECT * FROM win32_service");
ManagementObjectCollection data = wmiData.Get();
foreach (ManagementObject result in data)
using (ManagementObjectSearcher wmiData = new ManagementObjectSearcher(@"root\cimv2", "SELECT * FROM win32_service"))
{
if (result["PathName"] != null)
using (ManagementObjectCollection data = wmiData.Get())
{
string binaryPath = MyUtils.GetExecutableFromPath(result["PathName"].ToString());
string companyName = "";
string isDotNet = "";
try
foreach (ManagementObject result in data)
{
FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(binaryPath);
companyName = myFileVersionInfo.CompanyName;
isDotNet = MyUtils.CheckIfDotNet(binaryPath) ? "isDotNet" : "";
}
catch (Exception)
{
// Not enough privileges
}
if (result["PathName"] != null)
{
string binaryPath = MyUtils.GetExecutableFromPath(result["PathName"].ToString());
string companyName = "";
string isDotNet = "";
try
{
FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(binaryPath);
companyName = myFileVersionInfo.CompanyName;
isDotNet = MyUtils.CheckIfDotNet(binaryPath) ? "isDotNet" : "";
}
catch (Exception)
{
// Not enough privileges
}
if (string.IsNullOrEmpty(companyName) || (!Regex.IsMatch(companyName, @"^Microsoft.*", RegexOptions.IgnoreCase)))
{
Dictionary<string, string> toadd = new Dictionary<string, string>();
toadd["Name"] = GetStringOrEmpty(result["Name"]);
toadd["DisplayName"] = GetStringOrEmpty(result["DisplayName"]);
toadd["CompanyName"] = companyName;
toadd["State"] = GetStringOrEmpty(result["State"]);
toadd["StartMode"] = GetStringOrEmpty(result["StartMode"]);
toadd["PathName"] = GetStringOrEmpty(result["PathName"]);
toadd["FilteredPath"] = binaryPath;
toadd["isDotNet"] = isDotNet;
toadd["Description"] = GetStringOrEmpty(result["Description"]);
results.Add(toadd);
if (string.IsNullOrEmpty(companyName) || (!Regex.IsMatch(companyName, @"^Microsoft.*", RegexOptions.IgnoreCase)))
{
Dictionary<string, string> toadd = new Dictionary<string, string>();
toadd["Name"] = GetStringOrEmpty(result["Name"]);
toadd["DisplayName"] = GetStringOrEmpty(result["DisplayName"]);
toadd["CompanyName"] = companyName;
toadd["State"] = GetStringOrEmpty(result["State"]);
toadd["StartMode"] = GetStringOrEmpty(result["StartMode"]);
toadd["PathName"] = GetStringOrEmpty(result["PathName"]);
toadd["FilteredPath"] = binaryPath;
toadd["isDotNet"] = isDotNet;
toadd["Description"] = GetStringOrEmpty(result["Description"]);
results.Add(toadd);
}
}
}
}
}
@ -69,6 +72,7 @@ namespace winPEAS.Info.ServicesInfo
{
Beaprint.PrintException(ex.Message);
}
return results;
}
@ -239,7 +243,7 @@ namespace winPEAS.Info.ServicesInfo
}
}
catch (Exception ex)
catch (Exception)
{
//Beaprint.PrintException(ex.Message)
}

View File

@ -76,30 +76,40 @@ namespace winPEAS.Info.SystemInfo
string dnsDomain = properties.DomainName;
const string query = "SELECT HotFixID FROM Win32_QuickFixEngineering";
var search = new ManagementObjectSearcher(query);
var collection = search.Get();
string hotfixes = "";
foreach (ManagementObject quickFix in collection)
hotfixes += quickFix["HotFixID"].ToString() + ", ";
results.Add("Hostname", strHostName);
if (dnsDomain.Length > 1) results.Add("Domain Name", dnsDomain);
results.Add("ProductName", ProductName);
results.Add("EditionID", EditionID);
results.Add("ReleaseId", ReleaseId);
results.Add("BuildBranch", BuildBranch);
results.Add("CurrentMajorVersionNumber", CurrentMajorVersionNumber);
results.Add("CurrentVersion", CurrentVersion);
results.Add("Architecture", arch);
results.Add("ProcessorCount", ProcessorCount);
results.Add("SystemLang", systemLang);
results.Add("KeyboardLang", myCurrentLanguage.Culture.EnglishName);
results.Add("TimeZone", timeZone.DisplayName);
results.Add("IsVirtualMachine", isVM.ToString());
results.Add("Current Time", now.ToString());
results.Add("HighIntegrity", isHighIntegrity.ToString());
results.Add("PartOfDomain", Checks.Checks.IsPartOfDomain.ToString());
results.Add("Hotfixes", hotfixes);
using (var search = new ManagementObjectSearcher(query))
{
using (var collection = search.Get())
{
string hotfixes = "";
foreach (ManagementObject quickFix in collection)
{
hotfixes += quickFix["HotFixID"].ToString() + ", ";
}
results.Add("Hostname", strHostName);
if (dnsDomain.Length > 1)
{
results.Add("Domain Name", dnsDomain);
}
results.Add("ProductName", ProductName);
results.Add("EditionID", EditionID);
results.Add("ReleaseId", ReleaseId);
results.Add("BuildBranch", BuildBranch);
results.Add("CurrentMajorVersionNumber", CurrentMajorVersionNumber);
results.Add("CurrentVersion", CurrentVersion);
results.Add("Architecture", arch);
results.Add("ProcessorCount", ProcessorCount);
results.Add("SystemLang", systemLang);
results.Add("KeyboardLang", myCurrentLanguage.Culture.EnglishName);
results.Add("TimeZone", timeZone.DisplayName);
results.Add("IsVirtualMachine", isVM.ToString());
results.Add("Current Time", now.ToString());
results.Add("HighIntegrity", isHighIntegrity.ToString());
results.Add("PartOfDomain", Checks.Checks.IsPartOfDomain.ToString());
results.Add("Hotfixes", hotfixes);
}
}
}
catch (Exception ex)
{
@ -153,11 +163,14 @@ namespace winPEAS.Info.SystemInfo
whitelistpaths = String.Join("\n ", RegistryHelper.GetRegValues("HKLM", @"SOFTWARE\Microsoft\Windows Defender\Exclusions\Paths").Keys);
using (ManagementObjectSearcher wmiData = new ManagementObjectSearcher(@"root\SecurityCenter2", "SELECT * FROM AntiVirusProduct"))
{
foreach (ManagementObject virusChecker in wmiData.Get())
using (var data = wmiData.Get())
{
results["Name"] = (string)virusChecker["displayName"];
results["ProductEXE"] = (string)virusChecker["pathToSignedProductExe"];
results["pathToSignedReportingExe"] = (string)virusChecker["pathToSignedReportingExe"];
foreach (ManagementObject virusChecker in data)
{
results["Name"] = (string)virusChecker["displayName"];
results["ProductEXE"] = (string)virusChecker["pathToSignedProductExe"];
results["pathToSignedReportingExe"] = (string)virusChecker["pathToSignedReportingExe"];
}
}
}
}

View File

@ -137,11 +137,16 @@ namespace winPEAS.Info.UserInfo
List<string> retList = new List<string>();
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_UserProfile WHERE Loaded = True");
foreach (ManagementObject user in searcher.Get())
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_UserProfile WHERE Loaded = True"))
{
string username = new SecurityIdentifier(user["SID"].ToString()).Translate(typeof(NTAccount)).ToString();
if (!username.Contains("NT AUTHORITY")) retList.Add(username);
using (var data = searcher.Get())
{
foreach (ManagementObject user in data)
{
string username = new SecurityIdentifier(user["SID"].ToString()).Translate(typeof(NTAccount)).ToString();
if (!username.Contains("NT AUTHORITY")) retList.Add(username);
}
}
}
}
catch (Exception ex)
@ -157,21 +162,27 @@ namespace winPEAS.Info.UserInfo
try
{
SelectQuery query = new SelectQuery("Win32_UserProfile");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject user in searcher.Get())
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
{
try
using (var data = searcher.Get())
{
string username = new SecurityIdentifier(user["SID"].ToString()).Translate(typeof(NTAccount)).ToString();
if (!username.Contains("NT AUTHORITY"))
foreach (ManagementObject user in data)
{
retList.Add(username);
try
{
string username = new SecurityIdentifier(user["SID"].ToString()).Translate(typeof(NTAccount)).ToString();
if (!username.Contains("NT AUTHORITY"))
{
retList.Add(username);
}
}
// user SID could not be translated, ignore
catch (Exception)
{
}
}
}
// user SID could not be translated, ignore
catch (Exception)
{
}
}
}
catch (Exception ex)
@ -195,18 +206,21 @@ namespace winPEAS.Info.UserInfo
SelectQuery query = new SelectQuery("Win32_UserAccount");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
{
foreach (ManagementObject envVar in searcher.Get())
using (var data = searcher.Get())
{
string username = (string)envVar["Name"];
username = username?.ToLower();
if (currentUsername != username)
foreach (ManagementObject envVar in data)
{
string userDirectory = Path.Combine(usersBaseDirectory, username);
string username = (string)envVar["Name"];
username = username?.ToLower();
if (Directory.Exists(userDirectory))
if (currentUsername != username)
{
result.Add(userDirectory.ToLower());
string userDirectory = Path.Combine(usersBaseDirectory, username);
if (Directory.Exists(userDirectory))
{
result.Add(userDirectory.ToLower());
}
}
}
}