Android security implementation Phase 2 finalization part 1
This commit is contained in:
+196
-26
@@ -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 };
|
||||
|
||||
Reference in New Issue
Block a user