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 });
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user