diff --git a/.gitignore b/.gitignore index a2f6572..f8fe411 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ .DS_Store build/ local.properties +environment.properties libs/id-card-lib/build/ libs/smart-card-reader-lib/build/ diff --git a/IDEMIA_LV.md b/IDEMIA_LV.md new file mode 100644 index 0000000..5867634 --- /dev/null +++ b/IDEMIA_LV.md @@ -0,0 +1,1129 @@ + + + +# Latvian eID — IDEMIA card protocol specification + +A self-contained, platform-neutral specification of the Latvian eID card +(IDEMIA ID-One Cosmo v8 / IAS-ECC, Oberthur AWP applet) sufficient to +re-implement support on any host that can speak ISO/IEC 7816-4 APDUs over +ISO/IEC 14443-4 (NfcA). + +> Conventions +> - Bytes are hex, MSB-first, separated by spaces. `` denotes a placeholder. +> - APDUs are written as `CLA INS P1 P2 [Lc data] [Le]`. +> `Lc` and `Le` are written as a single byte where shown; APDUs without `Lc` +> omit the data block, APDUs without `Le` omit the trailing byte. +> - "MAIN AID", "Oberthur AID", "QSCD AID" are the three applet contexts of +> §3. "Selecting" an AID means sending the SELECT-AID APDU below. + +--- + +## 1. Overview + +| | | +|---|---| +| Card platform | IDEMIA ID-One Cosmo v8 (IAS-ECC) | +| Applets | MAIN (IAS-ECC; certs, EF.CardAccess, EF 0x5001) + Oberthur AWP (auth/decrypt) + QSCD (signing). See §3 for AID values. | +| Transport | ISO 14443-4 / NfcA, ISO 7816-4 APDUs | +| PACE curve | Negotiated from EF.CardAccess. Observed: `brainpoolP256r1` on LV, `secp256r1` on EE — both 256-bit. | +| User-key curve | `secp384r1` per the auth/sign certificates (independent of the PACE curve). All ECDSA signatures returned by the card are 96 bytes (`r ‖ s`, 48 + 48). | +| Secure messaging | PACE-derived AES-256 CBC + AES-256-CMAC (mechanism `id-PACE-ECDH-GM-AES-CBC-CMAC-256`) | +| User secrets | PIN1 (auth), PIN2 (sign), PUK (unblock); CAN for PACE | + +Every sensitive operation (cert read with SM, PIN verify, key operations, +EF.5001 read) requires a PACE channel. The CAN is printed on the card. + +--- + +## 2. Card identification + +Match against the contactless historical bytes / ATS. The library currently +recognises two LV variants: + +| Variant | Bytes | +|---|---| +| Newer LV | `00 12 42 8F 53 65 49 44 0F 90 00` | +| Older LV | `00 12 42 8F 54 65 49 44 32 0F 90 00` | + +The leading `00 12 42 8F` is the manufacturer signature unique to LV. +Match the full byte string. (Estonian IDEMIA cards use `00 12 23 3F` +— provided here for context only; do not match LV cards against the EE +prefix.) + +The byte strings above are **the historical bytes from the card's ATS** +(ISO 14443-4). The trailing `90 00` is part of the historical bytes the +card itself emits — chosen by the card OS, not a synthesized SW. Match +against the historical-bytes substring your stack exposes; if your +transport hands you a full or synthesized ATR instead, extract the +historical-bytes block first. + +For reference, what some common stacks expose by default: + +| Stack | Call | What it returns | +|---|---|---| +| Android (NfcA `IsoDep`) | `getHistoricalBytes()` | Historical bytes — exactly the strings above. | +| Android (NfcA `IsoDep`, alt) | `getHiLayerResponse()` | Full ATS framing — strip leading bytes to recover. | +| iOS (CoreNFC) | `NFCISO7816Tag.historicalBytes` | Historical bytes — same form as Android. | +| PC/SC contactless | `SCardStatus()` ATR | Reader-synthesized contact-style ATR (e.g. `3B 8x 80 01 `); parse out the historical-bytes block. | + +--- + +## 3. Applets and AIDs + +| Applet | AID | Purpose | +|---|---|---| +| MAIN (IAS-ECC) | `A0 00 00 00 77 01 08 00 07 00 00 FE 00 00 01 00` | EF.CardAccess, EF 0x5001, certificate files | +| Oberthur AWP | `E8 28 BD 08 0F F2 50 4F 54 20 41 57 50` | PIN1 verify, auth, decrypt | +| QSCD | `51 53 43 44 20 41 70 70 6C 69 63 61 74 69 6F 6E` (`"QSCD Application"`) | PIN2 verify, signing | + +**SELECT AID** (always P2 = `0x0C` over NFC — `0x00` does not work): + +``` +00 A4 04 0C +``` + +Examples: + +``` +SELECT MAIN: 00 A4 04 0C 10 A0 00 00 00 77 01 08 00 07 00 00 FE 00 00 01 00 +SELECT Oberthur: 00 A4 04 0C 0D E8 28 BD 08 0F F2 50 4F 54 20 41 57 50 +SELECT QSCD: 00 A4 04 0C 10 51 53 43 44 20 41 70 70 6C 69 63 61 74 69 6F 6E +``` + +Expected SW: `90 00`. Selecting an AID resets PIN security state for that +context — verify PINs **after** selecting the relevant AID. + +--- + +## 4. PACE handshake (mandatory) + +The card uses the `id-PACE-ECDH-GM-AES-CBC-CMAC-256` mechanism. OID bytes: + +``` +04 00 7F 00 07 02 02 04 02 04 +``` + +The trailing `04` arc selects the **AES-256** variant of this OID family. +The `02` and `03` arcs would be the AES-128 and AES-192 variants +respectively — picking either of those would yield a non-working client +against this card. + +AES-256 keys (32 bytes), 16-byte AES block size. The CAN is the PACE +password. + +The whole handshake runs in plaintext. After §4.6 succeeds, secure +messaging (§5) is active and the channel is bound to the new keys. + +### 4.1 Read PACE parameters from EF.CardAccess + +``` +SELECT EF.CardAccess: 00 A4 02 0C 02 01 1C +READ BINARY (chunked): 00 B0 00 (loop, see §6) +``` + +Parse the returned ASN.1 (`SET OF SecurityInfo`, possibly without an outer +SET wrapper). Find the `PACEInfo` entry — the `SEQUENCE` whose first child +is an OID equal to **`04 00 7F 00 07 02 02 04 02 04`** (the +`id-PACE-ECDH-GM-AES-CBC-CMAC-256` mechanism this spec uses). Take its +third child (`INTEGER parameterId`) as a single byte: + +> **Do not just pick the first `SEQUENCE { OID, INTEGER, INTEGER }`** — +> EF.CardAccess can carry other `SecurityInfo` entries with the same shape +> (e.g. `ChipAuthenticationInfo`), and selecting the wrong one yields a +> domain-parameter id that doesn't match the curve negotiated in §4.2. + +> **BER length forms.** EF.CardAccess uses standard BER-TLV. Lengths can +> be short-form (one byte, `≤ 0x7F` = the length itself) or long-form +> (`0x81 ` for one length byte, `0x82 ` for two). The +> reference TLV walker handles short-form, `0x81`, and `0x82`; longer +> forms aren't produced for files of this size. A minimal porter walker +> needs at least these three branches. + +| `parameterId` | Curve | Reference impl | +|---|---|---| +| `0x0C` | `secp256r1` | supported | +| `0x0D` | `brainpoolP256r1` | supported | +| `0x0F` | `secp384r1` | rejected — see note | +| `0x10` | `brainpoolP384r1` | rejected — see note | + +**Currently observed on LV cards:** `0x0D` (`brainpoolP256r1`) only; +on EE cards `0x0C` (`secp256r1`). + +The 384-bit rows are reference values from the IDEMIA / IAS-ECC family +and are included so a porter encountering a 384-bit variant can look up +the curve. **The reference implementation in this repo aborts with +"Unsupported PACE domain parameter" if a 384-bit parameterId is read +from EF.CardAccess.** The on-wire BER prefixes in §4.4–§4.6 are +hard-coded for 65-byte points (and the CMAC input for 79-byte length); +a 384-bit port must derive those from the curve's coordinate byte size +(see the per-step length notes below). + +If no usable `parameterId` is present, abort. The remainder of this spec +assumes 256-bit curve byte sizes (65-byte uncompressed SEC1 points, +32-byte shared-secret X) — applicable to both `secp256r1` (EE) and +`brainpoolP256r1` (LV). For 384-bit curves, points are 97 bytes and X is +48 bytes; adjust the point and integer lengths shown in §4.4–§4.6 +accordingly. + +### 4.2 MSE SET AT (Authentication Template) + +``` +00 22 C1 A4 12 + 80 0A 04 00 7F 00 07 02 02 04 02 04 ← PACE OID + 83 01 02 ← password ref = CAN + 84 01 ← curve from §4.1 +00 +``` + +- SW `90 00` → continue. +- SW `63 00` → wrong CAN. Surface this distinctly to the caller (e.g. + a dedicated exception type or error code) so a UI can prompt for + re-entry without retrying PACE blindly. + +### 4.3 GA — Get Encrypted Nonce + +``` +10 86 00 00 02 7C 00 00 ← CLA = 10 (chaining) +``` + +Response: `7C 22 80 20 90 00`. + +Decrypt the nonce with an AES-256 key derived from the CAN: + +``` +nonceKey = SHA-256( CAN-bytes-utf8 || 00 00 00 03 ) ← full 32-byte digest +nonce = AES-CBC-Decrypt(nonceKey, IV = 16×0x00, encryptedNonce) +``` + +(`0x03` is the constant for "nonce decryption key" in the PACE KDF — see +also `0x01` for K_enc and `0x02` for K_mac in §4.5. The full SHA-256 output +is used as the AES-256 key — do not truncate to 16 bytes.) + +> **Deviation from BSI TR-03110.** The standard PACE-GM nonce `s` is one +> AES block — 16 bytes — regardless of key size, and the encrypted-nonce +> response is therefore 16 bytes. This card returns a **two-block** +> (32-byte) ciphertext, decrypts to 32 bytes of plaintext, and §4.4 uses +> the entire 32-byte plaintext as the integer scalar. A strict BSI +> implementation that hard-codes a 16-byte nonce assumption (truncating +> ciphertext or scalar) will compute a different mapped base point than +> the card and the handshake will fail at GA Mutual Authentication. +> Use the full 32-byte block on this card. + +### 4.4 GA — Map Nonce + +All EC points in §4.4–§4.6 use **SEC1 uncompressed encoding**: +`04 || X || Y`, where X and Y are each fixed-width big-endian integers +of the curve's coordinate byte size (32 bytes for 256-bit curves, 48 for +384-bit). Decoders should validate the leading `0x04` byte; PACE-GM +mandates uncompressed form, so other SEC1 prefixes (`02`/`03` +compressed, `00` infinity) should be rejected. + +Generate ephemeral keypair `(d_term, Q_term = d_term · G)` on the curve. +The scalar must be drawn uniformly from `[1, n−1]` where `n` is the +curve order — most ECC libraries provide a helper for this. + +``` +10 86 00 00 45 7C 43 81 41 00 +``` + +Response: `7C 43 82 41 90 00`. + +> Lengths shown (`Lc=0x45`, point=65B) are for the 256-bit curves +> currently observed on LV cards. For a 384-bit PACE curve, points are +> **97 bytes** (uncompressed `04 || X || Y`, two 48-byte coordinates) and +> the inner length tag becomes `0x61` (97), the outer Lc `0x65` (101 = +> 4 + 97). Always derive point size from the curve negotiated in §4.1. + +Compute the mapped base point. `nonce` is the §4.3 plaintext bytes +interpreted as a big-endian integer (the full decrypted block — 32 bytes +for the AES-256 CBC-CMAC variant). All operations are on the EC group: +`·` is scalar multiplication, `+` is **elliptic-curve point addition** +(not coordinate-wise integer addition). + +> The 32-byte nonce, taken as an integer, can in principle exceed the +> curve order `n`. PACE-GM does not require explicit reduction, and +> mainstream EC libraries reduce internally during scalar multiplication +> — `nonce · G` produces the correct point either way. No explicit +> mod-`n` step is needed unless your library rejects oversized scalars. + +``` +H = d_term · Q_card (GM mapping point — BSI calls this H) +G' = nonce · G + H (point addition) +``` + +`H` is **not** the session shared secret — that's `K` in §4.5. `H` is +the intermediate Generic-Mapping point that re-bases the curve before +the second key exchange. Calling both "shared secret" leads to confusion +and bugs; keep them named distinctly when porting. + +### 4.5 GA — Key Agreement + +Generate a second ephemeral keypair on the **mapped** base point: + +``` +d_term2 = random scalar in [1, n−1] +Q_term2 = d_term2 · G' + +10 86 00 00 45 7C 43 83 41 00 +``` + +Response: `7C 43 84 41 90 00`. + +Compute the shared session secret and derive AES-256 session keys. +`K` is the affine X coordinate of the resulting point, encoded as a +**fixed-width big-endian integer of the curve's field byte size**: + +| Curve | Field byte size | `K` length | +|---|---|---| +| `secp256r1` | 32 | 32 B | +| `brainpoolP256r1` | 32 | 32 B | +| `secp384r1` | 48 | 48 B | +| `brainpoolP384r1` | 48 | 48 B | + +Left-pad with zeros if the X integer is shorter than the field size +(rare on uniform inputs but possible). The SHA-256 input length is +therefore `coordSize + 4`. + +> For all four curves listed above the field size and the group-order +> size happen to coincide. **Don't generalise that** to other curves — +> on some curves (e.g. some Koblitz / `sect` curves) field size and +> order size differ, and PACE-GM specifies the *field* size for `K`. + +``` +K = ( d_term2 · Q_card2 ).x ← fixed-width affine X, big-endian +K_enc = SHA-256( K || 00 00 00 01 ) ← full 32-byte digest, AES-256 key +K_mac = SHA-256( K || 00 00 00 02 ) ← full 32-byte digest, AES-256 key +``` + +### 4.6 GA — Mutual Authentication + +Build the auth-token data. The two length bytes track the curve's +point size: + +| Curve family | `7F 49` length | `86` length | `Q` size | +|---|---|---|---| +| 256-bit (`secp256r1`, `brainpoolP256r1`) | `4F` (79) | `41` (65) | 65 B | +| 384-bit (`secp384r1`, `brainpoolP384r1`) | `6F` (111) | `61` (97) | 97 B | + +Both lengths fit in BER short-form for these curves. + +``` +authData = 7F 49 ← public-key info template + 06 0A 04 00 7F 00 07 02 02 04 02 04 ← PACE OID + 86 ← peer's Q from §4.5 +T_term = AES-CMAC(K_mac, authData[with peer's Q = Q_card2])[0..7] +``` + +Bytes shown in the literal example below are the 256-bit form +(`7F 49 4F … 86 41 …`); substitute the 384-bit lengths if working with +P-384 or brainpoolP384r1. + +Send: + +``` +00 86 00 00 0C 7C 0A 85 08 00 ← CLA = 00, no chaining +``` + +Response: `7C 0A 86 08 90 00`. + +Verify: + +``` +T_card_expected = AES-CMAC(K_mac, authData[with peer's Q = Q_term2])[0..7] +must equal T_card returned by the card. +``` + +If the MAC matches, the PACE channel is established. From this point on +**every** APDU must be wrapped per §5. + +### 4.7 Send-Sequence-Counter initialisation + +``` +SSC = 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 (16 bytes, all zero) +``` + +The first SM-protected C-APDU increments this to `…0001` before MAC. + +--- + +## 5. Secure messaging + +After §4 every C-APDU must be wrapped and every R-APDU must be unwrapped. +The CLA byte's bits 4–5 are set (`CLA' = CLA | 0x0C`). Confidentiality: +AES-256-CBC. Integrity: AES-256-CMAC truncated to 8 bytes. + +### 5.1 SSC handling + +The SSC is a 16-byte big-endian integer: byte 0 is the most-significant +byte, byte 15 is the least-significant byte. To increment, start at +**index 15** and propagate the carry **toward index 0** — e.g. +`00 …00 FF` becomes `00 …01 00`, and `FF FF …FF` would wrap to all-zero +(which never happens in practice). + +The counter is incremented **twice per command/response pair**: + +1. Increment **before** computing the C-APDU's MAC. +2. Increment again **before** verifying the R-APDU's MAC. + +### 5.2 IV for AES-CBC + +Each command and each response uses an IV derived from the *current* SSC: + +``` +IV = AES-ECB-Encrypt(K_enc, SSC) ← 16-byte single-block output +``` + +(In the reference implementation the IV is computed by AES-ECB-encrypting +the SSC and truncating to 16 bytes — equivalent to a single-block ECB +encryption.) + +### 5.3 C-APDU wrapping + +Given a plaintext APDU `CLA INS P1 P2 [data] [Le]`: + +1. **Masked header (4 bytes, on-wire form)**: + ``` + maskedHeader = (CLA | 0x0C) || INS || P1 || P2 + ``` + These 4 bytes go into the wrapped APDU unchanged. A *padded* 16-byte + form is computed separately for MAC input in step 4 — it never appears + on the wire. + +2. **Encrypted-data DO** (only if `data` is non-empty): + ``` + plain = data || 80 00 … (pad to the next multiple of 16: + always append at least one 0x80 + byte plus zeros — a 16-byte input + becomes 32 bytes, not 16) + ct = AES-CBC-Encrypt(K_enc, IV from §5.2, plain) + + if INS is even (data is sent to the card — every command on this + card; the off-by-one warning below applies here): + DO_data = 87 01 ct + (Lc' = len(ct) + 1; the 0x01 indicator is counted in Lc'. + Example: 16-byte ct → Lc' = 0x11 (17); + 64-byte ct → Lc' = 0x41 (65). + Off-by-one here is a classic porter mistake.) + + if INS is odd (unreachable on this card; included for completeness): + DO_data = 85 ct (Lc' = len(ct), no indicator) + ``` + The reference implementation emits a **single-byte** length here. BER + long-form (`81 `, `82 `, …) is permitted by the standard + but is not produced by the current code; current payloads (PINs, 48-byte + hash inputs, ~65-byte ECC ciphertexts) all stay under 127 bytes after + SM padding and don't need it. Extend before sending larger plaintexts. + + > In this protocol every wrapped C-APDU sends data with even INS + > (`A4`, `20`, `B0`, `22`, `88`, `2A`, `24`, `2C`, `CB`), so `DO_data` + > is always tag `87`. The `85` branch is included for completeness and + > would be reached only if a future operation used an odd-INS write. + +3. **Le DO** (only if `Le` is present): + ``` + DO_Le = 97 01 + ``` + +4. **MAC**: + ``` + macInput = SSC || pad(maskedHeader, 16) || DO_data || DO_Le + if (length not a multiple of 16) macInput = pad(macInput, 16) ← conditional + MAC = AES-CMAC(K_mac, macInput)[0..7] + DO_MAC = 8E 08 MAC + ``` + Where `pad(x, 16)` = append `0x80`, then `0x00` bytes until length is a + multiple of 16. The 4-byte `maskedHeader` is therefore always padded + into a 16-byte block; the final `pad` call after appending DOs is + *only* applied if the running length isn't already aligned. + + > **Worked example — VERIFY PIN1.** Plaintext APDU `00 20 00 01` with + > 12-byte padded PIN, no Le. + > + > ``` + > maskedHeader (4) = 0C 20 00 01 + > pad(maskedHeader, 16) (16) = 0C 20 00 01 80 00 00 00 00 00 00 00 00 00 00 00 + > plain (12) = + > plain padded (16) = || 80 ← 0x80 added + > ct (16) = AES-CBC-Encrypt(K_enc, IV, plain padded) + > DO_data (19) = 87 11 01 ← Lc' = 0x11 + > DO_Le (0) = (absent — no inner Le) + > + > SSC || paddedHeader || DO_data || DO_Le + > = 16 + 16 + 19 + 0 = 51 bytes ← 51 mod 16 = 3, not aligned + > final pad → 64 bytes (append 80 00 00 00 …) + > AES-CMAC(K_mac, …)[0..7] = 8-byte MAC + > ``` + > + > **Observation.** For every wrapped APDU emitted by this protocol the + > running length before the conditional final pad is always either + > `3 mod 16` (when `DO_Le` is absent) or `6 mod 16` (when `DO_Le` is + > present, adding 3 bytes). The `SSC + paddedHeader` prefix is always + > 32 bytes (aligned), and the smallest `DO_data` is `87 11 01 …` = 19 + > bytes ≡ 3 mod 16 — and longer `DO_data` values stay congruent to 3 + > mod 16. So the running length is **never aligned** and the + > conditional final pad fires every time. + > + > **In practice both ends always pad.** The conditional is dead code + > on this card; treat it as "always pad". Note that ISO/IEC 7816-4 + > SM-MAC actually mandates **unconditional** padding (the `0x80` + > terminator is part of the MAC scheme, not optional). The reference + > implementation's conditional form is technically non-standard but + > equivalent here because the conditional never short-circuits. A + > clean port should just unconditionally pad both C-APDU and R-APDU + > MAC inputs (matching the unconditional R-APDU branch in §5.4). + +5. **Wrapped C-APDU**: + ``` + (CLA|0x0C) INS P1 P2 DO_data DO_Le DO_MAC 00 + ``` + - `newLc = len(DO_data) + len(DO_Le) + len(DO_MAC)`. This is the + **outer ISO 7816-4 Lc** (case 3 short-form) — a single byte, valid + range 1..255. For `newLc > 255` an ISO 7816-4 **extended-length + APDU** would be needed (`Lc` encoded as `00 `, three + bytes — not BER long-form). IDEMIA cards over NFC commonly reject + extended-length APDUs (see §6); in practice every wrapped C-APDU + this card receives stays well under the 255-byte short-form limit. + - **Le = `0x00` is appended unconditionally** after the body (request all + remaining bytes). This trailing byte is the SM-layer Le (asks the + card to return its SM-wrapped response) and is **independent** of + the inner `DO_Le = 97 01 ` of step 3, which carries the + application-level Le from the plaintext APDU. + +> **Scope note.** Every wrapped C-APDU emitted by this protocol either +> carries data (most APDUs) or carries an inner Le (`READ BINARY`, +> `INTERNAL AUTHENTICATE`, `PSO COMPUTE`, `PSO DECIPHER`, `GET DATA`). +> The "no data and no Le" branch is not reachable on this card — there's +> no need to special-case it. AES-CMAC over the resulting 32-byte +> aligned `SSC || pad(maskedHeader, 16)` would also work fine if it +> ever did fire. + +### 5.4 R-APDU unwrapping + +A protected response has the layout: + +``` +[ DO_85_or_87 ] [ DO_99 status ] DO_8E mac 90 00 +``` + +1. If the first tag is `85` or `87`: + - Read length byte. If high bit is set (`0x81`, `0x82`, …) read the + additional length bytes per BER. + - For tag `87`: skip the leading `01` indicator byte (decrement length). + - Decrypt body with `AES-CBC-Decrypt(K_enc, IV from §5.2)`. + - Strip ISO 7816-4 padding: scan **from the end** of the decrypted + buffer toward the start, find the last `0x80` byte (it terminates + the padding `80 00…00` suffix), and return everything before it. + Scanning from the start is wrong — the plaintext can legitimately + contain `0x80` bytes earlier in the buffer. + +2. If the next tag is `99 02 90 00`, consume it. Any other status word + inside SM should be treated as an error. + +3. Tag `8E 08 ` must verify: + + ``` + SM R-APDU layout: + + ┌──────────── responsePrefix ───────────┐ + │ │ + [ DO_85_or_87 ……… ] [ DO_99 02 90 00 ] [ 8E 08 ] 90 00 + ←─── encrypted body ─→ ← inner status → ←──── MAC ────→ ← outer SW + (unprotected, + not in MAC) + + verifyInput = SSC || responsePrefix + || 80 00 … ← unconditional ISO 7816-4 pad + (always at least one 0x80 byte; + if the running length is already + a multiple of 16, a full 16-byte + 80 00 … 00 block is appended) + expectedMAC = AES-CMAC(K_mac, verifyInput)[0..7] + ``` + + The trailing `90 00` is **outside** SM and is **not** part of the + MAC input. `responsePrefix` includes the encrypted-body DO and the + inner DO_99 status word (when present); it does not include the + `8E` tag, the MAC bytes, or the unprotected `90 00`. + + **Prose form (in case the box-drawing diagram doesn't render).** + `responsePrefix` is the concatenation of the encrypted-body DO + (`87 …` or `85 …`) and the inner DO_99 (`99 02 90 00`) if present; + it excludes the `8E` MAC tag and value, and excludes the trailing + unprotected `90 00`. + + (Recall: SSC has been incremented per §5.1.) + + > Note: this is **asymmetric** with the C-APDU MAC of §5.3 step 4, + > where padding is applied only when the length is not already a + > multiple of 16. The reference implementation pads conditionally on + > C-APDUs and unconditionally on R-APDUs; both work in practice + > against the LV card. + +4. The trailing `90 00` outside SM is the unprotected SW. + +If any of these checks fail, abort the session — the channel is no longer +trustworthy. + +--- + +## 6. Files used by the LV card + +| FID / Path | Description | SELECT | +|---|---|---| +| `01 1C` | EF.CardAccess (PACE params, ASN.1) | `00 A4 02 0C 02 01 1C` (after MAIN AID) | +| `50 00 / 50 01` | Personal code (UTF-8) | `00 A4 01 0C 02 50 00`, then `00 A4 02 0C 02 50 01` | +| `AD F1 34 01` | Authentication X.509 cert | `00 A4 09 0C 04 AD F1 34 01` (after MAIN AID, P1=`09` = "select by path") | +| `AD F2 34 1F` | Signing X.509 cert | `00 A4 09 0C 04 AD F2 34 1F` | +| `50 31` | EF.OD (PKCS#15 ObjectDirectory) — only used by §13 | `00 A4 02 0C 02 50 31` | + +### READ BINARY chunking (used everywhere) + +``` +loop: + response = transmit( 00 B0 00 ) + accumulate response + offset += len(response) +until SW = 6B 00 (offset out of range — end of file) + or SW = 6A 82 (file not found — treat as empty) +``` + +The whole loop happens **inside** secure messaging once §4 has completed. + +#### Notes for porters + +- Use short-form `Le = 00` only — do not switch to extended `Le = 00 00` + unless you've confirmed the card accepts it. IDEMIA cards commonly + reject extended-length APDUs over NFC. +- The card may return **fewer** bytes than `Le` requested. This is not + an error. Always advance the offset by `response.length`, never by a + fixed 256. +- Chunk size is determined by the card's internal record size, T=CL + frame negotiation, and SM overhead — not by your `Le`. Different + transports yield different chunk sizes (often well below 256 bytes); + the loop must not assume any particular value. +- **`SW1 = 0x61, SW2 = ` requires GET RESPONSE.** When the card + signals `61 xx` ("`xx` more bytes available"), the read isn't finished + — you must immediately issue an unencrypted `00 C0 00 00 ` (GET + RESPONSE), concatenate the body of that response with the body + preceding the `61 xx`, treat the combined buffer as the (single) + SM-wrapped response, then continue your read loop. Higher-level + transports that wrap ISO 7816-4 (typical OS-level NFC APIs) usually + handle this transparently and you can ignore it. Raw transports do + not — you have to implement the GET RESPONSE branch yourself, and + forgetting it manifests as truncated data with no obvious error. + + > **The fragments are not independently MAC'd.** On this card, an + > SM-wrapped response that exceeds one transport frame is split at + > the transport layer (T=CL) but the **logical SM message is a single + > unit with one DO_8E MAC at its end**. The partial body that arrives + > before `61 xx` does not carry its own MAC; you concatenate raw bytes + > (not authenticated chunks), and §5.4 verifies the single MAC over + > the reassembled whole. +- Terminate the read **only** on `6B 00` (offset past EOF) or `6A 82` + (file not found / empty). Do not terminate on a short response — it + just means the card chose a smaller chunk this round. +- P1/P2 encode a 16-bit offset (max `FF FF` = 65535 bytes). All LV files + in this spec fit well within 64 KB. For files > 64 KB you'd need + READ BINARY ODD (`INS = B1`) with an offset DO; this card has no such + files, so a porter doesn't need to implement that variant. + +--- + +## 7. PIN model + +| Code | VERIFY P2 | Retry-counter ref | Allowed length | Notes | +|---|---|---|---|---| +| PIN1 | `0x01` | `0x01` | 4–12 | Auth + decrypt + cert ops; verify after MAIN or Oberthur AID | +| PIN2 | `0x85` | `0x05` | 6–12 | Signing only; verify after QSCD AID | +| PUK | `0x02` | `0x02` | 8–12 | Unblock; verify after MAIN AID | + +All PIN values are right-padded with `0xFF` to **12 bytes** before +transmission. + +### 7.1 Verify PIN + +``` +00 20 00 0C +``` + +| SW | Meaning | +|---|---| +| `90 00` | Success | +| `63 C2` | Wrong PIN, 2 tries left | +| `63 C1` | Wrong PIN, 1 try left | +| `63 C0` | Wrong PIN, **this attempt exhausted the counter** — the PIN is now blocked (use PUK). Distinct from `69 83` for diagnostic logging; UX-equivalent. | +| `69 83` | PIN already blocked / authentication method blocked — no attempt was processed (counter was already at zero before this VERIFY). | +| `63 00` | Wrong PIN, generic / counter not reported. | + +### 7.2 Read retry counter + +``` +SELECT MAIN AID (or QSCD AID for PIN2) +00 CB 3F FF 0A 4D 08 70 06 BF 81 02 A0 80 00 +``` + +`` is the *retry-counter ref* from the table above +(`01`/`05`/`02`). The retry counter is byte **13** (0-based) of the +SM-decrypted plaintext response — i.e. read it after §5.4 unwrapping, +not from the raw on-wire bytes. + +> **Firmware caveat.** The reference implementation hard-codes offset +> 13; the surrounding bytes are a BER-TLV structure that mirrors the +> request template. On a fresh port, log the full plaintext response on +> the first run, locate the retry-counter byte by hand, and confirm it +> lives at index 13 on your card before trusting this offset. Treat it +> as firmware-dependent. +> +> **Robust alternative.** Walk the TLV instead of hard-coding 13. The +> response mirrors the request template `4D 08 70 06 BF 81 …`, +> with the retry counter inside the `BF 81 ` envelope. Find +> `4D` → `70` → `BF 81 ` → first primitive INTEGER-shaped child +> and read that byte. This survives small layout shifts (extra optional +> fields, reordered children) that would invalidate the magic offset. + +### 7.3 Change PIN + +``` +SELECT MAIN AID (or QSCD AID for PIN2) +00 24 00 18 +``` + +`` is the same value as the VERIFY P2 (`0x01` for PIN1, `0x85` +for PIN2, `0x02` for PUK). + +### 7.4 Unblock + change PIN with PUK + +``` +SELECT MAIN AID ← PUK lives in MAIN context +VERIFY PUK (§7.1, P2 = 0x02) +if changing PIN2: SELECT QSCD AID +00 2C 02 0C +``` + +`` is `0x01` for PIN1, `0x85` for PIN2. + +The leading SELECT MAIN AID is required regardless of caller-side state. +Skipping it relies on the active AID happening to be MAIN, which is true +right after PACE but not after sequences that have selected QSCD in +between (e.g. reading PIN2's retry counter, which lives under QSCD). +Always select MAIN first. + +--- + +## 8. Reading certificates + +(Same flow for AUTH and SIGN; only the path differs.) + +``` +SELECT MAIN AID +SELECT cert by path: + Auth: 00 A4 09 0C 04 AD F1 34 01 + Sign: 00 A4 09 0C 04 AD F2 34 1F +READ BINARY chunked (§6) until 6B 00 +``` + +Result is the DER-encoded X.509 certificate. + +--- + +## 9. Authentication (PIN1 → key 0x82) + +``` +SELECT Oberthur AID +VERIFY PIN1 (§7.1, P2 = 0x01) +MSE SET AT: + 00 22 41 A4 06 80 01 04 84 01 82 +INTERNAL AUTHENTICATE: + 00 88 00 00 00 +``` + +- `MSE SET AT` body: `80 01 04` → algorithm reference `0x04`; + `84 01 82` → key reference `0x82`. +- The signing operation here is **INTERNAL AUTHENTICATE** (`INS 0x88`, + ISO 7816-4 §7.5.5) — distinct from the `GENERAL AUTHENTICATE` + (`INS 0x86`) used during the PACE handshake in §4. The card signs the + caller-supplied `` with the auth key and returns the + signature directly. +- The card returns its response as a raw ECDSA signature `r || s` — + **96 bytes** total (48 + 48 for `secp384r1`). +- **`` is sent unmodified.** The card does **not** hash + internally and does **not** zero-pad (unlike §10). The caller is + responsible for the digest / format. For a Web-eID-style auth + challenge against the `secp384r1` user keys, that's typically a + 48-byte SHA-384 hash; the card signs it as-is and returns + `r || s` (96 bytes). + +> **LV vs Estonian:** Estonian IDEMIA uses a 4-byte algorithm reference +> `FF 20 08 00`; LV uses a 1-byte `0x04`. Length bytes must match +> (`80 01 04` vs `80 04 FF 20 08 00`). Do not copy Estonian code blindly. + +--- + +## 10. Signing (PIN2 → key 0x9E) + +``` +SELECT QSCD AID +VERIFY PIN2 (§7.1, P2 = 0x85) +MSE SET DST: + 00 22 41 B6 06 80 01 54 84 01 9E +PSO COMPUTE DIGITAL SIGNATURE: + 00 2A 9E 9A 00 +``` + +- `MSE SET DST` body: algorithm `0x54`, key `0x9E`. +- **Hash padding:** PSO COMPUTE on this card expects exactly **48 bytes** + of input. Shorter hashes (e.g. SHA-256, 32 bytes) must be **left-padded + with zero bytes to 48 bytes** before transmission — i.e. zeros first, + hash second: + + ``` + Input to PSO COMPUTE for SHA-256 digest H (32 bytes): + 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ← 16 zero bytes + H[0] H[1] … H[31] ← 32-byte digest + ─── + 48 bytes total + ``` + + Hashes already ≥ 48 bytes (SHA-384, or SHA-512 truncated to 48) are + passed through unchanged. (The 48-byte requirement is a downstream + consequence of the user signing key being `secp384r1`.) + + > **Why left-pad.** The card performs raw ECDSA on the input + > interpreted as a big-endian integer. Leading-zero bytes are + > mathematically inert — `0x00…00 || H` and `H` represent the same + > integer. Right-padding (or any other extension) would change the + > integer value and yield a different signature; left-padding with + > zeros does not. A useful corollary: it doesn't matter if the hash + > itself happens to start with a `0x00` byte (e.g. roughly 1 in 256 + > SHA-256 outputs do) — the resulting integer is the same. + > + > **Hashes longer than 48 bytes** (e.g. raw SHA-512, 64 bytes) are + > unspecified. The reference impl passes them through; the card may + > truncate to the first 48 bytes (per FIPS 186-4 ECDSA convention), + > reject the input, or behave unpredictably. Not exercised on this + > branch — truncate caller-side to 48 bytes if you need a + > deterministic outcome. +- Response is the raw ECDSA signature `r || s` — **96 bytes** total + (48 + 48 for `secp384r1`). + +--- + +## 11. Decryption (PIN1 → key 0x82) + +> ⚠ **Unverified path.** Included for completeness; **not exercised by +> the reference tests on this branch**. The byte-level APDU sequence +> below matches the reference codebase, but the upstream-level +> characterisation of what the card is actually doing (raw ECDH / +> ECKA — see further down) has not been verified against a known-good +> ciphertext on this branch. Verify before relying on this section. + +``` +SELECT Oberthur AID +VERIFY PIN1 (§7.1, P2 = 0x01) +MSE SET CT: + 00 22 41 B8 06 80 01 04 84 01 82 +PSO DECIPHER: + 00 2A 80 86 00 00 ← leading 0x00 is the encrypted-message indicator +``` + +The leading `0x00` byte before the ciphertext is required — it marks the +input as an encrypted message (not a hash). + +**What this operation actually does.** `MSE SET CT (algo 0x04, key 0x82)` +followed by `PSO DECIPHER` with the leading `0x00` indicator is, on +IAS-ECC IDEMIA cards, the **raw ECDH / ECKA** primitive: the input is +an ephemeral peer SEC1 point (`04 || X || Y`, 97 bytes for `secp384r1` +user keys), and the card returns the shared-secret X coordinate. The +host then derives a content-decryption key from that secret per the +application's encryption scheme. (One concrete consumer is CDOC2, the +encrypted-container format used by the broader DigiDoc ecosystem from +which this library originates; other applications can layer arbitrary +schemes on top of the same ECKA primitive.) + +The reference codebase exposes this method on its token interface but +the demo app does not exercise it. If you have no specific ciphertext +format to interoperate with, you can skip this section. + +> Verify against a known good ciphertext before relying on the +> characterisation above — it matches standard IAS-ECC behaviour but is +> not exercised by the reference test path on this branch. + +--- + +## 12. Personal data extraction + +LV stores **only the personal code on-card**; everything else (name, +issuing country, document number, certificate expiry) comes from the +auth certificate's subject DN and `Validity` field. + +> **Cardholder citizenship is not exposed by LV cards over NFC.** The +> cert subject's `C` RDN is the **issuing country** of the certificate +> authority (`LV` on a Latvian eID), not the cardholder's nationality — +> in practice they coincide for citizen-issued eID, but a foreign +> resident's LV-issued card would still carry `C=LV`. Treat the two as +> distinct: do not surface the cert `C` value to users under a +> "citizenship" label. + +> **Certificate expiry vs document expiry.** What is read here is the +> **auth certificate's `notAfter`**, which is typically shorter than the +> physical-card validity printed on the document. LV cards do not expose +> the document expiry over NFC; if your application needs the document +> expiry it must come from a different source (visual inspection, MRZ +> read, or out-of-band data). + +### 12.1 Read the personal code + +``` +SELECT MAIN AID +00 A4 01 0C 02 50 00 ← SELECT DF 0x5000 +00 A4 02 0C 02 50 01 ← SELECT EF 0x5001 +00 B0 00 00 00 ← single-shot READ BINARY (Le=0x00 = up to 256 + bytes; the EF body is ~12 bytes — fits in one + APDU, no chunking needed) +``` + +Strip any trailing `0xFF` bytes (CardOS unused-space padding on +fixed-size EFs) **before** decoding — most string-trimming primitives +operate on whitespace only and won't remove `0xFF`. Then decode the +remaining bytes as UTF-8 and trim ASCII whitespace. + +> If a future card revision puts more than ~250 bytes in EF 0x5001, the +> single-shot read above silently truncates. Switch to the §6 chunked +> loop (terminate on `6B 00`) for any file you don't have a hard +> upper-bound size for. + +### 12.2 Parse the auth certificate subject DN + +Read the auth certificate (§8), parse it as X.509, and extract the +following from the subject DN: + +| RDN OID | Field | Notes | +|---|---|---| +| `2.5.4.4` | surname | | +| `2.5.4.42` | givenName | | +| `2.5.4.5` | serialNumber | format `PNOLV-` | +| `2.5.4.6` (RFC2253 short name `C`) | issuing country | ISO 3166-1 alpha-2 — `LV` on a Latvian eID. **Not** the cardholder's citizenship — see the note in §12. | +| `Validity.notAfter` (X.509 field) | certificate expiry date | not in the DN. This is the auth-cert validity, not the document expiry. | + +The library uses the auth-cert `serialNumber` RDN value (e.g. +`PNOLV-`) as the document number — there is no separate +document-number field on the card. + +#### Recommended: parse the X.500 name structurally + +Use your X.509 library's "RDN by OID" accessor — every mainstream stack +has one — and call it for each OID in the table above. You should not +need to handle DER tag bytes, BER lengths, or RFC 2253 escape sequences +yourself; the library returns each RDN value already decoded to a +native string regardless of whether the source DER encoding was +`UTF8String`, `PrintableString`, `BMPString`, etc. (See §16 for the +concrete Java implementation used in this codebase.) + +#### Fallback: parsing RFC2253 hex-encoded values + +If you must work with the RFC2253 string form (e.g. from +`X500Principal.getName(RFC2253)`), non-ASCII RDN values come back as +`#`-prefixed DER hex: + +``` +2.5.4.4=#0C0A4B7572756B73206265726E73 ← UTF8String "Kuruks berns" +``` + +To decode: +1. Drop the leading `#`. +2. Hex-decode the rest. +3. The first byte is the DER tag (`0x0C` = UTF8String). The next byte is + the length (BER short form), or `0x81 ` (long form with 1 length + byte). Skip those bytes. +4. The remaining bytes are UTF-8 text. + +The string form also requires care with escaped commas inside multi-valued +RDN strings, escaped backslashes, and short-name-vs-OID variation. The +parsed-X500Name path avoids all of this. + +### 12.3 Date of birth from the personal code + +The Latvian personal code carries DOB only in the **old format**. + +Callers should pass the code in canonical form (`DDMMYY-CZZZQ`, with or +without the dash; no surrounding whitespace) — typically the trimmed +UTF-8 output of §12.1. Whitespace handling and Unicode normalisation +are out of scope for the parser. + +> **Do not confuse with the Estonian personal code scheme.** Estonia's +> personal identification code uses a *gender + century* leading digit +> (`1`/`2` → 19th c., `3`/`4` → 20th c., `5`/`6` → 21st c.). Latvia uses +> a *century-only* digit at position 6, with no gender encoding. +> Applying the Estonian rules to a Latvian code yields wrong DOBs. +> Canonical specification is the responsibility of Latvia's PMLP +> (Pilsonības un migrācijas lietu pārvalde — Office of Citizenship and +> Migration Affairs); reference Latvian secondary law if you need to +> validate edge cases. + +> **New-format detector is restrictive.** This spec checks for `32` as +> the leading two digits of the post-2017 format. If Latvia ever +> introduces additional new-format prefixes (e.g. `33…`), the parser +> will fall through to the old-format branch, fail the century-digit +> check at position 6, and return null. That's safe (no wrong DOB +> emitted) but it's not future-proof — revisit this rule when new +> formats are introduced. + +1. Strip dashes from the personal code. +2. If the digit string starts with `32`, the code is post-2017 format: + DOB is **not encoded**, return null. +3. Otherwise (old format `DDMMYY-CZZZQ`): + + | Index | Field | + |---|---| + | 0..1 | day | + | 2..3 | month | + | 4..5 | year (2-digit) | + | 6 | century digit | + + Century digit: `0` → 1800, `1` → 1900, `2` → 2000. Anything else is + invalid — return null and surface a parse error in logs. + + ``` + DOB = (century + yearShort) || "-" || month || "-" || day (ISO 8601) + ``` + +--- + +## 13. Optional: dynamic key-reference discovery (PrKDF) + +The current LV implementation hard-codes `authKeyRef = 0x82` and +`signKeyRef = 0x9E`, so this section is reference material for porters +faced with a card variant whose key slots are unknown. + +> **This is a deliberately minimal walker, not a robust PKCS#15 parser.** +> It assumes a single conformant PrKDF, takes the **first** matching tag +> at every level, and ignores anything else. Treat it as a starting +> point: if you point it at a card whose PKCS#15 layout differs (multiple +> private-key entries, optional fields reordered, RSA mixed with ECC, +> etc.) it will silently return the wrong key reference. Validate +> against your target card before relying on it. + +> **Per-applet PrKDF.** The auth and sign keys on this card live in +> **different applet contexts**: the auth key (`0x82`) is registered in +> the Oberthur AWP applet's PrKDF, the sign key (`0x9E`) in the QSCD +> applet's PrKDF. Each applet has its own EF.OD → PrKDF chain. That's +> why the SELECT step below is parameterised — Oberthur for auth-key +> discovery, QSCD for sign-key discovery — and why running the walk +> under the wrong AID returns the other key (or no key at all). + +``` +SELECT (Oberthur for auth, QSCD for sign) +00 A4 02 0C 02 50 31 ← SELECT EF.OD +READ BINARY chunked (§6) +``` + +Parse the EF.OD as TLVs: + +1. Find a top-level `A0` (PrivateKey directory entry). +2. Inside, find a `30` (SEQUENCE). +3. Inside that, find a 2-byte `04` (OCTET STRING) — that is the PrKDF + file id. + +``` +00 A4 02 0C 02 +READ BINARY chunked (§6) +``` + +Iterate the top-level SEQUENCE entries of PrKDF. For each entry, child[1] +is `CommonKeyAttributes`. Inside that SEQUENCE, find an INTEGER (`02`): + +- Length 1 → byte is the key reference. +- Length 2 → bytes are `00 ` (DER positive padding for refs ≥ `0x80`) + → byte[1] is the key reference. + +Use the first key ref found per AID context (auth in Oberthur, sign in +QSCD). + +--- + +## 14. End-to-end session sketch + +A complete "card-info + sign" session, with literal step ordering: + +``` +1. Connect NfcA, read historical bytes; match against §2. +2. SELECT MAIN AID (§3) +3. PACE handshake using user-entered CAN (§4) +4. Now SM is on; every following APDU is wrapped per §5. +5. Read auth cert: SELECT MAIN, SELECT path AD F1 34 01, READ BINARY chunks. +6. Read sign cert: SELECT MAIN, SELECT path AD F2 34 1F, READ BINARY chunks. +7. Read personal code: SELECT DF 5000, SELECT EF 5001, single-shot + READ BINARY (~12 bytes); strip trailing 0xFF and decode UTF-8. + See §12.1 — the single-shot read assumes the file fits in one + response and would need to switch to §6 chunked READ BINARY if the + file ever grows beyond that. +8. (For card view) Read PIN1 retry counter (§7.2). +9. (For sign) + SELECT QSCD AID + VERIFY PIN2 (§7.1) + MSE SET DST + PSO COMPUTE (§10) +10. (For auth) + SELECT Oberthur AID + VERIFY PIN1 (§7.1) + MSE SET AT + INTERNAL AUTHENTICATE (§9; INS 0x88 — not the + GENERAL AUTHENTICATE 0x86 + used during PACE) +11. Disconnect / let the card field drop. +``` + +If the user re-taps after a disconnection, restart from step 1 — PACE +keys do not survive the loss of the contactless field. + +--- + +## 15. Reference checklist for porters + +Use this list to validate a fresh implementation against a physical LV +card: + +- [ ] Historical bytes match exactly one entry in §2. +- [ ] PACE MSE SET AT (§4.2) returns `90 00` with the right CAN, `63 00` + with a wrong CAN. +- [ ] **First post-PACE APDU is SM-wrapped.** The on-wire CLA byte has + `0x0C` set, the body contains a `8E 08 …` MAC tag, and the + response is similarly wrapped — i.e. you have not silently fallen + through to plaintext (which IDEMIA permits for some unprotected + files and would mask a broken SM implementation by letting cert + reads work anyway). +- [ ] After PACE, the auth certificate (§8) reads as a valid DER X.509. +- [ ] The auth cert subject contains `2.5.4.5 = PNOLV-`, + and the on-card EF 0x5001 contains the same ``. +- [ ] The auth cert subject `2.5.4.6 (C)` is `LV` and is treated as + **issuing country**, not citizenship (§12). +- [ ] PIN1 retry counter (§7.2) reads in 0..3 and decrements after a wrong + VERIFY. +- [ ] Auth (§9) returns a **96-byte** ECDSA signature (`r || s`, 48 + 48 + bytes) — the user keys are `secp384r1`, independent of whichever + 256-bit curve PACE used. +- [ ] Signing (§10) returns a **96-byte** ECDSA signature on a SHA-256 + hash that has been left-padded with zeros to 48 bytes per §10. +- [ ] Old-format personal code (e.g. `010195-12345`) parses to + `1995-01-01`; new-format (`32xxxxxx`) yields no DOB. +- [ ] PUK + new PIN flow (§7.4) succeeds for both PIN1 and PIN2. + +--- + +## 16. Reference implementation (Java/Android) + +The protocol description above stands on its own. This section points +at one concrete implementation — the Java/Android codebase from which +the spec was derived — for cross-checking. A port to any other platform +should follow the spec proper, not these files. + +Source-of-truth Java classes used to derive this spec: + +| File | Role | +|---|---| +| `libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/TokenWithPace.java` | ATR table → dispatch | +| `libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/Idemia.java` | AIDs, cert paths, PIN refs and padding, retry counter, change/unblock | +| `libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/IdemiaWithPace.java` | PACE handshake, secure messaging, dynamic key-ref discovery | +| `libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/LatviaIdemiaWithPace.java` | LV-specific MSE values, key refs, personal-data flow | +| `libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/LatviaPersonalDataParser.java` | Personal-code → DOB | + +If this spec and the code disagree, the code is authoritative — please open +a PR to fix the spec. diff --git a/LICENSE b/LICENSE index 56dab5e..19e3071 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,504 @@ -MIT License - -Copyright (c) 2023 E-government building blocks - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +(This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.) + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + {description} + Copyright (C) {year} {fullname} + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 + USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random + Hacker. + + {signature of Ty Coon}, 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/README.md b/README.md index e01bc3e..7a5b827 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ - [Testing with the Demo App](#testing-with-the-demo-app) - [Using the Libraries in Other Applications](#using-the-libraries-in-other-applications) - [Building the AAR](#building-the-aar) + - [Overriding the AAR Filename](#overriding-the-aar-filename) - [Overview](#overview) - [NFC Interface](#nfc-interface) - [General Communication Scheme](#general-communication-scheme) @@ -97,6 +98,31 @@ implementation("org.bouncycastle:bcprov-jdk18on:1.86") implementation("org.jetbrains.kotlin:kotlin-stdlib") ``` +#### Overriding the AAR Filename + +By default the build produces `id-card-lib.aar`, `smart-card-reader-lib.aar`, and `card-utils-lib.aar`. +To stamp a version number and/or a custom suffix into the filename (useful when +distributing internal builds side-by-side, or when consumers need to pin an +exact build), create an `environment.properties` file at the repository root: + +```properties +# environment.properties +version=1.1.4 +suffix=internal +``` + +A template is checked in as `environment.properties.example`. Both keys are +optional and independent: + +* `version` only → `id-card-lib-1.1.4.aar` +* `suffix` only → `id-card-lib-internal.aar` +* both → `id-card-lib-1.1.4-internal.aar` +* file missing / blank → `id-card-lib.aar` (default) + +The override applies to every Android library subproject under `libs/` and is +wired up in `libs/build.gradle.kts`. `environment.properties` is gitignored, so +local overrides do not leak into commits. + ## Overview ID card support for Android applications is based on three libraries: `id-card-lib`, `smart-card-reader-lib` and `card-utils-lib`. @@ -163,12 +189,27 @@ public interface TokenWithPace extends Token { void tunnel(String can) throws SmartCardReaderException; static TokenWithPace create(NfcSmartCardReader reader) throws SmartCardReaderException { } + static TokenWithPace create(NfcSmartCardReader reader, TokenWithPaceConfig config) throws SmartCardReaderException { + } } ``` The `TokenWithPace` interface enables NFC communication with the ID card. An instance is obtained via -its `create` factory method, which selects the correct implementation based on the card's ATS (*Answer To Select*). -Currently, two NFC-enabled ID card types are supported: IDEMIA and Thales, implemented as `IdemiaWithPace` and `ThalesWithPace`. +its `create` factory method, which selects the correct implementation based on the card's ATS (*Answer To Select*) +and the `TokenWithPaceConfig` allow-list passed by the integrator. +Three NFC-enabled ID card types are currently supported: + +| Card | Implementation | +|---|---| +| Estonian IDEMIA (ID1) | `IdemiaWithPace` | +| Estonian Thales | `ThalesWithPace` | +| Latvian IDEMIA | `LatviaIdemiaWithPace` (extends `IdemiaWithPace`) | + +If the card's ATS does not match any of these, `create` throws a `NotSupportedException` +(see [Exception Handling](#exception-handling)). + +`create(reader)` without a `TokenWithPaceConfig` accepts only the Estonian cards (`ID1` and `THALES`), +as in earlier versions of the library. After creating the instance, establish the communication channel using the card’s `CAN` code and the `tunnel` method. @@ -195,11 +236,15 @@ The functions are defined in the `Token` interface. Below is an example of reading the personal data file from the ID card when an instance of `NfcSmartCardReaderManager` has already been created. ```kotlin +private val tokenConfig = TokenWithPaceConfig.Builder() + .allow(CardType.ID1, CardType.THALES) + .build() + private fun readCardData() { checkNfcStatus(nfcSmartCardReaderManager.startDiscovery(requireActivity()) { nfcReader, exc -> if ((nfcReader != null) && (exc == null)) { try { - val card = TokenWithPace.create(nfcReader) + val card = TokenWithPace.create(nfcReader, tokenConfig) card.tunnel(dataViewModel.getCan()) val cardData = card.personalData() } catch (ex: SmartCardReaderException) { @@ -212,13 +257,14 @@ private fun readCardData() { } ``` -* **Line 2:** Uses the `startDiscovery` method, which internally uses `android.nfc.NfcAdapter.enableReaderMode` to detect NFC tags. The returned `NfcStatus` value is processed. -* **Line 3:** The `startDiscovery` method relies on the `NfcSmartCardReaderCallback` interface; if no exception is present and an `NfcSmartCardReader` instance exists, processing continues. -* **Line 5:** Creates an instance implementing the `TokenWithPace` interface. -* **Line 6:** Uses the card’s `CAN` code to establish a secure NFC connection between the card and the device. -* **Line 7:** Uses ID card functionality to read the personal data file. -* **Line 8:** Any of the above operations may result in a `SmartCardReaderException`. -* **Line 11:** Stops waiting for NFC tags. +* **Lines 1–3:** Configure which card types the app accepts. Passing a `TokenWithPaceConfig` with only the card types you actually support is recommended so that a future library release that adds another country/variant cannot silently widen the set of cards your app reads. To opt in to every supported type explicitly, use `TokenWithPaceConfig.allowAll()`. +* **Line 6:** Uses the `startDiscovery` method, which internally uses `android.nfc.NfcAdapter.enableReaderMode` to detect NFC tags. The returned `NfcStatus` value is processed. +* **Line 7:** The `startDiscovery` method relies on the `NfcSmartCardReaderCallback` interface; if no exception is present and an `NfcSmartCardReader` instance exists, processing continues. +* **Line 9:** Creates an instance implementing the `TokenWithPace` interface. The card's ATS historical bytes are matched against the library's supported set; if the detected `CardType` is not in `tokenConfig.allowedCardTypes()`, a `NotSupportedException` is thrown immediately (no PACE handshake is attempted). +* **Line 10:** Uses the card's `CAN` code to establish a secure NFC connection between the card and the device. +* **Line 11:** Uses ID card functionality to read the personal data file. +* **Line 12:** Any of the above operations may result in a `SmartCardReaderException`. +* **Line 15:** Stops waiting for NFC tags. ### NFC Interface Status @@ -250,7 +296,9 @@ The following example demonstrates exception handling during the ID card communi ```kotlin private fun exceptionHandler(ex: SmartCardReaderException) { - if (ex is CodeVerificationException) { + if (ex is NotSupportedException) { + ... + } else if (ex is CodeVerificationException) { ... } else if (ex is PaceTunnelException) { ... @@ -269,14 +317,18 @@ private fun exceptionHandler(ex: SmartCardReaderException) { ``` * **Line 1:** `ee.ria.DigiDoc.smartcardreader.SmartCardReaderException` – base exception from which all ID card–related exceptions inherit. -* **Line 2:** `ee.ria.DigiDoc.idcard.CodeVerificationException` – specific exception indicating that the PIN1 or PIN2 used for authorization was incorrect. +* **Line 2:** `ee.ria.DigiDoc.idcard.NotSupportedException` – thrown by `TokenWithPace.create(...)` when either: + (a) the detected card's ATR/ATS does not match any supported model (e.g. attempting to read a non-Estonian / non-Latvian / non-Thales ID card), or + (b) the detected `CardType` is not in the `TokenWithPaceConfig.allowedCardTypes()` passed to `create()` — for example, an integrator scoped to `{ID1, THALES}` will get this when tapping a `LATVIA_IDEMIA` card. + Catch this case separately to show the user a "card not supported" message rather than a generic communication error. +* **Line 4:** `ee.ria.DigiDoc.idcard.CodeVerificationException` – specific exception indicating that the PIN1 or PIN2 used for authorization was incorrect. The exception includes information on how many attempts remain before the PIN becomes locked. -* **Line 4:** `ee.ria.DigiDoc.idcard.PaceTunnelException` – specific exception indicating that the establishment of a secure communication channel between the card and the device has failed. +* **Line 6:** `ee.ria.DigiDoc.idcard.PaceTunnelException` – specific exception indicating that the establishment of a secure communication channel between the card and the device has failed. Most likely, the issue is caused by an incorrect CAN code. -* **Line 6:** `ee.ria.DigiDoc.idcard.IdCardException` – general exception class for ID card-specific errors that don't fall into other categories. -* **Line 8:** `ee.ria.DigiDoc.smartcardreader.ApduResponseException` – exception indicating an error in the ID card's APDU communication protocol. -* **Line 11:** `android.nfc.TagLostException` – exception indicating that the NFC connection between the card and the device was lost. -* **Line 13:** Any other unexpected exception that triggered the `SmartCardReaderException`. +* **Line 8:** `ee.ria.DigiDoc.idcard.IdCardException` – general exception class for ID card-specific errors that don't fall into other categories. +* **Line 10:** `ee.ria.DigiDoc.smartcardreader.ApduResponseException` – exception indicating an error in the ID card's APDU communication protocol. +* **Line 13:** `android.nfc.TagLostException` – exception indicating that the NFC connection between the card and the device was lost. +* **Line 15:** Any other unexpected exception that triggered the `SmartCardReaderException`. --- diff --git a/demoapp/app/src/main/java/ee/ria/DigiDoc/smartcardreader/nfc/example/card/CardInfoFragment.kt b/demoapp/app/src/main/java/ee/ria/DigiDoc/smartcardreader/nfc/example/card/CardInfoFragment.kt index e4e36fa..edb8116 100644 --- a/demoapp/app/src/main/java/ee/ria/DigiDoc/smartcardreader/nfc/example/card/CardInfoFragment.kt +++ b/demoapp/app/src/main/java/ee/ria/DigiDoc/smartcardreader/nfc/example/card/CardInfoFragment.kt @@ -1,4 +1,5 @@ // SPDX-FileCopyrightText: Estonian Information System Authority +// SPDX-FileCopyrightText: 2026 Stagnation OÜ // SPDX-License-Identifier: LGPL-2.1-or-later package ee.ria.DigiDoc.smartcardreader.nfc.example.card @@ -68,9 +69,20 @@ class CardInfoFragment : Fragment() { surnameTextView.text = getString(R.string.last_name, dataViewModel.getSurname()) personalCodeTextView.text = getString(R.string.personal_code, dataViewModel.getPersonalCode()) - citizenshipTextView.text = getString(R.string.citizenship, dataViewModel.getCitizenship()) - dateOfExpiryTextView.text = - getString(R.string.expiration, dataViewModel.getExpiryDate()) + val citizenship = dataViewModel.getCitizenship() + val issuingCountry = dataViewModel.getIssuingCountry() + citizenshipTextView.text = when { + citizenship.isNotEmpty() -> getString(R.string.citizenship, citizenship) + !issuingCountry.isNullOrEmpty() -> getString(R.string.issuing_country, issuingCountry) + else -> getString(R.string.citizenship, "-") + } + val docExpiry = dataViewModel.getDocumentExpiryDate() + val certExpiry = dataViewModel.getCertExpiryDate() + dateOfExpiryTextView.text = when { + docExpiry != null -> getString(R.string.document_expiry, docExpiry) + certExpiry != null -> getString(R.string.cert_expiry, certExpiry) + else -> getString(R.string.expiration, "-") + } pin1TextView.text = getString(R.string.pin1_counter, dataViewModel.getPin1Counter()) pin2TextView.text = getString(R.string.pin2_counter, dataViewModel.getPin2Counter()) diff --git a/demoapp/app/src/main/java/ee/ria/DigiDoc/smartcardreader/nfc/example/card/CardReaderFragment.kt b/demoapp/app/src/main/java/ee/ria/DigiDoc/smartcardreader/nfc/example/card/CardReaderFragment.kt index 9867c55..8251c91 100644 --- a/demoapp/app/src/main/java/ee/ria/DigiDoc/smartcardreader/nfc/example/card/CardReaderFragment.kt +++ b/demoapp/app/src/main/java/ee/ria/DigiDoc/smartcardreader/nfc/example/card/CardReaderFragment.kt @@ -1,4 +1,5 @@ // SPDX-FileCopyrightText: Estonian Information System Authority +// SPDX-FileCopyrightText: 2026 Stagnation OÜ // SPDX-License-Identifier: LGPL-2.1-or-later package ee.ria.DigiDoc.smartcardreader.nfc.example.card @@ -25,6 +26,7 @@ import ee.ria.DigiDoc.idcard.CodeType import ee.ria.DigiDoc.idcard.CodeVerificationException import ee.ria.DigiDoc.idcard.PaceTunnelException import ee.ria.DigiDoc.idcard.TokenWithPace +import ee.ria.DigiDoc.idcard.TokenWithPaceConfig import ee.ria.DigiDoc.smartcardreader.ApduResponseException import ee.ria.DigiDoc.smartcardreader.CardConnectionLostException import ee.ria.DigiDoc.smartcardreader.SmartCardReaderException @@ -127,7 +129,7 @@ class CardReaderFragment : Fragment() { if ((nfcReader != null) && (exc == null)) { try { // Create card session over NFC - val card = TokenWithPace.create(nfcReader) + val card = TokenWithPace.create(nfcReader, TokenWithPaceConfig.allowAll()) // Establish PACE tunnel with previously captured CAN card.tunnel(dataViewModel.getCan()) // Get auth certificate @@ -200,7 +202,7 @@ class CardReaderFragment : Fragment() { if ((nfcReader != null) && (exc == null)) { try { - val card = TokenWithPace.create(nfcReader) + val card = TokenWithPace.create(nfcReader, TokenWithPaceConfig.allowAll()) card.tunnel(dataViewModel.getCan()) val signerCert = card.certificate(CertificateType.SIGNING) debugLog(logTag, Base64.toBase64String(signerCert)) @@ -218,6 +220,17 @@ class CardReaderFragment : Fragment() { } val message = ex.message ?: "Error communicating with card" errorLog(logTag, message, ex) + } catch (ex: Exception) { + // libdigidocpp throws plain RuntimeException for TSA/OCSP + // network failures inside extendSignatureProfile; without + // this catch the exception escapes the binder thread and + // the UI hangs on the spinner. Surface it as an error. + setReaderResult(R.drawable.error) + val message = ex.message ?: "Signature extension failed" + requireActivity().runOnUiThread { + Toast.makeText(requireContext(), message, Toast.LENGTH_LONG).show() + } + errorLog(logTag, message, ex) } finally { nfcSmartCardReaderManager.disableNfcReaderMode() } @@ -230,7 +243,14 @@ class CardReaderFragment : Fragment() { private fun addSignature(signatureArray: ByteArray) { signature.setSignatureValue(signatureArray) - signature.extendSignatureProfile(Utils.signatureProfile) + if (Utils.extendSignature) { + // Adds XAdES-T timestamp + OCSP. Requires network access to the + // CA endpoints (e.g. dd-at.ria.ee) — toggled off in the container + // UI when offline or when testing card flow without TSA/OCSP. + signature.extendSignatureProfile(Utils.signatureProfile) + } else { + debugLog(logTag, "Skipping signature extension (BES baseline only)") + } container.save() signatureIsAdded = true } @@ -246,7 +266,7 @@ class CardReaderFragment : Fragment() { } if ((nfcReader != null) && (exc == null)) { try { - val card = TokenWithPace.create(nfcReader) + val card = TokenWithPace.create(nfcReader, TokenWithPaceConfig.allowAll()) card.tunnel(dataViewModel.getCan()) val cardData = card.personalData() debugLog(logTag, cardData.toString()) diff --git a/demoapp/app/src/main/java/ee/ria/DigiDoc/smartcardreader/nfc/example/sign/ContainerFragment.kt b/demoapp/app/src/main/java/ee/ria/DigiDoc/smartcardreader/nfc/example/sign/ContainerFragment.kt index 57ecb27..39fb9b4 100644 --- a/demoapp/app/src/main/java/ee/ria/DigiDoc/smartcardreader/nfc/example/sign/ContainerFragment.kt +++ b/demoapp/app/src/main/java/ee/ria/DigiDoc/smartcardreader/nfc/example/sign/ContainerFragment.kt @@ -1,4 +1,5 @@ // SPDX-FileCopyrightText: Estonian Information System Authority +// SPDX-FileCopyrightText: 2026 Stagnation OÜ // SPDX-License-Identifier: LGPL-2.1-or-later package ee.ria.DigiDoc.smartcardreader.nfc.example.sign @@ -103,6 +104,11 @@ class ContainerFragment : Fragment() { addSignatureButton ) + binding.checkBoxExtendSignature.isChecked = Utils.extendSignature + binding.checkBoxExtendSignature.setOnCheckedChangeListener { _, isChecked -> + Utils.extendSignature = isChecked + } + backButton.setOnClickListener { clearData() findNavController().popBackStack(R.id.homeFragment, false) diff --git a/demoapp/app/src/main/java/ee/ria/DigiDoc/smartcardreader/nfc/example/util/Utils.kt b/demoapp/app/src/main/java/ee/ria/DigiDoc/smartcardreader/nfc/example/util/Utils.kt index c971eb1..b647fd3 100644 --- a/demoapp/app/src/main/java/ee/ria/DigiDoc/smartcardreader/nfc/example/util/Utils.kt +++ b/demoapp/app/src/main/java/ee/ria/DigiDoc/smartcardreader/nfc/example/util/Utils.kt @@ -1,4 +1,5 @@ // SPDX-FileCopyrightText: Estonian Information System Authority +// SPDX-FileCopyrightText: 2026 Stagnation OÜ // SPDX-License-Identifier: LGPL-2.1-or-later package ee.ria.DigiDoc.smartcardreader.nfc.example.util @@ -26,6 +27,15 @@ object Utils { lateinit var container: Container lateinit var signature: Signature var signatureProfile = "time-stamp" + + /** + * When true, [Signature.extendSignatureProfile] is called after the card + * signs — adds the XAdES-T timestamp + OCSP, requiring network access to + * the CA endpoints (e.g. dd-at.ria.ee). When false, the signature is left + * at the BES baseline (no network needed). Toggled from the container UI. + */ + var extendSignature = true + var signatureIsAdded = false fun addFileContent( diff --git a/demoapp/app/src/main/java/ee/ria/DigiDoc/smartcardreader/nfc/example/viewmodel/DataViewModel.kt b/demoapp/app/src/main/java/ee/ria/DigiDoc/smartcardreader/nfc/example/viewmodel/DataViewModel.kt index 69e4070..8095beb 100644 --- a/demoapp/app/src/main/java/ee/ria/DigiDoc/smartcardreader/nfc/example/viewmodel/DataViewModel.kt +++ b/demoapp/app/src/main/java/ee/ria/DigiDoc/smartcardreader/nfc/example/viewmodel/DataViewModel.kt @@ -1,4 +1,5 @@ // SPDX-FileCopyrightText: Estonian Information System Authority +// SPDX-FileCopyrightText: 2026 Stagnation OÜ // SPDX-License-Identifier: LGPL-2.1-or-later package ee.ria.DigiDoc.smartcardreader.nfc.example.viewmodel @@ -12,7 +13,9 @@ class DataViewModel : ViewModel() { private lateinit var surname: String private lateinit var personalCode: String private lateinit var citizenship: String - private lateinit var expiryDate: String + private var issuingCountry: String? = null + private var documentExpiryDate: String? = null + private var certExpiryDate: String? = null private var containerName: String = "" private var pin1Counter: Int = 0 @@ -39,7 +42,9 @@ class DataViewModel : ViewModel() { this.surname = cardData.surname() this.personalCode = cardData.personalCode() this.citizenship = cardData.citizenship() - this.expiryDate = cardData.expiryDate().toString() + this.issuingCountry = cardData.issuingCountry() + this.documentExpiryDate = cardData.documentExpiryDate()?.toString() + this.certExpiryDate = cardData.certExpiryDate()?.toString() } fun getCan(): String { @@ -62,8 +67,16 @@ class DataViewModel : ViewModel() { return citizenship } - fun getExpiryDate(): String { - return expiryDate + fun getIssuingCountry(): String? { + return issuingCountry + } + + fun getDocumentExpiryDate(): String? { + return documentExpiryDate + } + + fun getCertExpiryDate(): String? { + return certExpiryDate } fun setPin1Counter(p1: Int) { diff --git a/demoapp/app/src/main/res/layout/fragment_container.xml b/demoapp/app/src/main/res/layout/fragment_container.xml index ec347b5..280e637 100644 --- a/demoapp/app/src/main/res/layout/fragment_container.xml +++ b/demoapp/app/src/main/res/layout/fragment_container.xml @@ -1,5 +1,6 @@ + + +