Skip to content
12 changes: 8 additions & 4 deletions .docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ send HTML only. That HTML becomes lines at every `<br>`, table cell, row and blo
Store those bytes before reading them. A template the library does not know yet is `Unparsed`, and a later
release can read the stored message again.

Messages over 64 KiB are `Unparsed` without being looked at; a bank's notification is around 5 KiB. See
[verification](verification.md#the-size-limit).
Messages over 64 KiB are never verified: from a bank's sender they are `Unverified`, from anyone else
`NOT_A_BANK_EMAIL`. A bank's notification is around 5 KiB. See [verification](verification.md#the-size-limit).

## When there is no transaction

Expand All @@ -52,9 +52,13 @@ exception is sealed, so a `switch` over its three subtypes is exhaustive:

| `reason()` | Means | Do |
|---|---|---|
| `NOT_A_BANK_EMAIL` | not from a bank this release reads | nothing for the account holder; another bank may be added later |
| `NOT_A_BANK_EMAIL` | not from a bank this release reads, or no readable sender at all | nothing for the account holder; another bank may be added later |
| `UNSUPPORTED_FORMAT` | a bank's notification in a format the library will not read, e.g. Fio's short one without a transaction id | show the account holder `getMessage()`: it says what to choose in their banking |
| `NOT_READ` | anything else: a changed template, a misread value, bytes that are no e-mail | keep it; a later release, or a bug report with an anonymised copy, can fix it |
| `NOT_READ` | anything else: a changed template, a misread value | keep it; a later release, or a bug report with an anonymised copy, can fix it |

`UNSUPPORTED_FORMAT` and `NOT_READ` come only once the bank's signature holds, so either one means the bank wrote.
`NOT_A_BANK_EMAIL` is the only reason given before the signature is checked: with no bank named, there is no key to
check it against.

Keep a `default` branch: a reason may be added in a minor version.

Expand Down
22 changes: 14 additions & 8 deletions .docs/verification.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,31 +13,37 @@ flowchart TB

subgraph lib ["bank-notifications: read(raw)"]
direction TB
read["read"] --> parse{"Air Bank's template,<br/>every field consistent?"}
parse -- "no" --> unparsed(["Unparsed"])
parse -- "yes" --> dns{"bank's key from DNS,<br/>DNSSEC-validated<br/>from the root"}
read["read"] --> sender{"sender a bank<br/>this release reads?"}
sender -- "no" --> other(["Unparsed,<br/>NOT_A_BANK_EMAIL"])
sender -- "yes" --> dns{"bank's key from DNS,<br/>DNSSEC-validated<br/>from the root"}
dns -- "DNS down" --> temporary(["TemporaryFailure"])
dns -- "forged or unsigned" --> unverified(["Unverified"])
dns -- "secure" --> pin{"key pinned<br/>in this release?"}
pin -- "no" --> unverified
pin -- "yes" --> sig{"signature valid,<br/>d=airbank.cz,<br/>whole body?"}
sig -- "no" --> unverified
sig -- "yes" --> transaction(["Transaction"])
sig -- "yes" --> parse{"Air Bank's template,<br/>every field consistent?"}
parse -- "no" --> unparsed(["Unparsed"])
parse -- "yes" --> transaction(["Transaction"])
end

transaction --> you["you: is it my account?<br/>seen this transactionId?"]
```

Every arrow out of the box but one ends in an exception. A `Transaction` exists only when all four checks passed, with
no setting to forget. The two questions at the bottom stay with you, see [usage](usage.md#two-checks-stay-with-you).
Every arrow out of the box but one ends in an exception. A `Transaction` exists only when every check passed, with no
setting to forget. The body is read last, so nothing it says can count before the bank's signature does. The two questions at the bottom stay with you, see [usage](usage.md#two-checks-stay-with-you).

## What counts

A signature counts only when all of these hold, besides [whose key it is](#whose-key-it-is):

- it verifies over the **raw bytes**, recomputed here; an `Authentication-Results` header that came with the message
is never read, because whoever sent the message could have written it;
- its `d=` is the domain of the bank whose template matched (`airbank.cz` for Air Bank, `fio.cz` for Fio);
- its `d=` is the domain of the bank the sender names (`airbank.cz` for Air Bank, `fio.cz` for Fio); a signature of any
other domain is not even looked up;
- the headers reading depends on (`Message-ID`, `Subject`, `Content-Type`, `Content-Transfer-Encoding`) come once:
DKIM signs the last copy of a header and the mail library reads the first, so a copy added above a signed one is
`Unverified`;
- it signs the **whole body**: a signature with `l=` covers only the first bytes, and anything could follow them;
- its key is not in testing mode (`t=y` in the key record);
- an RSA key has at least 1024 bits, the shortest [RFC 8301](https://www.rfc-editor.org/rfc/rfc8301) lets a verifier
Expand Down Expand Up @@ -86,5 +92,5 @@ the wrapper makes one per message; `BankNotifications` and `DkimVerifier` are th

jDKIM's maintainers fixed parsing that was not linear in its input on 2026-11-05 (the `g=` check and the space after a
header name), after 0.5. Those fixes are not released yet. Since anyone can send mail to the address these e-mails come
to, the library refuses messages over 64 KiB before parsing them. The limit goes up once a jDKIM release carries the
to, the library refuses to verify messages over 64 KiB, so it never parses them. The limit goes up once a jDKIM release carries the
fixes.
Original file line number Diff line number Diff line change
Expand Up @@ -77,14 +77,20 @@ public Reason reason() {

/** Why an e-mail was not read. A constant may be added in a minor version: keep a {@code default} branch. */
public enum Reason {
/** Not from a bank this release reads: another bank, or not a bank at all. Nothing for the account holder to fix. */
/**
* Not from a bank this release reads: another bank, not a bank at all, or no readable sender. Nothing for the
* account holder to fix. The only reason given before the signature is checked: there is no key to check.
*/
NOT_A_BANK_EMAIL,
/**
* A bank's notification in a format the library knows but will not read, such as one without a transaction
* id. The account holder can fix it in their banking; the message says what to choose instead.
*/
UNSUPPORTED_FORMAT,
/** Anything else: a template that changed, a misread value, a message cut short, bytes that are no e-mail. */
/**
* Anything else in a message the bank's signature verified: a template that changed, a misread value. Like
* {@link #UNSUPPORTED_FORMAT}, only ever given after the signature holds, so it is the bank writing.
*/
NOT_READ
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,24 +104,28 @@ public Transaction read(byte[] rawMessage) {
* where the bank gives no transaction id.
*/
public List<Transaction> readAll(byte[] rawMessage) {
// Before the parser too: anyone can mail the address these come to.
if (rawMessage.length > DkimVerifier.MAX_MESSAGE_BYTES) {
throw new BankNotificationException.Unparsed("message of " + rawMessage.length + " bytes is over the "
+ DkimVerifier.MAX_MESSAGE_BYTES + " byte limit");
}
List<Transaction> transactions = parseAllUnverified(rawMessage);
// The signature first, against the key of the bank the sender domain picks: an unsigned e-mail that claims a
// bank must end as Unverified whatever its body says, not as Unparsed, which an app reads as "the bank wrote".
// Over DkimVerifier.MAX_MESSAGE_BYTES, the verifier fails it before jDKIM sees the bytes: Unverified from a
// bank's
// sender, NOT_A_BANK_EMAIL from anyone else.
Comment thread
landsman marked this conversation as resolved.
Resolved
MimeMessage message = mime(rawMessage);
Bank bank = bankOf(message);
refuseRepeatedHeaders(message);
DkimResult dkim;
try {
dkim = this.dkim.verify(rawMessage, transactions.get(0).signedBy());
dkim = this.dkim.verify(rawMessage, bank.domain());
} catch (RuntimeException e) {
throw new BankNotificationException.Unverified("signature could not be checked: " + e);
}
return switch (dkim) {
// Kept only when the signature covers it; anything unsigned in the headers is the sender's to change.
case DkimResult.Verified verified ->
verified.signedHeaders().contains("message-id")
case DkimResult.Verified verified -> {
List<Transaction> transactions = parse(bank, message);
// Kept only when the signature covers it; anything unsigned in the headers is the sender's to change.
yield verified.signedHeaders().contains("message-id")
Comment thread
landsman marked this conversation as resolved.
Resolved
? transactions
: transactions.stream().map(t -> t.withMessageId(null)).toList();
}
case DkimResult.Failed failed -> throw new BankNotificationException.Unverified(failed.reason());
case DkimResult.TemporaryFailure temporary ->
throw new BankNotificationException.TemporaryFailure(temporary.reason());
Expand All @@ -139,15 +143,67 @@ static Transaction parseUnverified(byte[] rawMessage) {

/** Every transaction of a message, signature unchecked. */
static List<Transaction> parseAllUnverified(byte[] rawMessage) {
MimeMessage message = mime(rawMessage);
return parse(bankOf(message), message);
}

/** Bytes that are no e-mail name no bank either, so there is no key to check them against. */
private static MimeMessage mime(byte[] rawMessage) {
try {
return new MimeMessage(SESSION, new ByteArrayInputStream(rawMessage));
} catch (MessagingException | RuntimeException e) {
throw new BankNotificationException.Unparsed(
BankNotificationException.Unparsed.Reason.NOT_A_BANK_EMAIL, "not a readable e-mail: " + e);
}
}

/**
* The bank the sender domain picks, or {@link BankNotificationException.Unparsed.Reason#NOT_A_BANK_EMAIL} for a
* sender with no parser. An unreadable From is one: it names no bank, so it cannot pass for one that wrote.
*/
private static Bank bankOf(MimeMessage message) {
String domain;
try {
domain = senderDomain(message);
} catch (MessagingException | RuntimeException e) {
throw new BankNotificationException.Unparsed(
BankNotificationException.Unparsed.Reason.NOT_A_BANK_EMAIL, "unreadable From header: " + e);
}
return BANKS.stream()
.filter(candidate -> candidate.domain().equals(domain))
.findFirst()
.orElseThrow(() -> new BankNotificationException.Unparsed(
BankNotificationException.Unparsed.Reason.NOT_A_BANK_EMAIL,
"no parser for sender domain " + domain));
}

/**
* DKIM signs the last copy of a header (RFC 6376, 5.4.2) and Jakarta Mail reads the first, so a copy added above a
* signed one would pass verification and be what is read: a replayed notification under a new {@code Message-ID},
* or another {@code Subject} picking another template. RFC 5322 and MIME allow one of each, so a bank sends one. A
* second {@code From} never gets here: {@link #bankOf} names no bank for it.
*/
private static void refuseRepeatedHeaders(MimeMessage message) {
for (String name : READ_HEADERS) {
String[] copies;
try {
copies = message.getHeader(name);
} catch (MessagingException e) {
throw new BankNotificationException.Unverified("unreadable " + name + " header: " + e);
}
if (copies != null && copies.length > 1) {
throw new BankNotificationException.Unverified(
name + " appears " + copies.length + " times; a bank sends one, so the others are not its own");
}
}
}

/** The headers besides {@code From} that reading depends on: the id, the template's subject, how the body decodes. */
private static final List<String> READ_HEADERS =
List.of("Message-ID", "Subject", "Content-Type", "Content-Transfer-Encoding");

private static List<Transaction> parse(Bank bank, MimeMessage message) {
try {
MimeMessage message = new MimeMessage(SESSION, new ByteArrayInputStream(rawMessage));
String domain = senderDomain(message);
Bank bank = BANKS.stream()
.filter(candidate -> candidate.domain().equals(domain))
.findFirst()
.orElseThrow(() -> new BankNotificationException.Unparsed(
BankNotificationException.Unparsed.Reason.NOT_A_BANK_EMAIL,
"no parser for sender domain " + domain));
String messageId = message.getMessageID();
List<Transaction> transactions = bank.parseAll(message.getSubject(), MailBody.text(message)).stream()
.map(t -> t.withMessageId(messageId))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@
*
* <pre>{@code
* DkimVerifier dkim = DkimVerifier.withDns();
* if (BankNotifications.parse(raw) instanceof Transaction t
* && dkim.verify(raw, t.signedBy()) instanceof DkimResult.Verified) {
* // genuine; still compare t.account() with the account you expect
* // The domain comes from your own configuration, never from the message: check first, parse after.
* if (dkim.verify(raw, "bank.example") instanceof DkimResult.Verified) {
* // genuine; only now read it, and compare what it says with the account you expect
* }
* }</pre>
*/
Expand Down Expand Up @@ -108,7 +108,7 @@ public static String fingerprint(PublicKey key) {
* Verifies one raw message against the domain that has to have signed it.
*
* @param rawMessage the message exactly as received, headers included; not re-serialised by a mail library
* @param domain the domain that must have signed it, e.g. {@code Transaction.signedBy()}
* @param domain the domain that must have signed it, from the caller's own configuration, never from the message
* @return verified, failed, or temporarily undecidable
*/
public DkimResult verify(byte[] rawMessage, String domain) {
Expand All @@ -117,7 +117,7 @@ public DkimResult verify(byte[] rawMessage, String domain) {
"message of " + rawMessage.length + " bytes is over the " + MAX_MESSAGE_BYTES + " byte limit");
}
// One jDKIM verifier per message: it keeps its results on the instance.
DKIMVerifier verifier = new DKIMVerifier(checked(keys, minimumKeyBits, pins));
DKIMVerifier verifier = new DKIMVerifier(checked(keys, minimumKeyBits, pins, domain.toLowerCase(Locale.ROOT)));
try {
verifier.verify(new ByteArrayInputStream(rawMessage));
} catch (FailException e) {
Expand Down Expand Up @@ -179,10 +179,18 @@ private DkimVerifier(PublicKeyRecordRetriever keys, int minimumKeyBits, Map<Stri
this.pins = pins;
}

/** Refuses, as a permanent failure, a key in testing mode, an RSA key that is too short, or one not pinned. */
/**
* Refuses, as a permanent failure, a domain other than the expected one, a key in testing mode, an RSA key that is
* too short, or one not pinned.
*/
private static PublicKeyRecordRetriever checked(
PublicKeyRecordRetriever keys, int minimumKeyBits, Map<String, Set<String>> pins) {
PublicKeyRecordRetriever keys, int minimumKeyBits, Map<String, Set<String>> pins, String expected) {
return (method, selector, domain) -> {
// jDKIM looks up the d= of every signature the message carries; the sender picks those, so a name that is
// not the expected domain is never looked up.
if (!domain.toString().toLowerCase(Locale.ROOT).equals(expected)) {
throw new PermFailException("d=" + domain + " is not " + expected + ", not looked up");
}
List<String> records = keys.getRecords(method, selector, domain);
for (String record : records) {
PublicKeyRecordImpl parsed;
Expand Down
Loading