references/vm-compiled.md
Constant-Time Analysis: VM-Compiled Languages
Analysis guidance for Java and C#. These languages compile to bytecode (JVM bytecode / CIL) that runs on a virtual machine with Just-In-Time (JIT) compilation to native code.
Understanding VM-Compiled Languages
Unlike native-compiled languages (C, Rust, Go), Java and C# add an intermediate layer:
Source Code (.java/.cs)
|
v
Compiler (javac/csc)
|
v
Bytecode (.class/.dll)
|
v
JIT Compiler (HotSpot/RyuJIT)
|
v
Native Code (at runtime)
Security implications:
- Bytecode is deterministic - Same source always produces same bytecode
- JIT is non-deterministic - Native code varies by runtime, version, and warmup state
- Analysis target - We analyze bytecode since JIT output is impractical to capture
Limitations:
- JIT may introduce timing variations not visible in bytecode
- Runtime optimizations can convert safe bytecode to unsafe native code
- Different JVM/CLR implementations may behave differently
Running the Analyzer
# Java
uv run {baseDir}/ct_analyzer/analyzer.py CryptoUtils.java
# C#
uv run {baseDir}/ct_analyzer/analyzer.py CryptoUtils.cs
# Include conditional branch warnings
uv run {baseDir}/ct_analyzer/analyzer.py --warnings CryptoUtils.java
# Filter to specific methods
uv run {baseDir}/ct_analyzer/analyzer.py --func 'sign|verify' CryptoUtils.java
# CI-friendly JSON output
uv run {baseDir}/ct_analyzer/analyzer.py --json CryptoUtils.java
Note: The --arch and --opt-level flags do not apply to VM-compiled languages.
Dangerous Bytecode Instructions
JVM Bytecode
| Category | Instructions | Risk |
|----------|--------------|------|
| Integer Division | idiv, ldiv, irem, lrem | Variable-time based on operand values |
| Floating Division | fdiv, ddiv, frem, drem | Variable latency |
| Conditional Branches | ifeq, ifne, iflt, ifge, ifgt, ifle, if_icmp*, if_acmp* | Timing leak if condition depends on secrets |
| Table Lookups | *aload, *astore, tableswitch, lookupswitch | Cache timing if index depends on secrets |
CIL (C# / .NET)
| Category | Instructions | Risk |
|----------|--------------|------|
| Integer Division | div, div.un, rem, rem.un | Variable-time based on operand values |
| Floating Division | (uses same div/rem opcodes) | Variable latency |
| Conditional Branches | beq, bne, blt, bgt, ble, bge, brfalse, brtrue | Timing leak if condition depends on secrets |
| Table Lookups | ldelem.*, stelem.*, switch | Cache timing if index depends on secrets |
Constant-Time Patterns
Java
Replace Division
// VULNERABLE: Division instruction emitted
int q = secretValue / divisor;
// SAFE: Barrett reduction (for fixed divisor)
// Precompute: mu = (1L << 32) / divisor
long mu = 0x100000000L / divisor;
int q = (int) ((secretValue * mu) >>> 32);
Replace Branches
// VULNERABLE: Branch timing reveals secret
int result;
if (secret != 0) {
result = a;
} else {
result = b;
}
// SAFE: Constant-time selection using bitwise ops
int mask = -(secret != 0 ? 1 : 0); // All 1s if true, all 0s if false
// Better: compute mask without branch
int mask = (secret | -secret) >> 31; // -1 if secret != 0, else 0
int result = (a & mask) | (b & ~mask);
Replace Comparisons
// VULNERABLE: Arrays.equals() may early-terminate
if (Arrays.equals(computed, expected)) { ... }
// SAFE: Use MessageDigest.isEqual() for constant-time comparison
import java.security.MessageDigest;
if (MessageDigest.isEqual(computed, expected)) { ... }
Secure Random
// VULNERABLE: Predictable PRNG
Random rand = new Random();
int value = rand.nextInt();
// SAFE: Cryptographically secure
SecureRandom secureRand = new SecureRandom();
int value = secureRand.nextInt();
C# / .NET
Replace Division
// VULNERABLE: Division instruction emitted
int q = secretValue / divisor;
// SAFE: Barrett reduction (for fixed divisor)
// Precompute: mu = (1UL << 32) / divisor
ulong mu = 0x100000000UL / (ulong)divisor;
int q = (int)((secretValue * mu) >> 32);
Replace Branches
// VULNERABLE: Branch timing reveals secret
int result = secret != 0 ? a : b;
// SAFE: Constant-time selection
int mask = -(secret != 0 ? 1 : 0);
int result = (a & mask) | (b & ~mask);
// Or use Vector<T> for SIMD constant-time ops (.NET 7+)
Replace Comparisons
// VULNERABLE: SequenceEqual may early-terminate
if (computed.SequenceEqual(expected)) { ... }
// SAFE: Use CryptographicOperations.FixedTimeEquals (.NET Core 2.1+)
using System.Security.Cryptography;
if (CryptographicOperations.FixedTimeEquals(computed, expected)) { ... }
Secure Random
// VULNERABLE: Predictable PRNG
Random rand = new Random();
int value = rand.Next();
// SAFE: Cryptographically secure
using System.Security.Cryptography;
int value = RandomNumberGenerator.GetInt32(int.MaxValue);
// Or for bytes:
byte[] bytes = RandomNumberGenerator.GetBytes(32);
Platform-Specific Considerations
Java
- Bouncy Castle: Use
org.bouncycastle.util.Arrays.constantTimeAreEqual()for constant-time comparison - JEP 329 (Java 12+): ChaCha20 and Poly1305 implementations are designed to be constant-time
- BigInteger: Operations like
modPow()may have timing leaks; consider using Bouncy Castle's constant-time implementations
C# / .NET
- Span: Use
CryptographicOperations.FixedTimeEquals(ReadOnlySpan<byte>, ReadOnlySpan<byte>)for best performance - NSec: Consider using NSec library for constant-time cryptographic primitives
- BigInteger: .NET's BigInteger has potential timing leaks; use specialized crypto libraries
JIT Compiler Caveats
Even if bytecode appears safe, JIT compilers can introduce timing vulnerabilities:
- Speculative optimization - JIT may convert constant-time bytecode to branching native code
- Escape analysis - May inline and optimize in ways that introduce timing
- Tiered compilation - Code behavior may change as it "warms up"
Mitigations:
- Test with production JVM/CLR versions
- Consider ahead-of-time (AOT) compilation (GraalVM Native Image, .NET Native AOT)
- For critical code, verify native code output with JIT logging:
# Java: Print JIT compilation
java -XX:+PrintCompilation -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly MyClass
# .NET: Enable tiered compilation diagnostics
DOTNET_TieredCompilation=0 dotnet run # Disable tiered compilation for consistent behavior
Setup Requirements
Java
Required: JDK 8+ with javac and javap available.
Installation:
# macOS (Homebrew)
brew install openjdk@21
# Ubuntu/Debian
sudo apt install openjdk-21-jdk
# Windows (via winget)
winget install Microsoft.OpenJDK.21
PATH Configuration (macOS):
On macOS, Homebrew installs OpenJDK as "keg-only" (not linked to /usr/local/bin). You must add it to your PATH:
# Add to ~/.zshrc or ~/.bashrc
export PATH="/opt/homebrew/opt/openjdk@21/bin:$PATH" # Apple Silicon
# or
export PATH="/usr/local/opt/openjdk@21/bin:$PATH" # Intel Mac
Verification:
javac --version # Should show: javac 21.x.x
javap -version # Should show version info
Common Issues:
- "Unable to locate a Java Runtime" on macOS: The system
/usr/bin/javacis a stub that requires a real JDK. Install OpenJDK via Homebrew. - Wrong Java version: If you have multiple JDKs, use
JAVA_HOMEor ensure the correct one is first in PATH.
C#
Required: .NET SDK 8.0+ with dotnet available, plus ilspycmd for IL disassembly.
Installation:
# macOS (Homebrew)
brew install dotnet-sdk
# Ubuntu/Debian
sudo apt install dotnet-sdk-8.0
# Windows
winget install Microsoft.DotNet.SDK.8
Install IL Disassembler:
dotnet tool install -g ilspycmd
PATH Configuration:
Ensure the .NET tools directory is in your PATH:
# Add to ~/.zshrc or ~/.bashrc
export PATH="$HOME/.dotnet/tools:$PATH"
Verification:
dotnet --version # Should show: 8.x.x or higher
ilspycmd --version # Should show: ilspycmd: 9.x.x
Common Issues:
-
"ilspycmd requires .NET 8.0 but you have .NET 10.0": This happens when ilspycmd targets an older .NET version than your installed SDK. ilspycmd installs framework-dependent, so the version you have decides which runtime it needs — ilspycmd 8.x needs .NET 8, 9.x needs .NET 9. Do not assume .NET 8; check what is actually in the tool store:
# Prints the target framework the installed ilspycmd was built for, e.g. net9.0 find ~/.dotnet/tools/.store/ilspycmd -maxdepth 6 -type d -name 'net*'findrather thanlson a glob, becausels ~/.dotnet/.../tools/*aborts under zsh when nothing matches. Iffinditself reports "No such file or directory", the store does not exist andilspycmdwas never installed withdotnet tool install— that is the answer, not an error to work around.The analyzer resolves this itself, preferring a Homebrew keg of that exact major and otherwise running the tool on whatever runtime it can find with
DOTNET_ROLL_FORWARD=Major. Installing the matching keg is the more reliable path:# macOS — substitute the major from the command above (dotnet@8, dotnet@9, …) brew install dotnet@9 # Other platforms: install that .NET runtime alongside your SDKNote that homebrew-core does not carry a keg for every major —
dotnet@6,dotnet@8anddotnet@9exist,dotnet@7was dropped at end of life. When there is no keg for the major you need, the roll-forward path above is what runs, and no install is required. -
"IL disassembly tools not found": Ensure
ilspycmdis installed globally and~/.dotnet/toolsis in your PATH. -
Source-only fallback: If IL disassembly fails, the analyzer falls back to source-level analysis. This still detects division operators and dangerous function calls but misses bytecode-level issues.
Alternative: Mono (Linux/macOS)
For environments without .NET SDK, you can use Mono:
# macOS
brew install mono
# Ubuntu/Debian
sudo apt install mono-complete
# Verify
mcs --version
monodis --help
Note: Mono's monodis produces different IL output than ilspycmd. The analyzer supports both formats.
Common Mistakes
-
Trusting high-level APIs -
Arrays.equals()in Java andSequenceEqual()in C# are NOT constant-time -
Ignoring JIT behavior - Bytecode analysis is necessary but not sufficient; JIT can introduce leaks
-
BigInteger operations - Both platforms' BigInteger implementations may leak timing; use crypto libraries
-
String comparisons - Never compare secrets as strings; use byte arrays with constant-time comparison
-
Exception timing - Try/catch blocks around secret operations may leak timing through exception handling
Further Reading
- Java Cryptography Architecture Guide
- .NET Cryptography Model
- Bouncy Castle Java - Constant-time crypto primitives
- NSec - Modern cryptographic library for .NET