From 57c414de0719ef37839f30be4509ad9a8d9c5d90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BD=D1=82=D0=BE=D0=BD=20=D0=A2=D1=80=D0=BE=D1=88?= =?UTF-8?q?=D0=B8=D0=BD?= Date: Mon, 31 Aug 2026 22:32:32 +0300 Subject: [PATCH] v1.9.21: SCP80 docs as parent section, GP+JavaCard AID labels, UX fixes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Docs: - SCP80 tab is now a parent section (3) with subsections 3.1/3.2/3.3 - Renumbered sections: Response parser→4, Card reader→5, Server→6, Version compat→7 - Applied to help.html, help-ru.html, README.md, README_RUS.md C-APDU/RAM form labels (GP + JavaCard terminology): - AID → Application / Instance AID - ELF AID → Load File AID / Package AID - Module AID → Executable Module AID / Applet Class AID SCP80/RAM explorer labels (GP + JavaCard terminology): - ISD → ISD (Issuer Security Domain) - Applications → Applications / Applet Instances - Executable Load Files → Executable Load Files (ELFs) / Packages - AID → Application/Instance AID or Load File AID/Package AID (context-dependent) - Module AIDs → Executable Module AIDs / Applet Class AIDs UX fixes: - Delete All button now matches Delete button style (red) - Explorer results cleared when switching away from Explore Card operation - KIc/KID dropdowns (index + algorithm) now update when selecting saved card - Added LANG_RU translations for new labels --- README.md | 287 +++++++++++++++-------------- README_RUS.md | 327 +++++++++++++++++++--------------- frontend/help-ru.html | 97 ++++++---- frontend/help.html | 98 ++++++---- frontend/index.html | 250 ++++++++++++++++++++++++-- frontend/sw.js | 2 +- pysim_otaman_server/server.py | 5 +- 7 files changed, 681 insertions(+), 385 deletions(-) diff --git a/README.md b/README.md index f27486c..f4fb6d5 100644 --- a/README.md +++ b/README.md @@ -31,15 +31,19 @@ npm run build ## Interface -Five tabs, each with a form and a "Generate" button. +Four top-level tabs: **C-APDU**, **SCP80**, **Response parser**, **Card reader**. The C-APDU and SCP80 tabs each have sub-tabs. --- -## SIM RFM Tab +## C-APDU tab + +Builds command APDUs (C-APDUs). Five sub-tabs cover different card generations and command sets. + +### SIM RFM CLA = `A0` (GSM 11.11 / ISO 7816-4). -### Commands +#### Commands | Command | INS | Description | |---|---|---| @@ -54,56 +58,48 @@ CLA = `A0` (GSM 11.11 / ISO 7816-4). | VERIFY PIN | 20 | Verify PIN1 or PIN2 | | CHANGE PIN | 24 | Change PIN1 or PIN2 | -### SELECT methods +#### SELECT methods | Method | P1 | P2 | Input | |---|---|---|---| -| По FID | 00 | 00 | 2-byte FID (4 hex) | -| По полному пути от MF | 08 | 00 | Full path hex from MF | -| По DF name / AID | 04 | 00 | AID (application ID) | -| ADF RFM цепочка | 00 | 00 | Comma-separated FIDs, each selected in turn | +| By FID | 00 | 00 | 2-byte FID (4 hex) | +| By full path from MF | 08 | 00 | Full path hex from MF | +| By DF name / AID | 04 | 00 | AID (application ID) | +| ADF RFM chain | 00 | 00 | Comma-separated FIDs, each selected in turn | -### Options +#### Options -- **Начать с SELECT** — checkbox to prepend a SELECT command before the operation. When unchecked, the operation is sent standalone with CLA. -- **Режим выборки (P2)** — for record commands: Absolute (04), Next (06), Previous (02). -- **Размер записи** — pad/truncate data to the specified byte count. -- **Переопределить P1/P2** — checkbox to enable manual override of P1/P2 bytes. +- **Start with SELECT** — checkbox to prepend a SELECT command before the operation. When unchecked, the operation is sent standalone with CLA. +- **Selection mode (P2)** — for record commands: Absolute (04), Next (06), Previous (02). +- **Record size** — pad/truncate data to the specified byte count. +- **Allow P1/P2 editing** — checkbox to enable manual override of P1/P2 bytes. -### Conversion sidebar - -A conversion panel is embedded in the right-hand column, supporting IMSI, MSISDN, ICCID, SPN, PLMN, and Nibble swap conversions. - -### References +#### References - ISO/IEC 7816-4: Organization, security and commands for interchange - ETSI TS 102 226: Remote APDU structure for UICC based applications - GSM 11.11: SIM-ME Interface ---- - -## USIM RFM Tab +### USIM RFM CLA = `00` (ETSI TS 102 221). Same commands as SIM, but SELECT uses P1=09, P2=0C (by FID from current directory). -### References +#### References - ETSI TS 102 221: UICC-Terminal Interface; Physical and Logical Characteristics - ETSI TS 102 226: Remote APDU structure for UICC based applications ---- - -## Expanded Script Tab +### Expanded Script Builds Expanded Remote Application data format per ETSI TS 102 226 §5.2.1. -### Format +#### Format Two encoding variants: - **Definite (AA)**: `AA` + length + Command TLVs - **Indefinite (AE)**: `AE` + `80` + Command TLVs + `00 00` -### Command TLVs +#### Command TLVs | Type | Tag | Description | |---|---|---| @@ -112,7 +108,7 @@ Two encoding variants: | Error Action | 82 | Proactive command on error | | Script Chaining | 83 | Chaining data for multi-packet scripts | -### Immediate Action builder +#### Immediate Action builder When the type is set to Immediate Action, the tool provides a structured builder for: @@ -122,54 +118,17 @@ When the type is set to Immediate Action, the tool provides a structured builder Error Action supports the same builder (DISPLAY TEXT, PLAY TONE). -### References +#### References - ETSI TS 102 226 V13.0.0 §5.2.1: Expanded Remote Application data format - ETSI TS 102 223: Card Application Toolkit (CAT) — proactive command structure - ETSI TS 101 220: BER-TLV tag assignments ---- +### RAM/GP -## RAM Tab +CLA = `80` (GlobalPlatform Card Specification v2.3.1). Remote Application Management commands for card content management. -CLA = `80` (GlobalPlatform Card Specification v2.3.1). Remote Application Management operations for card content management over SCP80. - -All RAM operations are delivered as SCP80 secured packets (ETSI TS 102 225) via SMS-PP-DOWNLOAD ENVELOPE. The card must support SCP03 (AES or 3DES) for secure transport. - -### Card Preset - -Select a saved card configuration from the **Card preset** dropdown. Each preset stores: - -| Field | Description | -|---|---| -| SPI1 / SPI2 | Security level and PoR settings | -| KIc / KID key | Encryption and MAC key hex | -| KIc / KID index | Key version number | -| TAR | Toolkit Application Reference (3 bytes) | -| Counter (CNTR) | 10-digit hex replay counter, auto-incremented after each successful SCP80 send | - -Card presets are managed in the **SCP80 → Cards** subtab (see below). If no preset is selected, the RAM tab warns and refuses to execute. - -### Operations - -The RAM subtab offers two operations selected from the **Operation** dropdown: - -| Operation | Description | -|---|---| -| **Explore Card (all GP data)** | Queries GET STATUS for ISD, Applications, ELFs, and ELF Modules, plus GET DATA FF21 for memory info. Results appear in an explorer view with per-item **Delete** buttons. | -| **Install Package (.cap file)** | Sends a `.cap` file to the card via the server: INSTALL\[for load\] → LOAD ×N → INSTALL\[for install (+make selectable)\]. | - -### Explorer View - -After "Explore Card" runs, the explorer view displays: - -- **ISD** — AID, lifecycle, privileges (no delete; the ISD cannot be removed) -- **Applications** — AID, lifecycle, privileges, associated ELF/SD. Each has a **Delete** button (GP `DELETE` by AID). -- **Executable Load Files** — AID, lifecycle, version, module AIDs. Each has **Delete** (ELF only) and **Delete All** (cascade: ELF + modules + installed Applications, P2=0x80) buttons. - -Delete confirms via a browser prompt before sending the GP `DELETE` command via SCP80. The explorer auto-refreshes after a successful deletion. - -### GP Commands Reference +#### GP Commands Reference | Command | INS | P1 | Description | |---|---|---|---| @@ -187,7 +146,7 @@ Delete confirms via a browser prompt before sending the GP `DELETE` command via | EXTERNAL AUTHENTICATE | 82 | 00 | SCP host authentication | | INTERNAL AUTHENTICATE | 88 | 00 | Card challenge-response | -### INSTALL [for install] — Privilege Builder +#### INSTALL [for install] — Privilege Builder Tag `C7` in the INSTALL data field. Built from 3 privilege bytes (GP spec Tables 11-7, 11-8, 11-9): @@ -218,7 +177,7 @@ Tag `C7` in the INSTALL data field. Built from 3 privilege bytes (GP spec Tables |---|---| | b8 | Receipt Generation | -### INSTALL [for install] — SIM/UICC Toolkit Parameters +#### INSTALL [for install] — SIM/UICC Toolkit Parameters Optional TLV objects appended to the INSTALL data field: @@ -235,7 +194,7 @@ Optional TLV objects appended to the INSTALL data field: | 16 | RC/DS/CC + MAC + Cipher | | 19 | RC/DS/CC + MAC + Cipher + DS | -### GET STATUS P1 values +#### GET STATUS P1 values | Value | Meaning | |---|---| @@ -244,7 +203,7 @@ Optional TLV objects appended to the INSTALL data field: | 20 | Executable Load Files | | 10 | ELF and their Executable Modules | -### GET STATUS P2 values +#### GET STATUS P2 values | Value | Meaning | |---|---| @@ -253,7 +212,7 @@ Optional TLV objects appended to the INSTALL data field: | 00 | First/all, old format (deprecated) | | 02 | Next, old format (deprecated) | -### GET DATA tag values +#### GET DATA tag values | Tag | Data Object | |---|---| @@ -271,14 +230,14 @@ Optional TLV objects appended to the INSTALL data field: | 7F21 | Certificate (SD public key) | | 5031 | Certificate info (EF.OD) | -### DELETE P1 values +#### DELETE P1 values | Value | Meaning | |---|---| | 00 | By AID | | 80 | Delete associated objects | -### STORE DATA P1 values +#### STORE DATA P1 values | Value | Meaning | |---|---| @@ -287,7 +246,7 @@ Optional TLV objects appended to the INSTALL data field: | 80 | Last block, encrypted | | C0 | More blocks, encrypted | -### SET STATUS parameters +#### SET STATUS parameters **P1 (Status Type)**: | Value | Target | @@ -302,18 +261,68 @@ Optional TLV objects appended to the INSTALL data field: | 00 | Unlock (return to previous state) | | 80 | Lock (LOCKED state) | -### References +#### References - GlobalPlatform Card Specification v2.3.1 (GPC_Spec_v2.3.1): Commands, Privileges, TLV structures - ETSI TS 102 226 V13.0.0 §8.2.1.3.2: SIM/UICC Toolkit parameters, MSL, TAR, Access Domain +### Conversion (SIM/USIM sidebars) + +Value encoding conversions embedded in the SIM RFM and USIM RFM tabs. + +#### IMSI → EF.IMSI + +Per TS 31.102 §4.2.3. Encodes a 15-digit IMSI into the 9-byte EF.IMSI format: +- Byte 0: number of subsequent bytes (8) +- Odd/even indicator nibble in the last byte +- BCD digits, swapped nibble pairs per identity + +Input: 15 decimal digits. Output: 18 hex characters. + +#### MSISDN → BCD + +Strips leading `+`, pads odd length with `f`, swaps nibble pairs. + +#### ICCID → hex + +Swaps nibble pairs of the ICCID string. + +#### Provider Name → SPN + +Per 3GPP TS 31.102 §4.2.5 (EF_SPN). Three encoding paths: + +1. **GSM 7-bit packed** (all chars in GSM 7-bit default alphabet): prefix `01`, DCS byte (spare bits), packed septets, 0xFF padding to 16 bytes. +2. **UCS2 non-BMP** (emoji / chars > U+FFFF): prefix `00`, DCS `80`, UTF-16BE, 0xFF padding to 16 bytes. +3. **UCS2 BMP non-GSM7** (Cyrillic, etc.): prefix `00`, DCS `81`, base byte, per-char offsets, 0xFF padding to 16 bytes. + +GSM 7-bit alphabet per 3GPP TS 23.038. Full extension table supported. + +#### PLMN → EF_PLMNsel / PLMNwAcT + +Per TS 31.102 §4.2.3. 3-byte BCD encoding for PLMN, plus optional 2-byte Access Technology selector. + +#### Nibble swap + +Swaps nibble pairs of an even-length hex string. + +#### References + +- 3GPP TS 31.102: Characteristics of the USIM Application +- 3GPP TS 23.038: Alphabets and language information +- ETSI TS 102 225: Secured packet structure for (U)SIM toolkit +- pySim: enc_imsi() implementation + --- -## SCP80 Tab — Secured Packet +## SCP80 tab -The **SCP80** top-level tab groups SCP80-related views, switched by two pills: **Secured Packet** (this section) and **Cards**. Assembles secured packets per ETSI TS 102 225. +The **SCP80** top-level tab groups SCP80-related views, switched by three pills: **Secured Packet**, **Cards**, and **RAM**. Assembles secured packets per ETSI TS 102 225. -### Packet structure +### Secured Packet + +Builds SCP80 secured packets per ETSI TS 102 225. + +#### Packet structure | Field | Size | Description | |---|---|---| @@ -330,7 +339,7 @@ The **SCP80** top-level tab groups SCP80-related views, switched by two pills: * | RC/CC/DS | 8 | Cryptographic Checksum / MAC | | Secured Data | variable | Padded APDU (encrypted if required) | -### SPI1 (Security Level) +#### SPI1 (Security Level) SPI1 bit layout (TS 102 225 §5.1.1): `b8–b6` padding, `b5–b4` counter, `b3` ciphering, `b2–b1` RC/CC/DS. @@ -350,7 +359,7 @@ SPI1 bit layout (TS 102 225 §5.1.1): `b8–b6` padding, `b5–b4` counter, `b3` > **AES requires `b5 b4 = 10` (higher) or `11` (+1)** per TS 102 225 §5.1.2 and §5.1.3.1. > The 3DES values `00/01/02/06` (no counter) remain valid for 3DES only. -### SPI2 (PoR settings) +#### SPI2 (PoR settings) | Value | Mode | Security | Cipher | |---|---|---|---| @@ -363,7 +372,7 @@ SPI1 bit layout (TS 102 225 §5.1.1): `b8–b6` padding, `b5–b4` counter, `b3` | 02 | PoR on error | None | No | | 06 | PoR on error | RC | No | -### Crypto +#### Crypto - **3DES-CBC** encryption (zero ICV), supporting 8, 16, and 24 byte keys — deprecated since Rel-18, still supported for backwards compatibility - **AES-CBC** encryption (zero ICV, zero-padded to 16), supporting 16, 24, and 32 byte keys (TS 102 225 §5.1.2, KIc `x2`) @@ -371,14 +380,7 @@ SPI1 bit layout (TS 102 225 §5.1.1): `b8–b6` padding, `b5–b4` counter, `b3` - **AES-CMAC** (NIST SP 800-38B, truncated to 8 octets) for the AES cryptographic checksum (TS 102 225 §5.1.3.1, KID `x2`) - Padding byte configurable (`00` per TS 102 225 default, or `FF`) -### References - -- ETSI TS 102 225 V18.1.0: Secured packet structure for UICC based applications -- ETSI TS 102 226: Remote APDU structure for UICC based applications -- ISO 9797-1: MAC algorithms -- NIST SP 800-38B: CMAC - -### PoR (Proof of Reception) +#### PoR (Proof of Reception) PoR confirms the card received and executed the secured packet. Two modes: @@ -389,9 +391,24 @@ PoR confirms the card received and executed the secured packet. Two modes: Delivery PoR (SPI2 `01`) is simpler — the card returns the PoR directly in the ENVELOPE response. Submit PoR (SPI2 `21`) is used when the card cannot respond inline (e.g. during ELF operations where the ENVELOPE response space is limited). -### Cards Subtab +#### References -The **Cards** pill in the SCP80 tab manages saved card configurations (presets). Each preset stores the cryptographic keys, SPI settings, TAR, and replay counter needed for SCP80 operations. +- ETSI TS 102 225 V18.1.0: Secured packet structure for UICC based applications +- ETSI TS 102 226: Remote APDU structure for UICC based applications +- ISO 9797-1: MAC algorithms +- NIST SP 800-38B: CMAC + +### Cards + +Stores saved card configurations (presets). Each preset stores the cryptographic keys, SPI settings, TAR, and replay counter needed for SCP80 operations. + +| Field | Description | +|---|---| +| SPI1 / SPI2 | Security level and PoR settings | +| KIc / KID key | Encryption and MAC key hex | +| KIc / KID index | Key version number | +| TAR | Toolkit Application Reference (3 bytes) | +| Counter (CNTR) | 10-digit hex replay counter, auto-incremented after each successful SCP80 send | **Add a card:** fill in the name, SPI1/SPI2, KIc/KID keys and indices, TAR, and click **Add**. The card appears in the list and becomes available in the RAM tab's **Card preset** dropdown. @@ -401,57 +418,41 @@ The **Cards** pill in the SCP80 tab manages saved card configurations (presets). **Counter:** the 10-digit hex counter (CNTR) is auto-incremented after each successful SCP80 send (both manual Secured Packet sends and RAM operations). The updated counter is saved back to the preset automatically. ---- +### RAM -## Conversion (SIM/USIM sidebars) +All RAM operations are delivered as SCP80 secured packets (ETSI TS 102 225) via SMS-PP-DOWNLOAD ENVELOPE. The card must support SCP03 (AES or 3DES) for secure transport. -Value encoding conversions embedded in the SIM RFM and USIM RFM tabs. +Select a saved card configuration from the **Card preset** dropdown. If no preset is selected, the RAM tab warns and refuses to execute. -### IMSI → EF.IMSI +The RAM subtab offers two operations selected from the **Operation** dropdown: -Per TS 31.102 §4.2.3. Encodes a 15-digit IMSI into the 9-byte EF.IMSI format: -- Byte 0: number of subsequent bytes (8) -- Odd/even indicator nibble in the last byte -- BCD digits, swapped nibble pairs per identity +| Operation | Description | +|---|---| +| **Explore Card (all GP data)** | Queries GET STATUS for ISD, Applications, ELFs, and ELF Modules, plus GET DATA FF21 for memory info. Results appear in an explorer view with per-item **Delete** buttons. | +| **Install Package (.cap file)** | Sends a `.cap` file to the card via the server: INSTALL\[for load\] → LOAD ×N → INSTALL\[for install (+make selectable)\]. | -Input: 15 decimal digits. Output: 18 hex characters. +#### Explorer View -### MSISDN → BCD +After "Explore Card" runs, the explorer view displays: -Strips leading `+`, pads odd length with `f`, swaps nibble pairs. +- **ISD** — AID, lifecycle, privileges (no delete; the ISD cannot be removed) +- **Applications** — AID, lifecycle, privileges, associated ELF/SD. Each has a **Delete** button (GP `DELETE` by AID). +- **Executable Load Files** — AID, lifecycle, version, module AIDs. Each has **Delete** (ELF only) and **Delete All** (cascade: ELF + modules + installed Applications, P2=0x80) buttons. -### ICCID → hex - -Swaps nibble pairs of the ICCID string. - -### Provider Name → SPN - -Per 3GPP TS 31.102 §4.2.5 (EF_SPN). Three encoding paths: - -1. **GSM 7-bit packed** (all chars in GSM 7-bit default alphabet): prefix `01`, DCS byte (spare bits), packed septets, 0xFF padding to 16 bytes. -2. **UCS2 non-BMP** (emoji / chars > U+FFFF): prefix `00`, DCS `80`, UTF-16BE, 0xFF padding to 16 bytes. -3. **UCS2 BMP non-GSM7** (Cyrillic, etc.): prefix `00`, DCS `81`, base byte, per-char offsets, 0xFF padding to 16 bytes. - -GSM 7-bit alphabet per 3GPP TS 23.038. Full extension table supported. - -### PLMN → EF_PLMNsel / PLMNwAcT - -Per TS 31.102 §4.2.3. 3-byte BCD encoding for PLMN, plus optional 2-byte Access Technology selector. - -### Nibble swap - -Swaps nibble pairs of an even-length hex string. - -### References - -- 3GPP TS 31.102: Characteristics of the USIM Application -- 3GPP TS 23.038: Alphabets and language information -- ETSI TS 102 225: Secured packet structure for (U)SIM toolkit -- pySim: enc_imsi() implementation +Delete confirms via a browser prompt before sending the GP `DELETE` command via SCP80. The explorer auto-refreshes after a successful deletion. --- +## Response parser tab +Decodes a raw command response: pick the command that was sent, enter the SW (e.g. `9000`) and the response data hex, then press **Decode**. + +- **Command** — SIM/USIM group (SELECT, STATUS, READ/UPDATE, PIN ops, CAT commands like TERMINAL PROFILE/ENVELOPE/FETCH/TERMINAL RESPONSE, MANAGE CHANNEL, ...) or RAM/GP group (INSTALL, LOAD, DELETE, GET/STORE DATA, auth, SCP commands). +- **SW decode** — status words resolved against generic, UICC (TS 102 221), and GlobalPlatform maps, with context auto-detected. +- **Privilege decode** — GET DATA / INSTALL response payloads decode the privilege bytes into human-readable flags. +- **Response data** — raw hex rendered and interpreted per command (e.g. SELECT FCP templates). + +--- ## Card Reader (pySim integration) @@ -480,11 +481,9 @@ Custom files persist in `localStorage` across sessions. Export/import as JSON fo ### Proactive UICC Pill -The **Proactive UICC** sub-tab in the Card Reader provides real-time CAT session -interaction: +The **Proactive UICC** sub-tab in the Card Reader provides real-time CAT session interaction: -**Subscribed Events** — the card's SET UP EVENT LIST is displayed with per-event -**Send** buttons. Clicking opens a form specific to the event type: +**Subscribed Events** — the card's SET UP EVENT LIST is displayed with per-event **Send** buttons. Clicking opens a form specific to the event type: - **No-data events** (User Activity, Idle Screen, etc.) — single-click confirmation - **Location Status** — dropdown for Normal / Limited / No service @@ -495,13 +494,9 @@ interaction: technology selection, and 53-cause unified rejection cause code dropdown covering EMM, GMM, 5GMM, and LU causes -**Proactive Command Log** — chronological list of proactive commands encountered -(seconds elapsed, type code, name, byte count). Covers SET UP MENU, SET UP EVENT -LIST, POLL INTERVAL, DISPLAY TEXT, SELECT ITEM, and PROVIDE LOCAL INFORMATION. +**Proactive Command Log** — chronological list of proactive commands encountered (seconds elapsed, type code, name, byte count). Covers SET UP MENU, SET UP EVENT LIST, POLL INTERVAL, DISPLAY TEXT, SELECT ITEM, and PROVIDE LOCAL INFORMATION. -**PLI Data Dictionary** — editable per-qualifier hex values for all 22 PROVIDE -LOCAL INFORMATION qualifiers (TS 102 223 + TS 131 111). 10 qualifiers have -inline decode/encode forms (▶ toggle): +**PLI Data Dictionary** — editable per-qualifier hex values for all 22 PROVIDE LOCAL INFORMATION qualifiers (TS 102 223 + TS 131 111). 10 qualifiers have inline decode/encode forms (toggle): | Code | Decoded fields | |------|--------------| @@ -516,14 +511,14 @@ inline decode/encode forms (▶ toggle): | 0A | Battery charge (%) | | 0E | Multiple Access Technologies (comma-list) | -Values persist on the server until restart. Apply → hex updates; Save → POSTs to -server. The server will use these values to populate TERMINAL RESPONSE data for -future PLI proactive commands. +Values persist on the server until restart. Apply → hex updates; Save → POSTs to server. The server will use these values to populate TERMINAL RESPONSE data for future PLI proactive commands. ### Command Hints Type a command name in the **pySim command line** input. Usage hints appear as a tooltip after 300ms. Command autocomplete suggestions appear above the input. +--- + ## PWA OTAMan is a Progressive Web App and can be installed for offline use. Use the **INSTALL PWA** button in the header, or use the browser's install prompt. diff --git a/README_RUS.md b/README_RUS.md index 028126f..59d2fad 100644 --- a/README_RUS.md +++ b/README_RUS.md @@ -31,15 +31,19 @@ npm run build ## Интерфейс -Пять вкладок, каждая с формой и кнопкой «Generate APDU». +Четыре вкладки: **C-APDU**, **SCP80**, **Response parser**, **Card reader**. Вкладки C-APDU и SCP80 имеют подвкладки. --- -## Вкладка SIM RFM +## Вкладка C-APDU + +Построение команд APDU (C-APDU). Пять подвкладок для разных поколений карт и наборов команд. + +### SIM RFM CLA = `A0` (GSM 11.11 / ISO 7816-4). -### Команды +#### Команды | Команда | INS | Описание | |---|---|---| @@ -54,7 +58,7 @@ CLA = `A0` (GSM 11.11 / ISO 7816-4). | VERIFY PIN | 20 | Проверка PIN1 или PIN2 | | CHANGE PIN | 24 | Смена PIN1 или PIN2 | -### Методы SELECT +#### Методы SELECT | Метод | P1 | P2 | Ввод | |---|---|---|---| @@ -63,46 +67,38 @@ CLA = `A0` (GSM 11.11 / ISO 7816-4). | By DF name / AID | 04 | 00 | AID | | ADF RFM chain | 00 | 00 | FID через запятую | -### Опции +#### Опции - **Start with SELECT** — добавить SELECT перед командой. - **Selection mode (P2)** — для record-команд: Absolute (04), Next (06), Previous (02). - **Record size** — дополнить/обрезать данные до указанного размера. - **Allow P1/P2 editing** — ручное редактирование P1/P2. -### Боковая панель конвертации - -Поддерживает IMSI, MSISDN, ICCID, SPN, PLMN, Nibble swap. - -### Ссылки +#### Ссылки - ISO/IEC 7816-4: Organization, security and commands for interchange - ETSI TS 102 226: Remote APDU structure for UICC based applications - GSM 11.11: SIM-ME Interface ---- - -## Вкладка USIM RFM +### USIM RFM CLA = `00` (ETSI TS 102 221). Те же команды, что и SIM, но SELECT использует P1=09, P2=0C. -### Ссылки +#### Ссылки - ETSI TS 102 221: UICC-Terminal Interface - ETSI TS 102 226: Remote APDU structure ---- - -## Вкладка Expanded Script +### Expanded Script Построение Expanded Remote Application data format по ETSI TS 102 226 §5.2.1. -### Формат +#### Формат - **Definite (AA)**: `AA` + длина + Command TLV - **Indefinite (AE)**: `AE` + `80` + Command TLV + `00 00` -### Command TLV +#### Command TLV | Тип | Тег | Описание | |---|---|---| @@ -111,60 +107,23 @@ CLA = `00` (ETSI TS 102 221). Те же команды, что и SIM, но SELE | Error Action | 82 | Proactive-команда при ошибке | | Script Chaining | 83 | Данные для многопакетных скриптов | -### Сборщик Immediate Action +#### Сборщик Immediate Action - **Action indicator**: `81` / `82` - **Proactive command**: REFRESH, DISPLAY TEXT, PLAY TONE - **Custom hex**: ручной ввод -### Ссылки +#### Ссылки - ETSI TS 102 226 §5.2.1 - ETSI TS 102 223: Card Application Toolkit - ETSI TS 101 220: BER-TLV tag assignments ---- - -## Вкладка RAM +### RAM/GP CLA = `80` (GlobalPlatform v2.3.1). Удалённое управление содержимым карты через SCP80. -Все операции RAM отправляются как защищённые пакеты SCP80 (ETSI TS 102 225) через SMS-PP-DOWNLOAD ENVELOPE. Карта должна поддерживать SCP03 (AES или 3DES) для безопасной транспортировки. - -### Выбор карты (Card Preset) - -Выберите сохранённую конфигурацию карты из выпадающего списка **Card preset**. Каждый пресет хранит: - -| Поле | Описание | -|---|---| -| SPI1 / SPI2 | Уровень безопасности и настройки PoR | -| Ключ KIc / KID | Hex ключи шифрования и MAC | -| Индекс KIc / KID | Номер версии ключа | -| TAR | Toolkit Application Reference (3 байта) | -| Счётчик (CNTR) | 10-значный hex счётчик повторов, автоматически увеличивается после каждой успешной отправки SCP80 | - -Пресеты карт управляются во вкладке **SCP80 → Cards** (см. ниже). Если пресет не выбран, RAM-вкладка предупреждает и отказывается выполнять. - -### Операции - -В RAM-подвкладке доступны две операции через выпадающий список **Operation**: - -| Операция | Описание | -|---|---| -| **Explore Card (all GP data)** | Запрос GET STATUS для ISD, приложений, ELF и модулей ELF, а также GET DATA FF21 для информации о памяти. Результаты отображаются в обзоре с кнопками **Delete** для каждого элемента. | -| **Install Package (.cap file)** | Отправка `.cap` файла на карту через сервер: INSTALL\[for load\] → LOAD ×N → INSTALL\[for install (+make selectable)\]. | - -### Обзор карты (Explorer View) - -После выполнения "Explore Card" отображается: - -- **ISD** — AID, жизненный цикл, привилегии (без удаления; ISD нельзя удалить) -- **Приложения** — AID, жизненный цикл, привилегии, связанный ELF/SD. Каждое имеет кнопку **Delete** (GP `DELETE` по AID). -- **Executable Load Files** — AID, жизненный цикл, версии, AID модулей. Каждый имеет **Delete** (только ELF) и **Delete All** (каскадное: ELF + модули + установленные приложения, P2=0x80). - -Удаление подтверждается через диалог браузера перед отправкой команды GP `DELETE` через SCP80. Обзор автоматически обновляется после успешного удаления. - -### Справочник GP-команд +#### Справочник GP-команд | Команда | INS | P1 | Описание | |---|---|---|---| @@ -182,7 +141,7 @@ CLA = `80` (GlobalPlatform v2.3.1). Удалённое управление со | EXTERNAL AUTHENTICATE | 82 | 00 | Аутентификация SCP | | INTERNAL AUTHENTICATE | 88 | 00 | Challenge-response | -### Привилегии (INSTALL) +#### Привилегии (INSTALL [for install]) Три байта привилегий по GP Spec Tables 11-7, 11-8, 11-9. @@ -213,7 +172,7 @@ CLA = `80` (GlobalPlatform v2.3.1). Удалённое управление со |---|---| | b8 | Receipt Generation | -### Параметры SIM/UICC Toolkit +#### Параметры SIM/UICC Toolkit - **Tag `CA`** (SIM Toolkit): Priority, Timers, Text Length, Menu Entries, Positions, Channels, MSL, TAR, Access Domain - **Tag `80`** (UICC Toolkit, внутри `EA`): те же поля без Access Domain @@ -228,7 +187,7 @@ CLA = `80` (GlobalPlatform v2.3.1). Удалённое управление со | 16 | RC/DS/CC + MAC + Cipher | | 19 | RC/DS/CC + MAC + Cipher + DS | -### GET STATUS P1 +#### GET STATUS P1 | Значение | Описание | |---|---| @@ -237,7 +196,7 @@ CLA = `80` (GlobalPlatform v2.3.1). Удалённое управление со | 20 | Executable Load Files | | 10 | ELF и модули | -### GET STATUS P2 +#### GET STATUS P2 | Значение | Описание | |---|---| @@ -246,7 +205,7 @@ CLA = `80` (GlobalPlatform v2.3.1). Удалённое управление со | 00 | Первые/все, старый формат (deprecated) | | 02 | Следующие, старый формат (deprecated) | -### GET DATA теги +#### GET DATA теги | Тег | Объект данных | |---|---| @@ -264,14 +223,14 @@ CLA = `80` (GlobalPlatform v2.3.1). Удалённое управление со | 7F21 | Certificate (SD public key) | | 5031 | Certificate info (EF.OD) | -### DELETE P1 +#### DELETE P1 | Значение | Описание | |---|---| | 00 | Только AID | | 80 | AID и связанные объекты | -### STORE DATA P1 +#### STORE DATA P1 | Значение | Описание | |---|---| @@ -280,24 +239,64 @@ CLA = `80` (GlobalPlatform v2.3.1). Удалённое управление со | 80 | Последний блок, с шифрованием | | C0 | Ещё блоки, с шифрованием | -### SET STATUS +#### SET STATUS **P1:** 80 = ISD, 40 = Приложение или SSD, 60 = SD и его приложения **P2:** 00 = Разблокировать, 80 = Заблокировать (LOCKED) -### Ссылки +#### Ссылки - GlobalPlatform Card Specification v2.3.1 - ETSI TS 102 226 §8.2.1.3.2: Параметры SIM/UICC Toolkit +### Конвертация (боковые панели SIM/USIM) + +#### IMSI → EF.IMSI + +15-значный IMSI → 9 байт EF.IMSI. + +#### MSISDN → BCD + +Удаление `+`, добавление `f`, обмен полубайтов. + +#### ICCID → hex + +Обмен полубайтов строки ICCID. + +#### Provider Name → SPN + +По 3GPP TS 31.102 §4.2.5. Три варианта кодирования: +1. GSM 7-bit packed +2. UCS2 non-BMP +3. UCS2 BMP non-GSM7 + +#### PLMN → EF_PLMNsel / PLMNwAcT + +3-байтное BCD-кодирование + опциональный Access Technology. + +#### Nibble swap + +Обмен полубайтов hex-строки. + +#### Ссылки + +- 3GPP TS 31.102 +- 3GPP TS 23.038 +- ETSI TS 102 225 +- pySim: enc_imsi() + --- -## Вкладка Secured Packet +## Вкладка SCP80 -Сборка защищённых пакетов по ETSI TS 102 225. +Вкладка **SCP80** группирует SCP80-виды, переключаемые тремя пиллами: **Secured Packet**, **Cards** и **RAM**. Сборка защищённых пакетов по ETSI TS 102 225. -### Структура пакета +### Secured Packet + +Сборка защищённых пакетов SCP80 по ETSI TS 102 225. + +#### Структура пакета | Поле | Размер | Описание | |---|---|---| @@ -314,7 +313,7 @@ CLA = `80` (GlobalPlatform v2.3.1). Удалённое управление со | RC/CC/DS | 8 | Контрольная сумма / MAC | | Secured Data | переменная | APDU (с шифрованием при необходимости) | -### SPI1 (Уровень безопасности) +#### SPI1 (Уровень безопасности) Битовое поле SPI1 (TS 102 225 §5.1.1): `b8–b6` — паддинг, `b5–b4` — счётчик, `b3` — шифрование, `b2–b1` — RC/CC/DS. @@ -334,7 +333,7 @@ CLA = `80` (GlobalPlatform v2.3.1). Удалённое управление со > **AES требует `b5 b4 = 10` (higher) или `11` (+1)** согласно TS 102 225 §5.1.2 и §5.1.3.1. > Значения `00/01/02/06` (без счётчика) допустимы только для 3DES. -### SPI2 (PoR) +#### SPI2 (PoR) | Значение | Режим | |---|---| @@ -347,7 +346,7 @@ CLA = `80` (GlobalPlatform v2.3.1). Удалённое управление со | 02 | PoR on error, no security | | 06 | PoR on error, RC | -### Крипто +#### Крипто - **3DES-CBC** шифрование, ключи 8/16/24 байт — устарело с Rel-18, но поддерживается для обратной совместимости - **AES-CBC** шифрование (нулевой ICV, дополнение нулями до 16), ключи 16/24/32 байта (TS 102 225 §5.1.2, KIc `x2`) @@ -355,26 +354,7 @@ CLA = `80` (GlobalPlatform v2.3.1). Удалённое управление со - **AES-CMAC** (NIST SP 800-38B, усечённый до 8 октетов) для AES (TS 102 225 §5.1.3.1, KID `x2`) - Padding byte: `00` (по умолчанию) или `FF` -### Ссылки - -- ETSI TS 102 225 V18.1.0 -- ETSI TS 102 226 -- ISO 9797-1 -- NIST SP 800-38B (CMAC) - -### Подвкладка Cards - -Пилл **Cards** во вкладке SCP80 управляет сохранёнными конфигурациями карт (пресеты). Каждый пресет хранит криптографические ключи, настройки SPI, TAR и счётчик повторов для SCP80-операций. - -**Добавить карту:** заполните имя, SPI1/SPI2, ключи KIc/KID и их индексы, TAR, нажмите **Add**. Карта появится в списке и станет доступна в выпаданом списке **Card preset** на RAM-вкладке. - -**Редактировать карту:** выберите карту в списке, измените поля, нажмите **Save**. - -**Удалить карту:** выберите карту, нажмите **Delete**. Удаляет пресет из `localStorage`. - -**Счётчик:** 10-значный hex-счётчик (CNTR) автоматически увеличивается после каждой успешной отправки SCP80 (ручные отправки Secured Packet и RAM-операции). Обновлённый счётчик автоматически сохраняется обратно в пресет. - -### PoR (Proof of Reception) +#### PoR (Proof of Reception) PoR подтверждает, что карта получила и выполнила защищённый пакет. Два режима: @@ -385,43 +365,127 @@ PoR подтверждает, что карта получила и выполн Delivery PoR (SPI2 `01`) проще — карта возвращает PoR напрямую в ответе ENVELOPE. Submit PoR (SPI2 `21`) используется, когда карта не может ответить inline (ограничено пространство ответа ENVELOPE). +#### Ссылки + +- ETSI TS 102 225 V18.1.0 +- ETSI TS 102 226 +- ISO 9797-1 +- NIST SP 800-38B (CMAC) + +### Cards + +Пилл **Cards** управляет сохранёнными конфигурациями карт (пресеты). Каждый пресет хранит криптографические ключи, настройки TAR и счётчик повторов для SCP80-операций. + +| Поле | Описание | +|---|---| +| SPI1 / SPI2 | Уровень безопасности и настройки PoR | +| Ключ KIc / KID | Hex ключи шифрования и MAC | +| Индекс KIc / KID | Номер версии ключа | +| TAR | Toolkit Application Reference (3 байта) | +| Счётчик (CNTR) | 10-значный hex счётчик повторов, автоматически увеличивается после каждой успешной отправки SCP80 | + +**Добавить карту:** заполните имя, SPI1/SPI2, ключи KIc/KID и их индексы, TAR, нажмите **Add**. Карта появится в списке и станет доступна в выпаданом списке **Card preset** на RAM-вкладке. + +**Редактировать карту:** выберите карту в списке, измените поля, нажмите **Save**. + +**Удалить карту:** выберите карту, нажмите **Delete**. Удаляет пресет из `localStorage`. + +**Счётчик:** 10-значный hex-счётчик (CNTR) автоматически увеличивается после каждой успешной отправки SCP80 (ручные отправки Secured Packet и RAM-операции). Обновлённый счётчик автоматически сохраняется обратно в пресет. + +### RAM + +Все операции RAM отправляются как защищённые пакеты SCP80 (ETSI TS 102 225) через SMS-PP-DOWNLOAD ENVELOPE. Карта должна поддерживать SCP03 (AES или 3DES) для безопасной транспортировки. + +Выберите сохранённую конфигурацию карты из выпадающего списка **Card preset**. Если пресет не выбран, RAM-вкладка предупреждает и отказывается выполнять. + +В RAM-подвкладке доступны две операции через выпадающий список **Operation**: + +| Операция | Описание | +|---|---| +| **Explore Card (all GP data)** | Запрос GET STATUS для ISD, приложений, ELF и модулей ELF, а также GET DATA FF21 для информации о памяти. Результаты отображаются в обзоре с кнопками **Delete** для каждого элемента. | +| **Install Package (.cap file)** | Отправка `.cap` файла на карту через сервер: INSTALL\[for load\] → LOAD ×N → INSTALL\[for install (+make selectable)\]. | + +#### Обзор карты (Explorer View) + +После выполнения "Explore Card" отображается: + +- **ISD** — AID, жизненный цикл, привилегии (без удаления; ISD нельзя удалить) +- **Приложения** — AID, жизненный цикл, привилегии, связанный ELF/SD. Каждое имеет кнопку **Delete** (GP `DELETE` по AID). +- **Executable Load Files** — AID, жизненный цикл, версии, AID модулей. Каждый имеет **Delete** (только ELF) и **Delete All** (каскадное: ELF + модули + установленные приложения, P2=0x80). + +Удаление подтверждается через диалог браузера перед отправкой команды GP `DELETE` через SCP80. Обзор автоматически обновляется после успешного удаления. + --- -## Конвертация (боковые панели SIM/USIM) +## Вкладка Response parser -### IMSI → EF.IMSI +Декодирование ответа команды: выберите отправленную команду, введите SW (например, `9000`) и данные ответа в hex, затем нажмите **Decode**. -15-значный IMSI → 9 байт EF.IMSI. +- **Команда** — группа SIM/USIM (SELECT, STATUS, READ/UPDATE, операции с PIN, CAT-команды TERMINAL PROFILE/ENVELOPE/FETCH/TERMINAL RESPONSE, MANAGE CHANNEL, ...) или группа RAM/GP (INSTALL, LOAD, DELETE, GET/STORE DATA, аутентификация, команды SCP). +- **Декодирование SW** — статусные слова по картам generic, UICC (TS 102 221) и GlobalPlatform с автоопределением контекста. +- **Декодирование привилегий** — байты привилегий из ответов GET DATA / INSTALL в читаемые флаги. +- **Данные ответа** — hex с интерпретацией по команде (например, шаблоны FCP из SELECT). -### MSISDN → BCD +--- -Удаление `+`, добавление `f`, обмен полубайтов. +## Card Reader (интеграция с pySim) -### ICCID → hex +Подключение к встроенному [`pysim-otaman-server`](pysim_otaman_server/) для работы с картой. -Обмен полубайтов строки ICCID. +> **Ограничение браузера:** если PWA раздаётся с публичного HTTPS-хоста, для доступа к локальному серверу (`http://127.0.0.1:8080`) нужны два условия: сервер должен отправлять `Access-Control-Allow-Private-Network: true` (pysim-otaman-server ≥ 1.6.1 делает это автоматически), и браузеру должно быть разрешено обращаться к локальной сети — в Chrome/Edge/Vivaldi: Настройки сайта → Доступ к локальной сети → разрешить сайт (или подтвердить запрос). Без разрешения браузера запрос к `127.0.0.1` блокируется ещё до отправки preflight. -### Provider Name → SPN +### Файловый менеджер -По 3GPP TS 31.102 §4.2.5. Три варианта кодирования: -1. GSM 7-bit packed -2. UCS2 non-BMP -3. UCS2 BMP non-GSM7 +Дерево файлов UICC. Отображаются имена, FID и AID (для ADF). Клик для чтения содержимого. -### PLMN → EF_PLMNsel / PLMNwAcT +- **Read** — чтение файла (автоопределение transparent/record) +- **Edit** — режим редактирования, измените hex-данные и нажмите **Save** для записи +- **Raw / Decoded** — переключение между hex-дампом и декодированным JSON -3-байтное BCD-кодирование + опциональный Access Technology. +### Пользовательские файлы -### Nibble swap +Файлы, отсутствующие в модели pysim, можно добавить вручную: -Обмен полубайтов hex-строки. +1. Перейдите на вкладку **Custom files** +2. Введите путь (например, `3F00/6F46`) и псевдоним (например, `EF.SPN`) +3. Нажмите **Add** — файл появится в дереве курсивом (непроверенный) +4. Кликните для проверки существования — при успехе работает как обычный файл -### Ссылки +Пользовательские файлы сохраняются в `localStorage`. Экспорт/импорт в JSON для обмена. -- 3GPP TS 31.102 -- 3GPP TS 23.038 -- ETSI TS 102 225 -- pySim: enc_imsi() +### Proactive UICC + +Подраздел **Proactive UICC** во вкладке Card Reader обеспечивает взаимодействие с CAT-сессией в реальном времени: + +**Subscribed Events** — список событий SET UP EVENT LIST с кнопками **Send**. Клик открывает форму для конкретного типа события: + +- **События без данных** (User Activity, Idle Screen и др.) — однократное уведомление +- **Location Status** — выпадающий список: Normal / Limited / No service +- **Access Technology Change** — 13 типов RAT +- **Network Rejection** — полная адаптивная форма: тип регистрации (LU / GPRS / EPS / 5GS), поля локации (MCC, MNC, LAC, RAC, TAC), доступные технологии, 53-позиционный выпадающий список причин отказа (EMM, GMM, 5GMM, LU) + +**Proactive Command Log** — хронологический список проактивных команд. Каждая строка показывает время, код типа, имя и декодированный квалификатор. + +**PLI Data Dictionary** — редактируемые hex-значения для всех 22 квалификаторов PROVIDE LOCAL INFORMATION (TS 102 223 + TS 131 111). 10 квалификаторов имеют встроенные формы декодирования/кодирования: + +| Код | Декодированные поля | +|------|--------------| +| 00 | MCC, MNC, LAC/TAC | +| 01 | IMEI (15 цифр) | +| 03 | Дата, время, TZ | +| 04 | Язык (2-символьный код) | +| 05 | ME Status, Timing Advance | +| 06 | Access Technology (выпадающий список) | +| 08 | IMEISV (16 цифр) | +| 09 | Search Mode (Auto/Manual) | +| 0A | Battery charge (%) | +| 0E | Multiple Access Technologies (список через запятую) | + +Значения сохраняются на сервере до перезапуска. Apply → hex обновляется; Save → POST на сервер. + +### Подсказки команд + +Введите имя команды в **pySim command line**. Подсказки по использованию появляются через 300 мс. Автодополнение команд — над полем ввода. --- @@ -452,35 +516,6 @@ PWA проверяет версию сервера при подключении --- -## Card Reader (интеграция с pySim) - -Подключение к встроенному [`pysim-otaman-server`](pysim_otaman_server/) для работы с картой. - -> **Ограничение браузера:** если PWA раздаётся с публичного HTTPS-хоста, для доступа к локальному серверу (`http://127.0.0.1:8080`) нужны два условия: сервер должен отправлять `Access-Control-Allow-Private-Network: true` (pysim-otaman-server ≥ 1.6.1 делает это автоматически), и браузеру должно быть разрешено обращаться к локальной сети — в Chrome/Edge/Vivaldi: Настройки сайта → Доступ к локальной сети → разрешить сайт (или подтвердить запрос). Без разрешения браузера запрос к `127.0.0.1` блокируется ещё до отправки preflight. - -### Файловый менеджер - -Дерево файлов UICC. Отображаются имена, FID и AID (для ADF). Клик для чтения содержимого. - -- **Read** — чтение файла (автоопределение transparent/record) -- **Edit** — режим редактирования, измените hex-данные и нажмите **Save** для записи -- **Raw / Decoded** — переключение между hex-дампом и декодированным JSON - -### Пользовательские файлы - -Файлы, отсутствующие в модели pysim, можно добавить вручную: - -1. Перейдите на вкладку **Custom files** -2. Введите путь (например, `3F00/6F46`) и псевдоним (например, `EF.SPN`) -3. Нажмите **Add** — файл появится в дереве курсивом (непроверенный) -4. Кликните для проверки существования — при успехе работает как обычный файл - -Пользовательские файлы сохраняются в `localStorage`. Экспорт/импорт в JSON для обмена. - -### Подсказки команд - -Введите имя команды в **pySim command line**. Подсказки по использованию появляются через 300 мс. Автодополнение команд — над полем ввода. - ## Сервер (pysim-otaman-server) Встроенный Python-сервер оборачивает [pySim](https://osmocom.org/projects/pysim/wiki) и раздаёт как PWA (из `frontend/`), так и JSON API по `/api/*`. @@ -531,4 +566,4 @@ pysim-otaman-server --http-port 8080 ### Справочник API -Полный справочник endpoints: [docs/api.md](docs/api.md). \ No newline at end of file +Полный справочник endpoints: [docs/api.md](docs/api.md). diff --git a/frontend/help-ru.html b/frontend/help-ru.html index ed4a157..61c0960 100644 --- a/frontend/help-ru.html +++ b/frontend/help-ru.html @@ -201,9 +201,12 @@
-

