From 526ca767b10ae5d95c0cf62cc18c723746df8cee Mon Sep 17 00:00:00 2001 From: Tero Date: Tue, 3 Nov 2026 23:16:16 +0200 Subject: [PATCH] Android security implementation Phase 2 finalization part 1 --- ANDROID_SECURITY_PLAN.md | 10 +- TODO.md | 5 +- .../daybreak/mail/AndroidMailService.kt | 19 +- package-lock.json | 4 +- package.json | 2 +- pgp-mail-ui.js | 52 ++-- platform-bridge.js | 222 ++++++++++++++++-- scripts/android-pgp.js | 142 +++++++++-- service-worker.js | 2 +- tests/android-pgp-gnupg.test.cjs | 160 +++++++++++++ tests/android-pgp.test.cjs | 94 +++++++- tests/android-ui-support.test.cjs | 5 + www/pgp-mail-ui.js | 52 ++-- www/platform-bridge.js | 222 ++++++++++++++++-- www/service-worker.js | 2 +- 15 files changed, 882 insertions(+), 111 deletions(-) create mode 100644 tests/android-pgp-gnupg.test.cjs diff --git a/ANDROID_SECURITY_PLAN.md b/ANDROID_SECURITY_PLAN.md index daeb789..db3ff3f 100644 --- a/ANDROID_SECURITY_PLAN.md +++ b/ANDROID_SECURITY_PLAN.md @@ -14,9 +14,9 @@ Related: [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md), [SECURITY_REVIEW.md](./SECU Tracking legend: `[x]` implemented for the stated item; `[~]` partially implemented, with the remaining work stated beside it; `[ ]` not yet complete. A checked implementation item does **not** mean its phase's exit criteria or release gate have passed. -OpenPGP.js 6.3.2 is bundled for Android testing. The test implementation stores passphrase-protected keys and public contacts in the existing Keystore-encrypted vault; supports key generation/import/export, contact trust controls, PGP/MIME encrypt/sign, and on-demand PGP/MIME or inline-encrypted-message decryption. Encrypted sends are converted to ciphertext before native sending or offline queueing; decrypted content is held in renderer memory only. Native prompts cover trust elevation, key replacement, and plaintext sending when keys exist or encryption was requested. Key-server lookup is disabled, and PGP/MIME messages are capped at 25 MiB. This work was implemented to enable testing before the independent review gate was satisfied; it is **not approved for sensitive or production use**. +OpenPGP.js 6.3.2 is bundled for Android testing. The test implementation stores passphrase-protected keys and public contacts in the existing Keystore-encrypted vault; supports key generation/import/export, contact trust controls, PGP/MIME encrypt/sign, on-demand PGP/MIME or inline-encrypted-message decryption, and verification of signed-only PGP/MIME and clear-signed messages. Encrypted sends are converted to ciphertext before native sending or offline queueing; decrypted content is held in renderer memory only. Native prompts cover trust elevation, key replacement, and plaintext sending when keys exist or encryption was requested. Key-server lookup is disabled, and PGP/MIME messages are capped at 25 MiB. This work was implemented to enable testing before the independent review gate was satisfied; it is **not approved for sensitive or production use**. -**Validation evidence:** DAV URL, attachment-name, notification privacy, Android OpenPGP policy decisions, one-shot confirmation callbacks, and the missing-vault-key policy have Android unit tests. The app lock was exercised on an emulator with a device PIN, including background lock/unlock; with the lock active, emulator screenshots were fully obscured, and unlocking/turning the setting off restored the app. OpenPGP key generation/storage and native trust/plaintext confirmation dialogs were exercised on an emulator; trust cancellation left trust unchanged, trust confirmation persisted, and plaintext cancellation returned `PLAINTEXT_CANCELLED`. The V0.5.11 worktree release-variant merged manifest was inspected; the hardened debug app loaded `https://localhost` and the Capacitor bridge in an emulator at a 411 px viewport. Current validation: 153 Node tests and 21 Android unit tests pass; the Android debug build and release-manifest task succeed. Device testing of vault-corruption/key-loss recovery, invalid-certificate integration tests, production-signed APK review, and automated instrumentation of the actual confirmation dialogs remain open. This does not constitute live-provider mail testing or GnuPG/Thunderbird interoperability testing on Android. +**Validation evidence:** DAV URL, attachment-name, notification privacy, Android OpenPGP policy decisions, one-shot confirmation callbacks, and the missing-vault-key policy have Android unit tests. The app lock was exercised on an emulator with a device PIN, including background lock/unlock; with the lock active, emulator screenshots were fully obscured, and unlocking/turning the setting off restored the app. OpenPGP key generation/storage and native trust/plaintext confirmation dialogs were exercised on an emulator; trust cancellation left trust unchanged, trust confirmation persisted, and plaintext cancellation returned `PLAINTEXT_CANCELLED`. The Android OpenPGP module also has automated GnuPG interoperability tests in a Node harness, but those are not device-level mail tests. The V0.5.11 worktree release-variant merged manifest was inspected; the hardened debug app loaded `https://localhost` and the Capacitor bridge in an emulator at a 411 px viewport. Current validation: 157 Node tests and 21 Android unit tests pass; the Android debug build and release-manifest task succeed. Device testing of vault-corruption/key-loss recovery, invalid-certificate integration tests, production-signed APK review, and automated instrumentation of the actual confirmation dialogs remain open. This does not constitute live-provider mail testing or GnuPG/Thunderbird interoperability testing on Android. **Release blockers:** independent human cryptography/security review; instrumented tests of actual native confirmation dialogs and policy-bypass attempts; full signed/inline and hostile-input parity; Android/GnuPG/Thunderbird interoperability; Keystore lifecycle/recovery and biometric design; invalid-certificate integration tests; production-signed APK/manifest review; app-lock recovery polish; and compatibility review/remediation of the three moderate `npm audit --omit=dev` advisories in `ip-address` and the `nodemailer`/`mailparser` dependency chain. @@ -60,11 +60,11 @@ These are implementation observations, not proof that all paths are safe. In par ### Phase 2 — OpenPGP on Android (P0 before claiming encrypted-mail parity) -- [~] OpenPGP.js 6.3.2 is pinned and used by the experimental Android bundle, before the independent review gate is complete solely to enable local testing. Independent review and GnuPG/Thunderbird interoperability on Android are release blockers. +- [~] OpenPGP.js 6.3.2 is pinned and used by the experimental Android bundle, before the independent review gate is complete solely to enable local testing. Automated Node-harness tests exercise the Android module against GnuPG; independent review and on-device GnuPG/Thunderbird interoperability remain release blockers. - [~] PGP keys, contacts, trust, and settings are stored in the existing Keystore-encrypted vault; keys generated/imported by the UI are passphrase-protected, and passphrases are not serialized. Biometric wrapping-key release, lifecycle/recovery handling, and automated checks against unprotected-key persistence remain open. - [ ] Add optional biometric/device-credential release of PGP key access and test Keystore invalidation/recovery. Background sync does not use PGP private keys. -- [~] The Android UI/bridge supports key generation, paste-based import, export, deletion, revocation export, contacts, fingerprints, and trust. Native prompts now guard trust elevation and replacement; automated cancel/confirm regression tests remain open. -- [~] PGP/MIME encryption/signing, PGP/MIME and inline-encrypted-message decryption, attachments, encrypted Sent copies, and ciphertext-before-queueing are implemented. Signed-only/clear-signed/inline signature parity, full hostile-input/tampering suite, and Android interoperability remain open. +- [~] The Android UI/bridge supports key generation, paste-based import, export, deletion, revocation export, contacts, fingerprints, trust, and public keys offered as message attachments (never imported silently). Native prompts guard trust elevation and replacement; automated cancel/confirm regression tests remain open. +- [~] PGP/MIME encryption/signing, PGP/MIME and inline-encrypted-message decryption, attachments, encrypted Sent copies, ciphertext-before-queueing, signed-only PGP/MIME and clear-signed verification, and attached-public-key offers are implemented with Android-module tests. Tests cover Android-module/GnuPG interoperability in a Node harness, plus tampered, malformed, and oversized encrypted input. Device-level Thunderbird/GnuPG interoperability, native outbox/process-death tests, and remaining parity cases are open. - [~] Native prompts guard trust elevation, key replacement, and plaintext sending when a key is available or encryption was requested; the native send path checks PGP/MIME structure. Emulator smoke tests cover trust accept/cancel and plaintext cancel; policy and confirmation-gate unit tests cover prompt decisions and one-shot accept/cancel handling. Instrumented tests of the actual dialog UI, bypass attempts, stale-key cases, and queue policy remain open. - [x] Key-server lookup and publication are disabled in the initial Android test implementation. diff --git a/TODO.md b/TODO.md index 5429bb4..1f947e7 100644 --- a/TODO.md +++ b/TODO.md @@ -34,8 +34,9 @@ - [x] Experimental Android test path: Keystore-encrypted vault key storage, key/contact management, PGP/MIME encryption/signing, and on-demand decryption. - [x] Exercise native trust-change and plaintext-send confirmations on an emulator, including cancellation. - [x] Add Android unit tests for trust-elevation, key-replacement, and plaintext-send confirmation decisions. - - [ ] Android release gate: instrumented native-dialog UI and bypass tests, full parity/interoperability tests, independent human cryptography/security review, and signed release review. - - [ ] Android follow-up: biometric unlock, full vault lifecycle/recovery, signed/inline verification parity, and dependency advisory remediation. + - [x] Add Android-module tests for signed-only PGP/MIME, clear-signed verification, attached public-key offers, and GnuPG interoperability in a Node harness. + - [ ] Android release gate: instrumented native-dialog UI and bypass tests, device-level parity/interoperability tests (including Thunderbird/GnuPG on Android), independent human cryptography/security review, and signed release review. + - [ ] Android follow-up: biometric unlock, full vault lifecycle/recovery, remaining signature parity/device interoperability, and dependency advisory remediation. - [x] Phase 5 (automated): large attachments, multiple recipients, corrupted/tampered payloads, inline PGP and PGP/MIME tests. - [x] Phase 5 (GnuPG): automated interoperability tests with GnuPG 2.5 (both directions: PGP/MIME, inline, clear-signed, detached signatures). - [x] Phase 6: documentation and release. diff --git a/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt b/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt index 1c63271..73bd6d1 100644 --- a/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt +++ b/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt @@ -669,6 +669,7 @@ internal object AndroidMailService { collectParts(message, body, htmlBodies, attachments, links) val bodyText = body.joinToString("\n\n").trim().take(8000) val encrypted = isEncryptedMessage(message) || bodyText.contains("-----BEGIN PGP MESSAGE-----") + val signed = isSignedMessage(message) || bodyText.contains("-----BEGIN PGP SIGNED MESSAGE-----") val visibleBody = if (encrypted) "This message is encrypted. Unlock it with your OpenPGP key to read it." else bodyText val snippet = (if (encrypted) "Encrypted message" else visibleBody.ifBlank { subject }).replace(Regex("\\s+"), " ").take(180) val date = message.receivedDate ?: message.sentDate ?: Date() @@ -694,6 +695,7 @@ internal object AndroidMailService { .put("subject", subject) .put("snippet", snippet) .put("encrypted", encrypted) + .put("signed", signed) .put("time", DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault()).format(date)) .put("date", DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.getDefault()).format(date)) .put("timestamp", date.time) @@ -723,18 +725,29 @@ internal object AndroidMailService { } else if (content is String && content.contains("-----BEGIN PGP MESSAGE-----")) return true return false } + + private fun isSignedMessage(part: javax.mail.Part): Boolean { + if (part.isMimeType("multipart/signed")) return true + val content = try { part.content } catch (_: Exception) { return false } + if (content is Multipart) { + for (index in 0 until content.count) if (isSignedMessage(content.getBodyPart(index))) return true + } else if (content is String && content.contains("-----BEGIN PGP SIGNED MESSAGE-----")) return true + return false + } private fun attachmentList(attachments: JSONArray): List = (0 until attachments.length()).map { attachments.getJSONObject(it) } - private fun collectParts( + private fun collectParts( part: javax.mail.Part, body: MutableList, htmlBodies: MutableList, attachments: JSONArray, links: MutableSet - ) { - val filename = decode(part.fileName) + ) { + if (part.isMimeType("application/pgp-signature") || part.isMimeType("application/pgp-encrypted")) return + val filename = decode(part.fileName) + if (part.isMimeType("application/octet-stream") && filename.equals("encrypted.asc", true)) return if (filename.isNotBlank() || part.disposition.equals(javax.mail.Part.ATTACHMENT, true)) { val name = filename.ifBlank { "attachment" } val size = part.size.coerceAtLeast(0) diff --git a/package-lock.json b/package-lock.json index accd919..f178ff1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "ep-mail", - "version": "0.5.11", + "version": "0.5.12", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ep-mail", - "version": "0.5.11", + "version": "0.5.12", "dependencies": { "@capacitor/android": "^8.5.2", "@capacitor/core": "^8.5.2", diff --git a/package.json b/package.json index fc90085..2fa8d7e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ep-mail", - "version": "0.5.11", + "version": "0.5.12", "private": true, "description": "Eternity Project mail client", "homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client", diff --git a/pgp-mail-ui.js b/pgp-mail-ui.js index cd16030..1c3a004 100644 --- a/pgp-mail-ui.js +++ b/pgp-mail-ui.js @@ -70,12 +70,18 @@ function pgpRenderReaderState(message) { if (!header) return; reader.querySelectorAll('.pgp-status, .pgp-banner').forEach(node => node.remove()); let html = ''; - if (message.encrypted && !message.pgpDecrypted) { - html = `
đź”’ This message is encryptedUnlock it with your key passphrase to read it.
`; - } else if (message.encrypted) { - html = pgpSignatureHtml(message.pgpResult?.signatures, true); - } else if (message.pgpSignatures) { - html = pgpSignatureHtml(message.pgpSignatures, false); + if (message.encrypted && !message.pgpDecrypted) { + html = `
đź”’ This message is encryptedUnlock it with your key passphrase to read it.
`; + } else if (message.encrypted) { + html = pgpSignatureHtml(message.pgpResult?.signatures, true); + } else if (message.signed && Array.isArray(message.pgpSignatures)) { + html = pgpSignatureHtml(message.pgpSignatures, false); + } else if (message.signed && message.pgpVerifyFailed) { + html = `
Could not check the OpenPGP signature${escapePgpMailUi(message.pgpVerifyFailed)}
`; + } else if (message.signed) { + html = '
Checking OpenPGP signature…Do not rely on this message until verification completes.
'; + } else if (message.pgpSignatures) { + html = pgpSignatureHtml(message.pgpSignatures, false); } const keys = message.pgpResult?.attachedKeys || []; header.insertAdjacentHTML('afterend', html + keys.map((key, index) => `
Public key attached${escapePgpMailUi(key.emails.join(', ') || 'unknown address')} · ${escapePgpMailUi(pgpFormatFingerprint(key.fingerprint))}
`).join('')); @@ -86,7 +92,7 @@ function pgpRenderReaderState(message) { if (unlock) unlock.onclick = () => pgpUnlockMessage(message, true); } -async function pgpUnlockMessage(message, interactive) { +async function pgpUnlockMessage(message, interactive) { let passphrase = null; for (let attempt = 0; attempt < 3; attempt += 1) { let result; @@ -114,18 +120,36 @@ async function pgpUnlockMessage(message, interactive) { if (text) text.textContent = result.message; else toastPgpMailUi(result.message); return; - } -} - + } +} + +async function pgpVerifyMessage(message) { + try { + const result = await pgpApi().verifyMessage({ folder: message.sourceFolder || 'Inbox', uid: message.uid }); + if (result.failed) message.pgpVerifyFailed = result.message || 'The signature could not be checked.'; + else { + message.pgpSignatures = result.signatures || []; + message.pgpVerifyFailed = null; + } + } catch (error) { + message.pgpVerifyFailed = error.message || 'The signature could not be checked.'; + } + if (pgpMailUi.state.activeMessage === message.id) pgpRenderReaderState(message); +} + pgpMailUi.wrapOpenMessage(baseOpenMessage => function (id) { baseOpenMessage(id); const message = pgpMailUi.state.messages.find(item => item.id === id); if (!message || !pgpApi()) return; pgpRenderReaderState(message); - if (message.encrypted && !message.pgpDecrypted && !message.pgpAutoTried) { - message.pgpAutoTried = true; - void pgpUnlockMessage(message, false); - } + if (message.encrypted && !message.pgpDecrypted && !message.pgpAutoTried) { + message.pgpAutoTried = true; + void pgpUnlockMessage(message, false); + } + if (!message.encrypted && message.signed && typeof pgpApi().verifyMessage === 'function' && !message.pgpVerifyTried) { + message.pgpVerifyTried = true; + void pgpVerifyMessage(message); + } }); // Compose: encrypt/sign options. diff --git a/platform-bridge.js b/platform-bridge.js index 4294820..2a2b271 100644 --- a/platform-bridge.js +++ b/platform-bridge.js @@ -5738,6 +5738,7 @@ super(e2, t2); } }; + var ka = /* @__PURE__ */ N.constructAllowedPackets([Ns]); var Ea = class { constructor(e2) { this.packets = e2 || new Gs(); @@ -5753,6 +5754,22 @@ return this.packets.map(((e2) => e2.issuerKeyID)); } }; + async function va({ armoredSignature: e2, binarySignature: t2, config: r2, ...n2 }) { + r2 = { ...F, ...r2 }; + let i2 = e2 || t2; + if (!i2) throw Error("readSignature: must pass options object containing `armoredSignature` or `binarySignature`"); + if (e2 && !N.isString(e2)) throw Error("readSignature: options.armoredSignature must be a string"); + if (t2 && !N.isUint8Array(t2)) throw Error("readSignature: options.binarySignature must be a Uint8Array"); + const s2 = Object.keys(n2); + if (s2.length > 0) throw Error("Unknown option: " + s2.join(", ")); + if (e2) { + const { type: e3, data: t3 } = await $(i2); + if (e3 !== R.armor.signature) throw Error("Armored text not of type signature"); + i2 = t3; + } + const a2 = await Gs.fromBinary(i2, ka, r2); + return new Ea(a2); + } async function Ia(e2, t2) { const r2 = new wa(e2.date, t2); return r2.packets = null, r2.algorithm = R.write(R.publicKey, e2.algorithm), await r2.generate(e2.rsaBits, e2.curve), await r2.computeFingerprintAndKeyID(), r2; @@ -6874,6 +6891,7 @@ const f2 = new no(h2); return f2.fromStream = c2, f2; } + var co = /* @__PURE__ */ N.constructAllowedPackets([Ns]); var uo = class _uo { constructor(e2, t2) { if (this.text = N.removeTrailingSpaces(e2).replace(/\r?\n/g, "\r\n"), t2 && !(t2 instanceof Ea)) throw Error("Invalid signature input"); @@ -6903,6 +6921,38 @@ return ee(R.armor.signed, r2, void 0, void 0, void 0, t2, e2); } }; + async function ho({ cleartextMessage: e2, config: t2, ...r2 }) { + if (t2 = { ...F, ...t2 }, !e2) throw Error("readCleartextMessage: must pass options object containing `cleartextMessage`"); + if (!N.isString(e2)) throw Error("readCleartextMessage: options.cleartextMessage must be a string"); + const n2 = Object.keys(r2); + if (n2.length > 0) throw Error("Unknown option: " + n2.join(", ")); + const i2 = await $(e2); + if (i2.type !== R.armor.signed) throw Error("No cleartext signed message."); + const s2 = await Gs.fromBinary(i2.data, co, t2); + !(function(e3, t3) { + const r3 = function(e4) { + const r4 = (e5) => (t4) => e5.hashAlgorithm === t4; + for (let n4 = 0; n4 < t3.length; n4++) if (t3[n4].constructor.tag === R.packet.signature && !e4.some(r4(t3[n4]))) return false; + return true; + }, n3 = []; + if (e3.forEach(((e4) => { + const t4 = e4.match(/^Hash: (.+)$/); + if (!t4) throw Error('Only "Hash" header allowed in cleartext signed message'); + { + const e5 = t4[1].replace(/\s/g, "").split(",").map(((e6) => { + try { + return R.write(R.hash, e6.toLowerCase()); + } catch { + throw Error("Unknown hash algorithm in armor header: " + e6.toLowerCase()); + } + })); + n3.push(...e5); + } + })), n3.length && !r3(n3)) throw Error("Hash algorithm mismatch in armor header and signature"); + })(i2.headers, s2); + const a2 = new Ea(s2); + return new uo(i2.text, a2); + } async function lo({ userIDs: e2 = [], passphrase: t2, type: r2, curve: n2, rsaBits: i2 = 4096, keyExpirationTime: s2 = 0, date: a2 = /* @__PURE__ */ new Date(), subkeys: o2 = [{}], format: c2 = "armored", signatureNotations: u2 = [], config: h2, ...f2 }) { Do(h2 = { ...F, ...h2 }), r2 || n2 ? (r2 = r2 || "ecc", n2 = n2 || "curve25519Legacy") : (r2 = h2.v6Keys ? "curve25519" : "ecc", n2 = "curve25519Legacy"), e2 = Uo(e2), u2 = Uo(u2); const l2 = Object.keys(f2); @@ -7011,6 +7061,23 @@ throw N.wrapError("Error signing message", e3); } } + async function ko({ message: e2, verificationKeys: t2, expectSigned: r2 = false, format: n2 = "utf8", signature: i2 = null, date: s2 = /* @__PURE__ */ new Date(), config: a2, ...o2 }) { + if (Do(a2 = { ...F, ...a2 }), So(e2), t2 = Uo(t2), o2.publicKeys) throw Error("The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead"); + const c2 = Object.keys(o2); + if (c2.length > 0) throw Error("Unknown option: " + c2.join(", ")); + if (e2 instanceof uo && "binary" === n2) throw Error("Can't return cleartext message data as binary"); + if (e2 instanceof uo && i2) throw Error("Can't verify detached cleartext signature"); + try { + const o3 = {}; + if (o3.signatures = i2 ? await e2.verifyDetached(i2, t2, s2, a2) : await e2.verify(t2, s2, a2), o3.data = "binary" === n2 ? e2.getLiteralData() : e2.getText(), e2.fromStream && !i2 && xo(o3, .../* @__PURE__ */ new Set([e2, e2.unwrapCompressed()])), r2) { + if (0 === o3.signatures.length) throw Error("Message is not signed"); + o3.data = A([o3.data, P((async () => (await N.anyPromise(o3.signatures.map(((e3) => e3.verified))), "binary" === n2 ? new Uint8Array() : "")))]); + } + return o3.data = await Po(o3.data), o3; + } catch (e3) { + throw N.wrapError("Error verifying signed message", e3); + } + } function Bo(e2) { if (!(e2 instanceof no)) throw Error("Parameter [message] needs to be of type Message"); } @@ -9896,6 +9963,25 @@ visit(bytes); return result; } + async function attachedPublicKeys(attachments) { + const found = []; + for (const file of attachments || []) { + const type = String(file.contentType || "").toLowerCase(); + if (type !== "application/pgp-keys" && !/\.asc$/i.test(file.filename || "")) continue; + if (!file.contentBase64 || Number(file.size) > MAX_KEY_LENGTH || file.contentBase64.length > MAX_KEY_LENGTH * 2) continue; + try { + const binary = atob(file.contentBase64); + const armoredKey = decoder.decode(Uint8Array.from(binary, (char) => char.charCodeAt(0))).trim(); + if (!/-----BEGIN PGP PUBLIC KEY BLOCK-----/.test(armoredKey) || /-----BEGIN PGP PRIVATE KEY BLOCK-----/.test(armoredKey) || armoredKey.length > MAX_KEY_LENGTH) continue; + const key = await Ja({ armoredKey }); + await key.getPrimaryUser(); + found.push({ armoredKey: key.armor(), fingerprint: key.getFingerprint().toUpperCase(), emails: emailsOf(key) }); + if (found.length === 5) break; + } catch { + } + } + return found; + } function randomBoundary() { const bytes = crypto.getRandomValues(new Uint8Array(18)); return `=_ep-${Array.from(bytes, (value) => value.toString(16).padStart(2, "0")).join("")}`; @@ -9961,6 +10047,72 @@ ${parts.join("")}`; for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCharCode(...bytes.subarray(index, index + 32768)); return btoa(binary); } + function bytesToLatin1(bytes) { + let text = ""; + for (let index = 0; index < bytes.length; index += 32768) { + text += String.fromCharCode(...bytes.subarray(index, index + 32768)); + } + return text; + } + function splitSignedMime(source, boundary) { + if (!boundary || boundary.length > 200) return null; + const text = bytesToLatin1(source); + const escaped = boundary.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const delimiter = new RegExp(`(?:^|\\r?\\n)--${escaped}(--)?[ \\t]*(?=\\r?\\n|$)`, "g"); + const marks = [...text.matchAll(delimiter)]; + if (marks.length < 3) return null; + const contentAfter = (mark) => { + const lineEnd = text.indexOf("\n", mark.index + mark[0].length); + return lineEnd < 0 ? text.length : lineEnd + 1; + }; + const signed = text.slice(contentAfter(marks[0]), marks[1].index).replace(/\r?\n/g, "\r\n"); + const signaturePart = text.slice(contentAfter(marks[1]), marks[2].index); + const signature = /-----BEGIN PGP SIGNATURE-----[\s\S]+?-----END PGP SIGNATURE-----/.exec(signaturePart)?.[0]; + if (!signature) return null; + return { signed: Uint8Array.from(signed, (char) => char.charCodeAt(0) & 255), signature }; + } + function senderFrom(headers) { + const value = String(headers.from || ""); + return (/<([^<>]+)>/.exec(value)?.[1] || /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i.exec(value)?.[0] || "").toLowerCase(); + } + function invalidSignature() { + return { + status: "invalid", + keyId: "", + fingerprint: null, + trust: null, + email: null, + matchesSender: false, + keyChanged: false + }; + } + async function signatureStatuses(signatures, verification, sender) { + const results = []; + for (const signature of signatures || []) { + const keyId = signature.keyID.toHex().toUpperCase(); + const known = verification.find((candidate) => candidate.key.getKeys().some((key) => key.getKeyID().toHex().toUpperCase() === keyId)); + let status = "valid"; + try { + await signature.verified; + } catch { + status = known ? "invalid" : "unknown-key"; + } + const keyEmails = known?.entry.emails || (known?.entry.email ? [known.entry.email.toLowerCase()] : []); + const matchesSender = Boolean(sender && keyEmails.includes(sender)); + const changed = Boolean(sender && verification.some((candidate) => !candidate.entry.own && candidate.entry.emails?.includes(sender) && candidate.entry.fingerprint !== known?.entry.fingerprint)); + results.push({ + status, + keyId, + fingerprint: known?.entry.fingerprint || null, + trust: known?.entry.trust || null, + email: keyEmails[0] || null, + matchesSender, + keyChanged: changed, + ...status === "valid" && known && sender && !matchesSender ? { mismatch: true } : {} + }); + } + return results; + } function createAndroidPgp({ EpMail: EpMail2, getAccount }) { let storePromise; const passphrases = /* @__PURE__ */ new Map(); @@ -10229,31 +10381,8 @@ ${body}`); return { failed: true, code: "CORRUPT", message: "The message could not be decrypted. It may be damaged or altered." }; } const content = parseInnerMime(decrypted.data); - const signatures = []; - for (const item of decrypted.signatures || []) { - const known = verify.find((candidate) => candidate.key.getKeys().some((key) => key.getKeyID().toHex().toUpperCase() === item.keyID.toHex().toUpperCase())); - let status = "valid"; - try { - await item.verified; - } catch { - status = known ? "invalid" : "unknown-key"; - } - const from = /^From:\s*(.*)$/im.exec(text)?.[1] || ""; - const sender = (/<([^<>]+)>/.exec(from)?.[1] || /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i.exec(from)?.[0] || "").toLowerCase(); - const keyEmails = known?.entry.emails || (known?.entry.email ? [known.entry.email.toLowerCase()] : []); - const changed = Boolean(sender && data.contacts.some((entry) => entry.emails.includes(sender) && entry.fingerprint !== known?.entry.fingerprint)); - const matchesSender = Boolean(sender && keyEmails.includes(sender)); - signatures.push({ - status, - keyId: item.keyID.toHex().toUpperCase(), - fingerprint: known?.entry.fingerprint || null, - trust: known?.entry.trust || null, - email: keyEmails[0] || null, - matchesSender, - keyChanged: changed, - ...status === "valid" && known && sender && !matchesSender ? { mismatch: true } : {} - }); - } + const signatures = await signatureStatuses(decrypted.signatures, verify, senderFrom(splitEntity(raw).headers)); + const attachedKeys = await attachedPublicKeys(content.attachments); return { ok: true, body: content.body ? content.body.split(/\n\s*\n/).filter(Boolean) : [], @@ -10263,12 +10392,52 @@ ${body}`); attachment: content.attachments[0]?.filename || null, size: content.attachments[0]?.size || "", signatures, - attachedKeys: [] + attachedKeys }; } catch (error) { return { failed: true, code: error.code || "ERROR", message: error.message || "Could not decrypt this message." }; } } + async function verifyMessage({ folder = "Inbox", uid }) { + try { + const source = await EpMail2.pgpGetMessageSource({ folder, uid }); + const raw = Uint8Array.from(atob(source.rawBase64), (char) => char.charCodeAt(0)); + if (raw.byteLength > MAX_MESSAGE_BYTES) { + return { failed: true, code: "TOO_LARGE", message: "This signed message is too large to verify." }; + } + const entity = splitEntity(raw); + const contentType = entity.headers["content-type"] || ""; + const sender = senderFrom(entity.headers); + const data = await store(); + const verification = await verificationKeys(data); + if (/^multipart\/signed/i.test(contentType) && parameter(contentType, "protocol").toLowerCase() === "application/pgp-signature") { + const parts = splitSignedMime(raw, parameter(contentType, "boundary")); + if (!parts) return { signatures: [invalidSignature()] }; + try { + const result = await ko({ + message: await oo({ binary: parts.signed }), + signature: await va({ armoredSignature: parts.signature }), + verificationKeys: verification.map((item) => item.key) + }); + return { signatures: await signatureStatuses(result.signatures, verification, sender) }; + } catch { + return { signatures: [invalidSignature()] }; + } + } + const body = decoder.decode(decodePart(entity.body, entity.headers["content-transfer-encoding"])); + const armored = /-----BEGIN PGP SIGNED MESSAGE-----[\s\S]+?-----END PGP SIGNATURE-----/.exec(body)?.[0]; + if (!armored) return { signatures: [] }; + try { + const message = await ho({ cleartextMessage: armored }); + const result = await ko({ message, verificationKeys: verification.map((item) => item.key) }); + return { signatures: await signatureStatuses(result.signatures, verification, sender) }; + } catch { + return { signatures: [invalidSignature()] }; + } + } catch (error) { + return { failed: true, code: error.code || "VERIFY_ERROR", message: error.message || "Could not verify this message." }; + } + } const api = { platform: "android", async list() { @@ -10413,6 +10582,7 @@ Only continue if you checked this fingerprint with the owner.`)) throw new Error }; }, decryptMessage, + verifyMessage, async getSettings() { const data = await store(); return { cacheMinutes }; diff --git a/scripts/android-pgp.js b/scripts/android-pgp.js index bd2db8b..2f3bfbd 100644 --- a/scripts/android-pgp.js +++ b/scripts/android-pgp.js @@ -118,6 +118,26 @@ function parseInnerMime(bytes) { return result; } +async function attachedPublicKeys(attachments) { + const found = []; + for (const file of attachments || []) { + const type = String(file.contentType || '').toLowerCase(); + if (type !== 'application/pgp-keys' && !/\.asc$/i.test(file.filename || '')) continue; + if (!file.contentBase64 || Number(file.size) > MAX_KEY_LENGTH || file.contentBase64.length > MAX_KEY_LENGTH * 2) continue; + try { + const binary = atob(file.contentBase64); + const armoredKey = decoder.decode(Uint8Array.from(binary, char => char.charCodeAt(0))).trim(); + if (!/-----BEGIN PGP PUBLIC KEY BLOCK-----/.test(armoredKey) || + /-----BEGIN PGP PRIVATE KEY BLOCK-----/.test(armoredKey) || armoredKey.length > MAX_KEY_LENGTH) continue; + const key = await openpgp.readKey({ armoredKey }); + await key.getPrimaryUser(); + found.push({ armoredKey: key.armor(), fingerprint: key.getFingerprint().toUpperCase(), emails: emailsOf(key) }); + if (found.length === 5) break; + } catch { /* ignore malformed, expired or non-public key attachments */ } + } + return found; +} + function randomBoundary() { const bytes = crypto.getRandomValues(new Uint8Array(18)); return `=_ep-${Array.from(bytes, value => value.toString(16).padStart(2, '0')).join('')}`; @@ -171,6 +191,70 @@ function toBase64(bytes) { return btoa(binary); } +function bytesToLatin1(bytes) { + let text = ''; + for (let index = 0; index < bytes.length; index += 0x8000) { + text += String.fromCharCode(...bytes.subarray(index, index + 0x8000)); + } + return text; +} + +function splitSignedMime(source, boundary) { + if (!boundary || boundary.length > 200) return null; + const text = bytesToLatin1(source); + const escaped = boundary.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const delimiter = new RegExp(`(?:^|\\r?\\n)--${escaped}(--)?[ \\t]*(?=\\r?\\n|$)`, 'g'); + const marks = [...text.matchAll(delimiter)]; + if (marks.length < 3) return null; + const contentAfter = mark => { + const lineEnd = text.indexOf('\n', mark.index + mark[0].length); + return lineEnd < 0 ? text.length : lineEnd + 1; + }; + const signed = text.slice(contentAfter(marks[0]), marks[1].index).replace(/\r?\n/g, '\r\n'); + const signaturePart = text.slice(contentAfter(marks[1]), marks[2].index); + const signature = /-----BEGIN PGP SIGNATURE-----[\s\S]+?-----END PGP SIGNATURE-----/.exec(signaturePart)?.[0]; + if (!signature) return null; + return { signed: Uint8Array.from(signed, char => char.charCodeAt(0) & 255), signature }; +} + +function senderFrom(headers) { + const value = String(headers.from || ''); + return (/<([^<>]+)>/.exec(value)?.[1] || /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i.exec(value)?.[0] || '').toLowerCase(); +} + +function invalidSignature() { + return { status: 'invalid', keyId: '', fingerprint: null, trust: null, email: null, + matchesSender: false, keyChanged: false }; +} + +async function signatureStatuses(signatures, verification, sender) { + const results = []; + for (const signature of signatures || []) { + const keyId = signature.keyID.toHex().toUpperCase(); + const known = verification.find(candidate => candidate.key.getKeys() + .some(key => key.getKeyID().toHex().toUpperCase() === keyId)); + let status = 'valid'; + try { await signature.verified; } + catch { status = known ? 'invalid' : 'unknown-key'; } + const keyEmails = known?.entry.emails || (known?.entry.email ? [known.entry.email.toLowerCase()] : []); + const matchesSender = Boolean(sender && keyEmails.includes(sender)); + const changed = Boolean(sender && verification.some(candidate => + !candidate.entry.own && candidate.entry.emails?.includes(sender) && + candidate.entry.fingerprint !== known?.entry.fingerprint)); + results.push({ + status, + keyId, + fingerprint: known?.entry.fingerprint || null, + trust: known?.entry.trust || null, + email: keyEmails[0] || null, + matchesSender, + keyChanged: changed, + ...(status === 'valid' && known && sender && !matchesSender ? { mismatch: true } : {}) + }); + } + return results; +} + export function createAndroidPgp({ EpMail, getAccount }) { let storePromise; const passphrases = new Map(); @@ -351,28 +435,55 @@ export function createAndroidPgp({ EpMail, getAccount }) { try { decrypted = await openpgp.decrypt({ message, decryptionKeys: privateKey, verificationKeys: verify.map(item => item.key), format: 'binary' }); } catch { return { failed: true, code: 'CORRUPT', message: 'The message could not be decrypted. It may be damaged or altered.' }; } const content = parseInnerMime(decrypted.data); - const signatures = []; - for (const item of decrypted.signatures || []) { - const known = verify.find(candidate => candidate.key.getKeys().some(key => key.getKeyID().toHex().toUpperCase() === item.keyID.toHex().toUpperCase())); - let status = 'valid'; - try { await item.verified; } catch { status = known ? 'invalid' : 'unknown-key'; } - const from = /^From:\s*(.*)$/im.exec(text)?.[1] || ''; - const sender = (/<([^<>]+)>/.exec(from)?.[1] || /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i.exec(from)?.[0] || '').toLowerCase(); - const keyEmails = known?.entry.emails || (known?.entry.email ? [known.entry.email.toLowerCase()] : []); - const changed = Boolean(sender && data.contacts.some(entry => entry.emails.includes(sender) && entry.fingerprint !== known?.entry.fingerprint)); - const matchesSender = Boolean(sender && keyEmails.includes(sender)); - signatures.push({ status, keyId: item.keyID.toHex().toUpperCase(), fingerprint: known?.entry.fingerprint || null, - trust: known?.entry.trust || null, email: keyEmails[0] || null, matchesSender, keyChanged: changed, - ...(status === 'valid' && known && sender && !matchesSender ? { mismatch: true } : {}) }); - } + const signatures = await signatureStatuses(decrypted.signatures, verify, senderFrom(splitEntity(raw).headers)); + const attachedKeys = await attachedPublicKeys(content.attachments); return { ok: true, body: content.body ? content.body.split(/\n\s*\n/).filter(Boolean) : [], html: content.html, links: [], attachments: content.attachments, attachment: content.attachments[0]?.filename || null, - size: content.attachments[0]?.size || '', signatures, attachedKeys: [] }; + size: content.attachments[0]?.size || '', signatures, attachedKeys }; } catch (error) { return { failed: true, code: error.code || 'ERROR', message: error.message || 'Could not decrypt this message.' }; } } + async function verifyMessage({ folder = 'Inbox', uid }) { + try { + const source = await EpMail.pgpGetMessageSource({ folder, uid }); + const raw = Uint8Array.from(atob(source.rawBase64), char => char.charCodeAt(0)); + if (raw.byteLength > MAX_MESSAGE_BYTES) { + return { failed: true, code: 'TOO_LARGE', message: 'This signed message is too large to verify.' }; + } + const entity = splitEntity(raw); + const contentType = entity.headers['content-type'] || ''; + const sender = senderFrom(entity.headers); + const data = await store(); + const verification = await verificationKeys(data); + if (/^multipart\/signed/i.test(contentType) && + parameter(contentType, 'protocol').toLowerCase() === 'application/pgp-signature') { + const parts = splitSignedMime(raw, parameter(contentType, 'boundary')); + if (!parts) return { signatures: [invalidSignature()] }; + try { + const result = await openpgp.verify({ + message: await openpgp.createMessage({ binary: parts.signed }), + signature: await openpgp.readSignature({ armoredSignature: parts.signature }), + verificationKeys: verification.map(item => item.key) + }); + return { signatures: await signatureStatuses(result.signatures, verification, sender) }; + } catch { return { signatures: [invalidSignature()] }; } + } + + const body = decoder.decode(decodePart(entity.body, entity.headers['content-transfer-encoding'])); + const armored = /-----BEGIN PGP SIGNED MESSAGE-----[\s\S]+?-----END PGP SIGNATURE-----/.exec(body)?.[0]; + if (!armored) return { signatures: [] }; + try { + const message = await openpgp.readCleartextMessage({ cleartextMessage: armored }); + const result = await openpgp.verify({ message, verificationKeys: verification.map(item => item.key) }); + return { signatures: await signatureStatuses(result.signatures, verification, sender) }; + } catch { return { signatures: [invalidSignature()] }; } + } catch (error) { + return { failed: true, code: error.code || 'VERIFY_ERROR', message: error.message || 'Could not verify this message.' }; + } + } + const api = { platform: 'android', async list() { return (await store()).keys.map(publicInfo); }, @@ -440,6 +551,7 @@ export function createAndroidPgp({ EpMail, getAccount }) { signer: entry ? { fingerprint: entry.fingerprint, email: entry.email, name: entry.name, unlocked: Boolean(cached(entry.fingerprint)) } : null }; }, decryptMessage, + verifyMessage, async getSettings() { const data = await store(); return { cacheMinutes }; }, async setSettings({ cacheMinutes: value }) { const number = Number(value); diff --git a/service-worker.js b/service-worker.js index ad39cf7..6c18bad 100644 --- a/service-worker.js +++ b/service-worker.js @@ -1,4 +1,4 @@ -const CACHE='ep-mail-v18'; +const CACHE='ep-mail-v19'; const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge-loader.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg']; self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES)).then(()=>self.skipWaiting()))); self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k)))).then(()=>self.clients.claim()))); diff --git a/tests/android-pgp-gnupg.test.cjs b/tests/android-pgp-gnupg.test.cjs new file mode 100644 index 0000000..9cbc1b0 --- /dev/null +++ b/tests/android-pgp-gnupg.test.cjs @@ -0,0 +1,160 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { spawnSync } = require('node:child_process'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const vm = require('node:vm'); +const esbuild = require('esbuild'); +const openpgp = require('openpgp'); +const { simpleParser } = require('mailparser'); +const { webcrypto } = require('node:crypto'); + +global.crypto ||= webcrypto; +global.document ||= { addEventListener() {} }; + +const bundled = esbuild.buildSync({ + entryPoints: [path.join(__dirname, '..', 'scripts', 'android-pgp.js')], + bundle: true, + platform: 'browser', + format: 'iife', + globalName: 'AndroidPgpInteropBundle', + write: false +}).outputFiles[0].text; +vm.runInThisContext(bundled); +const { createAndroidPgp } = global.AndroidPgpInteropBundle; + +const gpgPath = [process.env.GPG_PATH, 'gpg', 'C:\\Program Files\\GnuPG\\bin\\gpg.exe', 'C:\\Program Files (x86)\\GnuPG\\bin\\gpg.exe'] + .filter(Boolean).find(candidate => spawnSync(candidate, ['--version']).status === 0); +const skip = gpgPath ? false : 'GnuPG is not installed'; +const PASSPHRASE = 'Android GnuPG test passphrase'; + +function makeEndpoint(account) { + const vault = { keys: [], contacts: [], settings: {} }; + let messageSource = null; + const EpMail = { + async pgpLoadStore() { return JSON.parse(JSON.stringify(vault)); }, + async pgpSaveStore({ store }) { Object.assign(vault, JSON.parse(JSON.stringify(store))); return { ok: true }; }, + async pgpGetMessageSource() { return messageSource; } + }; + return { + api: createAndroidPgp({ EpMail, getAccount: async () => account }), + setMessage(rawBase64) { messageSource = { rawBase64 }; } + }; +} + +function setupGpg() { + const home = fs.mkdtempSync(path.join(os.tmpdir(), 'ep-android-gnupg-')); + const gpg = (args, input) => { + const result = spawnSync(gpgPath, [ + '--homedir', home, '--batch', '--yes', '--pinentry-mode', 'loopback', + '--passphrase', PASSPHRASE, '--trust-model', 'always', ...args + ], { input }); + if (result.status !== 0) throw new Error(`gpg ${args.join(' ')} failed: ${result.stderr}`); + return { out: result.stdout, err: result.stderr.toString() }; + }; + gpg(['--quick-generate-key', 'Gina Gnu ', 'ed25519', 'cert', 'never']); + const fingerprint = /^fpr:::::::::([0-9A-F]+):/m.exec( + gpg(['--list-keys', '--with-colons', 'gina@example.test']).out.toString() + )?.[1]; + if (!fingerprint) throw new Error('Could not find the generated GnuPG test key fingerprint.'); + gpg(['--quick-add-key', fingerprint, 'cv25519', 'encr', 'never']); + gpg(['--quick-add-key', fingerprint, 'ed25519', 'sign', 'never']); + return { home, fingerprint, gpg }; +} + +function encryptedMime(from, to, armor) { + const boundary = 'android-gnupg-encrypted'; + return Buffer.from([ + `From: ${from}`, + `To: ${to}`, + 'Subject: Android GnuPG interoperability', + 'MIME-Version: 1.0', + `Content-Type: multipart/encrypted; protocol="application/pgp-encrypted"; boundary="${boundary}"`, + '', + `--${boundary}`, + 'Content-Type: application/pgp-encrypted', + '', + 'Version: 1', + `--${boundary}`, + 'Content-Type: application/octet-stream; name="encrypted.asc"', + '', + armor.trim(), + `--${boundary}--`, + '' + ].join('\r\n')); +} + +test('Android OpenPGP PGP/MIME interoperates with GnuPG for send, read, and signature verification', { skip }, async () => { + const { home, fingerprint, gpg } = setupGpg(); + try { + const android = makeEndpoint({ email: 'android@example.test', displayName: 'Android User', signature: '' }); + const own = await android.api.generate({ + name: 'Android User', email: 'android@example.test', passphrase: 'android key test passphrase' + }); + const gpgPublic = gpg(['--armor', '--export', 'gina@example.test']).out.toString(); + await android.api.addContact({ armoredKey: gpgPublic }); + gpg(['--import'], Buffer.from(await android.api.exportPublic(own.key.fingerprint))); + + const outgoing = await android.api.buildOutgoing({ + to: 'Gina Gnu ', + cc: '', + subject: 'Android to GnuPG', + text: 'Encrypted and signed from the Android OpenPGP module', + messageId: '', + pgp: { encrypt: true, sign: true, passphrase: 'android key test passphrase' }, + attachments: [] + }); + const outboundText = Buffer.from(outgoing.rawBase64, 'base64').toString('utf8'); + const outboundArmor = /-----BEGIN PGP MESSAGE-----[\s\S]+?-----END PGP MESSAGE-----/.exec(outboundText)?.[0]; + assert.ok(outboundArmor, 'Android output should contain an armored encrypted message'); + const decrypted = gpg(['--decrypt'], Buffer.from(outboundArmor)); + assert.match((await simpleParser(decrypted.out)).text, /Encrypted and signed from the Android OpenPGP module/); + assert.match(decrypted.err, /Good signature from/); + + const incomingInner = Buffer.from('Content-Type: text/plain; charset=utf-8\r\n\r\nSigned and encrypted by GnuPG\r\n'); + const incomingArmor = gpg([ + '--armor', '--encrypt', '--sign', '--local-user', 'gina@example.test', '--recipient', 'android@example.test' + ], incomingInner).out.toString(); + android.setMessage(encryptedMime('Gina Gnu ', 'android@example.test', incomingArmor).toString('base64')); + const opened = await android.api.decryptMessage({ folder: 'Inbox', uid: 11, passphrase: 'android key test passphrase' }); + assert.equal(opened.ok, true, opened.message); + assert.deepEqual(opened.body, ['Signed and encrypted by GnuPG']); + assert.equal(opened.signatures[0].status, 'valid'); + assert.equal(opened.signatures[0].matchesSender, true); + + const signedPart = 'Content-Type: text/plain; charset=utf-8\r\n\r\nGnuPG detached signed body'; + const detached = gpg(['--armor', '--detach-sign', '--local-user', 'gina@example.test'], Buffer.from(signedPart)).out.toString().replace(/\r?\n/g, '\r\n').trim(); + const signedBoundary = 'android-gnupg-signed'; + const signedMime = Buffer.from([ + 'From: Gina Gnu ', + 'To: android@example.test', + 'MIME-Version: 1.0', + `Content-Type: multipart/signed; protocol="application/pgp-signature"; boundary="${signedBoundary}"`, + '', + `--${signedBoundary}`, + signedPart, + `--${signedBoundary}`, + 'Content-Type: application/pgp-signature', + '', + detached, + `--${signedBoundary}--`, + '' + ].join('\r\n')); + android.setMessage(signedMime.toString('base64')); + const signedMimeResult = await android.api.verifyMessage({ folder: 'Inbox', uid: 12 }); + assert.equal(signedMimeResult.signatures[0].status, 'valid'); + assert.equal(signedMimeResult.signatures[0].matchesSender, true); + + const clearSigned = gpg(['--clearsign', '--local-user', 'gina@example.test'], Buffer.from('GnuPG clear-signed body\n')).out.toString(); + const clearSource = Buffer.from( + `From: Gina Gnu \r\nTo: android@example.test\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n${clearSigned}\r\n` + ); + android.setMessage(clearSource.toString('base64')); + const clearResult = await android.api.verifyMessage({ folder: 'Inbox', uid: 13 }); + assert.equal(clearResult.signatures[0].status, 'valid'); + assert.equal(clearResult.signatures[0].matchesSender, true); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } +}); diff --git a/tests/android-pgp.test.cjs b/tests/android-pgp.test.cjs index d9bd950..2657d79 100644 --- a/tests/android-pgp.test.cjs +++ b/tests/android-pgp.test.cjs @@ -4,6 +4,7 @@ const path = require('node:path'); const vm = require('node:vm'); const esbuild = require('esbuild'); const { webcrypto } = require('node:crypto'); +const openpgp = require('openpgp'); global.crypto ||= webcrypto; global.document ||= { addEventListener() {} }; @@ -37,15 +38,20 @@ function makeEndpoint(account) { test('Android OpenPGP encrypts MIME attachments and decrypts with a recipient key', async () => { const sender = makeEndpoint({ email: 'alice@example.test', displayName: 'Alice', signature: '' }); const recipient = makeEndpoint({ email: 'bob@example.test', displayName: 'Bob', signature: '' }); + const thirdParty = makeEndpoint({ email: 'charlie@example.test', displayName: 'Charlie', signature: '' }); const alice = await sender.api.generate({ name: 'Alice', email: 'alice@example.test', passphrase: 'alice test passphrase' }); const bob = await recipient.api.generate({ name: 'Bob', email: 'bob@example.test', passphrase: 'bob test passphrase' }); + const charlie = await thirdParty.api.generate({ name: 'Charlie', email: 'charlie@example.test', passphrase: 'charlie test passphrase' }); await sender.api.addContact({ armoredKey: await recipient.api.exportPublic(bob.key.fingerprint) }); await recipient.api.addContact({ armoredKey: await sender.api.exportPublic(alice.key.fingerprint) }); const built = await sender.api.buildOutgoing({ to: 'Bob ', cc: '', subject: 'Secret note', text: 'hello from Android', messageId: '', pgp: { encrypt: true, sign: true, passphrase: 'alice test passphrase' }, - attachments: [{ filename: 'note.txt', contentType: 'text/plain', contentBase64: Buffer.from('private attachment').toString('base64') }] + attachments: [ + { filename: 'note.txt', contentType: 'text/plain', contentBase64: Buffer.from('private attachment').toString('base64') }, + { filename: 'charlie.asc', contentType: 'application/pgp-keys', contentBase64: Buffer.from(await thirdParty.api.exportPublic(charlie.key.fingerprint)).toString('base64') } + ] }); assert.ok(built.rawBase64); const raw = Buffer.from(built.rawBase64, 'base64').toString('utf8'); @@ -62,6 +68,8 @@ test('Android OpenPGP encrypts MIME attachments and decrypts with a recipient ke assert.deepEqual(opened.body, ['hello from Android']); assert.equal(opened.attachments[0].filename, 'note.txt'); assert.equal(Buffer.from(opened.attachments[0].contentBase64, 'base64').toString(), 'private attachment'); + assert.equal(opened.attachedKeys[0].fingerprint, charlie.key.fingerprint); + assert.deepEqual(opened.attachedKeys[0].emails, ['charlie@example.test']); assert.equal(opened.signatures[0].status, 'valid'); await recipient.api.setSettings({ cacheMinutes: 0 }); assert.equal((await recipient.api.getSettings()).cacheMinutes, 0); @@ -75,3 +83,87 @@ test('Android OpenPGP refuses encryption when any recipient key is missing', asy to: 'nobody@example.test', text: 'must not escape as plaintext', pgp: { encrypt: true }, attachments: [] }), error => error.code === 'NO_RECIPIENT_KEY'); }); + +test('Android verifies PGP/MIME signed-only and clear-signed mail', async () => { + const sender = makeEndpoint({ email: 'alice@example.test', displayName: 'Alice', signature: '' }); + const recipient = makeEndpoint({ email: 'bob@example.test', displayName: 'Bob', signature: '' }); + const created = await sender.api.generate({ name: 'Alice', email: 'alice@example.test', passphrase: 'alice test passphrase' }); + await recipient.api.addContact({ armoredKey: await sender.api.exportPublic(created.key.fingerprint) }); + + const signedMime = await sender.api.buildOutgoing({ + to: 'Bob ', cc: '', subject: 'Signed note', text: 'signed MIME body', + pgp: { encrypt: false, sign: true, passphrase: 'alice test passphrase' }, attachments: [] + }); + recipient.setMessage({ rawBase64: signedMime.rawBase64 }); + const mimeResult = await recipient.api.verifyMessage({ folder: 'Inbox', uid: 8 }); + assert.equal(mimeResult.signatures[0].status, 'valid'); + assert.equal(mimeResult.signatures[0].matchesSender, true); + + const protectedPrivateKey = await sender.api.exportPrivate(created.key.fingerprint, 'alice test passphrase'); + const signingKey = await openpgp.decryptKey({ + privateKey: await openpgp.readPrivateKey({ armoredKey: protectedPrivateKey }), + passphrase: 'alice test passphrase' + }); + const cleartext = await openpgp.createCleartextMessage({ text: 'clear-signed body' }); + const clearSigned = await openpgp.sign({ message: cleartext, signingKeys: signingKey }); + const raw = [ + 'From: Alice ', + 'To: Bob ', + 'Subject: Clear-signed note', + 'Content-Type: text/plain; charset=utf-8', + '', + clearSigned, + '' + ].join('\r\n'); + recipient.setMessage({ rawBase64: Buffer.from(raw).toString('base64') }); + const clearResult = await recipient.api.verifyMessage({ folder: 'Inbox', uid: 9 }); + assert.equal(clearResult.signatures[0].status, 'valid'); + assert.equal(clearResult.signatures[0].matchesSender, true); +}); + +test('Android marks a damaged PGP/MIME signature invalid', async () => { + const sender = makeEndpoint({ email: 'alice@example.test', displayName: 'Alice', signature: '' }); + const recipient = makeEndpoint({ email: 'bob@example.test', displayName: 'Bob', signature: '' }); + const created = await sender.api.generate({ name: 'Alice', email: 'alice@example.test', passphrase: 'alice test passphrase' }); + await recipient.api.addContact({ armoredKey: await sender.api.exportPublic(created.key.fingerprint) }); + const signed = await sender.api.buildOutgoing({ + to: 'bob@example.test', subject: 'Signed', text: 'change me', + pgp: { sign: true, passphrase: 'alice test passphrase' }, attachments: [] + }); + const raw = Buffer.from(signed.rawBase64, 'base64').toString('utf8'); + const armor = /-----BEGIN PGP SIGNATURE-----[\s\S]+?-----END PGP SIGNATURE-----/.exec(raw)?.[0]; + const signatureLine = armor?.split(/\r?\n/).find(line => /^[A-Za-z0-9+/]{20,}$/.test(line)); + assert.ok(signatureLine, 'signed MIME output should contain an armored signature'); + const tampered = raw.replace(signatureLine, `${signatureLine[0] === 'A' ? 'B' : 'A'}${signatureLine.slice(1)}`); + recipient.setMessage({ rawBase64: Buffer.from(tampered).toString('base64') }); + const result = await recipient.api.verifyMessage({ folder: 'Inbox', uid: 10 }); + assert.equal(result.signatures[0].status, 'invalid'); +}); + +test('Android rejects tampered, malformed, and oversized encrypted input', async () => { + const sender = makeEndpoint({ email: 'alice@example.test', displayName: 'Alice', signature: '' }); + const recipient = makeEndpoint({ email: 'bob@example.test', displayName: 'Bob', signature: '' }); + const bob = await recipient.api.generate({ name: 'Bob', email: 'bob@example.test', passphrase: 'bob test passphrase' }); + await sender.api.addContact({ armoredKey: await recipient.api.exportPublic(bob.key.fingerprint) }); + const built = await sender.api.buildOutgoing({ + to: 'bob@example.test', subject: 'Encrypted test', text: 'tamper test', + pgp: { encrypt: true }, attachments: [] + }); + const raw = Buffer.from(built.rawBase64, 'base64').toString('utf8'); + const armor = /-----BEGIN PGP MESSAGE-----[\s\S]+?-----END PGP MESSAGE-----/.exec(raw)?.[0]; + assert.ok(armor); + const lines = armor.split(/\r?\n/); + const armorLineIndex = lines.findIndex(line => /^[A-Za-z0-9+/]{20,}$/.test(line)); + assert.notEqual(armorLineIndex, -1); + lines[armorLineIndex] = `${lines[armorLineIndex][0] === 'A' ? 'B' : 'A'}${lines[armorLineIndex].slice(1)}`; + recipient.setMessage({ rawBase64: Buffer.from(raw.replace(armor, lines.join('\r\n'))).toString('base64') }); + assert.equal((await recipient.api.decryptMessage({ uid: 20, passphrase: 'bob test passphrase' })).code, 'CORRUPT'); + + recipient.setMessage({ rawBase64: Buffer.from( + 'From: Alice \r\nContent-Type: multipart/encrypted; boundary="broken"\r\n\r\nnot a valid PGP payload' + ).toString('base64') }); + assert.equal((await recipient.api.decryptMessage({ uid: 21, passphrase: 'bob test passphrase' })).code, 'CORRUPT'); + + recipient.setMessage({ rawBase64: 'A'.repeat(35_000_000) }); + assert.equal((await recipient.api.decryptMessage({ uid: 22, passphrase: 'bob test passphrase' })).code, 'TOO_LARGE'); +}); diff --git a/tests/android-ui-support.test.cjs b/tests/android-ui-support.test.cjs index d43dc41..7b64b7a 100644 --- a/tests/android-ui-support.test.cjs +++ b/tests/android-ui-support.test.cjs @@ -17,6 +17,7 @@ const androidPgpConfirmationGate = fs.readFileSync(path.join(root, 'android', 'a const productivity = fs.readFileSync(path.join(root, 'productivity.js'), 'utf8'); const androidBridge = fs.readFileSync(path.join(root, 'scripts', 'android-bridge.js'), 'utf8'); const androidPgp = fs.readFileSync(path.join(root, 'scripts', 'android-pgp.js'), 'utf8'); +const pgpMailUi = fs.readFileSync(path.join(root, 'pgp-mail-ui.js'), 'utf8'); const packageJson = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')); const packageLock = JSON.parse(fs.readFileSync(path.join(root, 'package-lock.json'), 'utf8')); @@ -98,6 +99,10 @@ test('Android OpenPGP uses the encrypted vault and queues only built MIME data', assert.match(androidPgp, /curve25519Legacy/); assert.match(androidPgp, /multipart\/encrypted/); assert.match(androidPgp, /MAX_MESSAGE_BYTES = 25 \* 1024 \* 1024/); + assert.match(androidPgp, /async function verifyMessage/); + assert.match(androidPgp, /readCleartextMessage/); + assert.match(androidPgp, /readSignature/); + assert.match(pgpMailUi, /message\.signed/); assert.match(androidBridge, /buildOutgoing\(message\)/); assert.match(androidBridge, /rawBase64, envelope: \{ from, to \}, text: '', attachments: \[\]/); assert.match(androidMailService, /validateOpenPgpMime\(message\)/); diff --git a/www/pgp-mail-ui.js b/www/pgp-mail-ui.js index cd16030..1c3a004 100644 --- a/www/pgp-mail-ui.js +++ b/www/pgp-mail-ui.js @@ -70,12 +70,18 @@ function pgpRenderReaderState(message) { if (!header) return; reader.querySelectorAll('.pgp-status, .pgp-banner').forEach(node => node.remove()); let html = ''; - if (message.encrypted && !message.pgpDecrypted) { - html = `
đź”’ This message is encryptedUnlock it with your key passphrase to read it.
`; - } else if (message.encrypted) { - html = pgpSignatureHtml(message.pgpResult?.signatures, true); - } else if (message.pgpSignatures) { - html = pgpSignatureHtml(message.pgpSignatures, false); + if (message.encrypted && !message.pgpDecrypted) { + html = `
đź”’ This message is encryptedUnlock it with your key passphrase to read it.
`; + } else if (message.encrypted) { + html = pgpSignatureHtml(message.pgpResult?.signatures, true); + } else if (message.signed && Array.isArray(message.pgpSignatures)) { + html = pgpSignatureHtml(message.pgpSignatures, false); + } else if (message.signed && message.pgpVerifyFailed) { + html = `
Could not check the OpenPGP signature${escapePgpMailUi(message.pgpVerifyFailed)}
`; + } else if (message.signed) { + html = '
Checking OpenPGP signature…Do not rely on this message until verification completes.
'; + } else if (message.pgpSignatures) { + html = pgpSignatureHtml(message.pgpSignatures, false); } const keys = message.pgpResult?.attachedKeys || []; header.insertAdjacentHTML('afterend', html + keys.map((key, index) => `
Public key attached${escapePgpMailUi(key.emails.join(', ') || 'unknown address')} · ${escapePgpMailUi(pgpFormatFingerprint(key.fingerprint))}
`).join('')); @@ -86,7 +92,7 @@ function pgpRenderReaderState(message) { if (unlock) unlock.onclick = () => pgpUnlockMessage(message, true); } -async function pgpUnlockMessage(message, interactive) { +async function pgpUnlockMessage(message, interactive) { let passphrase = null; for (let attempt = 0; attempt < 3; attempt += 1) { let result; @@ -114,18 +120,36 @@ async function pgpUnlockMessage(message, interactive) { if (text) text.textContent = result.message; else toastPgpMailUi(result.message); return; - } -} - + } +} + +async function pgpVerifyMessage(message) { + try { + const result = await pgpApi().verifyMessage({ folder: message.sourceFolder || 'Inbox', uid: message.uid }); + if (result.failed) message.pgpVerifyFailed = result.message || 'The signature could not be checked.'; + else { + message.pgpSignatures = result.signatures || []; + message.pgpVerifyFailed = null; + } + } catch (error) { + message.pgpVerifyFailed = error.message || 'The signature could not be checked.'; + } + if (pgpMailUi.state.activeMessage === message.id) pgpRenderReaderState(message); +} + pgpMailUi.wrapOpenMessage(baseOpenMessage => function (id) { baseOpenMessage(id); const message = pgpMailUi.state.messages.find(item => item.id === id); if (!message || !pgpApi()) return; pgpRenderReaderState(message); - if (message.encrypted && !message.pgpDecrypted && !message.pgpAutoTried) { - message.pgpAutoTried = true; - void pgpUnlockMessage(message, false); - } + if (message.encrypted && !message.pgpDecrypted && !message.pgpAutoTried) { + message.pgpAutoTried = true; + void pgpUnlockMessage(message, false); + } + if (!message.encrypted && message.signed && typeof pgpApi().verifyMessage === 'function' && !message.pgpVerifyTried) { + message.pgpVerifyTried = true; + void pgpVerifyMessage(message); + } }); // Compose: encrypt/sign options. diff --git a/www/platform-bridge.js b/www/platform-bridge.js index 4294820..2a2b271 100644 --- a/www/platform-bridge.js +++ b/www/platform-bridge.js @@ -5738,6 +5738,7 @@ super(e2, t2); } }; + var ka = /* @__PURE__ */ N.constructAllowedPackets([Ns]); var Ea = class { constructor(e2) { this.packets = e2 || new Gs(); @@ -5753,6 +5754,22 @@ return this.packets.map(((e2) => e2.issuerKeyID)); } }; + async function va({ armoredSignature: e2, binarySignature: t2, config: r2, ...n2 }) { + r2 = { ...F, ...r2 }; + let i2 = e2 || t2; + if (!i2) throw Error("readSignature: must pass options object containing `armoredSignature` or `binarySignature`"); + if (e2 && !N.isString(e2)) throw Error("readSignature: options.armoredSignature must be a string"); + if (t2 && !N.isUint8Array(t2)) throw Error("readSignature: options.binarySignature must be a Uint8Array"); + const s2 = Object.keys(n2); + if (s2.length > 0) throw Error("Unknown option: " + s2.join(", ")); + if (e2) { + const { type: e3, data: t3 } = await $(i2); + if (e3 !== R.armor.signature) throw Error("Armored text not of type signature"); + i2 = t3; + } + const a2 = await Gs.fromBinary(i2, ka, r2); + return new Ea(a2); + } async function Ia(e2, t2) { const r2 = new wa(e2.date, t2); return r2.packets = null, r2.algorithm = R.write(R.publicKey, e2.algorithm), await r2.generate(e2.rsaBits, e2.curve), await r2.computeFingerprintAndKeyID(), r2; @@ -6874,6 +6891,7 @@ const f2 = new no(h2); return f2.fromStream = c2, f2; } + var co = /* @__PURE__ */ N.constructAllowedPackets([Ns]); var uo = class _uo { constructor(e2, t2) { if (this.text = N.removeTrailingSpaces(e2).replace(/\r?\n/g, "\r\n"), t2 && !(t2 instanceof Ea)) throw Error("Invalid signature input"); @@ -6903,6 +6921,38 @@ return ee(R.armor.signed, r2, void 0, void 0, void 0, t2, e2); } }; + async function ho({ cleartextMessage: e2, config: t2, ...r2 }) { + if (t2 = { ...F, ...t2 }, !e2) throw Error("readCleartextMessage: must pass options object containing `cleartextMessage`"); + if (!N.isString(e2)) throw Error("readCleartextMessage: options.cleartextMessage must be a string"); + const n2 = Object.keys(r2); + if (n2.length > 0) throw Error("Unknown option: " + n2.join(", ")); + const i2 = await $(e2); + if (i2.type !== R.armor.signed) throw Error("No cleartext signed message."); + const s2 = await Gs.fromBinary(i2.data, co, t2); + !(function(e3, t3) { + const r3 = function(e4) { + const r4 = (e5) => (t4) => e5.hashAlgorithm === t4; + for (let n4 = 0; n4 < t3.length; n4++) if (t3[n4].constructor.tag === R.packet.signature && !e4.some(r4(t3[n4]))) return false; + return true; + }, n3 = []; + if (e3.forEach(((e4) => { + const t4 = e4.match(/^Hash: (.+)$/); + if (!t4) throw Error('Only "Hash" header allowed in cleartext signed message'); + { + const e5 = t4[1].replace(/\s/g, "").split(",").map(((e6) => { + try { + return R.write(R.hash, e6.toLowerCase()); + } catch { + throw Error("Unknown hash algorithm in armor header: " + e6.toLowerCase()); + } + })); + n3.push(...e5); + } + })), n3.length && !r3(n3)) throw Error("Hash algorithm mismatch in armor header and signature"); + })(i2.headers, s2); + const a2 = new Ea(s2); + return new uo(i2.text, a2); + } async function lo({ userIDs: e2 = [], passphrase: t2, type: r2, curve: n2, rsaBits: i2 = 4096, keyExpirationTime: s2 = 0, date: a2 = /* @__PURE__ */ new Date(), subkeys: o2 = [{}], format: c2 = "armored", signatureNotations: u2 = [], config: h2, ...f2 }) { Do(h2 = { ...F, ...h2 }), r2 || n2 ? (r2 = r2 || "ecc", n2 = n2 || "curve25519Legacy") : (r2 = h2.v6Keys ? "curve25519" : "ecc", n2 = "curve25519Legacy"), e2 = Uo(e2), u2 = Uo(u2); const l2 = Object.keys(f2); @@ -7011,6 +7061,23 @@ throw N.wrapError("Error signing message", e3); } } + async function ko({ message: e2, verificationKeys: t2, expectSigned: r2 = false, format: n2 = "utf8", signature: i2 = null, date: s2 = /* @__PURE__ */ new Date(), config: a2, ...o2 }) { + if (Do(a2 = { ...F, ...a2 }), So(e2), t2 = Uo(t2), o2.publicKeys) throw Error("The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead"); + const c2 = Object.keys(o2); + if (c2.length > 0) throw Error("Unknown option: " + c2.join(", ")); + if (e2 instanceof uo && "binary" === n2) throw Error("Can't return cleartext message data as binary"); + if (e2 instanceof uo && i2) throw Error("Can't verify detached cleartext signature"); + try { + const o3 = {}; + if (o3.signatures = i2 ? await e2.verifyDetached(i2, t2, s2, a2) : await e2.verify(t2, s2, a2), o3.data = "binary" === n2 ? e2.getLiteralData() : e2.getText(), e2.fromStream && !i2 && xo(o3, .../* @__PURE__ */ new Set([e2, e2.unwrapCompressed()])), r2) { + if (0 === o3.signatures.length) throw Error("Message is not signed"); + o3.data = A([o3.data, P((async () => (await N.anyPromise(o3.signatures.map(((e3) => e3.verified))), "binary" === n2 ? new Uint8Array() : "")))]); + } + return o3.data = await Po(o3.data), o3; + } catch (e3) { + throw N.wrapError("Error verifying signed message", e3); + } + } function Bo(e2) { if (!(e2 instanceof no)) throw Error("Parameter [message] needs to be of type Message"); } @@ -9896,6 +9963,25 @@ visit(bytes); return result; } + async function attachedPublicKeys(attachments) { + const found = []; + for (const file of attachments || []) { + const type = String(file.contentType || "").toLowerCase(); + if (type !== "application/pgp-keys" && !/\.asc$/i.test(file.filename || "")) continue; + if (!file.contentBase64 || Number(file.size) > MAX_KEY_LENGTH || file.contentBase64.length > MAX_KEY_LENGTH * 2) continue; + try { + const binary = atob(file.contentBase64); + const armoredKey = decoder.decode(Uint8Array.from(binary, (char) => char.charCodeAt(0))).trim(); + if (!/-----BEGIN PGP PUBLIC KEY BLOCK-----/.test(armoredKey) || /-----BEGIN PGP PRIVATE KEY BLOCK-----/.test(armoredKey) || armoredKey.length > MAX_KEY_LENGTH) continue; + const key = await Ja({ armoredKey }); + await key.getPrimaryUser(); + found.push({ armoredKey: key.armor(), fingerprint: key.getFingerprint().toUpperCase(), emails: emailsOf(key) }); + if (found.length === 5) break; + } catch { + } + } + return found; + } function randomBoundary() { const bytes = crypto.getRandomValues(new Uint8Array(18)); return `=_ep-${Array.from(bytes, (value) => value.toString(16).padStart(2, "0")).join("")}`; @@ -9961,6 +10047,72 @@ ${parts.join("")}`; for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCharCode(...bytes.subarray(index, index + 32768)); return btoa(binary); } + function bytesToLatin1(bytes) { + let text = ""; + for (let index = 0; index < bytes.length; index += 32768) { + text += String.fromCharCode(...bytes.subarray(index, index + 32768)); + } + return text; + } + function splitSignedMime(source, boundary) { + if (!boundary || boundary.length > 200) return null; + const text = bytesToLatin1(source); + const escaped = boundary.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const delimiter = new RegExp(`(?:^|\\r?\\n)--${escaped}(--)?[ \\t]*(?=\\r?\\n|$)`, "g"); + const marks = [...text.matchAll(delimiter)]; + if (marks.length < 3) return null; + const contentAfter = (mark) => { + const lineEnd = text.indexOf("\n", mark.index + mark[0].length); + return lineEnd < 0 ? text.length : lineEnd + 1; + }; + const signed = text.slice(contentAfter(marks[0]), marks[1].index).replace(/\r?\n/g, "\r\n"); + const signaturePart = text.slice(contentAfter(marks[1]), marks[2].index); + const signature = /-----BEGIN PGP SIGNATURE-----[\s\S]+?-----END PGP SIGNATURE-----/.exec(signaturePart)?.[0]; + if (!signature) return null; + return { signed: Uint8Array.from(signed, (char) => char.charCodeAt(0) & 255), signature }; + } + function senderFrom(headers) { + const value = String(headers.from || ""); + return (/<([^<>]+)>/.exec(value)?.[1] || /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i.exec(value)?.[0] || "").toLowerCase(); + } + function invalidSignature() { + return { + status: "invalid", + keyId: "", + fingerprint: null, + trust: null, + email: null, + matchesSender: false, + keyChanged: false + }; + } + async function signatureStatuses(signatures, verification, sender) { + const results = []; + for (const signature of signatures || []) { + const keyId = signature.keyID.toHex().toUpperCase(); + const known = verification.find((candidate) => candidate.key.getKeys().some((key) => key.getKeyID().toHex().toUpperCase() === keyId)); + let status = "valid"; + try { + await signature.verified; + } catch { + status = known ? "invalid" : "unknown-key"; + } + const keyEmails = known?.entry.emails || (known?.entry.email ? [known.entry.email.toLowerCase()] : []); + const matchesSender = Boolean(sender && keyEmails.includes(sender)); + const changed = Boolean(sender && verification.some((candidate) => !candidate.entry.own && candidate.entry.emails?.includes(sender) && candidate.entry.fingerprint !== known?.entry.fingerprint)); + results.push({ + status, + keyId, + fingerprint: known?.entry.fingerprint || null, + trust: known?.entry.trust || null, + email: keyEmails[0] || null, + matchesSender, + keyChanged: changed, + ...status === "valid" && known && sender && !matchesSender ? { mismatch: true } : {} + }); + } + return results; + } function createAndroidPgp({ EpMail: EpMail2, getAccount }) { let storePromise; const passphrases = /* @__PURE__ */ new Map(); @@ -10229,31 +10381,8 @@ ${body}`); return { failed: true, code: "CORRUPT", message: "The message could not be decrypted. It may be damaged or altered." }; } const content = parseInnerMime(decrypted.data); - const signatures = []; - for (const item of decrypted.signatures || []) { - const known = verify.find((candidate) => candidate.key.getKeys().some((key) => key.getKeyID().toHex().toUpperCase() === item.keyID.toHex().toUpperCase())); - let status = "valid"; - try { - await item.verified; - } catch { - status = known ? "invalid" : "unknown-key"; - } - const from = /^From:\s*(.*)$/im.exec(text)?.[1] || ""; - const sender = (/<([^<>]+)>/.exec(from)?.[1] || /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i.exec(from)?.[0] || "").toLowerCase(); - const keyEmails = known?.entry.emails || (known?.entry.email ? [known.entry.email.toLowerCase()] : []); - const changed = Boolean(sender && data.contacts.some((entry) => entry.emails.includes(sender) && entry.fingerprint !== known?.entry.fingerprint)); - const matchesSender = Boolean(sender && keyEmails.includes(sender)); - signatures.push({ - status, - keyId: item.keyID.toHex().toUpperCase(), - fingerprint: known?.entry.fingerprint || null, - trust: known?.entry.trust || null, - email: keyEmails[0] || null, - matchesSender, - keyChanged: changed, - ...status === "valid" && known && sender && !matchesSender ? { mismatch: true } : {} - }); - } + const signatures = await signatureStatuses(decrypted.signatures, verify, senderFrom(splitEntity(raw).headers)); + const attachedKeys = await attachedPublicKeys(content.attachments); return { ok: true, body: content.body ? content.body.split(/\n\s*\n/).filter(Boolean) : [], @@ -10263,12 +10392,52 @@ ${body}`); attachment: content.attachments[0]?.filename || null, size: content.attachments[0]?.size || "", signatures, - attachedKeys: [] + attachedKeys }; } catch (error) { return { failed: true, code: error.code || "ERROR", message: error.message || "Could not decrypt this message." }; } } + async function verifyMessage({ folder = "Inbox", uid }) { + try { + const source = await EpMail2.pgpGetMessageSource({ folder, uid }); + const raw = Uint8Array.from(atob(source.rawBase64), (char) => char.charCodeAt(0)); + if (raw.byteLength > MAX_MESSAGE_BYTES) { + return { failed: true, code: "TOO_LARGE", message: "This signed message is too large to verify." }; + } + const entity = splitEntity(raw); + const contentType = entity.headers["content-type"] || ""; + const sender = senderFrom(entity.headers); + const data = await store(); + const verification = await verificationKeys(data); + if (/^multipart\/signed/i.test(contentType) && parameter(contentType, "protocol").toLowerCase() === "application/pgp-signature") { + const parts = splitSignedMime(raw, parameter(contentType, "boundary")); + if (!parts) return { signatures: [invalidSignature()] }; + try { + const result = await ko({ + message: await oo({ binary: parts.signed }), + signature: await va({ armoredSignature: parts.signature }), + verificationKeys: verification.map((item) => item.key) + }); + return { signatures: await signatureStatuses(result.signatures, verification, sender) }; + } catch { + return { signatures: [invalidSignature()] }; + } + } + const body = decoder.decode(decodePart(entity.body, entity.headers["content-transfer-encoding"])); + const armored = /-----BEGIN PGP SIGNED MESSAGE-----[\s\S]+?-----END PGP SIGNATURE-----/.exec(body)?.[0]; + if (!armored) return { signatures: [] }; + try { + const message = await ho({ cleartextMessage: armored }); + const result = await ko({ message, verificationKeys: verification.map((item) => item.key) }); + return { signatures: await signatureStatuses(result.signatures, verification, sender) }; + } catch { + return { signatures: [invalidSignature()] }; + } + } catch (error) { + return { failed: true, code: error.code || "VERIFY_ERROR", message: error.message || "Could not verify this message." }; + } + } const api = { platform: "android", async list() { @@ -10413,6 +10582,7 @@ Only continue if you checked this fingerprint with the owner.`)) throw new Error }; }, decryptMessage, + verifyMessage, async getSettings() { const data = await store(); return { cacheMinutes }; diff --git a/www/service-worker.js b/www/service-worker.js index ad39cf7..6c18bad 100644 --- a/www/service-worker.js +++ b/www/service-worker.js @@ -1,4 +1,4 @@ -const CACHE='ep-mail-v18'; +const CACHE='ep-mail-v19'; const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge-loader.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg']; self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES)).then(()=>self.skipWaiting()))); self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k)))).then(()=>self.clients.claim())));