Sitemap
appsecwarrior

appsecwarrior

We offer free services including resume guidance, mock interviews, job referrals, and interview preparation. All of these resources are always free.

Press enter or click to view image in full size

Race Condition Vulnerability

20 min readApr 12, 2025

--

A Race Condition is a software vulnerability that occurs when the behavior of a system depends on the sequence or timing of uncontrollable events, such as thread execution order. If multiple threads or processes access shared resources concurrently without proper synchronization, it can lead to unexpected and potentially harmful outcomes.

A Race Condition occurs when:

  • Two or more threads/processes access shared data or resources simultaneously.
  • The outcome of the operation depends on the order of execution.
  • Proper synchronization mechanisms (e.g., locks, semaphores) are not implemented.

This can lead to:

  • Data corruption.
  • Unauthorized access.
  • Security breaches (e.g., privilege escalation, bypassing authentication).

Real-Time Scenarios

  1. Banking Systems:
  • Two transactions attempt to withdraw money from the same account simultaneously, leading to a negative balance.

2. E-commerce:

  • Multiple users try to purchase the last item in stock, resulting in overselling.

3. Authentication Systems:

A user exploits a race condition to bypass authentication or gain unauthorized access.

4. File Systems:

  • Two processes attempt to write to the same file simultaneously, causing data corruption.

How Race Conditions Happen

  1. Lack of Synchronization:
  • Shared resources are accessed without locks or semaphores.

2. Improper Thread Management:

  • Threads are not adequately managed, leading to unpredictable execution order.

3. Time-of-Check to Time-of-Use (TOCTOU):

  • The state of a resource changes between when it is checked and when it is used.

Methodology to Find Race Conditions

  1. Code Review:
  • Look for shared resources (e.g., variables, files, databases) accessed by multiple threads/processes.
  • Check for missing or improper synchronization mechanisms.

2. Testing:

  • Perform stress testing to simulate concurrent access.
  • Use tools to automate testing and detect race conditions.

3. Dynamic Analysis:

  • Monitor the application during runtime to identify unexpected behavior.

Tools to Detect Race Conditions

  1. ThreadSanitizer- Detects data races in C/C++ and Go programs.
  2. Helgrind- Part of Valgrind, detects race conditions in multithreaded applications.
  3. RaceFuzzer- Detects race conditions in web applications.
  4. AFL (American Fuzzy Lop)- Fuzz testing tool to identify race conditions.
  5. Burp Suite- Can be used to manually test for race conditions in web applications.

How to Exploit Race Conditions

  1. Time-of-Check to Time-of-Use (TOCTOU):
  • Exploit the delay between checking a condition and using the result.
  • Example: Changing a file’s permissions between the check and access.

2. Concurrent Requests:

  • Send multiple requests simultaneously to exploit a lack of synchronization.
  • Example: Sending multiple login requests to bypass authentication.

Mitigation Techniques

  1. Synchronization Mechanisms:
  • Use locks, semaphores, or mutexes to ensure only one thread accesses a resource at a time.

2. Atomic Operations:

  • Use atomic operations to ensure that critical sections are executed without interruption.

3. Thread-Safe Libraries:

  • Use libraries and frameworks that are designed to handle concurrency safely.

4. Avoid Shared Resources:

  • Minimize the use of shared resources where possible.

5. Input Validation:

  • Validate inputs to prevent malicious exploitation of race conditions.

6. Rate Limiting:

  • Implement rate limiting to prevent abuse of concurrent requests.

Understanding and Mitigating TOCTOU Vulnerabilities in C# Applications

A good article to read.

Types of Race Conditions

1. Time-of-Check to Time-of-Use (TOCTOU)

  • Description:
  • A race condition where the state of a resource changes between the time it is checked and the time it is used.
  • Commonly found in file systems, authentication systems, and privilege escalation scenarios.
  • Example:
  • A program checks if a file has write permissions, but before it writes to the file, an attacker changes the file’s permissions.

2. Data Races

  • Description:
  • Occurs when two or more threads access shared data concurrently, and at least one of the accesses is a write operation.
  • Leads to unpredictable behavior and data corruption.
  • Example:
  • Two threads increment a shared counter simultaneously, resulting in an incorrect final value.

3. Resource Exhaustion

  • Description:
  • A race condition where multiple processes or threads compete for limited resources (e.g., memory, file handles, database connections).
  • Can lead to denial of service (DoS) or system crashes.
  • Example:
  • Multiple threads open database connections simultaneously, exhausting the connection pool.

4. Privilege Escalation

  • Description:
  • A race condition that allows an attacker to gain elevated privileges by exploiting timing issues in privilege checks.
  • Example:
  • An attacker exploits a race condition in a setuid program to execute code with root privileges.

5. Authentication Bypass

  • Description:
  • A race condition in authentication systems that allows an attacker to bypass security checks.
  • Example:
  • An attacker sends multiple login requests simultaneously, causing the system to skip authentication checks.

6. Business Logic Race Conditions

  • Description:
  • Race conditions that affect the business logic of an application, leading to financial losses or data inconsistencies.
  • Example:
  • In an e-commerce application, two users purchase the last item in stock simultaneously, resulting in overselling.

7. File System Race Conditions

  • Description:
  • Race conditions that occur when multiple processes or threads access or modify files simultaneously.
  • Example:
  • Two processes attempt to write to the same file, causing data corruption.

8. Network Race Conditions

  • Description:
  • Race conditions that occur in networked systems due to timing issues in message handling or resource allocation.
  • Example:
  • Two clients send requests to a server simultaneously, causing the server to mishandle the requests.

9. Memory Race Conditions

  • Description:
  • Race conditions that occur when multiple threads access shared memory without proper synchronization.
  • Example:
  • Two threads modify the same memory location simultaneously, leading to undefined behavior.

10. UI Race Conditions

  • Description:
  • Race conditions in user interfaces that lead to inconsistent or unexpected behavior.
  • Example:
  • Two users interact with the same UI element simultaneously, causing the application to crash or behave unpredictably.

11. Database Race Conditions

  • Description:
  • Race conditions occur when multiple transactions access or modify database records simultaneously.
  • Example:
  • Two transactions attempt to update the same database record, leading to inconsistent data.

12. Concurrency Bugs

  • Description:
  • A broad category of race conditions that occur in concurrent systems due to improper synchronization.
  • Example:
  • Deadlocks, livelocks, and starvation caused by race conditions.

13. Signal Handling Race Conditions

  • Description:
  • Race conditions that occur in signal handling, where the timing of signals affects program behavior.
  • Example:
  • A signal interrupts a critical section of code, leading to inconsistent state.

14. Cache-Based Race Conditions

  • Description:
  • Race conditions that occur due to inconsistencies between cached data and the actual state of the system.
  • Example:
  • A cached value is used after it has been modified by another process, leading to incorrect behavior.

15. API Race Conditions

  • Description:
  • Race conditions occur when multiple clients interact with an API simultaneously.
  • Example:
  • Two clients send requests to an API at the same time, causing the server to mishandle the requests.

Summary of Types

  1. TOCTOU- State changes between check and use.
  2. Data Races-Concurrent access to shared data with at least one write operation.
  3. Resource Exhaustion- Competition for limited resources.
  4. Privilege Escalation- Exploiting timing issues to gain elevated privileges.
  5. Authentication Bypass- Bypassing security checks due to timing issues.
  6. Business Logic- Affecting business logic, leading to financial or data inconsistencies.
  7. File System- Concurrent access to files causes corruption or inconsistencies.
  8. Network- Timing issues in networked systems.
  9. Memory- Concurrent access to shared memory.
  10. UI- Inconsistent behavior in user interfaces.
  11. Database- Concurrent transactions leading to inconsistent data.
  12. Concurrency Bugs-Deadlocks, livelocks, and starvation.
  13. Signal Handling- Timing issues in signal handling.
  14. Cache-Based-Inconsistencies between cached data and actual state.
  15. API-Mishandling of concurrent API requests.

Practical — labs from Portswigger

Note

Solving this lab requires Burp Suite 2023.9 or higher. You should also use the latest version of the Turbo Intruder, which is available from the BApp Store.

1. Lab: Limit overrun race conditions

