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 64f9cb50c..391ab6982 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 3aa522379..d224d6e20 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 786ad9a7e..c8d195f36 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 d30b56885..98168a75a 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 2387531e7..58954b81b 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 000000000..73b9b6ce1 --- /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 000000000..c741ec3ed --- /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 000000000..ad3bd53a7 --- /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() } + } +}