diff --git a/AGENTS.md b/AGENTS.md index 34816cd..b7c0716 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -44,7 +44,7 @@ PipeWire. The verified device/carrier combinations are in the README. | `interfaces/Imsd-Sip.cppm` | `imsd::sip` — SIP as a text layer plus TCP framing: header extraction (from the header section only: a read ends at the first empty line after the start line, empty lines before it skipped; a header is asked for by its long name and found under that or its compact form — RFC 3261 7.3.3: the RFC's ten, and `o` for Event and `x` for Session-Expires — with or without white space before the colon; `Unfolded`, by which the framers hand a message on with its folded header lines — 7.3.1 — joined; `HeaderUri`: the party a header names; `Body`, moved here out of `CallMachine`), status codes, the granted lifetime, `ResponseOf` transaction matching (the Call-ID, and the CSeq as its number and its method, whatever spaces or tabs part them and whatever zeros stand before the number), `CutShortRequest`: the header section of a request — any but an ACK or a CANCEL — whose datagram has fewer body bytes than the Content-Length read from it says, which its 400 is built from. Not a full RFC 3261 parser, deliberately. | | `interfaces/Imsd-Sdp.cppm` | `imsd::sdp` — SDP offer/answer: the AMR-WB + AMR + telephone-event offer (optional IR.92 preconditions; `OfferedTelephoneEventPt` names its telephone-event numbers), the parser the media plane needs (the codec, its payload type and mode, and the telephone-event payload type the m-line lists at that codec's clock), `BuildAnswer` for the terminating side, the `CODECS` override. | | `interfaces/Imsd-Sms.cppm` | `imsd::sms` — the short message codecs SMS over IP rides on (TS 24.341 carries the bytes a 2G/3G phone puts in an RP-DATA, in a SIP MESSAGE body): the GSM 7-bit default alphabet with its extension table and the septet packing, UCS-2 (TS 23.038); the SM-TL PDUs (TS 23.040: SMS-SUBMIT built, one per segment with the concatenation header when the text needs more than one; SMS-DELIVER, SMS-STATUS-REPORT and SMS-SUBMIT-REPORT parsed; the SMS-DELIVER-REPORT that acknowledges a delivery; the user-data header — concatenation, application ports — and the `Reassembler` of a concatenated message); the SM-RL messages (TS 24.011: RP-DATA, RP-ACK, RP-ERROR in both directions, the cause values) and `RpCauseIsTemporary`, the causes of a submission after which imsd sends the segment again; EF_SMSP (TS 31.102 §4.2.27), where the (U)SIM names the service centre, and qmicli's hex dump of it. Byte-level only: no SIP, no clock, no I/O. | -| `interfaces/Imsd-Aka.cppm` | `imsd::aka` — USIM AKA glue: the AKAv1-MD5 digest (RFC 3310), IMPI/IMPU/realm from IMSI + MCC/MNC, parsers for `qmicli --uim-get-card-status` and `mmcli` output, the AUTHENTICATE APDU and its response. | +| `interfaces/Imsd-Aka.cppm` | `imsd::aka` — the card's side of a registration: the AKAv1-MD5 digest (RFC 3310), IMPI/IMPU/realm from IMSI + MCC/MNC, parsers for `qmicli --uim-get-card-status` and `mmcli` output, the AUTHENTICATE APDU and its response; since 1.2.3 the ISIM: the application of the slot in use out of the card status (`ParseIsimApp`, in whatever state the modem lists it), the SELECT and the two READ commands its identity files are read with, a card's answer (`ApduAnswer`: `90 00`, `91 XX` and `92 XX` are its normal endings; `HoldsRead` takes a read's data under `62 82` as well) and the command it asks for next (`ApduFollowUp`, for an answer without data: GET RESPONSE for `61 XX`, a command without data again for `6C XX`), the value a file holds (`ParseIsimValue`: the data object with tag `80`, the `FF` bytes at the end of its length cut, no blank and no byte outside printable ASCII) and `IsimIdentity`, the check of the three values — an `@` between two parts, a domain of labels of letters, digits and inner hyphens, 63 characters a label and 253 in all at most, a `sip:` at the start and more after it, the two identities 255 characters at most, no blank, no byte outside printable ASCII and no `"`, `\`, `<` or `>` — before they replace the derived names. | | `interfaces/Imsd-Ipsec.cppm` | `imsd::ipsec` — the two ESP SA pairs (TS 33.203) as `ip xfrm` argv lists, the ESP ciphers offered (`ParseEalgOffer`, `DefaultEalgOffer`), the Security-Server mechanism selection, and the reader that reconstructs SPIs/ports from `ip xfrm state`/`policy` text for a warm resume, and (1.0.0) `SaPeer`, the P-CSCF the kernel's pair is to, read from the `dir out` policies that carry imsd's fingerprint, `OwnXfrmDeleteCommands`, the deletes by exact key of what two rules select — the policies carrying imsd's fingerprint and the reqid-1/2 transport-mode ESP states in their direction or on the UE's ims-PDN address, whoever installed them (§12), and `FileNamesAnotherPair`, whether a state file's `spi_uc`/`spi_us` name the kernel's pair (unknown on either side decides nothing). | | `interfaces/Imsd-Messages.cppm` | `imsd::msg` — every SIP request and response imsd sends, built from an explicit `Context` and per-request variables so the builders are pure functions; `tests/Messages` is their suite. Also `IsEmergency`. Since 1.2.0 the SIP MESSAGE of SMS over IP (`BuildMessageSms`: an RP-DATA to the service centre's PSI, or an RP-ACK/RP-ERROR to the IP-SM-GW with In-Reply-To — TS 24.341 5.3.1.2 and 5.3.2.4), the `+g.3gpp.smsip` Contact tag behind `Context::smsOverIp`, `BuildResponse`, the final for an inbound MESSAGE outside a call's dialog (the 200, the 480, the 488): each Via row echoed in order and the To echoed with a tag added unless it already holds `tag=` (RFC 3261 8.2.6.2); since 1.2.1 `BuildBadRequest`, the 400 to a request cut short of the Content-Length read from it — any but an ACK or a CANCEL, in a call's dialog or not —, in that shape, a To tag it adds made from the request's header section and a secret of the run (RFC 3261 8.2.7); of requests that came whole, in-dialog requests, a MESSAGE among them, and the shell's answers to any other request outside a call — a NOTIFY, an OPTIONS, a method it does not handle; not an INVITE, whose 486 while a call exists is `BuildInviteResponse`'s — keep `BuildResponse200`'s hop-by-hop shape; and `ScPsi`, the service centre's PSI from its international number — never a dialled-number guess. | | `interfaces/Imsd-Engine.cppm` | `imsd::engine` — the decisions as pure reducers: `CallMachine` (one call's dialog, returning `Action`s for the shell), `RegRecovery` (the registration recovery policy, §7.4) and, since 1.2.0, SMS over IP (§7.9): `SmsOutbound` (one short message of ours on its way to the service centre, segment by segment, since 1.2.1 a segment that gets no answer, or an RP-ERROR with cause 41, sent once more with TP-RD set — TS 23.040 9.2.3.6 —, returning `SmsAction`s) and `OnSmsMessage` (what an inbound MESSAGE outside a call's dialog leads to: its final, the message or status report it delivered, the delivery report to send), and `RecentTransactions` (an inbound request's retransmission — the same Call-ID, CSeq and Via branch within 32 s (`TimerJ`), the branch being the value of the first `branch=` of its first Via row and a request with none or an empty one never matched — answered with the same final and not handled again) and, since 1.2.1, `RecentSubmissions` (the Call-IDs of the MESSAGEs our submissions went out in, an hour each, by which a submit report for one that is no longer in flight is known for ours — TS 24.341 5.3.1.2); `SameRecipient` and `StatusReportBook`, a status report's match to the message that asked for one — TP-MR and recipient — and its word for the whole message, with `SmsWordOrder`, the order of a message's words: the submission's first, a report's held until then (§7.9); `RunToken`, `SentSmsId` and `ReceivedSmsId`, the ids (§8.4); `StoredSms` with `FormatStoredSms`/`ParseStoredSms`, the record codec of the received-message store, and `StoredSmsBefore`, `List`'s order. | @@ -256,7 +256,28 @@ What the suites pin: text parsers, the AUTHENTICATE APDU and its response parser, the class byte of a command on a logical channel (the channel itself for 0 to 3, `4X` for 4 to 19 — TS 102 221 10.1.1; AUTHENTICATE on channels 3 and - 4, GET RESPONSE on channel 7). + 4, GET RESPONSE on channel 7); the ISIM application of a slot (a card with a `ready` USIM and + a `detected` ISIM in one slot, in either order — the applications, states + and AIDs the fp6 journal's probe read off a reporter's card, 2026-11-23, + in the lines qmicli prints for an application —; another slot's ISIM not + taken, a twelve-byte AID, a CSIM, a missing state line) and the slot of + a line whose number does not parse, the SELECT and the READ + commands byte for byte on standard and extended channels, a card's answer + and its follow-up (`61 XX`, `6C XX` to a read and to a command with + data, an error, data with `61 XX`; `91 XX` and `92 XX` normal endings, + `90 01` and `93 00` none; a read's data + taken under `62 82`, not under `62 81` or `63 82`), `ParseIsimValue` (the + three length forms, the padding after the object and `FF` at the end of + its length, an unused record, another tag, a length past the data, a + blank, a line break, a NUL, an `FF` before the value's end, a byte above + ASCII) and `IsimIdentity` (names unlike the derived ones, the derived + ones themselves, and what is refused: a private identity without an `@` + between two parts, a domain that is not labels of letters, digits and + inner hyphens or that has a label of 64 characters or 254 characters in + all, a public identity that does not begin `sip:` or + is that alone, a private or a public identity of 256 characters, a + quote, a backslash, an angle bracket, a blank or a line break in one of + the three). - `Ipsec` — the exact `ip xfrm` argv lists for the SA pairs, the `EALG` setting, the Security-Server mechanism selection against one offered cipher and against two (KPN's entry and Odido's, O2's six with the SPIs @@ -289,7 +310,10 @@ What the suites pin: TLVs) and the error names (OutOfCall, NoEffect, an unknown code as `?`). - `Messages` — the outgoing SIP messages: the initial and the protected REGISTER, the reg-event SUBSCRIBE and the INVITEs byte-for-byte, their - variants (a Security-Client for another offer among them), the in-dialog + variants (a Security-Client for another offer among them; the two + REGISTERs of an identity an ISIM holds, byte for byte the pinned ones + with the card's names for the derived ones, and `RuriFor` at an + ISIM's home domain), the in-dialog requests, the ACKs, the CANCEL and `BuildResponse200` by their lines, `BuildInviteResponse` by the lines of one 180 and by a 486 without a Record-Route (`tests/Engine` checks the @@ -2679,6 +2703,27 @@ the related code. 01:17:41–45, 28–36 min after their SC time stamps; what held them is unknown. The registrar echoes `+g.3gpp.smsip` in the reg-event reginfo (``) on both AORs. +- **Cards with an ISIM** (the fp6 journal's read-only probe on two + reporters' phones; the dev phone's card has none). A US card on AT&T's + network (operator name "Dark Star", SIM operator 310 280; 2026-11-23) and + a Norwegian one (Ice, 242 14; 2026-11-21) each list a USIM `ready` and + an ISIM `detected` in one slot of the Fairphone 6. On both a logical + channel opened on the ISIM's AID in that state and the probe read + EF_IMPI, EF_DOMAIN and EF_IMPU's record 1: it sends SELECT by file + identifier with P2 `04` and takes a `61 XX` for the file selected, sends + READ BINARY and READ RECORD with Le `00` and follows a `61 XX` or a + `6C XX` to those (which it got on the way it does not print), and cuts + `FF` bytes from the end of a value. The US card holds names of the + operator's own in all three + (the private identity `@private.att.net`, the home domain + `one.att.net`, the public identity `sip:@one.att.net`) and has no + EF_P-CSCF and no EF_IST (`6A 82` to their SELECT); the Norwegian card + holds the names TS 23.003 derives from the IMSI, an EF_P-CSCF of three + unused records and an EF_IST of seven zero bytes. On the dev phone's + USIM (a KPN eSIM, 2026-11-21, by hand) that SELECT answered `61 19` for + one file and `61 1C` for another, the + two reads data and `90 00` at once, and the SELECT of a file the + application does not have `6A 82`. - **A folded `WWW-Authenticate`** — the 401 to the unprotected REGISTER came with its `WWW-Authenticate` over four lines on KPN (2026-07-18) and on Odido (2026-07-13), the nonce on the second (RFC 3261 7.3.1; one diff --git a/interfaces/Imsd-Aka.cppm b/interfaces/Imsd-Aka.cppm index 32132db..e470a07 100644 --- a/interfaces/Imsd-Aka.cppm +++ b/interfaces/Imsd-Aka.cppm @@ -2,17 +2,26 @@ // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® /* -Imsd:Aka — USIM AKA (3GPP TS 33.102) glue for IMS registration: +Imsd:Aka — the card's side of an IMS registration: AKA (3GPP TS 33.102) and +the identity to register: * the AKAv1-MD5 HTTP-digest response (RFC 3310) the protected REGISTER carries in its Authorization header — MD5 over the binary RES; - * the home-network identity (IMPI/IMPU/registration URI/realm) derived - from IMSI + MCC/MNC; - * text parsers for the SIM facts the daemon shell scrapes from qmicli - (`--uim-get-card-status`: which slot holds a ready USIM and its AID) and - ModemManager (`mmcli`: the primary SIM path, then IMSI + operator id); + * the home-network identity (IMPI/IMPU/registration URI/realm): derived + from IMSI + MCC/MNC (TS 23.003 13.2 to 13.4B, the names of a UE without + an ISIM), and since 1.2.3 the one an ISIM holds (TS 24.229 5.1.1.1A) — + the value an identity file carries (`ParseIsimValue`) and the check of + the three before they stand in a REGISTER (`IsimIdentity`); + * text parsers for the SIM facts in qmicli's output + (`--uim-get-card-status`: which slot holds a ready USIM and its AID, + and the ISIM application of a slot) and in + ModemManager's (`mmcli`: the primary SIM path, then IMSI + operator id); * the ISO 7816 APDU for the AUTHENTICATE(AKA) command and the parser for - its 0xDB success response (RES / CK / IK TLV). + its 0xDB success response (RES / CK / IK TLV), the class byte of a + command on a logical channel, the SELECT and the two READ commands the + ISIM's files are read with, and a card's answer: its status word and, + for an answer without data, the command it asks for next ('61 XX', + '6C XX'). All pure std C++: the actual card I/O (open channel, transmit APDU) is the shell's job — this module only shapes the bytes and reads the answers back. @@ -25,7 +34,9 @@ import :Util; export namespace imsd::aka { - // The home-network identity a USIM registers under. + // The home-network identity: the one derived from the IMSI + // (MakeIdentity), whose shapes the comments below give, or the one an + // ISIM holds (IsimIdentity). struct Identity { std::string imsi; std::string mcc; @@ -75,24 +86,26 @@ export namespace imsd::aka { return imsd::util::Md5::HexDigest(std::format("{}:{}:{}:{}:{}:{}", ha1, nonce, nc, cnonce, qop, ha2)); } - // Which USIM the modem should authenticate against. + // The ready USIM of a card status: its slot and its AID. struct SimSelection { int slot = 0; std::string aid; // uppercase, colons stripped }; - // Parse qmicli `--uim-get-card-status`: the first ready USIM application, - // its slot number, and its Application ID (the hex line under - // "Application ID:"). nullopt if no ready USIM is present. Mirrors the - // Python detect_sim() scan exactly. - std::optional ParseCardStatus(std::string_view text) { - int curSlot = 0; - bool inUsim = false; - bool ready = false; - std::optional out; - std::size_t pos = 0; - auto isAidLine = [](std::string_view s) { - // trimmed line is HH(:HH)+ — two-or-more colon-separated hex pairs + // The pieces of qmicli's card status both of its readers take. + namespace detail { + // A line without the blanks before it and the blanks or the CR + // after it. + inline std::string_view Trimmed(std::string_view t) { + while (!t.empty() && (t.front() == ' ' || t.front() == '\t')) + t.remove_prefix(1); + while (!t.empty() && (t.back() == ' ' || t.back() == '\t' || t.back() == '\r')) + t.remove_suffix(1); + return t; + } + // A trimmed line that is an Application ID: HH(:HH)+, two or more + // colon-separated hex pairs. + inline bool AidLine(std::string_view s) { std::size_t i = 0; int pairs = 0; auto hex = [](char c) { @@ -108,36 +121,49 @@ export namespace imsd::aka { i++; } return pairs >= 2; - }; + } + // Such a line's AID: uppercase, colons stripped. + inline std::string AidOf(std::string_view t) { + std::string aid; + for (char c : t) + if (c != ':') aid.push_back(static_cast(std::toupper(static_cast(c)))); + return aid; + } + // The N of a "Slot [N]:" line: 0 when what stands between the + // brackets is no number, `fallback` for a line without the pair. + inline int SlotOf(std::string_view t, int fallback) { + std::size_t lb = t.find('['); + std::size_t rb = t.find(']', lb); + if (lb == std::string_view::npos || rb == std::string_view::npos) return fallback; + int v = 0; + std::from_chars(t.data() + lb + 1, t.data() + rb, v); + return v; + } + } + + // Parse qmicli `--uim-get-card-status`: the first ready USIM application, + // its slot number, and its Application ID (the hex line under + // "Application ID:"). nullopt if no ready USIM is present. Mirrors the + // Python detect_sim() scan exactly. + std::optional ParseCardStatus(std::string_view text) { + int curSlot = 0; + bool inUsim = false; + bool ready = false; + std::optional out; + std::size_t pos = 0; while (pos <= text.size()) { std::size_t nl = text.find('\n', pos); - std::string_view line = text.substr(pos, nl == std::string_view::npos ? std::string_view::npos : nl - pos); - std::string_view t = line; - while (!t.empty() && (t.front() == ' ' || t.front() == '\t')) - t.remove_prefix(1); - while (!t.empty() && (t.back() == ' ' || t.back() == '\t' || t.back() == '\r')) - t.remove_suffix(1); + std::string_view t = detail::Trimmed(text.substr(pos, nl == std::string_view::npos ? std::string_view::npos : nl - pos)); if (t.starts_with("Slot [")) { - std::size_t lb = t.find('['); - std::size_t rb = t.find(']', lb); - if (lb != std::string_view::npos && rb != std::string_view::npos) { - int v = 0; - std::from_chars(t.data() + lb + 1, t.data() + rb, v); - curSlot = v; - } + curSlot = detail::SlotOf(t, curSlot); inUsim = ready = false; } else if (t.contains("Application type") && t.contains("usim")) { inUsim = true; } else if (inUsim && t.contains("Application state") && t.contains("ready")) { ready = true; - } else if (inUsim && isAidLine(t)) { - if (ready && !out) { - std::string aid; - for (char c : t) - if (c != ':') aid.push_back(static_cast(std::toupper(static_cast(c)))); - out = SimSelection{curSlot, aid}; - } + } else if (inUsim && detail::AidLine(t)) { + if (ready && !out) out = SimSelection{curSlot, detail::AidOf(t)}; inUsim = false; } if (nl == std::string_view::npos) break; @@ -146,6 +172,49 @@ export namespace imsd::aka { return out; } + // An ISIM application as the card status lists it. + struct IsimApp { + std::string aid; // uppercase, colons stripped + std::string state; // the modem's word for it: detected, ready, … + }; + + // The first ISIM application of the card in `slot`, from the same card + // status, in whatever state the modem lists it: the Fairphone 6's modem + // lists an ISIM as `detected` beside a `ready` USIM (the two cards + // with an ISIM the probe read, AGENTS.md §13), and a logical channel + // opened on each all the same. nullopt when the card in that slot lists + // none — another + // slot's ISIM belongs to another subscription. + std::optional ParseIsimApp(std::string_view text, int slot) { + int curSlot = 0; + bool inIsim = false; + std::string state; + std::size_t pos = 0; + while (pos <= text.size()) { + std::size_t nl = text.find('\n', pos); + std::string_view t = detail::Trimmed(text.substr(pos, nl == std::string_view::npos ? std::string_view::npos : nl - pos)); + + if (t.starts_with("Slot [")) { + curSlot = detail::SlotOf(t, curSlot); + inIsim = false; + } else if (t.contains("Application type")) { + inIsim = t.contains("isim"); + state.clear(); + } else if (t.contains("Application state")) { + // the word between the quotes: Application state: 'detected' + std::size_t q1 = t.find('\''); + std::size_t q2 = q1 == std::string_view::npos ? q1 : t.find('\'', q1 + 1); + if (q2 != std::string_view::npos) state = t.substr(q1 + 1, q2 - q1 - 1); + } else if (inIsim && detail::AidLine(t)) { + if (curSlot == slot) return IsimApp{detail::AidOf(t), state}; + inIsim = false; + } + if (nl == std::string_view::npos) break; + pos = nl + 1; + } + return std::nullopt; + } + // "primary sim path: " from `mmcli -m any`. std::optional ParsePrimarySimPath(std::string_view text) { std::size_t at = text.find("primary sim path:"); @@ -273,6 +342,168 @@ export namespace imsd::aka { return std::format("{:02x}c00000{:02x}", ClassByte(channel), le & 0xFF); } + // ---- reading a file of the selected application ------------------------- + + // The ISIM's identity files (TS 31.103 4.2.2 to 4.2.4). + constexpr std::uint16_t EfImpi = 0x6F02; // transparent: the private user identity + constexpr std::uint16_t EfDomain = 0x6F03; // transparent: the home network domain name + constexpr std::uint16_t EfImpu = 0x6F04; // linear fixed: the public user identities + + // SELECT by file identifier under the application the channel was opened + // on (TS 102 221 11.1.1.2: P1 '00', select by file id; P2 '04', return + // the FCP template). + std::string BuildSelectFileApdu(int channel, std::uint16_t fileId) { + return std::format("{:02x}a4000402{:04x}", ClassByte(channel), fileId); + } + + // READ BINARY from the start of the selected transparent file (TS 102 221 + // 11.1.3), and READ RECORD of one record of the selected linear fixed + // file by its number (11.1.5: P2 '04', absolute mode), both with Le '00': + // a '6C XX' in answer names the length (7.3.1.1.5.1). + std::string BuildReadBinaryApdu(int channel) { + return std::format("{:02x}b0000000", ClassByte(channel)); + } + std::string BuildReadRecordApdu(int channel, int record) { + return std::format("{:02x}b2{:02x}0400", ClassByte(channel), record & 0xFF); + } + + // A card's answer to one command: the data and the status word. + struct ApduAnswer { + std::vector data; + std::uint8_t sw1 = 0; + std::uint8_t sw2 = 0; + // The normal endings (TS 102 221 10.2.1.1): '90 00'; '91 XX', from + // a card that has a proactive command waiting for the terminal + // (7.4.2.1); '92 XX', with a data transfer session going on. + bool Ok() const { return (sw1 == 0x90 && sw2 == 0x00) || sw1 == 0x91 || sw1 == 0x92; } + // The status word as the specifications write it: "6a82". + std::string Status() const { return std::format("{:02x}{:02x}", sw1, sw2); } + }; + + // The answer in the bytes qmicli prints for an exchange (the data, then + // SW1 SW2); nullopt for fewer than the two status bytes. + std::optional ParseApduAnswer(std::span bytes) { + if (bytes.size() < 2) return std::nullopt; + ApduAnswer a; + a.data.assign(bytes.begin(), bytes.end() - 2); + a.sw1 = bytes[bytes.size() - 2]; + a.sw2 = bytes[bytes.size() - 1]; + return a; + } + + // The command to send after `answer` to get what `apdu` (hex) asked for, + // when the card asks for one (TS 102 221 7.3.1.1.5, the procedure bytes + // '61xx' and '6Cxx'): GET RESPONSE with the length a '61 XX' names, or, + // for a '6C XX', the command again with that length in place of its + // last byte — of a command that is a header and an Le, five bytes. + // nullopt for any other answer, which is taken for the command's last: + // data with a '61 XX' behind it, which offers more, among them. + std::optional ApduFollowUp(int channel, std::string_view apdu, const ApduAnswer& answer) { + if (!answer.data.empty()) return std::nullopt; + if (answer.sw1 == 0x61) return BuildGetResponseApdu(channel, answer.sw2); + if (answer.sw1 == 0x6C && apdu.size() == 10) return std::format("{}{:02x}", apdu.substr(0, 8), answer.sw2); + return std::nullopt; + } + + // Whether a SELECT's answer says the file is selected: a normal ending, + // or '61 XX', the card offering the file's control parameters, which + // nothing here needs. + inline bool Selected(const ApduAnswer& answer) { + return answer.Ok() || answer.sw1 == 0x61; + } + + // Whether a read's answer holds what was read: a normal ending, or + // data under the warning '62 82', the file or the record having ended + // before the Le bytes asked for (TS 102 221 10.2.1.3). + inline bool HoldsRead(const ApduAnswer& answer) { + return answer.Ok() || (answer.sw1 == 0x62 && answer.sw2 == 0x82 && !answer.data.empty()); + } + + // The value of the data object with tag '80' that an ISIM identity file, + // or a record of EF_IMPU, begins with (TS 31.103 4.2.2 to 4.2.4: the + // NAI, the domain name, a URI), as text. The bytes after the object are + // the file's padding and are not read, and 'FF' bytes at the end of its + // length are taken for padding counted into it and cut: the probe that + // read two reporters' cards cuts them (AGENTS.md §13), so its output + // does not tell such a card from another. nullopt for anything else: + // another first byte (an unused record is all 'FF'), a length in + // another form than one byte, '81' and one or '82' and two, a length + // that runs past the data, no value, or a value with a blank or a byte + // that is not printable ASCII — the three are written into SIP header + // fields. + std::optional ParseIsimValue(std::span data) { + if (data.size() < 2 || data[0] != 0x80) return std::nullopt; + std::size_t i = 1; + std::size_t n = data[i++]; + if (n == 0x81) { + if (i >= data.size()) return std::nullopt; + n = data[i++]; + } else if (n == 0x82) { + if (i + 1 >= data.size()) return std::nullopt; + n = static_cast(data[i]) << 8 | data[i + 1]; + i += 2; + } else if (n >= 0x80) { + return std::nullopt; + } + if (i + n > data.size()) return std::nullopt; + while (n > 0 && data[i + n - 1] == 0xFF) n--; + if (n == 0) return std::nullopt; + std::string value; + for (std::size_t k = 0; k < n; k++) { + std::uint8_t c = data[i + k]; + if (c < 0x21 || c > 0x7E) return std::nullopt; + value.push_back(static_cast(c)); + } + return value; + } + + // The identity an ISIM holds in place of the derived one: `derived` + // (which keeps its IMSI and operator) with the private identity, the + // home domain and the public identity the card gave, and the + // registration URI of that domain. nullopt when one of the three cannot + // stand where imsd writes it: a private identity without an `@` between + // two parts, a domain that is not labels of letters, digits and inner + // hyphens, 63 characters a label and 253 in all at most, a + // public identity that does not begin `sip:` and go on, a private or a + // public identity of more than 255 characters, or one of the two with a + // `"`, a `\`, a `<` or a `>` (the private identity is written into a + // quoted string, the public one between angle brackets), a blank or a + // byte outside printable ASCII. + std::optional IsimIdentity(Identity derived, std::string_view impi, std::string_view domain, std::string_view impu) { + auto plain = [](std::string_view s) { + if (s.empty() || s.size() > 255) return false; + for (char ch : s) { + auto c = static_cast(ch); + if (c < 0x21 || c > 0x7E || c == '"' || c == '\\' || c == '<' || c == '>') return false; + } + return true; + }; + auto host = [](std::string_view s) { + if (s.empty() || s.size() > 253) return false; + char prev = '.'; + std::size_t label = 0; + for (char c : s) { + bool alnum = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); + if (!alnum && c != '-' && c != '.') return false; + if ((c == '.' || c == '-') && prev == '.') return false; // a label begins with a letter or a digit + if (c == '.' && prev == '-') return false; // and ends with one + label = c == '.' ? 0 : label + 1; + if (label > 63) return false; + prev = c; + } + return prev != '.' && prev != '-'; + }; + if (!plain(impi) || !plain(impu) || !host(domain)) return std::nullopt; + std::size_t at = impi.find('@'); + if (at == 0 || at == std::string_view::npos || at + 1 == impi.size()) return std::nullopt; + if (!impu.starts_with("sip:") || impu.size() == 4) return std::nullopt; + derived.impi = impi; + derived.domain = domain; + derived.impu = impu; + derived.regUri = std::format("sip:{}", domain); + return derived; + } + struct AkaResult { std::vector res; std::vector ck; @@ -302,4 +533,13 @@ export namespace imsd::aka { if (!take(r.res) || !take(r.ck) || !take(r.ik)) return std::nullopt; return r; } + + // The same of an answer already parted into its data and its status + // word (ParseApduAnswer). + std::optional ParseAkaResponse(const ApduAnswer& answer) { + std::vector resp = answer.data; + resp.push_back(answer.sw1); + resp.push_back(answer.sw2); + return ParseAkaResponse(std::span(resp)); + } } diff --git a/tests/Aka/main.cpp b/tests/Aka/main.cpp index baaf359..7cdad57 100644 --- a/tests/Aka/main.cpp +++ b/tests/Aka/main.cpp @@ -4,6 +4,10 @@ // Imsd:Aka unit tests — the AKAv1-MD5 digest against a vector cross-computed // with the Python reference, identity assembly, the qmicli/mmcli text // parsers (fed real device output), and the AUTHENTICATE APDU build/parse. +// Then the ISIM (since 1.2.3): the application of the slot in use out of a +// card status, the commands its files are read with, a card's answer and +// the command it asks for next, the value an identity file holds, and the +// check of the three values before they are an identity. import std; import Imsd; @@ -36,6 +40,69 @@ namespace { "\t\t\tA0:00:00:00:87:10:02:FF:31:F0:04:89:0E:00:00:01\n" "\t\tPIN1 state: 'disabled'\n"; + // A card with a USIM and an ISIM in one slot. The two applications, + // their states and their AIDs are those the fp6 journal's probe read off + // a reporter's card on 2026-11-23 (the modem lists the ISIM `detected` + // beside the `ready` USIM); the lines are the ones qmicli prints for an + // application, as in the fixture above: the probe prints its own listing + // of a card, not qmicli's. + constexpr std::string_view CardStatusIsim = + "[qrtr://0] Successfully got card status\n" + "Provisioning applications:\n" + "\tPrimary GW: slot '1', application '1'\n" + "Slot [1]:\n" + "\tCard state: 'present'\n" + "\tUPIN state: 'not-initialized'\n" + "\tApplication [1]:\n" + "\t\tApplication type: 'usim (2)'\n" + "\t\tApplication state: 'ready'\n" + "\t\tApplication ID:\n" + "\t\t\tA0:00:00:00:87:10:02:FF:FF:FF:FF:89:03:02:00:00\n" + "\t\tPIN1 state: 'disabled'\n" + "\tApplication [2]:\n" + "\t\tApplication type: 'isim (5)'\n" + "\t\tApplication state: 'detected'\n" + "\t\tApplication ID:\n" + "\t\t\tA0:00:00:00:87:10:04:FF:FF:FF:FF:89:03:02:00:00\n" + "\t\tPIN1 state: 'disabled'\n" + "Slot [2]:\n" + "\tCard state: 'absent'\n"; + + // The same two applications with the ISIM listed first, and a second + // card in slot 2 that has an ISIM of its own (its AID the twelve bytes + // of the other card with an ISIM the probe read, 2026-11-21) beside a USIM + // that is not ready. + constexpr std::string_view CardStatusIsimFirst = + "Slot [1]:\n" + "\tCard state: 'present'\n" + "\tApplication [1]:\n" + "\t\tApplication type: 'isim (5)'\n" + "\t\tApplication state: 'detected'\n" + "\t\tApplication ID:\n" + "\t\t\tA0:00:00:00:87:10:04:FF:FF:FF:FF:89:03:02:00:00\n" + "\tApplication [2]:\n" + "\t\tApplication type: 'usim (2)'\n" + "\t\tApplication state: 'ready'\n" + "\t\tApplication ID:\n" + "\t\t\tA0:00:00:00:87:10:02:FF:FF:FF:FF:89:03:02:00:00\n" + "Slot [2]:\n" + "\tCard state: 'present'\n" + "\tApplication [1]:\n" + "\t\tApplication type: 'usim (2)'\n" + "\t\tApplication state: 'detected'\n" + "\t\tApplication ID:\n" + "\t\t\tA0:00:00:00:87:10:02:FF:49:FF:05:89\n" + "\tApplication [2]:\n" + "\t\tApplication type: 'isim (5)'\n" + "\t\tApplication state: 'ready'\n" + "\t\tApplication ID:\n" + "\t\t\ta0:00:00:00:87:10:04:ff:49:ff:05:89\n" + "\tApplication [3]:\n" + "\t\tApplication type: 'isim (5)'\n" + "\t\tApplication state: 'detected'\n" + "\t\tApplication ID:\n" + "\t\t\tA0:00:00:00:87:10:04:FF:49:FF:05:99\n"; + constexpr std::string_view MmcliSim = " Properties | active: yes\n" " | imsi: 001010123456789\n" @@ -72,6 +139,10 @@ int main() { Check(sel && sel->aid == "A0000000871002FF31F004890E000001", "AID uppercased, colons stripped"); } Check(!ParseCardStatus("Slot [1]:\n\tCard state: 'absent'\n").has_value(), "no ready USIM -> nullopt"); + { + auto odd = ParseCardStatus("Slot [2]:\n\tCard state: 'absent'\nSlot [x]:\n\tApplication [1]:\n\t\tApplication type: 'usim (2)'\n\t\tApplication state: 'ready'\n\t\tApplication ID:\n\t\t\tA0:00:00:00:87:10:02:FF\n"); + Check(odd && odd->slot == 0, "a slot line whose number does not parse is slot 0, not the slot before it"); + } // ---- mmcli parsers Check(ParsePrimarySimPath(" SIM | primary sim path: /org/freedesktop/ModemManager1/SIM/0\n") == "/org/freedesktop/ModemManager1/SIM/0", "primary sim path"); @@ -126,6 +197,13 @@ int main() { Check(r && r->res.size() == 8 && r->res[0] == 0xA0, "RES extracted"); Check(r && r->ck.size() == 16 && r->ck[0] == 0xC0, "CK extracted"); Check(r && r->ik.size() == 16 && r->ik[0] == 0xD0, "IK extracted"); + // the same answer parted into its data and its status word + auto parted = ParseApduAnswer(body); + auto r2 = parted ? ParseAkaResponse(*parted) : std::nullopt; + Check(r2 && r2->res == r->res && r2->ck == r->ck && r2->ik == r->ik, "an ApduAnswer's AKA result is the raw answer's"); + std::vector refused = {0x69, 0x82}; + auto no = ParseApduAnswer(refused); + Check(no && !ParseAkaResponse(*no).has_value(), "a status word alone is no AKA result"); } { // sync-failure tag (0xDC) or truncated body -> nullopt @@ -158,6 +236,212 @@ int main() { Check(!ParsePani(Zeros).has_value(), "PANI all-zero cell rejected"); } + // ---- the ISIM application of the slot in use + { + auto sel = ParseCardStatus(CardStatusIsim); + Check(sel && sel->slot == 1 && sel->aid == "A0000000871002FFFFFFFF8903020000", "the ready USIM beside an ISIM is still the USIM read"); + auto isim = ParseIsimApp(CardStatusIsim, 1); + Check(isim.has_value(), "the ISIM of slot 1 is found"); + Check(isim && isim->aid == "A0000000871004FFFFFFFF8903020000", "its AID, uppercase, colons stripped"); + Check(isim && isim->state == "detected", "its state is the modem's word, detected"); + Check(!ParseIsimApp(CardStatusIsim, 2).has_value(), "an absent card in the slot asked for: no ISIM"); + Check(!ParseIsimApp(CardStatus, 2).has_value(), "a card with a USIM only: no ISIM"); + Check(!ParseIsimApp(CardStatus, 1).has_value(), "a slot with no card: no ISIM"); + Check(!ParseIsimApp("", 1).has_value(), "no card status: no ISIM"); + } + { + auto sel = ParseCardStatus(CardStatusIsimFirst); + Check(sel && sel->slot == 1 && sel->aid == "A0000000871002FFFFFFFF8903020000", "the USIM listed after an ISIM is read"); + auto first = ParseIsimApp(CardStatusIsimFirst, 1); + Check(first && first->aid == "A0000000871004FFFFFFFF8903020000" && first->state == "detected", "the ISIM listed before the USIM is found"); + // slot 2's ISIM is not slot 1's: each slot's reader gets its own card's + auto other = ParseIsimApp(CardStatusIsimFirst, 2); + Check(other && other->aid == "A0000000871004FF49FF0589", "the other slot's ISIM for the other slot: a twelve-byte AID, lower case made upper"); + Check(other && other->state == "ready", "its state, ready"); + Check(first && other && first->aid != other->aid, "slot 1 is not answered with slot 2's ISIM"); + Check(!ParseIsimApp(CardStatusIsimFirst, 3).has_value(), "a slot the status does not list: no ISIM"); + } + { + // an application of another type keeps its AID to itself, and an + // ISIM whose state line is missing is found with no state + auto none = ParseIsimApp("Slot [1]:\n\tApplication [1]:\n\t\tApplication type: 'csim (4)'\n\t\tApplication state: 'detected'\n\t\tApplication ID:\n\t\t\tA0:00:00:03:43:10:02:FF\n", 1); + Check(!none.has_value(), "a CSIM is no ISIM"); + auto bare = ParseIsimApp("Slot [1]:\n\tApplication [1]:\n\t\tApplication type: 'isim (5)'\n\t\tApplication ID:\n\t\t\tA0:00:00:00:87:10:04:FF\n", 1); + Check(bare && bare->aid == "A0000000871004FF" && bare->state.empty(), "an ISIM without a state line: found, the state empty"); + // the state of the application before it is not taken for the ISIM's + auto after = ParseIsimApp("Slot [1]:\n\tApplication [1]:\n\t\tApplication type: 'usim (2)'\n\t\tApplication state: 'ready'\n\t\tApplication ID:\n\t\t\tA0:00:00:00:87:10:02:FF\n\tApplication [2]:\n\t\tApplication type: 'isim (5)'\n\t\tApplication ID:\n\t\t\tA0:00:00:00:87:10:04:FF\n", 1); + Check(after && after->state.empty(), "the USIM's state is not the ISIM's"); + } + + // ---- the commands a file of the selected application is read with + Check(EfImpi == 0x6F02 && EfDomain == 0x6F03 && EfImpu == 0x6F04, "the three identity files' identifiers (TS 31.103 4.2.2 to 4.2.4)"); + Check(BuildSelectFileApdu(1, EfImpi) == "01a40004026f02", "SELECT EF_IMPI on channel 1"); + Check(BuildSelectFileApdu(5, EfDomain) == "41a40004026f03", "SELECT EF_DOMAIN on channel 5: the extended class byte"); + Check(BuildSelectFileApdu(2, 0x00AD) == "02a400040200ad", "a file identifier below 1000 keeps its four digits"); + Check(BuildReadBinaryApdu(1) == "01b0000000", "READ BINARY from offset 0, Le 00"); + Check(BuildReadBinaryApdu(4) == "40b0000000", "READ BINARY on channel 4"); + Check(BuildReadRecordApdu(1, 1) == "01b2010400", "READ RECORD 1, absolute, Le 00"); + Check(BuildReadRecordApdu(6, 2) == "42b2020400", "READ RECORD 2 on channel 6"); + + // ---- a card's answer, and the command it asks for next + { + std::vector offer = {0x61, 0x19}; + auto a = ParseApduAnswer(offer); + Check(a && a->data.empty() && a->sw1 == 0x61 && a->sw2 == 0x19, "61 19: no data, the status word"); + Check(a && !a->Ok() && a->Status() == "6119", "61 19 is not 90 00; written 6119"); + Check(a && Selected(*a), "a SELECT answered 61 XX has selected the file"); + Check(a && ApduFollowUp(1, "01a40004026f02", *a) == "01c0000019", "61 19 asks for GET RESPONSE with Le 19"); + Check(a && ApduFollowUp(5, "41b0000000", *a) == "41c0000019", "GET RESPONSE on the command's channel"); + + std::vector data = {0x80, 0x03, 'a', '.', 'b', 0x90, 0x00}; + auto d = ParseApduAnswer(data); + Check(d && d->data.size() == 5 && d->data[0] == 0x80 && d->data[4] == 'b', "data before 90 00 is the answer's data"); + Check(d && d->Ok() && d->Status() == "9000" && Selected(*d), "90 00 is Ok"); + Check(d && !ApduFollowUp(1, "01b0000000", *d).has_value(), "90 00 with data asks for nothing"); + + std::vector len = {0x6C, 0x23}; + auto l = ParseApduAnswer(len); + Check(l && ApduFollowUp(1, "01b0000000", *l) == "01b0000023", "6C 23 to READ BINARY: the command again with Le 23"); + Check(l && ApduFollowUp(4, "40b2010400", *l) == "40b2010423", "6C 23 to READ RECORD: the command again with Le 23"); + Check(l && !ApduFollowUp(1, "0188008122" "10" "11111111111111111111111111111111" "10" "22222222222222222222222222222222", *l).has_value(), "6C XX to a command that carries data: nothing to send again"); + Check(l && !Selected(*l), "6C XX is no selected file"); + + std::vector missing = {0x6A, 0x82}; + auto m = ParseApduAnswer(missing); + Check(m && m->Status() == "6a82" && !m->Ok() && !Selected(*m), "6A 82: file not found, nothing selected"); + Check(m && !ApduFollowUp(1, "01a40004026f09", *m).has_value(), "an error asks for nothing"); + + std::vector more = {0x80, 0x01, 'a', 0x61, 0x05}; + auto w = ParseApduAnswer(more); + Check(w && !ApduFollowUp(1, "01b0000000", *w).has_value(), "data with 61 XX is not followed"); + + std::vector one = {0x90}; + Check(!ParseApduAnswer(one).has_value(), "one byte is no answer"); + Check(!ParseApduAnswer({}).has_value(), "no bytes is no answer"); + std::vector sw = {0x90, 0x00}; + auto e = ParseApduAnswer(sw); + Check(e && e->data.empty() && e->Ok(), "90 00 alone: Ok, no data"); + + // a card with a proactive command waiting ends a command 91 XX, one + // with a data transfer session going on 92 XX + std::vector proactive = {0x80, 0x03, 'a', '.', 'b', 0x91, 0x0B}; + auto p = ParseApduAnswer(proactive); + Check(p && p->Ok() && Selected(*p) && HoldsRead(*p) && p->data.size() == 5, "91 XX is a normal ending"); + std::vector transfer = {0x80, 0x03, 'a', '.', 'b', 0x92, 0x10}; + auto x = ParseApduAnswer(transfer); + Check(x && x->Ok() && Selected(*x) && HoldsRead(*x), "92 XX is a normal ending"); + std::vector n9001 = {0x90, 0x01}, n9300 = {0x93, 0x00}; + Check(!ParseApduAnswer(n9001)->Ok(), "90 01 is no normal ending"); + Check(!ParseApduAnswer(n9300)->Ok(), "93 00 is no normal ending"); + + // a read may end 62 82 with all the file holds + std::vector eof = {0x80, 0x03, 'a', '.', 'b', 0x62, 0x82}; + auto f = ParseApduAnswer(eof); + Check(f && !f->Ok() && HoldsRead(*f) && !Selected(*f), "data under 62 82 is what a read holds, and no normal ending"); + Check(d && HoldsRead(*d), "data under 90 00 is what a read holds"); + std::vector bare6282 = {0x62, 0x82}, d6281 = {0x80, 0x01, 'a', 0x62, 0x81}, d6382 = {0x80, 0x01, 'a', 0x63, 0x82}; + Check(!HoldsRead(*ParseApduAnswer(bare6282)), "62 82 without data holds nothing"); + Check(!HoldsRead(*ParseApduAnswer(d6281)), "data under 62 81 is not taken"); + Check(!HoldsRead(*ParseApduAnswer(d6382)), "data under 63 82 is not taken"); + Check(m && !HoldsRead(*m), "6A 82 holds nothing"); + } + + // ---- the value an ISIM identity file holds (the data object with tag 80) + { + auto bytes = [](std::initializer_list head, std::string_view text, std::size_t pad) { + std::vector v(head); + v.insert(v.end(), text.begin(), text.end()); + v.insert(v.end(), pad, 0xFF); + return v; + }; + Check(ParseIsimValue(bytes({0x80, 0x0F}, "ims.example.net", 17)) == "ims.example.net", "the value of the object, the file's FF padding after it not read"); + Check(ParseIsimValue(bytes({0x80, 0x0F}, "ims.example.net", 0)) == "ims.example.net", "the value with nothing after it"); + Check(ParseIsimValue(bytes({0x80, 0x81, 0x0F}, "ims.example.net", 3)) == "ims.example.net", "a length in the 81 form"); + Check(ParseIsimValue(bytes({0x80, 0x82, 0x00, 0x0F}, "ims.example.net", 3)) == "ims.example.net", "a length in the 82 form"); + Check(ParseIsimValue(bytes({0x80, 0x23}, "001010123456789@private.example.net", 29)) == "001010123456789@private.example.net", "a private identity"); + Check(ParseIsimValue(bytes({0x80, 0x22}, "sip:001010123456789@ims.example.net", 30)) == "sip:001010123456789@ims.example.ne", "the length decides, not the bytes that follow"); + std::vector unused(64, 0xFF); + Check(!ParseIsimValue(unused).has_value(), "an unused record, all FF: no value"); + Check(!ParseIsimValue(bytes({0x81, 0x0F}, "ims.example.net", 0)).has_value(), "another tag: no value"); + Check(!ParseIsimValue(bytes({0x80, 0x10}, "ims.example.net", 0)).has_value(), "a length past the data: no value"); + Check(!ParseIsimValue(bytes({0x80, 0x00}, "", 4)).has_value(), "a length of zero: no value"); + Check(!ParseIsimValue(bytes({0x80, 0x83, 0x00, 0x00, 0x0F}, "ims.example.net", 0)).has_value(), "a length form of three bytes: no value"); + Check(!ParseIsimValue(bytes({0x80, 0x81}, "", 0)).has_value(), "an 81 form with no length byte: no value"); + Check(!ParseIsimValue(bytes({0x80, 0x82, 0x00}, "", 0)).has_value(), "an 82 form cut short: no value"); + Check(!ParseIsimValue(bytes({0x80}, "", 0)).has_value(), "the tag alone: no value"); + Check(!ParseIsimValue({}).has_value(), "no bytes: no value"); + Check(ParseIsimValue(bytes({0x80, 0x12}, "ims.example.net", 3)) == "ims.example.net", "FF at the end of the length are padding counted into it"); + std::vector ffInside = {0x80, 0x05, 'a', '.', 0xFF, '.', 'b'}; + Check(!ParseIsimValue(ffInside).has_value(), "an FF before the value's end: no value"); + std::vector ffOnly = {0x80, 0x03, 0xFF, 0xFF, 0xFF, 0xFF}; + Check(!ParseIsimValue(ffOnly).has_value(), "a length of nothing but FF: no value"); + Check(!ParseIsimValue(bytes({0x80, 0x0F}, "ims example.net", 0)).has_value(), "a blank in the value: no value"); + Check(!ParseIsimValue(bytes({0x80, 0x11}, "ims.example.net\r\n", 0)).has_value(), "a line break in the value: no value"); + std::vector nul = {0x80, 0x03, 'a', 0x00, 'b'}; + Check(!ParseIsimValue(nul).has_value(), "a NUL in the value: no value"); + std::vector utf8 = {0x80, 0x03, 'a', 0xC3, 0xA9}; + Check(!ParseIsimValue(utf8).has_value(), "a byte above ASCII in the value: no value"); + } + + // ---- the identity an ISIM holds + { + const Identity derived = MakeIdentity("001010123456789", "001", "01"); + // names unlike the derived ones: a domain of the operator's own + auto id = IsimIdentity(derived, "001010123456789@private.example.net", "one.example.net", "sip:001010123456789@one.example.net"); + Check(id.has_value(), "an ISIM's three values make an identity"); + Check(id && id->impi == "001010123456789@private.example.net", "the private identity is the card's"); + Check(id && id->domain == "one.example.net", "the home domain is the card's"); + Check(id && id->impu == "sip:001010123456789@one.example.net", "the public identity is the card's"); + Check(id && id->regUri == "sip:one.example.net", "the registration URI is that domain's"); + Check(id && id->imsi == derived.imsi && id->mcc == derived.mcc && id->mnc == derived.mnc, "the IMSI and the operator stay"); + // an ISIM that holds the names the IMSI gives: the same identity + auto same = IsimIdentity(derived, derived.impi, derived.domain, derived.impu); + Check(same && same->impi == derived.impi && same->domain == derived.domain && same->impu == derived.impu && same->regUri == derived.regUri, "the derived names from an ISIM give the derived identity"); + // a public identity that is a number, a domain with a hyphen and digits + Check(IsimIdentity(derived, "user@realm.example", "ims-1.example.net", "sip:+15555550100@ims-1.example.net").has_value(), "a number as the public identity, a hyphen in the domain"); + + auto no = [&](std::string_view impi, std::string_view domain, std::string_view impu) { return !IsimIdentity(derived, impi, domain, impu).has_value(); }; + const std::string_view P = "001010123456789@private.example.net", D = "one.example.net", U = "sip:001010123456789@one.example.net"; + Check(no("001010123456789", D, U), "a private identity without a realm is refused"); + Check(no("@private.example.net", D, U), "a private identity without a user is refused"); + Check(no("001010123456789@", D, U), "a private identity that ends at the @ is refused"); + Check(no("", D, U), "an empty private identity is refused"); + Check(no("0010101\"23456789@private.example.net", D, U), "a quote in the private identity is refused (it stands in a quoted string)"); + Check(no("001010123456789\\@private.example.net", D, U), "a backslash in the private identity is refused"); + Check(no("001010123456789@private.example.net\r\nVia: x", D, U), "a line break in the private identity is refused"); + Check(no("0010101 23456789@private.example.net", D, U), "a blank in the private identity is refused"); + Check(no(P, "", U), "an empty domain is refused"); + Check(no(P, "one.example.net>", U), "an angle bracket in the domain is refused"); + Check(no(P, "one_example.net", U), "an underscore in the domain is refused"); + Check(no(P, "one..example.net", U), "an empty label in the domain is refused"); + Check(no(P, ".one.example.net", U), "a domain that begins with a dot is refused"); + Check(no(P, "one.example.net.", U), "a domain that ends with a dot is refused"); + Check(no(P, "-one.example.net", U), "a label that begins with a hyphen is refused"); + Check(no(P, "one-.example.net", U), "a label that ends with a hyphen is refused"); + Check(no(P, "one.example.net-", U), "a domain that ends with a hyphen is refused"); + Check(no(P, "one.example.net:5060", U), "a port on the domain is refused"); + Check(no(P, "one.example.net;lr", U), "a parameter on the domain is refused"); + Check(no(P, "one.example.net\r\nRoute: ", U), "a line break in the domain is refused"); + Check(no(P, D, "tel:+15555550100"), "a tel: public identity is refused"); + Check(no(P, D, "sip:"), "a public identity that is the scheme alone is refused"); + Check(no(P, D, "001010123456789@one.example.net"), "a public identity without a scheme is refused"); + Check(no(P, D, "sip:001010123456789@one.example.net>;tag=x"), "an angle bracket in the public identity is refused (it stands between two)"); + Check(no(P, D, "sip:001010123456789@one.example.net"), "a line break in the public identity is refused"); + Check(no(P, D, "sip:0010101 23456789@one.example.net"), "a blank in the public identity is refused"); + Check(no(P, D, "sip:us\xC3\xA9r@one.example.net"), "a byte above ASCII in the public identity is refused"); + Check(no(P, std::string(64, 'a') + ".example.net", U), "a label of 64 characters in the domain is refused"); + Check(!no(P, std::string(63, 'a') + ".example.net", U), "a label of 63 characters is taken"); + Check(no(std::string(300, 'a') + "@x.example", D, U), "a private identity of 300 characters is refused"); + Check(no(std::string(246, 'a') + "@x.example", D, U), "a private identity of 256 characters is refused"); + Check(!no(std::string(245, 'a') + "@x.example", D, U), "a private identity of 255 characters is taken"); + Check(no(P, D, "sip:" + std::string(252, 'a')), "a public identity of 256 characters is refused"); + Check(!no(P, D, "sip:" + std::string(251, 'a')), "a public identity of 255 characters is taken"); + } + if (Failures == 0) std::println("Aka: all tests passed"); return Failures != 0; // not the count: `crafter-build test` takes an exit status of 77 for a skipped suite, and an exit status keeps 8 bits } diff --git a/tests/Messages/main.cpp b/tests/Messages/main.cpp index 64ef0c3..36103f4 100644 --- a/tests/Messages/main.cpp +++ b/tests/Messages/main.cpp @@ -18,7 +18,9 @@ // and left terminating access-domain selection routing incoming calls to // CS fallback (observed live 2026-07-20); and the REGISTERs' Security-Client // carries the default offer's two mechanisms, where the Python stack offered -// one cipher. Then the SMS over IP shapes: the +// one cipher. The two REGISTERs once more on an identity an ISIM holds: the +// pinned ones with the card's names in place of the derived ones. Then the +// SMS over IP shapes: the // +g.3gpp.smsip Contact tag behind Context::smsOverIp, the MESSAGE carrying // an RP-DATA to the service centre and the one carrying an RP-ACK to the // IP-SM-GW with In-Reply-To (TS 24.341 5.3.1.2, 5.3.2.4), and a final other @@ -251,6 +253,42 @@ int main() { Check(BuildRegisterProtected(c, "REGCALLID@2001:db8::db43", "FTAG5678", "REGBRANCH123456", 2, 7449812u, 176466735u, auth).contains("\r\nVia: SIP/2.0/TCP [2001:db8::db43]:45062;"), "default transport stays TCP"); } + // ---- the REGISTERs of an identity an ISIM holds (imsd::aka::IsimIdentity): + // every name is the card's — the Request-URI the home domain's, From and + // To the public identity, the digest's username the private identity, + // its realm the home domain; the rest of the message is the one pinned + // above. + { + Context ci = c; + ci.id = *imsd::aka::IsimIdentity(c.id, "001010123456789@private.example.net", "one.example.net", "sip:001010123456789@one.example.net"); + std::string want1(Reg1); + auto swap = [](std::string& s, std::string_view from, std::string_view to) { + int n = 0; + for (std::size_t at = s.find(from); at != std::string::npos; at = s.find(from, at + to.size())) { s.replace(at, from.size(), to); n++; } + return n; + }; + Check(swap(want1, "REGISTER sip:ims.mnc001.mcc001.3gppnetwork.org SIP/2.0", "REGISTER sip:one.example.net SIP/2.0") == 1, "the pinned REGISTER has one Request-URI"); + Check(swap(want1, "", "") == 2, "the pinned REGISTER has the public identity in From and To"); + Check(swap(want1, "username=\"001010123456789@ims.mnc001.mcc001.3gppnetwork.org\", realm=\"ims.mnc001.mcc001.3gppnetwork.org\", uri=\"sip:ims.mnc001.mcc001.3gppnetwork.org\"", + "username=\"001010123456789@private.example.net\", realm=\"one.example.net\", uri=\"sip:one.example.net\"") == 1, "the pinned REGISTER has one digest"); + Check(!want1.contains("3gppnetwork.org"), "no derived name is left in the expected REGISTER"); + Eq(BuildRegisterInitial(ci, "REGCALLID@2001:db8::db43", "FTAG5678", "REGBRANCH123456", 7449812u, 176466735u), want1, "unprotected REGISTER of an ISIM's identity"); + + std::string want2(Reg2); + swap(want2, "REGISTER sip:ims.mnc001.mcc001.3gppnetwork.org SIP/2.0", "REGISTER sip:one.example.net SIP/2.0"); + swap(want2, "", ""); + swap(want2, "username=\"001010123456789@ims.mnc001.mcc001.3gppnetwork.org\", realm=\"ims.mnc001.mcc001.3gppnetwork.org\", uri=\"sip:ims.mnc001.mcc001.3gppnetwork.org\"", + "username=\"001010123456789@private.example.net\", realm=\"one.example.net\", uri=\"sip:one.example.net\""); + Check(!want2.contains("3gppnetwork.org"), "no derived name is left in the expected protected REGISTER"); + std::string auth = AuthAka(ci, "NONCEXYZ", "CNONCE0123456789", "RESP0000"); + Eq(BuildRegisterProtected(ci, "REGCALLID@2001:db8::db43", "FTAG5678", "REGBRANCH123456", 2, 7449812u, 176466735u, auth), want2, "protected REGISTER of an ISIM's identity"); + // the Contact keeps the binding's own user-part: the IMSI here, as in + // the pinned message (an old state file's shape) + Check(BuildRegisterInitial(ci, "REGCALLID@2001:db8::db43", "FTAG5678", "REGBRANCH123456", 7449812u, 176466735u).contains("\r\nContact: "), "the Contact is not the public identity"); + // RuriFor with a home domain that is not a derived one + Eq(RuriFor("+31612345678", ci.id.domain), "sip:+31612345678@one.example.net;user=phone", "RuriFor puts a number at the domain it is given, an ISIM's here"); + } + // ---- RuriFor variants Eq(RuriFor("1233", c.id.domain), "sip:1233;phone-context=ims.mnc001.mcc001.3gppnetwork.org@ims.mnc001.mcc001.3gppnetwork.org;user=phone", "ruri short code"); Eq(RuriFor("+31612345678", c.id.domain), "sip:+31612345678@ims.mnc001.mcc001.3gppnetwork.org;user=phone", "ruri E.164");