From ef568540138ff78e5b41cfe9dd687d1b99e8e667 Mon Sep 17 00:00:00 2001
From: martgil <46025304+martgil@users.noreply.github.com>
Date: Tue, 24 Nov 2026 20:13:30 +0800
Subject: [PATCH 1/3] fix: bound untrusted OpenPGP message processing
---
.../java/com/flowcrypt/email/Constants.kt | 11 ++
.../email/core/msg/RawBlockParser.kt | 21 ++--
.../extensions/java/io/LimitedOutputStream.kt | 37 ++++++
.../email/extensions/kotlin/StringExt.kt | 34 ++++--
.../jetpack/viewmodel/DecryptDataViewModel.kt | 5 +-
.../flowcrypt/email/security/pgp/PgpArmor.kt | 10 +-
.../security/pgp/PgpDecryptAndOrVerify.kt | 4 +-
.../flowcrypt/email/security/pgp/PgpMsg.kt | 5 +-
.../email/security/pgp/PgpSignature.kt | 46 ++++---
.../java/io/LimitedOutputStreamTest.kt | 41 +++++++
.../email/extensions/kotlin/StringExtTest.kt | 28 +++++
.../email/security/pgp/PgpArmorLimitTest.kt | 34 ++++++
.../security/pgp/PgpDecompressionLimitTest.kt | 113 ++++++++++++++++++
.../security/pgp/PgpSignatureLimitTest.kt | 36 ++++++
14 files changed, 388 insertions(+), 37 deletions(-)
create mode 100644 FlowCrypt/src/main/java/com/flowcrypt/email/extensions/java/io/LimitedOutputStream.kt
create mode 100644 FlowCrypt/src/test/java/com/flowcrypt/email/extensions/java/io/LimitedOutputStreamTest.kt
create mode 100644 FlowCrypt/src/test/java/com/flowcrypt/email/extensions/kotlin/StringExtTest.kt
create mode 100644 FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpArmorLimitTest.kt
create mode 100644 FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpDecompressionLimitTest.kt
create mode 100644 FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpSignatureLimitTest.kt
diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/Constants.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/Constants.kt
index c1b13b5c94..759405d2f5 100644
--- a/FlowCrypt/src/main/java/com/flowcrypt/email/Constants.kt
+++ b/FlowCrypt/src/main/java/com/flowcrypt/email/Constants.kt
@@ -74,6 +74,17 @@ class Constants {
*/
const val MAX_PUB_KEY_SIZE = 1024 * 256
+ /**
+ * The max size of a buffered OpenPGP message and its decrypted content.
+ * Bounds decompression of untrusted attachments during message rendering.
+ */
+ const val MAX_PGP_MESSAGE_SIZE_IN_BYTES = 4 * 1024 * 1024
+
+ /**
+ * The max length of an HTML escaped string built from untrusted content.
+ */
+ const val MAX_ESCAPED_HTML_OUTPUT_LENGTH_IN_CHARS = 4 * 1024 * 1024
+
const val FORWARDED_ATTACHMENTS_CACHE_DIR = "forwarded"
const val ATTACHMENTS_CACHE_DIR = "attachments"
const val DRAFT_CACHE_DIR = "draft"
diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/core/msg/RawBlockParser.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/core/msg/RawBlockParser.kt
index 52721de07c..b85fbffbf7 100644
--- a/FlowCrypt/src/main/java/com/flowcrypt/email/core/msg/RawBlockParser.kt
+++ b/FlowCrypt/src/main/java/com/flowcrypt/email/core/msg/RawBlockParser.kt
@@ -6,12 +6,13 @@
package com.flowcrypt.email.core.msg
+import com.flowcrypt.email.Constants
import com.flowcrypt.email.core.msg.RawBlockParser.RawBlock
import com.flowcrypt.email.extensions.jakarta.mail.baseContentType
import com.flowcrypt.email.extensions.jakarta.mail.getFileNameWithCarefully
import com.flowcrypt.email.extensions.jakarta.mail.isAttachment
import com.flowcrypt.email.extensions.jakarta.mail.isInline
-import com.flowcrypt.email.extensions.java.io.readText
+import com.flowcrypt.email.extensions.java.io.readBytesWithLimit
import com.flowcrypt.email.extensions.kotlin.normalize
import com.flowcrypt.email.security.pgp.PgpArmor
import org.eclipse.angus.mail.util.BASE64DecoderStream
@@ -80,7 +81,7 @@ object RawBlockParser {
listOf(
RawBlock(
RawBlockType.PGP_MSG,
- mimePart.inputStream.readBytes(),
+ mimePart.inputStream.readBytesWithLimit(Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES),
isOpenPGPMimeSigned
)
)
@@ -94,7 +95,7 @@ object RawBlockParser {
listOf(
RawBlock(
RawBlockType.PGP_MSG,
- mimePart.inputStream.readBytes(),
+ mimePart.inputStream.readBytesWithLimit(Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES),
isOpenPGPMimeSigned
)
)
@@ -104,7 +105,7 @@ object RawBlockParser {
listOf(
RawBlock(
RawBlockType.PGP_PUBLIC_KEY,
- mimePart.inputStream.readBytes(),
+ mimePart.inputStream.readBytesWithLimit(Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES),
isOpenPGPMimeSigned
)
)
@@ -114,7 +115,7 @@ object RawBlockParser {
listOf(
RawBlock(
RawBlockType.PGP_PRIVATE_KEY,
- mimePart.inputStream.readBytes(),
+ mimePart.inputStream.readBytesWithLimit(Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES),
isOpenPGPMimeSigned
)
)
@@ -124,7 +125,7 @@ object RawBlockParser {
listOf(
RawBlock(
RawBlockType.ATTACHMENT,
- mimePart.inputStream.readBytes(),
+ mimePart.inputStream.readBytesWithLimit(Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES),
isOpenPGPMimeSigned
)
)
@@ -159,7 +160,7 @@ object RawBlockParser {
listOf(
RawBlock(
RawBlockType.INLINE_ATTACHMENT,
- inputStream.readBytes(),
+ inputStream.readBytesWithLimit(Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES),
isOpenPGPMimeSigned
)
)
@@ -181,12 +182,14 @@ object RawBlockParser {
"text/html" == mimePart.baseContentType() -> listOf(
RawBlock(
RawBlockType.HTML_TEXT,
- mimePart.inputStream.readBytes(),
+ mimePart.inputStream.readBytesWithLimit(Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES),
isOpenPGPMimeSigned
)
)
- else -> detectBlocks(mimePart.inputStream.readText()).map {
+ else -> detectBlocks(
+ mimePart.inputStream.readBytesWithLimit(Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES).decodeToString()
+ ).map {
it.copy(isOpenPGPMimeSigned = isOpenPGPMimeSigned)
}
}
diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/extensions/java/io/LimitedOutputStream.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/extensions/java/io/LimitedOutputStream.kt
new file mode 100644
index 0000000000..6d6dc57f82
--- /dev/null
+++ b/FlowCrypt/src/main/java/com/flowcrypt/email/extensions/java/io/LimitedOutputStream.kt
@@ -0,0 +1,37 @@
+/*
+ * © 2016-present FlowCrypt a.s. Limitations apply. Contact human@flowcrypt.com
+ * Contributors: denbond7
+ */
+
+package com.flowcrypt.email.extensions.java.io
+
+import java.io.ByteArrayOutputStream
+import java.io.IOException
+
+/**
+ * Buffers output in memory but fails with [IOException] once [maxBytes] is exceeded.
+ * Use for untrusted data whose expanded size is not known in advance.
+ */
+class LimitedOutputStream(private val maxBytes: Int) : ByteArrayOutputStream() {
+ init {
+ require(maxBytes >= 0) { "maxBytes must not be negative" }
+ }
+
+ @Synchronized
+ override fun write(b: Int) {
+ ensureCapacityFor(1)
+ super.write(b)
+ }
+
+ @Synchronized
+ override fun write(b: ByteArray, off: Int, len: Int) {
+ ensureCapacityFor(len)
+ super.write(b, off, len)
+ }
+
+ private fun ensureCapacityFor(additionalBytes: Int) {
+ if (count.toLong() + additionalBytes > maxBytes) {
+ throw IOException("The stream exceeds the limit of $maxBytes bytes")
+ }
+ }
+}
diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/extensions/kotlin/StringExt.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/extensions/kotlin/StringExt.kt
index 1aa3b38223..bfade0a16f 100644
--- a/FlowCrypt/src/main/java/com/flowcrypt/email/extensions/kotlin/StringExt.kt
+++ b/FlowCrypt/src/main/java/com/flowcrypt/email/extensions/kotlin/StringExt.kt
@@ -11,6 +11,7 @@ import android.util.TypedValue
import android.webkit.MimeTypeMap
import androidx.core.content.ContextCompat
import androidx.core.graphics.toColorInt
+import com.flowcrypt.email.Constants
import com.flowcrypt.email.R
import com.flowcrypt.email.util.BetterInternetAddress
import com.flowcrypt.email.util.UIUtil
@@ -19,6 +20,7 @@ import jakarta.mail.internet.ContentType
import jakarta.mail.internet.InternetAddress
import org.apache.commons.io.FilenameUtils
import org.json.JSONObject
+import java.io.IOException
import java.io.InputStream
import java.net.URLDecoder
import java.nio.charset.Charset
@@ -61,13 +63,31 @@ fun String.removeUtf8Bom(): String {
}
fun String.toEscapedHtml(): String {
- return this.replace("&", "&")
- .replace("\"", """)
- .replace("'", "'")
- .replace("<", "<")
- .replace(">", ">")
- .replace("/", "/")
- .replace("\n", "
")
+ val result = StringBuilder(length)
+ for (char in this) {
+ val replacement = when (char) {
+ '&' -> "&"
+ '"' -> """
+ '\'' -> "'"
+ '<' -> "<"
+ '>' -> ">"
+ '/' -> "/"
+ '\n' -> "
"
+ else -> null
+ }
+ if (replacement == null) {
+ if (result.length >= Constants.MAX_ESCAPED_HTML_OUTPUT_LENGTH_IN_CHARS) {
+ throw IOException("The escaped HTML exceeds the limit of $Constants.MAX_ESCAPED_HTML_OUTPUT_LENGTH_IN_CHARS characters")
+ }
+ result.append(char)
+ } else {
+ if (result.length + replacement.length > Constants.MAX_ESCAPED_HTML_OUTPUT_LENGTH_IN_CHARS) {
+ throw IOException("The escaped HTML exceeds the limit of $Constants.MAX_ESCAPED_HTML_OUTPUT_LENGTH_IN_CHARS characters")
+ }
+ result.append(replacement)
+ }
+ }
+ return result.toString()
}
fun String.unescapeHtml(): String {
diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/jetpack/viewmodel/DecryptDataViewModel.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/jetpack/viewmodel/DecryptDataViewModel.kt
index b982fdd9ef..963a0b71a9 100644
--- a/FlowCrypt/src/main/java/com/flowcrypt/email/jetpack/viewmodel/DecryptDataViewModel.kt
+++ b/FlowCrypt/src/main/java/com/flowcrypt/email/jetpack/viewmodel/DecryptDataViewModel.kt
@@ -7,12 +7,13 @@ package com.flowcrypt.email.jetpack.viewmodel
import android.app.Application
import android.content.Context
+import com.flowcrypt.email.Constants
+import com.flowcrypt.email.extensions.java.io.LimitedOutputStream
import com.flowcrypt.email.security.KeysStorageImpl
import com.flowcrypt.email.security.pgp.PgpDecryptAndOrVerify
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.bouncycastle.openpgp.PGPSecretKeyRingCollection
-import java.io.ByteArrayOutputStream
import java.io.InputStream
/**
@@ -25,7 +26,7 @@ abstract class DecryptDataViewModel(application: Application) : AccountViewModel
): ByteArray =
withContext(Dispatchers.IO) {
inputStream.use {
- val byteArrayOutputStream = ByteArrayOutputStream()
+ val byteArrayOutputStream = LimitedOutputStream(Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES)
val pgpSecretKeyRings = KeysStorageImpl.getInstance(context).getPGPSecretKeyRings()
val pgpSecretKeyRingCollection = PGPSecretKeyRingCollection(pgpSecretKeyRings)
val protector = KeysStorageImpl.getInstance(context).getSecretKeyRingProtector()
diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpArmor.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpArmor.kt
index c525167259..89a0f65347 100644
--- a/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpArmor.kt
+++ b/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpArmor.kt
@@ -6,7 +6,10 @@
package com.flowcrypt.email.security.pgp
import com.flowcrypt.email.BuildConfig
+import com.flowcrypt.email.Constants
import com.flowcrypt.email.core.msg.RawBlockParser
+import com.flowcrypt.email.extensions.java.io.LimitedOutputStream
+import com.flowcrypt.email.extensions.java.io.readBytesWithLimit
import com.flowcrypt.email.extensions.kotlin.countOfMatchesZeroOneOrMore
import com.flowcrypt.email.extensions.kotlin.isWhiteSpace
import com.flowcrypt.email.extensions.kotlin.normalize
@@ -14,6 +17,7 @@ import org.bouncycastle.bcpg.ArmoredInputStream
import org.bouncycastle.bcpg.ArmoredOutputStream
import org.bouncycastle.openpgp.PGPException
import org.bouncycastle.util.Strings
+import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.InputStream
@@ -159,8 +163,10 @@ object PgpArmor {
// https://github.com/bcgit/bc-java/blob/bc3b92f1f0e78b82e2584c5fb4b226a13e7f8b3b/pg/src/main/java/org/bouncycastle/openpgp/examples/ClearSignedFileProcessor.java
fun readSignedClearTextMessage(input: InputStream): CleartextSignedMessage {
try {
- ArmoredInputStream(input).use { armoredInput ->
- val out = ByteArrayOutputStream()
+ ArmoredInputStream(
+ ByteArrayInputStream(input.readBytesWithLimit(Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES))
+ ).use { armoredInput ->
+ val out = LimitedOutputStream(Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES)
out.use {
val lineOut = ByteArrayOutputStream()
var lookAhead = readInputLine(lineOut, armoredInput)
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 f2e25f7be7..d7ace4df1e 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
@@ -6,6 +6,8 @@
package com.flowcrypt.email.security.pgp
import android.os.Parcelable
+import com.flowcrypt.email.Constants
+import com.flowcrypt.email.extensions.java.io.LimitedOutputStream
import com.flowcrypt.email.extensions.org.pgpainless.decryption_verification.isSigned
import com.flowcrypt.email.util.exception.DecryptionException
import kotlinx.parcelize.Parcelize
@@ -69,7 +71,7 @@ object PgpDecryptAndOrVerify {
ignoreMdcErrors: Boolean = false
): DecryptionResult {
srcInputStream.use { srcStream ->
- val destOutputStream = ByteArrayOutputStream()
+ val destOutputStream = LimitedOutputStream(Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES)
destOutputStream.use { outStream ->
try {
val decryptionStream = genDecryptionStream(
diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpMsg.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpMsg.kt
index d6e77add5e..8f02832c5a 100644
--- a/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpMsg.kt
+++ b/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpMsg.kt
@@ -8,6 +8,7 @@ package com.flowcrypt.email.security.pgp
import android.content.Context
import android.util.Base64
import androidx.core.util.PatternsCompat
+import com.flowcrypt.email.Constants
import com.flowcrypt.email.api.email.JavaEmailConstants
import com.flowcrypt.email.api.retrofit.response.model.AlternativeContentMsgBlock
import com.flowcrypt.email.api.retrofit.response.model.AttMeta
@@ -30,6 +31,7 @@ import com.flowcrypt.email.api.retrofit.response.model.VerificationResult
import com.flowcrypt.email.core.msg.MimeUtils
import com.flowcrypt.email.core.msg.RawBlockParser
import com.flowcrypt.email.database.FlowCryptRoomDatabase
+import com.flowcrypt.email.extensions.java.io.LimitedOutputStream
import com.flowcrypt.email.extensions.jakarta.mail.isMultipart
import com.flowcrypt.email.extensions.jakarta.mail.isMultipartAlternative
import com.flowcrypt.email.extensions.jakarta.mail.isOpenPGPMimeEncrypted
@@ -67,7 +69,6 @@ import org.owasp.html.HtmlPolicyBuilder
import org.pgpainless.decryption_verification.SignatureVerification
import org.pgpainless.key.protection.SecretKeyRingProtector
import java.io.ByteArrayInputStream
-import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.nio.charset.StandardCharsets
import java.util.IdentityHashMap
@@ -285,7 +286,7 @@ object PgpMsg {
val contentPart = multiPart.getBodyPart(0)
val signaturePart = multiPart.getBodyPart(1)
- val openPGPMIMESignedContent = ByteArrayOutputStream().apply {
+ val openPGPMIMESignedContent = LimitedOutputStream(Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES).apply {
contentPart.writeTo(this)
}.toByteArray()
diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpSignature.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpSignature.kt
index c7570cf39c..ce817d36d0 100644
--- a/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpSignature.kt
+++ b/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpSignature.kt
@@ -6,15 +6,16 @@
package com.flowcrypt.email.security.pgp
+import com.flowcrypt.email.Constants
+import com.flowcrypt.email.extensions.java.io.LimitedOutputStream
+import com.flowcrypt.email.extensions.java.io.readBytesWithLimit
import org.bouncycastle.openpgp.PGPPublicKeyRingCollection
import org.pgpainless.PGPainless
import org.pgpainless.decryption_verification.ConsumerOptions
import org.pgpainless.decryption_verification.MessageMetadata
import org.pgpainless.decryption_verification.cleartext_signatures.ClearsignedMessageUtil
-import org.pgpainless.decryption_verification.cleartext_signatures.InMemoryMultiPassStrategy
import org.pgpainless.decryption_verification.cleartext_signatures.MultiPassStrategy
import java.io.ByteArrayInputStream
-import java.io.ByteArrayOutputStream
import java.io.InputStream
/**
@@ -22,19 +23,19 @@ import java.io.InputStream
*/
object PgpSignature {
fun extractClearText(source: String?, isSilent: Boolean = true): String? {
- return extractClearText(ByteArrayInputStream(source?.toByteArray()), isSilent)
+ return extractClearText(source?.byteInputStream() ?: ByteArrayInputStream(ByteArray(0)), isSilent)
}
@Suppress("MemberVisibilityCanBePrivate")
fun extractClearText(srcInputStream: InputStream, isSilent: Boolean = true): String? {
srcInputStream.use { srcStream ->
return try {
- val multiPassStrategy = MultiPassStrategy.keepMessageInMemory()
+ val messageOutputStream = LimitedOutputStream(Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES)
ClearsignedMessageUtil.detachSignaturesFromInbandClearsignedMessage(
- srcStream,
- multiPassStrategy.messageOutputStream
+ ByteArrayInputStream(srcStream.readBytesWithLimit(Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES)),
+ messageOutputStream
)
- String(multiPassStrategy.getBytes())
+ String(messageOutputStream.toByteArray())
} catch (e: Exception) {
if (isSilent) {
e.printStackTrace()
@@ -48,15 +49,17 @@ object PgpSignature {
srcInputStream: InputStream,
publicKeys: PGPPublicKeyRingCollection
): ClearTextVerificationResult {
- ByteArrayOutputStream().use { outStream ->
+ LimitedOutputStream(Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES).use { outStream ->
return try {
val api = PGPainless.getInstance()
val verificationStream = api.processMessage()
- .onInputStream(srcInputStream)
+ .onInputStream(
+ ByteArrayInputStream(srcInputStream.readBytesWithLimit(Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES))
+ )
.withOptions(
ConsumerOptions.get(api)
.addVerificationCerts(publicKeys.map { api.toCertificate(it) })
- .setMultiPassStrategy(InMemoryMultiPassStrategy())
+ .setMultiPassStrategy(LimitedMultiPassStrategy())
)
verificationStream.use { it.copyTo(outStream) }
@@ -75,16 +78,22 @@ object PgpSignature {
signatureInputStream: InputStream,
publicKeys: PGPPublicKeyRingCollection
): DetachedSignatureVerificationResult {
- ByteArrayOutputStream().use { outStream ->
+ LimitedOutputStream(Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES).use { outStream ->
return try {
val api = PGPainless.getInstance()
val verificationStream = api.processMessage()
- .onInputStream(srcInputStream)
+ .onInputStream(
+ ByteArrayInputStream(srcInputStream.readBytesWithLimit(Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES))
+ )
.withOptions(
ConsumerOptions.get(api)
- .addVerificationOfDetachedSignatures(signatureInputStream)
+ .addVerificationOfDetachedSignatures(
+ ByteArrayInputStream(
+ signatureInputStream.readBytesWithLimit(Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES)
+ )
+ )
.addVerificationCerts(publicKeys.map { api.toCertificate(it) })
- .setMultiPassStrategy(InMemoryMultiPassStrategy())
+ .setMultiPassStrategy(LimitedMultiPassStrategy())
)
verificationStream.use { it.copyTo(outStream) }
@@ -98,6 +107,15 @@ object PgpSignature {
}
}
+ private class LimitedMultiPassStrategy : MultiPassStrategy {
+ private val output = LimitedOutputStream(Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES)
+
+ override val messageOutputStream: java.io.OutputStream = output
+
+ override val messageInputStream: InputStream
+ get() = ByteArrayInputStream(output.toByteArray())
+ }
+
data class ClearTextVerificationResult(
override val messageMetadata: MessageMetadata? = null,
override val exception: Exception? = null,
diff --git a/FlowCrypt/src/test/java/com/flowcrypt/email/extensions/java/io/LimitedOutputStreamTest.kt b/FlowCrypt/src/test/java/com/flowcrypt/email/extensions/java/io/LimitedOutputStreamTest.kt
new file mode 100644
index 0000000000..9edb6aaee8
--- /dev/null
+++ b/FlowCrypt/src/test/java/com/flowcrypt/email/extensions/java/io/LimitedOutputStreamTest.kt
@@ -0,0 +1,41 @@
+/*
+ * © 2016-present FlowCrypt a.s. Limitations apply. Contact human@flowcrypt.com
+ * Contributors: denbond7
+ */
+
+package com.flowcrypt.email.extensions.java.io
+
+import org.junit.Assert.assertArrayEquals
+import org.junit.Assert.assertThrows
+import org.junit.Test
+import java.io.IOException
+
+class LimitedOutputStreamTest {
+ @Test
+ fun testWritesWithinLimit() {
+ val stream = LimitedOutputStream(LIMIT)
+ stream.write(ByteArray(LIMIT) { it.toByte() })
+ assertArrayEquals(ByteArray(LIMIT) { it.toByte() }, stream.toByteArray())
+ }
+
+ @Test
+ fun testThrowsWhenLimitExceeded() {
+ val stream = LimitedOutputStream(LIMIT)
+ assertThrows(IOException::class.java) {
+ stream.write(ByteArray(LIMIT + 1))
+ }
+ }
+
+ @Test
+ fun testThrowsWhenCumulativeWritesExceedLimit() {
+ val stream = LimitedOutputStream(LIMIT)
+ stream.write(ByteArray(LIMIT / 2))
+ assertThrows(IOException::class.java) {
+ stream.write(ByteArray(LIMIT / 2 + 1))
+ }
+ }
+
+ private companion object {
+ const val LIMIT = 64
+ }
+}
diff --git a/FlowCrypt/src/test/java/com/flowcrypt/email/extensions/kotlin/StringExtTest.kt b/FlowCrypt/src/test/java/com/flowcrypt/email/extensions/kotlin/StringExtTest.kt
new file mode 100644
index 0000000000..a9892aaa99
--- /dev/null
+++ b/FlowCrypt/src/test/java/com/flowcrypt/email/extensions/kotlin/StringExtTest.kt
@@ -0,0 +1,28 @@
+/*
+ * © 2016-present FlowCrypt a.s. Limitations apply. Contact human@flowcrypt.com
+ * Contributors: denbond7
+ */
+
+package com.flowcrypt.email.extensions.kotlin
+
+import com.flowcrypt.email.Constants
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertThrows
+import org.junit.Test
+import java.io.IOException
+
+class StringExtTest {
+ @Test
+ fun testToEscapedHtmlEscapesSpecialCharacters() {
+ assertEquals(
+ "&"'<>/
",
+ "&\"'<>/\n".toEscapedHtml()
+ )
+ }
+
+ @Test
+ fun testToEscapedHtmlThrowsWhenOutputExceedsLimit() {
+ val source = "/".repeat(Constants.MAX_ESCAPED_HTML_OUTPUT_LENGTH_IN_CHARS)
+ assertThrows(IOException::class.java) { source.toEscapedHtml() }
+ }
+}
diff --git a/FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpArmorLimitTest.kt b/FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpArmorLimitTest.kt
new file mode 100644
index 0000000000..7f60d3d372
--- /dev/null
+++ b/FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpArmorLimitTest.kt
@@ -0,0 +1,34 @@
+/*
+ * © 2016-present FlowCrypt a.s. Limitations apply. Contact human@flowcrypt.com
+ * Contributors: denbond7
+ */
+
+package com.flowcrypt.email.security.pgp
+
+import com.flowcrypt.email.Constants
+import org.bouncycastle.openpgp.PGPException
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.io.IOException
+
+class PgpArmorLimitTest {
+ @Test
+ fun testReadSignedClearTextMessageRejectsOversizedInput() {
+ val exception: Throwable? = try {
+ PgpArmor.readSignedClearTextMessage(
+ ByteArray(Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES + 1).inputStream()
+ )
+ null
+ } catch (e: Exception) {
+ e
+ }
+
+ assertTrue("No error for oversized input", exception is PGPException)
+ assertTrue(
+ "Error is not a size limit failure: ${exception?.message}",
+ generateSequence(exception) { it.cause }.any {
+ it is IOException && it.message?.contains("exceeds the limit") == true
+ }
+ )
+ }
+}
diff --git a/FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpDecompressionLimitTest.kt b/FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpDecompressionLimitTest.kt
new file mode 100644
index 0000000000..f1d4a2f1c0
--- /dev/null
+++ b/FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpDecompressionLimitTest.kt
@@ -0,0 +1,113 @@
+/*
+ * © 2016-present FlowCrypt a.s. Limitations apply. Contact human@flowcrypt.com
+ * Contributors: denbond7
+ */
+
+package com.flowcrypt.email.security.pgp
+
+import com.flowcrypt.email.BuildConfig
+import com.flowcrypt.email.api.retrofit.response.model.DecryptErrorMsgBlock
+import jakarta.mail.Session
+import jakarta.mail.internet.MimeBodyPart
+import jakarta.mail.internet.MimeMessage
+import jakarta.mail.internet.MimeMultipart
+import jakarta.mail.util.ByteArrayDataSource
+import org.bouncycastle.bcpg.CompressionAlgorithmTags
+import org.bouncycastle.openpgp.PGPCompressedDataGenerator
+import org.bouncycastle.openpgp.PGPLiteralData
+import org.bouncycastle.openpgp.PGPLiteralDataGenerator
+import org.bouncycastle.openpgp.PGPSecretKeyRingCollection
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.pgpainless.key.protection.SecretKeyRingProtector
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.annotation.Config
+import java.io.ByteArrayOutputStream
+import java.util.Date
+import java.util.Properties
+
+@RunWith(RobolectricTestRunner::class)
+@Config(manifest = Config.NONE, sdk = [BuildConfig.MIN_SDK_VERSION])
+class PgpDecompressionLimitTest {
+ @Test
+ fun testBombAttachmentProducesBoundedErrorBlock() {
+ val message = MimeMessage(Session.getInstance(Properties()))
+ val multipart = MimeMultipart()
+ val body = MimeBodyPart()
+ body.setText("message")
+ multipart.addBodyPart(body)
+ val attachment = MimeBodyPart()
+ attachment.setDataHandler(
+ jakarta.activation.DataHandler(
+ ByteArrayDataSource(compressLiteralData(ByteArray(DECOMPRESSED_SIZE)), "application/octet-stream")
+ )
+ )
+ attachment.fileName = "message.asc"
+ multipart.addBodyPart(attachment)
+ message.setContent(multipart)
+ message.saveChanges()
+
+ val result = PgpMsg.processMimeMessage(
+ msg = message,
+ secretKeys = PGPSecretKeyRingCollection(emptyList()),
+ protector = SecretKeyRingProtector.unprotectedKeys()
+ )
+ assertTrue(
+ "The oversized attachment was not rejected",
+ result.blocks.filterIsInstance().any {
+ it.decryptErr?.details?.message?.contains("exceeds the limit") == true
+ }
+ )
+ assertTrue(
+ "Rendered block grew beyond the decompression limit",
+ result.blocks.all { (it.content?.length ?: 0) < DECOMPRESSED_SIZE }
+ )
+ }
+
+ @Test
+ fun testDecompressionBeyondLimitIsRejected() {
+ val compressed = compressLiteralData(ByteArray(DECOMPRESSED_SIZE))
+ val result = PgpDecryptAndOrVerify.decryptAndOrVerifyWithResult(
+ srcInputStream = compressed.inputStream()
+ )
+ assertNull("Unbounded decompression result was returned", result.content)
+ assertNotNull("No error reported", result.exception)
+ }
+
+ @Test
+ fun testDecompressionWithinLimitSucceeds() {
+ val compressed = compressLiteralData(ByteArray(ONE_MB))
+ val result = PgpDecryptAndOrVerify.decryptAndOrVerifyWithResult(
+ srcInputStream = compressed.inputStream()
+ )
+ assertNull("Unexpected error", result.exception)
+ assertNotNull("Content not returned", result.content)
+ }
+
+ private fun compressLiteralData(data: ByteArray): ByteArray {
+ val compressedOutput = ByteArrayOutputStream()
+ val compressedGenerator = PGPCompressedDataGenerator(CompressionAlgorithmTags.ZIP)
+ val compressedStream = compressedGenerator.open(compressedOutput)
+ val literalGenerator = PGPLiteralDataGenerator()
+ val literalStream = literalGenerator.open(
+ compressedStream,
+ PGPLiteralData.BINARY,
+ "message.txt",
+ data.size.toLong(),
+ Date()
+ )
+ literalStream.write(data)
+ literalStream.close()
+ literalGenerator.close()
+ compressedGenerator.close()
+ return compressedOutput.toByteArray()
+ }
+
+ private companion object {
+ const val ONE_MB = 1024 * 1024
+ const val DECOMPRESSED_SIZE = 9 * ONE_MB
+ }
+}
diff --git a/FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpSignatureLimitTest.kt b/FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpSignatureLimitTest.kt
new file mode 100644
index 0000000000..bc93532c57
--- /dev/null
+++ b/FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpSignatureLimitTest.kt
@@ -0,0 +1,36 @@
+/*
+ * © 2016-present FlowCrypt a.s. Limitations apply. Contact human@flowcrypt.com
+ * Contributors: denbond7
+ */
+
+package com.flowcrypt.email.security.pgp
+
+import com.flowcrypt.email.Constants
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.io.IOException
+
+class PgpSignatureLimitTest {
+ @Test
+ fun testExtractClearTextRejectsOversizedContent() {
+ val source = "-----BEGIN PGP SIGNED MESSAGE-----\n" +
+ "Hash: SHA256\n\n" +
+ "a".repeat(Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES + 1) + "\n" +
+ "-----BEGIN PGP SIGNATURE-----\n\n-----END PGP SIGNATURE-----"
+
+ val exception: Throwable? = try {
+ PgpSignature.extractClearText(source, isSilent = false)
+ null
+ } catch (e: Exception) {
+ e
+ }
+
+ assertTrue("No error for oversized cleartext", exception != null)
+ assertTrue(
+ "Error is not a size limit failure: ${exception?.message}",
+ generateSequence(exception) { it.cause }.any {
+ it is IOException && it.message?.contains("exceeds the limit") == true
+ }
+ )
+ }
+}
From f26e5093887d8021c8d20975206833f0786d2508 Mon Sep 17 00:00:00 2001
From: martgil <46025304+martgil@users.noreply.github.com>
Date: Tue, 24 Nov 2026 20:31:35 +0800
Subject: [PATCH 2/3] fix: keep large attachments usable and close
text-attachment bypass
---
.../java/com/flowcrypt/email/Constants.kt | 9 +++-
.../response/model/MsgBlockFactory.kt | 3 +-
.../email/core/msg/RawBlockParser.kt | 8 ++--
.../email/extensions/kotlin/StringExt.kt | 43 +++++++++----------
.../jetpack/viewmodel/DecryptDataViewModel.kt | 2 +-
.../flowcrypt/email/security/pgp/PgpMsg.kt | 8 ++++
.../email/extensions/kotlin/StringExtTest.kt | 2 +-
.../security/pgp/PgpDecompressionLimitTest.kt | 31 ++++++++++++-
8 files changed, 74 insertions(+), 32 deletions(-)
diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/Constants.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/Constants.kt
index 759405d2f5..d310d2886f 100644
--- a/FlowCrypt/src/main/java/com/flowcrypt/email/Constants.kt
+++ b/FlowCrypt/src/main/java/com/flowcrypt/email/Constants.kt
@@ -80,10 +80,17 @@ class Constants {
*/
const val MAX_PGP_MESSAGE_SIZE_IN_BYTES = 4 * 1024 * 1024
+ /**
+ * The max size of a buffered message part or attachment. Larger parts are reported
+ * as an error block instead of being loaded into memory.
+ */
+ const val MAX_ATTACHMENT_SIZE_IN_BYTES = 25 * 1024 * 1024
+
/**
* The max length of an HTML escaped string built from untrusted content.
+ * Six times [MAX_PGP_MESSAGE_SIZE_IN_BYTES] covers the worst case expansion.
*/
- const val MAX_ESCAPED_HTML_OUTPUT_LENGTH_IN_CHARS = 4 * 1024 * 1024
+ const val MAX_ESCAPED_HTML_OUTPUT_LENGTH_IN_CHARS = 24 * 1024 * 1024
const val FORWARDED_ATTACHMENTS_CACHE_DIR = "forwarded"
const val ATTACHMENTS_CACHE_DIR = "attachments"
diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/api/retrofit/response/model/MsgBlockFactory.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/api/retrofit/response/model/MsgBlockFactory.kt
index bca6fa32c6..721433550f 100644
--- a/FlowCrypt/src/main/java/com/flowcrypt/email/api/retrofit/response/model/MsgBlockFactory.kt
+++ b/FlowCrypt/src/main/java/com/flowcrypt/email/api/retrofit/response/model/MsgBlockFactory.kt
@@ -91,7 +91,6 @@ object MsgBlockFactory {
isOpenPGPMimeSigned: Boolean
): MsgBlock {
try {
- val attContent = mimePart.content
val data = rawBlock.content
val attMeta = AttMeta(
name = mimePart.fileName,
@@ -100,7 +99,7 @@ object MsgBlockFactory {
type = mimePart.contentType,
contentId = mimePart.contentID
)
- val content = if (attContent is String) mimePart.content as String else null
+ val content = if (mimePart.isMimeType("text/*")) data.decodeToString() else null
return when (type) {
MsgBlock.Type.DECRYPTED_ATT -> DecryptedAttMsgBlock(
content = null,
diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/core/msg/RawBlockParser.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/core/msg/RawBlockParser.kt
index b85fbffbf7..4244dd0df3 100644
--- a/FlowCrypt/src/main/java/com/flowcrypt/email/core/msg/RawBlockParser.kt
+++ b/FlowCrypt/src/main/java/com/flowcrypt/email/core/msg/RawBlockParser.kt
@@ -125,7 +125,7 @@ object RawBlockParser {
listOf(
RawBlock(
RawBlockType.ATTACHMENT,
- mimePart.inputStream.readBytesWithLimit(Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES),
+ mimePart.inputStream.readBytesWithLimit(Constants.MAX_ATTACHMENT_SIZE_IN_BYTES),
isOpenPGPMimeSigned
)
)
@@ -160,7 +160,7 @@ object RawBlockParser {
listOf(
RawBlock(
RawBlockType.INLINE_ATTACHMENT,
- inputStream.readBytesWithLimit(Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES),
+ inputStream.readBytesWithLimit(Constants.MAX_ATTACHMENT_SIZE_IN_BYTES),
isOpenPGPMimeSigned
)
)
@@ -182,13 +182,13 @@ object RawBlockParser {
"text/html" == mimePart.baseContentType() -> listOf(
RawBlock(
RawBlockType.HTML_TEXT,
- mimePart.inputStream.readBytesWithLimit(Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES),
+ mimePart.inputStream.readBytesWithLimit(Constants.MAX_ATTACHMENT_SIZE_IN_BYTES),
isOpenPGPMimeSigned
)
)
else -> detectBlocks(
- mimePart.inputStream.readBytesWithLimit(Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES).decodeToString()
+ mimePart.inputStream.readBytesWithLimit(Constants.MAX_ATTACHMENT_SIZE_IN_BYTES).decodeToString()
).map {
it.copy(isOpenPGPMimeSigned = isOpenPGPMimeSigned)
}
diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/extensions/kotlin/StringExt.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/extensions/kotlin/StringExt.kt
index bfade0a16f..2c47093480 100644
--- a/FlowCrypt/src/main/java/com/flowcrypt/email/extensions/kotlin/StringExt.kt
+++ b/FlowCrypt/src/main/java/com/flowcrypt/email/extensions/kotlin/StringExt.kt
@@ -63,33 +63,32 @@ fun String.removeUtf8Bom(): String {
}
fun String.toEscapedHtml(): String {
- val result = StringBuilder(length)
+ val expectedLength = fold(0L) { length, char ->
+ length + (htmlEscapeReplacement(char)?.length ?: 1)
+ }
+ if (expectedLength > Constants.MAX_ESCAPED_HTML_OUTPUT_LENGTH_IN_CHARS) {
+ throw IOException("The escaped HTML exceeds the limit of $Constants.MAX_ESCAPED_HTML_OUTPUT_LENGTH_IN_CHARS characters")
+ }
+
+ val result = StringBuilder(expectedLength.toInt())
for (char in this) {
- val replacement = when (char) {
- '&' -> "&"
- '"' -> """
- '\'' -> "'"
- '<' -> "<"
- '>' -> ">"
- '/' -> "/"
- '\n' -> "
"
- else -> null
- }
- if (replacement == null) {
- if (result.length >= Constants.MAX_ESCAPED_HTML_OUTPUT_LENGTH_IN_CHARS) {
- throw IOException("The escaped HTML exceeds the limit of $Constants.MAX_ESCAPED_HTML_OUTPUT_LENGTH_IN_CHARS characters")
- }
- result.append(char)
- } else {
- if (result.length + replacement.length > Constants.MAX_ESCAPED_HTML_OUTPUT_LENGTH_IN_CHARS) {
- throw IOException("The escaped HTML exceeds the limit of $Constants.MAX_ESCAPED_HTML_OUTPUT_LENGTH_IN_CHARS characters")
- }
- result.append(replacement)
- }
+ val replacement = htmlEscapeReplacement(char)
+ if (replacement == null) result.append(char) else result.append(replacement)
}
return result.toString()
}
+private fun htmlEscapeReplacement(char: Char): String? = when (char) {
+ '&' -> "&"
+ '"' -> """
+ '\'' -> "'"
+ '<' -> "<"
+ '>' -> ">"
+ '/' -> "/"
+ '\n' -> "
"
+ else -> null
+}
+
fun String.unescapeHtml(): String {
// Comment from Typescript:
// the at the end is replaced with an actual NBSP character, not a space character.
diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/jetpack/viewmodel/DecryptDataViewModel.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/jetpack/viewmodel/DecryptDataViewModel.kt
index 963a0b71a9..cd453e24da 100644
--- a/FlowCrypt/src/main/java/com/flowcrypt/email/jetpack/viewmodel/DecryptDataViewModel.kt
+++ b/FlowCrypt/src/main/java/com/flowcrypt/email/jetpack/viewmodel/DecryptDataViewModel.kt
@@ -26,7 +26,7 @@ abstract class DecryptDataViewModel(application: Application) : AccountViewModel
): ByteArray =
withContext(Dispatchers.IO) {
inputStream.use {
- val byteArrayOutputStream = LimitedOutputStream(Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES)
+ val byteArrayOutputStream = LimitedOutputStream(Constants.MAX_ATTACHMENT_SIZE_IN_BYTES)
val pgpSecretKeyRings = KeysStorageImpl.getInstance(context).getPGPSecretKeyRings()
val pgpSecretKeyRingCollection = PGPSecretKeyRingCollection(pgpSecretKeyRings)
val protector = KeysStorageImpl.getInstance(context).getSecretKeyRingProtector()
diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpMsg.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpMsg.kt
index 8f02832c5a..934960d341 100644
--- a/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpMsg.kt
+++ b/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpMsg.kt
@@ -323,6 +323,14 @@ object PgpMsg {
if (GeneralUtil.isDebugBuild()) {
e.printStackTrace()
}
+ blocks.add(
+ GenericMsgBlock(
+ MsgBlock.Type.UNKNOWN,
+ null,
+ MsgBlockError(e.javaClass.simpleName + ": " + e.message),
+ isOpenPGPMimeSigned
+ )
+ )
}
}
diff --git a/FlowCrypt/src/test/java/com/flowcrypt/email/extensions/kotlin/StringExtTest.kt b/FlowCrypt/src/test/java/com/flowcrypt/email/extensions/kotlin/StringExtTest.kt
index a9892aaa99..adb17c4b09 100644
--- a/FlowCrypt/src/test/java/com/flowcrypt/email/extensions/kotlin/StringExtTest.kt
+++ b/FlowCrypt/src/test/java/com/flowcrypt/email/extensions/kotlin/StringExtTest.kt
@@ -22,7 +22,7 @@ class StringExtTest {
@Test
fun testToEscapedHtmlThrowsWhenOutputExceedsLimit() {
- val source = "/".repeat(Constants.MAX_ESCAPED_HTML_OUTPUT_LENGTH_IN_CHARS)
+ val source = "/".repeat(Constants.MAX_ESCAPED_HTML_OUTPUT_LENGTH_IN_CHARS / 6 + 1)
assertThrows(IOException::class.java) { source.toEscapedHtml() }
}
}
diff --git a/FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpDecompressionLimitTest.kt b/FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpDecompressionLimitTest.kt
index f1d4a2f1c0..9f57c2f566 100644
--- a/FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpDecompressionLimitTest.kt
+++ b/FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpDecompressionLimitTest.kt
@@ -6,7 +6,9 @@
package com.flowcrypt.email.security.pgp
import com.flowcrypt.email.BuildConfig
+import com.flowcrypt.email.Constants
import com.flowcrypt.email.api.retrofit.response.model.DecryptErrorMsgBlock
+import com.flowcrypt.email.api.retrofit.response.model.PlainAttMsgBlock
import jakarta.mail.Session
import jakarta.mail.internet.MimeBodyPart
import jakarta.mail.internet.MimeMessage
@@ -63,7 +65,34 @@ class PgpDecompressionLimitTest {
)
assertTrue(
"Rendered block grew beyond the decompression limit",
- result.blocks.all { (it.content?.length ?: 0) < DECOMPRESSED_SIZE }
+ result.blocks.all { (it.content?.length ?: 0) < Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES }
+ )
+ }
+
+ @Test
+ fun testTextAttachmentContentComesFromBoundedRawBlock() {
+ val message = MimeMessage(Session.getInstance(Properties()))
+ val multipart = MimeMultipart()
+ val body = MimeBodyPart()
+ body.setText("message")
+ multipart.addBodyPart(body)
+ val attachment = MimeBodyPart()
+ attachment.setDataHandler(
+ jakarta.activation.DataHandler(ByteArrayDataSource("hello".toByteArray(), "text/plain"))
+ )
+ attachment.fileName = "note.txt"
+ multipart.addBodyPart(attachment)
+ message.setContent(multipart)
+ message.saveChanges()
+
+ val result = PgpMsg.processMimeMessage(
+ msg = message,
+ secretKeys = PGPSecretKeyRingCollection(emptyList()),
+ protector = SecretKeyRingProtector.unprotectedKeys()
+ )
+ assertTrue(
+ "Text attachment content mismatch",
+ result.blocks.filterIsInstance().any { it.content == "hello" }
)
}
From 0e68d117bcfc69ca7e9f9f5618493812a24b69ac Mon Sep 17 00:00:00 2001
From: martgil <46025304+martgil@users.noreply.github.com>
Date: Tue, 24 Nov 2026 21:13:20 +0800
Subject: [PATCH 3/3] fix: allow large decrypted MIME messages while keeping
render limits
---
FlowCrypt/build.gradle.kts | 4 ++
.../security/pgp/PgpDecryptAndOrVerify.kt | 5 ++-
.../flowcrypt/email/security/pgp/PgpMsg.kt | 17 ++++---
.../security/pgp/PgpDecompressionLimitTest.kt | 31 ++++++++-----
.../security/pgp/PgpDecryptAndOrVerifyTest.kt | 45 +++++++++++++++++++
5 files changed, 84 insertions(+), 18 deletions(-)
diff --git a/FlowCrypt/build.gradle.kts b/FlowCrypt/build.gradle.kts
index e4c917df7c..3199238ace 100644
--- a/FlowCrypt/build.gradle.kts
+++ b/FlowCrypt/build.gradle.kts
@@ -432,6 +432,10 @@ easylauncher {
}
}
+tasks.withType().configureEach {
+ maxHeapSize = "1024m"
+}
+
tasks.register("checkCorrectBranch") {
val branchName = gitBranchName
doLast {
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 d7ace4df1e..c11cc8ec74 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
@@ -68,10 +68,11 @@ object PgpDecryptAndOrVerify {
secretKeys: PGPSecretKeyRingCollection? = null,
protector: SecretKeyRingProtector? = null,
passphrase: Passphrase? = null,
- ignoreMdcErrors: Boolean = false
+ ignoreMdcErrors: Boolean = false,
+ maxOutputBytes: Int = Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES
): DecryptionResult {
srcInputStream.use { srcStream ->
- val destOutputStream = LimitedOutputStream(Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES)
+ val destOutputStream = LimitedOutputStream(maxOutputBytes)
destOutputStream.use { outStream ->
try {
val decryptionStream = genDecryptionStream(
diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpMsg.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpMsg.kt
index 934960d341..15fcf50b15 100644
--- a/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpMsg.kt
+++ b/FlowCrypt/src/main/java/com/flowcrypt/email/security/pgp/PgpMsg.kt
@@ -1104,7 +1104,8 @@ object PgpMsg {
srcInputStream = rawBlock.content.inputStream(),
publicKeys = verificationPublicKeys,
secretKeys = secretKeys,
- protector = protector
+ protector = protector,
+ maxOutputBytes = Constants.MAX_ATTACHMENT_SIZE_IN_BYTES
)
val blocks = mutableListOf()
@@ -1141,12 +1142,14 @@ object PgpMsg {
// message that was actually fully armored (text not visible) with a mime msg inside
// ... -> in which case the user would I think see full mime content?
// ------------------------------------------------------------------------------------
+ val verifiedContent = decryptionResult.content?.toByteArray()
+ if (verifiedContent != null && verifiedContent.size > Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES) {
+ throw java.io.IOException("The decrypted message exceeds the limit of ${Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES} bytes")
+ }
blocks.add(
MsgBlockFactory.fromContent(
type = MsgBlock.Type.VERIFIED_MSG,
- content = decryptionResult.content?.toString(
- StandardCharsets.UTF_8.displayName()
- )?.toEscapedHtml(),
+ content = verifiedContent?.let { String(it, StandardCharsets.UTF_8) }?.toEscapedHtml(),
signature = decryptionResult.signature,
isOpenPGPMimeSigned = rawBlock.isOpenPGPMimeSigned
)
@@ -1159,7 +1162,8 @@ object PgpMsg {
publicKeys = verificationPublicKeys,
secretKeys = secretKeys,
protector = protector,
- ignoreMdcErrors = true
+ ignoreMdcErrors = true,
+ maxOutputBytes = Constants.MAX_ATTACHMENT_SIZE_IN_BYTES
)
val decryptErrorMsgBlock = if (resultWithIgnoredMDCErrors.exception == null) {
DecryptErrorMsgBlock(
@@ -1775,6 +1779,9 @@ object PgpMsg {
private fun fmtDecryptedAsSanitizedHtmlBlocks(decryptedContent: ByteArray?): Collection {
if (decryptedContent == null) return emptyList()
+ if (decryptedContent.size > Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES) {
+ throw java.io.IOException("The decrypted message exceeds the limit of ${Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES} bytes")
+ }
val decryptedText = String(decryptedContent)
val blocks = mutableListOf()
val strippedContent = stripFcReplyToken(extractFcAttachments(decryptedText, blocks))
diff --git a/FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpDecompressionLimitTest.kt b/FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpDecompressionLimitTest.kt
index 9f57c2f566..0d2bf74d62 100644
--- a/FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpDecompressionLimitTest.kt
+++ b/FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpDecompressionLimitTest.kt
@@ -18,6 +18,7 @@ import org.bouncycastle.bcpg.CompressionAlgorithmTags
import org.bouncycastle.openpgp.PGPCompressedDataGenerator
import org.bouncycastle.openpgp.PGPLiteralData
import org.bouncycastle.openpgp.PGPLiteralDataGenerator
+import org.bouncycastle.openpgp.PGPPublicKeyRingCollection
import org.bouncycastle.openpgp.PGPSecretKeyRingCollection
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
@@ -44,7 +45,7 @@ class PgpDecompressionLimitTest {
val attachment = MimeBodyPart()
attachment.setDataHandler(
jakarta.activation.DataHandler(
- ByteArrayDataSource(compressLiteralData(ByteArray(DECOMPRESSED_SIZE)), "application/octet-stream")
+ ByteArrayDataSource(compressLiteralData(DECOMPRESSED_SIZE), "application/octet-stream")
)
)
attachment.fileName = "message.asc"
@@ -52,20 +53,22 @@ class PgpDecompressionLimitTest {
message.setContent(multipart)
message.saveChanges()
- val result = PgpMsg.processMimeMessage(
- msg = message,
+ val blocks = PgpMsg.extractMsgBlocksFromPart(
+ part = message,
+ verificationPublicKeys = PGPPublicKeyRingCollection(emptyList()),
secretKeys = PGPSecretKeyRingCollection(emptyList()),
protector = SecretKeyRingProtector.unprotectedKeys()
)
assertTrue(
"The oversized attachment was not rejected",
- result.blocks.filterIsInstance().any {
- it.decryptErr?.details?.message?.contains("exceeds the limit") == true
+ blocks.any { block ->
+ block.error?.errorMsg?.contains("exceeds the limit") == true ||
+ (block as? DecryptErrorMsgBlock)?.decryptErr?.details?.message?.contains("exceeds the limit") == true
}
)
assertTrue(
"Rendered block grew beyond the decompression limit",
- result.blocks.all { (it.content?.length ?: 0) < Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES }
+ blocks.all { (it.content?.length ?: 0) < Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES }
)
}
@@ -98,7 +101,7 @@ class PgpDecompressionLimitTest {
@Test
fun testDecompressionBeyondLimitIsRejected() {
- val compressed = compressLiteralData(ByteArray(DECOMPRESSED_SIZE))
+ val compressed = compressLiteralData(DECOMPRESSED_SIZE)
val result = PgpDecryptAndOrVerify.decryptAndOrVerifyWithResult(
srcInputStream = compressed.inputStream()
)
@@ -108,7 +111,7 @@ class PgpDecompressionLimitTest {
@Test
fun testDecompressionWithinLimitSucceeds() {
- val compressed = compressLiteralData(ByteArray(ONE_MB))
+ val compressed = compressLiteralData(ONE_MB)
val result = PgpDecryptAndOrVerify.decryptAndOrVerifyWithResult(
srcInputStream = compressed.inputStream()
)
@@ -116,7 +119,7 @@ class PgpDecompressionLimitTest {
assertNotNull("Content not returned", result.content)
}
- private fun compressLiteralData(data: ByteArray): ByteArray {
+ private fun compressLiteralData(size: Int): ByteArray {
val compressedOutput = ByteArrayOutputStream()
val compressedGenerator = PGPCompressedDataGenerator(CompressionAlgorithmTags.ZIP)
val compressedStream = compressedGenerator.open(compressedOutput)
@@ -125,10 +128,16 @@ class PgpDecompressionLimitTest {
compressedStream,
PGPLiteralData.BINARY,
"message.txt",
- data.size.toLong(),
+ size.toLong(),
Date()
)
- literalStream.write(data)
+ val chunk = ByteArray(64 * 1024)
+ var remaining = size
+ while (remaining > 0) {
+ val count = minOf(remaining, chunk.size)
+ literalStream.write(chunk, 0, count)
+ remaining -= count
+ }
literalStream.close()
literalGenerator.close()
compressedGenerator.close()
diff --git a/FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpDecryptAndOrVerifyTest.kt b/FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpDecryptAndOrVerifyTest.kt
index f4c2c4dd6c..7c8c93ba66 100644
--- a/FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpDecryptAndOrVerifyTest.kt
+++ b/FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpDecryptAndOrVerifyTest.kt
@@ -5,6 +5,7 @@
package com.flowcrypt.email.security.pgp
+import com.flowcrypt.email.Constants
import com.flowcrypt.email.core.msg.RawBlockParser
import com.flowcrypt.email.extensions.createFileWithRandomData
import com.flowcrypt.email.extensions.kotlin.toInputStream
@@ -33,6 +34,7 @@ import org.pgpainless.key.protection.passphrase_provider.SecretKeyPassphraseProv
import org.pgpainless.util.Passphrase
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
+import java.io.InputStream
import java.nio.charset.Charset
import java.util.UUID
@@ -315,6 +317,31 @@ class PgpDecryptAndOrVerifyTest {
)
}
+ @Test
+ fun testDecryptWithAttachmentSizeLimit() {
+ val encrypted = ByteArrayOutputStream()
+ PgpEncryptAndOrSign.encryptAndOrSign(
+ srcInputStream = ZeroInputStream(Constants.MAX_PGP_MESSAGE_SIZE_IN_BYTES + 1),
+ destOutputStream = encrypted,
+ pgpPublicKeyRingCollection = PGPPublicKeyRingCollection(
+ listOf(
+ senderPGPSecretKeyRing.certificate,
+ receiverPGPSecretKeyRing.certificate
+ )
+ )
+ )
+
+ val result = PgpDecryptAndOrVerify.decryptAndOrVerifyWithResult(
+ srcInputStream = ByteArrayInputStream(encrypted.toByteArray()),
+ secretKeys = PGPSecretKeyRingCollection(listOf(receiverPGPSecretKeyRing)),
+ protector = allPredefinedKeysProtector,
+ maxOutputBytes = Constants.MAX_ATTACHMENT_SIZE_IN_BYTES
+ )
+
+ assertNull("Unexpected error", result.exception)
+ assertNotNull("Content not returned", result.content)
+ }
+
private fun testDecryptFileSuccess(shouldSrcBeArmored: Boolean) {
val srcFile = temporaryFolder.createFileWithRandomData(fileSizeInBytes = FileUtils.ONE_MB)
val sourceBytes = srcFile.readBytes()
@@ -344,6 +371,24 @@ class PgpDecryptAndOrVerifyTest {
Assert.assertArrayEquals(sourceBytes, decryptedBytesForSender)
}
+ private class ZeroInputStream(private var remaining: Int) : InputStream() {
+ private val chunk = ByteArray(64 * 1024)
+
+ override fun read(): Int {
+ if (remaining == 0) return -1
+ remaining--
+ return 0
+ }
+
+ override fun read(b: ByteArray, off: Int, len: Int): Int {
+ if (remaining == 0) return -1
+ val count = minOf(remaining, len, chunk.size)
+ System.arraycopy(chunk, 0, b, off, count)
+ remaining -= count
+ return count
+ }
+ }
+
private fun processMessage(messageKey: String): PgpDecryptAndOrVerify.DecryptionResult {
val messageInfo = findMessage(messageKey)
val result = PgpDecryptAndOrVerify.decryptAndOrVerifyWithResult(