3. Вкладка SCP80 — Secured Packet

-

Верхнеуровневая вкладка SCP80 объединяет разделы, связанные с SCP80. Переключение — двумя переключателями: Secured Packet (этот раздел) и Cards (раздел 5). Собирает защищённые пакеты SCP80 по ETSI TS 102 225.

-

Структура пакета

+

3. Вкладка SCP80

+

Верхнеуровневая вкладка SCP80 объединяет разделы, связанные с SCP80. Переключение — тремя переключателями: Secured Packet, Cards и RAM. Собирает защищённые пакеты SCP80 по ETSI TS 102 225.

+ +

3.1 Secured Packet

+

Собирает защищённые пакеты SCP80 по ETSI TS 102 225.

+

Структура пакета

@@ -221,7 +224,7 @@
ПолеРазмерОписание
Secured Dataпер.APDU (с шифрованием при необходимости)
-

Крипто

+

Крипто

Кнопка «Verify vs pySim» сверяет собранный пакет с эталонной реализацией OtaDialectSms.encode_cmd. Кнопка «Send to Card» доставляет пакет через ENVELOPE SMS-PP-DOWNLOAD (при подключении к серверу).

+

3.2 Cards

+

Хранит предустановки карт локально в браузере (localStorage), чтобы представление Secured Packet могло автоматически подставлять ключи и параметры.

