Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions FlowCrypt/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -432,6 +432,10 @@ easylauncher {
}
}

tasks.withType<Test>().configureEach {
maxHeapSize = "1024m"
}

tasks.register("checkCorrectBranch") {
val branchName = gitBranchName
doLast {
Expand Down
18 changes: 18 additions & 0 deletions FlowCrypt/src/main/java/com/flowcrypt/email/Constants.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,6 @@ object MsgBlockFactory {
isOpenPGPMimeSigned: Boolean
): MsgBlock {
try {
val attContent = mimePart.content
val data = rawBlock.content
val attMeta = AttMeta(
name = mimePart.fileName,
Expand All @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
)
)
Expand All @@ -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
)
)
Expand All @@ -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
)
)
Expand All @@ -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
)
)
Expand All @@ -124,7 +125,7 @@ object RawBlockParser {
listOf(
RawBlock(
RawBlockType.ATTACHMENT,
mimePart.inputStream.readBytes(),
mimePart.inputStream.readBytesWithLimit(Constants.MAX_ATTACHMENT_SIZE_IN_BYTES),
isOpenPGPMimeSigned
)
)
Expand Down Expand Up @@ -159,7 +160,7 @@ object RawBlockParser {
listOf(
RawBlock(
RawBlockType.INLINE_ATTACHMENT,
inputStream.readBytes(),
inputStream.readBytesWithLimit(Constants.MAX_ATTACHMENT_SIZE_IN_BYTES),
isOpenPGPMimeSigned
)
)
Expand All @@ -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)
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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")
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -61,13 +63,30 @@ fun String.removeUtf8Bom(): String {
}

fun String.toEscapedHtml(): String {
return this.replace("&", "&amp;")
.replace("\"", "&quot;")
.replace("'", "&#39;")
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace("/", "&#x2F;")
.replace("\n", "<br>")
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) {
'&' -> "&amp;"
'"' -> "&quot;"
'\'' -> "&#39;"
'<' -> "&lt;"
'>' -> "&gt;"
'/' -> "&#x2F;"
'\n' -> "<br>"
else -> null
}

fun String.unescapeHtml(): String {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

/**
Expand All @@ -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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,18 @@
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
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
Expand Down Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down
Loading
Loading