4

I have heard that running code in a managed language, e.g. Java in the JVM, is impossible to protect against timing attacks due to the JITing nature of most managed runtimes. In concept I can agree with this, but I would like to understand what the current industry knowledge around this is.

Anthony Kraft
  • 1,139
  • 1
  • 8
  • 18

1 Answers1

6

A broad statement such as "this is impossible" is unlikely to be 100% accurate.

It is true that Java (and similar languages such as C#/.NET) runs with a JIT compiler that will produce the actual opcodes only at runtime, so the sequence of opcodes is harder to predict; it may also change with the VM implementation version. Moreover, the language has an efficient GC that promotes dynamic memory usage, and in particular immutable strings, which offer a lot of data-dependent timing behaviours.

It is still possible to write code that is immune to timing attacks, in particular for cryptographic algorithms. You just have to shun some of the nice properties of Java, and use it as if it was some kind of watered-down C. Work on arrays of byte or char, use arithmetic rather than tests... (so don't use boolean). For instance, this timing-immune code compares x and y, and swaps them if x is greater than y:

int cc = (y - x) >> 31;
int tmpx = (cc & x) | (~cc & y);
int tmpy = (~cc & x) | (cc & y);
x = tmpy;
y = tmpx;

We may note that Java makes such code actually somewhat easier to write than C since, contrary to C, it offers standard, fixed behaviour when right-shifting a negative value.

Thomas Pornin
  • 320,799
  • 57
  • 780
  • 949
  • Is writing code in that style common practice, and how devastating is it for implementations out there of crypto algorithms that do not follow this restricted subset of Java? – Anthony Kraft Nov 12 '14 at 22:07
  • In many cases such code is not necessary. E.g. timing attacks on HMAC comparisons matter only for protocols that do MAC-then-encrypt instead of encrypt-then-MAC. – Thomas Pornin Nov 12 '14 at 22:11
  • This is just wrong. You have no contract with runtime about what optimizations may occur. Sure, writing code like this may prevent timing attacks with current JVM implementations, but that is happenstance. [This paper](https://eprint.iacr.org/2006/349.pdf) puts it well in the conclusion. – dan_waterworth Oct 24 '15 at 11:46
  • I _do_ have a contract about what optimizations may occur: I can assume that the JVM will perform only optimizations that are actually feasible. While JVM implementors are not bound to me with regards to what they do, they still must comply with the laws of physics. In that matter, these "runtime optimizations" are not qualitatively different to what an ahead-of-time compiler (like for C) can do. – Thomas Pornin Oct 24 '15 at 13:09