Skip to content
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,8 @@ class EmbeddedAttachmentsProvider : DocumentsProvider() {
val cacheSize = max(maxMemory / 4, FileUtils.ONE_MB * 25).toInt()
lruCache = object : LruCache<String, AttachmentInfo>(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()
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -636,6 +637,9 @@ class CreateMessageFragment : BaseFragment<FragmentCreateMessageBinding>(),
!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 {
Expand All @@ -653,9 +657,14 @@ class CreateMessageFragment : BaseFragment<FragmentCreateMessageBinding>(),

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) {
Expand Down Expand Up @@ -1058,10 +1067,10 @@ class CreateMessageFragment : BaseFragment<FragmentCreateMessageBinding>(),
* @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
)
}


Expand Down
Original file line number Diff line number Diff line change
@@ -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>): 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<Long>, 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")
}
}
}
}
Original file line number Diff line number Diff line change
@@ -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<String>?,
selection: String?,
selectionArgs: Array<String>?,
sortOrder: String?
): Cursor = MatrixCursor(
arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE)
).apply { addRow(arrayOf<Any?>(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<String>?): Int = 0
override fun update(
uri: Uri,
values: ContentValues?,
selection: String?,
selectionArgs: Array<String>?
): Int = 0
}
ShadowContentResolver.registerProviderInternal(authority, provider)
return Uri.parse("content://$authority/document")
}
}
Loading
Loading