- 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")) using (var searcher = new ManagementObjectSearcher(@"root\cimv2", "SELECT HotFixID FROM Win32_QuickFixEngineering"))
{ {
var hotFixes = searcher.Get(); using (var hotFixes = searcher.Get())
foreach (var hotFix in hotFixes)
{ {
var line = hotFix["HotFixID"].ToString().Remove(0, 2); foreach (var hotFix in hotFixes)
if (int.TryParse(line, out int kb))
{ {
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")) using (var searcher = new ManagementObjectSearcher(@"root\cimv2", "SELECT BuildNumber FROM Win32_OperatingSystem"))
{ {
var collection = searcher.Get(); using (var collection = searcher.Get())
foreach (var num in collection)
{ {
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); colors);
Beaprint.PrintLineSeparator(); Beaprint.PrintLineSeparator();
} }
catch (Exception e) { } catch (Exception) { }
} }
} }
else else
@ -272,7 +272,7 @@ namespace winPEAS.Checks
Beaprint.GoodPrint(" WSL - no installed Linux distributions found."); 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) foreach (var file in files)
{ {
FileAttributes attr = File.GetAttributes(file.FullPath); try
if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
{ {
List<string> dirRights = PermissionsHelper.GetPermissionsFolder(file.FullPath, Checks.CurrentUserSiDs, isOnlyWriteOrEquivalentCheck: true); FileAttributes attr = File.GetAttributes(file.FullPath);
if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
if (dirRights.Count > 0)
{ {
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}"); Beaprint.BadPrint($" {file.FullPath}");
} }
} }
catch (PathTooLongException ex) { } catch (PathTooLongException) { }
catch (Exception ex) catch (Exception)
{ {
// & other exceptions // & other exceptions
} }
@ -656,12 +662,14 @@ namespace winPEAS.Checks
@"c:\esupport", @"c:\esupport",
@"c:\perflogs", @"c:\perflogs",
@"c:\programdata", @"c:\programdata",
@"c:\program files(x86)", @"c:\program files (x86)",
@"c:\program files", @"c:\program files",
@"c:\windows", @"c:\windows",
@"c:\windows.old", @"c:\windows.old",
}; };
var currentUserDir = @$"{systemDrive}users\{Environment.GetEnvironmentVariable("USERNAME")}".ToLower();
var allowedExtensions = new HashSet<string>() var allowedExtensions = new HashSet<string>()
{ {
".bat", ".bat",
@ -673,16 +681,31 @@ namespace winPEAS.Checks
foreach (var file in files) foreach (var file in files)
{ {
if (file.Extension != null && allowedExtensions.Contains(file.Extension.ToLower())) try
{ {
// check the file permissions if (file.Extension != null && allowedExtensions.Contains(file.Extension.ToLower()))
List<string> fileRights = PermissionsHelper.GetPermissionsFile(file.FullPath, Checks.CurrentUserSiDs, isOnlyWriteOrEquivalentCheck: true);
if (fileRights.Count > 0)
{ {
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; return true;
} }
} }
catch (Exception e) catch (Exception)
{ {
// unauthorized access ?
} }
return false; return false;

View File

@ -83,6 +83,10 @@ namespace winPEAS.Helpers.Search
{ {
return new List<FileInfo>(); return new List<FileInfo>();
} }
catch (Exception)
{
return new List<FileInfo>();
}
List<FileInfo> result = new List<FileInfo>(); List<FileInfo> result = new List<FileInfo>();
@ -104,6 +108,9 @@ namespace winPEAS.Helpers.Search
catch (DirectoryNotFoundException) catch (DirectoryNotFoundException)
{ {
} }
catch (Exception)
{
}
return result; return result;
} }
@ -151,6 +158,10 @@ namespace winPEAS.Helpers.Search
{ {
return new List<DirectoryInfo>(); return new List<DirectoryInfo>();
} }
catch (Exception)
{
return new List<DirectoryInfo>();
}
return GetStartDirectories(directories[0].FullName, files, pattern); 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", "" } { "isUnquotedSpaced", "" }
}); });
} }
catch (Exception e) catch (Exception)
{ {
} }
} }
@ -422,24 +422,25 @@ namespace winPEAS.Info.ApplicationInfo
try try
{ {
SelectQuery query = new SelectQuery("Win32_StartupCommand"); 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(); foreach (ManagementObject startup in win32_startup)
command = Environment.ExpandEnvironmentVariables(string.Format("{0}", command));
string filepath = MyUtils.GetExecutableFromPath(command);
if (!string.IsNullOrEmpty(filepath))
{ {
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); string filepathCleaned = filepath.Replace("'", "").Replace("\"", "");
results.Add(new Dictionary<string, string>()
try
{
string folder = Path.GetDirectoryName(filepathCleaned);
results.Add(new Dictionary<string, string>()
{ {
{"Reg", ""}, {"Reg", ""},
{"RegKey", "From WMIC"}, {"RegKey", "From WMIC"},
@ -457,9 +458,10 @@ namespace winPEAS.Info.ApplicationInfo
}, },
{"isUnquotedSpaced", MyUtils.CheckQuoteAndSpace(command).ToString()} {"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>>(); List<Dictionary<string, string>> results = new List<Dictionary<string, string>>();
try try
{ {
using (ManagementObjectSearcher wmiData = new ManagementObjectSearcher(@"root\standardcimv2", "SELECT * FROM MSFT_DNSClientCache"))
ManagementObjectSearcher wmiData = new ManagementObjectSearcher(@"root\standardcimv2", "SELECT * FROM MSFT_DNSClientCache");
ManagementObjectCollection data = wmiData.Get();
foreach (ManagementObject result in data)
{ {
Dictionary<string, string> dnsEntry = new Dictionary<string, string>(); using (ManagementObjectCollection data = wmiData.Get())
string entry = $"{result["Entry"]}"; {
string name = $"{result["Name"]}"; foreach (ManagementObject result in data)
string dataDns = $"{result["Data"]}"; {
dnsEntry["Entry"] = (entry.Length > 33) ? "..." + result["Entry"].ToString().Substring(entry.Length - 32) : entry; Dictionary<string, string> dnsEntry = new Dictionary<string, string>();
dnsEntry["Name"] = (name.Length > 33) ? "..." + name.Substring(name.Length - 32) : name; string entry = $"{result["Entry"]}";
dnsEntry["Data"] = (dataDns.Length > 33) ? "..." + dataDns.Substring(dataDns.Length - 32) : dataDns; string name = $"{result["Name"]}";
results.Add(dnsEntry); 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) catch (ManagementException ex) when (ex.ErrorCode == ManagementStatus.InvalidNamespace)

View File

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

View File

@ -76,30 +76,40 @@ namespace winPEAS.Info.SystemInfo
string dnsDomain = properties.DomainName; string dnsDomain = properties.DomainName;
const string query = "SELECT HotFixID FROM Win32_QuickFixEngineering"; 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); using (var search = new ManagementObjectSearcher(query))
if (dnsDomain.Length > 1) results.Add("Domain Name", dnsDomain); {
results.Add("ProductName", ProductName); using (var collection = search.Get())
results.Add("EditionID", EditionID); {
results.Add("ReleaseId", ReleaseId); string hotfixes = "";
results.Add("BuildBranch", BuildBranch); foreach (ManagementObject quickFix in collection)
results.Add("CurrentMajorVersionNumber", CurrentMajorVersionNumber); {
results.Add("CurrentVersion", CurrentVersion); hotfixes += quickFix["HotFixID"].ToString() + ", ";
results.Add("Architecture", arch); }
results.Add("ProcessorCount", ProcessorCount);
results.Add("SystemLang", systemLang); results.Add("Hostname", strHostName);
results.Add("KeyboardLang", myCurrentLanguage.Culture.EnglishName); if (dnsDomain.Length > 1)
results.Add("TimeZone", timeZone.DisplayName); {
results.Add("IsVirtualMachine", isVM.ToString()); results.Add("Domain Name", dnsDomain);
results.Add("Current Time", now.ToString()); }
results.Add("HighIntegrity", isHighIntegrity.ToString()); results.Add("ProductName", ProductName);
results.Add("PartOfDomain", Checks.Checks.IsPartOfDomain.ToString()); results.Add("EditionID", EditionID);
results.Add("Hotfixes", hotfixes); 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) 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); whitelistpaths = String.Join("\n ", RegistryHelper.GetRegValues("HKLM", @"SOFTWARE\Microsoft\Windows Defender\Exclusions\Paths").Keys);
using (ManagementObjectSearcher wmiData = new ManagementObjectSearcher(@"root\SecurityCenter2", "SELECT * FROM AntiVirusProduct")) 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"]; foreach (ManagementObject virusChecker in data)
results["ProductEXE"] = (string)virusChecker["pathToSignedProductExe"]; {
results["pathToSignedReportingExe"] = (string)virusChecker["pathToSignedReportingExe"]; 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>(); List<string> retList = new List<string>();
try try
{ {
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_UserProfile WHERE Loaded = True"); using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_UserProfile WHERE Loaded = True"))
foreach (ManagementObject user in searcher.Get())
{ {
string username = new SecurityIdentifier(user["SID"].ToString()).Translate(typeof(NTAccount)).ToString(); using (var data = searcher.Get())
if (!username.Contains("NT AUTHORITY")) retList.Add(username); {
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) catch (Exception ex)
@ -157,21 +162,27 @@ namespace winPEAS.Info.UserInfo
try try
{ {
SelectQuery query = new SelectQuery("Win32_UserProfile"); 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(); foreach (ManagementObject user in data)
if (!username.Contains("NT AUTHORITY"))
{ {
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) catch (Exception ex)
@ -195,18 +206,21 @@ namespace winPEAS.Info.UserInfo
SelectQuery query = new SelectQuery("Win32_UserAccount"); SelectQuery query = new SelectQuery("Win32_UserAccount");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query)) using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
{ {
foreach (ManagementObject envVar in searcher.Get()) using (var data = searcher.Get())
{ {
string username = (string)envVar["Name"]; foreach (ManagementObject envVar in data)
username = username?.ToLower();
if (currentUsername != username)
{ {
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());
}
} }
} }
} }