This lab’s purchasing flow contains a race condition that enables you to purchase items for an unintended price.

Get appsecwarrior’s stories in your inbox

Join Medium for free to get updates from this writer.

To solve the lab, successfully purchase a Lightweight L33t Leather Jacket.

You can log in to your account with the following credentials: wiener:peter.

As usual, we log into the application using the provided credentials.

Press enter or click to view image in full size
Press enter or click to view image in full size
Press enter or click to view image in full size
a. Lab Home Page b. we login with credentials c. after successful login

We added a leather jacket to our cart, and when we visited the cart, we noticed that we had a balance of $50. However, the price of the jacket is $1,337. We have a promo code, “promo20,” that we can use; but after applying the promo code, we still need an additional $1,069.60 to complete the purchase.

Press enter or click to view image in full size
Press enter or click to view image in full size
Press enter or click to view image in full size
a. Product page b. cart page c. price after promo applied

We will now navigate to the Burp Suite history and send the coupon request (POST) to the Repeater. As shown in diagram B, the request takes 212 milliseconds to complete. We can take advantage of this time to apply multiple coupons.

Press enter or click to view image in full size
Press enter or click to view image in full size
a. coupon request b. response of crquest

We attempted to request duplicates in multiples of 5 until we succeeded. We used the “send group in parallel” option from the request send dropdown. After several failed attempts, we finally achieved success.

Press enter or click to view image in full size
Press enter or click to view image in full size
a. 5 coupon request b. cart price got manipulated
Press enter or click to view image in full size
Press enter or click to view image in full size
c. 35 Coupon request d. we got success for price manipulation

We purchased the product for $15 and completed the laboratory work.

Press enter or click to view image in full size
lab solved

2. Lab: Bypassing rate limits via race conditions

This lab’s login mechanism uses rate limiting to defend against brute-force attacks. However, this can be bypassed due to a race condition.

To solve the lab:

  1. Work out how to exploit the race condition to bypass the rate limit.
  2. Successfully brute-force the password for the user carlos.
  3. Log in and access the admin panel.
  4. Delete the user carlos.

You can log in to your account with the following credentials: wiener:peter.

You should use the following list of potential passwords:

123123
abc123
football
monkey
letmein
shadow
master
666666
qwertyuiop
123321
mustang
123456
password
12345678
qwerty
123456789
12345
1234
111111
1234567
dragon
1234567890
michael
x654321
superman
1qaz2wsx
baseball
7777777
121212
000000

Note

Solving this lab requires Burp Suite 2023.9 or higher. You should also use the latest version of the Turbo Intruder, which is available from the BApp Store.

You have a time limit of 15 mins. If you don’t solve the lab within the time limit, you can reset the lab. However, Carlos’s password changes each time.

as usual we loginto lab with credentials and we see homepage having timer of 15 min to solved the lab.As usual, we log into the lab with our credentials, and we see the homepage displaying a timer of 15 minutes to solve the lab.

Press enter or click to view image in full size
Press enter or click to view image in full size
a. lab home page b. after login page

we capture the traffic in burp suite and go to history tab and send login We sent a POST request to the repeater tab to intentionally check the rate limit, as shown in the screenshot. Next, we used the Turbo Intruder extension to conduct the attack because the normal Intruder tool lacks the necessary features and does not allow scripting.

Press enter or click to view image in full size
Press enter or click to view image in full size
a. Log In request b. repeater response
Press enter or click to view image in full size
Press enter or click to view image in full size
c. Wrong login attempt d. use of turbo extension

We have now modified the script for brute force attacks. Remember to select the field where you need to perform the attack at the time the request is sent to Turbo Intruder. In the screenshot below, you can see that we added the word list provided by the lab and changed the gate value to “1.” We successfully obtained the password for Carlos.

Press enter or click to view image in full size
Press enter or click to view image in full size
a. Turbo Script b. output of intruder

Next, we will log in using Carlos's credentials and simply delete the Carlos user and lab. That should solve the issue.

Press enter or click to view image in full size
Press enter or click to view image in full size
Press enter or click to view image in full size
a. login with carlos credentials b. carlos login page c. delete the user to solve lab

3. Lab: Multi-endpoint race conditions

