⚠️

Understanding Race Conditions in Programming

May 31, 2025

Lecture Notes on Race Conditions

Definition

  • Race Condition: Occurs when two events happen nearly simultaneously in an application without the application accounting for these simultaneous operations.
  • Commonly checked by developers but unexpected outcomes can occur when multiple events interplay unexpectedly.

Types of Race Conditions

  • TOCTOU (Time of Check to Time of Use) Attack:
    • The application retrieves a value from the system, performs a function, but an unseen process may change the value before use.

Practical Example

  • Scenario: Two users moving money between two accounts (Account A and Account B).

    1. Initial State: Both Account A and B have $100.
    2. User 1 Action: Transfers $50 to Account B.
      • Account A: $100
      • Account B: $150
    3. User 2 Action: Also transfers $50 to Account B.
      • Account A: $100
      • Account B: $200
    4. User 1 Action: Withdraws $50 from Account A.
      • Account A: $50
      • Account B: $200
    5. User 2 Action: Withdraws $50 from Account A.
      • From User 2's perspective:
        • Account A: $50
        • Account B: $200
      • Actual Outcome: Account A should have $0, but due to race condition, it shows $50.

Real-World Examples

Mars Rover - Spirit (2004)

  • Issue: File system error caused rover to continuously reboot (reboot loop).
  • Solution: Developers sent additional code to bypass the error.

Tesla Model 3 (Pwn2Own 2023)

  • Type: TOCTOU attack on infotainment system via Bluetooth.
  • Outcome: Privilege escalation to root user, attackers won $100,000 and the car.

Key Takeaways

  • Race conditions can lead to significant and unintended consequences if not properly managed.
  • Developers must account for the potential of simultaneous events that may interfere with application logic.
  • Real-world cases highlight the importance of robust error handling and updates to prevent race conditions.