Android security implementation Phase 2 finalization part 1
This commit is contained in:
@@ -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 <gina@example.test>', '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 <gina@example.test>',
|
||||
cc: '',
|
||||
subject: 'Android to GnuPG',
|
||||
text: 'Encrypted and signed from the Android OpenPGP module',
|
||||
messageId: '<android-to-gnupg@example.test>',
|
||||
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 <gina@example.test>', '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 <gina@example.test>',
|
||||
'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 <gina@example.test>\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 });
|
||||
}
|
||||
});
|
||||
@@ -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 <bob@example.test>', cc: '', subject: 'Secret note', text: 'hello from Android',
|
||||
messageId: '<test-message@example.test>', 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 <bob@example.test>', 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 <alice@example.test>',
|
||||
'To: Bob <bob@example.test>',
|
||||
'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 <alice@example.test>\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');
|
||||
});
|
||||
|
||||
@@ -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\)/);
|
||||
|
||||
Reference in New Issue
Block a user