This lab’s purchasing flow contains a race condition that enables you to purchase items for an unintended price.

To solve the lab, successfully purchase a Lightweight L33t Leather Jacket.

You can log into your account with the following credentials: wiener:peter.

As usual, we log in to the lab with our credentials. We have a $100 credit, and we need to buy a jacket as we did previously. However, we need to perform the same operation with multiple endpoints.

Press enter or click to view image in full size
Press enter or click to view image in full size
a. Home page b. User profile

We visit the history tab and select these two requests to perform operations on them. We already have a coupon code which we buy.

Press enter or click to view image in full size
Press enter or click to view image in full size
a. cart request b. cart checkout request

Now we will add a jacket to the cart and perform a parallel attack on two requests as a group.

Press enter or click to view image in full size
cart page

As you can see, we successfully bought a jacket with the help of a coupon code request due to a race condition, and we solved the lab.

Press enter or click to view image in full size
lab solved

4. Lab: Single-endpoint race conditions

This lab’s email change feature contains a race condition that enables you to associate an arbitrary email address with your account.

Someone with the address carlos@ginandjuice.shop has a pending invite to be an administrator for the site, but they have not yet created an account. Therefore, any user who successfully claims this address will automatically inherit admin privileges.

To solve the lab:

  1. Identify a race condition that lets you claim an arbitrary email address.
  2. Change your email address to carlos@ginandjuice.shop.
  3. Access the admin panel.
  4. Delete the user carlos

You can log in to your own account with the following credentials: wiener:peter.

You also have access to an email client, where you can view all emails sent to @exploit-<YOUR-EXPLOIT-SERVER-ID>.exploit-server.net addresses.

Press enter or click to view image in full size
Press enter or click to view image in full size
Press enter or click to view image in full size
a. home page b. User page c. user mailbox

As usual, we log into the application with credentials. we are sending parallel requests with different values to a single end point can sometimes trigger powerful race conditions consider a password reset mechanism that stores the user ID and the reset token in the user session in this scenario sending two parallel password reset requests from the same session but with two different usernames could potentially cause the following Collision so we have this below screenshot which is showing two attempted password resets one is from an attacker and one is from a victim and you can see that these get mixed up due to this race window so that essentially we get halfway through setting up the session variables for the attacker and then the victims comes

Press enter or click to view image in full size
2 user same id

through and all of those session variables are updated with the vi victim’s information but then once that’s done it continues doing the password reset request for the attacker so long story short what happens in the end is that you have a session where some of the values are tied to the attacker and other values are tied to the victim and in this case the code is tied to the victim it’s tied to the victim’s account but the token is actually going to be sent back to the attacker email address for this attack

to work the different operations performed by each process must occur in just the right order it would likely require multiple attempts or a bit of look to achieve the desired outcome email address confirmations or any email based operations are generally a good Target for single endpoint race conditions emails are often sent in a background thread after the server issues the HTTP response to the client making race conditions more likely

Press enter or click to view image in full size
change email address

We can open Burp Suite and capture a copy of the POST request used to change the email. Next, we’ll send this request to the Repeater. I’ll create a group and initially call it User1 and User2. Then, we’ll send the request to the Repeater again and change the email to “testtwo.”

We can continue this process by pressing Control + R to send another request to the Repeater. It’s important to use different email addresses for tracking purposes. I’m not entirely sure how many requests we need to make, but I’ll aim for 10.

Next, we want to send these requests in sequence over separate connections. After selecting that option, we can click “Send.” This will send all 10 requests, and then we can wait and review the responses here.

Press enter or click to view image in full size

Let’s check our email server to confirm that we’ve received a single email for each of the usernames. It appears that we received all of them with no duplicates, and they are in the correct order. Now, during the probe phase, we want to try sending the requests again using a single packet attack. I will send these requests in parallel, and then we’ll refresh the page. After doing that, we should receive the credentials and successfully complete the lab.

Press enter or click to view image in full size
lab solved

5. Lab: Exploiting time-sensitive vulnerabilities

This lab contains a password reset mechanism. Although it doesn’t contain a race condition, you can exploit the mechanism’s broken cryptography by sending carefully timed requests.

