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/Constants.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/Constants.kt index c1b13b5c94..d310d2886f 100644 --- a/FlowCrypt/src/main/java/com/flowcrypt/email/Constants.kt +++ b/FlowCrypt/src/main/java/com/flowcrypt/email/Constants.kt @@ -74,6 +74,24 @@ 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 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 = 24 * 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/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 52721de07c..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 @@ -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_ATTACHMENT_SIZE_IN_BYTES), isOpenPGPMimeSigned ) ) @@ -159,7 +160,7 @@ object RawBlockParser { listOf( RawBlock( RawBlockType.INLINE_ATTACHMENT, - inputStream.readBytes(), + inputStream.readBytesWithLimit(Constants.MAX_ATTACHMENT_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_ATTACHMENT_SIZE_IN_BYTES), isOpenPGPMimeSigned ) ) - else -> detectBlocks(mimePart.inputStream.readText()).map { + else -> detectBlocks( + 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/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..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 @@ -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,30 @@ fun String.removeUtf8Bom(): String { } fun String.toEscapedHtml(): String { - return this.replace("&", "&") - .replace("\"", """) - .replace("'", "'") - .replace("<", "<") - .replace(">", ">") - .replace("/", "/") - .replace("\n", "
") + 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 = 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 { 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..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 @@ -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_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/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..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 @@ -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 @@ -66,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 = ByteArrayOutputStream() + 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 d6e77add5e..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 @@ -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() @@ -322,6 +323,14 @@ object PgpMsg { if (GeneralUtil.isDebugBuild()) { e.printStackTrace() } + blocks.add( + GenericMsgBlock( + MsgBlock.Type.UNKNOWN, + null, + MsgBlockError(e.javaClass.simpleName + ": " + e.message), + isOpenPGPMimeSigned + ) + ) } } @@ -1095,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() @@ -1132,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 ) @@ -1150,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( @@ -1766,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/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..adb17c4b09 --- /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 / 6 + 1) + 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..0d2bf74d62 --- /dev/null +++ b/FlowCrypt/src/test/java/com/flowcrypt/email/security/pgp/PgpDecompressionLimitTest.kt @@ -0,0 +1,151 @@ +/* + * © 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.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 +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.PGPPublicKeyRingCollection +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(DECOMPRESSED_SIZE), "application/octet-stream") + ) + ) + attachment.fileName = "message.asc" + multipart.addBodyPart(attachment) + message.setContent(multipart) + message.saveChanges() + + val blocks = PgpMsg.extractMsgBlocksFromPart( + part = message, + verificationPublicKeys = PGPPublicKeyRingCollection(emptyList()), + secretKeys = PGPSecretKeyRingCollection(emptyList()), + protector = SecretKeyRingProtector.unprotectedKeys() + ) + assertTrue( + "The oversized attachment was not rejected", + 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", + 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" } + ) + } + + @Test + fun testDecompressionBeyondLimitIsRejected() { + val compressed = compressLiteralData(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(ONE_MB) + val result = PgpDecryptAndOrVerify.decryptAndOrVerifyWithResult( + srcInputStream = compressed.inputStream() + ) + assertNull("Unexpected error", result.exception) + assertNotNull("Content not returned", result.content) + } + + private fun compressLiteralData(size: Int): 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", + size.toLong(), + Date() + ) + 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() + 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/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( 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 + } + ) + } +}