diff --git a/AGENTS.md b/AGENTS.md index b7c0716..8b9105c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,8 +15,10 @@ bug — fix it in the same change. imsd is a userspace IMS/VoLTE client for mainline Linux phones. The modem firmware on such phones brings up the IMS PDN but cannot carry call audio, so -imsd does the whole IMS client itself: SIP registration with USIM AKA -authentication over kernel IPsec (ESP), call signalling for outgoing and +imsd does the whole IMS client itself: SIP registration — by default under +the identity the card's ISIM holds, else the one derived from the IMSI, with +AKA authentication in that ISIM, else in the USIM (§7.2) — over +kernel IPsec (ESP), call signalling for outgoing and incoming calls, and the RTP media plane (AMR-WB, AMR, G.711) wired into PipeWire, and since 1.2.0 short messages over IMS (TS 24.341: the SIP MESSAGE carrying an RP-DATA, a store, the Messaging interface — @@ -25,7 +27,8 @@ and GNOME Mobile — places and receives real VoLTE calls on a commercial network through it. It talks to the modem through ModemManager (`mmcli`) and `qmicli` over QRTR -(the USIM AKA run goes through a UIM logical channel) and, for the P-CSCF list +(the AKA run and the read of an ISIM's identity files go through UIM logical +channels) and, for the P-CSCF list the network put in the ims PDN's PCO, through its own QMI WDS client (`imsd-pcscf`, a raw QRTR socket bound to the bearer's mux data port — §13), installs its security @@ -139,7 +142,23 @@ both sides (1.0.0) is unbenched: no capture stages a holds file whose `pdn` is spelled unlike `LOCAL`). For the schedule, a reducer next to `RegRecovery`, with a Subscription-State parser in `Imsd:Sip` pinned by `tests/Sip`, is the follow-up that moves it; a pure format/parse pair in -`Imsd:Engine` is the holds file's. SMS over IP (1.2.0, §7.9) keeps in the +`Imsd:Engine` is the holds file's. The card's side (1.2.3, §7.2 step 2) +keeps in the shell the choice of the identity (`BringUp`: `ISIM=0`, no ISIM +application in the USIM's slot, an ISIM that gave none, and `FreshRecover`'s +asking of such an ISIM again), the read itself +(`ReadIsimIdentity`: the three files and their order, record 1 of EF_IMPU, +a SELECT's `61 XX` taken for the file selected, what its `why` says), the +channel (`UimChannel`: the open, the exchanges, the two follow-ups at most, +the close), the application the challenge goes to with its +fall-back to the USIM and the journal's words for an answer that is no +result (`Authenticate`, `AkaIn`), and which identity a +registration carries: the card's at a fresh registration, the one it was +made under at a resume (`TryResume`: the state file's three names, the +derived ones for a file that has none; `FreshRegister`'s restore after a +failed attempt) — the commands, the +answers' reading, the follow-up, the value of a file and the check of the +identity are `Imsd:Aka`'s, with tests; the shell's part ran against +stand-ins on the workstation (§5). SMS over IP (1.2.0, §7.9) keeps in the shell, among others, the service centre's source (`SMSC=` over EF_SMSP, `LoadSmsParameters`), the three counters (TP-MR, RP-MR, the concatenation reference), their seeding and the TP-MR file, the routing of an inbound MESSAGE @@ -527,7 +546,44 @@ Rules: selection of a null entry is pinned in `tests/Ipsec` with Odido's answer of 2026-07-13 to the Python stack's offer of the null cipher and ran against a stand-in P-CSCF on the workstation as far as the `SA:` line; - no capture holds a registration of imsd's over a null SA pair); a + no capture holds a registration of imsd's over a null SA pair); an + ISIM's identity and an AKA in an ISIM (1.2.3; the dev phone's card has no + ISIM: the daemon ran its registration on the workstation against a + stand-in for qmicli and a stand-in network that answers a first REGISTER + of any other names than its subscriber's 480 and tells the two + applications' answers to the challenge apart — the fp6 journal's + `2026-11-23-isim-identity` capture, 46 scenarios: a card without an + ISIM, an ISIM that holds names of the operator's own and one that holds + the derived names, `ISIM=0`, another slot's ISIM, an ISIM listed `ready` + or with no state; an ISIM that gives no identity (no channel, no answer + to a SELECT, to a read or to the GET RESPONSE after one, no EF_DOMAIN, + a refused read, an + unused or a `tel:` first record of EF_IMPU, a private identity without + a realm); reads answered `6C XX` or `61 XX` first, one after the other, + or `61 XX` to every GET RESPONSE (two are sent, then the read counts as + failed), reads that end `91 XX` or `62 82`, and a length that counts + the padding in; channels 4 and 5; an ISIM that refuses the AUTHENTICATE + or answers a + synchronisation failure, the USIM asked after it; no application giving + a result (both refusing; a USIM with no channel, with an answer of one + byte, of bytes that are no result, with no answer to the AUTHENTICATE + or to the GET RESPONSE after it); the registration + made again over UDP; a second bring-up in one run at which the ISIM + gives none; resumes — of a registration of a card without an ISIM, of + one made under the ISIM's names, with and without `ISIM=0` at the + restart, of one 1.2.2 made under the derived names on a card whose ISIM + holds others (kept under the derived names; refused by a network that + knows the card's names only, and registered fresh under those), of a + state file whose identity fails the check, with a fresh target and + without (also under a forced `SIP_TRANSPORT` that is not the file's), or + lacks one of the three names — and, in a run that resumed, a + fresh registration the network refuses (the reconnect after it goes out + under the standing registration's names) and fresh registrations before + which an ISIM that gave none at the bring-up is read again: giving its + identity at the first, or none again at the first and its identity at + the second. The reads' commands ran on two reporters' cards in the + journal's probe, §13; this daemon has sent no network a REGISTER with + names it read from an ISIM, and no real ISIM an AUTHENTICATE); a Security-Server list `PersistState` writes empty (one with a quote, a backslash or a newline — neither KPN's nor O2's list has one; the resume of such a file ran with a hand-edited empty key, @@ -1031,7 +1087,7 @@ The daemon's own bring-up (`BringUp()` in `main.cpp`): registration is due or a binding a NOTIFY terminated under the attempt write the registration off — either way the pair counts as one nothing can resume. A pair nothing can resume (its UE address left the link, no - state file, a file another attempt left behind, written off before this start or + state file, a file another attempt left behind or whose identity fails the check, written off before this start or given up by the engine during the attempt) is written off (`old_gone` in the holds — written as well for a pair `RESUME=0` leaves untried) and taken out of the kernel first (`the SA pair to … is nothing to resume: removing @@ -1040,7 +1096,37 @@ The daemon's own bring-up (`BringUp()` in `main.cpp`): 2. `qmicli -d qrtr://0 --uim-get-card-status` finds the ready USIM (slot, AID); `mmcli -m any` gives the primary SIM path and the IMEI (for the `+sip.instance` URN); `mmcli -i ` gives IMSI and MCC/MNC, from which - the IMPI/IMPU/realm are derived; with SMS over IP on and `SMSC=` unset, + the IMPI/IMPU/realm are derived (TS 23.003 13.2 to 13.4B) — the names + of a UE without an ISIM (TS 24.229 5.1.1.1A). Since 1.2.3, unless + `ISIM=0` is set, a card with an ISIM application in the USIM's slot + (`ParseIsimApp`, in whatever state the modem lists it) is asked for the + identity that ISIM holds: over a logical channel on the application imsd + reads EF_IMPI (the private identity), EF_DOMAIN (the home domain) and + record 1 of EF_IMPU (the public identity to register, GSMA IR.92 2.2.1), + each with a SELECT by file identifier and a read, and takes the three + when `IsimIdentity` accepts them (`identity: the ISIM's (application + state …): …`, with whether they are the names the IMSI gives). Then the + ISIM is asked for the answer to the challenge (step 4). When the card + has no ISIM, when `ISIM=0` is set, or when the ISIM gave no identity, + the derived identity and the USIM stand, as in 1.2.2, + and the `identity: derived from the IMSI …` line says which of the three + and, for the last, what was missing (§7.8). The read is made at every + bring-up of such a card, a resume's too, and at each recovery by a + fresh registration later in the same run (`FreshRecover`) while no read + since the bring-up has given one. That is the card's identity, and a fresh + registration is made under it. A resumed registration keeps the one it + was made under until its next fresh registration, as it keeps its + P-CSCF and its address (step 3): the state file records the three names + since 1.2.3, and a file without them is taken for one made under the + derived ones (`identity: the registration to + resume was made under …; it keeps them until the next fresh + registration, which takes the card's` when they are not the card's; + `identity: the fresh registration takes the card's: …` when that + registration comes under other names, and after an attempt that fails + the names are back that stood before it). The registration's home + domain is also what `RuriFor` and `ScPsi` take, for an outgoing call's + Request-URI and for the service centre's address of an SMS submission + (§12). With SMS over IP on and `SMSC=` unset, `qmicli --uim-read-record` of EF_SMSP record 1 names the service centre (§7.9). `mmcli --location-get` fills `P-Access-Network-Info`. @@ -1098,7 +1184,15 @@ The daemon's own bring-up (`BringUp()` in `main.cpp`): route (imsd's own `ip -6 route replace`; step 3 says which target), an unprotected REGISTER on `PCSCF_PORT` (UDP, always), the 401 with the AKA challenge and the `Security-Server` list, the AKA run over a UIM logical channel - (`--uim-open-logical-channel`, `--uim-send-apdu`), the SA pair installed + (`--uim-open-logical-channel`, `--uim-send-apdu`) — in the ISIM when the + card's identity was read from it, else in the USIM; the command is the + same (AUTHENTICATE with P2 `81`: the 3G context of TS 31.102 7.1.2, the + IMS AKA context of TS 31.103 7.1.2), and an ISIM that gives no result + is followed by the same challenge to the card's USIM (`AKA: the ISIM + application gave no result (…); asking the USIM`). TS 24.229 5.1.1.1A + has the ISIM used for authentication whenever the card has one: with + `ISIM=0`, with an ISIM that gave no identity and behind one that gives + no result imsd asks the USIM —, the SA pair installed with `ip xfrm`, the protected REGISTER over the negotiated transport (§10.1, `SIP_TRANSPORT`), `REGISTERED (fresh)`. Then the reg-event SUBSCRIBE (§7.4). @@ -1135,7 +1229,12 @@ The daemon's own bring-up (`BringUp()` in `main.cpp`): in-use SPIs) was refused with 503 (§13). The state file is JSON: `callid`, `ftag`, `cseq`, `spi_uc`, `spi_us`, -`expiry`, `route`, `ppi`, `aor`, `contact_user`, `transport`, since 1.0.0 +`expiry`, `route`, `ppi`, `aor`, `contact_user`, `transport`, since 1.2.3 +`impi`, `domain` and `impu` (the identity the registration was made under, +which a resume keeps — step 2; all three absent in an older file: the +derived identity; a file that holds one or two of them, or three that are +no identity `IsimIdentity` accepts, is not resumed: `the state file's +identity is not one imsd can register; …`), since 1.0.0 `pcscf` (the P-CSCF the registration was made to; named in the line that reports a file another attempt left behind — the check is the SPIs', `FileNamesAnotherPair`), since 0.3.12 @@ -1330,7 +1429,7 @@ The policy, with its constants: | A silent fresh attempt | Backs off 30 s → 10 min (`FreshDelayMin`/`Max`). | | `Retry-After` | Always wins over a shorter wait, honoured up to an hour (`RetryAfterMax`, the schedule's longest wait); a longer one is cut to an hour and the refusal heard again then. On a refused fresh attempt it replaces the schedule's wait, shorter or longer, never below 30 s (`FreshDelayMin`). | | A 403 | A refusal like the others: never hammered (the schedule), never abandoned (a SIM that is unbarred registers within the hour). | -| The old registration is gone | A 403 once a fresh registration is due, a fresh attempt that got past the SA setup, a binding the network terminated (reg-event), an older address that left the netdev, or a bring-up whose resume failed while a fresh registration follows (with no fresh target a resumable pair whose attempt failed is kept for the restart; a pair nothing can resume — given up or written off by the engine, its address off the link, no state file, a file another attempt left behind, left untried by `RESUME=0` — is written off and taken out of the kernel, §7.2 step 1): no reconnect over the old SA from then on. Otherwise the existing SA is still retried on the reconnect back-off while a fresh registration is deferred. | +| The old registration is gone | A 403 once a fresh registration is due, a fresh attempt that got past the SA setup, a binding the network terminated (reg-event), an older address that left the netdev, or a bring-up whose resume failed while a fresh registration follows (with no fresh target a resumable pair whose attempt failed is kept for the restart; a pair nothing can resume — given up or written off by the engine, its address off the link, no state file, a file another attempt left behind or whose identity fails the check, left untried by `RESUME=0` — is written off and taken out of the kernel, §7.2 step 1): no reconnect over the old SA from then on. Otherwise the existing SA is still retried on the reconnect back-off while a fresh registration is deferred. | | A `Dial` while unregistered | Brings the next recovery step forward (the reconnect, or the fresh attempt once it is due) — never a wait the network imposed (a `Retry-After`, or the schedule after a refused or throttled fresh attempt). imsd-ofonod refuses a `Dial` then and imsd-dialerd lists no modem. | | Success | Resets everything. | @@ -1344,7 +1443,8 @@ the SA setup, a binding the network terminated, an older address that left the netdev, and every bring-up that goes on to register fresh — its resume failed or there was nothing to resume; a bring-up with no fresh target writes `old_gone` when nothing can be resumed — a pair nothing can resume: its UE -address left the link, no state file, a file another attempt left behind, written +address left the link, no state file, a file another attempt left behind or whose +identity fails the check, written off before this start, given up or written off by the engine during the attempt, left untried by `RESUME=0` — never for a pair kept for the restart, §7.2 step 1); the reducer's refusal count travels too (`refusals`): a resume @@ -1592,8 +1692,33 @@ account `user`, its old default. Lines the operator (and the scripts) look for, all prefixed `imsd: `: -- `LOCAL=… P-CSCF=…`, `SIP transport: …`, `ESP ciphers offered: …`, `SIM slot=… IMSI=… domain=…` at start; +- `LOCAL=… P-CSCF=…`, `SIP transport: …`, `ESP ciphers offered: …`, `SIM slot=… IMSI=… domain=…` at start + (the home domain of the card's identity, which the line before names); `EALG entry '…' is not a cipher imsd can install; ignored` for a name in `EALG` that imsd cannot install. +- Before the `SIM slot=…` line, at every bring-up, where the identity is from (§7.2 step 2): `identity: the + ISIM's (application state S): private identity P, home domain D, public identity U; the names the IMSI gives` + or `…; not the names the IMSI gives (home domain D')`, `identity: derived from the IMSI (the card has no + ISIM application)`, `identity: derived from the IMSI (ISIM=0)`, `identity: derived from the IMSI: the ISIM + application (state S) gave none — …` with what was missing: `no logical channel opened on it`, `EF_X: the + SELECT answered `, `EF_X: the read answered `, `EF_X: no answer with a status + word to the SELECT`, `EF_X: an exchange of the read brought no answer with a status word` (the read or a + command the card asked for after it), `EF_X: no value in the N bytes read`, or `EF_IMPI '…', EF_DOMAIN + '…' and EF_IMPU record 1 '…' are no identity imsd can register`. At a resume whose + registration was made under other names than the card gives now: `identity: the registration to resume was + made under private identity P, home domain D, public identity U; it keeps them until the next fresh + registration, which takes the card's`; at a fresh registration under other names than the ones in use + before it: `identity: the fresh registration takes the card's: private identity P, home domain D, public + identity U`; + `the state file's identity is not one imsd can register; resume falls back to fresh` (with no fresh target + `…; nothing can resume it: the pair is removed`) for a file whose three names fail the check or that + holds one or two of them. At a recovery by a fresh registration, while the ISIM has given none since the + bring-up, it is read again and the line of that read follows: `identity: the ISIM's …` or + `… gave none — …`. +- `AKA: the ISIM application gave no result (…); asking the USIM` and, when no application gave one, `AKA: no + result (…)` before `USIM AKA failed`: `no logical channel opened`, `an exchange brought no answer with a + status word` (the AUTHENTICATE or a GET RESPONSE after it), + `status word `, `a synchronisation failure, tag DC`, or `N bytes that are no AKA result, + status word `. - `RESUME via existing SA (cseq N)`, `REGISTERED (resumed + true-refreshed)`, `FRESH registration`, `Security-Server: …`, `REGISTERED (fresh)`. - `bring-up deferred: …; next: fresh registration in N s` — one line; `in N @@ -2513,6 +2638,25 @@ only the imsd side of its bus choice. authorization is polkit's, not the policy file's. Keep it that way: a policy that names an account breaks the moment the account is called something else. +- What an ISIM's identity files hold goes into the requests of a + registration made under it. Its REGISTERs: the home domain as the + Request-URI's host and in the digest's quoted `realm` and `uri`, the + private identity inside the quoted `username`, the public identity + between the angle brackets of From and To. Beyond them: the home domain + in the address `RuriFor` makes of a dialled number, an outgoing call's + Request-URI and To (its host, and its phone-context where `RuriFor` + writes one), and as the host of the service centre's address of an SMS + submission (`ScPsi`: the MESSAGE's Request-URI and To); the public + identity, while no + P-Associated-URI has named another, as the reg-event SUBSCRIBE's + Request-URI, From and To (`BuildSubscribeReg`) and as the identity of + imsd's own requests (`CallerId`). `ParseIsimValue` takes no blank and no + byte outside printable ASCII and `IsimIdentity` no quote, backslash or + angle bracket, and in the domain nothing but letters, digits, hyphens + and dots, so a card cannot end a header field or a request line or add + one; a card whose values fail the check registers the derived names. The + journal prints the three as it prints the IMSI, and the state file holds + them. - SIP dumps and the state file carry the IMSI, the MSISDN, SPIs and addresses, and the state file (since 0.3.11) the last challenge answer — nonce, cnonce and response — and (since 0.3.12) the P-CSCF's @@ -2723,7 +2867,14 @@ the related code. 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`. + application does not have `6A 82`. The US card's network answered imsd + 1.1.0's first REGISTER, which carried the derived names + (`ims.mnc280.mcc310.3gppnetwork.org`), `480 Temporarily Unavailable` + (2026-11-09: a journal has the answer in the second the REGISTER was + sent, a dump of such an answer has no Reason, Warning or Retry-After) — + what TS 24.229 5.3.1.3 has an I-CSCF answer + when the HSS lookup "cannot be completed"; this daemon has not sent + that network the card's own names. - **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/README.md b/README.md index a0772c7..8fffcd9 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,7 @@ Configuration is environment variables in `/etc/imsd.env`, none are required. | `DEV` | `qmapmux0.0` | ims-PDN netdev; the packaged service passes the real one via `/run/imsd.env` | | `LOCAL` | *(auto)* | UE address (compared in RFC 5952 form). The packaged service gets the PDN address ModemManager assigned, via `/run/imsd.env` from `ims-pdn-up.sh`; a manual run prefers a global IPv6 on `DEV` that is neither temporary nor `dynamic` (RA-derived), then any non-temporary one, then the first (the kernel's temporary SLAAC address is listed first, and a registration bound to it is lost when the kernel retires it) | | `USER_AGENT` | `imsd/` | REGISTER User-Agent. Some networks fingerprint UAs; setting your device's stock build string reproduces the stock modem's registration exactly. Empty omits the header | +| `ISIM` | `1` | `0` registers the names derived from the IMSI and answers the challenge in the USIM, as 1.2.2 did. By default a card that has an ISIM registers the identity the ISIM holds (its private identity, home domain and first public identity) and the ISIM is asked for the answer to the challenge; a card without one, or with one imsd cannot use, registers the derived names. The journal's `identity:` line says which. A registration that stands keeps the names it was made under, so a change of the setting shows after a reboot | | `STATE_FILE` | `/var/lib/imsd/imsreg.state` (root) / `$XDG_STATE_HOME/imsd/imsreg.state` | persisted registration context for warm resume | | `HOLDS_FILE` | `/run/imsd.holds` (root) / `$XDG_RUNTIME_DIR/imsd.holds` (`/tmp/imsd.holds` without a runtime dir) | the waits the network imposed (a `Retry-After`, the refusal schedule), where that schedule stands whether the old registration is gone (`old_gone`) and the refusal count (`refusals`: a resume refused without a Retry-After at a start with no fresh target is one, the restart's the second), kept across a restart of imsd for the PDN they were set on — not across a reboot; `/dev/null` switches the file off (only a regular file is ever removed; anything else is emptied). `imsd-handover.sh` honours it too | | `RESUME` | `auto` | `0` forces a fresh registration (ignores a warm SA) where there is a fresh target; with none the untried pair is removed and the bring-up ends as AGENTS §7.2 (the daemon's own bring-up) step 1 says | diff --git a/implementations/main.cpp b/implementations/main.cpp index fe1c7ae..02fd75b 100644 --- a/implementations/main.cpp +++ b/implementations/main.cpp @@ -5,8 +5,10 @@ imsd — the userspace IMS/VoLTE daemon (control plane). Owns net.catcrafts.IMS1 on the system bus with the project's frozen D-Bus ABI -(AGENTS.md §8.1) and drives it with the engine core: register on the IMS PDN (USIM AKA -+ IPsec sec-agree, fresh or warm-resume, with a keepalive re-REGISTER refresh), +(AGENTS.md §8.1) and drives it with the engine core: register on the IMS PDN (by default the +identity the card's ISIM holds, else the one derived from the IMSI; AKA in that +ISIM, else in the USIM; IPsec sec-agree, fresh or warm-resume, with a keepalive +re-REGISTER refresh), run outgoing and incoming calls through the Imsd:Engine call machine (inbound INVITEs on the protected-port listeners become ringing calls a dialer answers via Accept), spawn one imsd-media data-plane process per answered call, and @@ -194,6 +196,90 @@ std::optional CompletedHex(std::string_view out) { return h; } +// ---- the card, through qmicli's UIM logical channels ---------------------- + +// A logical channel to one application of the card: opened on the +// application's AID, closed when the object goes. Exchange sends one command +// and returns the card's answer to it; Transmit also sends what the card asks +// for after it (imsd::aka::ApduFollowUp, for an answer without data: GET +// RESPONSE for '61 XX', a command without data again with the length a +// '6C XX' names — two follow-ups at most) and returns the last answer. +// nullopt when one of the exchanges +// brought no answer with a status word back: qmicli printed none, or fewer +// than two bytes. +class UimChannel { +public: + UimChannel(int slot, std::string_view aid) : slot_(slot) { + auto open = RunCapture({"qmicli", "-d", "qrtr://0", std::format("--uim-open-logical-channel={},{}", slot, aid)}); + if (auto ch = CompletedInt(open.out)) channel_ = static_cast(*ch); + } + UimChannel(const UimChannel&) = delete; + UimChannel& operator=(const UimChannel&) = delete; + ~UimChannel() { + if (channel_ >= 0) RunCapture({"qmicli", "-d", "qrtr://0", std::format("--uim-close-logical-channel={},{}", slot_, channel_)}); + } + bool Open() const { return channel_ >= 0; } + int Number() const { return channel_; } + std::optional Exchange(std::string_view apdu) const { + auto r = RunCapture({"qmicli", "-d", "qrtr://0", std::format("--uim-send-apdu={},{},{}", slot_, channel_, apdu)}); + auto hex = CompletedHex(r.out); + if (!hex) return std::nullopt; + auto bytes = imsd::util::FromHex(*hex); + if (!bytes) return std::nullopt; + return imsd::aka::ParseApduAnswer(*bytes); + } + std::optional Transmit(std::string apdu) const { + auto answer = Exchange(apdu); + for (int i = 0; answer && i < 2; i++) { + auto next = imsd::aka::ApduFollowUp(channel_, apdu, *answer); + if (!next) break; + apdu = std::move(*next); + answer = Exchange(apdu); + } + return answer; + } +private: + int slot_; + int channel_ = -1; +}; + +// Whether two identities are the same three names. +bool SameNames(const imsd::aka::Identity& a, const imsd::aka::Identity& b) { + return a.impi == b.impi && a.domain == b.domain && a.impu == b.impu; +} + +// The identity the card's ISIM application holds (TS 24.229 5.1.1.1A): the +// private identity of EF_IMPI, the home domain of EF_DOMAIN and the public +// identity of EF_IMPU's first record (GSMA IR.92 2.2.1), read over a logical +// channel on the application with the commands that read two reporters' +// cards (AGENTS.md §13); a SELECT's '61 XX' is taken for the file selected +// and the control parameters it offers are not fetched, as there. nullopt, +// with `why` saying what was missing, when it gives none. +std::optional ReadIsimIdentity(int slot, const imsd::aka::IsimApp& app, const imsd::aka::Identity& derived, std::string& why) { + UimChannel ch(slot, app.aid); + if (!ch.Open()) { why = "no logical channel opened on it"; return std::nullopt; } + auto read = [&](std::uint16_t file, std::string_view name, bool record) -> std::optional { + auto selected = ch.Exchange(imsd::aka::BuildSelectFileApdu(ch.Number(), file)); + if (!selected) { why = std::format("{}: no answer with a status word to the SELECT", name); return std::nullopt; } + if (!imsd::aka::Selected(*selected)) { why = std::format("{}: the SELECT answered {}", name, selected->Status()); return std::nullopt; } + auto got = ch.Transmit(record ? imsd::aka::BuildReadRecordApdu(ch.Number(), 1) : imsd::aka::BuildReadBinaryApdu(ch.Number())); + if (!got) { why = std::format("{}: an exchange of the read brought no answer with a status word", name); return std::nullopt; } + if (!imsd::aka::HoldsRead(*got)) { why = std::format("{}: the read answered {}", name, got->Status()); return std::nullopt; } + auto value = imsd::aka::ParseIsimValue(got->data); + if (!value) why = std::format("{}: no value in the {} bytes read", name, got->data.size()); + return value; + }; + auto impi = read(imsd::aka::EfImpi, "EF_IMPI", false); + if (!impi) return std::nullopt; + auto domain = read(imsd::aka::EfDomain, "EF_DOMAIN", false); + if (!domain) return std::nullopt; + auto impu = read(imsd::aka::EfImpu, "EF_IMPU record 1", true); + if (!impu) return std::nullopt; + auto id = imsd::aka::IsimIdentity(derived, *impi, *domain, *impu); + if (!id) why = std::format("EF_IMPI '{}', EF_DOMAIN '{}' and EF_IMPU record 1 '{}' are no identity imsd can register", *impi, *domain, *impu); + return id; +} + // The UE address on the ims PDN when LOCAL is not given: a global IPv6 on // that is neither temporary nor RA-derived (`dynamic`) — the one // ims-pdn-up.sh assigned from ModemManager — else the first non-temporary @@ -760,8 +846,15 @@ struct RegState { std::uint32_t spiUc = 0; std::uint32_t spiUs = 0; long expiry = 0; + // The card application the challenge goes to, by its slot and AID: the + // ISIM when the card's identity was read from it, else the USIM. int slot = 0; std::string aid; + // The identity this registration was made under. Set on the fresh 200 + // and when a resume takes its state file's (the file's since 1.2.3; the + // derived one for an older file, as 1.2.2 wrote it for a registration + // under it); empty before the first of either. + imsd::aka::Identity id; // Contact user-part of the stored binding (UUID since the s53 oracle // diff; empty = legacy IMSI binding from an older state file). std::string contactUser; @@ -815,6 +908,10 @@ void SaveTpMr(std::uint8_t mr) { // since 0.3.12. The file's values are quoted without escaping; a value // with a quote, a backslash or a newline in it (none RFC 3329's token // syntax produces) is written empty, and the resume falls back to the SA. +// `impi`, `domain` and `impu` (since 1.2.3) are the identity the +// registration was made under, which a resume keeps (TryResume); the three +// have passed imsd::aka::IsimIdentity or are MakeIdentity's, so none holds +// a character the quoting cannot carry. void PersistState(const RegState& r, const std::string& route, const std::string& ppi, const std::string& aor, const std::string& transport, const std::string& pcscf) { std::string ss = r.securityServer.find_first_of("\"\\\n") == std::string::npos ? r.securityServer : std::string(); std::string j = std::format( @@ -822,9 +919,11 @@ void PersistState(const RegState& r, const std::string& route, const std::string "\"spi_us\": {}, \"expiry\": {}, \"route\": \"{}\", \"ppi\": \"{}\", " "\"aor\": \"{}\", \"contact_user\": \"{}\", \"transport\": \"{}\", " "\"auth_nonce\": \"{}\", \"auth_cnonce\": \"{}\", \"auth_response\": \"{}\", " - "\"security_server\": \"{}\", \"pcscf\": \"{}\"}}", + "\"security_server\": \"{}\", \"pcscf\": \"{}\", " + "\"impi\": \"{}\", \"domain\": \"{}\", \"impu\": \"{}\"}}", r.callid, r.ftag, r.cseq, r.spiUc, r.spiUs, r.expiry, route, ppi, aor, - r.contactUser, transport, r.authNonce, r.authCnonce, r.authResponse, ss, pcscf); + r.contactUser, transport, r.authNonce, r.authCnonce, r.authResponse, ss, pcscf, + r.id.impi, r.id.domain, r.id.impu); std::string path = StatePath(); std::error_code ec; std::filesystem::create_directories(std::filesystem::path(path).parent_path(), ec); @@ -850,7 +949,7 @@ void DumpRaw(std::string_view name, std::string_view msg) { } struct PersistedState { - std::optional callid, ftag, route, ppi, aor, contactUser, transport, authNonce, authCnonce, authResponse, securityServer, pcscf; + std::optional callid, ftag, route, ppi, aor, contactUser, transport, authNonce, authCnonce, authResponse, securityServer, pcscf, impi, domain, impu; std::optional cseq, spiUc, spiUs, expiry; }; std::optional LoadState() { @@ -873,6 +972,9 @@ std::optional LoadState() { ps.authResponse = QuotedAfter(s, "\"auth_response\": \""); ps.securityServer = QuotedAfter(s, "\"security_server\": \""); // absent in pre-0.3.12 files ps.pcscf = QuotedAfter(s, "\"pcscf\": \""); // absent in pre-1.0.0 files + ps.impi = QuotedAfter(s, "\"impi\": \""); // the three absent in pre-1.2.3 files + ps.domain = QuotedAfter(s, "\"domain\": \""); + ps.impu = QuotedAfter(s, "\"impu\": \""); ps.cseq = IntAfter(s, "\"cseq\": "); ps.spiUc = IntAfter(s, "\"spi_uc\": "); ps.spiUs = IntAfter(s, "\"spi_us\": "); @@ -1636,7 +1738,7 @@ private: // what follows a resume that failed: with a fresh target the fresh // registration, without one the restart's new resume attempt std::string ResumeFailedNext() const { return pcscfTarget_.empty() ? "the restart tries the resume again" : "the next registration is a fresh one"; } - // a pair nothing can resume (no state file, the file another attempt's): with a fresh target the fresh registration replaces it; with none BringUp writes it off and takes it out of the kernel + // a pair nothing can resume (no state file, the file another attempt's or its identity failing the check): with a fresh target the fresh registration replaces it; with none BringUp writes it off and takes it out of the kernel std::string ResumeDeadNext() const { return pcscfTarget_.empty() ? "nothing can resume it: the pair is removed" : "resume falls back to fresh"; } // the failed resume's line tail by the engine's verdict: a registration it // wrote off is removed (no fresh target) or replaced by the fresh one; with @@ -1685,6 +1787,22 @@ private: // registration imsd::msg::Context ctx_; RegState reg_; + // The identity the card gives — its ISIM's, else the one derived from + // the IMSI — and the derived one. A fresh registration is made under the + // first. A resumed one keeps the identity it was made under (reg_.id) + // until the next fresh registration, as it keeps its P-CSCF and its + // address: the binding to refresh is the one made under those names. + imsd::aka::Identity cardId_; + imsd::aka::Identity derivedId_; + // The card's USIM: the challenge goes to it when the identity is not an + // ISIM's, and after an ISIM that gave the identity and gives no result + // for the challenge. + std::string usimAid_; + // The ISIM application that has given no identity since the bring-up: + // asked again at each recovery by a fresh registration later in the + // same run (FreshRecover), which else would go out under the derived + // names. + std::optional isimOwed_; std::string route_, ppi_, ss_; std::string simOperator_; // the SIM's operator id as read at bring-up: MCC then MNC bool registered_ = false; @@ -1798,7 +1916,8 @@ private: auto siminfo = RunCapture({"mmcli", "-i", *simPath}); auto info = imsd::aka::ParseSimInfo(siminfo.out); if (!info) throw std::runtime_error("SIM IMSI/operator not found"); - ctx_.id = imsd::aka::MakeIdentity(info->imsi, info->mcc, info->mnc); + derivedId_ = imsd::aka::MakeIdentity(info->imsi, info->mcc, info->mnc); + cardId_ = derivedId_; simOperator_ = info->mcc + info->mnc; ctx_.local = local_; ctx_.ealgOffer = ealgOffer_; @@ -1816,7 +1935,26 @@ private: if (auto imei = imsd::aka::ParseEquipmentId(modem.out)) if (auto urn = imsd::aka::ImeiUrn(*imei)) ctx_.instanceId = *urn; reg_.slot = sel->slot; - reg_.aid = sel->aid; + reg_.aid = usimAid_ = sel->aid; + // The identity so far is the one TS 23.003 derives from the IMSI, + // the names of a UE without an ISIM (TS 24.229 5.1.1.1A). When the + // card's ISIM gives an identity, that one is the card's and the + // challenge goes to the ISIM. The names can be the operator's own: a US + // card on AT&T's network holds @private.att.net and + // one.att.net, and the derived names drew a 480 to the first + // REGISTER there (2026-11-09; the read of the card 2026-11-23, + // AGENTS.md §13). An ISIM that gives none leaves the derived + // identity and the USIM, what 1.2.2 registered with; ISIM=0 asks for + // that. + std::optional app; + if (EnvOr("ISIM", "1") == "0") { + Log("identity: derived from the IMSI (ISIM=0)"); + } else { + app = imsd::aka::ParseIsimApp(card.out, sel->slot); + if (!app) Log("identity: derived from the IMSI (the card has no ISIM application)"); + } + isimOwed_ = app && !TakeIsimIdentity(*app) ? app : std::nullopt; + ctx_.id = cardId_; Log(std::format("SIM slot={} IMSI={} domain={}", sel->slot, info->imsi, ctx_.id.domain)); ctx_.smsOverIp = smsOverIp_; if (smsOverIp_) LoadSmsParameters(); @@ -1874,7 +2012,8 @@ private: // binding; a 401, a refusal with a Retry-After, the second refusal — // the count travels in the holds; Dead above); a pair nothing can // resume (its UE address left the link, no - // state file, the file another attempt's, written off before this + // state file, the file another attempt's or its identity failing + // the check, written off before this // start) is written off and taken out of the kernel by exact key // — the fresh registration that would have replaced it does not // come — so the next bring-up finds nothing to resume, and the @@ -1968,11 +2107,27 @@ private: sa->spiUc, sa->spiUs, pcscf_, ResumeDeadNext())); return ResumeOutcome::Dead; } + // The registration's identity is the one it was made under, whatever + // the card gives today: the file's since 1.2.3, and for an older file + // the derived one, under which 1.2.2 registered. A file whose three + // names are no identity imsd can write names a registration nothing + // can refresh, whatever else the file holds: judged before the + // transport, as the file of another attempt is. + imsd::aka::Identity made = derivedId_; + if (ps->impi || ps->domain || ps->impu) { + auto filed = imsd::aka::IsimIdentity(derivedId_, ps->impi.value_or(""), ps->domain.value_or(""), ps->impu.value_or("")); + if (!filed) { Log(std::format("the state file's identity is not one imsd can register; {}", ResumeDeadNext())); return ResumeOutcome::Dead; } + made = *filed; + } // The registration's transport is what the P-CSCF knows; a resume // must reuse it. A forced policy that disagrees means a fresh start // — decided before anything from the file is adopted. Transport t = ps->transport.value_or("TCP") == "UDP" ? Transport::Udp : Transport::Tcp; if (sipPolicy_ != "auto" && t != transport_) { Log(std::format("state file transport differs from SIP_TRANSPORT; {}", ResumeFailedNext())); return ResumeOutcome::Failed; } + if (!SameNames(made, cardId_)) + Log(std::format("identity: the registration to resume was made under private identity {}, home domain {}, public identity {}; it keeps them until the next fresh registration, which takes the card's", made.impi, made.domain, made.impu)); + ctx_.id = made; + reg_.id = made; route_ = ps->route.value_or(std::format("", imsd::util::HostPort(pcscf_, sa->portPs))); // No fallback identity: an empty ppi omits P-Preferred-Identity and @@ -2004,7 +2159,8 @@ private: } // The public identity our requests are signed with (From) — restored // here so a call placed before the refresh 200 re-learns it does not - // fall back to the barred temporary IMPU. + // fall back to the identity's own (for a registration made under the + // derived names, the temporary IMPU). ctx_.aor = ps->aor.value_or(""); ctx_.route = route_; ctx_.ppi = ppi_; ctx_.securityServer = ss_; ctx_.portUc = PortUc; ctx_.portUs = PortUs; @@ -2050,18 +2206,48 @@ private: Log(std::format("binding: {}", ct)); } + // The ISIM application's identity for the card: when the three files + // read and pass the check it is the card's, and the challenge goes to + // the ISIM. The journal's `identity:` line says which way it went. + bool TakeIsimIdentity(const imsd::aka::IsimApp& app) { + std::string state = app.state.empty() ? "unknown" : app.state; + std::string why; + auto id = ReadIsimIdentity(reg_.slot, app, derivedId_, why); + if (!id) { + Log(std::format("identity: derived from the IMSI: the ISIM application (state {}) gave none — {}", state, why)); + return false; + } + cardId_ = *id; + reg_.aid = app.aid; + Log(std::format("identity: the ISIM's (application state {}): private identity {}, home domain {}, public identity {}; {}", + state, id->impi, id->domain, id->impu, + SameNames(cardId_, derivedId_) ? "the names the IMSI gives" : std::format("not the names the IMSI gives (home domain {})", derivedId_.domain))); + return true; + } + // A fresh registration. The attempt mints its own Contact user-part into // ctx_ for its REGISTERs; on any failure the stored binding's comes back, // so requests over the existing SA meanwhile (a reconnect, a refresh) // carry the binding the network knows. reg_ takes the new one on the 200. + // The identity goes the same way: the attempt registers the card's + // (cardId_), and on a failure the one ctx_ held before it comes back — + // a resumed registration's can be another than the card's (TryResume). void FreshRegister() { saReplaced_ = false; + imsd::aka::Identity before = ctx_.id; try { FreshRegisterAttempt(); } - catch (...) { ctx_.contactUser = reg_.contactUser; throw; } + catch (...) { + ctx_.contactUser = reg_.contactUser; + ctx_.id = before; + throw; + } } void FreshRegisterAttempt() { Log("FRESH registration"); + if (!SameNames(ctx_.id, cardId_)) + Log(std::format("identity: the fresh registration takes the card's: private identity {}, home domain {}, public identity {}", cardId_.impi, cardId_.domain, cardId_.impu)); + ctx_.id = cardId_; // Oracle diff (journal/ims.md s53): stock's Contact user-part is a // fresh UUID per registration, not the IMSI. Minted before reg1 so // both REGISTERs and the stored binding carry the same URI. @@ -2204,6 +2390,7 @@ private: } reg_.callid = callidReg; reg_.ftag = ftag; reg_.cseq = 2; reg_.contactUser = contactUser; + reg_.id = ctx_.id; reg_.spiUc = spiUc; reg_.spiUs = spiUs; reg_.authNonce = *nonceB64; reg_.authCnonce = cnonce; reg_.authResponse = response; reg_.securityServer = ss_; @@ -2385,33 +2572,40 @@ private: Log(std::format("self AOR: {}", ctx_.aor.empty() ? ctx_.id.impu : ctx_.aor)); } - // USIM AKA via qmicli UIM logical channel. + // AKA in the card: the challenge to the application that goes with the + // card's identity (reg_.aid: the ISIM when the identity was read from it, + // else the USIM), over a UIM logical channel. The command is the same in + // both: AUTHENTICATE with P2 '81' is the 3G context of a USIM (TS 31.102 + // 7.1.2) and the IMS AKA context of an ISIM (TS 31.103 7.1.2), and both + // answer RES, CK and IK under tag DB. + // An ISIM that gives no result is not the end of the attempt: the same + // card's USIM is asked, where 1.2.2 sent every challenge — + // no AKA in a real ISIM has run on this code (AGENTS.md §5). std::optional Authenticate(std::span rand16, std::span autn16) { - auto open = RunCapture({"qmicli", "-d", "qrtr://0", - std::format("--uim-open-logical-channel={},{}", reg_.slot, reg_.aid)}); - auto ch = CompletedInt(open.out); - if (!ch) return std::nullopt; - int channel = static_cast(*ch); - auto closeCh = [&] { - RunCapture({"qmicli", "-d", "qrtr://0", - std::format("--uim-close-logical-channel={},{}", reg_.slot, channel)}); - }; - std::string apdu = imsd::aka::BuildAkaApdu(channel, rand16, autn16); - auto r1 = RunCapture({"qmicli", "-d", "qrtr://0", - std::format("--uim-send-apdu={},{},{}", reg_.slot, channel, apdu)}); - auto b1 = CompletedHex(r1.out); - if (!b1) { closeCh(); return std::nullopt; } - if (b1->size() >= 2 && b1->substr(0, 2) == "61") { - std::string gr = imsd::aka::BuildGetResponseApdu(channel, std::stoi(b1->substr(2, 2), nullptr, 16)); - auto r2 = RunCapture({"qmicli", "-d", "qrtr://0", - std::format("--uim-send-apdu={},{},{}", reg_.slot, channel, gr)}); - b1 = CompletedHex(r2.out); - if (!b1) { closeCh(); return std::nullopt; } + std::string what; + auto result = AkaIn(reg_.aid, rand16, autn16, what); + if (!result && reg_.aid != usimAid_) { + Log(std::format("AKA: the ISIM application gave no result ({}); asking the USIM", what)); + result = AkaIn(usimAid_, rand16, autn16, what); } - closeCh(); - auto bytes = imsd::util::FromHex(*b1); - if (!bytes) return std::nullopt; - return imsd::aka::ParseAkaResponse(*bytes); + if (!result) Log(std::format("AKA: no result ({})", what)); + return result; + } + + // One AUTHENTICATE in the application `aid` of the card in reg_.slot; + // `what` says why there is no result. + std::optional AkaIn(const std::string& aid, std::span rand16, std::span autn16, std::string& what) { + UimChannel ch(reg_.slot, aid); + if (!ch.Open()) { what = "no logical channel opened"; return std::nullopt; } + auto answer = ch.Transmit(imsd::aka::BuildAkaApdu(ch.Number(), rand16, autn16)); + if (!answer) { what = "an exchange brought no answer with a status word"; return std::nullopt; } + auto result = imsd::aka::ParseAkaResponse(*answer); + if (!result) { + what = answer->data.empty() ? std::format("status word {}", answer->Status()) + : answer->data[0] == 0xDC ? std::string("a synchronisation failure, tag DC") + : std::format("{} bytes that are no AKA result, status word {}", answer->data.size(), answer->Status()); + } + return result; } // ---- keepalive refresh (only while idle) ------------------------------ @@ -2610,6 +2804,9 @@ private: bool ok = false; try { RefreshPani(); + // an ISIM that has given no identity since the bring-up is asked + // again: its names can be the only ones the network takes + if (isimOwed_ && TakeIsimIdentity(*isimOwed_)) isimOwed_.reset(); FreshRegister(); subRetryAt_ = 0; // a new registration: its subscription starts afresh OnRegistered(); diff --git a/interfaces/Imsd-Messages.cppm b/interfaces/Imsd-Messages.cppm index d11bf35..5500ed1 100644 --- a/interfaces/Imsd-Messages.cppm +++ b/interfaces/Imsd-Messages.cppm @@ -352,7 +352,8 @@ export namespace imsd::msg { // The identity we sign our own requests with: the registered public // identity (P-Associated-URI sip: entry), else the tel: one, and the - // IMSI-derived temporary IMPU only before either is learned. 3GPP allows + // identity's own (an ISIM's first, or the IMSI-derived temporary IMPU) + // only before either is learned. 3GPP allows // the temporary IMPU in REGISTER alone; a P-CSCF that does not overwrite // From shows it to the callee (Telia, 2026-09-01: the reporter's IMSI on // the far phone) and a strict one may reject the request.