From edf7cec93e07d0367aa0d71844bb50b19be5bc9d Mon Sep 17 00:00:00 2001 From: Tero Date: Wed, 7 Oct 2026 16:15:21 +0300 Subject: [PATCH] Add GnuPG interoperability tests; generate GnuPG-compatible Curve25519 keys, v0.3.1 --- ENCRYPTION_PLAN.md | 7 ++- TODO.md | 3 +- desktop/pgp-keystore.cjs | 3 +- package-lock.json | 4 +- package.json | 2 +- tests/pgp-gnupg-interop.test.cjs | 104 +++++++++++++++++++++++++++++++ 6 files changed, 115 insertions(+), 8 deletions(-) create mode 100644 tests/pgp-gnupg-interop.test.cjs diff --git a/ENCRYPTION_PLAN.md b/ENCRYPTION_PLAN.md index 369effa..f83502c 100644 --- a/ENCRYPTION_PLAN.md +++ b/ENCRYPTION_PLAN.md @@ -1,6 +1,6 @@ # Encryption plan: OpenPGP mail encryption for ep-mail -Status: **Phases 1–3 and the desktop parts of 4–6 are implemented.** Android support, manual interop checks with Thunderbird/GnuPG and an independent security review are still open; see [TODO.md](./TODO.md). +Status: **Phases 1–3 and the desktop parts of 4–6 are implemented.** Android support, a manual Thunderbird check and an independent security review are still open; see [TODO.md](./TODO.md). ## 1. Format: OpenPGP with PGP/MIME (RFC 3156) @@ -13,7 +13,7 @@ Decision: OpenPGP only for v1; S/MIME may follow later. - Library: [OpenPGP.js](https://github.com/openpgpjs/openpgpjs) (`openpgp`), pure JS, usable in Electron and the Android WebView. - Messages: `multipart/encrypted` (`application/pgp-encrypted` + `application/octet-stream`), signed and encrypted together. Attachments go inside the encrypted payload. -- Keys: Curve25519 with modern defaults. +- Keys: Curve25519 (legacy EdDSA/ECDH, OpenPGP v4). OpenPGP.js' default native Ed25519 keys are rejected by GnuPG 2.5, so the widely supported format is used. - Also detect and decrypt legacy inline PGP (`-----BEGIN PGP MESSAGE-----`). - Out of scope for v1: Autocrypt headers, key servers, Web Key Directory. @@ -55,7 +55,7 @@ Decision: OpenPGP only for v1; S/MIME may follow later. | 2 | Receive: detect PGP/MIME and inline PGP, decrypt on open, verify signatures, status UI, missing-key and wrong-passphrase handling | Done (desktop) | | 3 | Send: public-key keyring and contact import, encrypt and sign on compose, encrypted Sent copy, downgrade warnings | Done (desktop) | | 4 | Trust and polish: fingerprint verification, key-change warnings, passphrase cache timeout, Android Keystore and biometric unlock | Desktop done; Android open | -| 5 | Interop testing with Thunderbird and GnuPG, large attachments, multiple recipients, corrupted payloads | Automated tests done; manual interop open | +| 5 | Interop testing with Thunderbird and GnuPG, large attachments, multiple recipients, corrupted payloads | Automated and GnuPG interop tests done; Thunderbird check open | | 6 | Docs, security review, release | Docs and release done; independent review open | ## 6. Phase 1 implementation notes @@ -73,6 +73,7 @@ Decision: OpenPGP only for v1; S/MIME may follow later. - Encrypted messages appear in the list as "Encrypted message"; they are decrypted on demand (`pgp:decrypt-message`) and the plaintext is never cached on disk. Attachments are read from the decrypted payload. - Compose shows Encrypt and Sign options. Encrypt turns on by default when every recipient has a key; if a key is missing the app asks before sending unencrypted. Encryption happens before the message is sent or queued offline, so passphrases and plaintext never enter the outbox. The Sent copy is also encrypted to the sender's own key. - A signature from a key that differs from the one on file for the sender is flagged as a changed key. +- Interop: [tests/pgp-gnupg-interop.test.cjs](./tests/pgp-gnupg-interop.test.cjs) runs against a real GnuPG (skipped when it is not installed). - Tests: [tests/pgp-mail.test.cjs](./tests/pgp-mail.test.cjs) (round trips, several recipients, tampering, key changes, large attachments, inline PGP). - Limits: subjects and headers are not encrypted; drafts are stored unencrypted; opening encrypted attachments requires the passphrase to be remembered (see Settings → Encryption keys). ## 8. Risks diff --git a/TODO.md b/TODO.md index 1ad122c..b991252 100644 --- a/TODO.md +++ b/TODO.md @@ -32,8 +32,9 @@ - [x] Phase 4 (desktop): trust levels and fingerprint verification, key-change warnings, passphrase cache timeout. - [ ] Phase 4 (Android): Android Keystore key storage, biometric unlock, and the reading/sending bridge (encryption is desktop-only until then). - [x] Phase 5 (automated): large attachments, multiple recipients, corrupted/tampered payloads, inline PGP and PGP/MIME tests. - - [ ] Phase 5 (manual): interoperability check with Thunderbird and GnuPG. + - [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. + - [ ] Manual interoperability check with Thunderbird. - [ ] Independent security review of the encryption code before relying on it. ## Appearance and settings diff --git a/desktop/pgp-keystore.cjs b/desktop/pgp-keystore.cjs index 6f410f6..a0131ce 100644 --- a/desktop/pgp-keystore.cjs +++ b/desktop/pgp-keystore.cjs @@ -215,7 +215,8 @@ function createKeyStore(storage) { if (!/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(cleanEmail)) throw new Error('Enter a valid email address for the key.'); requirePassphrase(passphrase); const { privateKey, publicKey, revocationCertificate } = await openpgp.generateKey({ - type: 'curve25519', + type: 'ecc', + curve: 'curve25519Legacy', userIDs: [{ name: cleanName || undefined, email: cleanEmail }], passphrase, format: 'armored' diff --git a/package-lock.json b/package-lock.json index dac1e63..681b252 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "ep-mail", - "version": "0.3.0", + "version": "0.3.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ep-mail", - "version": "0.3.0", + "version": "0.3.1", "dependencies": { "@capacitor/android": "^8.5.2", "@capacitor/core": "^8.5.2", diff --git a/package.json b/package.json index e1c78a1..c95ccfb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ep-mail", - "version": "0.3.0", + "version": "0.3.1", "private": true, "description": "Eternity Project mail client", "author": "Eternity Project", diff --git a/tests/pgp-gnupg-interop.test.cjs b/tests/pgp-gnupg-interop.test.cjs new file mode 100644 index 0000000..3297eb9 --- /dev/null +++ b/tests/pgp-gnupg-interop.test.cjs @@ -0,0 +1,104 @@ +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 { simpleParser } = require('mailparser'); +const { createKeyStore } = require('../desktop/pgp-keystore.cjs'); +const { createPgpMail, createPassphraseCache } = require('../desktop/pgp-mail.cjs'); + +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 PASS = 'interop passphrase'; + +function gpgIn(home) { + return (args, input) => { + const result = spawnSync(gpgPath, ['--homedir', home, '--batch', '--yes', '--pinentry-mode', 'loopback', '--passphrase', PASS, '--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() }; + }; +} + +async function setup() { + const home = fs.mkdtempSync(path.join(os.tmpdir(), 'ep-gnupg-')); + const gpg = gpgIn(home); + gpg(['--quick-generate-key', 'Gina Gnu ', 'ed25519', 'cert', 'never']); + const fingerprint = /^fpr:::::::::([0-9A-F]+):/m.exec(gpg(['--list-keys', '--with-colons', 'gina@example.com']).out.toString())[1]; + gpg(['--quick-add-key', fingerprint, 'cv25519', 'encr', 'never']); + gpg(['--quick-add-key', fingerprint, 'ed25519', 'sign', 'never']); + let data = null; + const keyStore = createKeyStore({ async load() { return data && JSON.parse(JSON.stringify(data)); }, async save(value) { data = JSON.parse(JSON.stringify(value)); } }); + const mail = createPgpMail({ keyStore, cache: createPassphraseCache(async () => 10) }); + const { key } = await keyStore.generate({ name: 'Eppu Mail', email: 'eppu@example.com', passphrase: PASS }); + gpg(['--import'], Buffer.from(await keyStore.exportPublic(key.fingerprint))); + await keyStore.addContact({ armoredKey: gpg(['--armor', '--export', 'gina@example.com']).out.toString() }); + return { home, gpg, keyStore, mail }; +} + +const options = extra => ({ + from: { name: 'Eppu Mail', address: 'eppu@example.com' }, to: 'Gina Gnu ', + subject: 'Interop', text: 'Hello from ep-mail ✓', messageId: '', passphrase: PASS, ...extra +}); + +test('GnuPG decrypts and verifies mail encrypted and signed by ep-mail', { skip }, async () => { + const { home, gpg, mail } = await setup(); + try { + const { raw } = await mail.build(options({ encrypt: true, sign: true })); + const parsed = await simpleParser(raw); + const armored = /-----BEGIN PGP MESSAGE-----[\s\S]+?-----END PGP MESSAGE-----/.exec(parsed.attachments[1]?.content?.toString() || parsed.attachments[0].content.toString())[0]; + const { out, err } = gpg(['--decrypt'], Buffer.from(armored)); + assert.match((await simpleParser(out)).text, /Hello from ep-mail ✓/); + assert.match(err, /Good signature from "Eppu Mail "/); + } finally { fs.rmSync(home, { recursive: true, force: true }); } +}); + +test('GnuPG verifies PGP/MIME signed-only mail from ep-mail', { skip }, async () => { + const { home, gpg, mail } = await setup(); + try { + const { raw } = await mail.build(options({ sign: true })); + const text = raw.toString('latin1'); + const { splitSigned } = require('../desktop/pgp-mail.cjs'); + const boundary = /boundary="([^"]+)"/.exec(text)[1]; + const parts = splitSigned(raw, boundary); + const signaturePath = path.join(home, 'sig.asc'); + const dataPath = path.join(home, 'data.bin'); + fs.writeFileSync(signaturePath, parts.signature); + fs.writeFileSync(dataPath, parts.signed); + const { err } = gpg(['--verify', signaturePath, dataPath]); + assert.match(err, /Good signature from "Eppu Mail/); + } finally { fs.rmSync(home, { recursive: true, force: true }); } +}); + +test('ep-mail decrypts GnuPG-encrypted PGP/MIME mail and verifies its signature', { skip }, async () => { + const { home, gpg, mail, keyStore } = await setup(); + try { + const inner = Buffer.from('Content-Type: text/plain; charset=utf-8\r\n\r\nHello from GnuPG ✓\r\n'); + const armored = gpg(['--armor', '--encrypt', '--sign', '--local-user', 'gina@example.com', '--recipient', 'eppu@example.com'], inner).out.toString(); + const source = Buffer.from(`From: Gina Gnu \r\nTo: eppu@example.com\r\nSubject: from gpg\r\nMIME-Version: 1.0\r\nContent-Type: multipart/encrypted; protocol="application/pgp-encrypted"; boundary="gb"\r\n\r\n--gb\r\nContent-Type: application/pgp-encrypted\r\n\r\nVersion: 1\r\n\r\n--gb\r\nContent-Type: application/octet-stream; name="encrypted.asc"\r\n\r\n${armored}\r\n--gb--\r\n`); + const result = await mail.decrypt(await simpleParser(source), { passphrase: PASS }); + assert.match(result.parsed.text, /Hello from GnuPG ✓/); + assert.equal(result.signatures[0].status, 'valid'); + assert.equal(result.signatures[0].matchesSender, true); + assert.ok(await keyStore.listContacts()); + } finally { fs.rmSync(home, { recursive: true, force: true }); } +}); + +test('ep-mail decrypts GnuPG inline PGP and verifies GnuPG clear-signed and PGP/MIME signed mail', { skip }, async () => { + const { home, gpg, mail } = await setup(); + try { + const inline = gpg(['--armor', '--encrypt', '--recipient', 'eppu@example.com'], Buffer.from('inline from gpg')).out.toString(); + const inlineSource = Buffer.from(`From: gina@example.com\r\nSubject: i\r\nContent-Type: text/plain\r\n\r\n${inline}\r\n`); + assert.match((await mail.decrypt(await simpleParser(inlineSource), { passphrase: PASS })).parsed.text, /inline from gpg/); + + const clear = gpg(['--clearsign', '--local-user', 'gina@example.com'], Buffer.from('clear signed text\n')).out.toString().replace(/\r?\n/g, '\r\n'); + const clearSource = Buffer.from(`From: gina@example.com\r\nSubject: c\r\nContent-Type: text/plain\r\n\r\n${clear}\r\n`); + assert.equal((await mail.verifySigned(await simpleParser(clearSource), clearSource))[0].status, 'valid'); + + const signedPart = 'Content-Type: text/plain; charset=utf-8\r\n\r\nsigned by gpg'; + const detached = gpg(['--armor', '--detach-sign', '--local-user', 'gina@example.com'], Buffer.from(signedPart)).out.toString().replace(/\r?\n/g, '\r\n').trim(); + const mimeSource = Buffer.from(`From: gina@example.com\r\nSubject: m\r\nMIME-Version: 1.0\r\nContent-Type: multipart/signed; protocol="application/pgp-signature"; micalg=pgp-sha512; boundary="sb"\r\n\r\n--sb\r\n${signedPart}\r\n--sb\r\nContent-Type: application/pgp-signature\r\n\r\n${detached}\r\n--sb--\r\n`); + assert.equal((await mail.verifySigned(await simpleParser(mimeSource), mimeSource))[0].status, 'valid'); + } finally { fs.rmSync(home, { recursive: true, force: true }); } +});