Created
March 25, 2011 22:53
-
-
Save olim7t/887802 to your computer and use it in GitHub Desktop.
Example code for my blog post "The TOCTTOU attack", available at http://out-println.appspot.com/posts/tocttou.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.Date; | |
| /** | |
| * Example code for my blog post "The TOCTTOU attack", available at http://out-println.appspot.com/posts/tocttou. | |
| */ | |
| public class Tocttou { | |
| public static final class Interval { | |
| private final Date min; | |
| private final Date max; | |
| public Interval(final Date min, final Date max) { | |
| if (min.after(max)) { | |
| throw new IllegalArgumentException(); | |
| } | |
| this.min = (Date) min.clone(); | |
| this.max = (Date) max.clone(); | |
| } | |
| public Date min() { return (Date) min.clone(); } | |
| public Date max() { return (Date) max.clone(); } | |
| } | |
| public static class Attacker { | |
| volatile Date max = new Date(); | |
| final Thread burglar = new Thread() { | |
| @Override public void run() { | |
| max.setTime(0); | |
| } | |
| }; | |
| public Interval attack() { | |
| Date min = new Date(); | |
| max.setTime(min.getTime()); | |
| burglar.start(); | |
| try { | |
| Interval i = new Interval(min, max); | |
| if (i.min().after(i.max())) { | |
| System.out.println("Success!"); | |
| return i; | |
| } else System.out.println("Too late"); | |
| } | |
| catch (final IllegalArgumentException e) { | |
| System.out.println("Too soon"); | |
| } | |
| return null; | |
| } | |
| } | |
| public static void main(final String[] args) { | |
| Interval corrupted; | |
| long start = System.currentTimeMillis(); | |
| int count = 0; | |
| while ((corrupted = (new Attacker()).attack()) == null) count += 1; | |
| System.out.println("In " + (System.currentTimeMillis() - start) + " ms and " + | |
| count + " attacks, I have created a corrupt interval with min=" + | |
| corrupted.min() + " and max=" + corrupted.max()); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment