Check S/MIME signatures, and remember who signed

A signed message now says whether that holds up, as it is read. This is
verification only: nothing here signs, encrypts or decrypts, and the
private-key question that blocks those is untouched. Verifying needed
none of it, because the certificate travels inside the message -- which
is why this is the half that could be built.

What it checks. For multipart/signed carrying PKCS#7, the exact bytes of
the signed part -- headers included, canonicalised to CRLF -- are hashed
against the messageDigest attribute, and the signature over the signed
attributes is verified with WebCrypto against the certificate inside the
message. RSA PKCS#1 v1.5 and ECDSA over P-256/384/521, with SHA-256, 384
or 512.

The trust model is the design, and it is deliberately small. A browser
has no system trust store, and the certificate arrives inside the
message, so anyone can self-sign as anyone: on its own a good signature
shows only that the sender held the key they attached. So the word
"verified" is never rendered, and the reassuring case is not the loud
one. What carries the weight is remembering -- the first signed message
from an address pins its fingerprint, later ones are compared, and a
signer that changed is reported with both names and told to check by
another route. Trust on first use, no certificate authority anywhere.

The pins live in the account's settings rather than the browser: one
that only a single device knew would greet the same correspondent as new
everywhere else, which is how people are trained to click past the one
warning that matters. A pin records the message that created it, so the
message that established a signer keeps saying so instead of appearing
to be corroborated by itself -- without that, the very first signed
message anybody receives reads as "the same signer as before", where
before is itself. A changed, mismatched or expired signer is never
pinned, since writing the anomaly into the baseline makes every later
message agree with it.

Three things are declined rather than attempted, and all three say
"could not check" rather than "does not check out", because ignorance
and an accusation are different claims:

  - OpenPGP, by name. The signature carries no key and there is nowhere
    to get the sender's: x:PublicKey is the account's OWN registry, and
    a keyserver or WKD lookup would tell a third party who you
    correspond with -- the leak the image proxy exists to close.
  - SHA-1. Not forgeable in practice today, still not something to put a
    tick beside.
  - RSA-PSS, whose salt length lives in parameters this does not read.
    Guessing wrong would report a good signature as bad.

Nothing validates a chain: no CA bundle is shipped and revocation is not
checked. "Issued by" reports what the certificate claims, and a
self-signed one claims itself.

The DER, CMS, X.509 and MIME readers are hand-written and deliberately
narrow -- no new dependency, and the whole verifier is a lazily imported
8.6 kB chunk that a reader of unsigned mail never downloads. The one
place this is easy to get quietly wrong has its own function and its own
test: signed attributes are signed as a SET OF, not as the [0] IMPLICIT
they arrive as, and hashing the message instead would make every
signature "pass".

Tested against real `openssl smime -sign` output rather than hand-built
fixtures -- RSA, ECDSA, a tampered copy, and a valid signature by a
certificate for somebody else -- because a signed message written by
hand only agrees with whatever its author believed the format to be.
Also driven in a browser against the mock, which now serves three real
signed messages so every branch of the banner is reachable.

Translations: 34 new strings in all nine catalogues, 306 entries.
Falling back to English is unchanged at 24 per language.
This commit is contained in:
jcoffey-dev committed 2026-09-05 01:42:51 -07:00
1 parent 7aa2e374d4
commit c84f190f76
31 files changed
+2287 -4

No files matched your search

+103
View File
@@ -0,0 +1,103 @@
/**
* Checking the signature on the message being read.
*
* Two things this is careful about, both about not doing work:
*
* - The verifier is imported dynamically. Signed mail is rare, and DER
* parsing plus certificate reading has no business in the bundle everybody
* downloads to read an unsigned message.
* - Nothing is fetched unless the message says it is signed. The structure
* already came with the message, so the common answer costs one string
* comparison and no network at all.
*/
import { useEffect, useState } from "react";
import { client } from "@/jmap/client";
import type { Email, EmailBodyPart, Id } from "@/jmap/types";
import { useSettings, type SignerPin } from "@/store/settings";
import type { SignatureReport } from "./verify";
/**
* How many signers are remembered before the oldest pin is dropped.
*
* A cap is needed because this rides in the account's settings file, which is
* fetched on every sign-in. Evicting is not free — a dropped signer is greeted
* as new next time, which is a quieter message than it should be — so the limit
* is set far above what S/MIME's actual prevalence will produce rather than at
* a number that trades safety for bytes.
*/
const MAX_PINS = 500;
export type SignatureState = { status: "idle" } | { status: "checking" } | { status: "done"; report: SignatureReport };
/** Whether anything in this message's structure claims to be signed. */
export function structureLooksSigned(part: EmailBodyPart | undefined): boolean {
if (!part) return false;
if (part.type === "multipart/signed") return true;
return (part.subParts ?? []).some(structureLooksSigned);
}
export function useSignature(email: Email | undefined, accountId: Id | null): SignatureState {
const [state, setState] = useState<SignatureState>({ status: "idle" });
useEffect(() => {
if (!email || !accountId || !structureLooksSigned(email.bodyStructure)) {
setState({ status: "idle" });
return;
}
let live = true;
setState({ status: "checking" });
void (async () => {
try {
const [{ judge, shouldRemember, verifyMessage }, blob] = await Promise.all([
import("./verify"),
client.fetchBlob(accountId, email.blobId, "message/rfc822"),
]);
if (!live) return;
const raw = new Uint8Array(await blob.arrayBuffer());
const from = (email.from?.[0]?.email ?? "").toLowerCase();
const crypto = await verifyMessage(raw);
const stored = useSettings.getState().settings.knownSigners[from];
// A pin this very message created is not corroboration of it. Treated
// as absent, so the message that established a signer keeps saying so
// however many times it is reopened.
const known = stored && stored.messageId === email.id ? undefined : stored;
const report = judge(crypto, from, known);
if (!live) return;
if (from && shouldRemember(report) && report.crypto.kind === "intact") {
pin(from, {
fingerprint: report.crypto.cert.fingerprint,
name: report.crypto.cert.subject.commonName || report.crypto.cert.subject.emailAddress || from,
firstSeen: new Date().toISOString(),
messageId: email.id,
});
}
setState({ status: "done", report });
} catch (err) {
if (!live) return;
// A failure to *look* is not a failure to verify, and must not be shown
// as one: a dropped connection is not a bad signature.
setState({ status: "done", report: { crypto: { kind: "unsupported", reason: "other", detail: (err as Error).message }, warnings: [] } });
}
})();
return () => {
live = false;
};
}, [email, accountId]);
return state;
}
function pin(address: string, entry: SignerPin): void {
const { settings, update } = useSettings.getState();
const next = { ...settings.knownSigners, [address]: entry };
const keys = Object.keys(next);
if (keys.length > MAX_PINS) {
const oldest = keys.sort((a, b) => (next[a]!.firstSeen < next[b]!.firstSeen ? -1 : 1)).slice(0, keys.length - MAX_PINS);
for (const k of oldest) delete next[k];
}
update({ knownSigners: next });
}