@@ -63,9 +63,32 @@ public class Wallet {
6363 private static final int CURRENT_VERSION = 3 ;
6464 private static final String CIPHER = "aes-128-ctr" ;
6565
66+ // Upper bounds for untrusted keystore KDF cost parameters. A hostile
67+ // keystore file may declare arbitrary KDF strengths: extreme scrypt
68+ // parameters make Bouncy Castle either allocate unbounded memory
69+ // (n*r*128 bytes — e.g. n=2^22, r=8 requests 4 GiB and dies with OOM)
70+ // or compute for hours, and out-of-range values can crash the JVM with
71+ // NegativeArraySizeException / ArithmeticException inside SCrypt.generate.
72+ // All values here are rejected by validationError() before any KDF runs.
73+ private static final int SCRYPT_N_MIN = 1 << 12 ;
74+ private static final int SCRYPT_N_MAX = 1 << 20 ;
75+ private static final int SCRYPT_R_MAX = 8 ;
76+ private static final int SCRYPT_P_MAX = 8 ;
77+ private static final long SCRYPT_MEMORY_MAX_BYTES = 1L << 30 ; // 128 * r * n cap = 1 GiB
78+ private static final int KDF_DKLEN_MAX = 128 ;
79+ private static final int PBKDF2_C_MAX = 1 << 20 ;
80+
6681 public static WalletFile create (String password , SignInterface sign , int n , int p )
6782 throws CipherException {
6883
84+ // Keep create() symmetric with validate()/decrypt(): reject KDF cost
85+ // parameters that the decryption path would refuse, so create() can
86+ // never produce a wallet file that only this class rejects.
87+ String paramError = scryptKdfParamsError (DKLEN , n , R , p );
88+ if (paramError != null ) {
89+ throw new CipherException (paramError );
90+ }
91+
6992 byte [] salt = generateRandomBytes (32 );
7093
7194 byte [] derivedKey = generateDerivedScryptKey (password .getBytes (UTF_8 ), salt , n , R , p , DKLEN );
@@ -194,15 +217,28 @@ public static SignInterface decrypt(String password, WalletFile walletFile)
194217 int p = scryptKdfParams .getP ();
195218 int r = scryptKdfParams .getR ();
196219 byte [] salt = ByteArray .fromHexString (scryptKdfParams .getSalt ());
197- derivedKey = generateDerivedScryptKey (password .getBytes (UTF_8 ), salt , n , r , p , dklen );
220+ try {
221+ derivedKey = generateDerivedScryptKey (password .getBytes (UTF_8 ), salt , n , r , p , dklen );
222+ } catch (RuntimeException e ) {
223+ // Defense-in-depth: any residual KDF engine failure (e.g. an
224+ // IllegalArgumentException from Bouncy Castle) must surface as a
225+ // clean CipherException, never as a raw RuntimeException stack.
226+ // Errors (OutOfMemoryError etc.) are deliberately not caught —
227+ // they remain fatal.
228+ throw new CipherException ("Scrypt key derivation failed" , e );
229+ }
198230 } else if (kdfParams instanceof WalletFile .Aes128CtrKdfParams ) {
199231 WalletFile .Aes128CtrKdfParams aes128CtrKdfParams =
200232 (WalletFile .Aes128CtrKdfParams ) crypto .getKdfparams ();
201233 int c = aes128CtrKdfParams .getC ();
202234 String prf = aes128CtrKdfParams .getPrf ();
203235 byte [] salt = ByteArray .fromHexString (aes128CtrKdfParams .getSalt ());
204236
205- derivedKey = generateAes128CtrDerivedKey (password .getBytes (UTF_8 ), salt , c , prf );
237+ try {
238+ derivedKey = generateAes128CtrDerivedKey (password .getBytes (UTF_8 ), salt , c , prf );
239+ } catch (RuntimeException e ) {
240+ throw new CipherException ("Pbkdf2 key derivation failed" , e );
241+ }
206242 } else {
207243 throw new CipherException ("Unable to deserialize params: " + crypto .getKdf ());
208244 }
@@ -254,11 +290,15 @@ public static SignInterface decrypt(String password, WalletFile walletFile)
254290 /**
255291 * Returns a description of the first schema violation found in
256292 * {@code walletFile}, or {@code null} if the file matches the supported
257- * V3 keystore shape (current version, known cipher, known KDF).
293+ * V3 keystore shape (current version, known cipher, known KDF, and KDF
294+ * cost parameters within safe bounds).
258295 *
259- * <p>Shared by {@link #validate(WalletFile)} (which throws the message)
260- * and {@link #isValidKeystoreFile(WalletFile)} (which returns boolean
261- * for discovery-style filtering).
296+ * <p>KDF cost bounds are enforced here — the single chokepoint shared by
297+ * {@link #validate(WalletFile)} (which throws the message) and
298+ * {@link #isValidKeystoreFile(WalletFile)} (which returns boolean for
299+ * discovery-style filtering) — so untrusted keystore files can never
300+ * drive the KDF into unbounded memory allocation, multi-hour CPU
301+ * exhaustion, or engine-level crashes before {@link #decrypt} runs.
262302 */
263303 private static String validationError (WalletFile walletFile ) {
264304 if (walletFile .getVersion () != CURRENT_VERSION ) {
@@ -276,6 +316,58 @@ private static String validationError(WalletFile walletFile) {
276316 if (kdf == null || (!kdf .equals (PBKDF2 ) && !kdf .equals (SCRYPT ))) {
277317 return "KDF type is not supported" ;
278318 }
319+ WalletFile .KdfParams kdfParams = crypto .getKdfparams ();
320+ if (kdfParams == null ) {
321+ // Structural stubs (e.g. tooling fixtures) may omit kdfparams entirely;
322+ // there are no cost parameters to bound. Real keystores always carry them.
323+ return null ;
324+ }
325+ if (SCRYPT .equals (kdf )) {
326+ if (!(kdfParams instanceof WalletFile .ScryptKdfParams )) {
327+ return "Scrypt KDF params are missing or malformed" ;
328+ }
329+ WalletFile .ScryptKdfParams params = (WalletFile .ScryptKdfParams ) kdfParams ;
330+ return scryptKdfParamsError (params .getDklen (), params .getN (), params .getR (), params .getP ());
331+ }
332+ if (!(kdfParams instanceof WalletFile .Aes128CtrKdfParams )) {
333+ return "Pbkdf2 KDF params are missing or malformed" ;
334+ }
335+ WalletFile .Aes128CtrKdfParams params = (WalletFile .Aes128CtrKdfParams ) kdfParams ;
336+ return pbkdf2KdfParamsError (params .getDklen (), params .getC ());
337+ }
338+
339+ private static String scryptKdfParamsError (int dklen , int n , int r , int p ) {
340+ // dklen must yield at least 32 bytes: generateMac copies derivedKey[16..32)
341+ // and AES-128 needs bytes [0..16); smaller keys throw raw ArrayIndexOutOfBoundsException.
342+ if (dklen < 32 || dklen > KDF_DKLEN_MAX ) {
343+ return "Scrypt dklen is out of range [32, " + KDF_DKLEN_MAX + "]: " + dklen ;
344+ }
345+ if (n < SCRYPT_N_MIN || n > SCRYPT_N_MAX || (n & (n - 1 )) != 0 ) {
346+ return "Scrypt n must be a power of 2 in [" + SCRYPT_N_MIN + ", " + SCRYPT_N_MAX
347+ + "]: " + n ;
348+ }
349+ if (r < 1 || r > SCRYPT_R_MAX ) {
350+ return "Scrypt r is out of range [1, " + SCRYPT_R_MAX + "]: " + r ;
351+ }
352+ if (p < 1 || p > SCRYPT_P_MAX ) {
353+ return "Scrypt p is out of range [1, " + SCRYPT_P_MAX + "]: " + p ;
354+ }
355+ // Compute in long arithmetic: hostile r * n must not overflow int.
356+ long memoryBytes = 128L * r * n ;
357+ if (memoryBytes > SCRYPT_MEMORY_MAX_BYTES ) {
358+ return "Scrypt memory requirement 128*r*n=" + memoryBytes
359+ + " exceeds the " + SCRYPT_MEMORY_MAX_BYTES + " byte limit" ;
360+ }
361+ return null ;
362+ }
363+
364+ private static String pbkdf2KdfParamsError (int dklen , int c ) {
365+ if (dklen < 1 || dklen > KDF_DKLEN_MAX ) {
366+ return "Pbkdf2 dklen is out of range [1, " + KDF_DKLEN_MAX + "]: " + dklen ;
367+ }
368+ if (c < 1 || c > PBKDF2_C_MAX ) {
369+ return "Pbkdf2 iteration count c is out of range [1, " + PBKDF2_C_MAX + "]: " + c ;
370+ }
279371 return null ;
280372 }
281373
0 commit comments