#89 Decrypt and verify with OpenPGP.js and GnuPG

This commit is contained in:
the-djmaze 2022-02-11 11:01:07 +01:00
parent 85f9209176
commit e0e490c64f
8 changed files with 354 additions and 315 deletions

View file

@ -21,7 +21,7 @@ export function ParseMime(text)
} }
get bodyRaw() { get bodyRaw() {
return text.slice(this.body_start, this.body_end); return text.slice(this.bodyStart, this.bodyEnd);
} }
get body() { get body() {
@ -99,9 +99,10 @@ export function ParseMime(text)
part.headers = headers; part.headers = headers;
// get body // get body
part.body_start = start_pos + head.length; part.bodyStart = start_pos + head.length;
part.body_end = start_pos + mimePart.length; part.bodyEnd = start_pos + mimePart.length;
// get child parts
let boundary = headers['content-type'].params.boundary; let boundary = headers['content-type'].params.boundary;
if (boundary) { if (boundary) {
part.boundary = boundary; part.boundary = boundary;
@ -109,16 +110,16 @@ export function ParseMime(text)
let regex = new RegExp('(?:^|\r?\n)--' + boundary + '(?:--)?(?:\r?\n|$)', 'g'), let regex = new RegExp('(?:^|\r?\n)--' + boundary + '(?:--)?(?:\r?\n|$)', 'g'),
body = mimePart.slice(head.length), body = mimePart.slice(head.length),
bodies = body.split(regex), bodies = body.split(regex),
pos = part.body_start; pos = part.bodyStart;
[...body.matchAll(regex)].forEach(([boundary], index) => { [...body.matchAll(regex)].forEach(([boundary], index) => {
if (!index) { if (!index) {
part.body_text = bodies[0]; // Mostly something like: "This is a multi-part message in MIME format."
part.bodyText = bodies[0];
} }
pos += bodies[index].length; // Not the end?
pos += boundary.length; if ('--' != boundary.trim().slice(-2)) {
pos += bodies[index].length + boundary.length;
part.parts.push(ParsePart(bodies[1+index], pos, ((id ? id + '.' : '') + (1+index)))); part.parts.push(ParsePart(bodies[1+index], pos, ((id ? id + '.' : '') + (1+index))));
if ('--' == boundary.trim().slice(-2)) {
// end
} }
}); });
} }

76
dev/Mime/Utils.js Normal file
View file

@ -0,0 +1,76 @@
import { ParseMime } from 'Mime/Parser';
import { AttachmentModel } from 'Model/Attachment';
import { FileInfo } from 'Common/File';
import { BEGIN_PGP_MESSAGE } from 'Stores/User/Pgp';
/**
* @param string data
* @param MessageModel message
*/
export function MimeToMessage(data, message)
{
let signed;
const struct = ParseMime(data);
if (struct.headers) {
let html = struct.getByContentType('text/html');
html = html ? html.body : '';
struct.forEach(part => {
let cd = part.header('content-disposition'),
cid = part.header('content-id'),
type = part.header('content-type');
if (cid || cd) {
// if (cd && 'attachment' === cd.value) {
let attachment = new AttachmentModel;
attachment.mimeType = type.value;
attachment.fileName = type.name || (cd && cd.params.filename) || '';
attachment.fileNameExt = attachment.fileName.replace(/^.+(\.[a-z]+)$/, '$1');
attachment.fileType = FileInfo.getType('', type.value);
attachment.url = part.dataUrl;
attachment.friendlySize = FileInfo.friendlySize(part.body.length);
/*
attachment.isThumbnail = false;
attachment.contentLocation = '';
attachment.download = '';
attachment.folder = '';
attachment.uid = '';
attachment.mimeIndex = part.id;
attachment.framed = false;
*/
attachment.cid = cid ? cid.value : '';
if (cid && html) {
let cid = 'cid:' + attachment.contentId(),
found = html.includes(cid);
attachment.isInline(found);
attachment.isLinked(found);
found && (html = html
.replace('src="' + cid + '"', 'src="' + attachment.url + '"')
.replace("src='" + cid + "'", "src='" + attachment.url + "'")
);
} else {
message.attachments.push(attachment);
}
} else if ('multipart/signed' === type.value && 'application/pgp-signature' === type.params.protocol) {
signed = {
MicAlg: type.micalg,
BodyPart: part.parts[0],
SigPart: part.parts[1]
};
}
});
const text = struct.getByContentType('text/plain');
message.plain(text ? text.body : '');
message.html(html);
} else {
message.plain(data);
}
if (!signed && message.plain().includes(BEGIN_PGP_MESSAGE)) {
signed = true;
}
message.pgpSigned(signed);
// TODO: Verify instantly?
}

View file

@ -459,8 +459,7 @@ export class MessageModel extends AbstractModel {
body.classList.toggle('plain', 1); body.classList.toggle('plain', 1);
body.innerHTML = plainToHtml( body.innerHTML = plainToHtml(
this.plain() this.plain()
.replace(/-----BEGIN PGP SIGNATURE-----[\s\S]*/, '') .replace(/-----BEGIN PGP (SIGNED MESSAGE-----(\r?\n[a-z][^\r\n]+)+|SIGNATURE-----[\s\S]*)/, '')
.replace(/-----BEGIN PGP SIGNED MESSAGE-----(\r?\n[a-z][^\r\n]+)+/i, '')
.trim() .trim()
) )
.replace(url, '$1<a href="$2" target="_blank">$2</a>') .replace(url, '$1<a href="$2" target="_blank">$2</a>')

View file

@ -197,10 +197,15 @@ export const GnuPGUserStore = new class {
async verify(message) { async verify(message) {
let data = message.pgpSigned(); // { BodyPartId: "1", SigPartId: "2", MicAlg: "pgp-sha256" } let data = message.pgpSigned(); // { BodyPartId: "1", SigPartId: "2", MicAlg: "pgp-sha256" }
if (data) { if (data) {
data = { ...data }; // clone
// const sender = message.from[0].email; // const sender = message.from[0].email;
// let mode = await this.hasPublicKeyForEmails([sender]); // let mode = await this.hasPublicKeyForEmails([sender]);
data.Folder = message.folder; data.Folder = message.folder;
data.Uid = message.uid; data.Uid = message.uid;
if (data.BodyPart) {
data.BodyPart = data.BodyPart.raw;
data.SigPart = data.SigPart.body;
}
let response = await Remote.post('MessagePgpVerify', null, data); let response = await Remote.post('MessagePgpVerify', null, data);
if (response && response.Result) { if (response && response.Result) {
return { return {

View file

@ -214,9 +214,14 @@ export const OpenPGPUserStore = new class {
data.Folder = message.folder; data.Folder = message.folder;
data.Uid = message.uid; data.Uid = message.uid;
data.GnuPG = 0; data.GnuPG = 0;
let response = data.SigPartId let response;
? await Remote.post('MessagePgpVerify', null, data) if (data.SigPartId) {
: { Result: { text: message.plain(), signature: null } }; response = await Remote.post('MessagePgpVerify', null, data);
} else if (data.BodyPart) {
response = { Result: { text: data.BodyPart.raw, signature: data.SigPart.body } };
} else {
response = { Result: { text: message.plain(), signature: null } };
}
if (response) { if (response) {
const signature = response.Result.signature const signature = response.Result.signature
? await openpgp.readSignature({ armoredSignature: response.Result.signature }) ? await openpgp.readSignature({ armoredSignature: response.Result.signature })

View file

@ -10,7 +10,12 @@ import { staticLink } from 'Common/Links';
import { GnuPGUserStore } from 'Stores/User/GnuPG'; import { GnuPGUserStore } from 'Stores/User/GnuPG';
import { OpenPGPUserStore } from 'Stores/User/OpenPGP'; import { OpenPGPUserStore } from 'Stores/User/OpenPGP';
export const PgpUserStore = new class { export const
BEGIN_PGP_MESSAGE = '-----BEGIN PGP MESSAGE-----',
// BEGIN_PGP_SIGNATURE = '-----BEGIN PGP SIGNATURE-----',
// BEGIN_PGP_SIGNED = '-----BEGIN PGP SIGNED MESSAGE-----',
PgpUserStore = new class {
constructor() { constructor() {
// https://mailvelope.github.io/mailvelope/Keyring.html // https://mailvelope.github.io/mailvelope/Keyring.html
this.mailvelopeKeyring = null; this.mailvelopeKeyring = null;
@ -72,7 +77,7 @@ export const PgpUserStore = new class {
* @returns {boolean} * @returns {boolean}
*/ */
isEncrypted(text) { isEncrypted(text) {
return 0 === text.trim().indexOf('-----BEGIN PGP MESSAGE-----'); return 0 === text.trim().indexOf(BEGIN_PGP_MESSAGE);
} }
async mailvelopeHasPublicKeyForEmails(recipients) { async mailvelopeHasPublicKeyForEmails(recipients) {

View file

@ -33,7 +33,6 @@ import { SMAudio } from 'Common/Audio';
import { i18n } from 'Common/Translator'; import { i18n } from 'Common/Translator';
import { attachmentDownload } from 'Common/Links'; import { attachmentDownload } from 'Common/Links';
import { FileInfo } from 'Common/File';
import { MessageFlagsCache } from 'Common/Cache'; import { MessageFlagsCache } from 'Common/Cache';
@ -53,73 +52,12 @@ import { AbstractViewRight } from 'Knoin/AbstractViews';
import { PgpUserStore } from 'Stores/User/Pgp'; import { PgpUserStore } from 'Stores/User/Pgp';
import { ParseMime } from 'Mime/Parser'; import { MimeToMessage } from 'Mime/Utils';
import { AttachmentModel } from 'Model/Attachment';
const const
oMessageScrollerDom = () => elementById('messageItem') || {}, oMessageScrollerDom = () => elementById('messageItem') || {},
currentMessage = () => MessageUserStore.message(), currentMessage = () => MessageUserStore.message();
mimeToMessage = (data, message) => {
const headers = data.split(/\r?\n\r?\n/)[0];
if (/Content-Type:/i.test(headers)) {
const struct = ParseMime(data),
text = struct.getByContentType('text/plain');
let html = struct.getByContentType('text/html');
html = html ? html.body : '';
// TODO: Check multipart/signed application/pgp-signature application/pgp-keys
struct.forEach(part => {
let cd = part.header('content-disposition'),
cid = part.header('content-id'),
type = part.header('content-type');
if (cid || cd) {
// if (cd && 'attachment' === cd.value) {
let attachment = new AttachmentModel;
attachment.mimeType = type.value;
attachment.fileName = type.name || (cd && cd.params.filename) || '';
attachment.fileNameExt = attachment.fileName.replace(/^.+(\.[a-z]+)$/, '$1');
attachment.fileType = FileInfo.getType('', type.value);
attachment.url = part.dataUrl;
attachment.friendlySize = FileInfo.friendlySize(part.body.length);
/*
attachment.isThumbnail = false;
attachment.contentLocation = '';
attachment.download = '';
attachment.folder = '';
attachment.uid = '';
attachment.mimeIndex = part.id;
attachment.framed = false;
*/
attachment.cid = cid ? cid.value : '';
if (cid && html) {
let cid = 'cid:' + attachment.contentId(),
found = html.includes(cid);
attachment.isInline(found);
attachment.isLinked(found);
found && (html = html
.replace('src="' + cid + '"', 'src="' + attachment.url + '"')
.replace("src='" + cid + "'", "src='" + attachment.url + "'")
);
} else {
message.attachments.push(attachment);
}
}
});
message.plain(text ? text.body : '');
if (html) {
message.html(html.replace(/<\/?script[\s\S]*?>/gi, ''));
message.viewHtml();
} else {
message.viewPlain();
}
return;
}
message.plain(data);
message.viewPlain();
};
export class MailMessageView extends AbstractViewRight { export class MailMessageView extends AbstractViewRight {
constructor() { constructor() {
@ -647,7 +585,8 @@ export class MailMessageView extends AbstractViewRight {
const oMessage = currentMessage(); const oMessage = currentMessage();
PgpUserStore.decrypt(oMessage).then(result => { PgpUserStore.decrypt(oMessage).then(result => {
if (result && result.data) { if (result && result.data) {
mimeToMessage(result.data, oMessage); MimeToMessage(result.data, oMessage);
oMessage.html() ? oMessage.viewHtml() : oMessage.viewPlain();
if (result.signatures && result.signatures.length) { if (result.signatures && result.signatures.length) {
oMessage.pgpSigned(true); oMessage.pgpSigned(true);
oMessage.pgpVerified({ oMessage.pgpVerified({

View file

@ -660,6 +660,14 @@ trait Messages
{ {
$sFolderName = $this->GetActionParam('Folder', ''); $sFolderName = $this->GetActionParam('Folder', '');
$iUid = (int) $this->GetActionParam('Uid', 0); $iUid = (int) $this->GetActionParam('Uid', 0);
$sBodyPart = $this->GetActionParam('BodyPart', '');
$sSigPart = $this->GetActionParam('SigPart', '');
if ($sBodyPart) {
$result = [
'text' => \preg_replace('/\\R/s', "\r\n", $sBodyPart),
'signature' => $this->GetActionParam('SigPart', '')
];
} else {
$sBodyPartId = $this->GetActionParam('BodyPartId', ''); $sBodyPartId = $this->GetActionParam('BodyPartId', '');
$sSigPartId = $this->GetActionParam('SigPartId', ''); $sSigPartId = $this->GetActionParam('SigPartId', '');
// $sMicAlg = $this->GetActionParam('MicAlg', ''); // $sMicAlg = $this->GetActionParam('MicAlg', '');
@ -704,6 +712,7 @@ trait Messages
$result['text'] = \quoted_printable_decode($result['text']); $result['text'] = \quoted_printable_decode($result['text']);
} }
} }
}
if ($this->GetActionParam('GnuPG', 1)) { if ($this->GetActionParam('GnuPG', 1)) {
$GPG = $this->GnuPG(); $GPG = $this->GnuPG();