...
The following code example demonstrates such an attack:
Code Block | ||
---|---|---|
| ||
BigInteger msg = new BigInteger("123"); msg = msg.modPow(exp, m); // Always returns 1 // Malicious subclassing of java.math.BigInteger class BigInteger extends java.math.BigInteger { private intbyte[] valueba; public BigInteger(String str) { super(str); valueba = Integer.parseInt(str (new java.math.BigInteger(str)).toByteArray(); } public void setValue(int valueBigInteger(byte[] ba) { super(ba); this.valueba = valueba; } public @Override public java.math.BigInteger modPow( java.math.BigInteger exponent, java.math.BigInteger mvoid setValue(byte[] ba) { this.valueba = ((int) (Math.pow(this.doubleValue(), ba; } @Override public exponent.doubleValue()))) % m.intValue();byte[] toByteArray() { return thisba; } } |
Unlike the benign BigInteger
class, this malicious BigInteger
class is clearly mutable because of the setValue()
method. Furthermore, the malicious modPow()
method (which overrides a benign modPow()
method) is subject to precision loss (see NUM00-J. Detect or prevent integer overflow, NUM08-J. Check floating-point inputs for exceptional values, NUM12-J. Ensure conversions of numeric types to narrower types do not result in lost or misinterpreted data, and NUM13-J. Avoid loss of precision when converting primitive integers to floating-point for more information). Any code that receives an object of this class and assumes that the object is immutable will behave unexpectedly, as shown by the following code:
Code Block | ||
---|---|---|
| ||
BigInteger bi = new BigInteger("123"); bi.setValue((new BigInteger("246")).toByteArray()); System.out.println(new BigInteger(bi.toByteArray())); |
This code prints: "246", which shows that the value of the supposedly immutable BigInteger bi
has been changed.
This example is particularly important because the BigInteger.modPow()
method type has several useful cryptographic applications.
...
[API 2006] | Class |
Item 15: "Minimize mutability" Item 17, "Design and Document for Inheritance or Else Prohibit It" | |
Chapter 6, "Enforcing Security Policy" | |
[Lai 2008] | Java Insecurity, Accounting for Subtleties That Can Compromise Code |
Chapter 7, Rule 3, Make everything final, unless there's a good reason not to | |
[SCG 2009] | |
[Ware 2008] |
...