library: validate length prefixes on peer crypto data
- Commit
be1348ed358bc86bfd78695d0f64d6d349265585- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-19 01:54 UTC (17 days ago)
- Parents
b8a7e3f
Pqc.unLenPrefix indexed the first four bytes and trusted the embedded length without validation, so a truncated bundle or ciphertext from a peer or storage threw IndexOutOfBoundsException / IllegalArgumentException from copyOfRange with a misleading type. It now requires a full prefix and an in-bounds length, failing as IllegalArgumentException, the failure type crypto callers already handle. E2ee.aesDecrypt likewise requires at least an IV's worth of bytes before slicing. Verified: ./gradlew :library:e2ee-p2p:testDebugUnitTest and ./check library/e2ee-p2p pass.
Diff
library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/E2ee.kt
diff --git a/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/E2ee.kt b/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/E2ee.ktindex fd1255ae37..93a0d7745b 100644--- a/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/E2ee.kt+++ b/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/E2ee.kt@@ -31,6 +31,7 @@ object E2ee { /** Decrypts data produced by [aesEncrypt] (IV prepended). */ fun aesDecrypt(key: ByteArray, data: ByteArray): ByteArray {+ require(data.size >= IV_LEN) { "ciphertext too short: ${data.size}" } val iv = data.copyOfRange(0, IV_LEN) val ct = data.copyOfRange(IV_LEN, data.size) val cipher = Cipher.getInstance("AES/GCM/NoPadding")
library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/Pqc.kt
diff --git a/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/Pqc.kt b/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/Pqc.ktindex 7619e9025d..aa0da32600 100644--- a/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/Pqc.kt+++ b/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/Pqc.kt@@ -107,10 +107,16 @@ object Pqc { private const val BYTE_THIRD_INDEX = 3 private fun unLenPrefix(x: ByteArray): Pair<ByteArray, ByteArray> {+ // Bundles/ciphertexts arrive from peers and storage; a truncated or+ // lying length prefix must fail as IllegalArgumentException (the+ // failure type callers already handle for bad crypto input), not as+ // an IndexOutOfBoundsException from a raw array read.+ require(x.size >= LEN_PREFIX_BYTES) { "length-prefixed data too short: ${x.size}" } val len = ((x[0].toInt() and BYTE_MASK) shl BYTE_THIRD_SHIFT) or ((x[1].toInt() and BYTE_MASK) shl BYTE_SECOND_SHIFT) or ((x[BYTE_SECOND_INDEX].toInt() and BYTE_MASK) shl BYTE_BITS) or (x[BYTE_THIRD_INDEX].toInt() and BYTE_MASK)+ require(len >= 0 && LEN_PREFIX_BYTES + len <= x.size) { "length prefix $len exceeds size ${x.size}" } return x.copyOfRange(LEN_PREFIX_BYTES, LEN_PREFIX_BYTES + len) to x.copyOfRange(LEN_PREFIX_BYTES + len, x.size) }