Skip to content
Open
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
7 changes: 3 additions & 4 deletions FlowCrypt/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ android {
versionName = rootProject.extra["appVersionName"] as String
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
buildConfigField("int", "MIN_SDK_VERSION", "$minSdk")
multiDexEnabled = true
}

signingConfigs {
Expand Down Expand Up @@ -143,7 +142,7 @@ android {
testBuildType = "uiTests"

sourceSets {
getByName("androidTest").assets.srcDir("$projectDir/schemas")
getByName("androidTest").assets.directories.add("$projectDir/schemas")
}

flavorDimensions += "standard"
Expand Down Expand Up @@ -449,8 +448,8 @@ tasks.register<Copy>("copyReleaseApks") {
}
}

val devDebugImplementation: Configuration by configurations.creating
val uiTestsImplementation by configurations.named("uiTestsImplementation")
val devDebugImplementation: Configuration = configurations.create("devDebugImplementation")
val uiTestsImplementation = configurations.named("uiTestsImplementation")

dependencies {
ksp("com.github.bumptech.glide:ksp:5.0.9")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -499,7 +499,7 @@ class SendMsgTest {
0,
).sortedArray()

val actualIds = messageMetadata.recipientKeyIds.toTypedArray().sortedArray()
val actualIds = messageMetadata.recipientKeyIdentifiers.map { it.keyId }.toTypedArray().sortedArray()

assertArrayEquals(
"Expected = ${expectedIds.contentToString()}, actual = ${actualIds.contentToString()}",
Expand All @@ -508,7 +508,7 @@ class SendMsgTest {
)

assertFalse(
messageMetadata.recipientKeyIds.contains(
messageMetadata.recipientKeyIdentifiers.map { it.keyId }.contains(
PgpKey.parseKeys(bccPgpKeyDetails.publicKey)
.pgpKeyRingCollection
.pgpPublicKeyRingCollection
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import okhttp3.mockwebserver.RecordedRequest
import org.apache.commons.codec.binary.ZBase32
import org.apache.commons.codec.digest.DigestUtils
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Ignore
import org.junit.Rule
Expand All @@ -32,6 +33,7 @@ import org.junit.rules.RuleChain
import org.junit.rules.TestRule
import org.junit.runner.RunWith
import org.pgpainless.PGPainless
import java.io.IOException
import java.net.HttpURLConnection

@SmallTest
Expand All @@ -57,6 +59,15 @@ class WkdClientTest {
)
}

genLookupUrlPath(OVERSIZED_RESPONSE_EMAIL) -> {
val armoredKey = PGPainless.getInstance().generateKey()
.simpleEcKeyRing(OVERSIZED_RESPONSE_EMAIL).toCertificate().toAsciiArmoredString()
val body = buildString {
while (length <= WkdClient.MAX_RESPONSE_SIZE_IN_BYTES) append(armoredKey)
}
return MockResponse().setResponseCode(HttpURLConnection.HTTP_OK).setBody(body)
}

genLookupUrlPath(NOT_EXISTING_EMAIL) -> {
return MockResponse().setResponseCode(HttpURLConnection.HTTP_NOT_FOUND)
.setBody(
Expand Down Expand Up @@ -109,10 +120,22 @@ class WkdClientTest {
assertNull("Key found for non-existing domain", keys)
}

@Test
fun oversizedResponseTest() {
val exception = assertThrows(IOException::class.java) {
runBlocking { WkdClient.lookupEmail(context, OVERSIZED_RESPONSE_EMAIL) }
}
assertTrue(
"Unexpected error: ${exception.message}",
exception.message?.contains("exceeds the limit") == true
)
}

companion object {

const val EXISTING_EMAIL = "existing@flowcrypt.test"
const val NOT_EXISTING_EMAIL = "not_existing@flowcrypt.test"
const val OVERSIZED_RESPONSE_EMAIL = "oversized_response@flowcrypt.test"

private fun genLookupUrlPath(email: String): String {
val user = email.substringBefore("@")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ abstract class BaseComposeGmailFlow(accountEntity: AccountEntity = BASE_ACCOUNT_
}.toTypedArray().sortedArray()

val actualIds =
messageMetadata.recipientKeyIds.toTypedArray().sortedArray()
messageMetadata.recipientKeyIdentifiers.map { it.keyId }.toTypedArray().sortedArray()

assertArrayEquals(
"Expected = ${finalExpectedIds.contentToString()}, actual = ${actualIds.contentToString()}",
Expand All @@ -243,7 +243,7 @@ abstract class BaseComposeGmailFlow(accountEntity: AccountEntity = BASE_ACCOUNT_

if (outgoingMessageConfiguration.bcc.isNotEmpty()) {
//https://github.com/FlowCrypt/flowcrypt-android/issues/2306
assertFalse(messageMetadata.recipientKeyIds.contains(extractKeyId(defaultBccPgpKeyDetails)))
assertFalse(messageMetadata.recipientKeyIdentifiers.map { it.keyId }.contains(extractKeyId(defaultBccPgpKeyDetails)))
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ class PasswordProtectedEncryptedComposeGmailApiFlow : BaseComposeGmailFlow() {
assertFalse(decryptionResult.isSigned)
//check that message was not encrypted by public keys
//ref https://github.com/pgpainless/pgpainless/issues/376
assertTrue(decryptionResult.messageMetadata?.recipientKeyIds?.isEmpty() == true)
assertTrue(decryptionResult.messageMetadata?.recipientKeyIdentifiers?.isEmpty() == true)

val decryptedContent = decryptionResult.content
assertNotNull(decryptedContent)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1315,8 +1315,10 @@ class EmailUtil {
val replyToMessageEntityId = info.replyToMessageEntityId
?: throw IllegalArgumentException("replyToMessageEntityId is null")

val keys = PGPainless.readKeyRing()
.secretKeyRingCollection(accountEntity.servicePgpPrivateKey)
val keys = PGPSecretKeyRingCollection(
PGPainless.getInstance().readKey().parseKeys(accountEntity.servicePgpPrivateKey)
.map { it.pgpSecretKeyRing }
)

val replyToMessageEntity =
FlowCryptRoomDatabase.getDatabase(context).msgDao().getMsgById(replyToMessageEntityId)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import kotlinx.coroutines.withContext
import okio.FileSystem
import okio.Path.Companion.toOkioPath
import okio.buffer
import org.bouncycastle.openpgp.PGPPublicKeyRingCollection
import org.pgpainless.PGPainless
import java.io.File
import java.io.IOException
Expand Down Expand Up @@ -110,8 +111,10 @@ object MsgsCacheManager {

PgpEncryptAndOrSign.encryptAndOrSign(
destOutputStream = bufferedSink.outputStream(),
pgpPublicKeyRingCollection = PGPainless.readKeyRing()
.publicKeyRingCollection(accountEntity.servicePgpPrivateKey)
pgpPublicKeyRingCollection = PGPPublicKeyRingCollection(
PGPainless.getInstance().readKey().parseKeys(accountEntity.servicePgpPrivateKey)
.map { it.getPGPPublicKeyRing() }
)
) { out ->
out.use { outputStream ->
action.invoke(outputStream)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ package com.flowcrypt.email.api.wkd
import android.content.Context
import com.flowcrypt.email.api.retrofit.ApiHelper
import com.flowcrypt.email.api.retrofit.RetrofitApiServiceInterface
import com.flowcrypt.email.extensions.java.io.readBytesWithLimit
import com.flowcrypt.email.extensions.kotlin.isValidEmail
import com.flowcrypt.email.util.BetterInternetAddress
import kotlinx.coroutines.Dispatchers
Expand All @@ -27,6 +28,7 @@ import java.util.concurrent.TimeUnit

object WkdClient {
private const val DEFAULT_REQUEST_TIMEOUT = 4000L
internal const val MAX_RESPONSE_SIZE_IN_BYTES = 1024 * 1024

suspend fun lookupEmail(context: Context, email: String): PGPPublicKeyRingCollection? =
withContext(Dispatchers.IO) {
Expand Down Expand Up @@ -119,7 +121,12 @@ object WkdClient {
if (!wkdResponse.isSuccessful || incomingBytes == null) {
return@withContext UrlLookupResult(true)
} else {
val keys = PGPainless.readKeyRing().publicKeyRingCollection(incomingBytes)
// parseKeysOrCertificates() reads the whole stream into memory, so limit the response size
val responseBytes = incomingBytes.use { it.readBytesWithLimit(MAX_RESPONSE_SIZE_IN_BYTES) }
val keys = PGPPublicKeyRingCollection(
PGPainless.getInstance().readKey().parseKeysOrCertificates(responseBytes)
.map { it.getPGPPublicKeyRing() }
)
return@withContext UrlLookupResult(true, keys)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import android.view.inputmethod.InputMethodManager
*/
fun View.showKeyboard() {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
imm.showSoftInput(this, 0)
}

fun View.hideKeyboard() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import com.flowcrypt.email.security.pgp.PgpMsg
import com.flowcrypt.email.util.cache.DiskLruCache
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.bouncycastle.openpgp.PGPSecretKeyRingCollection
import org.pgpainless.PGPainless
import org.pgpainless.key.protection.PasswordBasedSecretKeyRingProtector
import org.pgpainless.util.Passphrase
Expand All @@ -34,8 +35,10 @@ suspend fun DiskLruCache.Snapshot.processing(
val inputStream =
context.contentResolver.openInputStream(uri) ?: throw java.lang.IllegalStateException()

val keys = PGPainless.readKeyRing()
.secretKeyRingCollection(accountEntity.servicePgpPrivateKey)
val keys = PGPSecretKeyRingCollection(
PGPainless.getInstance().readKey().parseKeys(accountEntity.servicePgpPrivateKey)
.map { it.pgpSecretKeyRing }
)

val decryptionStream = PgpDecryptAndOrVerify.genDecryptionStream(
srcInputStream = inputStream,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,32 @@

package com.flowcrypt.email.extensions.java.io

import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.InputStream
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets

fun InputStream.readText(charset: Charset = StandardCharsets.UTF_8): String =
String(readBytes(), charset)

/**
* Read all bytes, but fail with [IOException] as soon as more than [maxBytes] bytes were read.
* Use it for untrusted sources where the size of the content is not known in advance.
*/
fun InputStream.readBytesWithLimit(maxBytes: Int): ByteArray {
require(maxBytes >= 0) { "maxBytes must not be negative" }
val output = ByteArrayOutputStream()
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
var total = 0L
while (true) {
val read = read(buffer)
if (read == -1) break
total += read
if (total > maxBytes) {
throw IOException("The stream exceeds the limit of $maxBytes bytes")
}
output.write(buffer, 0, read)
}
return output.toByteArray()
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ fun <T> Iterable<T>?.toPGPPublicKeyRingCollection(): PGPPublicKeyRingCollection?
val keysStream = ByteArrayInputStream(this.joinToString(separator = "\n").toByteArray())
return keysStream.use {
ArmoredInputStream(it).use { armoredInputStream ->
PGPainless.readKeyRing().publicKeyRingCollection(armoredInputStream)
PGPPublicKeyRingCollection(
PGPainless.getInstance().readKey().parseKeysOrCertificates(armoredInputStream)
.map { it.getPGPPublicKeyRing() }
)
}
}
}
Expand All @@ -29,7 +32,10 @@ fun <T> Iterable<T>?.toPGPSecretKeyRingCollection(): PGPSecretKeyRingCollection?
val keysStream = ByteArrayInputStream(this.joinToString(separator = "\n").toByteArray())
return keysStream.use {
ArmoredInputStream(it).use { armoredInputStream ->
PGPainless.readKeyRing().secretKeyRingCollection(armoredInputStream)
PGPSecretKeyRingCollection(
PGPainless.getInstance().readKey().parseKeys(armoredInputStream)
.map { it.pgpSecretKeyRing }
)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,5 @@ import org.bouncycastle.openpgp.PGPSecretKeyRing
import org.pgpainless.key.util.KeyRingUtils

fun PGPSecretKeyRing.toPublicKeyRing(): PGPPublicKeyRing {
return KeyRingUtils.publicKeyRingFrom(this)
return KeyRingUtils.publicKeys(this)
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.bouncycastle.openpgp.PGPSecretKeyRingCollection
import org.pgpainless.PGPainless
import org.pgpainless.key.protection.PasswordBasedSecretKeyRingProtector
import org.pgpainless.util.Passphrase
Expand Down Expand Up @@ -211,8 +212,10 @@ class DraftViewModel(
?.let { fileUri ->
(getApplication() as Context).contentResolver?.openInputStream(fileUri)
?.let { inputStream ->
val keys = PGPainless.readKeyRing()
.secretKeyRingCollection(activeAccount.servicePgpPrivateKey)
val keys = PGPSecretKeyRingCollection(
PGPainless.getInstance().readKey().parseKeys(activeAccount.servicePgpPrivateKey)
.map { it.pgpSecretKeyRing }
)

val decryptionStream = PgpDecryptAndOrVerify.genDecryptionStream(
srcInputStream = inputStream,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,14 @@ class EmailAndNameWorker(context: Context, params: WorkerParameters) : BaseWorke
private var recipientDao: RecipientDao = FlowCryptRoomDatabase.getDatabase(context).recipientDao()

override suspend fun doWork(): Result {
val emails = inputData.getStringArray(EXTRA_KEY_EMAILS) ?: return Result.failure()
val names = inputData.getStringArray(EXTRA_KEY_NAMES) ?: return Result.failure()
val emails = inputData.getNullableStringArray(EXTRA_KEY_EMAILS) ?: return Result.failure()
val names = inputData.getNullableStringArray(EXTRA_KEY_NAMES) ?: return Result.failure()

if (emails.size != names.size) return Result.failure()

for (i in emails.indices) {
val email = emails[i].lowercase()
val name = names[i].takeIf { it.isNotEmpty() }
val email = emails[i]?.lowercase() ?: continue
val name = names[i]?.takeIf { it.isNotEmpty() }
val recipientEntity = recipientDao.getRecipientByEmailSuspend(email)
if (recipientEntity != null) {
if (recipientEntity.name.isNullOrEmpty()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,20 +162,12 @@ class KeysStorageImpl private constructor(context: Context) : KeysStorage {
override fun getSecretKeyRingProtector(): SecretKeyRingProtector {
val availablePGPSecretKeyRings = getPGPSecretKeyRings()
val passphraseProvider = object : SecretKeyPassphraseProvider {
override fun getPassphraseFor(keyId: Long): Passphrase? {
return doGetPassphrase(keyId, true)
}

override fun getPassphraseFor(keyIdentifier: KeyIdentifier): Passphrase? {
return getPassphraseFor(keyIdentifier.keyId)
}

override fun hasPassphrase(keyId: Long): Boolean {
return doGetPassphrase(keyId, false) != null
return doGetPassphrase(keyIdentifier.keyId, true)
}

override fun hasPassphrase(keyIdentifier: KeyIdentifier): Boolean {
return hasPassphrase(keyIdentifier.keyId)
return doGetPassphrase(keyIdentifier.keyId, false) != null
}

private fun doGetPassphrase(keyId: Long, throwException: Boolean): Passphrase? {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ object PgpDecryptAndOrVerify {
return api.processMessage()
.onInputStream(srcInputStream)
.withOptions(
ConsumerOptions.get()
ConsumerOptions.get(api)
.setMissingKeyPassphraseStrategy(MissingKeyPassphraseStrategy.THROW_EXCEPTION)
.apply {
//this one deprecated but we use it and show warning for a user if needed
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ object PgpEncryptAndOrSign {
generateDetachedSignatures: Boolean = false,
): EncryptionStream {
val api = PGPainless.getInstance()
val encOpt = EncryptionOptions.get().apply {
val encOpt = EncryptionOptions.get(api).apply {
passphrase?.let { addMessagePassphrase(passphrase) }
pgpPublicKeyRingCollection?.forEach {
addRecipient(it.toOpenPGPCertificate(api.implementation))
Expand All @@ -189,7 +189,7 @@ object PgpEncryptAndOrSign {

val producerOptions: ProducerOptions =
if (passphrase == null && pgpSecretKeyRingCollection?.any() == true) {
ProducerOptions.signAndEncrypt(encOpt, SigningOptions.get().apply {
ProducerOptions.signAndEncrypt(encOpt, SigningOptions.get(api).apply {
pgpSecretKeyRingCollection.forEach { pgpSecretKeyRing ->
secretKeyRingProtector?.let { protector ->
if (generateDetachedSignatures) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ object PgpKey {
for (keyRing in secretKeyRings) {
val protector = SecretKeyRingProtector.unlockEachKeyWith(passphrase, keyRing)
for (key in keyRing.secretKeys) {
UnlockSecretKey.unlockSecretKey(key, protector)
UnlockSecretKey.unlockSecretKey(key, protector, PGPainless.getInstance().algorithmPolicy)
}
}
}
Expand Down
Loading
Loading