To solve the lab:

  1. Identify the vulnerability in the way the website generates password reset tokens.
  2. Obtain a valid password reset token for the user carlos.
  3. Log in as carlos.
  4. Access the admin panel and delete the user carlos.

You can log into your account with the following credentials: wiener:peter.

we login to the application background information before we jump into the Practical lab it says that sometimes you may not find race conditions but the technique for delivering requests with precise timing can still reveal the presence of other vulnerabilities one such example is when high resolution time stamps are used instead of cryptographically secure random strings to generate security tokens consider a password reset token that’s only randomized using a Tim stamp in this case it might be possible to trigger two password resets for two different users which both use the same token all you need to do is time the requests so they generate the same Time stamp.

Press enter or click to view image in full size
Press enter or click to view image in full size
a. homepage b. User mailbox

lab so the description says this lab contains a password reset mechanism although it doesn’t contain a race condition you can exploit the mechanism’s broken cryptography by sending carefully time requests to solve the lab we should identify the vulnerability in the way the website generates password password reset tokens and then we should obtain a valid password reset token for Callos log in and then delete the user Carlos

Press enter or click to view image in full size
request required during attack

I’m going to add these to a group and add all of the tabs. then we can either send these in a sequence or send them in parallel I’m going to try and send them in parallel so it we’ll send all these off let’s just see do we get different responses first of all this one came back in the time stamps of these so if this was based on the millisecond none of these are coming back in the same range

Press enter or click to view image in full size
Press enter or click to view image in full size
CSRF token change and session ID

On our second request I’m going to change the session ID and then we also need to change the csrf token so I’m going to go and get that from the response and we will add this here and let’s just try and send both of these off so we’re doing the same thing we’re doing a password reset we’re going to send them as a group in the single packet attack and click Send.

Press enter or click to view image in full size
parallael request send
Press enter or click to view image in full size
Request response after change CSRF and ID

Now, Carlos has the exact same email with the same token. So, we take a copy of ours and go to the site. Then, we change the username to “Carlos,” but it says “invalid token.” Oh wow, that work. Let me check the response.

Press enter or click to view image in full size
Token reciveded

Then we’ll log in. Carlos’ password is 123, and we will delete the user Carlos to solve the lab.

Press enter or click to view image in full size
Press enter or click to view image in full size
Press enter or click to view image in full size
a.carlos profile b. carlos admin panel c. lab solved

6. Lab: Partial construction race conditions

This lab contains a user registration mechanism. A race condition enables you to bypass email verification and register with an arbitrary email address that you do not own.

To solve the lab, exploit this race condition to create an account, then log in and delete the user carlos

open the lab so we’ve got an email client we can open that up as well and that has our email address that we’re able to use for lab we’ve got our home my account and register let’s go straight to the register page and this is the predict phase so we want to try and work out where the potential Collision might be and then we’ll probe it and then prove and that’s part of the methodology that we want to try and build up so I’m going

Press enter or click to view image in full size
Press enter or click to view image in full size
register with given email domain

We don’t have access to that email address, so we need to find a way to either insert this email address or compromise the email address associated with Jin and Juice Shop. Alternatively, we could explore a race condition to see if we can claim the account using that email address that we don’t own.

Next, I’ll head over to Burp Suite and copy the request we just made during registration. I’ll send it to the Repeater so we can manipulate it further. When I click “Send” again, I want to check the response we receive. It indicates that an account already exists with that username. Therefore, each time we perform an action here, we will need to use a different username to conduct our tests properly.

Since we have no way of obtaining the 2FA code, let’s return to the site. I’ll open the DevTools, but you can also use Burp for this. The first thing we want to do is enumerate the website to see if there’s anything interesting available. It appears that there isn’t any JavaScript.

Press enter or click to view image in full size
js file

JS file which has some Javas script code we can go and analyze and we have our registration form we already know that because we’ve filled it in already and that is the post request but we’ve also got a confirm email function down here which is going to grab a token from our URL and so we need a get parameter called token and then it’s going to send that to repeter confirm as a post request along with our token so we could just check.

Press enter or click to view image in full size
Press enter or click to view image in full size
confirm request

