user1071840
user1071840

Reputation: 3592

How does the race condition in TOCTOU work?

The following code is supposed to be vulnerable to TOCTOU attack:

 public Period(final Date start, final Date end) {
    if (start.compare(end) > 0) {
       throw new IllegalArgumentException("");
    }

    this.start = start;
    this.end = end;      // Class period has 2 private final member 
                         // variables Date start & end.

 }

What I fail to understand is that how will this race condition work? Say there are 2 threads T1 and T2 where T1 has a valid set of arguments and should pass the check and T2 is a hacker who wants to set invalid values in the class.

If 2 threads are racing and this piece of code is our critical section, then say T1 runs passes the check and sleeps. Now when T2 will start running won't it go through the check again (and fail)??

Upvotes: 3

Views: 2431

Answers (1)

assylias
assylias

Reputation: 328775

The problem is that Date is mutable, so another thread could change the end date: end.setTime(0); after you have checked that start.after(end) (easier way to write your condition).

So it would look like:

  • T1: start.after(end) => returns false, all looks good
  • T2: end.setTime(0); => sneaky Thread 2 changes the date
  • T1: this.start = start; this.end = end; //boom => your class invariant is not valid anymore

Upvotes: 9

Related Questions