+ + + + + + + + + + + +
ПолеОписание
NameПонятная метка
ICCIDОпциональный идентификатор карты
KIc / KIDИндикаторы ключа и алгоритма (например, 15 = индекс 1, 3DES-CBC2; x2 = AES)
SPI1 / SPI2Security Parameter Indicators
TARToolkit Application Reference
CounterСчётчик повторов (5 байт)
KIc key / KID key16/24/32 hex-символа (ключи 8/16/24 байта 3DES) или 32/48/64 hex-символа (ключи 16/24/32 байта AES)
+

Export as JSON / Import JSON from clipboard для обмена предустановками. Выбранная предустановка автоматически заполняет форму Secured Packet.

+ +

3.3 RAM

+

Выполняет операции удалённого управления приложениями (Remote Application Management) как защищённые пакеты SCP80 через SMS-PP-DOWNLOAD ENVELOPE. Карта должна поддерживать SCP03 (AES или 3DES). Предустановка карты из подвкладки Cards обеспечивает SPI, ключи, TAR и счётчик.

+ +

Операции

+ + + + + + +
ОперацияОписание
Explore Card (all GP data)Запрос GET STATUS для ISD, приложений, ELF и модулей ELF, а также GET DATA FF21 для информации о памяти. Результаты отображаются в обзоре с кнопками Delete для каждого элемента.
Install Package (.cap file)Отправка .cap файла на карту через сервер: INSTALL[for load] → LOAD ×N → INSTALL[for install (+make selectable)].
+ +

Обзор карты (Explorer View)

+

После выполнения «Explore Card» отображается:

+ +

Удаление подтверждается через диалог браузера перед отправкой команды GP DELETE через SCP80. Обзор автоматически обновляется после успешного удаления.

+

4. Вкладка Response parser

-

Декодирование ответа команды: выберите отправленную команду, введите SW (например, 9000) и данные ответа в hex, затем нажмите Decode.

-
    -
  • Команда — группа SIM/USIM (SELECT, STATUS, READ/UPDATE, операции с PIN, CAT-команды TERMINAL PROFILE/ENVELOPE/FETCH/TERMINAL RESPONSE, MANAGE CHANNEL, …) или группа RAM/GP (INSTALL, LOAD, DELETE, GET/STORE DATA, аутентификация, команды SCP).
  • -
  • Декодирование SW — статусные слова по картам generic, UICC (TS 102 221) и GlobalPlatform с автоопределением контекста.
  • -
  • Декодирование привилегий — байты привилегий из ответов GET DATA / INSTALL в читаемые флаги.
  • -
  • Данные ответа — hex с интерпретацией по команде (например, шаблоны FCP из SELECT).
  • -
- - -
-

5. Вкладка SCP80 — Cards

Второй переключатель вкладки SCP80. Хранит предустановки карт локально в браузере (localStorage), чтобы представление Secured Packet могло автоматически подставлять ключи и параметры.