This POST request we are interested in will be sent through to the repeater, allowing us to explore further. We get different responses like 403 Forbidden, incorrect token

Press enter or click to view image in full size
Press enter or click to view image in full size
Press enter or click to view image in full size
diffrent payload tryout

This is forbidden because the developers have put in some kind of protection to make sure we can’t submit an empty token but potentially they’ve forgotten about the array option because we get the incorrect token array here so maybe we can use that null exploit with an uninitialized array to confirm this token so lets we need to create a new account and we’re going to need to have a new email address

Press enter or click to view image in full size
Press enter or click to view image in full size
Turbo request

We’ll send the request to the Turbo Intruder and then update the template since it’s currently set to the last one used. I’m going to change that to the single packet attack. This is just Python code. If we look at our request here, we can see where the placeholder is for the username. Each time we will insert a different username into this request. Our goal is to send multiple registration requests, each one with a unique username, and then for each username we register, we want to attempt multiple token verification requests.

First, we need a unique username. Let’s set our username to “siya13.” I’ve already used “appsec,” so I’ll choose this one instead and append the loop index to it. We’ll label the first one as “siya1,” and the second as “siya2,” continuing this pattern until we reach a total of 20 usernames.

The gate we send will also need to be unique, so I’ll set it to `str(i)` for each loop iteration. We need to include the username in the request as well, which is where we’ll use the placeholder `%s` to fill it in.

After looping through, you might need to experiment with the values; I found better luck with some values that weren’t specified in the official solution. For now, I’ll stick to the recommended value of 40, which means we want to send 40 requests to the token page.

Final script

def queueRequests(target, wordlists):

# if the target supports HTTP/2, use engine=Engine.BURP2 to trigger the single-packet attack
# if they only support HTTP/1, use Engine.THREADED or Engine.BURP instead
# for more information, check out https://portswigger.net/research/smashing-the-state-machine
engine = RequestEngine(endpoint=target.endpoint,
concurrentConnections=1,
engine=Engine.BURP2
)

confirmtoken='''POST /confirm?token[]= HTTP/2
Host: 0a5d005e0414357580f9fd850029000e.web-security-academy.net
Cookie: phpsessionid=PqWQRsNcSxgQE2elsNYpe4VK1K1iq5Z1
Content-Length: 96
Cache-Control: max-age=0
Sec-Ch-Ua: "Not:A-Brand";v="24", "Chromium";v="134"
Sec-Ch-Ua-Mobile: ?0
Sec-Ch-Ua-Platform: "Windows"
Accept-Language: en-US,en;q=0.9
Origin: https://0a5d005e0414357580f9fd850029000e.web-security-academy.net
Content-Type: application/x-www-form-urlencoded
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Referer: https://0a5d005e0414357580f9fd850029000e.web-security-academy.net/register
Accept-Encoding: gzip, deflate, br
Priority: u=0, i'''

for i in range(20):
username = "siya" + str(i)
engine.queue(target.req, username, gate=str(i))

for p in range(40):
engine.queue(confirmtoken, gate=str(i))
engine.openGate(str(i))


def handleResponse(req, interesting):
table.add(req)

Here is the output of the intruder

Press enter or click to view image in full size

some request don’t have any username and the length is different so if we go and have a look at those and have a look at the response we’ll see that it says says account registration for user siya13 is successful and this means we can just go and try and log in with that user account and whatever password we set.

Press enter or click to view image in full size
Press enter or click to view image in full size
Press enter or click to view image in full size
a.login credntials b.admin panel c. delete user

Finally, we can delete the user and solve the lab

Press enter or click to view image in full size

Conclusion

Race conditions are a common yet dangerous problem in concurrent programming. They can lead to unpredictable behavior, data corruption, and security vulnerabilities. By using proper synchronization, avoiding shared state, and leveraging concurrency best practices, developers can mitigate these risks.

Key Takeaways

✔ Always synchronize access to shared resources.
✔ Prefer immutable data and message-passing where possible.
✔ Use tools to detect and debug race conditions early.
✔ Test concurrent code under heavy load to expose timing issues.

Further Reading:

Happy coding, and may your threads always synchronize smoothly! 😊

--

--