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
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,16 +22,15 @@ 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
import java.io.InputStream

/**
* @author Denys Bondarenko
Expand Down Expand Up @@ -113,22 +112,30 @@ 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
if (origFileUri != null) {
val sourceStream = if (origFileUri != null) {
OutgoingAttachmentUriValidator.requireAllowedUri(context, origFileUri)
originalFileInputStream = context.contentResolver.openInputStream(origFileUri)
context.contentResolver.openInputStream(origFileUri)
} else if (attachmentInfo.rawData?.isNotEmpty() == true) {
originalFileInputStream = ByteArrayInputStream(attachmentInfo.rawData)
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) {
Expand All @@ -140,12 +147,20 @@ object ProcessingOutgoingMessageInfoHelper {
attsCacheDir, encryptedTempFile.name
)
}
PgpEncryptAndOrSign.encryptAndOrSign(
srcInputStream = originalFileInputStream,
destOutputStream = encryptedTempFile.outputStream(),
pubKeys = requireNotNull(pubKeys),
fileName = originalAttName,
)
try {
encryptedTempFile.outputStream().use { output ->
PgpEncryptAndOrSign.encryptAndOrSign(
srcInputStream = limitedSource,
destOutputStream = output,
pubKeys = requireNotNull(pubKeys),
fileName = originalAttName,
)
}
} catch (e: Exception) {
encryptedTempFile.delete()
throw e
}
remainingBytes -= limitedSource.bytesRead
uri = Uri.fromFile(encryptedTempFile)
name = encryptedTempFile.name
} else {
Expand All @@ -155,7 +170,8 @@ object ProcessingOutgoingMessageInfoHelper {
FileAndDirectoryUtils.createFileWithIncreasedIndex(attsCacheDir, cachedAtt.name)
}

FileUtils.copyInputStreamToFile(originalFileInputStream, cachedAtt)
AttachmentSizeValidator.copyInputStreamToFile(limitedSource, cachedAtt, budget)
remainingBytes = AttachmentSizeValidator.consumeStoredBytes(budget, cachedAtt)
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,106 @@
/*
* © 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): 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 {
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
}
return destination.length()
}

private fun safeAdd(first: Long, second: Long): Long? =
if (first > Long.MAX_VALUE - second) null else first + second

class LimitedInputStream internal constructor(input: InputStream, private val maxBytes: Long) :
FilterInputStream(input) {
val bytesRead: Long
get() = bytesReadValue

private var bytesReadValue = 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
}

override fun skip(byteCount: Long): Long {
val result = super.skip(byteCount)
if (result > 0) count(result)
return result
}

private fun count(count: Long) {
bytesReadValue += count
if (bytesReadValue > maxBytes) {
throw IOException("Attachment exceeds the allowed size limit")
}
}
}
}
Loading
Loading