@@ -263,29 +292,29 @@
-

6. Вкладка Card reader (pySim)

+

5. Вкладка Card reader (pySim)

Подключение к локальному pysim-otaman-server для работы с картой. Подвкладки: File manager, Custom files, pySim command line, Raw APDU и Proactive UICC.

-

6.1 File manager

+

5.1 File manager

  • Read — чтение файла (автоопределение transparent/record)
  • Edit — изменить hex-данные, Save для записи
  • Raw / Decoded — переключение между hex-дампом и декодированным JSON
-

6.2 Custom files

+

5.2 Custom files

Добавление файлов, не покрытых моделью pySim. Сохраняется в localStorage; экспорт/импорт JSON.

-

6.3 pySim command line

+

5.3 pySim command line

Выполнение любых команд pySim-shell с подсказками (300 мс) и автодополнением.

-

6.4 Raw APDU

+

5.4 Raw APDU

Отправка произвольного APDU и просмотр ответа.

-

6.5 Proactive UICC

+

5.5 Proactive UICC

Работа с сессией Card Application Toolkit: подписанные события, журнал проактивных команд, словарь данных PROVIDE LOCAL INFORMATION и опрос STATUS.

-

6.5.1 Подписанные события (SET UP EVENT LIST)

+

5.5.1 Подписанные события (SET UP EVENT LIST)

