Android security implementation Phase 3.1

This commit is contained in:
2026-11-03 18:05:14 +02:00
parent d165fdc4b4
commit e3b3a9bb52
14 changed files with 224 additions and 48 deletions
@@ -275,10 +275,7 @@ internal object AndroidMailService {
val bytes = Base64.decode(rawBase64, Base64.DEFAULT)
require(bytes.size <= 25 * 1024 * 1024) { "The encrypted message is too large to send on Android testing builds." }
message = MimeMessage(session, ByteArrayInputStream(bytes))
val contentType = message.contentType.lowercase(Locale.ROOT)
require(contentType.startsWith("multipart/encrypted") || contentType.startsWith("multipart/signed")) {
"Only an OpenPGP MIME message can use the encrypted send path."
}
validateOpenPgpMime(message)
require(message.from?.isNotEmpty() == true && message.allRecipients?.isNotEmpty() == true) {
"The encrypted message needs a sender and at least one recipient."
}
@@ -373,6 +370,33 @@ internal object AndroidMailService {
}
}
private fun validateOpenPgpMime(message: MimeMessage) {
val contentType = message.contentType.lowercase(Locale.ROOT)
val multipart = message.content as? Multipart
?: throw IllegalArgumentException("The OpenPGP MIME message is malformed.")
require(multipart.count == 2) { "The OpenPGP MIME message has an unexpected structure." }
if (contentType.startsWith("multipart/encrypted")) {
val versionPart = multipart.getBodyPart(0)
val encryptedPart = multipart.getBodyPart(1)
val version = runCatching { versionPart.content.toString().trim() }.getOrDefault("")
val armor = runCatching { String(encryptedPart.inputStream.readBytes(), Charsets.US_ASCII) }.getOrDefault("")
require(versionPart.isMimeType("application/pgp-encrypted") && version == "Version: 1" &&
encryptedPart.isMimeType("application/octet-stream") &&
armor.contains("-----BEGIN PGP MESSAGE-----") && armor.contains("-----END PGP MESSAGE-----")) {
"The encrypted OpenPGP payload is missing or malformed."
}
} else if (contentType.startsWith("multipart/signed")) {
val signaturePart = multipart.getBodyPart(1)
val armor = runCatching { String(signaturePart.inputStream.readBytes(), Charsets.US_ASCII) }.getOrDefault("")
require(signaturePart.isMimeType("application/pgp-signature") &&
armor.contains("-----BEGIN PGP SIGNATURE-----") && armor.contains("-----END PGP SIGNATURE-----")) {
"The OpenPGP signature is missing or malformed."
}
} else {
throw IllegalArgumentException("Only an OpenPGP MIME message can use the protected send path.")
}
}
fun savePgpAttachment(context: Context, input: JSONObject): JSONObject {
val filename = input.optString("filename").replace(Regex("[\\\\/\\r\\n\\u0000]"), "").take(255).ifBlank { "attachment" }
val contentType = input.optString("contentType", "application/octet-stream").lowercase(Locale.ROOT)
@@ -14,8 +14,9 @@ import com.getcapacitor.PluginMethod
import com.getcapacitor.annotation.CapacitorPlugin
import java.util.Locale
import java.util.UUID
import org.json.JSONArray
import org.json.JSONObject
import org.json.JSONArray
import org.json.JSONObject
import javax.mail.internet.InternetAddress
@CapacitorPlugin(name = "EpMail")
class EpMailPlugin : Plugin() {
@@ -119,13 +120,77 @@ class EpMailPlugin : Plugin() {
fun pgpSaveStore(call: PluginCall) {
try {
val candidate = call.getObject("store") ?: throw IllegalArgumentException("The OpenPGP key store is missing.")
AndroidAccountVault.savePgpStore(JSONObject(candidate.toString()))
call.resolve(JSObject().put("ok", true))
val next = JSONObject(candidate.toString())
val warning = pgpStoreChangeWarning(AndroidAccountVault.pgpStore(), next)
if (warning == null) {
AndroidAccountVault.savePgpStore(next)
call.resolve(JSObject().put("ok", true))
} else {
val host = activity
host.runOnUiThread {
AlertDialog.Builder(host)
.setTitle("Confirm OpenPGP key changes")
.setMessage(warning)
.setNegativeButton("Cancel") { _, _ -> call.reject("OpenPGP key change cancelled.") }
.setPositiveButton("Confirm changes") { _, _ ->
bridge.execute {
try {
AndroidAccountVault.savePgpStore(next)
call.resolve(JSObject().put("ok", true))
} catch (error: Exception) {
call.reject(error.message ?: "Could not save the Android OpenPGP key store.")
}
}
}
.setOnCancelListener { call.reject("OpenPGP key change cancelled.") }
.show()
}
}
} catch (error: Exception) {
call.reject(error.message ?: "Could not save the Android OpenPGP key store.")
}
}
private fun pgpStoreChangeWarning(previous: JSONObject, candidate: JSONObject): String? {
val oldContacts = previous.optJSONArray("contacts") ?: JSONArray()
val newContacts = candidate.optJSONArray("contacts") ?: JSONArray()
val oldByFingerprint = (0 until oldContacts.length()).mapNotNull { oldContacts.optJSONObject(it) }
.associateBy { it.optString("fingerprint").uppercase(Locale.ROOT) }
val warnings = ArrayList<String>()
for (index in 0 until newContacts.length()) {
val current = newContacts.optJSONObject(index) ?: continue
val fingerprint = current.optString("fingerprint").uppercase(Locale.ROOT)
val previousContact = oldByFingerprint[fingerprint]
val trustOrder = mapOf("unknown" to 0, "trusted" to 1, "verified" to 2)
if (previousContact != null &&
(trustOrder[current.optString("trust")] ?: 0) > (trustOrder[previousContact.optString("trust")] ?: 0)) {
warnings.add("Trust change for ${safePgpLabel(current.optJSONArray("emails"))}\nFingerprint: ${formatPgpFingerprint(fingerprint)}\nNew trust: ${current.optString("trust")}")
}
if (previousContact == null) {
val newEmails = jsonStrings(current.optJSONArray("emails")).map { it.lowercase(Locale.ROOT) }.toSet()
for (oldIndex in 0 until oldContacts.length()) {
val old = oldContacts.optJSONObject(oldIndex) ?: continue
val oldFingerprint = old.optString("fingerprint").uppercase(Locale.ROOT)
val overlap = jsonStrings(old.optJSONArray("emails")).map { it.lowercase(Locale.ROOT) }.any(newEmails::contains)
if (overlap && oldFingerprint != fingerprint) {
warnings.add("A different key is already stored for ${safePgpLabel(current.optJSONArray("emails"))}.\nNew fingerprint: ${formatPgpFingerprint(fingerprint)}\nExisting fingerprint: ${formatPgpFingerprint(oldFingerprint)}")
}
}
}
}
return warnings.take(6).takeIf { it.isNotEmpty() }?.joinToString("\n\n")?.let {
"$it\n\nOnly confirm trust or a replacement after comparing fingerprints with the key owner through another channel."
}
}
private fun jsonStrings(values: JSONArray?): List<String> =
values?.let { array -> (0 until array.length()).mapNotNull { array.optString(it).takeIf(String::isNotBlank) } }.orEmpty()
private fun safePgpLabel(values: JSONArray?): String =
jsonStrings(values).joinToString(", ").replace(Regex("[\\r\\n\\u0000]"), " ").take(300).ifBlank { "this contact" }
private fun formatPgpFingerprint(value: String): String = value.chunked(4).joinToString(" ").take(200)
@PluginMethod
fun pgpGetMessageSource(call: PluginCall) {
try {
@@ -380,13 +445,38 @@ class EpMailPlugin : Plugin() {
}
@PluginMethod
fun send(call: PluginCall) {
val input = JSONObject(call.data.toString()).apply {
if (optString("messageId").isBlank()) put("messageId", "<${UUID.randomUUID()}@ep-mail.local>")
}
try {
val account = AndroidAccountVault.account()
?: throw IllegalStateException("Add a mail account before sending.")
fun send(call: PluginCall) {
val input = JSONObject(call.data.toString()).apply {
if (optString("messageId").isBlank()) put("messageId", "<${UUID.randomUUID()}@ep-mail.local>")
}
val warning = try { plaintextSendWarning(input) } catch (error: Exception) {
call.reject(error.message ?: "Could not check the OpenPGP send policy.")
return
}
if (warning == null) {
sendPrepared(call, input)
return
}
val host = activity
host.runOnUiThread {
AlertDialog.Builder(host)
.setTitle("Send without OpenPGP encryption?")
.setMessage(warning)
.setNegativeButton("Cancel") { _, _ ->
call.resolve(JSObject().put("failed", true).put("code", "PLAINTEXT_CANCELLED").put("message", "Plaintext send cancelled."))
}
.setPositiveButton("Send plaintext") { _, _ -> bridge.execute { sendPrepared(call, input) } }
.setOnCancelListener {
call.resolve(JSObject().put("failed", true).put("code", "PLAINTEXT_CANCELLED").put("message", "Plaintext send cancelled."))
}
.show()
}
}
private fun sendPrepared(call: PluginCall, input: JSONObject) {
try {
val account = AndroidAccountVault.account()
?: throw IllegalStateException("Add a mail account before sending.")
call.resolve(AndroidMailService.send(account, input).toJSObject())
} catch (error: Exception) {
val account = AndroidAccountVault.account()
@@ -396,9 +486,42 @@ class EpMailPlugin : Plugin() {
.put("type", "send")
.put("data", input))
call.resolve(JSObject().put("ok", true).put("queued", true))
} else call.reject(error.message ?: "Could not send the message.")
}
}
} else call.reject(error.message ?: "Could not send the message.")
}
}
private fun plaintextSendWarning(input: JSONObject): String? {
if (input.optString("rawBase64").isNotBlank()) return null
val recipients = (listOf(input.optString("to"), input.optString("cc"))
.filter(String::isNotBlank)
.flatMap { InternetAddress.parse(it, true).mapNotNull { address -> (address as? InternetAddress)?.address?.lowercase(Locale.ROOT) } })
.distinct()
if (recipients.isEmpty()) return null
val data = AndroidAccountVault.pgpStore()
val contacts = data.optJSONArray("contacts") ?: JSONArray()
val keys = data.optJSONArray("keys") ?: JSONArray()
val available = ArrayList<Pair<String, String>>()
for (address in recipients) {
for (index in 0 until contacts.length()) {
val contact = contacts.optJSONObject(index) ?: continue
if (jsonStrings(contact.optJSONArray("emails")).any { it.equals(address, true) }) {
available.add(address to contact.optString("fingerprint"))
}
}
for (index in 0 until keys.length()) {
val key = keys.optJSONObject(index) ?: continue
if (key.optString("email").equals(address, true)) available.add(address to key.optString("fingerprint"))
}
}
val explicitRequest = input.optBoolean("pgpRequested")
if (!explicitRequest && available.isEmpty()) return null
val recipientLines = recipients.take(10).map { address ->
val fingerprints = available.filter { it.first == address }.map { formatPgpFingerprint(it.second) }.distinct()
if (fingerprints.isEmpty()) "$address — no key stored" else "$address\n${fingerprints.joinToString("\n")}"
}.joinToString("\n\n")
val prefix = if (explicitRequest) "OpenPGP was requested, but this message will be sent in plaintext." else "A stored OpenPGP key is available for at least one recipient."
return "$prefix\n\nRecipients and stored key fingerprints:\n$recipientLines\n\nThe message body and attachments will be readable by the mail provider and anyone who receives it. Send plaintext anyway?"
}
@PluginMethod
fun listDrafts(call: PluginCall) {