Skip to content
Merged
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 @@ -17,10 +17,13 @@ import java.util.concurrent.CancellationException
import javax.inject.Inject
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import org.openintents.openpgp.IOpenPgpService2
import org.openintents.openpgp.OpenPgpError
import org.openintents.openpgp.OpenPgpMetadata
import org.openintents.openpgp.util.OpenPgpApi
import org.openintents.openpgp.util.OpenPgpServiceConnection

Expand Down Expand Up @@ -87,6 +90,7 @@ class OpenPgpApiBackend internal constructor(private val executor: OpenPgpApiExe
maxOutputBytes = maxOutputBytes,
interactionHandler = interactionHandler,
) { call ->
validateDecryptedOutput(call)
call.output
}

Expand Down Expand Up @@ -141,7 +145,11 @@ class OpenPgpApiBackend internal constructor(private val executor: OpenPgpApiExe
repeat(MAX_INTERACTION_ROUNDS) {
val call =
try {
executor.execute(providerPackage, request, input, maxOutputBytes)
// Coordinate every IPC round across backend instances, not the user interaction
// that may follow it. The API client and its output stream are transaction-scoped.
transactionMutex.withLock {
executor.execute(providerPackage, request, input, maxOutputBytes)
}
} catch (error: CancellationException) {
throw error
} catch (error: Throwable) {
Expand Down Expand Up @@ -209,7 +217,24 @@ class OpenPgpApiBackend internal constructor(private val executor: OpenPgpApiExe
)
}

private fun validateDecryptedOutput(call: OpenPgpApiCall) {
@Suppress("DEPRECATION")
val metadata = call.result.getParcelableExtra<OpenPgpMetadata>(OpenPgpApi.RESULT_METADATA)
val expectedSize = metadata?.originalSize
if (expectedSize != null && expectedSize >= 0 && expectedSize != call.output.size.toLong()) {
throw OpenPgpProviderException(
"OpenPGP provider returned incomplete or inconsistent plaintext"
)
}
// This backend decrypts password entries and passkey records, neither of which can use an
// empty plaintext. Providers that omit size metadata must still return a non-empty payload.
if (call.output.isEmpty()) {
throw OpenPgpProviderException("OpenPGP provider returned no decrypted content")
}
}

companion object {
private val transactionMutex = Mutex()
const val DEFAULT_MAX_DECRYPT_OUTPUT_BYTES = 16 * 1024 * 1024L
private const val MAX_PUBLIC_KEY_OUTPUT_BYTES = 1024 * 1024L
private const val MAX_METADATA_OUTPUT_BYTES = 64 * 1024L
Expand Down
23 changes: 15 additions & 8 deletions app/src/main/java/app/passwordstore/ui/crypto/DecryptActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ import app.passwordstore.ui.adapters.FieldItemAdapter
import app.passwordstore.util.crypto.AESEncryption
import app.passwordstore.util.extensions.enableEdgeToEdgeView
import app.passwordstore.util.extensions.getString
import app.passwordstore.util.extensions.snackbar
import app.passwordstore.util.extensions.toCharArray
import app.passwordstore.util.extensions.unsafeLazy
import app.passwordstore.util.extensions.viewBinding
Expand Down Expand Up @@ -107,21 +106,29 @@ class DecryptActivity : BasePGPActivity() {
}
OpenPgpApiBackend.OperationResult.Cancelled -> finish()
is OpenPgpApiBackend.OperationResult.UserInteractionRequired ->
snackbar(message = getString(R.string.openpgp_provider_interaction_failed))
showProviderDecryptionError(getString(R.string.openpgp_provider_interaction_failed))
is OpenPgpApiBackend.OperationResult.Failure ->
snackbar(
message =
getString(
R.string.openpgp_provider_operation_failed,
result.error.message ?: getString(R.string.error),
)
showProviderDecryptionError(
getString(
R.string.openpgp_provider_operation_failed,
result.error.message ?: getString(R.string.error),
)
)
}
} finally {
ciphertext.wipe()
}
}

private fun showProviderDecryptionError(message: String) {
if (isFinishing || isDestroyed) return
MaterialAlertDialogBuilder(this)
.setMessage(message)
.setPositiveButton(android.R.string.ok) { _, _ -> finish() }
.setOnDismissListener { finish() }
.show()
}

override suspend fun decryptWithPassphrase(
passphrases: Map<String, CharArray?>,
identifiers: List<PGPIdentifier>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,15 @@ import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertIs
import kotlin.test.assertTrue
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import org.junit.runner.RunWith
import org.openintents.openpgp.OpenPgpMetadata
import org.openintents.openpgp.util.OpenPgpApi
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
Expand All @@ -36,6 +42,175 @@ class OpenPgpApiBackendTest {
)
}

@Test
fun `decrypt accepts matching size metadata`(): Unit = runBlocking {
val plaintext = byteArrayOf(1, 2, 3)
val executor = FakeExecutor { _, _, _, _ -> OpenPgpApiCall(successWithSize(3), plaintext) }

val operation = OpenPgpApiBackend(executor).decrypt("provider", byteArrayOf(9))

assertContentEquals(
byteArrayOf(1, 2, 3),
assertIs<OpenPgpApiBackend.OperationResult.Success<ByteArray>>(operation).value,
)
}

@Test
fun `decrypt rejects inconsistent size metadata and wipes output`(): Unit = runBlocking {
for (reportedSize in listOf(0L, 2L, 4L)) {
val plaintext = byteArrayOf(1, 2, 3)
val executor = FakeExecutor { _, _, _, _ ->
OpenPgpApiCall(successWithSize(reportedSize), plaintext)
}

val operation = OpenPgpApiBackend(executor).decrypt("provider", byteArrayOf(9))

assertIs<OpenPgpProviderException>(
assertIs<OpenPgpApiBackend.OperationResult.Failure>(operation).error
)
assertContentEquals(ByteArray(3), plaintext)
}
}

@Test
fun `decrypt accepts unknown size metadata`(): Unit = runBlocking {
val executor = FakeExecutor { _, _, _, _ ->
OpenPgpApiCall(successWithSize(-1), byteArrayOf(1))
}

val operation = OpenPgpApiBackend(executor).decrypt("provider", byteArrayOf(9))

assertContentEquals(
byteArrayOf(1),
assertIs<OpenPgpApiBackend.OperationResult.Success<ByteArray>>(operation).value,
)
}

@Test
fun `decrypt rejects empty plaintext even without size metadata`(): Unit = runBlocking {
val responses =
listOf(result(OpenPgpApi.RESULT_CODE_SUCCESS), successWithSize(0), successWithSize(101))
for (response in responses) {
val executor = FakeExecutor { _, _, _, _ -> OpenPgpApiCall(response, byteArrayOf()) }

val operation = OpenPgpApiBackend(executor).decrypt("provider", byteArrayOf(9))

assertIs<OpenPgpProviderException>(
assertIs<OpenPgpApiBackend.OperationResult.Failure>(operation).error
)
}
}

@Test
fun `transactions are coordinated across backend instances`(): Unit = runBlocking {
val firstEntered = CompletableDeferred<Unit>()
val releaseFirst = CompletableDeferred<Unit>()
val secondEntered = CompletableDeferred<Unit>()
val firstBackend =
OpenPgpApiBackend(
FakeExecutor { _, _, _, _ ->
firstEntered.complete(Unit)
releaseFirst.await()
OpenPgpApiCall(result(OpenPgpApi.RESULT_CODE_SUCCESS), byteArrayOf(1))
}
)
val secondBackend =
OpenPgpApiBackend(
FakeExecutor { _, _, _, _ ->
secondEntered.complete(Unit)
OpenPgpApiCall(result(OpenPgpApi.RESULT_CODE_SUCCESS), byteArrayOf(2))
}
)
val first =
async(start = CoroutineStart.UNDISPATCHED) {
firstBackend.decrypt("provider", byteArrayOf(9))
}
firstEntered.await()
val second =
async(start = CoroutineStart.UNDISPATCHED) {
secondBackend.getPublicKey("provider", 123L)
}

try {
assertFalse(secondEntered.isCompleted)
} finally {
releaseFirst.complete(Unit)
}
assertContentEquals(
byteArrayOf(1),
assertIs<OpenPgpApiBackend.OperationResult.Success<ByteArray>>(first.await()).value,
)
assertContentEquals(
byteArrayOf(2),
assertIs<OpenPgpApiBackend.OperationResult.Success<ByteArray>>(second.await()).value,
)
}

@Test
fun `authentication does not hold the transaction lock`(): Unit = runBlocking {
val pendingIntent =
PendingIntent.getActivity(
RuntimeEnvironment.getApplication(),
9,
Intent("interaction"),
PendingIntent.FLAG_IMMUTABLE,
)
val authenticating = CompletableDeferred<Unit>()
val resumeAuthentication = CompletableDeferred<Unit>()
val otherEntered = CompletableDeferred<Unit>()
var attempts = 0
val backend =
OpenPgpApiBackend(
FakeExecutor { _, _, _, _ ->
if (attempts++ == 0) {
OpenPgpApiCall(
result(OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED).apply {
putExtra(OpenPgpApi.RESULT_INTENT, pendingIntent)
},
byteArrayOf(),
)
} else {
OpenPgpApiCall(successWithSize(1), byteArrayOf(7))
}
}
)
val otherBackend =
OpenPgpApiBackend(
FakeExecutor { _, _, _, _ ->
otherEntered.complete(Unit)
OpenPgpApiCall(result(OpenPgpApi.RESULT_CODE_SUCCESS), byteArrayOf())
}
)
val first =
async(start = CoroutineStart.UNDISPATCHED) {
backend.decrypt(
"provider",
byteArrayOf(9),
OpenPgpApiBackend.InteractionHandler {
authenticating.complete(Unit)
resumeAuthentication.await()
OpenPgpApiBackend.InteractionResult.Completed(Intent(OpenPgpApi.ACTION_DECRYPT_VERIFY))
},
)
}
authenticating.await()
val second =
async(start = CoroutineStart.UNDISPATCHED) {
otherBackend.checkPermission("provider")
}

try {
assertTrue(otherEntered.isCompleted)
} finally {
resumeAuthentication.complete(Unit)
}
assertIs<OpenPgpApiBackend.OperationResult.Success<Unit>>(second.await())
assertContentEquals(
byteArrayOf(7),
assertIs<OpenPgpApiBackend.OperationResult.Success<ByteArray>>(first.await()).value,
)
}

@Test
fun `decrypt forwards the caller output limit`(): Unit = runBlocking {
var seenLimit = 0L
Expand Down Expand Up @@ -124,6 +299,11 @@ class OpenPgpApiBackendTest {
assertIs<OpenPgpApiBackend.OperationResult.UserInteractionRequired>(operation)
}

private fun successWithSize(size: Long): Intent =
result(OpenPgpApi.RESULT_CODE_SUCCESS).apply {
putExtra(OpenPgpApi.RESULT_METADATA, OpenPgpMetadata("", "text/plain", 0L, size))
}

private fun result(code: Int): Intent = Intent().apply { putExtra(OpenPgpApi.RESULT_CODE, code) }

private class FakeExecutor(
Expand Down