Skip to main content

fints_client/mask/
pseudonym.rs

1//! Stand-ins for identity values in traces: per-trace aliases for account
2//! identifiers, keyed pseudonyms for references and IDs.
3//!
4//! Both give equal values equal stand-ins, so a trace still shows which
5//! values are the same while the values are gone. The user's own account
6//! identifiers and the IDs of the dialog keep their length and character
7//! classes, because requests and answers must still fit together. What
8//! comes from other people does not: a counterparty's IBAN, a creditor ID
9//! and every booking and payment reference are written in one fixed form
10//! each, because the length and pattern of such a value names its issuer
11//! (a payment service's references are recognisable by their shape). They
12//! differ in what links them:
13//!
14//! - **Aliases** for account identifiers: IBAN, account number, user and
15//!   customer ID, creditor ID. These have little entropy (a German IBAN is
16//!   the bank code, which is in clear, plus ten digits), so no function of
17//!   the value may be written: anyone holding the key could try every
18//!   value. An alias is a number: the values of a kind are numbered in the
19//!   order they first appear in the trace, from a random start drawn per
20//!   [`Identities`] (per recorder), and the number is written in the
21//!   value's character classes. It has no mathematical link to the value.
22//!   The table from value to number lives only in memory and is never
23//!   written; two recorders, even with the same [`Salt`], give the same
24//!   value unrelated aliases.
25//! - **Pseudonyms** (every other class: booking reference, end-to-end ID,
26//!   message and payment information ID, mandate reference, instant order
27//!   ID, VOP-ID, polling ID, system ID). These are keyed by the [`Salt`],
28//!   so traces recorded with the same salt give a value the same
29//!   pseudonym.
30//!
31//! # Aliases
32//!
33//! Three kinds are numbered apart: accounts (IBAN and account number
34//! share one table), users (user ID and customer ID), creditors. The alias
35//! of number `n` writes `n` from the right over the value's ASCII letters
36//! and digits, a digit in base 10 and a letter in base 26 (`A`/`a` is 0,
37//! case kept); every other character stays. Formats:
38//!
39//! - Account number ([`IdClass::Account`]): leading zeros stay; the rest is
40//!   the key of the table, and its first character, if a digit, is not
41//!   `0` (the zeros keep their count). So `0001234567` (KTV) and `1234567` (MT940 `:25:`) of the same
42//!   account get the same digits after the zeros.
43//! - IBAN ([`IdClass::Iban`]): country and bank part of the BBAN stay (the
44//!   bank code is in clear in the KTI anyway; [`bank_part_len`]), the
45//!   account part gets the account number's alias, and the check digits
46//!   are computed again (ISO 13616 mod 97): the alias is a valid IBAN, and
47//!   its account part matches the alias of the same account's KTV number.
48//!   A value that is not of the IBAN form gets an account number's alias.
49//! - IBAN of someone else ([`IdClass::OtherIban`]): always `DE`, check
50//!   digits, the bank code `00000000` and ten digits of the alias, whatever
51//!   country, bank and length the value had.
52//! - Creditor ID ([`IdClass::CreditorId`]): always `DE`, check digits,
53//!   `ZZZ` and eleven digits of the alias (mod 97 over the national
54//!   identifier and the country, the business code left out).
55//!
56//! # Pseudonyms
57//!
58//! For a value `v` of identity class `c` (the tag of [`IdClass`]):
59//!
60//! 1. `k = HMAC-SHA256(salt, c ‖ 0x00 ‖ v)`;
61//! 2. a key stream `HMAC-SHA256(k, 0) ‖ HMAC-SHA256(k, 1) ‖ …` (counter as
62//!    four bytes, big-endian);
63//! 3. each ASCII digit of `v` becomes the next stream byte below 250,
64//!    modulo 10; each upper-case letter the next byte below 234, modulo 26,
65//!    as an upper-case letter; lower case likewise. Every other character
66//!    stays. A booking or payment reference (booking reference, end-to-end
67//!    ID, message and payment information ID, mandate reference) is instead
68//!    twelve characters of `0-9A-Z` from the stream, whatever it looked
69//!    like; the constants `NOTPROVIDED` and `NONREF` stay.
70//!
71//! Every character depends on the whole value, so the pseudonym of a
72//! prefix says nothing about the pseudonym of the whole value. With the
73//! same salt the pseudonyms are the same in every trace; with another salt
74//! they are unrelated. Two different values with the same pattern collide
75//! with probability one in the number of values of that pattern.
76//!
77//! - [`IdClass::SystemId`]: `0` (no system ID yet) stays.
78//! - Binary data that is not printable ASCII (a VOP-ID or polling ID made
79//!   of raw bytes): every byte becomes a stream byte.
80
81use std::collections::HashMap;
82use std::sync::Mutex;
83
84use hmac_sha256::HMAC;
85
86/// The secret key of the pseudonyms: 32 bytes. Never written into a trace.
87/// Account identifiers do not depend on it (they get aliases).
88#[derive(Clone, PartialEq, Eq)]
89pub struct Salt([u8; 32]);
90
91/// 32 bytes from the operating system's random number generator.
92fn random_bytes() -> [u8; 32] {
93    use rand::TryRngCore as _;
94    let mut bytes = [0u8; 32];
95    rand::rngs::OsRng
96        .try_fill_bytes(&mut bytes)
97        .expect("the operating system's random number generator works");
98    bytes
99}
100
101impl Salt {
102    /// A new salt from the operating system's random number generator.
103    pub fn random() -> Salt {
104        Salt(random_bytes())
105    }
106
107    /// The salt with these bytes.
108    pub fn from_bytes(bytes: [u8; 32]) -> Salt {
109        Salt(bytes)
110    }
111
112    /// The salt as 64 lower-case hex digits.
113    pub fn to_hex(&self) -> String {
114        self.0.iter().map(|b| format!("{b:02x}")).collect()
115    }
116
117    /// Reads 64 hex digits; surrounding white space is ignored.
118    pub fn from_hex(text: &str) -> Result<Salt, String> {
119        let text = text.trim();
120        if text.len() != 64 || !text.bytes().all(|b| b.is_ascii_hexdigit()) {
121            return Err("a salt is 64 hex digits".into());
122        }
123        let mut bytes = [0u8; 32];
124        for (i, byte) in bytes.iter_mut().enumerate() {
125            *byte = u8::from_str_radix(&text[2 * i..2 * i + 2], 16)
126                .map_err(|_| "a salt is 64 hex digits".to_string())?;
127        }
128        Ok(Salt(bytes))
129    }
130}
131
132impl std::fmt::Debug for Salt {
133    /// Never shows the bytes.
134    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
135        f.write_str("Salt(…)")
136    }
137}
138
139/// What an identity value is. Equal values of different classes get
140/// different stand-ins; the classes are chosen so that the same thing
141/// gets the same class wherever it occurs.
142#[derive(Clone, Copy, Debug, PartialEq, Eq)]
143pub(crate) enum IdClass {
144    /// IBAN of one of the user's accounts (KTI, KTZ, HIUPD, a statement's
145    /// own account, the debtor of a pain.001). Alias of the account part;
146    /// the bank code stays, as it does in the KTI.
147    Iban,
148    /// IBAN of anyone else (counterparty of a booking, payee). Alias of the
149    /// whole BBAN: a counterparty's bank code would say where the user's
150    /// other accounts are.
151    OtherIban,
152    /// National account or depot number (KTV, KTI, KTZ, MT940 `:25:`,
153    /// `:86:` `?31`, MT535 `:97A:`, camt `Othr/Id` of an account). Alias.
154    Account,
155    /// User ID and customer ID (HKIDN, HNSHK, HNVSK, HIUPA, HIUPD). Alias.
156    UserId,
157    /// Creditor ID: camt and pain `CdtrSchmeId`, MT940 `CRED+`. Alias.
158    CreditorId,
159    /// Customer system ID (HKIDN, HNSHK, HNVSK, HISYN).
160    SystemId,
161    /// The bank's booking reference: camt `AcctSvcrRef`, MT940 `:61:`
162    /// bank reference.
163    BookingRef,
164    /// End-to-end ID: pain and camt `EndToEndId`, `OrgnlEndToEndId`,
165    /// MT940 `EREF+` and `:61:` customer reference.
166    EndToEnd,
167    /// pain `MsgId`, `OrgnlMsgId` (and a camt's own `MsgId`).
168    MessageId,
169    /// pain `PmtInfId`, `OrgnlPmtInfId`.
170    PaymentInfoId,
171    /// Mandate reference: `MndtId`, MT940 `MREF+`.
172    Mandate,
173    /// Order ID of an instant payment (HKIPS, HIIPS, HIIPZ).
174    OrderId,
175    /// VOP-ID (HIVPP, HKVPA).
176    VopId,
177    /// Polling ID (HIVPP, HKVPP).
178    PollingId,
179}
180
181/// The alias tables: one per kind of account identifier.
182#[derive(Clone, Copy, PartialEq, Eq, Hash)]
183enum Kind {
184    Account = 0,
185    User = 1,
186    Creditor = 2,
187}
188
189impl IdClass {
190    fn tag(self) -> &'static str {
191        match self {
192            IdClass::Iban => "iban",
193            IdClass::OtherIban => "other-iban",
194            IdClass::Account => "account",
195            IdClass::UserId => "user-id",
196            IdClass::CreditorId => "creditor-id",
197            IdClass::SystemId => "system-id",
198            IdClass::BookingRef => "booking-ref",
199            IdClass::EndToEnd => "end-to-end-id",
200            IdClass::MessageId => "message-id",
201            IdClass::PaymentInfoId => "payment-info-id",
202            IdClass::Mandate => "mandate-ref",
203            IdClass::OrderId => "order-id",
204            IdClass::VopId => "vop-id",
205            IdClass::PollingId => "polling-id",
206        }
207    }
208
209    /// The alias table of an account identifier, which gets a per-trace
210    /// alias and never a pseudonym; `None` for a class that gets a
211    /// pseudonym.
212    fn kind(self) -> Option<Kind> {
213        match self {
214            IdClass::Iban | IdClass::OtherIban | IdClass::Account => Some(Kind::Account),
215            IdClass::UserId => Some(Kind::User),
216            IdClass::CreditorId => Some(Kind::Creditor),
217            _ => None,
218        }
219    }
220}
221
222/// The value-to-number tables of the aliases. Held in memory only.
223#[derive(Default)]
224struct Table {
225    numbers: HashMap<(Kind, Vec<u8>), u64>,
226    count: [u64; 3],
227}
228
229/// Makes the stand-ins of one trace: aliases for account identifiers,
230/// pseudonyms keyed by one [`Salt`] for the rest.
231pub(crate) struct Identities {
232    salt: Salt,
233    /// How many days every date of the trace is moved (`mask::dates`).
234    days: i32,
235    /// The random start of each kind's numbering.
236    start: [u64; 3],
237    table: Mutex<Table>,
238}
239
240impl std::fmt::Debug for Identities {
241    /// Never shows the salt or the alias table.
242    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
243        f.write_str("Identities(…)")
244    }
245}
246
247/// The key stream of one value.
248struct Stream {
249    key: [u8; 32],
250    counter: u32,
251    block: [u8; 32],
252    at: usize,
253}
254
255impl Stream {
256    fn new(key: [u8; 32]) -> Stream {
257        let mut s = Stream {
258            key,
259            counter: 0,
260            block: [0; 32],
261            at: 32,
262        };
263        s.refill();
264        s
265    }
266
267    fn refill(&mut self) {
268        self.block = HMAC::mac(self.counter.to_be_bytes(), self.key);
269        self.counter = self.counter.wrapping_add(1);
270        self.at = 0;
271    }
272
273    fn byte(&mut self) -> u8 {
274        if self.at == 32 {
275            self.refill();
276        }
277        let b = self.block[self.at];
278        self.at += 1;
279        b
280    }
281
282    /// A uniform number below `n` (rejection sampling).
283    fn below(&mut self, n: u8) -> u8 {
284        let limit = 256 - (256 % u16::from(n));
285        loop {
286            let b = self.byte();
287            if u16::from(b) < limit {
288                return b % n;
289            }
290        }
291    }
292}
293
294impl Identities {
295    /// Pseudonyms keyed by `salt`; aliases numbered from a fresh random
296    /// start.
297    pub(crate) fn new(salt: Salt) -> Identities {
298        let r = random_bytes();
299        let start = std::array::from_fn(|k| {
300            u64::from_be_bytes(r[8 * k..8 * k + 8].try_into().expect("8 bytes"))
301        });
302        Identities {
303            salt,
304            days: 0,
305            start,
306            table: Mutex::default(),
307        }
308    }
309
310    /// These identities with every date moved by `days`.
311    pub(crate) fn with_days(mut self, days: i32) -> Identities {
312        self.days = days;
313        self
314    }
315
316    /// How many days a date of the trace is moved.
317    pub(crate) fn days(&self) -> i32 {
318        self.days
319    }
320
321    /// A number of days to move the dates of one trace by: 3 to 30 days
322    /// back, drawn from the operating system's random number generator.
323    pub(crate) fn random_days() -> i32 {
324        -(3 + i32::from(random_bytes()[0] % 28))
325    }
326
327    fn stream(&self, class: IdClass, value: &[u8]) -> Stream {
328        let mut mac = HMAC::new(self.salt.0);
329        mac.update(class.tag());
330        mac.update([0u8]);
331        mac.update(value);
332        Stream::new(mac.finalize())
333    }
334
335    /// ASCII letters and digits of `value` mapped with `stream`, every
336    /// other byte kept.
337    fn map(stream: &mut Stream, value: &[u8]) -> Vec<u8> {
338        value
339            .iter()
340            .map(|&c| match c {
341                b'0'..=b'9' => b'0' + stream.below(10),
342                b'A'..=b'Z' => b'A' + stream.below(26),
343                b'a'..=b'z' => b'a' + stream.below(26),
344                other => other,
345            })
346            .collect()
347    }
348
349    /// The stand-in of `value` (bytes of text or binary data). The same
350    /// length and character classes, except for the classes with one fixed
351    /// form (a counterparty's IBAN, a creditor ID, a reference).
352    pub(crate) fn bytes(&self, class: IdClass, value: &[u8]) -> Vec<u8> {
353        if value.is_empty() {
354            return Vec::new();
355        }
356        match class {
357            IdClass::Iban if is_iban(value) => self.iban_alias(value),
358            IdClass::OtherIban if is_iban(value) => {
359                let mut out = b"DE0000000000".to_vec();
360                out.extend(self.alias(Kind::Account, &value[4..], b"0000000000", false));
361                set_check_digits(&mut out, 4);
362                out
363            }
364            IdClass::Iban | IdClass::OtherIban | IdClass::Account => self.account_alias(value),
365            IdClass::UserId => self.alias(Kind::User, value, value, false),
366            IdClass::CreditorId if is_creditor_id(value) => {
367                let mut out = b"DE00ZZZ".to_vec();
368                out.extend(self.alias(Kind::Creditor, &value[7..], b"00000000000", false));
369                set_check_digits(&mut out, 7);
370                out
371            }
372            IdClass::BookingRef
373            | IdClass::EndToEnd
374            | IdClass::MessageId
375            | IdClass::PaymentInfoId
376            | IdClass::Mandate => {
377                if matches!(value, b"NOTPROVIDED" | b"NONREF") {
378                    return value.to_vec();
379                }
380                let mut stream = self.stream(class, value);
381                (0..REFERENCE_LEN)
382                    .map(|_| match stream.below(36) {
383                        n @ 0..=9 => b'0' + n,
384                        n => b'A' + n - 10,
385                    })
386                    .collect()
387            }
388            IdClass::CreditorId => self.alias(Kind::Creditor, value, value, false),
389            IdClass::SystemId if value == b"0" => value.to_vec(),
390            IdClass::VopId | IdClass::PollingId
391                if !value.iter().all(|b| (0x20..0x7f).contains(b)) =>
392            {
393                let mut stream = self.stream(class, value);
394                value.iter().map(|_| stream.byte()).collect()
395            }
396            _ => {
397                let mut stream = self.stream(class, value);
398                Self::map(&mut stream, value)
399            }
400        }
401    }
402
403    /// The stand-in of a text value: ASCII letters and digits are
404    /// replaced, every other character stays.
405    pub(crate) fn text(&self, class: IdClass, value: &str) -> String {
406        let reference = matches!(
407            class,
408            IdClass::BookingRef
409                | IdClass::EndToEnd
410                | IdClass::MessageId
411                | IdClass::PaymentInfoId
412                | IdClass::Mandate
413        );
414        if value.is_ascii() || reference {
415            return self
416                .bytes(class, value.as_bytes())
417                .into_iter()
418                .map(char::from)
419                .collect();
420        }
421        // Replace the ASCII characters only; the derivation and the alias
422        // table see the whole value.
423        if let Some(kind) = class.kind() {
424            // A non-ASCII character is neither letter nor digit to `fill`.
425            let pattern: Vec<u8> = value
426                .chars()
427                .map(|c| if c.is_ascii() { c as u8 } else { 0x80 })
428                .collect();
429            let out = self.alias(kind, value.as_bytes(), &pattern, false);
430            return value
431                .chars()
432                .zip(out)
433                .map(|(c, b)| if c.is_ascii() { char::from(b) } else { c })
434                .collect();
435        }
436        let mut stream = self.stream(class, value.as_bytes());
437        value
438            .chars()
439            .map(|c| {
440                if c.is_ascii() {
441                    char::from(Self::map(&mut stream, &[c as u8])[0])
442                } else {
443                    c
444                }
445            })
446            .collect()
447    }
448
449    /// The number of `key` in the table of `kind` (the next one if `key`
450    /// is new), plus the kind's random start.
451    fn number(&self, kind: Kind, key: &[u8]) -> u64 {
452        let mut table = self.table.lock().unwrap_or_else(|e| e.into_inner());
453        let Table { numbers, count } = &mut *table;
454        let n = *numbers.entry((kind, key.to_vec())).or_insert_with(|| {
455            count[kind as usize] += 1;
456            count[kind as usize]
457        });
458        self.start[kind as usize].wrapping_add(n)
459    }
460
461    /// The alias of `key` in the table of `kind`, written over `pattern`.
462    fn alias(&self, kind: Kind, key: &[u8], pattern: &[u8], nonzero_first: bool) -> Vec<u8> {
463        fill(pattern, self.number(kind, key), nonzero_first)
464    }
465
466    /// An account number: leading zeros stay, the rest is the key.
467    fn account_alias(&self, value: &[u8]) -> Vec<u8> {
468        let zeros = value.iter().take_while(|&&b| b == b'0').count();
469        let rest = &value[zeros..];
470        let mut out = value[..zeros].to_vec();
471        if !rest.is_empty() {
472            out.extend(self.alias(Kind::Account, rest, rest, true));
473        }
474        out
475    }
476
477    /// An IBAN: country and bank part stay, the account part gets the
478    /// account number's alias, the check digits are computed again.
479    fn iban_alias(&self, iban: &[u8]) -> Vec<u8> {
480        let bank = (4 + bank_part_len(&iban[..2])).min(iban.len());
481        let mut out = iban[..bank].to_vec();
482        out.extend(self.account_alias(&iban[bank..]));
483        set_check_digits(&mut out, 4);
484        out
485    }
486}
487
488/// Length of the stand-in of a booking or payment reference. It fits the
489/// shortest field a reference is sent in (MT940 `:61:`, 16 characters).
490const REFERENCE_LEN: usize = 12;
491
492/// `number` written from the right over the ASCII letters and digits of
493/// `pattern` (digits base 10, letters base 26 from `A`/`a`, case kept);
494/// every other byte stays. With `nonzero_first` the first letter or digit,
495/// if a digit, is `1` to `9`. What does not fit is dropped.
496fn fill(pattern: &[u8], number: u64, nonzero_first: bool) -> Vec<u8> {
497    let first = pattern.iter().position(u8::is_ascii_alphanumeric);
498    let mut rest = number;
499    let mut out = pattern.to_vec();
500    for (i, c) in out.iter_mut().enumerate().rev() {
501        let (base, radix) = match *c {
502            b'0'..=b'9' if nonzero_first && Some(i) == first => (b'1', 9),
503            b'0'..=b'9' => (b'0', 10),
504            b'A'..=b'Z' => (b'A', 26),
505            b'a'..=b'z' => (b'a', 26),
506            _ => continue,
507        };
508        *c = base + (rest % radix) as u8;
509        rest /= radix;
510    }
511    out
512}
513
514/// The length of the bank part of the BBAN (bank code, and branch code
515/// where an account number is per branch), by country (ISO 13616
516/// registry). Other countries: 0, the whole BBAN gets the alias.
517fn bank_part_len(country: &[u8]) -> usize {
518    match country {
519        b"DE" | b"ES" | b"PL" => 8,
520        b"AT" | b"CH" | b"LI" => 5,
521        b"NL" => 4,
522        b"BE" | b"LU" => 3,
523        b"FR" | b"MC" | b"GB" => 10,
524        b"IT" | b"SM" => 11,
525        _ => 0,
526    }
527}
528
529/// Two upper-case letters, two digits, 11 to 30 upper-case letters and
530/// digits (ISO 13616: 15 to 34 characters).
531pub(crate) fn is_iban(v: &[u8]) -> bool {
532    (15..=34).contains(&v.len()) && is_country_check_alnum(v)
533}
534
535/// A SEPA creditor ID: two upper-case letters, two digits, a business
536/// code of three letters or digits, a national identifier of letters and
537/// digits; 8 to 35 characters.
538fn is_creditor_id(v: &[u8]) -> bool {
539    (8..=35).contains(&v.len()) && is_country_check_alnum(v)
540}
541
542fn is_country_check_alnum(v: &[u8]) -> bool {
543    v[..2].iter().all(u8::is_ascii_uppercase)
544        && v[2..4].iter().all(u8::is_ascii_digit)
545        && v[4..]
546            .iter()
547            .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit())
548}
549
550/// Sets the check digits (positions 2 and 3) of an IBAN or creditor ID:
551/// 98 minus the remainder modulo 97 of the characters from `body` on,
552/// then the country and `00`, letters read as 10 to 35 (ISO 13616; the
553/// creditor ID leaves its business code, positions 4 to 6, out).
554fn set_check_digits(id: &mut [u8], body: usize) {
555    let mut rem: u32 = 0;
556    for &c in id[body..].iter().chain(&id[..2]).chain(b"00") {
557        let v = if c.is_ascii_digit() {
558            u32::from(c - b'0')
559        } else {
560            u32::from(c - b'A') + 10
561        };
562        rem = if v >= 10 {
563            (rem * 100 + v) % 97
564        } else {
565            (rem * 10 + v) % 97
566        };
567    }
568    let check = 98 - rem;
569    id[2] = b'0' + (check / 10) as u8;
570    id[3] = b'0' + (check % 10) as u8;
571}
572
573#[cfg(test)]
574mod tests;