hacktricks/pentesting-web/race-condition.md

302 lines
17 KiB
Markdown
Raw Normal View History

2022-08-31 22:35:39 +00:00
# Race Condition
2022-04-28 16:01:33 +00:00
<figure><img src="../.gitbook/assets/image (3) (1) (1) (1) (1).png" alt=""><figcaption></figcaption></figure>
2022-08-31 22:35:39 +00:00
\
2022-09-01 23:40:55 +00:00
Use [**Trickest**](https://trickest.com/?utm\_campaign=hacktrics\&utm\_medium=banner\&utm\_source=hacktricks) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\
2022-08-31 22:35:39 +00:00
Get Access Today:
{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %}
2022-04-28 16:01:33 +00:00
<details>
2023-12-31 01:25:17 +00:00
<summary><strong>Learn AWS hacking from zero to hero with</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
2022-04-28 16:01:33 +00:00
2023-12-31 01:25:17 +00:00
Other ways to support HackTricks:
* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
2022-09-30 10:43:59 +00:00
* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
2023-12-31 01:25:17 +00:00
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.**
* **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
2022-04-28 16:01:33 +00:00
</details>
2024-02-06 03:10:38 +00:00
{% hint style="warning" %}
For obtaining a deep understanding of this technique check the original report in [https://portswigger.net/research/smashing-the-state-machine](https://portswigger.net/research/smashing-the-state-machine)
{% endhint %}
2024-02-06 03:10:38 +00:00
## Enhancing Race Condition Attacks
2024-02-06 03:10:38 +00:00
The main hurdle in taking advantage of race conditions is making sure that multiple requests are handled at the same time, with **very little difference in their processing times—ideally, less than 1ms**.
2024-02-06 03:10:38 +00:00
Here you can find some techniques for Synchronizing Requests:
2024-02-06 03:10:38 +00:00
#### HTTP/2 Single-Packet Attack vs. HTTP/1.1 Last-Byte Synchronization
2024-02-06 03:10:38 +00:00
- **HTTP/2**: Supports sending two requests over a single TCP connection, reducing network jitter impact. However, due to server-side variations, two requests may not suffice for a consistent race condition exploit.
- **HTTP/1.1 'Last-Byte Sync'**: Enables the pre-sending of most parts of 20-30 requests, withholding a small fragment, which is then sent together, achieving simultaneous arrival at the server.
2024-02-06 03:10:38 +00:00
**Preparation for Last-Byte Sync** involves:
1. Sending headers and body data minus the final byte without ending the stream.
2. Pausing for 100ms post-initial send.
3. Disabling TCP_NODELAY to utilize Nagle's algorithm for batching final frames.
4. Pinging to warm up the connection.
2024-02-06 03:10:38 +00:00
The subsequent sending of withheld frames should result in their arrival in a single packet, verifiable via Wireshark. This method does not apply to static files, which are not typically involved in RC attacks.
2024-02-06 03:10:38 +00:00
### Adapting to Server Architecture
2024-02-06 03:10:38 +00:00
Understanding the target's architecture is crucial. Front-end servers might route requests differently, affecting timing. Preemptive server-side connection warming, through inconsequential requests, might normalize request timing.
2024-02-06 03:10:38 +00:00
#### Handling Session-Based Locking
2024-02-06 03:10:38 +00:00
Frameworks like PHP's session handler serialize requests by session, potentially obscuring vulnerabilities. Utilizing different session tokens for each request can circumvent this issue.
2024-02-06 03:10:38 +00:00
#### Overcoming Rate or Resource Limits
2024-02-06 03:10:38 +00:00
If connection warming is ineffective, triggering web servers' rate or resource limit delays intentionally through a flood of dummy requests might facilitate the single-packet attack by inducing a server-side delay conducive to race conditions.
2024-02-06 03:10:38 +00:00
## Attack Examples
* **Tubo Intruder - HTTP2 single-packet attack (1 endpoint)**: You can send the request to **Turbo intruder** (`Extensions` -> `Turbo Intruder` -> `Send to Turbo Intruder`), you can change in the request the value you want to brute force for **`%s`** like in `csrf=Bn9VQB8OyefIs3ShR2fPESR0FzzulI1d&username=carlos&password=%s` and then select the **`examples/race-single-packer-attack.py`** from the drop down:
<figure><img src="../.gitbook/assets/image (4) (1) (1) (1) (1) (1).png" alt=""><figcaption></figcaption></figure>
If you are going to **send different values**, you could modify the code with this one that uses a wordlist from the clipboard:
```python
passwords = wordlists.clipboard
for password in passwords:
engine.queue(target.req, password, gate='race1')
```
{% hint style="warning" %}
If the web doesn't support HTTP2 (only HTTP1.1) use `Engine.THREADED` or `Engine.BURP` instead of `Engine.BURP2`.
{% endhint %}
* **Tubo Intruder - HTTP2 single-packet attack (Several endpoints)**: In case you need to send a request to 1 endpoint and then multiple to other endpoints to trigger the RCE, you can change the `race-single-packet-attack.py` script with something like:
```python
def queueRequests(target, wordlists):
engine = RequestEngine(endpoint=target.endpoint,
concurrentConnections=1,
engine=Engine.BURP2
)
# Hardcode the second request for the RC
confirmationReq = '''POST /confirm?token[]= HTTP/2
Host: 0a9c00370490e77e837419c4005900d0.web-security-academy.net
Cookie: phpsessionid=MpDEOYRvaNT1OAm0OtAsmLZ91iDfISLU
Content-Length: 0
'''
# For each attempt (20 in total) send 50 confirmation requests.
for attempt in range(20):
currentAttempt = str(attempt)
username = 'aUser' + currentAttempt
# queue a single registration request
engine.queue(target.req, username, gate=currentAttempt)
# queue 50 confirmation requests - note that this will probably sent in two separate packets
for i in range(50):
engine.queue(confirmationReq, gate=currentAttempt)
# send all the queued requests for this attempt
engine.openGate(currentAttempt)
```
* It's also available in **Repeater** via the new '**Send group in parallel**' option in Burp Suite.
* For **limit-overrun** you could just add the **same request 50 times** in the group.
* For **connection warming**, you could **add** at the **beginning** of the **group** some **requests** to some non static part of the web server.
* For **delaying** the process **between** processing **one request and another** in a 2 substates steps, you could **add extra requests between** both requests.
* For a **multi-endpoint** RC you could start sending the **request** that **goes to the hidden state** and then **50 requests** just after it that **exploits the hidden state**.
<figure><img src="../.gitbook/assets/image (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1).png" alt=""><figcaption></figcaption></figure>
### Raw BF
Before the previous research these were some payloads used which just tried to send the packets as fast as possible to cause a RC.
* **Repeater:** Check the examples from the previous section.
* **Intruder**: Send the **request** to **Intruder**, set the **number of threads** to **30** inside the **Options menu and,** select as payload **Null payloads** and generate **30.**
* **Turbo Intruder**
```python
def queueRequests(target, wordlists):
engine = RequestEngine(endpoint=target.endpoint,
concurrentConnections=5,
requestsPerConnection=1,
pipeline=False
)
a = ['Session=<session_id_1>','Session=<session_id_2>','Session=<session_id_3>']
for i in range(len(a)):
engine.queue(target.req,a[i], gate='race1')
# open TCP connections and send partial requests
engine.start(timeout=10)
engine.openGate('race1')
engine.complete(timeout=60)
def handleResponse(req, interesting):
table.add(req)
```
* **Python - asyncio**
2022-10-11 22:51:42 +00:00
```python
import asyncio
import httpx
async def use_code(client):
resp = await client.post(f'http://victim.com', cookies={"session": "asdasdasd"}, data={"code": "123123123"})
return resp.text
async def main():
async with httpx.AsyncClient() as client:
tasks = []
for _ in range(20): #20 times
tasks.append(asyncio.ensure_future(use_code(client)))
# Get responses
results = await asyncio.gather(*tasks, return_exceptions=True)
# Print results
for r in results:
print(r)
# Async2sync sleep
await asyncio.sleep(0.5)
print(results)
asyncio.run(main())
```
## **RC Methodology**
### Limit-overrun / TOCTOU
This is the most basic type of race condition where **vulnerabilities** that **appear** in places that **limit the number of times you can perform an action**. Like using the same discount code in a web store several times. A very easy example can be found in [**this report**](https://medium.com/@pravinponnusamy/race-condition-vulnerability-found-in-bug-bounty-program-573260454c43) or in [**this bug**](https://hackerone.com/reports/759247)**.**
There are many variations of this kind of attack, including:
* Redeeming a gift card multiple times
* Rating a product multiple times
* Withdrawing or transferring cash in excess of your account balance
* Reusing a single CAPTCHA solution
* Bypassing an anti-brute-force rate limit
### **Hidden substates**
2024-02-06 03:10:38 +00:00
Exploiting complex race conditions often involves taking advantage of brief opportunities to interact with hidden or **unintended machine substates**. Heres how to approach this:
2024-02-06 03:10:38 +00:00
1. **Identify Potential Hidden Substates**
- Start by pinpointing endpoints that modify or interact with critical data, such as user profiles or password reset processes. Focus on:
- **Storage**: Prefer endpoints that manipulate server-side persistent data over those handling data client-side.
- **Action**: Look for operations that alter existing data, which are more likely to create exploitable conditions compared to those that add new data.
- **Keying**: Successful attacks usually involve operations keyed on the same identifier, e.g., username or reset token.
2024-02-06 03:10:38 +00:00
2. **Conduct Initial Probing**
- Test the identified endpoints with race condition attacks, observing for any deviations from expected outcomes. Unexpected responses or changes in application behavior can signal a vulnerability.
2024-02-06 03:10:38 +00:00
3. **Demonstrate the Vulnerability**
- Narrow down the attack to the minimal number of requests needed to exploit the vulnerability, often just two. This step might require multiple attempts or automation due to the precise timing involved.
### Time Sensitive Attacks
2024-02-06 03:10:38 +00:00
Precision in timing requests can reveal vulnerabilities, especially when predictable methods like timestamps are used for security tokens. For instance, generating password reset tokens based on timestamps could allow identical tokens for simultaneous requests.
2024-02-06 03:10:38 +00:00
**To Exploit:**
- Use precise timing, like a single packet attack, to make concurrent password reset requests. Identical tokens indicate a vulnerability.
2024-02-06 03:10:38 +00:00
**Example:**
- Request two password reset tokens at the same time and compare them. Matching tokens suggest a flaw in token generation.
2024-02-06 03:10:38 +00:00
**Check this [PortSwigger Lab](https://portswigger.net/web-security/race-conditions/lab-race-conditions-exploiting-time-sensitive-vulnerabilities) to try this.**
## Hidden substates case studies
### Pay & add an Item
2024-02-06 03:10:38 +00:00
Check this [**PortSwigger Lab**](https://portswigger.net/web-security/logic-flaws/examples/lab-logic-flaws-insufficient-workflow-validation) to see how to **pay** in a store and **add an extra** item you that **won't need to pay for it**.
### Confirm other emails
The idea is to **verify an email address and change it to a different one at the same time** to find out if the platform verifies the new one changed.
### Change email to 2 emails addresses Cookie based
2024-02-06 03:10:38 +00:00
According to [**this research**](https://portswigger.net/research/smashing-the-state-machine) Gitlab was vulnerable to a takeover this way because it might **send** the **email verification token of one email to the other email**.
2024-02-06 03:10:38 +00:00
**Check this [PortSwigger Lab](https://portswigger.net/web-security/race-conditions/lab-race-conditions-single-endpoint) to try this.**
### Hidden Database states / Confirmation Bypass
2024-02-06 03:10:38 +00:00
If **2 different writes** are used to **add** **information** inside a **database**, there is a small portion of time where **only the first data has been written** inside the database. For example, when creating a user the **username** and **password** might be **written** and **then the token** to confirm the newly created account is written. This means that for a small time the **token to confirm an account is null**.
Therefore **registering an account and sending several requests with an empty token** (`token=` or `token[]=` or any other variation) to confirm the account right away could allow to c**onfirm an account** where you don't control the email.
2024-02-06 03:10:38 +00:00
**Check this [PortSwigger Lab](https://portswigger.net/web-security/race-conditions/lab-race-conditions-partial-construction) to try this.**
### Bypass 2FA
2024-02-06 03:10:38 +00:00
The following pseudo-code is vulnerable to race condition because in a very small time the **2FA is not enforced** while the session is created:
```python
session['userid'] = user.userid
if user.mfa_enabled:
session['enforce_mfa'] = True
# generate and send MFA code to user
# redirect browser to MFA code entry form
```
### OAuth2 eternal persistence
2021-11-30 16:46:07 +00:00
There are several [**OAUth providers**](https://en.wikipedia.org/wiki/List\_of\_OAuth\_providers). Theses services will allow you to create an application and authenticate users that the provider has registered. In order to do so, the **client** will need to **permit your application** to access some of their data inside of the **OAUth provider**.\
2024-02-06 03:10:38 +00:00
So, until here just a common login with google/linkedin/github... where you are prompted with a page saying: "_Application \<InsertCoolName> wants to access you information, do you want to allow it?_"
2022-08-31 22:35:39 +00:00
#### Race Condition in `authorization_code`
2022-10-11 22:51:42 +00:00
The **problem** appears when you **accept it** and automatically sends an **`authorization_code`** to the malicious application. Then, this **application abuses a Race Condition in the OAUth service provider to generate more that one AT/RT** (_Authentication Token/Refresh Token_) from the **`authorization_code`** for your account. Basically, it will abuse the fact that you have accept the application to access your data to **create several accounts**. Then, if you **stop allowing the application to access your data one pair of AT/RT will be deleted, but the other ones will still be valid**.
2022-08-31 22:35:39 +00:00
#### Race Condition in `Refresh Token`
2022-04-05 22:24:52 +00:00
Once you have **obtained a valid RT** you could try to **abuse it to generate several AT/RT** and **even if the user cancels the permissions** for the malicious application to access his data, **several RTs will still be valid.**
## **RC in WebSockets**
In [**WS\_RaceCondition\_PoC**](https://github.com/redrays-io/WS\_RaceCondition\_PoC) you can find a PoC in Java to send websocket messages in **parallel** to abuse **Race Conditions also in Web Sockets**.
2022-08-31 22:35:39 +00:00
## References
* [https://hackerone.com/reports/759247](https://hackerone.com/reports/759247)
* [https://pandaonair.com/2020/06/11/race-conditions-exploring-the-possibilities.html](https://pandaonair.com/2020/06/11/race-conditions-exploring-the-possibilities.html)
* [https://hackerone.com/reports/55140](https://hackerone.com/reports/55140)
* [https://portswigger.net/research/smashing-the-state-machine](https://portswigger.net/research/smashing-the-state-machine)
* [https://portswigger.net/web-security/race-conditions](https://portswigger.net/web-security/race-conditions)
2022-04-28 16:01:33 +00:00
<details>
2023-12-31 01:25:17 +00:00
<summary><strong>Learn AWS hacking from zero to hero with</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
2022-04-28 16:01:33 +00:00
2023-12-31 01:25:17 +00:00
Other ways to support HackTricks:
* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
2022-09-30 10:43:59 +00:00
* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
2023-12-31 01:25:17 +00:00
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.**
* **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
2022-04-28 16:01:33 +00:00
</details>
<figure><img src="../.gitbook/assets/image (3) (1) (1) (1) (1).png" alt=""><figcaption></figcaption></figure>
2022-08-31 22:35:39 +00:00
\
2022-09-01 23:40:55 +00:00
Use [**Trickest**](https://trickest.com/?utm\_campaign=hacktrics\&utm\_medium=banner\&utm\_source=hacktricks) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\
2022-08-31 22:35:39 +00:00
Get Access Today:
2022-04-28 16:01:33 +00:00
2022-08-31 22:35:39 +00:00
{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %}