diff --git a/help-ru.html b/help-ru.html new file mode 100644 index 0000000..36e8d2d --- /dev/null +++ b/help-ru.html @@ -0,0 +1,432 @@ + + + + + +OTAMan — Справка + + + + +
+ + + +
+

OTAMan Документация

+
+

1. Обзор

+

OTAMan — Progressive Web App (PWA) для построения APDU-команд, сборки защищённых пакетов SCP80, просмотра меню SIM Toolkit (STK) и симуляции реальной сетевой среды для тестирования SIM/USIM/UICC-карт через PC/SC-ридер.

+

Приложение — один статический файл index.html. Все вычисления выполняются в браузере; доступ к карте — через локальный HTTP-сервер (pysim-otaman-server), оборачивающий библиотеку pySim.

+
Браузер (OTAMan PWA) → HTTP :8080 → pysim-otaman-server → pySim → PC/SC → ридер → UICC/SIM
+

Стандарты, на которые опирается приложение:

+
    +
  • ETSI TS 102 221 — интерфейс UICC-терминал (CLA 00, файлы USIM)
  • +
  • ETSI TS 102 222 — административные команды
  • +
  • ETSI TS 102 223 — Card Application Toolkit (CAT, проактивные команды)
  • +
  • ETSI TS 102 225 — структура защищённых пакетов для (U)SIM toolkit
  • +
  • ETSI TS 102 226 — структура удалённых APDU для UICC-приложений
  • +
  • ETSI TS 151 011 — интерфейс SIM-ME (CLA A0)
  • +
  • 3GPP TS 131 111 — USIM Application Toolkit (USAT)
  • +
  • 3GPP TS 31.102 — характеристики приложения USIM
  • +
  • 3GPP TS 23.038 — алфавит GSM 7-bit и DCS
  • +
  • 3GPP TS 24.008 / 24.301 / 24.501 — коды причин NAS
  • +
  • GlobalPlatform Card Specification v2.3.1
  • +
  • ISO/IEC 7816-4 — команды обмена
  • +
  • ISO/IEC 9797-1 — алгоритмы MAC
  • +
+ + +
+

2. Вкладка C-APDU

+

Построение командных APDU (C-APDU). Четыре подвкладки охватывают разные поколения карт и наборы команд.

+ +

2.1 SIM RFM

+

CLA = A0 (GSM 11.11 / TS 151 011, ISO 7816-4). Удалённое управление файлами классических SIM-карт.

+ + + + + + + + + + + + + + + + +
КомандаINSОписание
SELECTA4Выбор EF/DF по FID, пути, DF name или цепочке
UPDATE RECORDDCОбновление записи
UPDATE BINARYD6Обновление бинарных данных
READ RECORDB2Чтение записи
READ BINARYB0Чтение бинарных данных
ERASE BINARY0EСтирание бинарных данных
ACTIVATE FILE44Активация файла
DEACTIVATE FILE04Деактивация файла
VERIFY PIN20Проверка PIN1 или PIN2
CHANGE PIN24Смена PIN1 или PIN2
+

Методы SELECT

+ + + + + + + + + + +
МетодP1P2Ввод
По FID0000FID (4 hex)
По полному пути от MF0800Полный путь от MF
По DF name / AID0400AID
Цепочка ADF RFM0000FID через запятую
+

Опции

+
    +
  • 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). См. §2.5.

+ +

2.2 USIM RFM

+

CLA = 00 (ETSI TS 102 221). Те же команды, что и SIM, но SELECT использует P1=09, P2=0C (выбор по FID из текущего каталога).

+ +

2.3 Expanded BER-TLV

+

Построение формата Expanded Remote Application data по ETSI TS 102 226 §5.2.1.

+

Формат

+
    +
  • Definite (AA): AA + длина + Command TLV
  • +
  • Indefinite (AE): AE + 80 + Command TLV + 00 00
  • +
+

Command TLV

+ + + + + + + + + + +
ТипТегОписание
C-APDU22APDU
Immediate Action81Проактивная команда или action indicator
Error Action82Проактивная команда при ошибке
Script Chaining83Данные для многопакетных скриптов
+

Сборщик Immediate Action предлагает action indicator (81/82), структурированный сборщик проактивных команд (REFRESH, DISPLAY TEXT, PLAY TONE с авто-генерацией COMPREHENSION-TLV), или ручной hex-ввод.

+ +

2.4 RAM/GP

+

CLA = 80 (GlobalPlatform Card Specification v2.3.1). Команды удалённого управления приложениями.

+ + + + + + + + + + + + + + + + + + + +
КомандаINSP1Описание
INSTALL [for load]E602Регистрация загружаемого файла
INSTALL [for install]E60CУстановка приложения или SD
INSTALL [make selectable]E610Сделать приложение выбираемым
INSTALL [registry update]E601Обновление реестра
INSTALL [extradition]E604Перемещение между SD
LOADE800Загрузка кода
DELETEE400/80Удаление приложения или SD
GET STATUSF280/40/20/10Статус карты
GET DATACAtagЧтение объектов данных
STORE DATAE200/40/80/C0Запись данных
SET STATUSF080/40/60Управление жизненным циклом
EXTERNAL AUTHENTICATE8200Аутентификация SCP
INTERNAL AUTHENTICATE8800Challenge-response
+

Привилегии (INSTALL [for install])

+

Тег C7 в поле данных INSTALL, три байта привилегий (таблицы 11-7/8/9 спецификации GP):

+ + + + + + + + + + + + + + +
БитБайт 1Байт 2Байт 3
b8Security DomainTrusted PathReceipt Generation
b7DAP VerificationAuthorized Management
b6Delegated ManagementToken Verification
b5Card LockGlobal Delete
b4Card TerminateGlobal Lock
b3Card ResetGlobal Registry
b2CVM ManagementFinal Application
b1Mandated DAP Verification
+

MSL (Minimum Security Level) — байт SPI1 по TS 102 225

+ + + + + + + + + + +
ЗначениеОписание
00Нет проверки
11RC/CC/DS
12RC/DS/CC
15RC/DS/CC + MAC
16RC/DS/CC + MAC + Cipher
19RC/DS/CC + MAC + Cipher + DS
+

Полные таблицы GET STATUS P1/P2, тегов GET DATA, DELETE P1, STORE DATA P1 и SET STATUS см. в GlobalPlatform v2.3.1 и ETSI TS 102 226 §8.2.1.3.2.

+ +

2.5 Конвертация (боковые панели SIM/USIM)

+
    +
  • IMSI → EF.IMSI — 15-значный IMSI в 9-байтный формат (TS 31.102 §4.2.3).
  • +
  • MSISDN → BCD — удалить +, дополнить нечётную длину символом f, поменять полубайты.
  • +
  • ICCID → hex — поменять полубайты строки ICCID.
  • +
  • Provider Name → SPN — GSM 7-bit packed, UCS2 non-BMP или UCS2 BMP (TS 31.102 §4.2.5, TS 23.038).
  • +
  • PLMN → EF_PLMNsel / PLMNwAcT — 3-байтный BCD + опциональный селектор технологии доступа.
  • +
  • Nibble swap — поменять пары полубайтов hex-строки чётной длины.
  • +
+ + +
+

3. Вкладка Secured Packet

+

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

+

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

+ + + + + + + + + + + + + + + + +
ПолеРазмерОписание
CPI1Command Packet Identifier (02)
CPL1Command Packet Length
CHI1Command Header Identifier (01)
CHL1Command Header Length
SPI2Security Parameter Indicator
KIc1Key Identifier для шифрования
KID1Key Identifier для MAC
TAR3Toolkit Application Reference
CNTR5Счётчик повторов
PCNTR1Padding counter
RC/CC/DS8Контрольная сумма / MAC
Secured Dataпер.APDU (с шифрованием при необходимости)
+

Крипто

+
    +
  • 3DES-CBC шифрование (нулевой ICV), ключи 8/16/24 байта
  • +
  • Retail MAC (ISO 9797-1, MAC algorithm 3) для контрольной суммы
  • +
  • Байт паддинга настраивается (00 по умолчанию или FF)
  • +
+

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

+ + +
+

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. Вкладка Cards

+

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

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

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

+ + +
+

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

+

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

+ +

6.1 File manager

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

6.2 Custom files

+

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

+ +

6.3 pySim command line

+

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

+ +

6.4 Raw APDU

+

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

+ +

6.5 Proactive UICC

+

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

+ +

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

+

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

+
    +
  • События без данных (User Activity, Idle Screen, Data Available, …) — уведомление в один клик
  • +
  • Location Status — выпадающий список: Normal / Limited / No service (тег 9B)
  • +
  • Access Technology Change — 13 типов RAT (тег BF)
  • +
  • Network Rejection — полная адаптивная форма: тип регистрации (LU / GPRS / EPS / 5GS), поля местоположения (MCC, MNC, LAC, RAC, TAC), технология доступа и единый выпадающий список из 53 кодов причин (EMM, GMM, 5GMM и LU)
  • +
+

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

+ +

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

+

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

+ +

6.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)
  • +
  • 01 IMEI · 03 Дата/время/TZ · 04 Язык · 05 Timing Advance
  • +
  • 06 Access Technology · 08 IMEISV · 09 Search Mode
  • +
  • 0A Battery · 0E Multiple Access Technologies
  • +
+

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

+ +

6.5.4 Опрос STATUS

+

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

+ +

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

+ +

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

+
    +
  1. Получите FID целевого файла (документация вендора или анализ ATR/файловой системы; такие файлы часто отсутствуют в открытых спецификациях).
  2. +
  3. Откройте вкладку Card reader → подвкладку Custom files.
  4. +
  5. Введите полный путь (например, 3F00/7F20/6F46) и псевдоним (например, EF.SPN).
  6. +
  7. Нажмите Add — файл появится в дереве курсивом (непроверенный).
  8. +
  9. Кликните по файлу для проверки существования; при успехе (9000) он работает как обычный файл.
  10. +
  11. Читайте, редактируйте и сохраняйте hex-данные; переключайте Raw/Decoded.
  12. +
  13. Экспортируйте список пользовательских файлов в JSON для переноса на другие машины.
  14. +
+ +

Сценарий B — Симуляция реальной сетевой среды для тестирования SIM

+

B.1 Ответы на PROVIDE LOCAL INFORMATION (PLI)

+
    +
  1. Откройте Proactive UICCPROVIDE LOCAL INFORMATION response data.
  2. +
  3. Используйте формы декодирования/кодирования для IMEI (01), Location Info (00), Access Technology (06) и т.д.
  4. +
  5. Нажмите Save — значения сохранятся на сервере.
  6. +
  7. Включите Polling (интервал 30 с), чтобы карта периодически выдавала PLI.
  8. +
  9. Сервер вставляет значения словаря в каждый TERMINAL RESPONSE.
  10. +
  11. Проверьте в журнале проактивных команд: запись PLI покажет декодированный ответ.
  12. +
+

B.2 Симуляция сетевых действий через ENVELOPE (event download)

+
    +
  1. Проверьте список подписанных событий (из SET UP EVENT LIST).
  2. +
  3. Нажмите Send на событии (например, Location Status) и заполните форму; будет отправлен ENVELOPE(Event Download).
  4. +
  5. Для Network Rejection выберите тип регистрации → поля местоположения → технологию доступа → причину отклонения.
  6. +
  7. Карта может ответить проактивной командой, которую обработчик цепочки зарегистрирует и обработает автоматически.
  8. +
+

B.3 Проверка симулированной среды

+
    +
  • Журнал проактивных команд показывает полный цикл (команда + байты TERMINAL RESPONSE).
  • +
  • Кнопка STATUS / автопросмотр поддерживают сессию CAT (цикл дренажа).
  • +
+ + +
+

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

+

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

+ +

7.1 Требования

+
    +
  • Python 3.8+ с pip
  • +
  • Git
  • +
  • Смарт-картридер (PC/SC или serial/FTDI). Предпочтителен PC/SC; на Linux требуются pcsc-lite + ccid
  • +
+ +

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

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

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

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

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

+ + + + + + +
СкриптНазначение
setup.sh / setup.batСоздаёт .venv/, устанавливает pySim и сервер. Запускается один раз после клонирования.
start.sh / start.batЗапускает сервер из venv (при отсутствии — из глобальной установки).
+ +

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

+
    +
  • PC/SC (Linux) — если запущен демон pcscd, передаёт -p 0
  • +
  • Serial (Linux) — если существует /dev/ttyUSB0, передаёт -d /dev/ttyUSB0
  • +
  • PC/SC (Windows) — всегда использует -p 0 (PC/SC встроен в Windows)
  • +
+

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

+ +

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

+
# Создать и активировать venv
+python3 -m venv .venv
+source .venv/bin/activate   # Linux/macOS
+# .venv\Scripts\activate    # Windows
+
+# Установить pysim
+pip install git+https://gitea.osmocom.org/sim-card/pysim.git
+
+# Установить pysim-otaman-server
+pip install .
+
+# Запустить сервер
+pysim-otaman-server --http-port 8080
+

Подключите PC/SC-ридер с SIM-картой и укажите в PWA адрес http://127.0.0.1:8080.

+ + +
+

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

+ + + + + + + +
PWA (OTAMan)СерверСтатус
1.x.x1.x.x✅ Совместимы
1.x.x0.x.x❌ Устарел — обновите сервер
1.x.x2.x.x+⚠️ Сервер новее — обновите PWA
+

PWA проверяет версию сервера при подключении через GET /api/version и предупреждает о несовместимости.

+ + +
+
+ + + + diff --git a/help.html b/help.html new file mode 100644 index 0000000..642508f --- /dev/null +++ b/help.html @@ -0,0 +1,432 @@ + + + + + +OTAMan — Help + + + + +
+ + + +
+

OTAMan Documentation

+
+

1. Overview

+

OTAMan is a Progressive Web App (PWA) for building APDU commands, assembling SCP80 secured packets, browsing the SIM Toolkit (STK) menu, and simulating a real network environment against a SIM/USIM/UICC card via a PC/SC reader.

+

The application is a single static index.html file. All computation runs in the browser; the card is accessed through a local HTTP server (pysim-otaman-server) that wraps the pySim library.

+
Browser (OTAMan PWA) → HTTP :8080 → pysim-otaman-server → pySim → PC/SC → card reader → UICC/SIM
+

Standards referenced across the application:

+
    +
  • ETSI TS 102 221 — UICC-Terminal interface (CLA 00, USIM files)
  • +
  • ETSI TS 102 222 — Administrative commands
  • +
  • ETSI TS 102 223 — Card Application Toolkit (CAT, proactive commands)
  • +
  • ETSI TS 102 225 — Secured packet structure for (U)SIM toolkit
  • +
  • ETSI TS 102 226 — Remote APDU structure for UICC based applications
  • +
  • ETSI TS 151 011 — SIM-ME interface (CLA A0)
  • +
  • 3GPP TS 131 111 — USIM Application Toolkit (USAT)
  • +
  • 3GPP TS 31.102 — USIM application characteristics
  • +
  • 3GPP TS 23.038 — GSM 7-bit alphabet and DCS
  • +
  • 3GPP TS 24.008 / 24.301 / 24.501 — NAS cause codes
  • +
  • GlobalPlatform Card Specification v2.3.1
  • +
  • ISO/IEC 7816-4 — commands for interchange
  • +
  • ISO/IEC 9797-1 — MAC algorithms
  • +
+ + +
+

2. C-APDU tab

+

Builds command APDUs (C-APDUs). Four sub-tabs cover different card generations and command sets.

+ +

2.1 SIM RFM

+

CLA = A0 (GSM 11.11 / TS 151 011, ISO 7816-4). Remote File Management for classic SIM cards.

+ + + + + + + + + + + + + + + + +
CommandINSDescription
SELECTA4Select EF/DF by FID, path, DF name or chain
UPDATE RECORDDCUpdate a record in a record-oriented EF
UPDATE BINARYD6Update binary content at an offset
READ RECORDB2Read a record
READ BINARYB0Read binary content
ERASE BINARY0EErase binary at an offset
ACTIVATE FILE44Activate a file
DEACTIVATE FILE04Deactivate a file
VERIFY PIN20Verify PIN1 or PIN2
CHANGE PIN24Change PIN1 or PIN2
+

SELECT methods

+ + + + + + + + + + +
MethodP1P2Input
By FID00002-byte FID (4 hex)
By full path from MF0800Full path hex from MF
By DF name / AID0400AID (application ID)
ADF RFM chain0000Comma-separated FIDs
+

Options

+
    +
  • Start with SELECT — prepend a SELECT before the operation; unchecked sends standalone.
  • +
  • Selection mode (P2) — record commands: Absolute (04), Next (06), Previous (02).
  • +
  • Record size — pad/truncate data to the specified byte count.
  • +
  • Allow P1/P2 editing — manual override of P1/P2 bytes.
  • +
+

A conversion panel is embedded in the right column (IMSI, MSISDN, ICCID, SPN, PLMN, nibble swap). See §2.5.

+ +

2.2 USIM RFM

+

CLA = 00 (ETSI TS 102 221). Same commands as SIM, but SELECT uses P1=09, P2=0C (select by FID from the current directory).

+ +

2.3 Expanded BER-TLV

+

Builds the Expanded Remote Application data format per ETSI TS 102 226 §5.2.1.

+

Format

+
    +
  • Definite (AA): AA + length + Command TLVs
  • +
  • Indefinite (AE): AE + 80 + Command TLVs + 00 00
  • +
+

Command TLVs

+ + + + + + + + + + +
TypeTagDescription
C-APDU22Raw APDU hex
Immediate Action81Proactive command or action indicator
Error Action82Proactive command on error
Script Chaining83Chaining data for multi-packet scripts
+

The Immediate Action builder offers an action indicator (81/82), a structured proactive command builder (REFRESH, DISPLAY TEXT, PLAY TONE with auto-generated COMPREHENSION-TLV objects), or a freeform hex input.

+ +

2.4 RAM/GP

+

CLA = 80 (GlobalPlatform Card Specification v2.3.1). Remote Application Management commands for card content management.

+ + + + + + + + + + + + + + + + + + + +
CommandINSP1Description
INSTALL [for load]E602Register a load file for loading
INSTALL [for install]E60CInstall an application or SD
INSTALL [make selectable]E610Make an application selectable
INSTALL [registry update]E601Update registry entries
INSTALL [extradition]E604Extradition between SDs
LOADE800Load executable code blocks
DELETEE400/80Delete application or SD
GET STATUSF280/40/20/10Get card status
GET DATACAtagRead card data objects
STORE DATAE200/40/80/C0Store data (key, certificate, …)
SET STATUSF080/40/60Lifecycle state management
EXTERNAL AUTHENTICATE8200SCP host authentication
INTERNAL AUTHENTICATE8800Card challenge-response
+

Privileges (INSTALL [for install])

+

Tag C7 in the INSTALL data field, built from 3 privilege bytes (GP spec Tables 11-7/8/9):

+ + + + + + + + + + + + + + +
BitByte 1Byte 2Byte 3
b8Security DomainTrusted PathReceipt Generation
b7DAP VerificationAuthorized Management
b6Delegated ManagementToken Verification
b5Card LockGlobal Delete
b4Card TerminateGlobal Lock
b3Card ResetGlobal Registry
b2CVM ManagementFinal Application
b1Mandated DAP Verification
+

MSL (Minimum Security Level) — SPI1 byte per TS 102 225

+ + + + + + + + + + +
ValueMeaning
00No check
11RC/CC/DS
12RC/DS/CC
15RC/DS/CC + MAC
16RC/DS/CC + MAC + Cipher
19RC/DS/CC + MAC + Cipher + DS
+

Refer to GlobalPlatform v2.3.1 and ETSI TS 102 226 §8.2.1.3.2 for the full GET STATUS P1/P2, GET DATA tag, DELETE P1, STORE DATA P1, and SET STATUS tables.

+ +

2.5 Conversion (SIM/USIM sidebars)

+
    +
  • IMSI → EF.IMSI — 15-digit IMSI to 9-byte format (TS 31.102 §4.2.3).
  • +
  • MSISDN → BCD — strip +, pad odd length with f, swap nibbles.
  • +
  • ICCID → hex — nibble-swap the ICCID string.
  • +
  • Provider Name → SPN — GSM 7-bit packed, UCS2 non-BMP, or UCS2 BMP (TS 31.102 §4.2.5, TS 23.038).
  • +
  • PLMN → EF_PLMNsel / PLMNwAcT — 3-byte BCD + optional access technology selector.
  • +
  • Nibble swap — swap nibble pairs of an even-length hex string.
  • +
+ + +
+

3. Secured Packet tab

+

Assembles SCP80 secured packets per ETSI TS 102 225.

+

Packet structure

+ + + + + + + + + + + + + + + + +
FieldSizeDescription
CPI1Command Packet Identifier (02)
CPL1Command Packet Length
CHI1Command Header Identifier (01)
CHL1Command Header Length
SPI2Security Parameter Indicator
KIc1Key Identifier for ciphering
KID1Key Identifier for MAC
TAR3Toolkit Application Reference
CNTR5Replay counter
PCNTR1Padding counter
RC/CC/DS8Cryptographic Checksum / MAC
Secured Datavar.Padded APDU (encrypted if required)
+

Crypto

+
    +
  • 3DES-CBC encryption (zero ICV), 8/16/24-byte keys
  • +
  • Retail MAC (ISO 9797-1 MAC algorithm 3) for the cryptographic checksum
  • +
  • Padding byte configurable (00 default, or FF)
  • +
+

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. Cards tab

+

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

+ + + + + + + + + + + +
FieldDescription
NameHuman-readable label
ICCIDOptional card identifier
KIc / KIDKey and algorithm indicators (e.g. 15 = index 1, 3DES-CBC2)
SPI1 / SPI2Security Parameter Indicators
TARToolkit Application Reference
CounterReplay counter (5 bytes)
KIc key / KID key32 hex chars each (16-byte 3DES keys)
+

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

+ + +
+

6. 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

+
    +
  • 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

+

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

+ +

6.3 pySim command line

+

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

+ +

6.4 Raw APDU

+

Send an arbitrary APDU and view the raw response.

+ +

6.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)

+

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
  • +
  • Location Status — dropdown: Normal / Limited / No service (tag 9B)
  • +
  • Access Technology Change — 13 RAT types (tag BF)
  • +
  • Network Rejection — full adaptive form: registration type (LU / GPRS / EPS / 5GS), location fields (MCC, MNC, LAC, RAC, TAC), access technology, and a 53-cause unified rejection cause dropdown covering EMM, GMM, 5GMM and LU causes
  • +
+

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

+ +

6.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

+

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)
  • +
  • 01 IMEI · 03 Date/Time/TZ · 04 Language · 05 Timing Advance
  • +
  • 06 Access Technology · 08 IMEISV · 09 Search Mode
  • +
  • 0A Battery · 0E Multiple Access Technologies
  • +
+

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

+

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

+ +

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

+
    +
  1. Obtain the FID of the target file (vendor documentation or ATR/file-system analysis; such files are often not in public specs).
  2. +
  3. Open the Card reader tab → Custom files sub-tab.
  4. +
  5. Enter the full path (e.g. 3F00/7F20/6F46) and an alias (e.g. EF.SPN).
  6. +
  7. Click Add — the file appears in the tree in italics (unverified).
  8. +
  9. Click the file to verify existence; on success (9000) it behaves like a normal file.
  10. +
  11. Read, edit and save hex data; toggle Raw/Decoded views.
  12. +
  13. Export the custom-file list as JSON to share with other machines.
  14. +
+ +

Scenario B — Simulating a real network environment for SIM testing

+

B.1 Answer PROVIDE LOCAL INFORMATION (PLI)

+
    +
  1. Open Proactive UICCPROVIDE LOCAL INFORMATION response data.
  2. +
  3. Use the decode/encode forms to set IMEI (01), Location Info (00), Access Technology (06), etc.
  4. +
  5. Click Save — values persist server-side.
  6. +
  7. Enable Polling (interval 30 s) so the card issues PLI periodically.
  8. +
  9. The server injects the dictionary values into each TERMINAL RESPONSE.
  10. +
  11. Verify in the proactive log: the PLI entry shows the decoded response.
  12. +
+

B.2 Simulate network actions via ENVELOPE (event download)

+
    +
  1. Check the subscribed events list (from SET UP EVENT LIST).
  2. +
  3. Click Send on an event (e.g. Location Status) and fill the form; an ENVELOPE(Event Download) is sent.
  4. +
  5. For Network Rejection, select registration type → location fields → access technology → rejection cause.
  6. +
  7. The card may respond with a proactive command, which the chain handler logs and answers automatically.
  8. +
+

B.3 Verify the simulated environment

+
    +
  • The proactive command log shows the full round-trip (command + TERMINAL RESPONSE bytes).
  • +
  • The STATUS button / auto-polling keep the CAT session alive (drain loop).
  • +
+ + +
+

7. Server installation

+

Live card operations (Card reader tab, Proactive UICC, OTA delivery) require the local pysim-otaman-server — a small HTTP server that wraps pySim and talks to the reader over PC/SC or serial.

+ +

7.1 Prerequisites

+
    +
  • Python 3.8+ with pip
  • +
  • Git
  • +
  • Smart card reader (PC/SC or serial/FTDI). PC/SC is preferable; on Linux it requires pcsc-lite + ccid
  • +
+ +

7.2 Quick start — Linux / macOS

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

7.3 Quick start — Windows

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

7.4 Helper scripts

+ + + + + + +
ScriptPurpose
setup.sh / setup.batCreates .venv/, installs pySim and the server. Run once after cloning.
start.sh / start.batStarts the server from the venv (falls back to a global install).
+ +

7.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
  • +
  • PC/SC (Windows) — always uses -p 0 (PC/SC is built into Windows)
  • +
+

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

+
# Create and activate a venv
+python3 -m venv .venv
+source .venv/bin/activate   # Linux/macOS
+# .venv\Scripts\activate    # Windows
+
+# Install pysim
+pip install git+https://gitea.osmocom.org/sim-card/pysim.git
+
+# Install pysim-otaman-server
+pip install .
+
+# Start the server
+pysim-otaman-server --http-port 8080
+

Connect a PC/SC reader with a SIM card, then point the PWA at http://127.0.0.1:8080.

+ + +
+

8. Version compatibility

+ + + + + + + +
PWA (OTAMan)ServerStatus
1.x.x1.x.x✅ Compatible
1.x.x0.x.x❌ Outdated — update server
1.x.x2.x.x+⚠️ Server newer — update PWA
+

The PWA checks the server version on connect via GET /api/version and warns if versions are incompatible.

+ + +
+
+ + + + diff --git a/index.html b/index.html index 03b07db..2711215 100644 --- a/index.html +++ b/index.html @@ -20,6 +20,7 @@
github + help
@@ -999,6 +1000,10 @@ function switchTab(name) { active.classList.remove('bg-gray-200', 'text-gray-700', 'dark:bg-slate-700', 'dark:text-slate-300'); active.classList.add('bg-blue-600', 'text-white', 'dark:bg-blue-500', 'dark:text-white'); if (name === 'c-apdu') cApduSwitchSubtab('sim'); + else if (name === 'sp') setHelpAnchor('secured-packet'); + else if (name === 'response') setHelpAnchor('response-parser'); + else if (name === 'cards') setHelpAnchor('cards'); + else if (name === 'pysim') setHelpAnchor(pysimHelpAnchor); } function cApduSwitchSubtab(name) { @@ -1019,6 +1024,7 @@ function cApduSwitchSubtab(name) { updateSimUsimFields(name); updateSimSelectMethod(name); } + setHelpAnchor({sim:'sim-rfm', usim:'usim-rfm', ber:'ber-tlv', ram:'ram-gp'}[name] || 'c-apdu'); } document.querySelectorAll('.tab-btn').forEach(btn => { btn.addEventListener('click', () => switchTab(btn.dataset.tab)); @@ -3107,6 +3113,8 @@ function pysimSwitchSubtab(name) { }); if (name === 'custom') pysimCustomRender(); if (name === 'proactive') { pysimEventsRender(); pysimProactiveLogRender(); pysimPliRender(); pysimPollStatusInit(); } + pysimHelpAnchor = {cmd:'pysim-cmdline', apdu:'raw-apdu', files:'file-manager', custom:'custom-files', proactive:'proactive-uicc'}[name] || 'card-reader'; + setHelpAnchor(pysimHelpAnchor); } function pysimCmdKeydown(e) { @@ -4630,6 +4638,7 @@ const LANG_RU = { 'Card reader inserted': 'Картридер вставлен', 'PROVIDE LOCAL INFORMATION response data': 'Данные для PROVIDE LOCAL INFORMATION', 'Send STATUS': 'Отправить STATUS', + 'help': 'справка', 'STATUS and Polling': 'STATUS и опрос', 'Polling': 'Опрос', 'STATUS...': 'STATUS...', @@ -4650,6 +4659,20 @@ function toggleLang() { document.getElementById('lang-btn').textContent = currentLang.toUpperCase(); translatePage(); translatePage(); + updateHelpLink(); +} + +let currentHelpAnchor = 'sim-rfm'; +let pysimHelpAnchor = 'file-manager'; + +function updateHelpLink() { + const link = document.getElementById('help-link'); + if (link) link.href = (currentLang === 'ru' ? 'help-ru.html' : 'help.html') + '#' + currentHelpAnchor; +} + +function setHelpAnchor(anchor) { + currentHelpAnchor = anchor; + updateHelpLink(); } function translatePage() { @@ -4665,6 +4688,7 @@ function translatePage() { const userLang = (navigator.language || '').split('-')[0]; currentLang = localStorage.getItem('lang') || (userLang === 'ru' ? 'ru' : 'en'); document.getElementById('lang-btn').textContent = currentLang.toUpperCase(); +updateHelpLink(); cardsLoad(); diff --git a/style.css b/style.css index 6907060..a4948b3 100644 --- a/style.css +++ b/style.css @@ -554,6 +554,10 @@ video { display: none; } +.static { + position: static; +} + .fixed { position: fixed; } @@ -566,6 +570,10 @@ video { position: relative; } +.sticky { + position: sticky; +} + .inset-0 { inset: 0px; } @@ -582,6 +590,10 @@ video { right: 0px; } +.top-0 { + top: 0px; +} + .z-10 { z-index: 10; } @@ -608,6 +620,10 @@ video { margin-bottom: 0.375rem; } +.mb-10 { + margin-bottom: 2.5rem; +} + .mb-2 { margin-bottom: 0.5rem; } @@ -668,6 +684,10 @@ video { display: block; } +.inline { + display: inline; +} + .flex { display: flex; } @@ -688,8 +708,8 @@ video { height: 4rem; } -.max-h-20 { - max-height: 5rem; +.h-screen { + height: 100vh; } .max-h-32 { @@ -744,10 +764,6 @@ video { width: 7rem; } -.w-3 { - width: 0.75rem; -} - .w-32 { width: 8rem; } @@ -772,6 +788,10 @@ video { width: 1.5rem; } +.w-72 { + width: 18rem; +} + .w-8 { width: 2rem; } @@ -808,6 +828,10 @@ video { flex-shrink: 0; } +.border-collapse { + border-collapse: collapse; +} + .cursor-pointer { cursor: pointer; } @@ -822,6 +846,22 @@ video { resize: none; } +.list-inside { + list-style-position: inside; +} + +.list-decimal { + list-style-type: decimal; +} + +.list-disc { + list-style-type: disc; +} + +.list-none { + list-style-type: none; +} + .grid-cols-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); } @@ -969,6 +1009,10 @@ video { border-left-width: 1px; } +.border-r { + border-right-width: 1px; +} + .border-t { border-top-width: 1px; } @@ -1142,10 +1186,32 @@ video { padding-bottom: 1rem; } +.py-6 { + padding-top: 1.5rem; + padding-bottom: 1.5rem; +} + +.py-8 { + padding-top: 2rem; + padding-bottom: 2rem; +} + +.pb-1 { + padding-bottom: 0.25rem; +} + .pl-2 { padding-left: 0.5rem; } +.pl-4 { + padding-left: 1rem; +} + +.pl-\[5\.5rem\] { + padding-left: 5.5rem; +} + .pt-1 { padding-top: 0.25rem; } @@ -1193,6 +1259,11 @@ video { line-height: 1.25rem; } +.text-xl { + font-size: 1.25rem; + line-height: 1.75rem; +} + .text-xs { font-size: 0.75rem; line-height: 1rem; @@ -1302,6 +1373,11 @@ video { color: rgb(185 28 28 / var(--tw-text-opacity, 1)); } +.text-slate-500 { + --tw-text-opacity: 1; + color: rgb(100 116 139 / var(--tw-text-opacity, 1)); +} + .text-white { --tw-text-opacity: 1; color: rgb(255 255 255 / var(--tw-text-opacity, 1)); diff --git a/sw.js b/sw.js index b5e7d0e..3a36d80 100644 --- a/sw.js +++ b/sw.js @@ -1,6 +1,8 @@ -const CACHE = 'otaman-v5'; +const CACHE = 'otaman-v6'; const URLS = [ 'index.html', + 'help.html', + 'help-ru.html', 'style.css', 'sim.png', 'icon-192.png', diff --git a/tailwind.config.js b/tailwind.config.js index 707b5a7..997dfa1 100644 --- a/tailwind.config.js +++ b/tailwind.config.js @@ -1,7 +1,7 @@ /** @type {import('tailwindcss').Config} */ module.exports = { darkMode: 'class', - content: ['./index.html'], + content: ['./index.html', './help.html', './help-ru.html'], theme: { extend: { textColor: {