// SPDX-License-Identifier: GPL-3.0-only // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® /* 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 (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), 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. Digest and parser behavior is pinned by tests/Aka. */ export module Imsd:Aka; import std; import :Util; export namespace imsd::aka { // 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; std::string mnc; // already zero-padded to 3 digits std::string domain; // ims.mncXXX.mccYYY.3gppnetwork.org std::string impi; // @ std::string impu; // sip:@ std::string regUri; // sip: }; // Build the identity from IMSI + MCC + a (2- or 3-digit) MNC. The MNC is // zero-padded to 3 digits, matching the Python detect_sim()/mnc.zfill(3) // — KPN's operator id 20408 becomes mnc008 in the domain. Identity MakeIdentity(std::string_view imsi, std::string_view mcc, std::string_view mnc) { std::string mnc3(mnc); while (mnc3.size() < 3) mnc3.insert(mnc3.begin(), '0'); Identity id; id.imsi = imsi; id.mcc = mcc; id.mnc = mnc3; id.domain = std::format("ims.mnc{}.mcc{}.3gppnetwork.org", mnc3, mcc); id.impi = std::format("{}@{}", imsi, id.domain); id.impu = std::format("sip:{}@{}", imsi, id.domain); id.regUri = std::format("sip:{}", id.domain); return id; } // AKAv1-MD5 digest-response (RFC 3310 §3.2): HA1 = MD5(IMPI:realm:RES) // where RES is the *binary* AKA result, HA2 = MD5(method:uri), and the // response = MD5(HA1:nonce:nc:cnonce:qop:HA2). realm is the home domain. std::string DigestAkav1(std::string_view nonce, std::span res, std::string_view cnonce, std::string_view uri, std::string_view impi, std::string_view realm, std::string_view nc = "00000001", std::string_view qop = "auth", std::string_view method = "REGISTER") { imsd::util::Md5 h1; h1.Update(impi); h1.Update(":"); h1.Update(realm); h1.Update(":"); h1.Update(res); std::string ha1 = imsd::util::ToHex(h1.Digest()); std::string ha2 = imsd::util::Md5::HexDigest(std::format("{}:{}", method, uri)); return imsd::util::Md5::HexDigest(std::format("{}:{}:{}:{}:{}:{}", ha1, nonce, nc, cnonce, qop, ha2)); } // The ready USIM of a card status: its slot and its AID. struct SimSelection { int slot = 0; std::string aid; // uppercase, colons stripped }; // 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) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); }; while (i < s.size()) { if (i + 2 > s.size() || !hex(s[i]) || !hex(s[i + 1])) return false; i += 2; pairs++; if (i == s.size()) break; if (s[i] != ':') return false; 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 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); 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 && detail::AidLine(t)) { if (ready && !out) out = SimSelection{curSlot, detail::AidOf(t)}; inUsim = false; } if (nl == std::string_view::npos) break; pos = nl + 1; } 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:"); if (at == std::string_view::npos) return std::nullopt; std::string_view rest = text.substr(at + std::string_view("primary sim path:").size()); std::size_t nl = rest.find('\n'); std::string_view line = rest.substr(0, nl == std::string_view::npos ? rest.size() : nl); while (!line.empty() && (line.front() == ' ' || line.front() == '\t')) line.remove_prefix(1); while (!line.empty() && (line.back() == ' ' || line.back() == '\t' || line.back() == '\r')) line.remove_suffix(1); if (line.empty()) return std::nullopt; return std::string(line); } struct SimInfo { std::string imsi; std::string mcc; std::string mnc; // as printed (operator id minus mcc), not padded }; // Grab a labelled numeric value ("imsi:" / "operator id:") from mmcli -i // output. Values are digit runs. namespace detail { inline std::optional Digits(std::string_view text, std::string_view label) { std::size_t at = text.find(label); if (at == std::string_view::npos) return std::nullopt; std::size_t i = at + label.size(); while (i < text.size() && (text[i] == ' ' || text[i] == '\t')) i++; std::size_t start = i; while (i < text.size() && text[i] >= '0' && text[i] <= '9') i++; if (i == start) return std::nullopt; return std::string(text.substr(start, i - start)); } } // "equipment id: " (15 digits) from `mmcli -m any`. std::optional ParseEquipmentId(std::string_view text) { return detail::Digits(text, "equipment id:"); } // RFC 7254 IMEI URN from a 15-digit IMEI (TAC-SNR-check digit) — the // +sip.instance value a UE registers with; nullopt for anything else. std::optional ImeiUrn(std::string_view imei) { if (imei.size() != 15) return std::nullopt; for (char c : imei) if (c < '0' || c > '9') return std::nullopt; return std::format("urn:gsma:imei:{}-{}-{}", imei.substr(0, 8), imei.substr(8, 6), imei.substr(14)); } // IMSI + operator id (MCC = first 3 digits, MNC = the rest) from `mmcli -i`. std::optional ParseSimInfo(std::string_view text) { auto imsi = detail::Digits(text, "imsi:"); auto op = detail::Digits(text, "operator id:"); if (!imsi || !op || op->size() < 4) return std::nullopt; SimInfo s; s.imsi = *imsi; s.mcc = op->substr(0, 3); s.mnc = op->substr(3); return s; } // P-Access-Network-Info value from `mmcli -m any --location-get`: // "3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=" // (TS 24.229 7.2A.4: E-UTRAN cell id = MCC + MNC as broadcast + 16-bit // TAC + 28-bit ECI; mmcli prints both hex fields zero-padded wider, so // take the low digits). The stock modem sends exactly this shape in // every REGISTER/INVITE — the TAS reads it to see which access the UE // is reachable on. FDD is a constant: every KPN LTE band in use is FDD // and MM does not expose the duplex mode. nullopt when the fields are // missing or zero (no serving cell) — callers then omit the header // rather than fabricate one. std::optional ParsePani(std::string_view text) { auto mcc = detail::Digits(text, "operator mcc:"); auto mnc = detail::Digits(text, "operator mnc:"); auto hexAfter = [&](std::string_view label) -> std::optional { std::size_t at = text.find(label); if (at == std::string_view::npos) return std::nullopt; std::size_t i = at + label.size(); while (i < text.size() && (text[i] == ' ' || text[i] == '\t')) i++; std::size_t start = i; while (i < text.size() && std::isxdigit(static_cast(text[i]))) i++; if (i == start) return std::nullopt; return std::string(text.substr(start, i - start)); }; auto tac = hexAfter("tracking area code:"); auto ci = hexAfter("cell id:"); if (!mcc || !mnc || !tac || !ci) return std::nullopt; if (tac->size() > 4) *tac = tac->substr(tac->size() - 4); while (tac->size() < 4) tac->insert(tac->begin(), '0'); if (ci->size() > 7) *ci = ci->substr(ci->size() - 7); while (ci->size() < 7) ci->insert(ci->begin(), '0'); if (tac->find_first_not_of('0') == std::string::npos && ci->find_first_not_of('0') == std::string::npos) return std::nullopt; return std::format("3GPP-E-UTRAN-FDD;utran-cell-id-3gpp={}{}{}{}", *mcc, *mnc, *tac, *ci); } // ---- AUTHENTICATE(AKA) APDU (ISO 7816-4 over the qmicli UIM channel) ---- // The class byte of a command on a logical channel (ETSI TS 102 221 // 10.1.1): '0X' with the channel in its two low bits for the standard // channels 0 to 3, '4X' with the channel less four in its low nibble for // the extended ones, 4 to 19. Before 1.2.3 the channel number itself was // the class byte, which is the first form only: a command for channel 4 // went out as '04', channel 0 with a secure-messaging bit set. inline int ClassByte(int channel) { return channel < 4 ? channel & 0x03 : 0x40 | ((channel - 4) & 0x0F); } // The command APDU (hex, no separators) for a 3G AKA authentication: // CLA= INS=88 P1=00 P2=81 Lc [10 RAND(16) 10 AUTN(16)] // `channel` is the logical-channel number qmicli returned. std::string BuildAkaApdu(int channel, std::span rand16, std::span autn16) { std::string data = std::format("10{}10{}", imsd::util::ToHex(rand16), imsd::util::ToHex(autn16)); std::size_t lc = data.size() / 2; // CLA INS=88 P1=00 P2=81 Lc return std::format("{:02x}880081{:02x}{}", ClassByte(channel), lc, data); } // GET RESPONSE APDU for when the card answers 61xx (xx bytes available). std::string BuildGetResponseApdu(int channel, int le) { 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; std::vector ik; }; // Parse the card's AUTHENTICATE response body. `resp` is the raw APDU // response INCLUDING the trailing SW1 SW2 (two status bytes), which are // stripped here. A successful 3G AKA body is: // DB L_RES RES.. L_CK CK.. L_IK IK.. // (tag 0xDB = "AKA success"; 0xDC would be sync-failure). nullopt on a // short buffer, a non-DB tag, or a length that runs past the end. std::optional ParseAkaResponse(std::span resp) { if (resp.size() < 3) return std::nullopt; std::span body = resp.subspan(0, resp.size() - 2); if (body.empty() || body[0] != 0xDB) return std::nullopt; std::size_t i = 1; auto take = [&](std::vector& out) -> bool { if (i >= body.size()) return false; std::size_t n = body[i++]; if (i + n > body.size()) return false; out.assign(body.begin() + i, body.begin() + i + n); i += n; return true; }; AkaResult r; 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)); } }