From df0b39498e1219d16262a8508d1925242afdafbc Mon Sep 17 00:00:00 2001 From: martgil <46025304+martgil@users.noreply.github.com> Date: Fri, 27 Nov 2026 18:18:36 +0800 Subject: [PATCH 1/3] fix(attachment): cap untrusted attachment size and copies Use Long arithmetic for attachment size checks, normalize invalid provider reports, and enforce a hard byte ceiling on every copy of a provider-supplied stream. --- .../flowcrypt/email/api/email/EmailUtil.kt | 26 +++--- .../jetpack/viewmodel/PrivateKeysViewModel.kt | 8 +- .../providers/EmbeddedAttachmentsProvider.kt | 3 +- .../ProcessingOutgoingMessageInfoHelper.kt | 16 +++- .../fragment/CreateMessageFragment.kt | 21 +++-- .../email/util/AttachmentSizeValidator.kt | 85 ++++++++++++++++++ .../api/email/EmailUtilAttachmentInfoTest.kt | 89 +++++++++++++++++++ .../email/util/AttachmentSizeValidatorTest.kt | 89 +++++++++++++++++++ 8 files changed, 315 insertions(+), 22 deletions(-) create mode 100644 FlowCrypt/src/main/java/com/flowcrypt/email/util/AttachmentSizeValidator.kt create mode 100644 FlowCrypt/src/test/java/com/flowcrypt/email/api/email/EmailUtilAttachmentInfoTest.kt create mode 100644 FlowCrypt/src/test/java/com/flowcrypt/email/util/AttachmentSizeValidatorTest.kt diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/api/email/EmailUtil.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/api/email/EmailUtil.kt index 64f9cb50cb..391ab6982a 100644 --- a/FlowCrypt/src/main/java/com/flowcrypt/email/api/email/EmailUtil.kt +++ b/FlowCrypt/src/main/java/com/flowcrypt/email/api/email/EmailUtil.kt @@ -38,6 +38,7 @@ import com.flowcrypt.email.security.SecurityUtils import com.flowcrypt.email.security.model.PgpKeyRingDetails import com.flowcrypt.email.security.pgp.PgpDecryptAndOrVerify import com.flowcrypt.email.security.pgp.PgpEncryptAndOrSign +import com.flowcrypt.email.util.AttachmentSizeValidator import com.flowcrypt.email.util.GeneralUtil import com.flowcrypt.email.util.OutgoingMessagesManager import com.flowcrypt.email.util.SharedPreferencesHelper @@ -180,21 +181,26 @@ class EmailUtil { ), null, null, null ) if (cursor != null) { - if (cursor.moveToFirst()) { - val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME) - if (nameIndex != -1) { - attInfoBuilder.name = cursor.getString(nameIndex) - } + cursor.use { + if (it.moveToFirst()) { + val nameIndex = it.getColumnIndex(OpenableColumns.DISPLAY_NAME) + if (nameIndex != -1) { + attInfoBuilder.name = SecurityUtils.sanitizeFileName(it.getString(nameIndex)) + } - val sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE) - if (sizeIndex != -1) { - attInfoBuilder.encodedSize = cursor.getLong(sizeIndex) + val sizeIndex = it.getColumnIndex(OpenableColumns.SIZE) + if (sizeIndex != -1) { + attInfoBuilder.encodedSize = + AttachmentSizeValidator.normalizeReportedSize(it.getLong(sizeIndex)) + } } } - cursor.close() } else if (ContentResolver.SCHEME_FILE.equals(uri.scheme, ignoreCase = true)) { attInfoBuilder.name = GeneralUtil.getFileNameFromUri(context, uri) - attInfoBuilder.encodedSize = GeneralUtil.getFileSizeFromUri(context, uri) + ?.let { SecurityUtils.sanitizeFileName(it) } + attInfoBuilder.encodedSize = AttachmentSizeValidator.normalizeReportedSize( + GeneralUtil.getFileSizeFromUri(context, uri) + ) } return attInfoBuilder.build() diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/jetpack/viewmodel/PrivateKeysViewModel.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/jetpack/viewmodel/PrivateKeysViewModel.kt index 3aa5223798..d224d6e207 100644 --- a/FlowCrypt/src/main/java/com/flowcrypt/email/jetpack/viewmodel/PrivateKeysViewModel.kt +++ b/FlowCrypt/src/main/java/com/flowcrypt/email/jetpack/viewmodel/PrivateKeysViewModel.kt @@ -38,6 +38,7 @@ import com.flowcrypt.email.security.SecurityUtils import com.flowcrypt.email.security.model.PgpKeyRingDetails import com.flowcrypt.email.security.pgp.PgpKey import com.flowcrypt.email.service.actionqueue.actions.BackupPrivateKeyToInboxAction +import com.flowcrypt.email.util.AttachmentSizeValidator import com.flowcrypt.email.util.GeneralUtil import com.flowcrypt.email.util.coroutines.runners.ControlledRunner import com.flowcrypt.email.util.exception.ApiException @@ -347,8 +348,11 @@ class PrivateKeysViewModel(application: Application) : AccountViewModel(applicat throw NullPointerException("Uri is null!") } - val source = context.contentResolver.openInputStream(keyImportModel.fileUri) - ?: throw java.lang.IllegalStateException(sourceNotAvailableMsg) + val source = AttachmentSizeValidator.limitedInputStream( + context.contentResolver.openInputStream(keyImportModel.fileUri) + ?: throw java.lang.IllegalStateException(sourceNotAvailableMsg), + MAX_SIZE_IN_BYTES.toLong() + ) parseKeyResult = PgpKey.parseKeys( source = source, throwExceptionIfUnknownSource = false diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/providers/EmbeddedAttachmentsProvider.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/providers/EmbeddedAttachmentsProvider.kt index 786ad9a7e9..c8d195f367 100644 --- a/FlowCrypt/src/main/java/com/flowcrypt/email/providers/EmbeddedAttachmentsProvider.kt +++ b/FlowCrypt/src/main/java/com/flowcrypt/email/providers/EmbeddedAttachmentsProvider.kt @@ -112,7 +112,8 @@ class EmbeddedAttachmentsProvider : DocumentsProvider() { val cacheSize = max(maxMemory / 4, FileUtils.ONE_MB * 25).toInt() lruCache = object : LruCache(cacheSize) { override fun sizeOf(key: String, value: AttachmentInfo): Int { - return value.rawData?.size ?: value.encodedSize.toInt() + return value.rawData?.size + ?: value.encodedSize.coerceIn(0, Int.MAX_VALUE.toLong()).toInt() } } } diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/service/ProcessingOutgoingMessageInfoHelper.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/service/ProcessingOutgoingMessageInfoHelper.kt index d30b56885c..98168a75a6 100644 --- a/FlowCrypt/src/main/java/com/flowcrypt/email/service/ProcessingOutgoingMessageInfoHelper.kt +++ b/FlowCrypt/src/main/java/com/flowcrypt/email/service/ProcessingOutgoingMessageInfoHelper.kt @@ -22,12 +22,12 @@ import com.flowcrypt.email.extensions.replaceWithCachedRecipients import com.flowcrypt.email.model.MessageEncryptionType import com.flowcrypt.email.security.SecurityUtils import com.flowcrypt.email.security.pgp.PgpEncryptAndOrSign +import com.flowcrypt.email.util.AttachmentSizeValidator import com.flowcrypt.email.util.FileAndDirectoryUtils import com.flowcrypt.email.util.OutgoingAttachmentUriValidator import jakarta.mail.Message import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext -import org.apache.commons.io.FileUtils import java.io.ByteArrayInputStream import java.io.File import java.io.IOException @@ -122,8 +122,16 @@ object ProcessingOutgoingMessageInfoHelper { if (origFileUri != null) { OutgoingAttachmentUriValidator.requireAllowedUri(context, origFileUri) originalFileInputStream = context.contentResolver.openInputStream(origFileUri) + ?.let { + AttachmentSizeValidator.limitedInputStream( + it, Constants.MAX_TOTAL_ATTACHMENT_SIZE_IN_BYTES + ) + } } else if (attachmentInfo.rawData?.isNotEmpty() == true) { - originalFileInputStream = ByteArrayInputStream(attachmentInfo.rawData) + originalFileInputStream = AttachmentSizeValidator.limitedInputStream( + ByteArrayInputStream(attachmentInfo.rawData), + Constants.MAX_TOTAL_ATTACHMENT_SIZE_IN_BYTES + ) } if (originalFileInputStream == null) { @@ -155,7 +163,9 @@ object ProcessingOutgoingMessageInfoHelper { FileAndDirectoryUtils.createFileWithIncreasedIndex(attsCacheDir, cachedAtt.name) } - FileUtils.copyInputStreamToFile(originalFileInputStream, cachedAtt) + AttachmentSizeValidator.copyInputStreamToFile( + originalFileInputStream, cachedAtt, Constants.MAX_TOTAL_ATTACHMENT_SIZE_IN_BYTES + ) uri = Uri.fromFile(cachedAtt) } diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/CreateMessageFragment.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/CreateMessageFragment.kt index 2387531e78..58954b81b8 100644 --- a/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/CreateMessageFragment.kt +++ b/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/CreateMessageFragment.kt @@ -109,6 +109,7 @@ import com.flowcrypt.email.ui.adapter.AutoCompleteResultRecyclerViewAdapter import com.flowcrypt.email.ui.adapter.FromAddressesAdapter import com.flowcrypt.email.ui.adapter.RecipientChipRecyclerViewAdapter import com.flowcrypt.email.ui.adapter.recyclerview.itemdecoration.MarginItemDecoration +import com.flowcrypt.email.util.AttachmentSizeValidator import com.flowcrypt.email.util.EmailSignatureUtil import com.flowcrypt.email.util.FileAndDirectoryUtils import com.flowcrypt.email.util.GeneralUtil @@ -636,6 +637,9 @@ class CreateMessageFragment : BaseFragment(), !ContentResolver.SCHEME_FILE.equals(it.uri?.scheme, ignoreCase = true) }?.forEach { attachmentInfo -> val uri = attachmentInfo.uri ?: return@forEach + val remainingBytes = AttachmentSizeValidator.remainingBudget( + composeMsgViewModel.attachmentsStateFlow.value.map { it.encodedSize } + ) if (hasAbilityToAddAtt(attachmentInfo)) { val fileName = attachmentInfo.getSafeName() var draftAtt = try { @@ -653,9 +657,14 @@ class CreateMessageFragment : BaseFragment(), try { requireContext().contentResolver.openInputStream(uri)?.use { inputStream -> - FileUtils.copyInputStreamToFile(inputStream, draftAtt) + AttachmentSizeValidator.copyInputStreamToFile(inputStream, draftAtt, remainingBytes) composeMsgViewModel.addAttachments( - listOf(attachmentInfo.copy(uri = Uri.fromFile(draftAtt))) + listOf( + attachmentInfo.copy( + uri = Uri.fromFile(draftAtt), + encodedSize = draftAtt.length() + ) + ) ) } } catch (e: IOException) { @@ -1058,10 +1067,10 @@ class CreateMessageFragment : BaseFragment(), * @return true if the attachment can be added, otherwise false. */ private fun hasAbilityToAddAtt(newAttInfo: AttachmentInfo?): Boolean { - val existedAttsSize = - (composeMsgViewModel.attachmentsStateFlow.value.sumOf { it.encodedSize.toInt() }) - val newAttSize = newAttInfo?.encodedSize?.toInt() ?: 0 - return (existedAttsSize + newAttSize) < Constants.MAX_TOTAL_ATTACHMENT_SIZE_IN_BYTES + return AttachmentSizeValidator.canAddAttachment( + composeMsgViewModel.attachmentsStateFlow.value.map { it.encodedSize }, + newAttInfo?.encodedSize + ) } diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/util/AttachmentSizeValidator.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/util/AttachmentSizeValidator.kt new file mode 100644 index 0000000000..73b9b6ce1d --- /dev/null +++ b/FlowCrypt/src/main/java/com/flowcrypt/email/util/AttachmentSizeValidator.kt @@ -0,0 +1,85 @@ +/* + * © 2016-present FlowCrypt a.s. Limitations apply. Contact human@flowcrypt.com + * Contributors: denbond7 + */ + +package com.flowcrypt.email.util + +import com.flowcrypt.email.Constants +import java.io.File +import java.io.FilterInputStream +import java.io.IOException +import java.io.InputStream + +/** + * Keeps attachment sizes in [Long] and enforces a byte ceiling while reading untrusted streams. + * + * A content provider reports the size of an attachment. That report is not authoritative: it can + * be negative, unknown or far larger than the real content. The limit must be checked with [Long] + * arithmetic and the number of bytes actually read must be capped. + */ +object AttachmentSizeValidator { + /** Turn a missing or negative provider report into a usable size. */ + fun normalizeReportedSize(size: Long?): Long = if (size == null || size < 0) 0 else size + + /** Bytes left for another attachment in the current message. */ + fun remainingBudget(existingSizes: Collection): Long { + var total = 0L + for (size in existingSizes) { + if (size < 0) return 0L + total = safeAdd(total, size) ?: return 0L + } + return (Constants.MAX_TOTAL_ATTACHMENT_SIZE_IN_BYTES - total).coerceAtLeast(0L) + } + + fun canAddAttachment(existingSizes: Collection, newSize: Long?): Boolean { + if (newSize == null || newSize < 0) return false + return newSize < remainingBudget(existingSizes) + } + + /** Wrap [input] so reads past [maxBytes] fail instead of growing without a bound. */ + fun limitedInputStream(input: InputStream, maxBytes: Long): InputStream = + LimitedInputStream(input, maxBytes) + + /** Copy at most [maxBytes] bytes, removing a partial file when the limit is exceeded. */ + @Throws(IOException::class) + fun copyInputStreamToFile(input: InputStream, destination: File, maxBytes: Long) { + try { + input.use { source -> + limitedInputStream(source, maxBytes).use { limited -> + java.io.FileOutputStream(destination).use { output -> limited.copyTo(output) } + } + } + } catch (e: IOException) { + destination.delete() + throw e + } + } + + private fun safeAdd(first: Long, second: Long): Long? = + if (first > Long.MAX_VALUE - second) null else first + second + + private class LimitedInputStream(input: InputStream, private val maxBytes: Long) : + FilterInputStream(input) { + private var bytesRead = 0L + + override fun read(): Int { + val result = super.read() + if (result >= 0) count(1) + return result + } + + override fun read(bytes: ByteArray, offset: Int, length: Int): Int { + val result = super.read(bytes, offset, length) + if (result > 0) count(result.toLong()) + return result + } + + private fun count(count: Long) { + bytesRead += count + if (bytesRead > maxBytes) { + throw IOException("Attachment exceeds the allowed size limit") + } + } + } +} diff --git a/FlowCrypt/src/test/java/com/flowcrypt/email/api/email/EmailUtilAttachmentInfoTest.kt b/FlowCrypt/src/test/java/com/flowcrypt/email/api/email/EmailUtilAttachmentInfoTest.kt new file mode 100644 index 0000000000..c741ec3ed1 --- /dev/null +++ b/FlowCrypt/src/test/java/com/flowcrypt/email/api/email/EmailUtilAttachmentInfoTest.kt @@ -0,0 +1,89 @@ +/* + * © 2016-present FlowCrypt a.s. Limitations apply. Contact human@flowcrypt.com + * Contributors: denbond7 + */ + +package com.flowcrypt.email.api.email + +import android.content.ContentProvider +import android.content.ContentValues +import android.content.Context +import android.database.Cursor +import android.database.MatrixCursor +import android.net.Uri +import android.provider.OpenableColumns +import androidx.test.core.app.ApplicationProvider +import com.flowcrypt.email.BuildConfig +import com.flowcrypt.email.util.AttachmentSizeValidator +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import org.robolectric.shadows.ShadowContentResolver + +@RunWith(RobolectricTestRunner::class) +@Config(manifest = Config.NONE, minSdk = BuildConfig.MIN_SDK_VERSION) +class EmailUtilAttachmentInfoTest { + private val context: Context + get() = ApplicationProvider.getApplicationContext() + + @Test + fun getAttInfoFromUriNormalizesNegativeReportedSize() { + val uri = registerProvider("negative", -1L, "payload.txt") + + val attInfo = requireNotNull(EmailUtil.getAttInfoFromUri(context, uri)) + + assertEquals(0L, attInfo.encodedSize) + } + + @Test + fun getAttInfoFromUriKeepsWrappedReportedSizeOutOfValidRange() { + val size = Int.MAX_VALUE.toLong() + 1 + val uri = registerProvider("wrapped", size, "payload.txt") + + val attInfo = requireNotNull(EmailUtil.getAttInfoFromUri(context, uri)) + + assertEquals(size, attInfo.encodedSize) + assertFalse(AttachmentSizeValidator.canAddAttachment(emptyList(), attInfo.encodedSize)) + } + + @Test + fun getAttInfoFromUriSanitizesProviderSuppliedName() { + val uri = registerProvider("names", 10L, "../../evil.txt") + + val attInfo = requireNotNull(EmailUtil.getAttInfoFromUri(context, uri)) + + assertEquals("evil.txt", attInfo.name) + } + + private fun registerProvider(tag: String, size: Long, name: String): Uri { + val authority = "com.flowcrypt.email.test.provider.$tag" + val provider = object : ContentProvider() { + override fun onCreate(): Boolean = true + + override fun query( + uri: Uri, + projection: Array?, + selection: String?, + selectionArgs: Array?, + sortOrder: String? + ): Cursor = MatrixCursor( + arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE) + ).apply { addRow(arrayOf(name, size)) } + + override fun getType(uri: Uri): String = "application/octet-stream" + override fun insert(uri: Uri, values: ContentValues?): Uri? = null + override fun delete(uri: Uri, selection: String?, selectionArgs: Array?): Int = 0 + override fun update( + uri: Uri, + values: ContentValues?, + selection: String?, + selectionArgs: Array? + ): Int = 0 + } + ShadowContentResolver.registerProviderInternal(authority, provider) + return Uri.parse("content://$authority/document") + } +} diff --git a/FlowCrypt/src/test/java/com/flowcrypt/email/util/AttachmentSizeValidatorTest.kt b/FlowCrypt/src/test/java/com/flowcrypt/email/util/AttachmentSizeValidatorTest.kt new file mode 100644 index 0000000000..ad3bd53a7a --- /dev/null +++ b/FlowCrypt/src/test/java/com/flowcrypt/email/util/AttachmentSizeValidatorTest.kt @@ -0,0 +1,89 @@ +/* + * © 2016-present FlowCrypt a.s. Limitations apply. Contact human@flowcrypt.com + * Contributors: denbond7 + */ + +package com.flowcrypt.email.util + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.ByteArrayInputStream +import java.io.IOException + +class AttachmentSizeValidatorTest { + @get:Rule + val temporaryFolder = TemporaryFolder() + + @Test + fun rejectReportedSizeThatWrapsToNegativeInt() { + assertFalse( + AttachmentSizeValidator.canAddAttachment(emptyList(), Int.MAX_VALUE.toLong() + 1) + ) + } + + @Test + fun rejectSumThatOverflowsLong() { + assertFalse( + AttachmentSizeValidator.canAddAttachment(listOf(Long.MAX_VALUE - 1), 10) + ) + } + + @Test + fun rejectNegativeReportedSize() { + assertFalse(AttachmentSizeValidator.canAddAttachment(emptyList(), -1)) + } + + @Test + fun acceptSizesWithinLimit() { + assertTrue( + AttachmentSizeValidator.canAddAttachment( + listOf(10L * 1024 * 1024), 10L * 1024 * 1024 + ) + ) + } + + @Test + fun normalizeUnusableReportedSizeToZero() { + assertEquals(0L, AttachmentSizeValidator.normalizeReportedSize(null)) + assertEquals(0L, AttachmentSizeValidator.normalizeReportedSize(-1)) + assertEquals(10L, AttachmentSizeValidator.normalizeReportedSize(10)) + } + + @Test + fun copyInputStreamToFileWritesExactlyLimit() { + val destination = temporaryFolder.newFile("exact.bin") + val content = ByteArray(2048) + + AttachmentSizeValidator.copyInputStreamToFile( + ByteArrayInputStream(content), destination, content.size.toLong() + ) + + assertEquals(content.size.toLong(), destination.length()) + } + + @Test + fun copyInputStreamToFileRejectsOverLimitAndRemovesPartialFile() { + val destination = java.io.File(temporaryFolder.root, "partial.bin") + + assertThrows(IOException::class.java) { + AttachmentSizeValidator.copyInputStreamToFile( + ByteArrayInputStream(ByteArray(2048)), destination, 1024 + ) + } + assertFalse(destination.exists()) + } + + @Test + fun limitedInputStreamCapsByteArrayReads() { + val input = AttachmentSizeValidator.limitedInputStream( + ByteArrayInputStream(ByteArray(2048)), 1024 + ) + + assertThrows(IOException::class.java) { input.readBytes() } + } +} From 3c5748965ac750e255cb3438e58f50ef338c5c0e Mon Sep 17 00:00:00 2001 From: martgil <46025304+martgil@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:53:51 +0800 Subject: [PATCH 2/3] fix(attachment): enforce a cumulative byte budget when caching attachments Track remaining bytes across the send-time cache loop so several attachments cannot each consume the full limit, and make the stream ceiling count skipped bytes. --- .../ProcessingOutgoingMessageInfoHelper.kt | 20 ++++++++-- .../email/util/AttachmentSizeValidator.kt | 9 ++++- .../email/util/AttachmentSizeValidatorTest.kt | 38 +++++++++++++++++++ 3 files changed, 62 insertions(+), 5 deletions(-) diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/service/ProcessingOutgoingMessageInfoHelper.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/service/ProcessingOutgoingMessageInfoHelper.kt index 98168a75a6..1916984236 100644 --- a/FlowCrypt/src/main/java/com/flowcrypt/email/service/ProcessingOutgoingMessageInfoHelper.kt +++ b/FlowCrypt/src/main/java/com/flowcrypt/email/service/ProcessingOutgoingMessageInfoHelper.kt @@ -113,9 +113,15 @@ object ProcessingOutgoingMessageInfoHelper { pubKeys.addAll(SecurityUtils.getSenderPublicKeys(context, senderEmail)) } + var remainingBytes = Constants.MAX_TOTAL_ATTACHMENT_SIZE_IN_BYTES + for (attachmentInfo in outgoingMsgInfo.atts ?: emptyList()) { var uri: Uri? var name: String? = null + val budget = remainingBytes + if (budget <= 0) { + throw IOException("Total attachment size limit exceeded") + } val origFileUri = attachmentInfo.uri var originalFileInputStream: InputStream? = null @@ -124,13 +130,13 @@ object ProcessingOutgoingMessageInfoHelper { originalFileInputStream = context.contentResolver.openInputStream(origFileUri) ?.let { AttachmentSizeValidator.limitedInputStream( - it, Constants.MAX_TOTAL_ATTACHMENT_SIZE_IN_BYTES + it, budget ) } } else if (attachmentInfo.rawData?.isNotEmpty() == true) { originalFileInputStream = AttachmentSizeValidator.limitedInputStream( ByteArrayInputStream(attachmentInfo.rawData), - Constants.MAX_TOTAL_ATTACHMENT_SIZE_IN_BYTES + budget ) } @@ -154,6 +160,12 @@ object ProcessingOutgoingMessageInfoHelper { pubKeys = requireNotNull(pubKeys), fileName = originalAttName, ) + val encryptedSize = encryptedTempFile.length() + if (encryptedSize > budget) { + encryptedTempFile.delete() + throw IOException("Total attachment size limit exceeded") + } + remainingBytes -= encryptedSize uri = Uri.fromFile(encryptedTempFile) name = encryptedTempFile.name } else { @@ -163,8 +175,8 @@ object ProcessingOutgoingMessageInfoHelper { FileAndDirectoryUtils.createFileWithIncreasedIndex(attsCacheDir, cachedAtt.name) } - AttachmentSizeValidator.copyInputStreamToFile( - originalFileInputStream, cachedAtt, Constants.MAX_TOTAL_ATTACHMENT_SIZE_IN_BYTES + remainingBytes -= AttachmentSizeValidator.copyInputStreamToFile( + originalFileInputStream, cachedAtt, budget ) uri = Uri.fromFile(cachedAtt) } diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/util/AttachmentSizeValidator.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/util/AttachmentSizeValidator.kt index 73b9b6ce1d..177768f01d 100644 --- a/FlowCrypt/src/main/java/com/flowcrypt/email/util/AttachmentSizeValidator.kt +++ b/FlowCrypt/src/main/java/com/flowcrypt/email/util/AttachmentSizeValidator.kt @@ -43,7 +43,7 @@ object AttachmentSizeValidator { /** Copy at most [maxBytes] bytes, removing a partial file when the limit is exceeded. */ @Throws(IOException::class) - fun copyInputStreamToFile(input: InputStream, destination: File, maxBytes: Long) { + fun copyInputStreamToFile(input: InputStream, destination: File, maxBytes: Long): Long { try { input.use { source -> limitedInputStream(source, maxBytes).use { limited -> @@ -54,6 +54,7 @@ object AttachmentSizeValidator { destination.delete() throw e } + return destination.length() } private fun safeAdd(first: Long, second: Long): Long? = @@ -75,6 +76,12 @@ object AttachmentSizeValidator { return result } + override fun skip(byteCount: Long): Long { + val result = super.skip(byteCount) + if (result > 0) count(result) + return result + } + private fun count(count: Long) { bytesRead += count if (bytesRead > maxBytes) { diff --git a/FlowCrypt/src/test/java/com/flowcrypt/email/util/AttachmentSizeValidatorTest.kt b/FlowCrypt/src/test/java/com/flowcrypt/email/util/AttachmentSizeValidatorTest.kt index ad3bd53a7a..e2e556ec41 100644 --- a/FlowCrypt/src/test/java/com/flowcrypt/email/util/AttachmentSizeValidatorTest.kt +++ b/FlowCrypt/src/test/java/com/flowcrypt/email/util/AttachmentSizeValidatorTest.kt @@ -86,4 +86,42 @@ class AttachmentSizeValidatorTest { assertThrows(IOException::class.java) { input.readBytes() } } + + @Test + fun copyInputStreamToFileReturnsBytesWritten() { + val destination = temporaryFolder.newFile("counted.bin") + + val written = AttachmentSizeValidator.copyInputStreamToFile( + ByteArrayInputStream(ByteArray(777)), destination, 1024 + ) + + assertEquals(777L, written) + } + + @Test + fun cumulativeBudgetCapsSecondCopy() { + val first = temporaryFolder.newFile("first.bin") + val second = java.io.File(temporaryFolder.root, "second.bin") + var budget = 1024L + + budget -= AttachmentSizeValidator.copyInputStreamToFile( + ByteArrayInputStream(ByteArray(1024)), first, budget + ) + + assertThrows(IOException::class.java) { + AttachmentSizeValidator.copyInputStreamToFile( + ByteArrayInputStream(ByteArray(1024)), second, budget + ) + } + assertFalse(second.exists()) + } + + @Test + fun limitedInputStreamCountsSkip() { + val input = AttachmentSizeValidator.limitedInputStream( + ByteArrayInputStream(ByteArray(2048)), 1024 + ) + + assertThrows(IOException::class.java) { input.skip(2048) } + } } From 35147dce011a532206f6f659d6486fd4d891940d Mon Sep 17 00:00:00 2001 From: martgil <46025304+martgil@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:23:56 +0800 Subject: [PATCH 3/3] fix(attachment): clean up failed encryption and count consumed input bytes Delete partial ciphertext on encryption failure, count plaintext bytes read against the cumulative budget, and cover stored-byte accounting with tests. --- .../ProcessingOutgoingMessageInfoHelper.kt | 48 ++++++++----------- .../email/util/AttachmentSizeValidator.kt | 24 ++++++++-- .../email/util/AttachmentSizeValidatorTest.kt | 27 +++++++++++ 3 files changed, 67 insertions(+), 32 deletions(-) diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/service/ProcessingOutgoingMessageInfoHelper.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/service/ProcessingOutgoingMessageInfoHelper.kt index 1916984236..4844aa4310 100644 --- a/FlowCrypt/src/main/java/com/flowcrypt/email/service/ProcessingOutgoingMessageInfoHelper.kt +++ b/FlowCrypt/src/main/java/com/flowcrypt/email/service/ProcessingOutgoingMessageInfoHelper.kt @@ -31,7 +31,6 @@ import kotlinx.coroutines.withContext import java.io.ByteArrayInputStream import java.io.File import java.io.IOException -import java.io.InputStream /** * @author Denys Bondarenko @@ -124,25 +123,19 @@ object ProcessingOutgoingMessageInfoHelper { } val origFileUri = attachmentInfo.uri - var originalFileInputStream: InputStream? = null - if (origFileUri != null) { + val sourceStream = if (origFileUri != null) { OutgoingAttachmentUriValidator.requireAllowedUri(context, origFileUri) - originalFileInputStream = context.contentResolver.openInputStream(origFileUri) - ?.let { - AttachmentSizeValidator.limitedInputStream( - it, budget - ) - } + context.contentResolver.openInputStream(origFileUri) } else if (attachmentInfo.rawData?.isNotEmpty() == true) { - originalFileInputStream = AttachmentSizeValidator.limitedInputStream( - ByteArrayInputStream(attachmentInfo.rawData), - budget - ) + ByteArrayInputStream(attachmentInfo.rawData) + } else { + null } - if (originalFileInputStream == null) { + if (sourceStream == null) { throw IllegalStateException("The file stream is null") } + val limitedSource = AttachmentSizeValidator.limitedInputStream(sourceStream, budget) val originalAttName = attachmentInfo.getSafeName() if (attachmentInfo.isEncryptionAllowed && outgoingMsgInfo.encryptionType === MessageEncryptionType.ENCRYPTED) { @@ -154,18 +147,20 @@ object ProcessingOutgoingMessageInfoHelper { attsCacheDir, encryptedTempFile.name ) } - PgpEncryptAndOrSign.encryptAndOrSign( - srcInputStream = originalFileInputStream, - destOutputStream = encryptedTempFile.outputStream(), - pubKeys = requireNotNull(pubKeys), - fileName = originalAttName, - ) - val encryptedSize = encryptedTempFile.length() - if (encryptedSize > budget) { + try { + encryptedTempFile.outputStream().use { output -> + PgpEncryptAndOrSign.encryptAndOrSign( + srcInputStream = limitedSource, + destOutputStream = output, + pubKeys = requireNotNull(pubKeys), + fileName = originalAttName, + ) + } + } catch (e: Exception) { encryptedTempFile.delete() - throw IOException("Total attachment size limit exceeded") + throw e } - remainingBytes -= encryptedSize + remainingBytes -= limitedSource.bytesRead uri = Uri.fromFile(encryptedTempFile) name = encryptedTempFile.name } else { @@ -175,9 +170,8 @@ object ProcessingOutgoingMessageInfoHelper { FileAndDirectoryUtils.createFileWithIncreasedIndex(attsCacheDir, cachedAtt.name) } - remainingBytes -= AttachmentSizeValidator.copyInputStreamToFile( - originalFileInputStream, cachedAtt, budget - ) + AttachmentSizeValidator.copyInputStreamToFile(limitedSource, cachedAtt, budget) + remainingBytes = AttachmentSizeValidator.consumeStoredBytes(budget, cachedAtt) uri = Uri.fromFile(cachedAtt) } diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/util/AttachmentSizeValidator.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/util/AttachmentSizeValidator.kt index 177768f01d..0688313ec8 100644 --- a/FlowCrypt/src/main/java/com/flowcrypt/email/util/AttachmentSizeValidator.kt +++ b/FlowCrypt/src/main/java/com/flowcrypt/email/util/AttachmentSizeValidator.kt @@ -38,9 +38,20 @@ object AttachmentSizeValidator { } /** Wrap [input] so reads past [maxBytes] fail instead of growing without a bound. */ - fun limitedInputStream(input: InputStream, maxBytes: Long): InputStream = + fun limitedInputStream(input: InputStream, maxBytes: Long): LimitedInputStream = LimitedInputStream(input, maxBytes) + /** Consume a stored attachment's real size from [budget], deleting an oversized file. */ + @Throws(IOException::class) + fun consumeStoredBytes(budget: Long, file: File): Long { + val storedSize = file.length() + if (storedSize > budget) { + file.delete() + throw IOException("Attachment exceeds the allowed size limit") + } + return budget - storedSize + } + /** Copy at most [maxBytes] bytes, removing a partial file when the limit is exceeded. */ @Throws(IOException::class) fun copyInputStreamToFile(input: InputStream, destination: File, maxBytes: Long): Long { @@ -60,9 +71,12 @@ object AttachmentSizeValidator { private fun safeAdd(first: Long, second: Long): Long? = if (first > Long.MAX_VALUE - second) null else first + second - private class LimitedInputStream(input: InputStream, private val maxBytes: Long) : + class LimitedInputStream internal constructor(input: InputStream, private val maxBytes: Long) : FilterInputStream(input) { - private var bytesRead = 0L + val bytesRead: Long + get() = bytesReadValue + + private var bytesReadValue = 0L override fun read(): Int { val result = super.read() @@ -83,8 +97,8 @@ object AttachmentSizeValidator { } private fun count(count: Long) { - bytesRead += count - if (bytesRead > maxBytes) { + bytesReadValue += count + if (bytesReadValue > maxBytes) { throw IOException("Attachment exceeds the allowed size limit") } } diff --git a/FlowCrypt/src/test/java/com/flowcrypt/email/util/AttachmentSizeValidatorTest.kt b/FlowCrypt/src/test/java/com/flowcrypt/email/util/AttachmentSizeValidatorTest.kt index e2e556ec41..844020d219 100644 --- a/FlowCrypt/src/test/java/com/flowcrypt/email/util/AttachmentSizeValidatorTest.kt +++ b/FlowCrypt/src/test/java/com/flowcrypt/email/util/AttachmentSizeValidatorTest.kt @@ -124,4 +124,31 @@ class AttachmentSizeValidatorTest { assertThrows(IOException::class.java) { input.skip(2048) } } + + @Test + fun subLimitSkipCountsTowardLaterReads() { + val input = AttachmentSizeValidator.limitedInputStream( + ByteArrayInputStream(ByteArray(2048)), 1024 + ) + + assertEquals(512L, input.skip(512)) + assertThrows(IOException::class.java) { input.skip(600) } + } + + @Test + fun consumeStoredBytesReturnsRemainingBudget() { + val file = temporaryFolder.newFile("stored.bin").apply { writeBytes(ByteArray(2048)) } + + assertEquals(2048L, AttachmentSizeValidator.consumeStoredBytes(4096, file)) + } + + @Test + fun consumeStoredBytesRejectsOversizedFileAndDeletesIt() { + val file = temporaryFolder.newFile("oversized.bin").apply { writeBytes(ByteArray(2048)) } + + assertThrows(IOException::class.java) { + AttachmentSizeValidator.consumeStoredBytes(1024, file) + } + assertFalse(file.exists()) + } }