From e2d25c4d808575101a84e9290ab3470d8e48fe01 Mon Sep 17 00:00:00 2001 From: martgil <46025304+martgil@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:30:28 +0800 Subject: [PATCH 1/2] fix(pgp): bound OpenPGP packet parsing to prevent heap exhaustion --- .../security/pgp/PgpDecryptAndOrVerify.kt | 7 +- .../security/pgp/PgpPacketBudgetGuard.kt | 201 +++++++++++++++ .../security/pgp/PgpPacketBudgetGuardTest.kt | 242 ++++++++++++++++++ 3 files changed, 449 insertions(+), 1 deletion(-) create mode 100644 FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpPacketBudgetGuard.kt create mode 100644 FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpPacketBudgetGuardTest.kt diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpDecryptAndOrVerify.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpDecryptAndOrVerify.kt index f2e25f7be..47f223000 100644 --- a/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpDecryptAndOrVerify.kt +++ b/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpDecryptAndOrVerify.kt @@ -103,9 +103,10 @@ object PgpDecryptAndOrVerify { passphrase: Passphrase? = null, ignoreMdcErrors: Boolean = false ): DecryptionStream { + val guardedInputStream = PgpPacketBudgetGuard.guard(srcInputStream) val api = PGPainless.getInstance() return api.processMessage() - .onInputStream(srcInputStream) + .onInputStream(guardedInputStream) .withOptions( ConsumerOptions.get(api) .setMissingKeyPassphraseStrategy(MissingKeyPassphraseStrategy.THROW_EXCEPTION) @@ -155,6 +156,10 @@ object PgpDecryptAndOrVerify { DecryptionException(DecryptionErrorType.KEY_MISMATCH, e) } + is PgpPacketBudgetGuard.BudgetExceededException -> { + DecryptionException(DecryptionErrorType.FORMAT, e) + } + is DecryptionException -> e else -> { diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpPacketBudgetGuard.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpPacketBudgetGuard.kt new file mode 100644 index 000000000..d71262684 --- /dev/null +++ b/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpPacketBudgetGuard.kt @@ -0,0 +1,201 @@ +/* + * © 2016-present FlowCrypt a.s. Limitations apply. Contact human@flowcrypt.com + * Contributors: + * Ivan Pizhenko + */ + +package com.flowcrypt.email.security.pgp + +import org.bouncycastle.apache.bzip2.CBZip2InputStream +import org.bouncycastle.bcpg.ArmoredInputStream +import org.bouncycastle.bcpg.BCPGInputStream +import org.bouncycastle.bcpg.CompressionAlgorithmTags +import org.bouncycastle.bcpg.CompressedDataPacket +import org.bouncycastle.bcpg.InputStreamPacket +import org.bouncycastle.bcpg.PacketTags +import org.bouncycastle.bcpg.UnsupportedPacketVersionException +import org.bouncycastle.util.io.Streams +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.io.FilterInputStream +import java.io.IOException +import java.io.InputStream +import java.nio.charset.StandardCharsets +import java.util.zip.Inflater +import java.util.zip.InflaterInputStream + +/** + * Bounds the amount of OpenPGP state that may be allocated for a single untrusted message. + * + * OpenPGP parsers keep one object per packet. A tiny, highly compressible input can therefore + * expand into hundreds of thousands of packets (typically prepended signature packets) and + * exhaust the heap before any limit on emitted/decrypted output applies. This guard walks the + * packet structure before the data reaches the parser and rejects inputs that exceed a cumulative + * budget. Compressed layers are followed so that the budget applies to the decompressed packet + * stream, not just the bytes on the wire. Encrypted layers cannot be inspected without keys; + * a bomb hidden inside an encrypted message is a remaining limitation of this pre-scan. + */ +object PgpPacketBudgetGuard { + /** Largest input accepted. Bigger inputs are rejected rather than parsed without a budget. */ + private const val MAX_INPUT_BYTES = 32 * 1024 * 1024 + + /** Bounds memory used while following a compressed stream. */ + private const val MAX_DECOMPRESSED_BYTES = 8 * 1024 * 1024L + + /** Total packets accepted across all layers of one message. */ + private const val MAX_TOTAL_PACKETS = 10_000 + + /** Prepended signatures are not useful in email and are the usual amplification vector. */ + private const val MAX_SIGNATURE_PACKETS = 1_000 + + /** Session key packets are another per-packet state amplification vector. */ + private const val MAX_SESSION_KEY_PACKETS = 1_000 + + private const val MAX_NESTING_DEPTH = 8 + + private val ARMOR_HEADER_MARKER = "-----BEGIN PGP ".toByteArray(StandardCharsets.US_ASCII) + + class BudgetExceededException(message: String) : IOException(message) + + /** + * Returns a stream that is safe to hand to an OpenPGP parser. The input is validated and + * replayed from memory. Oversized input is rejected: skipping the scan would let a small + * compressible bomb sit behind enough noise to cross any size threshold. + */ + fun guard(srcInputStream: InputStream): InputStream { + val buffered = ByteArrayOutputStream() + val chunk = ByteArray(DEFAULT_BUFFER_SIZE) + var total = 0 + + while (true) { + val read = srcInputStream.read(chunk) + if (read == -1) break + total += read + if (total > MAX_INPUT_BYTES) { + throw BudgetExceededException("OpenPGP message is too large") + } + buffered.write(chunk, 0, read) + } + + val bytes = buffered.toByteArray() + validate(bytes) + return ByteArrayInputStream(bytes) + } + + private fun validate(bytes: ByteArray) { + val armorStart = indexOfArmorHeader(bytes) + val offset = maxOf(0, armorStart) + val source = ByteArrayInputStream(bytes, offset, bytes.size - offset) + val input = if (armorStart >= 0) { + BCPGInputStream(ArmoredInputStream(source)) + } else { + BCPGInputStream(source) + } + walk(input, Counters(), depth = 0) + } + + private fun indexOfArmorHeader(bytes: ByteArray): Int { + // Armor is only recognized at the start of the stream, after leading whitespace. + // Searching anywhere would let binary input hide a marker inside a packet body. + var start = 0 + while (start < bytes.size && bytes[start].toInt().toChar().isWhitespace()) start++ + if (start + ARMOR_HEADER_MARKER.size > bytes.size) return -1 + for (j in ARMOR_HEADER_MARKER.indices) { + if (bytes[start + j] != ARMOR_HEADER_MARKER[j]) return -1 + } + return start + } + + private class Counters(var total: Int = 0, var signatures: Int = 0, var sessionKeys: Int = 0) + + private fun walk(input: BCPGInputStream, counters: Counters, depth: Int) { + if (depth > MAX_NESTING_DEPTH) { + throw BudgetExceededException("OpenPGP message nests too deeply") + } + + while (true) { + val tag = input.nextPacketTag() + if (tag == -1) return + + counters.total++ + if (counters.total > MAX_TOTAL_PACKETS) { + throw BudgetExceededException("OpenPGP message has too many packets") + } + + when (tag) { + PacketTags.SIGNATURE -> { + counters.signatures++ + if (counters.signatures > MAX_SIGNATURE_PACKETS) { + throw BudgetExceededException("OpenPGP message has too many signature packets") + } + consumePacket(input, tag) + } + + PacketTags.PUBLIC_KEY_ENC_SESSION, PacketTags.SYMMETRIC_KEY_ENC_SESSION -> { + counters.sessionKeys++ + if (counters.sessionKeys > MAX_SESSION_KEY_PACKETS) { + throw BudgetExceededException("OpenPGP message has too many session key packets") + } + consumePacket(input, tag) + } + + PacketTags.COMPRESSED_DATA -> { + val packet = input.readPacket() as? CompressedDataPacket + ?: throw BudgetExceededException("Malformed compressed OpenPGP packet") + val decompressed = LimitedInputStream( + decompress(packet.algorithm, packet.inputStream), MAX_DECOMPRESSED_BYTES + ) + walk(BCPGInputStream(decompressed), counters, depth + 1) + } + + else -> consumePacket(input, tag) + } + } + } + + private fun decompress(algorithm: Int, source: InputStream): InputStream = when (algorithm) { + CompressionAlgorithmTags.UNCOMPRESSED -> source + CompressionAlgorithmTags.ZIP -> InflaterInputStream(source, Inflater(true)) + CompressionAlgorithmTags.ZLIB -> InflaterInputStream(source) + CompressionAlgorithmTags.BZIP2 -> CBZip2InputStream(source) + else -> throw BudgetExceededException("Unsupported OpenPGP compression algorithm: $algorithm") + } + + private fun consumePacket(input: BCPGInputStream, tag: Int) { + try { + val packet = input.readPacket() ?: return + // Stream packets leave their body unread; skip it so the next header is aligned. + if (packet is InputStreamPacket) { + Streams.drain(packet.inputStream) + } + } catch (e: UnsupportedPacketVersionException) { + // Only the signature parser drains the body before throwing. Other packet types would + // leave the stream mid-packet, so reject instead of misreading later headers. + if (tag != PacketTags.SIGNATURE) throw e + } + } + + private class LimitedInputStream(source: InputStream, private val maxBytes: Long) : + FilterInputStream(source) { + private var readBytes = 0L + + override fun read(): Int { + val value = super.read() + if (value >= 0) count(1) + return value + } + + override fun read(b: ByteArray, off: Int, len: Int): Int { + val read = super.read(b, off, len) + if (read > 0) count(read.toLong()) + return read + } + + private fun count(count: Long) { + readBytes += count + if (readBytes > maxBytes) { + throw BudgetExceededException("Decompressed OpenPGP data is too large") + } + } + } +} diff --git a/FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpPacketBudgetGuardTest.kt b/FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpPacketBudgetGuardTest.kt new file mode 100644 index 000000000..2b12b10de --- /dev/null +++ b/FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpPacketBudgetGuardTest.kt @@ -0,0 +1,242 @@ +/* + * © 2016-present FlowCrypt a.s. Limitations apply. Contact human@flowcrypt.com + * Contributors: + * Ivan Pizhenko + */ + +package com.flowcrypt.email.security.pgp + +import com.flowcrypt.email.api.retrofit.response.model.MsgBlock +import jakarta.mail.Session +import jakarta.mail.internet.MimeMessage +import org.bouncycastle.bcpg.ArmoredOutputStream +import org.bouncycastle.bcpg.CompressionAlgorithmTags +import org.bouncycastle.bcpg.PacketTags +import org.bouncycastle.openpgp.PGPCompressedDataGenerator +import org.bouncycastle.openpgp.PGPPublicKeyRingCollection +import org.bouncycastle.openpgp.PGPSecretKeyRingCollection +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test +import org.pgpainless.key.protection.SecretKeyRingProtector +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.nio.charset.StandardCharsets +import java.util.Properties + +class PgpPacketBudgetGuardTest { + @Test + fun compressedSignatureBombIsRejectedByDecrypt() { + val armored = armoredMessage(signatureCount = 2_000, literalText = "secret") + + val result = PgpDecryptAndOrVerify.decryptAndOrVerifyWithResult( + srcInputStream = armored.byteInputStream(), + publicKeys = PGPPublicKeyRingCollection(emptyList()), + secretKeys = PGPSecretKeyRingCollection(emptyList()), + protector = SecretKeyRingProtector.unprotectedKeys() + ) + + assertNull("Content must not be produced", result.content) + assertNotNull("Over-budget message must be rejected", result.exception) + assertEquals( + PgpDecryptAndOrVerify.DecryptionErrorType.FORMAT, + result.exception?.decryptionErrorType + ) + assertTrue( + "Budget error expected but was: ${result.exception?.message}", + result.exception?.message?.contains("signature packets") == true + ) + } + + @Test + fun reportedScaleSignatureBombIsRejected() { + val armored = armoredMessage(signatureCount = 120_000, literalText = "secret") + assertRejected(armored, "signature packets") + } + + @Test + fun armorMarkerInsideBinaryPacketIsNotMistakenForArmor() { + val inner = ByteArrayOutputStream() + writePacket( + inner, 60, "-----BEGIN PGP MESSAGE----- noise".toByteArray(StandardCharsets.US_ASCII) + ) + repeat(2_000) { writePacket(inner, PacketTags.SIGNATURE, byteArrayOf(0, 1, 2, 3)) } + + try { + PgpPacketBudgetGuard.guard(ByteArrayInputStream(inner.toByteArray())) + fail("Expected an over-budget rejection") + } catch (e: PgpPacketBudgetGuard.BudgetExceededException) { + assertTrue("Unexpected message: ${e.message}", e.message!!.contains("signature packets")) + } + } + + @Test + fun binarySignatureBombIsRejected() { + val inner = ByteArrayOutputStream() + repeat(2_000) { writePacket(inner, PacketTags.SIGNATURE, byteArrayOf(0, 1, 2, 3)) } + try { + PgpPacketBudgetGuard.guard(ByteArrayInputStream(inner.toByteArray())) + fail("Expected an over-budget rejection") + } catch (e: PgpPacketBudgetGuard.BudgetExceededException) { + assertTrue("Unexpected message: ${e.message}", e.message!!.contains("signature packets")) + } + } + + @Test + fun uncompressedSignatureBombIsRejected() { + val armored = armoredMessage(signatureCount = 2_000, compress = false) + assertRejected(armored, "signature packets") + } + + @Test + fun nestedCompressedSignatureBombIsRejected() { + val armored = armoredMessage(signatureCount = 2_000, nestedCompression = true) + assertRejected(armored, "signature packets") + } + + @Test + fun tooManyPacketsAreRejected() { + val inner = ByteArrayOutputStream() + repeat(12_000) { writePacket(inner, 60, byteArrayOf(1)) } + assertRejected(armoredRaw(inner.toByteArray(), compress = false), "too many packets") + } + + @Test + fun oversizedDecompressedStreamIsRejected() { + val output = ByteArrayOutputStream() + val generator = PGPCompressedDataGenerator(CompressionAlgorithmTags.ZIP) + val compressor = generator.open(output) + // 1,100 packets of 8 KiB each decompress to about 8.6 MiB. + repeat(1_100) { writePacket(compressor, 60, ByteArray(8 * 1024)) } + compressor.close() + generator.close() + assertRejected(armorRaw(output.toByteArray()), "Decompressed") + } + + @Test + fun underBudgetMessageIsAccepted() { + val armored = armoredMessage(signatureCount = 100, literalText = "hello") + val guarded = PgpPacketBudgetGuard.guard(armored.byteInputStream()) + assertNotNull(guarded) + + val result = PgpDecryptAndOrVerify.decryptAndOrVerifyWithResult( + srcInputStream = armored.byteInputStream(), + publicKeys = PGPPublicKeyRingCollection(emptyList()), + secretKeys = PGPSecretKeyRingCollection(emptyList()), + protector = SecretKeyRingProtector.unprotectedKeys() + ) + assertFalse( + "Legitimate message wrongly rejected: ${result.exception?.message}", + result.exception?.message?.contains("packets") == true + ) + } + + @Test + fun processMimeMessageRendersBoundedErrorForBomb() { + val armored = armoredMessage(signatureCount = 2_000, literalText = "secret") + val rawMessage = ( + "From: attacker@example.com\r\nTo: victim@example.com\r\n" + + "Subject: test\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n$armored" + ).toByteArray(StandardCharsets.UTF_8) + val mime = MimeMessage(Session.getInstance(Properties()), ByteArrayInputStream(rawMessage)) + + val result = PgpMsg.processMimeMessage( + mime, + verificationPublicKeys = PGPPublicKeyRingCollection(emptyList()), + secretKeys = PGPSecretKeyRingCollection(emptyList()), + protector = SecretKeyRingProtector.unprotectedKeys() + ) + + assertTrue( + "Expected a decrypt-error block, got ${result.blocks.map { it.type }}", + result.blocks.any { it.type == MsgBlock.Type.DECRYPT_ERROR } + ) + assertFalse( + "Bomb plaintext must not be rendered", + result.text.contains("secret") + ) + } + + private fun assertRejected(armored: String, expectedMessage: String) { + try { + PgpPacketBudgetGuard.guard(armored.byteInputStream()) + fail("Expected an over-budget rejection") + } catch (e: PgpPacketBudgetGuard.BudgetExceededException) { + assertTrue( + "Unexpected message: ${e.message}", + e.message?.contains(expectedMessage, ignoreCase = true) == true + ) + } + } + + private fun armoredMessage( + signatureCount: Int = 0, + literalText: String? = null, + compress: Boolean = true, + nestedCompression: Boolean = false + ): String { + val inner = ByteArrayOutputStream() + repeat(signatureCount) { writePacket(inner, PacketTags.SIGNATURE, byteArrayOf(0, 1, 2, 3)) } + literalText?.let { text -> + val body = ByteArrayOutputStream().apply { + write('b'.code) // 'b' = binary literal data + write(0) // no file name + repeat(4) { write(0) } // timestamp + write(text.toByteArray(StandardCharsets.UTF_8)) + } + writePacket(inner, PacketTags.LITERAL_DATA, body.toByteArray()) + } + return armoredRaw(inner.toByteArray(), compress, nestedCompression) + } + + private fun armoredRaw( + data: ByteArray, + compress: Boolean, + nestedCompression: Boolean = false + ): String { + var payload = data + if (nestedCompression) payload = compress(payload) + if (compress) payload = compress(payload) + + return armorRaw(payload) + } + + private fun armorRaw(payload: ByteArray): String { + val armored = ByteArrayOutputStream() + ArmoredOutputStream(armored).use { it.write(payload) } + return String(armored.toByteArray(), StandardCharsets.US_ASCII) + } + + private fun compress(data: ByteArray): ByteArray { + val output = ByteArrayOutputStream() + val generator = PGPCompressedDataGenerator(CompressionAlgorithmTags.ZIP) + generator.open(output).use { it.write(data) } + generator.close() + return output.toByteArray() + } + + private fun writePacket(output: java.io.OutputStream, tag: Int, body: ByteArray) { + output.write(0xC0 or tag) + when { + body.size < 192 -> output.write(body.size) + body.size < 8384 -> { + val length = body.size - 192 + output.write((length shr 8) + 192) + output.write(length and 0xFF) + } + + else -> { + output.write(0xFF) + output.write(body.size shr 24) + output.write(body.size shr 16) + output.write(body.size shr 8) + output.write(body.size) + } + } + output.write(body) + } +} From 71b194e5980131d9e5e9a06aff9e4a71e5846945 Mon Sep 17 00:00:00 2001 From: martgil <46025304+martgil@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:20:30 +0800 Subject: [PATCH 2/2] chore: remove contributor attribution from new files --- .../com/flowcrypt/email/security/pgp/PgpPacketBudgetGuard.kt | 2 -- .../flowcrypt/email/security/pgp/PgpPacketBudgetGuardTest.kt | 2 -- 2 files changed, 4 deletions(-) diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpPacketBudgetGuard.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpPacketBudgetGuard.kt index d71262684..466db8803 100644 --- a/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpPacketBudgetGuard.kt +++ b/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpPacketBudgetGuard.kt @@ -1,7 +1,5 @@ /* * © 2016-present FlowCrypt a.s. Limitations apply. Contact human@flowcrypt.com - * Contributors: - * Ivan Pizhenko */ package com.flowcrypt.email.security.pgp diff --git a/FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpPacketBudgetGuardTest.kt b/FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpPacketBudgetGuardTest.kt index 2b12b10de..cb0aa5f1d 100644 --- a/FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpPacketBudgetGuardTest.kt +++ b/FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpPacketBudgetGuardTest.kt @@ -1,7 +1,5 @@ /* * © 2016-present FlowCrypt a.s. Limitations apply. Contact human@flowcrypt.com - * Contributors: - * Ivan Pizhenko */ package com.flowcrypt.email.security.pgp