События, которые отслеживает карта. У каждого события есть кнопка Send, открывающая форму, специфичную для типа события:

  • События без данных (User Activity, Idle Screen, Data Available, …) — уведомление в один клик
  • @@ -295,10 +324,10 @@

Отправка события использует ENVELOPE(Event Download) по TS 102 223 / TS 131 111.

-

6.5.2 Журнал проактивных команд

+

5.5.2 Журнал проактивных команд

Хронологический список извлечённых проактивных команд. Каждая строка показывает время, код типа, имя и декодированный квалификатор (для команд, у которых он есть). Для команд с данными ответа показывается строка Response: с байтами TERMINAL RESPONSE (без служебных TLV); ответы PROVIDE LOCAL INFORMATION декодируются через словарь данных PLI.

-

6.5.3 Словарь данных PROVIDE LOCAL INFORMATION

+

5.5.3 Словарь данных PROVIDE LOCAL INFORMATION

Редактируемые hex-значения для всех 22 квалификаторов PLI (TS 102 223 §8.6 + TS 131 111). У десяти квалификаторов есть встроенные формы декодирования/кодирования:

  • 00 Location Info (MCC, MNC, LAC/TAC, Cell ID)
  • @@ -308,10 +337,10 @@

Значения хранятся на сервере до перезапуска. Когда карта выдаёт PLI, сервер вставляет значения словаря в TERMINAL RESPONSE.

