Lesson 5 of 5
Race conditions
Listen to an AI summary of Race conditions
Two tills and one ticket
A club sells tickets for a match at two tills, and one ticket is left. Each till looks at the list, sees one ticket left and sells the ticket. Two people now hold a ticket for the same seat.
On a website, each till is one request. Looking at the list is the check. Selling the ticket is the write, the step that saves a change to the data. The people at two tills can talk to each other, and two requests cannot.
What is a race condition
A race condition (CWE-362) is code that gives a wrong result when two requests run at the same moment. Two sales of the last ticket are a business logic weakness.
A discount code in the sports shop
The sports shop gives Sam the discount code SAM5, which takes £5 off one order. The shop keeps each code as a row in a database table named codes. A table in a database is a grid where each row is one record. The column used holds FALSE until the code is used.
The server runs the Python code for each request that has a discount code. The variable code holds the discount code from the request. The three comments name the three steps.
# read row = database.execute("SELECT used FROM codes WHERE code = ?", [code]) # check if row.used: return "Code already used" # write database.execute("UPDATE codes SET used = TRUE WHERE code = ?", [code]) take_five_pounds_off(order)
database.execute sends a query to the database. The read is a SELECT query that fetches the row for the code. The ? marks where the database puts the value of code (SQL injection). The check reads row.used, the value of the column used, and stops the request when the value is TRUE. The write is an UPDATE, the SQL statement that changes a row, and sets used to TRUE.
The last line takes £5 off the order. The pattern of the three steps is called read, check, write. The same pattern can take a bank balance below zero or give one free trial ten times.
Two requests at the same moment
Sam has two orders open in two tabs of the browser. Sam types SAM5 into both tabs and presses Apply in both at the same moment. The browser sends two requests, request A and request B.
The server can pause request A between any two lines and run lines of request B.
- Request A, from the first tab, asks the database whether the code SAM5 is used.
- Request B, from the second tab, asks the same.
- The database answers No to request A, so the check passes.
- The database answers No to request B, so the check passes. Neither request has written yet.
- Request A marks the code as used.
- Request B marks the code as used a second time.
- Order 1 and order 2 both get £5 off. One code gave two discounts.
SAM5. Each request goes through the server, where the code for the request asks the database.Both requests read FALSE before either request writes TRUE, so both requests pass the check.
Who sends two requests together
An attacker sends the requests together on purpose. A short program can send twenty requests with the same code in the same second.
An ordinary customer can cause the same fault by accident. A double click on a button sends the same request twice, a moment apart. An app can also send a request again when the answer is slow.
The check as part of the write
One fix lets the database do the check and the write as one step. The safer code has no separate read. Look at the end of the UPDATE statement, after the word AND.
# check and write in one statement changed = database.execute( "UPDATE codes SET used = TRUE WHERE code = ? AND used = FALSE", [code]) if changed == 0: return "Code already used" take_five_pounds_off(order)
The words AND used = FALSE are the check, so the UPDATE changes the row only when used is still FALSE. For an UPDATE, database.execute returns the number of rows changed. The database finishes one UPDATE on a row before starting the next. Request A changes one row. Request B then finds used is TRUE, changes no rows and stops at Code already used.
- Request A, from the first tab, tells the database to mark the code SAM5 as used if the code is not used yet.
- Request B, from the second tab, tells the database the same.
- The database answers request A that one row changed.
- The database answers request B that no row changed. The database did the check and the write as one step.
- Order 1 gets £5 off. Order 2 gets the message Code already used. One code gave one discount.
Examples of other fixes
A lock makes one request wait while another request finishes using the same data. A transaction is a group of database steps that all happen together or not at all. A transaction on its own does not stop the race. Code puts the read, the check and the write in one transaction and adds FOR UPDATE to the SELECT. FOR UPDATE locks the row until the transaction ends, so request B waits for request A to finish, then reads used as TRUE.
A unique constraint is a database rule that refuses a second record with the same value. The shop can record each use of a code as a row in a table code_uses, with a unique constraint on the column code. The database refuses the second row, and request B stops before the discount.
An idempotency key is a value sent with a request so that a repeat of the same request does nothing the second time. The checkout page puts one random value in the payment request. A double click sends the same value twice, and the server takes the payment once.
Time of check to time of use
A time-of-check to time-of-use race condition (CWE-367) is a race condition where a thing changes between the check and the use.
The sports shop lets Sam upload a photo for a ticket. The code checks that the file sam.jpg is a picture, then shows the file on the ticket. Look at how both lines find the file by name.
if is_picture("uploads/sam.jpg"): # check show_on_ticket("uploads/sam.jpg") # use
A second request can replace sam.jpg with a different file between the two lines. The ticket then shows a file that nobody checked. Safer code opens the file once, then checks and uses the opened file:
photo = open("uploads/sam.jpg", "rb") # open the file once if is_picture(photo): # check the opened file show_on_ticket(photo) # use the same opened file
The value "rb" opens the file for reading. A name can point to a different file a moment later, and the variable photo keeps the file that the code checked. For a row in a database, safer code locks and checks the row inside the transaction that uses the row.
Threads and shared memory
A thread is one of several parts of a program that run at the same time. Some servers run each request in a thread of one program. Two threads can then use the same variable in the memory of the program.
The variable sold counts the tickets the shop has sold, and holds 7. Two threads each run the line sold = sold + 1. The line is three steps, which are read sold, add 1 and save sold.
1.Thread 1 reads sold
gets 7
2.Thread 2 reads sold
gets 7
3.Thread 1 adds 1
has 8
4.Thread 2 adds 1
has 8
5.Both threads save sold
sold is 8, not 9
sold at the same moment. Each thread reads sold before the other thread saves sold, so one addition is lost.A variable that every request can use, such as a count of tickets sold, needs a lock around the three steps. Some languages have a ready-made counter that does the three steps as one, such as AtomicInteger in Java.
Examples of what to look for
- A read, a check and a write as three separate steps, on a balance, a count, a limit or a code that works once.
- A check on a file by name, followed by a use of the file by the same name.
- A payment with no idempotency key, so that a repeated request takes the payment twice.
- A variable shared by every request, such as a counter declared outside every function, changed with no lock.
Example words to search for are synchronized in Java and sync.Mutex in Go, another programming language. Each of the two words makes a lock. The word to search for in JavaScript for Node.js is await, which makes no lock. Other requests run while the code waits at an await, so a check before an await and a write after the await can race. The lesson on searching the code shows how to search for a word.
Check your understanding
Name the pattern of three steps that can cause a race condition.
Show the answer
Read, check, write.
Two requests use the code
SAM5at the same moment. State why both requests pass the check.Show the answer
Both requests read
usedasFALSEbefore either request writesTRUE.Give one reason why a double click can cause the same fault as an attacker.
Show the answer
A double click sends the same request twice, a moment apart, so two requests run at the same moment.
Practise it
Challenges with a weakness this lesson teaches.
- Discount codesSwiftcart, IntermediateOpen
- Gift cardsSwiftcart, IntermediateOpen
- Payday remindersBrightledger, IntermediateOpen
- regreSSHionReal CVEs, IntermediateOpen