-

6.5.4 Опрос STATUS

+

5.5.4 Опрос STATUS

Кнопка Send STATUS отправляет STATUS (F2) вручную. Переключатель Polling включает фоновый опрос: после настраиваемого интервала бездействия (аргумент сервера --poll-interval, 1–255 с, по умолчанию 30 с) сервер отправляет STATUS и обрабатывает любую ожидающую проактивную команду. При извлечении карты опрос останавливается, а состояние карты сбрасывается.

-

6.6 Сценарии использования

+

5.6 Сценарии использования

Сценарий A — Работа с файлами, не входящими в модель pySim (Custom files)

    @@ -349,10 +378,10 @@
    -

    7. Установка сервера

    +

    6. Установка сервера

    Для работы с картой (вкладка Card reader, Proactive UICC, доставка OTA) нужен локальный pysim-otaman-server — встроенный в OTAMan HTTP-сервер, оборачивающий pySim, работающий с ридером через PC/SC или serial и раздающий сам PWA (откройте http://127.0.0.1:8080).

    -

    7.1 Требования

    +

    6.1 Требования

    • Python 3.8+ с pip
    • Git
    • @@ -360,20 +389,20 @@
    • Только Windows — используйте Python 3.10–3.13 (рекомендуется 3.13): pyscard (обёртка драйвера PC/SC) поставляет готовые wheels для этих версий. На Python 3.9 / 3.14 pip собирает pyscard из исходников, для чего требуются Microsoft C++ Build Tools («Desktop development with C++»). Мост SMPP (smpp.twisted3) на Windows намеренно не устанавливается, поэтому для Python 3.10–3.13 C++ Build Tools не нужны.
    -

    7.2 Быстрый старт — Linux / macOS

    +

    6.2 Быстрый старт — Linux / macOS

    git clone https://github.com/anttro/otaman.git
     cd otaman
     chmod +x setup.sh start.sh
     ./setup.sh          # создаёт .venv, устанавливает pysim + сервер (однократно)
     ./start.sh          # запускает сервер (PWA + API, автоопределение ридера)
    -

    7.3 Быстрый старт — Windows

    +

    6.3 Быстрый старт — Windows

    git clone https://github.com/anttro/otaman.git
     cd otaman
     setup.bat           # создаёт .venv, устанавливает pysim + сервер (однократно)
     start.bat           # запускает сервер (PWA + API)
    -

    7.4 Вспомогательные скрипты

    +

    6.4 Вспомогательные скрипты

ПолеОписание
@@ -382,7 +411,7 @@ start.bat # запускает сервер (PWA + API)
СкриптНазначение
-

7.5 Автоопределение ридера (start.sh)

+

6.5 Автоопределение ридера (start.sh)

  • PC/SC (Linux) — если запущен демон pcscd, передаёт -p 0
  • Serial (Linux) — если существует /dev/ttyUSB0, передаёт -d /dev/ttyUSB0
  • @@ -390,7 +419,7 @@ start.bat # запускает сервер (PWA + API)

Если ридер не обнаружен, сервер запускается без аргументов и показывает «Reader: none». Карту можно инициализировать позже кнопкой Equip на вкладке Card reader.

-

7.6 Ручная установка

+

6.6 Ручная установка

# Создать и активировать venv
 python3 -m venv .venv
 source .venv/bin/activate   # Linux/macOS
@@ -409,7 +438,7 @@ pysim-otaman-server --http-port 8080
-

8. Совместимость версий

+

7. Совместимость версий

diff --git a/frontend/help.html b/frontend/help.html index 2dc3756..30ff5f9 100644 --- a/frontend/help.html +++ b/frontend/help.html @@ -201,9 +201,12 @@
-

3. SCP80 tab — Secured Packet

-

The SCP80 top-level tab groups the SCP80-related views. It is switched by two pills: Secured Packet (this section) and Cards (section 5). Assembles SCP80 secured packets per ETSI TS 102 225.

-

Packet structure

+

3. SCP80 tab

+

The SCP80 top-level tab groups the SCP80-related views. It is switched by three pills: Secured Packet, Cards, and RAM. Assembles SCP80 secured packets per ETSI TS 102 225.

+ +

3.1 Secured Packet

+

Builds SCP80 secured packets per ETSI TS 102 225.

+

Packet structure

PWA (OTAMan)СерверСтатус
@@ -221,7 +224,7 @@
FieldSizeDescription
Secured Datavar.Padded APDU (encrypted if required)
-

Crypto

+

Crypto

  • 3DES-CBC encryption (zero ICV), 8/16/24-byte keys — deprecated since Rel-18, still supported for backwards compatibility
  • AES-CBC encryption (zero ICV, zero-padded to 16), 16/24/32-byte keys (TS 102 225 §5.1.2, KIc x2)
  • @@ -232,21 +235,8 @@

A “Verify vs pySim” button cross-checks the assembled packet against pySim’s reference OtaDialectSms.encode_cmd. A “Send to Card” button delivers it via SMS-PP-DOWNLOAD ENVELOPE (when connected to the server).

- -
-

4. Response parser tab

-

Decodes a raw command response: pick the command that was sent, enter the SW (e.g. 9000) and the response data hex, then press Decode.

-
    -
  • Command — SIM/USIM group (SELECT, STATUS, READ/UPDATE, PIN ops, CAT commands like TERMINAL PROFILE/ENVELOPE/FETCH/TERMINAL RESPONSE, MANAGE CHANNEL, …) or RAM/GP group (INSTALL, LOAD, DELETE, GET/STORE DATA, auth, SCP commands).
  • -
  • SW decode — status words resolved against generic, UICC (TS 102 221), and GlobalPlatform maps, with context auto-detected.
  • -
  • Privilege decode — GET DATA / INSTALL response payloads decode the privilege bytes into human-readable flags.
  • -
  • Response data — raw hex rendered and interpreted per command (e.g. SELECT FCP templates).
  • -
- - -
-

5. SCP80 tab — Cards

-

The second pill of the SCP80 tab. Stores card presets locally in the browser (localStorage) so the Secured Packet view can auto-fill keys and parameters.

+

3.2 Cards

+

Stores card presets locally in the browser (localStorage) so the Secured Packet view can auto-fill keys and parameters.

@@ -261,31 +251,63 @@
FieldDescription

Export as JSON / Import JSON from clipboard share presets. The selected card preset auto-fills the Secured Packet form.

+

3.3 RAM

+

Delivers Remote Application Management operations as SCP80 secured packets via SMS-PP-DOWNLOAD ENVELOPE. The card must support SCP03 (AES or 3DES). A saved card preset from the Cards sub-tab provides the SPI, keys, TAR, and counter.

+ +

Operations

+ + + + + + +
OperationDescription
Explore Card (all GP data)Queries GET STATUS for ISD, Applications, ELFs, and ELF Modules, plus GET DATA FF21 for memory info. Results appear in an explorer view with per-item Delete buttons.
Install Package (.cap file)Sends a .cap file to the card via the server: INSTALL[for load] → LOAD ×N → INSTALL[for install (+make selectable)].
+ +

Explorer View

+

After “Explore Card” runs, the explorer displays:

+
    +
  • ISD — AID, lifecycle, privileges (no delete; the ISD cannot be removed)
  • +
  • Applications — AID, lifecycle, privileges, associated ELF/SD. Each has a Delete button (GP DELETE by AID).
  • +
  • Executable Load Files — AID, lifecycle, version, module AIDs. Each has Delete (ELF only) and Delete All (cascade: ELF + modules + installed Applications, P2=0x80) buttons.
  • +
+

Delete confirms via a browser prompt before sending the GP DELETE command via SCP80. The explorer auto-refreshes after a successful deletion.

+
-

6. Card reader (pySim) tab

+

4. Response parser tab

+

Decodes a raw command response: pick the command that was sent, enter the SW (e.g. 9000) and the response data hex, then press Decode.

+
    +
  • Command — SIM/USIM group (SELECT, STATUS, READ/UPDATE, PIN ops, CAT commands like TERMINAL PROFILE/ENVELOPE/FETCH/TERMINAL RESPONSE, MANAGE CHANNEL, …) or RAM/GP group (INSTALL, LOAD, DELETE, GET/STORE DATA, auth, SCP commands).
  • +
  • SW decode — status words resolved against generic, UICC (TS 102 221), and GlobalPlatform maps, with context auto-detected.
  • +
  • Privilege decode — GET DATA / INSTALL response payloads decode the privilege bytes into human-readable flags.
  • +
  • Response data — raw hex rendered and interpreted per command (e.g. SELECT FCP templates).
  • +
+ + +
+

5. Card reader (pySim) tab

Connects to a local pysim-otaman-server for live card operations. Sub-tabs: File manager, Custom files, pySim command line, Raw APDU, and Proactive UICC.

-

6.1 File manager

+

5.1 File manager

  • Read — reads the selected file (auto-detects transparent vs record files)
  • Edit — modify hex data, Save to write back
  • Raw / Decoded — toggle between hex dump and pySim-decoded JSON
-

6.2 Custom files

+

5.2 Custom files

Add files that pySim’s model does not cover. Persists in localStorage; JSON export/import.

-

6.3 pySim command line

+

5.3 pySim command line

Execute any pySim-shell command with usage hints (300 ms) and autocomplete.

-

6.4 Raw APDU

+

5.4 Raw APDU

Send an arbitrary APDU and view the raw response.

-

6.5 Proactive UICC

+

5.5 Proactive UICC

Interacts with the Card Application Toolkit session: subscribed events, the proactive command log, the PROVIDE LOCAL INFORMATION data dictionary, and STATUS polling.

-

6.5.1 Subscribed events (SET UP EVENT LIST)

+

5.5.1 Subscribed events (SET UP EVENT LIST)

The events the card monitors. Each event has a Send button that opens a form specific to the event type:

  • No-data events (User Activity, Idle Screen, Data Available, …) — one-click notification
  • @@ -295,10 +317,10 @@

Sending an event uses ENVELOPE(Event Download) per TS 102 223 / TS 131 111.

-

6.5.2 Proactive command log

+

5.5.2 Proactive command log

Chronological list of fetched proactive commands. Each row shows the elapsed time, type code, name, and a decoded qualifier (for commands that have one). Commands with response data show a Response: line with the TERMINAL RESPONSE bytes (boilerplate TLVs stripped); PROVIDE LOCAL INFORMATION responses are decoded using the PLI data dictionary decoders.

-

6.5.3 PROVIDE LOCAL INFORMATION data dictionary

+

5.5.3 PROVIDE LOCAL INFORMATION data dictionary

Editable hex values for all 22 PLI qualifiers (TS 102 223 §8.6 + TS 131 111). Ten qualifiers have inline decode/encode forms:

  • 00 Location Info (MCC, MNC, LAC/TAC, Cell ID)
  • @@ -308,10 +330,10 @@

Values persist server-side until restart. When the card issues PLI, the server injects the dictionary values into the TERMINAL RESPONSE.

-

6.5.4 STATUS polling

+

5.5.4 STATUS polling

A Send STATUS button issues a manual STATUS (F2). A Polling toggle enables background polling: after a configurable idle interval (server CLI --poll-interval, 1–255 s, default 30 s) the server sends STATUS and handles any pending proactive command. Polling stops and card state resets if the card is removed.

-

6.6 Usage scenarios

+

5.6 Usage scenarios

Scenario A — Working with files not in pySim’s model (Custom files)

    @@ -349,10 +371,10 @@
    -

    7. Server installation

    +

    6. Server installation

    Live card operations (Card reader tab, Proactive UICC, OTA delivery) require the local pysim-otaman-server — a small HTTP server bundled with OTAMan that wraps pySim, talks to the reader over PC/SC or serial, and also serves the PWA itself (open http://127.0.0.1:8080).

    -

    7.1 Prerequisites

    +

    6.1 Prerequisites

    • Python 3.8+ with pip
    • Git
    • @@ -360,20 +382,20 @@
    • Windows only — use Python 3.10–3.13 (3.13 recommended): pyscard (the PC/SC driver wrapper) ships precompiled wheels for these versions. On Python 3.9 / 3.14 pip builds pyscard from source, which requires Microsoft C++ Build Tools (“Desktop development with C++”). The SMPP bridge (smpp.twisted3) is intentionally not installed on Windows, so no C++ Build Tools are needed for Python 3.10–3.13.
    -

    7.2 Quick start — Linux / macOS

    +

    6.2 Quick start — Linux / macOS

    git clone https://github.com/anttro/otaman.git
     cd otaman
     chmod +x setup.sh start.sh
     ./setup.sh          # creates .venv, installs pysim + server (run once)
     ./start.sh          # starts the server (serves PWA + API, auto-detects reader)
    -

    7.3 Quick start — Windows

    +

    6.3 Quick start — Windows

    git clone https://github.com/anttro/otaman.git
     cd otaman
     setup.bat           # creates .venv, installs pysim + server (run once)
     start.bat           # starts the server (serves PWA + API)
    -

    7.4 Helper scripts

    +

    6.4 Helper scripts

    @@ -382,7 +404,7 @@ start.bat # starts the server (serves PWA + API)
    ScriptPurpose
    -

    7.5 Reader auto-detection (start.sh)

    +

    6.5 Reader auto-detection (start.sh)

    • PC/SC (Linux) — if the pcscd daemon is running, passes -p 0
    • Serial (Linux) — if /dev/ttyUSB0 exists, passes -d /dev/ttyUSB0
    • @@ -390,7 +412,7 @@ start.bat # starts the server (serves PWA + API)

    If no reader is detected, the server starts without reader arguments and shows “Reader: none”. The card can be initialized later via the Equip button in the Card reader tab.

    -

    7.6 Manual installation

    +

    6.6 Manual installation

    # Create and activate a venv
     python3 -m venv .venv
     source .venv/bin/activate   # Linux/macOS
    @@ -409,7 +431,7 @@ pysim-otaman-server --http-port 8080
    -

    8. Version compatibility

    +

    7. Version compatibility

    diff --git a/frontend/index.html b/frontend/index.html index 666f8b4..58c73f2 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -18,7 +18,7 @@
    -

    OTAMan SIM OTA with a Human Face v1.9.19

    +

    OTAMan SIM OTA with a Human Face v1.9.21

    github @@ -401,7 +401,7 @@
    - +
    @@ -409,11 +409,11 @@
    - +
    - +
    @@ -902,9 +902,114 @@ - +
    +
    + + +
    +
    +
    Byte 1
    +
    Byte 2
    + + + + + + + + + + + + + + + +
    + +
    +
    +
    +
    + +
    + +
    + - +
    PWA (OTAMan)ServerStatus