diff --git a/.github/ISSUE_TEMPLATE/checklist-for-release.md b/.github/ISSUE_TEMPLATE/checklist-for-release.md index 534124ca9..aada17dd8 100644 --- a/.github/ISSUE_TEMPLATE/checklist-for-release.md +++ b/.github/ISSUE_TEMPLATE/checklist-for-release.md @@ -11,7 +11,7 @@ assignees: doegox, iceman1001 - [ ] `make style` - [ ] `make miscchecks` -- [ ] `make clean; make host CC=clang CXX=clang++ LD=clang++` on recent Debian or Ubuntu +- [ ] `make clean; make -j host CC=clang CXX=clang++ LD=clang++` on recent Debian or Ubuntu - [ ] `mymanualchecks.sh` - [ ] `mycppcheck.sh` no alarming warning? - [ ] `tools/build_all_firmwares.sh` check that the script contains all standalone modes then compile all standalone modes (linux only) @@ -44,7 +44,7 @@ Run `tools/release_tests.sh` on: - [ ] Ubuntu 25.10 - [ ] OSX (MacPorts) - [ ] OSX (Homebrew) -- [ ] Termux +- [ ] Termux cf `docker/termux-README.md` - [ ] Android cmake cross-compilation ? # creating release diff --git a/.github/workflows/fpga-pm3.yml b/.github/workflows/fpga-pm3.yml new file mode 100644 index 000000000..afe9a969c --- /dev/null +++ b/.github/workflows/fpga-pm3.yml @@ -0,0 +1,72 @@ +name: FPGA PM3 Build + +on: + push: + paths: + - 'fpga/**' + - '.github/workflows/fpga-pm3.yml' + pull_request: + paths: + - 'fpga/**' + - '.github/workflows/fpga-pm3.yml' + workflow_dispatch: + +permissions: + contents: read + +env: + # The PM3, PM3-ULT and iCopy-X images are Spartan-II and Spartan-3E, and + # WebPack ISE 10.1 is the only tool chain that places and routes them. It is a + # licensed multi gigabyte install, so the build runs inside this image, the + # one doc/fpga_arm_notes.md points at. Pinned by digest rather than by the + # tag, which has been re-pushed since it was first published. + ISE_IMAGE: nhutton/prox-container@sha256:b42abab7f88df928e59ab97ce3a557b547bc5fc967c19e49f30d7cfb8d3a5a15 + +jobs: + build: + name: Build the PM3 bitstreams + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v6 + + # The image is 8 GB unpacked, so keep an eye on the runner's disk. + - name: Pull the ISE image + run: | + df -h / + docker pull "$ISE_IMAGE" + + - name: Build the PM3 bitstreams + run: | + set -euo pipefail + docker run --rm -v "$PWD:/src" -w /src "$ISE_IMAGE" bash -euc ' + # The image exports its PATH from ~/.bashrc, which returns early in + # a non interactive shell, so name the ISE bin directory here. + export PATH="$PATH:/opt/Xilinx/10.1/ISE/bin/lin" + # XST cannot create its project temp directory on the mounted + # volume, so build a copy inside the container and copy the + # bitstreams back out over the checked out ones. + rm -rf /build && mkdir /build && cp -r /src/fpga/. /build/ + cd /build + make all -j"$(nproc)" + cp *.bit /src/fpga/ + ' + + - name: Check the bitstreams + run: | + set -euo pipefail + # fpga_icopyx_felica, fpga_icopyx_hf_15 and fpga_icopyx_lf have no + # target of their own and stay empty; the rest must have content + for t in fpga_pm3_lf fpga_pm3_hf fpga_pm3_hf_15 fpga_pm3_felica \ + fpga_pm3_ult_lf fpga_pm3_ult_hf fpga_pm3_ult_hf_15 \ + fpga_pm3_ult_felica fpga_icopyx_hf; do + size=$(stat -c%s "fpga/$t.bit") + echo "fpga/$t.bit ${size} bytes" + test "$size" -gt 1000 + done + + - uses: actions/upload-artifact@v6 + with: + name: fpga-pm3-bitstreams + path: fpga/*.bit + if-no-files-found: error diff --git a/.github/workflows/fpga-pm5.yml b/.github/workflows/fpga-pm5.yml new file mode 100644 index 000000000..00076fff8 --- /dev/null +++ b/.github/workflows/fpga-pm5.yml @@ -0,0 +1,89 @@ +name: FPGA PM5 Build + +on: + push: + paths: + - 'fpga/**' + - '.github/workflows/fpga-pm5.yml' + pull_request: + paths: + - 'fpga/**' + - '.github/workflows/fpga-pm5.yml' + workflow_dispatch: + +env: + # oss-cad-suite is released daily; bump the date to move to a newer one. + OSS_CAD_SUITE_VERSION: '2026-10-11' + +permissions: + contents: read + +jobs: + pm5: + name: Build PM5 bitstream + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v6 + + - name: Install oss-cad-suite + run: | + set -euo pipefail + url="https://github.com/YosysHQ/oss-cad-suite-build/releases/download/${OSS_CAD_SUITE_VERSION}/oss-cad-suite-linux-x64-${OSS_CAD_SUITE_VERSION//-/}.tgz" + echo "Fetching $url" + curl -sSL "$url" | tar -xz -C "$RUNNER_TEMP" + # the makefile puts the suite's bin/, lib/ and bundled python3 in + # front of PATH itself, so nothing else needs to be exported + echo "OSS_CAD_SUITE=$RUNNER_TEMP/oss-cad-suite" >> "$GITHUB_ENV" + + # Runs the real tools through the same environment the build uses, so a + # suite that cannot run fails here instead of half way through the build. + - name: Check the toolchain + run: make -C fpga -f proxmark5_fpga.mk smoke + + # Place and route fails the job on a timing violation, so this does not + # only prove the design still elaborates. + - name: Build the PM5 bitstream + run: make -C fpga pm5 + + - name: Check the bitstream + run: | + set -euo pipefail + bin_size=$(stat -c%s fpga/fpga_pm5.bin) + fs_size=$(stat -c%s fpga/fpga_pm5.fs) + echo "fpga_pm5.bin ${bin_size} bytes" + echo "fpga_pm5.fs ${fs_size} bytes" + # the .bin is the bitstream the ARM JTAG loader shifts out, the .fs is + # its ASCII form: 8 characters plus a newline per byte + test "$bin_size" -gt 100000 + test "$fs_size" -gt $((bin_size * 6)) + test "$fs_size" -lt $((bin_size * 10)) + + # The device only accepts a bitstream naming its own IDCODE and + # otherwise stays unconfigured, with nothing driving the antennas. + # apycula's GW1N-4 database writes the plain GW1N-4, so the build + # stamps the part's in (fpga/common/gowin_devid.py) - keep it that way. + # The IDCODE is the four bytes at 0x1C of the header. + idcode=$(od -An -tx1 -j 28 -N 4 fpga/fpga_pm5.bin | tr -d ' \n') + echo "device idcode in the bitstream: 0x${idcode}" + test "$idcode" = "1100381b" + + # A rebuild from scratch has to produce the same bytes; the tools carry no + # timestamp, so a difference means something started leaking one in, and + # a released bitstream could no longer be checked against the sources. + - name: Check the build is reproducible + run: | + set -euo pipefail + md5sum fpga/fpga_pm5.fs fpga/fpga_pm5.bin > "$RUNNER_TEMP/bitstream.md5" + make -C fpga -f proxmark5_fpga.mk clean + make -C fpga pm5 + md5sum -c "$RUNNER_TEMP/bitstream.md5" + + - name: Upload the bitstream + uses: actions/upload-artifact@v6 + with: + name: fpga-pm5-bitstream + path: | + fpga/fpga_pm5.fs + fpga/fpga_pm5.bin + if-no-files-found: error diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml index 2b02abbda..25daedb8d 100644 --- a/.github/workflows/macos.yml +++ b/.github/workflows/macos.yml @@ -37,6 +37,9 @@ jobs: run: brew update continue-on-error: true + - name: Trust brew repo + run: brew trust rfidresearchgroup/proxmark3 + - name: Tap RfidResearchGroup/proxmark3 run: brew tap RfidResearchGroup/proxmark3 @@ -78,6 +81,9 @@ jobs: run: brew update continue-on-error: true + - name: Trust brew repo + run: brew trust rfidresearchgroup/proxmark3 + - name: Tap RfidResearchGroup/proxmark3 run: brew tap RfidResearchGroup/proxmark3 @@ -120,6 +126,9 @@ jobs: run: brew update continue-on-error: true + - name: Trust brew repo + run: brew trust rfidresearchgroup/proxmark3 + - name: Tap RfidResearchGroup/proxmark3 run: brew tap RfidResearchGroup/proxmark3 diff --git a/.github/workflows/uniq.yaml b/.github/workflows/uniq.yaml index a21e26cc5..210f6adf1 100644 --- a/.github/workflows/uniq.yaml +++ b/.github/workflows/uniq.yaml @@ -4,9 +4,13 @@ on: push: paths: - 'client/dictionaries/**' + - 'client/resources/*.json' + - 'tools/check_json_uniq.py' pull_request: paths: - 'client/dictionaries/**' + - 'client/resources/*.json' + - 'tools/check_json_uniq.py' workflow_dispatch: @@ -20,3 +24,7 @@ jobs: run: | find . -type f -name "*.dic" | xargs -I {} sh -c "echo {} && cat {} | sed 's/ *#.*//;/^$/d' | sed 's/\(.*\)/\U\1/' | sort | uniq -i -d -c | sort -n -r " if [[ $(find . -type f -name "*.dic" | xargs -I {} sh -c "echo {} && cat {} | sed 's/ *#.*//;/^$/d' | sed 's/\(.*\)/\U\1/' | sort | uniq -i -d -c | sort -n -r " | grep -v '^\./' | wc -l) -gt 0 ]]; then exit 1; fi + + - name: check unique AIDs in resource json files + shell: bash + run: python3 tools/check_json_uniq.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 2cfca5970..6cb9823c2 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -23,7 +23,6 @@ jobs: run: shell: pwsh env: - PATH: C:/ProxSpace/msys2/ucrt64/bin;C:/ProxSpace/msys2/usr/local/bin;C:/ProxSpace/msys2/usr/bin;C:/ProxSpace/msys2/bin MSYSTEM: UCRT64 PYTHONHOME: /ucrt64 @@ -107,6 +106,19 @@ jobs: - uses: actions/checkout@v6 + # Prepend MSYS2 tools to PATH only for steps after checkout, so actions/checkout + # keeps using the runner's native git (MSYS2's git.exe mangles refs like + # 'tag^{commit}' due to its own bash-style argv reparsing). + - name: Add ProxSpace/MSYS2 to PATH + run: | + Add-Content -Path $env:GITHUB_PATH -Value "C:\ProxSpace\msys2\ucrt64\bin" + Add-Content -Path $env:GITHUB_PATH -Value "C:\ProxSpace\msys2\usr\local\bin" + Add-Content -Path $env:GITHUB_PATH -Value "C:\ProxSpace\msys2\usr\bin" + Add-Content -Path $env:GITHUB_PATH -Value "C:\ProxSpace\msys2\bin" + # Not set by an MSYS2 login shell here, so pkg-config wouldn't otherwise + # find the ucrt64 .pc files (zlib, jansson, gdlib, python3, etc). + Add-Content -Path $env:GITHUB_ENV -Value "PKG_CONFIG_PATH=/ucrt64/lib/pkgconfig:/ucrt64/share/pkgconfig" + # TODO workaround: "error: linker script file 'xxxx' appears multiple times" # This should be reverted once MSYS2 ships a non-broken version of the linker. - name: Downgrade ARM linker (Windows, temporary) diff --git a/.gitignore b/.gitignore index e667db8a6..22a5ed0a2 100644 --- a/.gitignore +++ b/.gitignore @@ -100,6 +100,8 @@ tools/mfulc_des_brute/mfulc_des_brute !tools/lena.bmp fpga/__build* +# the ASCII form of the PM5 bitstream, regenerated by the build like its .bin +fpga/*.fs # offcial dumps folder dumps/* diff --git a/AGENTS.md b/AGENTS.md index 2e10ef9a2..893c92d14 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -52,6 +52,27 @@ test): `tools/pm3_tests.sh` coverage if you're adding a new command/module that can be exercised offline. +### Never `rm -rf` an `obj/` directory + +The ARM-side build has no `mkdir` for its object directories — only the host +build creates its own. `armsrc/obj/`, `armsrc/obj/Standalone/` and +`bootrom/obj/` exist because each is held open in git by a tracked `.dummy` +file, and `make clean` deliberately deletes only the files *inside* them. +Delete such a directory and nothing recreates it. Every subsequent build dies +with messages that give no hint a tracked file went missing: + +``` +Error. Cannot open output file obj/fpga_all.bit.z +Fatal error: can't create obj/start.o: No such file or directory +``` + +`git checkout -- armsrc/obj/.dummy armsrc/obj/Standalone/.dummy bootrom/obj/.dummy` +puts it back. `git status` showing a deleted `.dummy` is the tell. + +If you script a build matrix, switch `PLATFORM=` / `STANDALONE=` and let make +decide what to rebuild — changing those changes the defines, which is enough to +force the recompile you want. + ## Code style - Respect the style used in this project: trailing @@ -134,3 +155,5 @@ Don't omit this to make a PR look purely human-written. - Don't introduce a dependency in one client build file without mirroring it in the other two. - Don't submit ARM-side changes only test-built for one platform target. +- Don't `rm -rf` any `obj/` directory to force a rebuild — it deletes tracked + `.dummy` files and breaks the build until they are restored. Use `make clean`. diff --git a/CHANGELOG.md b/CHANGELOG.md index ceef461b4..9a981101e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,10 +3,200 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] +- Fixed `lf t55xx detect -p` - the password is no longer sent to a tag whose PWD bit could not be confirmed, which could set it and destroy the tag's data; pass `-o` to override (@mfcarroll) +- Fixed `hf mf hardnested`/`hf mf autopwn` on PM5 with hardened MIFARE Classic EV1 (#3595, #3664) (@ByteOrderMarc) +- Added PM5 FPGA open source (@xianglin1998) +- Fixed `lf search`, `lf t55xx detect`, `data modulation` and the TI/Visa2000/ZX8211 demods leaking the saved graph and demod buffers on every call (@r3wretrhy) +- Updated `/Getting_Started_With_PM5.md` (@innocentbystanderproxmark) +- Fixed corrected `sim014.bin` references to `sim024.bin` as `sim014.bin` does not exist in this repo currently, thus removing some newbie confusion. (@innocentbystanderproxmark) +- Added `A1856618` (an EM4305 anti-clone card password) to the `t55xx_default_pwds` dictionary used by `lf em 4x05 chk` (@nemanjan00) +- Added `hw bwm ble` - the BWM's BLE settings: `on`/`off` (persisted radio switch), `pairing` (require a 6-digit passkey, LE Secure Connections; the module ships open), `forget` bonded devices, `txpower`, `status` (@Msprg) +- Changed `hw bwm autooff` - `--idle ` adds an opt-in power-off after that long idle on battery (no command, button press or BLE/WiFi client) (@Msprg) +- Added `hw bwm wifipower` - turn the BWM WiFi fully off, or set its modem power-save type (none/min/max), persisted on the module (@Msprg) +- Added `hw bwm powersave` - show/set the BWM (ESP32) power-save switch: DFS, light sleep and slow advertising after 30 s, or the stock always-on behaviour, persisted on the module (@Msprg) +- Added `hw powersave` - PM5 low-power idle, on by default: between commands the core drops to 48 MHz with the PLL off, the FPGA clock stopped and the CPU halted (WFI); USB now runs crystal-less off HICK' (@Msprg) +- Added `CMD_PM5_BWM_GET_BATTERY` on PM5 - compact structured battery/charger telemetry (SoC, voltage, current, remaining/full capacity, temp, health, charger fault/status) (@TomHarkness) +- Fixed `lf t55xx dump -p` - reuses the password already confirmed by `lf t55xx detect` (@iceman1001) +- Fixed `lf t55xx p1detect`, `lf search` - T5577 clones with a non-Atmel manufacturer byte now recognised (@iceman1001) +- Added Flipper Zero link on PM5's Type-C extended port (handshake + NG frames over SPI) - tracked in #3667 (@TomHarkness) +- Fixed PM5 CEP hang - missing `StartTicks()` before `I2C_init()` in `cep_attach_poll()`/`cep_init()` could freeze the main loop, e.g. during `hf search` (@TomHarkness) +- Fixed PM5 CEP reply corruption - `receive_ng()` zeroed the payload buffer between two time-critical SPI reads, losing bytes on CEP's FIFO-less receiver (@TomHarkness) +- Added `CMD_CEP_STATUS` on PM5 - a compact snapshot (CEP handshake active state, battery SoC, firmware version string) for CEP clients (@TomHarkness) +- Fixed `hf mf autopwn` on FM11RF08S - static encrypted nonce is now detected via the backdoor key (@iceman1001) +- Added `hf mfu view -v` - prints the UL-C 3DES key or UL-AES key stored in the dump file (@iceman1001) +- Added `hf mf sen --ns` - skip writing the key and dump files (@iceman1001) +- Fixed `hf mf autopwn --ns` on FM11RF08S - the flag is now honoured by the static encrypted nonce recovery instead of being dropped (@iceman1001) +- Added `hf mf sen --suffix` - generated files can be named `hf-mf---` (@iceman1001) +- Fixed `hf mf autopwn --suffix` on FM11RF08S - the suffix is now forwarded to the static encrypted nonce recovery instead of being dropped (@iceman1001) +- Fixed `hf mf sen` and `hf mf autopwn` on FM11RF08S - the recovered card dump is now saved as JSON as well as BIN (@iceman1001) +- Fixed `hf mfdes chk` - a key given with `--key` is now tried every round instead of being overwritten by the dictionary and pattern fills (@iceman1001) +- Fixed `hf mfdes chk` - when key settings are unreadable, key numbers are found with GetKeyVersion instead of the file access rights, which are gated by the same bit (@iceman1001) +- Fixed `hf mfdes chk` - the PICC master key is now checked, and a card that refuses GetApplicationIDs no longer aborts the whole run (@iceman1001) +- Fixed `hf mfdes chk` and `hf mfdes detect` - AuthenticateISO (0x1A) is read on its own instead of only when Authenticate (0x0A) answered, so an application holding 3TDEA keys is no longer skipped (@iceman1001) +- Changed `hf mfdes detect` - a key type the application does not hold is dropped on the first answer instead of after the error counter fills (@iceman1001) +- Changed `hf mfdes view` - now names known applications from the `aid_desfire` dictionary (@iceman1001) +- Added new entries from Metrodroid project into our AID json (@iceman1001) +- Changed `hf iclass view` - SIO Insights now surfaces unhandled TLV tags (e.g. the [5]/[9] context tags seen on SR credentials) instead of silently dropping them (@youngh82) +- Changed `hf mfdes view` - decodes the card issuer header of NORTIC travel cards, the Norwegian national public transport card (@iceman1001) +- Added `hf mf view` - decodes RKF travel cards, the Nordic public transport card (Resekortsföreningen i Norden) on MIFARE Classic (@iceman1001) +- Fixed `hf 14a info` now correctly handles NAK when receiving RATS (@iceman1001) +- Fixed `hf mfu restore` to support Ultralight AES (@iceman1001) +- Fixed `hf mfu info` to print UL-AES config pages again (@iceman1001) + + +## [Frosty Lemon.4.23346][2026-09-18] +- Fixed `hf mfdes sim` - the ATS now advertises 106 kbit/s only, PPS to a higher rate is refused, a selected card ignores REQA/WUPA, and ISO-DEP block recovery now follows the card sequence (@mistial-dev) +- Added `hf mfdes sim` - answers ISO 7816 SELECT by DF name or file id with real status words, so a reader that opens with a SELECT reaches the card (@mistial-dev) +- Fixed `hf mfdes sim` - a session opened with the 0x0A legacy authentication now uses the legacy secure messaging: 4 byte DES MAC, CRC16, no MAC on plain answers (@mistial-dev) +- Fixed `hf mfdes sim` - the 0x0A legacy authentication now enciphers the reader token and RndA' from a zero IV as a card does, so the session key and final frame match genuine silicon (@mistial-dev) +- Added `hf mfdes etest` - drives the DESFire simulation over USB without RF, with injectable RndB / random UID (@mistial-dev) +- Fixed USB receive stalling on a zero-length OUT packet and missing a command already buffered behind another (@cindersocket) +- Fixed dictionary loading to skip keys longer than the requested key size instead of truncating them (@iceman1001) +- Changed `hf mfdes chk` to check every key number the application declares, not only the ones a file's access rights name (@iceman1001) +- Changed `hf mfdes chk` to report when no keys were found and to stop spending a card round trip on an exhausted dictionary (@iceman1001) +- Changed `hf mfu cchk` and `hf mfu aeschk` into one `hf mfu chk` which detects UL-C vs UL-AES (@iceman1001) +- Added `hf 14b view` - MyKey / COGES keys on SRIX4K now decode (@iceman1001) +- Added `hf 14b view --selftest` - runs the MyKey parser self tests (@iceman1001) +- Removed `hf 14b valid` - the SRIX4K scrambler stub it wrapped is finished and lives in the MyKey parser (@iceman1001) +- Fixed build too large for 256kb images by guarding WITH_DESFIRE_SIM (@iceman1001) +- Fixed `pm3 flash` - the progress bar no longer keeps SIGINT after it finishes, CTRL-C works again afterwards (@iceman1001) +- Fixed `CTRL-C` / `CTRL-Z` - the client owns its signals instead of letting readline re-raise them, CTRL-C quits cleanly saving the history and CTRL-Z suspends reliably (@iceman1001) +- Fixed `CTRL-C` / `CTRL-Z` - readline re-raised caught signals to itself, which in a threaded client looped instead of quitting or suspending (@iceman1001) +- Fixed `pm3 flash` - the progress bar no longer keeps SIGINT after it finishes, CTRL-C works again afterwards (@iceman1001) +- Changed `pm3 history` - written after every command, so it survives a kill instead of only a clean exit (@iceman1001) +- Changed `memset` - the device's own implementation now fills a word at a time, the same treatment `memcpy` got. (@iceman1001) +- Changed `receive_ng` - the command payload is zeroed when a packet actually arrives rather than on every idle pass of the main loop. Thanks @Msprg (@iceman1001) +- Changed `hf mfdes chk` - runs with no arguments now, falling back to the bundled dictionary the way `hf mfdes detect` already does (@iceman1001) +- Changed `hf mfdes chk` - tidier output(@iceman1001) +- Fixed `hf mfdes sim` - a chained write is answered instead of being refused with 91 1C on its second frame. (@iceman1001) +- Fixed `hf mfdes sim` - an error status now ends the authenticated session, as M134034 7.3.4 requires of a card (@iceman1001) +- Fixed `hf mfdes sim` - answers are sized from the frame size the reader asks for in its RATS instead of a fixed 96 bytes (@iceman1001) +- Fixed `hf mfdes sim` - the length of a write is taken from the 3 byte length the command carries rather than guessed from how full a frame looked (@iceman1001) +- Fixed `hf mfdes detect` - the same cipher is no longer sent to the card twice, cutting a PICC level scan with the bundled dictionary from 99 authentications to 63 (@iceman1001) +- Changed `hf mfdes detect` - a single key number is printed as one value instead of a range of one, so a PICC level scan reads `key num 0x00` (@iceman1001) +- Fixed `hf mfdes sim` - an enciphered read longer than one frame is chained instead of refused, the init vector carrying from frame to frame (@iceman1001) +- Fixed `lf read` - a realtime read no longer ends early when the host falls behind, and the device no longer goes silent until it is replugged (@iceman1001) +- Fixed `lf read` - a realtime read ending on a full USB packet now delivers its last 64 bytes, an odd packet count was silently one packet short (@iceman1001) +- Fixed `lf read` - a transfer that stops short says so, instead of being presented as a complete read (@iceman1001) +- Changed `lf read` / `lf sniff` - the sample count is capped to the graph buffer size, the surplus was streamed and then thrown away (@iceman1001) +- Added `hf mfdes sim` - SetConfiguration is answered, so a reader can disable FormatPICC, switch the card to a random id, or give it a user defined ATS (@iceman1001) +- Added `hf mfdes sim` - ReadSignature is answered for a card image of a generation that has one, and refused the way a genuine EV1 refuses it (@iceman1001) +- Added `hf mfdes sim` - GetKeyVersion is answered, so a reader can read the version of any key without knowing the key itself (@iceman1001) +- Added `hf mfdes sim` - ChangeKeySettings is answered, enciphered and master key only, and clearing the configuration changeable bit is one way as it is on a card (@iceman1001) +- Added `hf mfdes sim` - ChangeKey is answered, both the plain and the XORed key frame, so a reader can rekey the simulated card and the new keys are in what `hf mfdes esave` writes out (@iceman1001) +- Added `hf mfdes sim` - ChangeFileSettings is answered, plain when the change access right is free and enciphered under the key it names otherwise (@iceman1001) +- Added `hf mfdes esave` - `--keep` saves applications and files a reader deleted, which are otherwise left out so the dump is the card as a reader sees it (@iceman1001) +- Added `hf mfdes sim` - CreateFile in all five EV1 flavours and DeleteFile are answered, so a reader can lay out an application's file system on the simulated card (@iceman1001) +- Added `hf mfdes sim` - CreateApplication and DeleteApplication are answered, so a reader can add and remove applications on the simulated card (@iceman1001) +- Added `hf mfdes sim` - FormatPICC is answered, releasing every application and file and handing the memory back, with the PICC master key and its settings kept (@iceman1001) +- Fixed `hf mfdes esave` - the ATS was saved as zeros, a `sizeof()` of the 256 byte destination cast to uint8_t wrapped to 0 and the copy was skipped while its length was still reported (@iceman1001) +- Added `hf mfdes sim` - DESFire EV1 simulation now answers authentication, secure messaging, file reads, writes and transactions from the card image in emulator memory (@iceman1001) +- Fixed `hf mfdes sim` - a 2TDEA key whose two halves match is handled as a single DES key, session key generation included, so the session key matches what a genuine PICC derives (@iceman1001) +- Fixed `hf mfdes sim` - the CMAC of a chained answer is taken over the whole transfer instead of being restarted on every 0xAF continuation (@iceman1001) +- Fixed `PLATFORM_EXTRAS=BWM` - a command started over the Proxmark5 wireless module can be aborted again. (@tweathers-sec) +- Fixed `lf search` - a leftover debug print no longer reports `DEBUG: detectindala | ` on every failed Indala demodulation (@tweathers-sec) +- Changed `memcpy` - the device's own implementation now copies a word at a time when source and destination allow it (@iceman1001) +- Changed NG replies - the outgoing frame is offset so its payload lands word aligned, taking USB transfer speed from 630 to 789 kB/s on RDV4 (@iceman1001) +- Fixed `AT91F_USB_SendStall` - waiting for the host to collect the STALL is now bounded (@iceman1001) +- Fixed `GET_LINE_CODING` - the CDC line coding struct is now packed to the 7 bytes the spec defines (@iceman1001) +- Fixed USB control transfers - a descriptor whose length is an exact multiple of the 8 byte control endpoint now ends with a zero length packet (@iceman1001) +- Fixed USB WCID descriptors - the device advertised Microsoft OS descriptor support in string 0xEE but stalled the vendor request that follows (@iceman1001) +- Added `hf mfdes sim` - answers GetDFNames and GetISOFileIDs, so a reader sees the ISO file ids and DF names of the simulated card (@iceman1001) +- Fixed `hf 14a` - an FPGA bitstream download no longer destroys the emulator memory that `eload` just filled (@iceman1001) +- Changed `hf mfdes sim` - now a self contained DESFire simulation, answering both native and ISO 7816 wrapped commands (@iceman1001) +- Fixed `hf mfdes` - GetDFNames is no longer sent inside an authenticated session, which permanently disabled DESFire EV1 cards (@iceman1001) +- Added `hf mfdes` - the five DESFire status codes that mean the card damaged or disabled itself are now named instead of reported as `-20` (@iceman1001) +- Fixed `hf mfdes` - a command error now drops the client's secure channel, since the PICC has already ended the authentication (@iceman1001) +- Fixed `hf mfdes` - file settings that could not be read are no longer reported and dumped as a zero byte standard data file (@iceman1001) +- Fixed `hf mfdes pc` - the proximity check commands now check the card's status byte instead of treating an error as success (@iceman1001) +- Changed `hf mfdes sim` - now runs through the shared ISO14443-A simulation loop as tag type 3 (@iceman1001) +- Added `hf mfdes eload/esave/eview` - load a DESFire card dump into emulator memory (@iceman1001) + - Fixed `PLATFORM=PM3ICOPYX` - builds again, it has no FPGA power switch and the AT91 GPIO layer used the pin unconditionally (@iceman1001) +- Fixed `fpga_compress` - PM3ULTIMATE builds again, its bitstreams are an exact multiple of the interleave size (@iceman1001) +- Fixed `hf legic eload` - an upload after a command that left a different FPGA bitstream loaded now writes the whole image (@iceman1001) +- Fixed `hf legic sim` - no longer wipes the emulator memory that `hf legic eload` just filled (@iceman1001) +- Changed emulator memory - raised from 4096 to 8192 bytes (@iceman1001) +- Fixed `hf 14a sim` - a dynamic response now gets a modulation buffer sized to fit it, instead of one 68 bytes too small (or 1788 too large for ST25TA) (@iceman1001) +- Fixed `BigBuf_malloc` - takes a uint32_t, so a request of 64KB or more fails instead of wrapping to zero (@iceman1001) +- Fixed `BigBuf_max_traceLen` - returns a uint32_t, so LF sampling on a device with more than 64KB of BigBuf is not handed a truncated buffer (@iceman1001) +- Fixed PM5 BigBuf allocation +- Changed `hf mf view` - now show which VIGIK fields are RSA signed (@iceman1001) +- Changed `hw status` - now reports EMULATOR memory (@iceman1001) +- Changed `hf mf view` - Urmet Captiv cards now decode their number field and data regions (@iceman1001) +- Changed `hf mf view --selftest` - now also checks the Hexact payload decoder, both ways (@iceman1001) +- Changed `hf mf view` - Hexact sector 9,11 payload is now decoded and cross checked against sector 0,15 and UID (@iceman1001) +- Added `hf mfdes dump` - now walks the whole PICC and saves a `hf-mfdes--dump.json` card image, picking up `hf-mfdes--keys.json` on its own (@iceman1001) +- Added `hf mfdes view` - print a DESFire card dump file, no device needed (@iceman1001) +- Fixed `sprint_hex` - a buffer twice the old size, so printing a long block no longer runs off the end of the static buffer (@iceman1001) +- Added `vigik_recover_pk.py` - recover public keys from RSA signatures (@iceman1001) +- Fixed `hf mf autopwn` - a sector that cannot be cracked no longer discards the keys already recovered (@iceman1001) +- Fixed `hf mf nested` - a NAK from the tag now ends the nonce collection instead of retrying until the client times out (@iceman1001) +- Fixed `hf mfdes` - select / authenticate failures are now reported once, naming the AID and the failing step (@iceman1001) +- Fixed `-f ` - a filename given with its own extension is now used as-is on both load and save (@iceman1001) +- Fixed `hf mf view` - VIGIK signature verification now recovers the ISO 9796-1 message and checks it against the card (@iceman1001) +- Added `hf mf view --selftest` - recovers and checks the signature of a known good expired VIGIK card (@iceman1001) +- Changed `hf mf view` / `hf mf dump --ns` - identify VIGIK family systems (@iceman1001) +- Added `parsehid.c` - HID PACS decoding for MIFARE Classic dumps +- Added `parsevigik.c` - VIGIK PACS decoding for MIFARE Classic dumps (@iceman1001) +- Changed `hf mf view` - now decode a HID PACS credential (@iceman1001) +- Changed `hf mf dump --ns` - now decode a HID PACS credential (@iceman1001) +- Fixed `fpga_compress -d` - a single bitstream archive was unpacked 2384 bytes short, the trailing partial interleave chunk was dropped (@iceman1001) +- Fixed `fpga_compress` - a build with only one FPGA bitstream (`SKIP_LF`, `SKIP_FELICA`, `SKIP_ISO15693`) packed it as a single 1 MB block the ARM could not decompress (@iceman1001) +- Fixed `FpgaDownloadAndGo` - a failed FPGA decompress leaked the ring buffer, leaving BigBuf 16 kB short for the rest of the session (@iceman1001) +- Added `hf mf dump --sk` - save extracted keys to binary file (@iceman1001) +- Changed `hf mf dump --ns` - now runs the same analysis as `hf mf view`(@iceman1001) +- Changed `tools/pm3_online_tests.sh desfire_value` - the plain/mac assertion pairs sent byte identical APDUs (@iceman1001) +- Fixed `smart raw --t1` - a card runs the protocol its ATR names until a PPS changes it (@iceman1001) +- Fixed `tools/pm3_online_tests.sh smartcard` - the T=0 checks used the non existent `-0` flag (@iceman1001) +- Fixed `hf mfdes dump` - the ISO file id probe ends the PICC session on applications without ISO file ids (@iceman1001) +- Changed `hf mfdes lsfiles` / `hf mfdes dump` - no longer warn about a missing ISO file id list (@iceman1001) +- Fixed `hf mfdes read` / `hf mfdes write` - a file whose access right is free (0x0E) is served in plain by the PICC (@iceman1001) +- Fixed `hf mfdes value` - credit/debit/limitedcredit used a fixed comm mode, now look on card (@iceman1001) +- Fixed `hf mfdes value -o get` / `hf mfdes dump` - a value file read in the wrong comm mode printed a silently wrong value instead of failing (@iceman1001) +- Fixed `lf idteck demod` - without `--raw` it decoded a zeroed stack buffer instead of the graphbuffer, always reporting card id 0 (@mfcarroll) +- Fixed `lf idteck demod` - a raw frame without the Idteck preamble printed `No genuine IDTECK found` and then announced a tag anyway (@mfcarroll) +- Changed `lf idteck demod` - no longer prints an HID H10301 credential built from the Idteck card id (@mfcarroll) +- Added `trace clear` - clears the tracebuffer (@iceman1001) +- Changed `trace save -1` - now downloads from device by default (@iceman1001) +- Added `hf 14a antifuzz --coll` - the UID collides from the 9th bit (@iceman1001) +- Changed `trace list -t 14a` - decodes SEL 0x99..0x9F, shows how many UID bits a bit oriented ANTICOLL claims (@iceman1001) +- Fixed `hf iclass encode` / `hf iclass tagsim` / `hf mf encodehid` / `lf hid sim` / `lf hid clone` / `lf hid brute` - `--cn` was read with a 32 bit getter (@iceman1001) +- Changed `hf mf eload` - the device now zeroes the emulator memory before the upload (@iceman1001) +- Fixed `hf mf sim` / `hf 14a sim` - the anticollision responses were prepared in BigBuf before `iso14443a_setup()` (@iceman1001) +- Changed `CAPABILITIES_VERSION` to 10 - `hf mf eload` sends a flags byte the device did not have before, so client and firmware must be flashed as a pair (@iceman1001) +- Changed `mem spiffs upload` - the file is held open across packets instead of being reopened by name for each one (@iceman1001) +- Added `hf thinfilm sniff` - passively records the frames a Thinfilm / NFC Barcode tag beams at a reader (@iceman1001) +- Fixed `hf thinfilm sim` - it now holds the genuine tag's measured 65536 carrier period frame rate instead of a fixed delay (@iceman1001) +- Changed `mem spiffs upload`/`mem spiffs dump` - both now print inline progress, and a refused write is reported with the byte it stopped at instead of claiming success (@iceman1001) +- Changed real-time LF sample reads `lf read`, `lf sniff`, `lf cotag reader`(@iceman1001) +- Changed the `INPLACE` spinner prefix (@iceman1001) +- Fixed `mem spiffs dump` - a file of 64K or more wrapped the uint16_t `BigBuf_calloc()` takes, the download now streams one frame at a time (@iceman1001) +- Fixed SPIFFS flash layer - a failed erase was reported to SPIFFS as success, letting it write into an un-erased sector where NOR AND-semantics silently mangled file data (@iceman1001) +- Fixed `hf thinfilm sim` - a 32 sample field read between every frame cost 3.8ms and nearly doubled the frame repeat period (@iceman1001) +- Added `hf thinfilm sim` - it now traces, so `trace list -t thinfilm` works on the sim side (@iceman1001) +- Fixed `hf texkom reader -v` - now no ovewflow in the general decoder (@iceman1001) +- Changed `trace list` - the Hitag U and Hitag S annotators now build their text with the `strlen()` offset (@iceman1001) +- Fixed `hf felica` - the service code footer wrote its closing bar past the end of a 128 byte buffer (@iceman1001) +- Fixed `trace list` - a Hitag U LOGIN or WRITE SINGLE BLOCK frame could write up to 17 bytes past the end of the 60 byte annotation buffer (@iceman1001) +- Fixed `hf mf autopwn` - it now re-authenticates and retries the block with the other key (@iceman1001) +- Fixed `hf mf hardnested` - the device declared `num_nonces * 4` bytes but packs 9 bytes per nonce pair. Thanks @TheArchitect0880 (@iceman1001) +- Changed `hf mfdes detect` - with no `-n` it now sweeps every key number the application declares instead of only key 0 (@iceman1001) +- Fixed `hf mfdes detect` - the card error counter was shared by every key type, so a bad run during the DES pass could abort the AES pass (@iceman1001) +- Fixed `hf mfdes detect` - with no `-f` it drew candidates from the MIFARE Plus 16 byte key list, it now defaults to the bundled `mfdes_default_keys` dictionary (@iceman1001) +- Fixed `hf mfdes detect` - LRP was only found when the key settings happened to be unreadable (@iceman1001) +- Added `hf mfdes chk --schann` - now detect the secure channel EV/EV2/LRP mode; detected per application and can be overridden (@iceman1001) +- Fixed `hf mfdes chk` - found keys were tracked per key number instead of per application, so a key number recovered on one AID was skipped later (@iceman1001) +- Fixed `data modulation` - the 160 sample antenna settle trim was never undone, so the graph buffer stayed short for everything after it (@mfcarroll) +- Changed `tests/lf_t55xx_writetest.lua` - reads each block three times and names how a bad read differs (`rol1`, `ror5`, `inverted`, `shr1`) instead of only pass/fail (@mfcarroll) - Fixed `lf t55xx detect` - PSK1 now detects at every bit rate and subcarrier. (@iceman1001) - Fixed `lf t55xx detect` - FSK was skipped entirely when the field-clock pair measured as neither legal pair, losing FSK1 at RF/32 and RF/40 and every variant at RF/16 (@iceman1001) +- Fixed `lf t55xx detect` - the block 0 rotation was picked by scan order; the measured broadcast period now settles it (@mfcarroll) +- Fixed `lf t55xx detect` - the psk antenna-settle trim left the graph 160 samples short, so the graph-sample anchor was discarded on most block reads (@mfcarroll) +- Fixed `lf psk demod` - lead-in samples were accepted as a phase shift, complementing the rest of the word (@mfcarroll) +- Fixed `lf fsk demod` - a leading run too short to be a bit was forced to one, fabricating a bit and shifting the word (@mfcarroll) +- Fixed `lf nrz demod` - the samples before the first level change were counted as bits, rotating the word whenever that edge moved (@mfcarroll) - Fixed `lf t55xx dump/read` - blocks were extracted at a bit offset cached from the last `detect` The offset is now anchored in graph samples (@iceman1001) -- Fixed `lf t55xx write --verify` - a successful write could be reported as a validation failure, both from the rotated read above and from the pre-write config decoding the post-write signal into garbage (@iceman1001) +- Fixed `lf t55xx write --verify` - a successful write could be reported as a validation failure (@iceman1001) - Fixed `lf t55xx detect` - the automatic detect after a block 0 write reported a password that was never supplied (@iceman1001) - Fixed `hf emrtd info` - now correctly pretty print algos (@iceman1001) - Fixed `trace list -t topaz` - now parses topaz reader frames up to 16 bytes (@iceman1001) @@ -17,10 +207,10 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac - Fixed `lf hitag list` - now prints in same style like the rest (@iceman1001) - Changed pathing - client now supports `~/` tilde sign in paths (@iceman1001) - Added `hf_legic_rdv4` - Standalone mode for managing 7 persistent legic dumps (@digitalhoax) -- Fixed `lf t55xx detect` - dropped the psk3 candidates, which run the same demodulation as the psk2 one beside them and so can never match a psk3 tag, only fire on demodulation errors (@mfcarroll) -- Fixed `lf t55xx detect` - a psk3 tag read back as psk2 with a block 0 one bit out, and a freshly wiped psk2 tag was reported as psk3 on no evidence; the two are now reported as ambiguous where the waveform cannot separate them, and block 0 is narrowed using the subcarrier, the broadcast period and whether password mode is in use (@mfcarroll) +- Fixed `lf t55xx detect` - dropped the psk3 candidates (@mfcarroll) +- Fixed `lf t55xx detect` - a psk3 tag read back as psk2 with a block 0 one bit out (@mfcarroll) - Added doc/md/PM5_Start_Here/Getting_Started_With_PM5.md now exists as a starting point for those who have their PM5 (@innocentbystanderproxmark) -- Fixed `tools/ePassport` - the personal number read from the MRZ optional-data field showed a filler character where a space belonged, and a document number longer than nine characters left its overflow there (@pkilar) +- Fixed `tools/ePassport` - the personal number read from the MRZ optional-data field showed a filler character where a space belonged (@pkilar) - Fixed `tools/ePassport` - the detail tabs named the files their data came from as fixed text, so a document without EF_DG11 was told otherwise, and the personal-number caption wrapped (@pkilar) - Added `tools/ePassport` - EF_DG13 is decoded, and a Polish document's PESEL is shown as the personal number when it carries no EF_DG11 (@pkilar) - Fixed `tools/ePassport` - a disabled button drew Kivy's banded disabled texture, which left its label unreadable (@pkilar) @@ -49,7 +239,7 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac - Fixed clock `SpinDelayUsPrecision` to not wrap. Now more 43ms issues (@iceman1001) - Changed `hf felica raw` - now can stream per-window envelope for better measurments (@iceman1001) - Updated `fpga_pm3_felica.bit` - FeliCa signal handling got refactored. (@iceman1001) -- Changed client tab completion - vocabulary is now built at runtime from the live command tree and uses the same availability rules as `help`, removing the generated `pm3line_vocabulary.h` and `pm3_help2list.py` (@Msprg) +- Changed client tab completion - vocabulary is now built at runtime from the live command tree and uses the same availability rules as `help` (@Msprg) - Fixed standalone modes - the one second button hold trigger was a no-op on all non-PM5 platforms, leaving `hw standalone` over USB as the only entry point (@ShawInnes) - Added `sim022.bin` - enabled burst mode transfers, which allows us to do TA1=96 in speeds (@iceman1001) - Fixed `hf felica liteauth` - empty long option names for `-c` and `-k` made argtable read past the string (found by ASAN on `--fulltext`) (@Msprg) diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index 28470f8d2..000000000 --- a/CLAUDE.md +++ /dev/null @@ -1,3 +0,0 @@ -# Instructions - -See [AGENTS.md](./AGENTS.md) for coding, build, and PR guidelines. This project keeps a single source of truth in AGENTS.md rather than duplicating instructions per tool. diff --git a/Makefile b/Makefile index 712bf8fbd..b5536fad4 100644 --- a/Makefile +++ b/Makefile @@ -337,7 +337,7 @@ style: commands # Make sure astyle is installed @command -v astyle >/dev/null || ( echo "Please install 'astyle' package first" ; exit 1 ) # Remove spaces & tabs at EOL, add LF at EOF if needed on *.c, *.h, *.cpp. *.lua, *.py, *.pl, Makefile, *.v, pm3 - find . \( -not -path "./cov-int/*" -and -not -path "./fpga*/xst/*" -and -not -path "./venv*" -and \( -name "*.[ch]" -or \( -name "*.cpp" -and -not -name "*.moc.cpp" \) -or -name "*.lua" -or -name "*.py" -or -name "*.pl" -or -name "Makefile" -or -name "*.v" -or -name "pm3" \) \) \ + find . \( -not -path "./cov-int/*" -and -not -path "./fpga*/xst/*" -and -not -path "./venv*" -and \( -name "*.[ch]" -or \( -name "*.cpp" -and -not -name "*.moc.cpp" \) -or -name "*.lua" -or -name "*.py" -or -name "*.pl" -or -name "Makefile" -or -name "*.v" -or \( -name "pm3" -and -type f \) \) \) \ -exec perl -pi -e 's/[ \t]+$$//' {} \; \ -exec sh -c "tail -c1 {} | xxd -p | tail -1 | grep -q -v 0a$$" \; \ -exec sh -c "echo >> {}" \; @@ -354,13 +354,20 @@ style: commands --style=google --unpad-paren --pad-header \ --align-pointer=name {} \; +COMMANDS_UTF8_FILTER := cat +COMMANDS_PYTHON := $(PYTHON3) +ifdef IS_MINGW + COMMANDS_UTF8_FILTER := iconv -f CP850 -t UTF-8 + COMMANDS_PYTHON := PYTHONIOENCODING=utf-8 $(PYTHON3) +endif + commands: client # Update commands.md - [ -x client/proxmark3 ] && client/proxmark3 -m | tr -d '\r' > doc/commands.md + [ -x client/proxmark3 ] && client/proxmark3 -m | $(COMMANDS_UTF8_FILTER) | tr -d '\r' > doc/commands.md # Make sure python3 is installed - @command -v python3 >/dev/null || ( echo "Please install 'python3' package first" ; exit 1 ) + @command -v $(PYTHON3) >/dev/null || ( echo "Please install '$(PYTHON3)' package first" ; exit 1 ) # Update commands.json, patch port in case it was run under Windows - [ -x client/proxmark3 ] && client/proxmark3 --fulltext | sed 's#com[0-9]#/dev/ttyACM0#'|python3 client/pyscripts/pm3_help2json.py - - | tr -d '\r' > doc/commands.json + [ -x client/proxmark3 ] && client/proxmark3 --fulltext | $(COMMANDS_UTF8_FILTER) | sed 's#com[0-9]#/dev/ttyACM0#'|$(COMMANDS_PYTHON) client/pyscripts/pm3_help2json.py - - | tr -d '\r' > doc/commands.json # Detecting weird codepages and tabs. @@ -376,7 +383,7 @@ miscchecks: # Make sure recode is installed @command -v recode >/dev/null || ( echo "Please install 'recode' package first" ; exit 1 ) @echo "Files with suspicious chars:" - @find . \( -not -path "./cov-int/*" -and -not -path "./client/deps/*" -and -not -path "./venv*" -and \( -name "*.[ch]" -or -name "*.cpp" -or -name "*.lua" -or -name "*.py" -or -name "*.pl" -or -name "Makefile" -or -name "*.v" -or -name "pm3" \) \) \ + @find . \( -not -path "./cov-int/*" -and -not -path "./client/deps/*" -and -not -path "./venv*" -and \( -name "*.[ch]" -or -name "*.cpp" -or -name "*.lua" -or -name "*.py" -or -name "*.pl" -or -name "Makefile" -or -name "*.v" -or \( -name "pm3" -and -type f \) \) \) \ -exec sh -c "cat {} |recode utf8.. >/dev/null || echo {}" \; ifneq (,$(EDIT)) @echo "Files with tabs: (EDIT enabled, files will be rewritten!)" @@ -384,7 +391,7 @@ else @echo "Files with tabs: (rerun with EDIT=1 if you want to convert them with vim)" endif # to remove tabs within lines, one can try with: vi $file -c ':set tabstop=4' -c ':set et|retab' -c ':wq' - @find . \( -not -path "./cov-int/*" -and -not -path "./client/deps/*" -and -not -path "./venv*" -and -not -wholename "./client/src/pm3_*wrap.c" -and \( -name "*.[ch]" -or \( -name "*.cpp" -and -not -name "*.moc.cpp" \) -or -name "*.lua" -or -name "*.py" -or -name "*.pl" -or -name "*.md" -or -name "*.txt" -or -name "*.awk" -or -name "*.v" -or -name "pm3" \) \) \ + @find . \( -not -path "./cov-int/*" -and -not -path "./client/deps/*" -and -not -path "./venv*" -and -not -wholename "./client/src/pm3_*wrap.c" -and \( -name "*.[ch]" -or \( -name "*.cpp" -and -not -name "*.moc.cpp" \) -or -name "*.lua" -or -name "*.py" -or -name "*.pl" -or -name "*.md" -or -name "*.txt" -or -name "*.awk" -or -name "*.v" -or \( -name "pm3" -and -type f \) \) \) \ -exec sh -c "$(TABSCMD)" \; # @echo "Files with printf \\\\t:" # @find . \( -name "*.[ch]" -or \( -name "*.cpp" -and -not -name "*.moc.cpp" \) -or -name "*.lua" -or -name "*.py" -or -name "*.pl" -or -name "*.md" -or -name "*.txt" -or -name "*.awk" -or -name "*.v" \) \ diff --git a/Makefile.defs b/Makefile.defs index 8cfcce10e..7304bb5f6 100644 --- a/Makefile.defs +++ b/Makefile.defs @@ -53,6 +53,7 @@ USERMOD = usermod -aG ADDUSER = adduser GETENT_BL = getent group bluetooth +PYTHON3 ?= python3 PYTHON3_PKGCONFIG ?= python3 PATHSEP=/ diff --git a/Makefile.platform.sample b/Makefile.platform.sample index ee68c7a3e..d912ce9d6 100644 --- a/Makefile.platform.sample +++ b/Makefile.platform.sample @@ -30,6 +30,7 @@ PLATFORM=PM3RDV4 #PLATFORM_EXTRAS=FLASH #PLATFORM_EXTRAS=SMARTCARD #PLATFORM_EXTRAS=BTADDON FPC_USART_DEV FLASH +#ENABLE_HFMFDESETEST=1 #STANDALONE=HF_UNISNIFF diff --git a/armsrc/BigBuf.c b/armsrc/BigBuf.c index cfd495c5d..a3172ffb5 100644 --- a/armsrc/BigBuf.c +++ b/armsrc/BigBuf.c @@ -23,7 +23,7 @@ #include "util.h" // nbytes #define BIGBUF_ALIGN_BYTES (4) -#define BIGBUF_ALIGN_MASK (0xFFFF + 1 - BIGBUF_ALIGN_BYTES) +#define BIGBUF_ALIGN_MASK (~(uint32_t)(BIGBUF_ALIGN_BYTES - 1)) extern uint32_t _stack_start[], __bss_end__[]; @@ -113,11 +113,18 @@ uint32_t BigBuf_get_hi(void) { return s_bigbuf_hi; } -/* +// how much emulator memory a card image may use. Reported to the client in +// capabilities_t so it sizes eload / esave from what the device actually has, +// instead of hardcoding a copy of CARD_MEMORY_SIZE uint32_t BigBuf_get_EM_size(void) { return CARD_MEMORY_SIZE; } -*/ + +// has the emulator memory been handed out yet? It is allocated lazily on the +// first BigBuf_get_EM_addr(), so "not allocated" means no card image is loaded +bool BigBuf_is_EM_allocated(void) { + return (s_emulator_memory != NULL); +} // clear ALL of BigBuf void BigBuf_Clear(void) { @@ -144,10 +151,16 @@ void BigBuf_Clear_keep_EM(void) { // allocate a chunk of memory from BigBuf. We allocate high memory first. The unallocated memory // at the beginning of BigBuf is always for traces/samples -uint8_t *BigBuf_malloc(uint16_t chunksize) { +// +// chunksize is a uint32_t on purpose. It used to be a uint16_t, which silently +// wrapped anything from 64 kbyte up -- a request for exactly 65536 came through +// as 0 -- and on a PM5, where BigBuf is several hundred kbyte, that is a size a +// caller can reasonably ask for. Oversized requests now fail the check below and +// return NULL like any other allocation that does not fit. +uint8_t *BigBuf_malloc(uint32_t chunksize) { chunksize = (chunksize + BIGBUF_ALIGN_BYTES - 1) & BIGBUF_ALIGN_MASK; // round up to next multiple of 4 - if (s_bigbuf_hi - s_trace_len < chunksize || chunksize == 0) { + if (chunksize == 0 || chunksize > s_bigbuf_hi || s_bigbuf_hi - s_trace_len < chunksize) { // no memory left or chunksize too large return NULL; } @@ -158,7 +171,7 @@ uint8_t *BigBuf_malloc(uint16_t chunksize) { // allocate a chunk of memory from BigBuf, and returns a pointer to it. // sets the memory to zero -uint8_t *BigBuf_calloc(uint16_t chunksize) { +uint8_t *BigBuf_calloc(uint32_t chunksize) { uint8_t *mem = BigBuf_malloc(chunksize); if (mem != NULL) { memset(mem, 0x00, ((chunksize + BIGBUF_ALIGN_BYTES - 1) & BIGBUF_ALIGN_MASK)); // round up to next multiple of 4 @@ -192,8 +205,12 @@ void BigBuf_print_status(void) { DbpString(_CYAN_("Memory")); Dbprintf(" BigBuf_size............. %d", s_bigbuf_size); Dbprintf(" Available memory........ %d", s_bigbuf_hi); + Dbprintf(" Emulator memory......... %d ( %s )" + , CARD_MEMORY_SIZE + , (s_emulator_memory != NULL) ? "in use" : "not allocated" + ); DbpString(_CYAN_("Tracing")); - Dbprintf(" tracing ................ %d", s_tracing); + Dbprintf(" tracing ................ %s", (s_tracing) ? "yes" : "no"); Dbprintf(" traceLen ............... %d", s_trace_len); if (g_dbglevel >= DBG_DEBUG) { @@ -218,7 +235,11 @@ void BigBuf_print_status(void) { } // return the maximum trace length (i.e. the unallocated size of BigBuf) -uint16_t BigBuf_max_traceLen(void) { +// Room left for traces and samples, ie everything below the lowest allocation. +// s_bigbuf_hi is a uint32_t and on a PM5 BigBuf is several hundred kbyte, so this +// must not be narrowed -- truncating it to 16 bits would silently hand LF +// sampling a fraction of the buffer it actually has +uint32_t BigBuf_max_traceLen(void) { return s_bigbuf_hi & BIGBUF_ALIGN_MASK; } diff --git a/armsrc/BigBuf.h b/armsrc/BigBuf.h index fa763cf22..43dfe66d8 100644 --- a/armsrc/BigBuf.h +++ b/armsrc/BigBuf.h @@ -20,12 +20,28 @@ #define __BIGBUF_H #include "common.h" +#include "pm3_cmd.h" #define MAX_FRAME_SIZE 256 // maximum allowed ISO14443 frame -#define MAX_PARITY_SIZE ((MAX_FRAME_SIZE + 7) / 8) +// The 14a demodulator stores 8 parity bits per 8 received bytes and then flushes +// one more byte once the receive buffer is full, so a full MAX_FRAME_SIZE frame +// needs (MAX_FRAME_SIZE / 8) + 1 parity bytes, not (MAX_FRAME_SIZE + 7) / 8 +#define MAX_PARITY_SIZE ((MAX_FRAME_SIZE / 8) + 1) #define MAX_MIFARE_FRAME_SIZE 19 // biggest Mifare frame is UL AES answer to AUTH (1 + 16 Bytes) + 2 Bytes CRC #define MAX_MIFARE_PARITY_SIZE 3 // need 19 parity bits for the 19 Byte above. 3 Bytes are enough to store these -#define CARD_MEMORY_SIZE 4096 +// How much of BigBuf a card image may use. A MIFARE Classic 4K fills 4096 of +// this exactly, so at that size emulator memory was fully committed and nothing +// larger could be simulated at all. +// +// This is carved out of BigBuf, which on AT91 is 33272 bytes, so every byte here +// is a byte traces and LF samples do not get. The largest allocation any tag +// simulation makes alongside it is 10459 bytes total, leaving 18.7 kB of trace +// at this size. LF acquisition is unaffected either way -- lfops.c calls +// BigBuf_free(), which drops emulator memory entirely. +// +// The device reports this to the client in capabilities_t, so the client sizes +// eload / esave from what the device has rather than a copy of this constant. +#define CARD_MEMORY_SIZE 8192 // For now we're storing FM11RF08S nonces in the upper 1k of CARD_MEMORY_SIZE // but we might have to allocate extra space if one day we've to support sth like a FM11RF32S #define CARD_MEMORY_RF08S_OFFSET 1024 @@ -35,11 +51,18 @@ // 8 data bits and 1 parity bit per payload byte, 1 correction bit, 1 SOC bit, 2 EOC bits #define TOSEND_BUFFER_SIZE (9 * MAX_FRAME_SIZE + 1 + 1 + 2) +// For double buffering, must be at least 2x PM3_CMD_DATA_SIZE +#if (PM3_CMD_DATA_SIZE * 2) > TOSEND_BUFFER_SIZE +#undef TOSEND_BUFFER_SIZE +#define TOSEND_BUFFER_SIZE (PM3_CMD_DATA_SIZE * 2) +#endif uint8_t *BigBuf_get_addr(void); uint32_t BigBuf_get_size(void); uint8_t *BigBuf_get_EM_addr(void); -uint16_t BigBuf_max_traceLen(void); +uint32_t BigBuf_get_EM_size(void); +bool BigBuf_is_EM_allocated(void); +uint32_t BigBuf_max_traceLen(void); uint32_t BigBuf_get_hi(void); void BigBuf_initialize(void); @@ -47,8 +70,8 @@ void BigBuf_Clear(void); void BigBuf_Clear_ext(bool verbose); void BigBuf_Clear_keep_EM(void); void BigBuf_Clear_EM(void); -uint8_t *BigBuf_malloc(uint16_t); -uint8_t *BigBuf_calloc(uint16_t); +uint8_t *BigBuf_malloc(uint32_t); +uint8_t *BigBuf_calloc(uint32_t); void BigBuf_free(void); void BigBuf_free_keep_EM(void); void BigBuf_print_status(void); diff --git a/armsrc/CMakeLists.txt b/armsrc/CMakeLists.txt index 6916590c2..4223d8812 100644 --- a/armsrc/CMakeLists.txt +++ b/armsrc/CMakeLists.txt @@ -31,6 +31,11 @@ include(${CMAKE_CURRENT_LIST_DIR}/../tools/FpgaCompress.cmake) # --------------------------------------------------------------------------------- +option(ENABLE_HFMFDESETEST "Build the host-driven DESFire emulator test hook" OFF) +if (ENABLE_HFMFDESETEST) + list(APPEND PLATFORM_DEFS -DENABLE_HFMFDESETEST) +endif () + set(APP_CFLAGS ${PLATFORM_DEFS} -ffunction-sections -fdata-sections) set(INC_DIRS @@ -104,6 +109,10 @@ set(SRC_ISO14443a sam_sc.c ) +if (NOT SKIP_DESFIRE_SIM) + list(APPEND SRC_ISO14443a desfiresim.c) +endif () + #UNUSED: mifaresniff.c set(SRC_ISO14443b iso14443b.c) @@ -178,6 +187,12 @@ else () set(SRC_FPC) endif () +if ("${APP_CFLAGS}" MATCHES "WITH_BWM_FORWARD") + set(SRC_BWM bwm_uart_at32.c bwm_forward.c bwm_wifi.c bwm_frame.c) +else () + set(SRC_BWM) +endif () + # BWM charger (AW32001) + fuel gauge (BQ27427), incl. the optional low-batt beep if ("${APP_CFLAGS}" MATCHES "WITH_BWM_STATUS" OR "${APP_CFLAGS}" MATCHES "WITH_BWM_CHARGERKICK") set(SRC_BWM_CHARGER bwm_charger.c) @@ -262,6 +277,7 @@ set(THUMBSRC ${SRC_FLASH} ${SRC_SMARTCARD} ${SRC_FPC} + ${SRC_BWM} ${SRC_HITAG} ${SRC_EM4x50} ${SRC_EM4x70} @@ -304,6 +320,7 @@ if (PM5) list(APPEND THUMBSRC startup_at32f435_437.s) list(APPEND THUMBSRC i2c.c) list(APPEND THUMBSRC buzzer.c) # generic mainboard buzzer (QC self-test + BWM low-batt) + list(APPEND THUMBSRC pm5_power.c) # low-power idle (core clock scaling + WFI) list(APPEND THUMBSRC at32_unit_test.c) # TODO DXL: AT32单元测试代码 endif () diff --git a/armsrc/Makefile b/armsrc/Makefile index 7003ade65..9faca1ab4 100644 --- a/armsrc/Makefile +++ b/armsrc/Makefile @@ -74,6 +74,10 @@ SRC_HF = hfops.c SRC_ISO15693 = iso15693.c iso15693tools.c SRC_ISO14443a = iso14443a.c secc.c mifareutil.c mifarecmd.c epa.c mifaresim.c +ifneq (,$(findstring WITH_DESFIRE_SIM,$(APP_CFLAGS))) + SRC_ISO14443a += desfiresim.c +endif + ifneq (,$(findstring WITH_SMARTCARD,$(APP_CFLAGS))) SRC_ISO14443a += sam_common.c sam_mfc.c sam_seos.c sam_sc.c endif @@ -115,11 +119,17 @@ else endif ifneq (,$(findstring WITH_BWM_FORWARD,$(APP_CFLAGS))) - SRC_BWM = bwm_uart_at32.c bwm_forward.c bwm_wifi.c + SRC_BWM = bwm_uart_at32.c bwm_forward.c bwm_wifi.c bwm_frame.c else SRC_BWM = endif +ifneq (,$(findstring WITH_CEP,$(APP_CFLAGS))) + SRC_CEP = pm5_cep.c +else + SRC_CEP = +endif + # BWM charger (AW32001) + fuel gauge (BQ27427), incl. the optional low-batt beep ifneq (,$(findstring WITH_BWM_STATUS,$(APP_CFLAGS))$(findstring WITH_BWM_CHARGERKICK,$(APP_CFLAGS))) SRC_BWM_CHARGER = bwm_charger.c @@ -134,6 +144,13 @@ else SRC_BUZZER = endif +# PM5 low-power idle (core clock scaling + WFI) +ifeq ($(PLATFORM),PM5) + SRC_PM5_POWER = pm5_power.c +else + SRC_PM5_POWER = +endif + # PM5 antenna-RGB power/battery indicator ifneq (,$(findstring WITH_PM5_PWR_LED,$(APP_CFLAGS))) SRC_RGB_INDICATOR = rgb_indicator.c @@ -198,8 +215,10 @@ THUMBSRC = start.c \ $(SRC_SMARTCARD) \ $(SRC_FPC) \ $(SRC_BWM) \ + $(SRC_CEP) \ $(SRC_BWM_CHARGER) \ $(SRC_BUZZER) \ + $(SRC_PM5_POWER) \ $(SRC_RGB_INDICATOR) \ $(SRC_HITAG) \ $(SRC_EM4x50) \ @@ -319,9 +338,9 @@ $(OBJDIR)/fullimage.data.bin: $(OBJDIR)/fullimage.stage1.elf $(OBJDIR)/fullimage.data.bin.z: $(OBJDIR)/fullimage.data.bin $(FPGA_COMPRESSOR) $(info [-] GEN $@) ifeq ($(Q),@) - @$(FPGA_COMPRESSOR) $(filter %.bin,$^) $@ >/dev/null + @$(FPGA_COMPRESSOR) -s $(filter %.bin,$^) $@ >/dev/null else - $(FPGA_COMPRESSOR) $(filter %.bin,$^) $@ + $(FPGA_COMPRESSOR) -s $(filter %.bin,$^) $@ endif $(OBJDIR)/fullimage.elf: $(OBJDIR)/fullimage.stage1.elf $(OBJDIR)/fullimage.data.bin.z diff --git a/armsrc/Standalone/Makefile.hal b/armsrc/Standalone/Makefile.hal index 0c8673151..906f68cc9 100644 --- a/armsrc/Standalone/Makefile.hal +++ b/armsrc/Standalone/Makefile.hal @@ -77,10 +77,10 @@ define KNOWN_STANDALONE_DEFINITIONS | HF_14BSNIFF | 14b sniff to flashmem (rdv4) or ram | | | | +-----------------------------------------------------------+ -| HF_15SNIFF | 15693 sniff to flashmem (rdv4) or ram | +| HF_15SIM | 15693 tag simulator | | | | +-----------------------------------------------------------+ -| HF_15SIM | 15693 tag simulator | +| HF_15SNIFF | 15693 sniff to flashmem (rdv4) or ram | | | | +-----------------------------------------------------------+ | HF_AVEFUL | Mifare ultralight read/simulation | @@ -104,6 +104,9 @@ define KNOWN_STANDALONE_DEFINITIONS | HF_DOEGOX_COMMIT | DESFire suspended commit | | | - Philippe Teuwen | +-----------------------------------------------------------+ +| HF_EMVPNG | Read and emulate EMV Visa cards | +| | - Davi Mikael (Penegui) | ++-----------------------------------------------------------+ | HF_ICECLASS | Simulate HID iCLASS legacy ags | | (RDV4 only) | storing in flashmem | +-----------------------------------------------------------+ @@ -146,15 +149,12 @@ define KNOWN_STANDALONE_DEFINITIONS | DANKARMULTI | Load multiple standalone modes. | | | - Daniel Karling | +-----------------------------------------------------------+ -| HF_EMVPNG | Read and emulate EMV Visa cards | -| | - Davi Mikael (Penegui) | -+-----------------------------------------------------------+ endef STANDALONE_MODES := LF_SKELETON STANDALONE_MODES += LF_EM4100EMUL LF_EM4100RSWB LF_EM4100RSWW LF_EM4100RWC LF_HIDBRUTE LF_HIDFCBRUTE LF_ICEHID LF_MULTIHID LF_NEDAP_SIM LF_NEXID LF_PROXBRUTE LF_PROX2BRUTE LF_SAMYRUN LF_THAREXDE -STANDALONE_MODES += HF_14ASNIFF HF_14BSNIFF HF_15SNIFF HF_15SIM HF_AVEFUL HF_BOG HF_CARDHOPPER HF_COLIN HF_CRAFTBYTE HF_DOEGOX_AUTH0 HF_DOEGOX_COMMIT HF_ICECLASS HF_LEGIC HF_LEGIC_RDV4 HF_LEGICSIM HF_MATTYRUN HF_MFCSIM HF_MSDSAL HF_REBLAY HF_ST25_TEAROFF HF_TCPRST HF_TMUDFORD HF_UNISNIFF HF_YOUNG HF_EMVPNG +STANDALONE_MODES += HF_14ASNIFF HF_14BSNIFF HF_15SIM HF_15SNIFF HF_AVEFUL HF_BOG HF_CARDHOPPER HF_COLIN HF_CRAFTBYTE HF_DOEGOX_AUTH0 HF_DOEGOX_COMMIT HF_EMVPNG HF_ICECLASS HF_LEGIC HF_LEGIC_RDV4 HF_LEGICSIM HF_MATTYRUN HF_MFCSIM HF_MSDSAL HF_REBLAY HF_ST25_TEAROFF HF_TCPRST HF_TMUDFORD HF_UNISNIFF HF_YOUNG STANDALONE_MODES += DANKARMULTI STANDALONE_MODES_REQ_BT := HF_CARDHOPPER HF_REBLAY STANDALONE_MODES_REQ_SMARTCARD := diff --git a/armsrc/Standalone/hf_bog.c b/armsrc/Standalone/hf_bog.c index 7c4b3e5d5..758c5139a 100644 --- a/armsrc/Standalone/hf_bog.c +++ b/armsrc/Standalone/hf_bog.c @@ -76,6 +76,14 @@ static void RAMFUNC SniffAndStore(uint8_t param) { // The DMA buffer, used to stream samples from the FPGA uint8_t *dmaBuf = BigBuf_calloc(DMA_BUFFER_SIZE); + + if (capturedPwds == NULL || receivedCmd == NULL || receivedCmdPar == NULL || + receivedResp == NULL || receivedRespPar == NULL || dmaBuf == NULL) { + if (g_dbglevel >= DBG_ERROR) DbpString("hf bog: failed to allocate buffers"); + BigBuf_free(); + return; + } + uint8_t *data = dmaBuf; uint8_t previous_data = 0; diff --git a/armsrc/Standalone/hf_colin.c b/armsrc/Standalone/hf_colin.c index 1dab49959..7d9ca9b48 100644 --- a/armsrc/Standalone/hf_colin.c +++ b/armsrc/Standalone/hf_colin.c @@ -252,6 +252,14 @@ static char *ReadSchemasFromSPIFFS(char *filename) { int changed = rdv40_spiffs_lazy_mount(); uint32_t size = size_in_spiffs((char *)filename); uint8_t *mem = BigBuf_calloc(size); + if (mem == NULL) { + if (changed) { + rdv40_spiffs_lazy_unmount(); + } + SpinOff(0); + return NULL; + } + rdv40_spiffs_read_as_filetype((char *)filename, (uint8_t *)mem, size, RDV40_SPIFFS_SAFETY_SAFE); if (changed) { @@ -264,6 +272,11 @@ static char *ReadSchemasFromSPIFFS(char *filename) { static void __attribute__((noinline)) add_schemas_from_json_in_spiffs(char *filename) { const char *jsonfile = ReadSchemasFromSPIFFS((char *)filename); + if (jsonfile == NULL) { + DbprintfEx(FLAG_NEWLINE, "[!!] out of memory, schemas NOT loaded"); + cjSetCursLeft(); + return; + } int i, len = strlen(jsonfile); struct json_token t; @@ -294,6 +307,12 @@ static void __attribute__((noinline)) ReadLastTagFromFlash(void) { cjSetCursLeft(); uint8_t *mem = BigBuf_calloc(size); + if (mem == NULL) { + DbprintfEx(FLAG_NEWLINE, "[!!] out of memory, last tag NOT recovered"); + cjSetCursLeft(); + SpinOff(0); + return; + } // this one will handle filetype (symlink or not) and resolving by itself rdv40_spiffs_read_as_filetype((char *)HFCOLIN_LASTTAG_SYMLINK, (uint8_t *)mem, len, RDV40_SPIFFS_SAFETY_SAFE); @@ -457,6 +476,13 @@ void RunMod(void) { // Can remember something like that in case of Bigbuf keyBlock = BigBuf_calloc(ARRAYLEN(mfKeys) * MF_KEY_LENGTH); + if (keyBlock == NULL) { + DbprintfEx(FLAG_NEWLINE, "[!!] out of memory, aborting"); + cjSetCursLeft(); + SpinOff(0); + return; + } + int mfKeysCnt = ARRAYLEN(mfKeys); for (int mfKeyCounter = 0; mfKeyCounter < mfKeysCnt; mfKeyCounter++) { @@ -961,7 +987,7 @@ static int saMifareCSetBlock(uint32_t arg0, uint32_t arg1, uint32_t arg2, const if (workFlags & 0x08) { iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); // clear_trace(); - set_tracing(FALSE); + set_tracing(false); } while (true) { diff --git a/armsrc/Standalone/hf_colin.h b/armsrc/Standalone/hf_colin.h index fa8730d98..1bb59c2a8 100644 --- a/armsrc/Standalone/hf_colin.h +++ b/armsrc/Standalone/hf_colin.h @@ -19,10 +19,6 @@ #include #include -#ifndef FALSE -#define FALSE 0 -#endif - #ifndef __HF_COLIN_H #define __HF_COLIN_H diff --git a/armsrc/Standalone/hf_doegox_auth0.c b/armsrc/Standalone/hf_doegox_auth0.c index 2e1c9ff60..09d36e77b 100644 --- a/armsrc/Standalone/hf_doegox_auth0.c +++ b/armsrc/Standalone/hf_doegox_auth0.c @@ -193,6 +193,12 @@ static bool RAMFUNC sniff_wait_for_rnda_reply(tag_t type) { uint8_t *receivedResp = BigBuf_calloc(MAX_FRAME_SIZE); uint8_t *receivedRespPar = BigBuf_calloc(MAX_PARITY_SIZE); + if (receivedCmd == NULL || receivedCmdPar == NULL || + receivedResp == NULL || receivedRespPar == NULL) { + if (g_dbglevel >= DBG_ERROR) DbpString("hf doegox auth0: failed to allocate buffers"); + goto out; + } + uint8_t previous_data = 0; int maxDataLen = 0, dataLen; bool TagIsActive = false; diff --git a/armsrc/Standalone/hf_doegox_commit.c b/armsrc/Standalone/hf_doegox_commit.c index c46f79080..3a4e8b75c 100644 --- a/armsrc/Standalone/hf_doegox_commit.c +++ b/armsrc/Standalone/hf_doegox_commit.c @@ -169,6 +169,12 @@ static bool RAMFUNC sniff_wait_for_commit(tag_t type) { uint8_t *receivedResp = BigBuf_calloc(MAX_FRAME_SIZE); uint8_t *receivedRespPar = BigBuf_calloc(MAX_PARITY_SIZE); + if (receivedCmd == NULL || receivedCmdPar == NULL || + receivedResp == NULL || receivedRespPar == NULL) { + if (g_dbglevel >= DBG_ERROR) DbpString("hf doegox commit: failed to allocate buffers"); + goto out; + } + uint8_t previous_data = 0; int maxDataLen = 0, dataLen; bool TagIsActive = false; diff --git a/armsrc/Standalone/hf_iceclass.c b/armsrc/Standalone/hf_iceclass.c index 8a6345d79..840fd36f0 100644 --- a/armsrc/Standalone/hf_iceclass.c +++ b/armsrc/Standalone/hf_iceclass.c @@ -240,6 +240,10 @@ static int reader_attack_mode(void) { BigBuf_free(); uint16_t mac_response_len = 0; uint8_t *mac_responses = BigBuf_calloc(MAC_RESPONSES_SIZE); + if (mac_responses == NULL) { + Dbprintf("Failed to allocate memory"); + return PM3_EMALLOC; + } iclass_simulate(ICLASS_SIM_MODE_READER_ATTACK, NUM_CSNS, false, false, csns, mac_responses, &mac_response_len); @@ -252,7 +256,7 @@ static int reader_attack_mode(void) { size_t dumplen = NUM_CSNS * 24; uint8_t *dump = BigBuf_calloc(dumplen); - if (dump == false) { + if (dump == NULL) { Dbprintf("Failed to allocate memory"); return PM3_EMALLOC; } @@ -306,6 +310,10 @@ static int reader_dump_mode(void) { BigBuf_free(); uint8_t *card_data = BigBuf_malloc(ICLASS_16KS_SIZE); + if (card_data == NULL) { + Dbprintf("Failed to allocate memory"); + return PM3_EMALLOC; + } // Don't use calloc since we set allocated memory to 0xFF's memset(card_data, 0xFF, ICLASS_16KS_SIZE); @@ -444,6 +452,10 @@ static int dump_sim_mode(void) { BigBuf_free(); uint8_t *card_data = BigBuf_malloc(ICLASS_16KS_SIZE); + if (card_data == NULL) { + Dbprintf("Failed to allocate memory"); + return PM3_EMALLOC; + } // Don't use calloc since we set allocated memory to 0xFF's memset(card_data, 0xFF, ICLASS_16KS_SIZE); diff --git a/armsrc/Standalone/hf_legic_rdv4.c b/armsrc/Standalone/hf_legic_rdv4.c index 94d8e8534..6fb28a8e1 100644 --- a/armsrc/Standalone/hf_legic_rdv4.c +++ b/armsrc/Standalone/hf_legic_rdv4.c @@ -61,10 +61,14 @@ static uint8_t get_slot_led_mask(uint8_t slot_1_to_7) { static const char *get_tagtype_name(uint8_t tagtype) { switch (tagtype) { - case 0: return "MIM22"; - case 1: return "MIM256"; - case 2: return "MIM1024"; - default: return "Unknown"; + case 0: + return "MIM22"; + case 1: + return "MIM256"; + case 2: + return "MIM1024"; + default: + return "Unknown"; } } @@ -358,10 +362,18 @@ void RunMod(void) { if (p_card && p_card->cardsize > 0) { uint8_t ct = 2; switch (p_card->tagtype) { - case 0x0D: ct = 0; break; - case 0x1D: ct = 1; break; - case 0x3D: ct = 2; break; - default: ct = 2; break; + case 0x0D: + ct = 0; + break; + case 0x1D: + ct = 1; + break; + case 0x3D: + ct = 2; + break; + default: + ct = 2; + break; } Dbprintf(_GREEN_("[+] [TAG DETECTED] Read successful on Slot %u!"), (unsigned int)(current_slot + 1)); diff --git a/armsrc/Standalone/hf_mattyrun.c b/armsrc/Standalone/hf_mattyrun.c index d35345528..3ddf11e91 100644 --- a/armsrc/Standalone/hf_mattyrun.c +++ b/armsrc/Standalone/hf_mattyrun.c @@ -269,6 +269,11 @@ void RunMod(void) { sizeof(uint64_t) * (ARRAYLEN(MATTYRUN_MFC_ESSENTIAL_KEYS) + ARRAYLEN(MATTYRUN_MFC_DEFAULT_KEYS) + MIFARE_4K_MAXSECTOR * 2)); + if (mfcKeys == NULL) { + DbpString("Failed to allocate memory"); + return; + } + uint16_t mfcKeyCount = 0; // Load essential keys to dictionary buffer diff --git a/armsrc/Standalone/hf_st25_tearoff.c b/armsrc/Standalone/hf_st25_tearoff.c index e32b86c40..88935276c 100644 --- a/armsrc/Standalone/hf_st25_tearoff.c +++ b/armsrc/Standalone/hf_st25_tearoff.c @@ -1077,7 +1077,10 @@ void ModInfo(void) { void RunMod(void) { StandAloneMode(); Dbprintf(_YELLOW_("HF ST25TB Store/Restore mode started")); - iso14443b_setup(); + if (iso14443b_setup() != PM3_SUCCESS) { + Dbprintf(_RED_("Failed to allocate buffers, exiting")); + return; + } LED_D_OFF(); FpgaDownloadAndGo(FPGA_BITSTREAM_HF); // Use HF bitstream for ISO14443B diff --git a/armsrc/Standalone/hf_unisniff.c b/armsrc/Standalone/hf_unisniff.c index c26b53632..0596302c6 100644 --- a/armsrc/Standalone/hf_unisniff.c +++ b/armsrc/Standalone/hf_unisniff.c @@ -156,7 +156,7 @@ static void UniSniff_DownloadTraceInstructions(char *fn, const char *proto) { #endif void ModInfo(void) { - DbpString(" HF UNISNIFF - multimode HF sniffer (hazardousvoltage)"); + DbpString(" HF UNISNIFF - multimode HF sniffer ( hazardousvoltage )"); Dbprintf(" Compile-time default protocol... %s", HF_UNISNIFF_PROTOCOL); #ifdef WITH_FLASH DbpString(" FLASH support................... yes"); diff --git a/armsrc/Standalone/lf_multihid.c b/armsrc/Standalone/lf_multihid.c index cf471da33..984bdc9fe 100644 --- a/armsrc/Standalone/lf_multihid.c +++ b/armsrc/Standalone/lf_multihid.c @@ -31,8 +31,8 @@ #include "dbprint.h" #include "ticks_apis.h" #include "lfops.h" +#include "commonutil.h" // ARRAYLEN -#define ARRAYLEN(x) (sizeof(x) / sizeof((x)[0])) #define MAX_IND 4 void LED_Slot(int i); diff --git a/armsrc/Standalone/lf_tharexde.c b/armsrc/Standalone/lf_tharexde.c index 76b143a4b..87013593f 100644 --- a/armsrc/Standalone/lf_tharexde.c +++ b/armsrc/Standalone/lf_tharexde.c @@ -104,6 +104,11 @@ static bool get_input_data_from_file(uint32_t *tag, char *inputfile) { uint32_t size = size_in_spiffs(inputfile); uint8_t *mem = BigBuf_calloc(size); + if (mem == NULL) { + Dbprintf(_RED_("failed to allocate memory for %s"), inputfile); + BigBuf_free(); + return false; + } Dbprintf("found input file `" _YELLOW_("%s") "`", inputfile); diff --git a/armsrc/appmain.c b/armsrc/appmain.c index 328434b14..09f06dbec 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -27,6 +27,9 @@ #include "bwm_forward.h" // bwm_fwd_negotiate_baud() #include "bwm_wifi.h" #endif +#ifdef WITH_CEP +#include "pm5_cep.h" +#endif #include "pm3_cmd.h" #include "proxmark3_arm.h" #include "dbprint.h" @@ -68,6 +71,9 @@ #include "mifarecmd.h" #include "mifaredesfire.h" #include "mifaresim.h" +#ifdef WITH_DESFIRE_SIM +#include "desfiresim.h" +#endif #include "emvsim.h" #include "pcf7931.h" #include "Standalone/standalone.h" @@ -86,38 +92,95 @@ #include "bwm_charger.h" // BWM charger / fuel-gauge + low-batt warning (WITH_BWM_*) #include "buzzer.h" // PM5 mainboard buzzer API #include "rgb_indicator.h" // PM5 antenna-RGB power/battery indicator (WITH_PM5_PWR_LED) +#include "pm5_power.h" // PM5 power-save idle (clock scaling + WFI) #ifdef WITH_PM5_AUTOOFF -// Automatic power-off on USB unplug. When the BWM keeps the PM5 alive on battery, -// users leave it draining. This powers the board down after USB has been absent -// continuously for a grace period, using the SAME latch release as the long-press -// shutdown (Gpio_ARM_Power_ON_Low). Button power-ON is a hardware function and is -// unaffected - once powered off there is no firmware running to interfere with it. -// -// Runtime toggle (default ON) via CMD_PM5_BWM_AUTOOFF; resets to default each boot. -// Standalone / BLE-relay users who run unplugged on purpose can disable it. +// Automatic power-off, through the same latch release as the long-press shutdown +// (Gpio_ARM_Power_ON_Low); button power-ON is hardware and unaffected. Two +// triggers: a USB unplug (g_autooff_unplug) and, opt-in, g_autooff_idle_ms idle +// on battery. Idle resets on a command, a button press or a client coming/going. +// The switch and both trigger settings are set over CMD_PM5_BWM_AUTOOFF, persisted +// on the BWM and reloaded at boot; without a module the defaults hold: on, unplug +// on, idle off. #ifndef PM5_AUTOOFF_POLL_MS -#define PM5_AUTOOFF_POLL_MS 250 // how often to sample VUSB +#define PM5_AUTOOFF_POLL_MS 250 // how often to sample VUSB and the link state +#endif +#ifndef PM5_AUTOOFF_IDLE_MS +#define PM5_AUTOOFF_IDLE_MS 0 // e.g. (5 * 60 * 1000) for 5 min #endif -bool g_autooff_enabled = true; // default on; toggled by CMD_PM5_BWM_AUTOOFF +bool g_autooff_enabled = true; // default on; CMD_PM5_BWM_AUTOOFF +uint32_t g_autooff_idle_ms = PM5_AUTOOFF_IDLE_MS; // 0 = no idle power-off +bool g_autooff_unplug = true; // power off when USB is pulled static bool s_autooff_setup = false; +static uint32_t s_autooff_activity_tick = 0; // last interaction, see above +static bool s_autooff_usb_seen = false; +static bool s_autooff_link = false; +static bool s_autooff_persisted = false; // setting loaded from / saved to the module -// Auto power-off on USB unplug. CRITICAL: only powers off on a USB-present -> absent -// TRANSITION - i.e. the board was running on USB and the cable was pulled. A board that -// booted on battery (button press, no USB) must NOT auto-off, or it could never be used -// unplugged at all (and the hw bwm autooff toggle would be unreachable, since setting it -// needs a client/USB). So we require having seen USB present at least once this session -// before an absent reading triggers shutdown. +void pm5_autooff_touch(void) { + s_autooff_activity_tick = GetTickCount(); +} + +void pm5_autooff_get_status(bwm_autooff_status_t *st) { + st->enabled = g_autooff_enabled ? 1 : 0; + st->idle_s = g_autooff_idle_ms / 1000; + st->idle_now_s = GetTickCountDelta(s_autooff_activity_tick) / 1000; + st->link = s_autooff_link ? 1 : 0; + st->ble_live = 0xFF; +#ifdef WITH_BWM_FORWARD + (void)bwm_esp_get_ble_state(&st->ble_live, 800); +#endif + st->usb = Gpio_VUSB_Read() ? 1 : 0; + st->usb_seen = s_autooff_usb_seen ? 1 : 0; + st->persisted = s_autooff_persisted ? 1 : 0; + st->unplug = g_autooff_unplug ? 1 : 0; +} + +// The setting lives on the BWM host value slots: the PM5 has no store of its own. +static void pm5_autooff_save(void) { +#ifdef WITH_BWM_FORWARD + // 1 s each: an NVS write is tens of ms, and three must still fit the client's wait. + s_autooff_persisted = (bwm_esp_host_value_set(BWM_HOSTVAL_AUTOOFF_ENABLED, g_autooff_enabled ? 1 : 0, 1000) == PM3_SUCCESS) && + (bwm_esp_host_value_set(BWM_HOSTVAL_AUTOOFF_IDLE_S, g_autooff_idle_ms / 1000, 1000) == PM3_SUCCESS) && + (bwm_esp_host_value_set(BWM_HOSTVAL_AUTOOFF_UNPLUG, g_autooff_unplug ? 1 : 0, 1000) == PM3_SUCCESS); +#endif +} + +static void pm5_autooff_load(void) { +#ifdef WITH_BWM_FORWARD + uint32_t v = 0; + int r = bwm_esp_host_value_get(BWM_HOSTVAL_AUTOOFF_ENABLED, &v, 300); + if (r == PM3_SUCCESS) { + g_autooff_enabled = (v != 0); + } + if (r == PM3_SUCCESS || r == PM3_ENODATA) { + s_autooff_persisted = true; // the module keeps the setting, stored or still default + if (bwm_esp_host_value_get(BWM_HOSTVAL_AUTOOFF_IDLE_S, &v, 300) == PM3_SUCCESS) { + g_autooff_idle_ms = MIN(v, BWM_AUTOOFF_IDLE_MAX_S) * 1000; + } + if (bwm_esp_host_value_get(BWM_HOSTVAL_AUTOOFF_UNPLUG, &v, 300) == PM3_SUCCESS) { + g_autooff_unplug = (v != 0); + } + } +#endif +} + +static void pm5_power_off(void) { + LEDsoff(); + Gpio_ARM_Power_ON_Low(); + while (1); // wait for hardware power-off (button press powers back on, in hardware) +} + +// CRITICAL: the unplug trigger fires only on a USB present -> absent TRANSITION. +// A board that booted on battery must not go off at once, or it could never be +// used unplugged (and the toggle would be unreachable): it gets the idle timer. static void bwm_autooff_check(void) { static uint32_t last_tick = 0; - static bool usb_was_present = false; // have we seen USB present since boot? + static bool usb_prev = false; // VUSB at the previous poll - if (g_autooff_enabled == false) { - return; - } if ((last_tick != 0) && (GetTickCountDelta(last_tick) < PM5_AUTOOFF_POLL_MS)) { return; } @@ -125,24 +188,94 @@ static void bwm_autooff_check(void) { if (s_autooff_setup == false) { gpio_vusb_setup(); + pm5_autooff_load(); +#ifdef WITH_BWM_FORWARD + // The ESP only broadcasts link changes: ask once for the state at boot + // (a BLE client can outlive an AT32 reset). Silence = no ESP or old fw. + uint8_t st = 0; + if (bwm_esp_get_ble_state(&st, 300) == PM3_SUCCESS) { + bwm_fwd_link_seed_ble(st == BWM_BLE_STATE_CONNECTED); + } +#endif + pm5_autooff_touch(); // the boot itself counts s_autooff_setup = true; } + if (g_autooff_enabled == false) { + usb_prev = Gpio_VUSB_Read(); // keep following VUSB: a re-enable on battery is not an unplug + return; + } - // Gpio_VUSB_Read() == true means USB power present. + bool link_up = false; +#ifdef WITH_BWM_FORWARD + link_up = bwm_fwd_link_connected(); +#endif + if (link_up != s_autooff_link) { + s_autooff_link = link_up; + pm5_autooff_touch(); // a client came or went: the idle clock restarts + } + + // Gpio_VUSB_Read() == true means USB power present: never power off. if (Gpio_VUSB_Read()) { - usb_was_present = true; // latch: USB has been present this session + s_autooff_usb_seen = true; // latch: USB has been present this session + usb_prev = true; return; } - // USB absent. Only power off if USB had previously been present (a real unplug). - // If it booted on battery and never saw USB, leave it running. - if (usb_was_present == false) { - return; + // USB absent after having been present: a real unplug. Off at once, or with + // the unplug trigger off, just restart the idle clock. + if (usb_prev) { + usb_prev = false; + if (g_autooff_unplug) { + pm5_power_off(); + } + pm5_autooff_touch(); } - LEDsoff(); - Gpio_ARM_Power_ON_Low(); - while (1); // wait for hardware power-off (button press powers back on, in hardware) + // On battery: off only after g_autooff_idle_ms with no interaction and no client. + if (g_autooff_idle_ms == 0) { + return; + } + if (GetTickCountDelta(s_autooff_activity_tick) < g_autooff_idle_ms) { + return; + } + if (link_up) { +#ifdef WITH_BWM_FORWARD + static uint32_t last_verify_tick = 0; + // The timer would fire but a client is (still) tracked: the broadcast + // that reported it leaving could have been lost, so ask the module, + // at most every 10 s. Only BLE can be asked; a WiFi client is trusted. + if ((last_verify_tick == 0) || (GetTickCountDelta(last_verify_tick) >= 10000)) { + last_verify_tick = GetTickCount(); + uint8_t st = 0; + if (bwm_esp_get_ble_state(&st, 300) == PM3_SUCCESS) { + bwm_fwd_link_seed_ble(st == BWM_BLE_STATE_CONNECTED); + } + } +#endif + return; // (a corrected flag is picked up on the next pass) + } +#ifdef WITH_BWM_FORWARD + // A client the module never reported (module firmware without LINK_STATE, or + // a lost broadcast): ask once before going off; no answer means off. + uint8_t ble = 0; + if ((bwm_esp_get_ble_state(&ble, 300) == PM3_SUCCESS) && (ble == BWM_BLE_STATE_CONNECTED)) { + bwm_fwd_link_seed_ble(true); + return; + } +#endif + pm5_power_off(); +} + +static void pm5_autooff_print_status(void) { + if (g_autooff_enabled == false) { + Dbprintf(" Auto power-off...... " _YELLOW_("off")); + } else if (g_autooff_idle_ms == 0) { + Dbprintf(" Auto power-off...... " _GREEN_("on") " (%s)", g_autooff_unplug ? "USB unplug only" : "no trigger set"); + } else if (g_autooff_unplug) { + Dbprintf(" Auto power-off...... " _GREEN_("on") " (USB unplug, or %u s idle on battery)", g_autooff_idle_ms / 1000); + } else { + Dbprintf(" Auto power-off...... " _GREEN_("on") " (%u s idle on battery, also after an unplug)", g_autooff_idle_ms / 1000); + } } #endif // WITH_PM5_AUTOOFF @@ -556,7 +689,7 @@ static void printConnSpeed(uint32_t wait) { Dbprintf(" Time elapsed................... %dms", delta_time); Dbprintf(" Bytes transferred.............. %d", bytes_transferred); - Dbprintf(" Frames sent.................... %d ( %d bytes on the wire each )", frames_sent, wire_len); + Dbprintf(" Frames sent.................... %d ( %d bytes )", frames_sent, wire_len); if (delta_time) { Dbprintf(" Transfer Speed PM3 -> Client... " _YELLOW_("%llu") " bytes/s", 1000 * (uint64_t)bytes_transferred / delta_time); Dbprintf(" Frame rate..................... " _YELLOW_("%llu") " frames/s", 1000 * (uint64_t)frames_sent / delta_time); @@ -593,15 +726,56 @@ static void SendStatus(uint32_t wait) { { // Read the ESP firmware version so hw status shows what the BWM runs // (and lets you confirm an OTA took: the string flips after a reflash). + // Keep the wait short: the client gives hw status about 2 s in total. One + // retry - a slow light-sleep wake eats the first frame but leaves the module up. uint8_t bwm_ver[64] = {0}; uint16_t bwm_ver_len = sizeof(bwm_ver) - 1; - if (bwm_esp_get_version(bwm_ver, &bwm_ver_len) == PM3_SUCCESS) { + int vres = bwm_esp_get_version(bwm_ver, &bwm_ver_len, 800); + if (vres == PM3_ETIMEOUT) { + bwm_ver_len = sizeof(bwm_ver) - 1; + vres = bwm_esp_get_version(bwm_ver, &bwm_ver_len, 800); + } + if (vres == PM3_SUCCESS) { bwm_ver[bwm_ver_len] = 0x00; Dbprintf(" BWM fw version...... " _YELLOW_("%s"), bwm_ver); + // Only once the ESP answered; older fw lacks these, so keep the wait short. + uint8_t ps = 0; + if (bwm_esp_get_power_save(&ps, 300) == PM3_SUCCESS) { + Dbprintf(" BWM power save...... " _YELLOW_("%s"), ps ? "on" : "off"); + } + uint8_t bs = 0; + if (bwm_esp_get_ble_state(&bs, 300) == PM3_SUCCESS) { + Dbprintf(" BWM BLE............. " _YELLOW_("%s"), (bs == BWM_BLE_STATE_CONNECTED) ? "client connected" : (bs == 1) ? "advertising" : "off"); + } + // Our cached copy of the ESP's LINK_STATE broadcasts (BLE or WiFi), which holds + // off the idle power-off. Debug only: it should agree with the live line above. + if (g_dbglevel >= DBG_DEBUG) { + Dbprintf(" BWM tracked client.. " _YELLOW_("%s"), bwm_fwd_link_connected() ? "connected (BLE or WiFi)" : "none"); + } } else { Dbprintf(" BWM fw version...... " _YELLOW_("%s"), "unknown"); } } + if (g_dbglevel >= DBG_DEBUG) { + // Flow-control diagnostics (since boot). Read before this reply is queued. + bwm_fc_stats_t fc; + bwm_fwd_fc_stats(&fc); + Dbprintf(" BWM fwd frames...... " _YELLOW_("%u") " sent, " _YELLOW_("%u") " acked, " _YELLOW_("%u") " errored", + fc.frames, fc.acks, fc.errors); + Dbprintf(" BWM fwd gate........ " _YELLOW_("%u") " timeouts, " _YELLOW_("%u") " forgotten, peak in flight " _YELLOW_("%u") " B", + fc.timeouts, fc.forgotten, fc.bytes_max); + Dbprintf(" BWM fwd now......... " _YELLOW_("%u") " frames / " _YELLOW_("%u") " B in flight", + fc.in_flight_frames, fc.in_flight_bytes); + } +#endif +#ifdef PM5 + pm5_power_print_status(); +#endif +#ifdef WITH_PM5_AUTOOFF + pm5_autooff_print_status(); +#endif +#ifdef WITH_CEP + Dbprintf(" CEP (Flipper) link.. " _YELLOW_("%s"), cep_is_active() ? "attached" : "not attached"); #endif printConnSpeed(wait); DbpString(_CYAN_("Various")); @@ -712,6 +886,8 @@ static void SendCapabilities(void) { capabilities.via_fpc = g_reply_via_fpc; capabilities.via_usb = g_reply_via_usb; capabilities.bigbuf_size = BigBuf_get_size(); + capabilities.em_size = BigBuf_get_EM_size(); + capabilities.em_allocated = BigBuf_is_EM_allocated(); capabilities.baudrate = 0; // no real baudrate for USB-CDC #ifdef WITH_FPC_USART if (g_reply_via_fpc) @@ -795,6 +971,16 @@ static void SendCapabilities(void) { #else capabilities.compiled_with_hitag = false; #endif +#if defined(WITH_BWM_STATUS) || defined(WITH_BWM_FORWARD) + capabilities.compiled_with_bwm = true; +#else + capabilities.compiled_with_bwm = false; +#endif +#ifdef WITH_CEP + capabilities.compiled_with_cep = true; +#else + capabilities.compiled_with_cep = false; +#endif #ifdef WITH_EM4x50 capabilities.compiled_with_em4x50 = true; #else @@ -1294,6 +1480,17 @@ static int reply_download_chunk(uint16_t cmd, uint32_t offset, const uint8_t *da return reply_ng(cmd, PM3_SUCCESS, buf, sizeof(download_chunk_t) + len); } +#ifdef WITH_FLASH +// CMD_SPIFFS_DOWNLOAD streams the file out chunk by chunk, this is the sink +static int spiffs_download_chunk(uint32_t offset, const uint8_t *data, uint16_t len) { + int res = reply_download_chunk(CMD_SPIFFS_DOWNLOADED, offset, data, len); + if (res != PM3_SUCCESS) { + Dbprintf("transfer to client failed :: | bytes between %u - %u (%u) | result: %d", offset, offset + len, len, res); + } + return res; +} +#endif + static void reply_download_done(uint16_t cmd, uint32_t bytes_sent, uint32_t extra) { download_done_t done = { .bytes_sent = bytes_sent, @@ -1814,11 +2011,13 @@ static void PacketReceived(PacketCommandNG *packet) { } case CMD_LF_EM4X50_SIM: { //----------------------------------------------------------------------------- - // Note: we call FpgaDownloadAndGo(FPGA_BITSTREAM_LF) here although FPGA is not - // involved in dealing with emulator memory. But if it is called later, it might - // destroy the Emulator Memory. + // The FPGA is not involved in dealing with emulator memory, but loading a + // bitstream later would wipe it, so the load is brought forward to here. + // It has to be the _keep_EM variant: FpgaDownloadAndGo() frees and clears + // the whole of BigBuf to make room to decompress, emulator memory included, + // which is the very thing this is here to preserve. //----------------------------------------------------------------------------- - FpgaDownloadAndGo(FPGA_BITSTREAM_LF); + FpgaDownloadAndGo_keep_EM(FPGA_BITSTREAM_LF); em4x50_sim((const uint32_t *)packet->data.asBytes, true); break; } @@ -1828,11 +2027,13 @@ static void PacketReceived(PacketCommandNG *packet) { } case CMD_LF_EM4X50_ESET: { //----------------------------------------------------------------------------- - // Note: we call FpgaDownloadAndGo(FPGA_BITSTREAM_LF) here although FPGA is not - // involved in dealing with emulator memory. But if it is called later, it might - // destroy the Emulator Memory. + // The FPGA is not involved in dealing with emulator memory, but loading a + // bitstream later would wipe it, so the load is brought forward to here. + // It has to be the _keep_EM variant: FpgaDownloadAndGo() frees and clears + // the whole of BigBuf to make room to decompress, emulator memory included, + // which is the very thing this is here to preserve. //----------------------------------------------------------------------------- - FpgaDownloadAndGo(FPGA_BITSTREAM_LF); + FpgaDownloadAndGo_keep_EM(FPGA_BITSTREAM_LF); if (packet->length < sizeof(em4x50_eset_t)) { reply_ng(CMD_LF_EM4X50_ESET, PM3_EINVARG, NULL, 0); @@ -1945,11 +2146,13 @@ static void PacketReceived(PacketCommandNG *packet) { } case CMD_HF_ISO15693_EML_SETMEM: { //----------------------------------------------------------------------------- - // Note: we call FpgaDownloadAndGo(FPGA_BITSTREAM_HF_15) here although FPGA is not - // involved in dealing with emulator memory. But if it is called later, it might - // destroy the Emulator Memory. + // The FPGA is not involved in dealing with emulator memory, but loading a + // bitstream later would wipe it, so the load is brought forward to here. + // It has to be the _keep_EM variant: FpgaDownloadAndGo() frees and clears + // the whole of BigBuf to make room to decompress, emulator memory included, + // which is the very thing this is here to preserve. //----------------------------------------------------------------------------- - FpgaDownloadAndGo(FPGA_BITSTREAM_HF_15); + FpgaDownloadAndGo_keep_EM(FPGA_BITSTREAM_HF_15); struct p { uint32_t offset; uint16_t count; @@ -1960,7 +2163,8 @@ static void PacketReceived(PacketCommandNG *packet) { break; } case CMD_HF_ISO15693_EML_GETMEM: { - FpgaDownloadAndGo(FPGA_BITSTREAM_HF_15); + // keep the Emulator Memory, we are about to read it back + FpgaDownloadAndGo_keep_EM(FPGA_BITSTREAM_HF_15); struct p { uint32_t offset; uint16_t length; @@ -1973,6 +2177,10 @@ static void PacketReceived(PacketCommandNG *packet) { } uint8_t *buf = BigBuf_calloc(payload->length); + if (buf == NULL) { + reply_ng(CMD_HF_ISO15693_EML_GETMEM, PM3_EMALLOC, NULL, 0); + return; + } emlGet(buf, payload->offset, payload->length); LED_B_ON(); reply_ng(CMD_HF_ISO15693_EML_GETMEM, PM3_SUCCESS, buf, payload->length); @@ -2005,6 +2213,18 @@ static void PacketReceived(PacketCommandNG *packet) { SetTag15693Uid_v2(payload->uid); break; } + case CMD_HF_ISO15693_CSETUID_V3: { + struct p { + uint8_t uid[8]; + } PACKED; + struct p *payload = (struct p *) packet->data.asBytes; + SetTag15693Uid_v3(payload->uid); + break; + } + case CMD_HF_ISO15693_CFINALIZE_V3: { + FinalizeTag15693_v3(); + break; + } case CMD_HF_ISO15693_SLIX_DISABLE_EAS: { struct p { uint8_t pwd[4]; @@ -2116,12 +2336,14 @@ static void PacketReceived(PacketCommandNG *packet) { break; } case CMD_HF_LEGIC_ESET: { - //----------------------------------------------------------------------------- - // Note: we call FpgaDownloadAndGo(FPGA_BITSTREAM_HF) here although FPGA is not - // involved in dealing with emulator memory. But if it is called later, it might - // destroy the Emulator Memory. - //----------------------------------------------------------------------------- - FpgaDownloadAndGo(FPGA_BITSTREAM_HF); + // No FPGA work here on purpose. An upload arrives as a burst of + // back-to-back packets, and a bitstream download in the first one takes + // long enough that the device stops servicing USB and the packets behind + // it are lost -- `hf legic eload` after a command that left a different + // bitstream loaded used to write only its first 619 bytes. + // init_tag() in legicrfsim.c loads the bitstream when the simulation + // actually starts, and does it with the _keep_EM variant so the content + // uploaded here survives. legic_packet_t *payload = (legic_packet_t *) packet->data.asBytes; emlSet(payload->data, payload->offset, payload->len); break; @@ -2337,9 +2559,12 @@ static void PacketReceived(PacketCommandNG *packet) { case CMD_HF_ISO14443A_ANTIFUZZ: { struct p { uint8_t flag; + uint8_t mode; } PACKED; struct p *payload = (struct p *) packet->data.asBytes; - iso14443a_antifuzz(payload->flag); + // older clients only send the flag byte + uint8_t mode = (packet->length >= sizeof(struct p)) ? payload->mode : ANTIFUZZ_MODE_CASCADE; + iso14443a_antifuzz(payload->flag, mode); break; } // EPA related @@ -2519,16 +2744,29 @@ static void PacketReceived(PacketCommandNG *packet) { Mifare1ksim(payload->flags, payload->exitAfter, payload->uid, payload->atqa, payload->sak); break; } +#ifdef WITH_DESFIRE_SIM + case CMD_HF_DESFIRE_SIMULATE: { + SimulateDesfireTag(); + break; + } +#ifdef ENABLE_HFMFDESETEST + case CMD_HF_DESFIRE_SIM_TEST: { + DesfireSimTest(packet); + break; + } +#endif +#endif case CMD_HF_MIFARE_EML_MEMCLR: { //----------------------------------------------------------------------------- // Work with emulator memory // - // Note: we call FpgaDownloadAndGo(FPGA_BITSTREAM_HF) here although FPGA is not - // involved in dealing with emulator memory. But if it is called later, it might - // destroy the Emulator Memory. + // The FPGA is not involved here, but loading a bitstream later would wipe + // emulator memory, so the load is brought forward. _keep_EM because + // FpgaDownloadAndGo() frees and clears all of BigBuf to decompress into, + // which would drop the allocation emlClearMem() is about to fill in. //----------------------------------------------------------------------------- - FpgaDownloadAndGo(FPGA_BITSTREAM_HF); + FpgaDownloadAndGo_keep_EM(FPGA_BITSTREAM_HF); // Not only clears the emulator memory, // also sets default MIFARE values for sector trailers. @@ -2537,13 +2775,21 @@ static void PacketReceived(PacketCommandNG *packet) { break; } case CMD_HF_MIFARE_EML_MEMSET: { - FpgaDownloadAndGo(FPGA_BITSTREAM_HF); + // keep the Emulator Memory, a partial update must not wipe the rest of it + FpgaDownloadAndGo_keep_EM(FPGA_BITSTREAM_HF); struct p { uint16_t blockno; uint8_t blockcnt; uint8_t blockwidth; + uint8_t flags; uint8_t data[]; } PACKED; + + if (packet->length < sizeof(struct p)) { + reply_ng(CMD_HF_MIFARE_EML_MEMSET, PM3_EINVARG, NULL, 0); + break; + } + struct p *payload = (struct p *) packet->data.asBytes; // backwards compat... default bytewidth @@ -2551,12 +2797,19 @@ static void PacketReceived(PacketCommandNG *packet) { payload->blockwidth = MIFARE_BLOCK_SIZE; } + // a whole-dump upload zeroes what was there first, so a smaller dump can't + // leave a tail behind that reads back as card data. esetblk never sets this. + if (payload->flags & MFEMUL_MEMSET_CLEAR) { + BigBuf_Clear_EM(); + } + emlSetMem_xt(payload->data, payload->blockno, payload->blockcnt, payload->blockwidth); break; } case CMD_HF_MIFARE_EML_MEMGET: { - FpgaDownloadAndGo(FPGA_BITSTREAM_HF); + // keep the Emulator Memory, we are about to read it back + FpgaDownloadAndGo_keep_EM(FPGA_BITSTREAM_HF); struct p { uint16_t blockno; uint8_t blockcnt; @@ -2572,6 +2825,10 @@ static void PacketReceived(PacketCommandNG *packet) { } uint8_t *buf = BigBuf_calloc(size); + if (buf == NULL) { + reply_ng(CMD_HF_MIFARE_EML_MEMGET, PM3_EMALLOC, NULL, 0); + return; + } emlGetMem_xt(buf, payload->blockno, payload->blockcnt, payload->blockwidth); // data, block num, blocks count (max 4) @@ -2606,12 +2863,11 @@ static void PacketReceived(PacketCommandNG *packet) { break; } case CMD_HF_MIFARE_CIDENT: { - struct p { - uint8_t is_mfc; - uint8_t keytype; - uint8_t key[6]; - } PACKED; - struct p *payload = (struct p *) packet->data.asBytes; + if (packet->length < sizeof(mf_chinese_ident_t)) { + reply_ng(CMD_HF_MIFARE_CIDENT, PM3_EINVARG, NULL, 0); + break; + } + mf_chinese_ident_t *payload = (mf_chinese_ident_t *)packet->data.asBytes; MifareCIdent(payload->is_mfc, payload->keytype, payload->key); break; } @@ -2780,6 +3036,11 @@ static void PacketReceived(PacketCommandNG *packet) { SimulateThinFilm(packet->data.asBytes, packet->length); break; } + case CMD_HF_THINFILM_SNIFF: { + int res = SniffThinFilm(); + reply_ng(CMD_HF_THINFILM_SNIFF, res, NULL, 0); + break; + } #endif #ifdef WITH_ICLASS @@ -3015,6 +3276,12 @@ static void PacketReceived(PacketCommandNG *packet) { uint16_t available; uint16_t pre_available = 0; uint8_t *dest = BigBuf_calloc(USART_FIFOLEN); + if (dest == NULL) { + if (g_dbglevel >= DBG_DEBUG) Dbprintf("Failed to allocate memory"); + reply_ng(CMD_USART_RX, PM3_EMALLOC, NULL, 0); + LED_B_OFF(); + break; + } uint32_t wait = payload->waittime; StartTicks(); @@ -3059,6 +3326,12 @@ static void PacketReceived(PacketCommandNG *packet) { uint16_t available; uint16_t pre_available = 0; uint8_t *dest = BigBuf_calloc(USART_FIFOLEN); + if (dest == NULL) { + if (g_dbglevel >= DBG_DEBUG) Dbprintf("Failed to allocate memory"); + reply_ng(CMD_USART_TXRX, PM3_EMALLOC, NULL, 0); + LED_B_OFF(); + break; + } uint32_t wait = payload->waittime; StartTicks(); @@ -3264,10 +3537,33 @@ static void PacketReceived(PacketCommandNG *packet) { if (packet->length < sizeof(download_req_t)) { break; } + + if (mem == NULL) { + reply_download_done(CMD_DOWNLOAD_EML_BIGBUF, 0, 0); + LED_B_OFF(); + break; + } + const download_req_t *dreq = (const download_req_t *)packet->data.asBytes; uint32_t startidx = dreq->start_index; uint32_t numofbytes = dreq->bytes; + // We report the emulator memory size in capabilities_t, so honour it + // here as well. Without this a client asking for more than the + // emulator holds reads on past it into the rest of BigBuf + uint32_t em_size = BigBuf_get_EM_size(); + if (startidx >= em_size) { + Dbprintf("Emulator memory download starts past the end, %u >= %u", startidx, em_size); + reply_download_done(CMD_DOWNLOAD_EML_BIGBUF, 0, 0); + LED_B_OFF(); + break; + } + + if (startidx + numofbytes > em_size) { + Dbprintf("Emulator memory is %u bytes, truncating download of %u to %u", em_size, numofbytes, em_size - startidx); + numofbytes = em_size - startidx; + } + // arg0 = startindex // arg1 = length bytes to transfer // arg2 = RFU @@ -3369,40 +3665,42 @@ static void PacketReceived(PacketCommandNG *packet) { } case CMD_SPIFFS_DOWNLOAD: { LED_B_ON(); - uint8_t filename[32]; if (packet->length < sizeof(download_req_t)) { reply_ng(CMD_SPIFFS_DOWNLOAD, PM3_EINVARG, NULL, 0); + LED_B_OFF(); break; } + + // a client can fill the name field, keep room for the terminator + char filename[SPIFFS_OBJ_NAME_LEN] = {0}; const download_req_t *dreq = (const download_req_t *)packet->data.asBytes; - uint16_t fnlen = MIN((uint16_t)(packet->length - sizeof(download_req_t)), (uint16_t)SPIFFS_OBJ_NAME_LEN); + uint16_t fnlen = MIN((uint16_t)(packet->length - sizeof(download_req_t)), (uint16_t)(SPIFFS_OBJ_NAME_LEN - 1)); memcpy(filename, dreq->data, fnlen); if (g_dbglevel >= DBG_DEBUG) Dbprintf("Filename received for spiffs dump : %s", filename); - uint32_t size = dreq->bytes; - - uint8_t *buff = BigBuf_calloc(size); - if (buff == NULL) { + // a file can be bigger than BigBuf, so it is streamed out one frame at a + // time. Reading it into BigBuf first used to wrap at 64KB, back when + // BigBuf_calloc() took a uint16_t, and read the whole file into the + // short buffer that produced + const uint16_t dl_chunk = reply_ng_max_data_size() - sizeof(download_chunk_t); + uint8_t *chunkbuf = BigBuf_calloc(dl_chunk); + if (chunkbuf == NULL) { if (g_dbglevel >= DBG_DEBUG) Dbprintf("Failed to allocate memory"); // Trigger a finish downloading signal with an PM3_EMALLOC reply_ng(CMD_SPIFFS_DOWNLOAD, PM3_EMALLOC, NULL, 0); - } else { - rdv40_spiffs_read_as_filetype((char *)filename, (uint8_t *)buff, size, RDV40_SPIFFS_SAFETY_SAFE); - // arg0 = filename - // arg1 = size - // arg2 = RFU - - const size_t dl_chunk = reply_ng_max_data_size() - sizeof(download_chunk_t); - for (size_t i = 0; i < size; i += dl_chunk) { - size_t len = MIN((size - i), dl_chunk); - int result = reply_download_chunk(CMD_SPIFFS_DOWNLOADED, i, buff + i, len); - if (result != PM3_SUCCESS) - Dbprintf("transfer to client failed :: | bytes between %d - %d (%d) | result: %d", i, i + len, len, result); - } - // Trigger a finish downloading signal with an ACK frame - reply_ng(CMD_SPIFFS_DOWNLOAD, PM3_SUCCESS, NULL, 0); - BigBuf_free(); + LED_B_OFF(); + break; } + + int res = rdv40_spiffs_read_stream(filename, dreq->start_index, dreq->bytes, chunkbuf, dl_chunk, spiffs_download_chunk, RDV40_SPIFFS_SAFETY_SAFE); + if (res < 0) { + reply_ng(CMD_SPIFFS_DOWNLOAD, res, NULL, 0); + } else { + // Trigger a finish downloading signal with an ACK frame + reply_download_done(CMD_SPIFFS_DOWNLOAD, (uint32_t)res, 0); + } + + BigBuf_free(); LED_B_OFF(); break; } @@ -3479,6 +3777,7 @@ static void PacketReceived(PacketCommandNG *packet) { Dbprintf("Destination... %s", payload->dest); } rdv40_spiffs_copy((char *)payload->src, (char *)payload->dest, RDV40_SPIFFS_SAFETY_SAFE); + BigBuf_free(); reply_ng(CMD_SPIFFS_COPY, PM3_SUCCESS, NULL, 0); LED_B_OFF(); break; @@ -3486,8 +3785,22 @@ static void PacketReceived(PacketCommandNG *packet) { case CMD_SPIFFS_WRITE: { LED_B_ON(); + if (packet->length < sizeof(flashmem_write_t)) { + reply_ng(CMD_SPIFFS_WRITE, PM3_EINVARG, NULL, 0); + LED_B_OFF(); + break; + } + flashmem_write_t *payload = (flashmem_write_t *)packet->data.asBytes; + // the packet size follows the negotiated frame, so do not take the + // client's word for how much data is in it + if (payload->bytes_in_packet > (packet->length - sizeof(flashmem_write_t))) { + reply_ng(CMD_SPIFFS_WRITE, PM3_EINVARG, NULL, 0); + LED_B_OFF(); + break; + } + if (g_dbglevel >= DBG_DEBUG) { Dbprintf("SPIFFS WRITE, dest `%s` with APPEND set to: %c", payload->fn, payload->append ? 'Y' : 'N'); } @@ -3498,7 +3811,10 @@ static void PacketReceived(PacketCommandNG *packet) { rdv40_spiffs_write((char *) payload->fn, payload->data, payload->bytes_in_packet, RDV40_SPIFFS_SAFETY_SAFE); } - reply_ng(CMD_SPIFFS_WRITE, PM3_SUCCESS, NULL, 0); + // tell the client whether the bytes actually landed. The SPIFFS errno + // rides along so it can name the reason, ie: -10001 filesystem full + int32_t res = rdv40_spiffs_write_status(); + reply_ng(CMD_SPIFFS_WRITE, (res == SPIFFS_OK) ? PM3_SUCCESS : PM3_EFLASH, (uint8_t *)&res, sizeof(res)); LED_B_OFF(); break; } @@ -3529,6 +3845,10 @@ static void PacketReceived(PacketCommandNG *packet) { break; } + // a dump smaller than the emulator memory must not leave the tail of a + // previous one behind + BigBuf_Clear_EM(); + rdv40_spiffs_read_as_filetype(fn, em, size, RDV40_SPIFFS_SAFETY_SAFE); reply_ng(CMD_SPIFFS_ELOAD, PM3_SUCCESS, NULL, 0); LED_B_OFF(); @@ -3596,6 +3916,13 @@ static void PacketReceived(PacketCommandNG *packet) { LED_B_ON(); uint8_t *mem = BigBuf_calloc(PM3_CMD_DATA_SIZE); + if (mem == NULL) { + if (g_dbglevel >= DBG_DEBUG) Dbprintf("Failed to allocate memory"); + reply_ng(CMD_FLASHMEM_DOWNLOAD, PM3_EMALLOC, NULL, 0); + LED_B_OFF(); + break; + } + if (packet->length < sizeof(download_req_t)) { break; } @@ -3636,6 +3963,12 @@ static void PacketReceived(PacketCommandNG *packet) { LED_B_ON(); rdv40_validation_t *info = (rdv40_validation_t *)BigBuf_calloc(sizeof(rdv40_validation_t)); + if (info == NULL) { + if (g_dbglevel >= DBG_DEBUG) Dbprintf("Failed to allocate memory"); + reply_ng(CMD_FLASHMEM_GET_SIGNATURE, PM3_EMALLOC, NULL, 0); + LED_B_OFF(); + break; + } // returns 0 when failing uint16_t isok = Flash_ReadData(FLASH_MEM_SIGNATURE_OFFSET_P(spi_flash_pages64k), info->signature, FLASH_MEM_SIGNATURE_LEN); @@ -3765,6 +4098,20 @@ static void PacketReceived(PacketCommandNG *packet) { SendCapabilities(); break; } + case CMD_CEP_STATUS: { + cep_status_t status = {0}; +#ifdef WITH_CEP + status.cep_active = cep_is_active(); +#endif +#ifdef WITH_BWM_STATUS + bwm_read_battery_info(&status.battery); +#endif + if (CheckValidInformationMagic(&g_version_information)) { + strncpy(status.fw_version, g_version_information.gitversion, sizeof(status.fw_version) - 1); + } + reply_ng(CMD_CEP_STATUS, PM3_SUCCESS, (uint8_t *)&status, sizeof(status)); + break; + } case CMD_PING: { reply_ng(CMD_PING, PM3_SUCCESS, packet->data.asBytes, packet->length); break; @@ -4015,7 +4362,8 @@ static void PacketReceived(PacketCommandNG *packet) { res = bwm_wifi_forward_status(&state, &ip); uint8_t st[5] = { state, (uint8_t)(ip & 0xFF), (uint8_t)((ip >> 8) & 0xFF), - (uint8_t)((ip >> 16) & 0xFF), (uint8_t)((ip >> 24) & 0xFF) }; + (uint8_t)((ip >> 16) & 0xFF), (uint8_t)((ip >> 24) & 0xFF) + }; reply_ng(CMD_PM5_BWM_WIFI, res, st, sizeof(st)); } else { uint16_t port = packet->data.asBytes[1] | (packet->data.asBytes[2] << 8); @@ -4047,7 +4395,7 @@ static void PacketReceived(PacketCommandNG *packet) { // ack is lost). Replies here with a payload, unlike the others. uint8_t ver[64]; uint16_t vlen = sizeof(ver); - res = bwm_esp_get_version(ver, &vlen); + res = bwm_esp_get_version(ver, &vlen, 3000); reply_ng(CMD_PM5_BWM_ESP_OTA, res, ver, (res == PM3_SUCCESS) ? vlen : 0); replied = true; break; @@ -4093,22 +4441,208 @@ static void PacketReceived(PacketCommandNG *packet) { } #else reply_ng(CMD_PM5_BWM_ESP_OTA, PM3_ENOTIMPL, NULL, 0); +#endif + break; + } + case CMD_PM5_BWM_BLE_NAME: { +#ifdef WITH_BWM_FORWARD + // Payload: [action:u8][name bytes if SET]. GET replies with the current + // BLE device name string. SET stores it on the ESP (persisted to NVS) and + // then reboots the ESP so the new advertising name takes effect - the ESP + // only applies the name at BLE startup, and rebooting is easier for users + // than a physical power-cycle. + if (packet->length < 1) { + reply_ng(CMD_PM5_BWM_BLE_NAME, PM3_EINVARG, NULL, 0); + break; + } + uint8_t action = packet->data.asBytes[0]; + if (action == BWM_BLE_NAME_ACTION_GET) { + uint8_t name[BWM_BLE_NAME_MAX_LEN + 1] = {0}; + uint16_t nlen = sizeof(name); + int res = bwm_esp_get_ble_name(name, &nlen); + reply_ng(CMD_PM5_BWM_BLE_NAME, res, name, (res == PM3_SUCCESS) ? nlen : 0); + } else if (action == BWM_BLE_NAME_ACTION_SET) { + uint16_t nlen = packet->length - 1; + if (nlen == 0 || nlen > BWM_BLE_NAME_MAX_LEN) { + reply_ng(CMD_PM5_BWM_BLE_NAME, PM3_EINVARG, NULL, 0); + break; + } + int res = bwm_esp_set_ble_name(packet->data.asBytes + 1, nlen); + if (res == PM3_SUCCESS) { + // Best-effort: the name is already saved to NVS, so even if the + // reboot ack is lost it applies on the next BLE startup anyway. + (void)bwm_esp_reboot(); + } + reply_ng(CMD_PM5_BWM_BLE_NAME, res, NULL, 0); + } else { + reply_ng(CMD_PM5_BWM_BLE_NAME, PM3_EINVARG, NULL, 0); + } +#else + reply_ng(CMD_PM5_BWM_BLE_NAME, PM3_ENOTIMPL, NULL, 0); +#endif + break; + } + case CMD_PM5_BWM_POWERSAVE: { +#ifdef WITH_BWM_FORWARD + // Payload / reply layout: pm3_cmd.h. The ESP persists it; nothing kept here. + if (packet->length < 1) { + reply_ng(CMD_PM5_BWM_POWERSAVE, PM3_EINVARG, NULL, 0); + break; + } + uint8_t action = packet->data.asBytes[0]; + uint8_t state = 0; + int res; + if (action == BWM_POWERSAVE_ACTION_GET) { + res = bwm_esp_get_power_save(&state, 3000); + } else if (action == BWM_POWERSAVE_ACTION_SET && packet->length >= 2) { + res = bwm_esp_set_power_save(packet->data.asBytes[1] != 0, &state); + } else { + reply_ng(CMD_PM5_BWM_POWERSAVE, PM3_EINVARG, NULL, 0); + break; + } + reply_ng(CMD_PM5_BWM_POWERSAVE, res, &state, (res == PM3_SUCCESS) ? 1 : 0); +#else + reply_ng(CMD_PM5_BWM_POWERSAVE, PM3_ENOTIMPL, NULL, 0); +#endif + break; + } + case CMD_PM5_BWM_BLE: { +#ifdef WITH_BWM_FORWARD + // BLE settings on the module: one action, then a full status snapshot back. + if (packet->length < 1) { + reply_ng(CMD_PM5_BWM_BLE, PM3_EINVARG, NULL, 0); + break; + } + uint8_t action = packet->data.asBytes[0]; + const uint8_t *arg = &packet->data.asBytes[1]; + uint16_t alen = packet->length - 1; + int res = PM3_SUCCESS; + bool restart = false; // a bonding change applies at the next stack start + switch (action) { + case BWM_BLE_ACTION_STATUS: + break; + case BWM_BLE_ACTION_ENABLE: { + uint8_t stored = 0; + res = (alen >= 1) ? bwm_esp_set_ble_enable(arg[0] != 0, &stored) : PM3_EINVARG; + break; + } + case BWM_BLE_ACTION_PAIRING: + res = (alen >= 1) ? bwm_esp_set_ble_bonding(arg[0] != 0) : PM3_EINVARG; + restart = (res == PM3_SUCCESS); + break; + case BWM_BLE_ACTION_KEY: + res = (alen >= 6) ? bwm_esp_set_ble_key(arg) : PM3_EINVARG; + break; + case BWM_BLE_ACTION_FORGET: + res = (alen >= 1) ? bwm_esp_ble_forget(arg[0]) : PM3_EINVARG; + break; + case BWM_BLE_ACTION_TXPOWER: + res = (alen >= 2) ? bwm_esp_set_ble_txpower(arg[0], arg[1]) : PM3_EINVARG; + break; + default: + res = PM3_EINVARG; + break; + } + if (res != PM3_SUCCESS) { + reply_ng(CMD_PM5_BWM_BLE, res, NULL, 0); + break; + } + bwm_ble_status_t st; + res = bwm_esp_ble_status(&st); + if (res != PM3_SUCCESS) { + reply_ng(CMD_PM5_BWM_BLE, res, NULL, 0); + if (restart) { + (void)bwm_esp_ble_restart(); + } + break; + } + reply_ng(CMD_PM5_BWM_BLE, PM3_SUCCESS, (uint8_t *)&st, sizeof(st)); + if (restart) { + // Reply first: over BLE the restart drops the client's own link. + SpinDelay(500); + (void)bwm_esp_ble_restart(); + } +#else + reply_ng(CMD_PM5_BWM_BLE, PM3_ENOTIMPL, NULL, 0); +#endif + break; + } + case CMD_PM5_BWM_WIFI_PS: { +#ifdef WITH_BWM_FORWARD + // Payload / reply layout: pm3_cmd.h. wifi_state rides along so the host + // can say the type is moot while WiFi is down. + if (packet->length < 1) { + reply_ng(CMD_PM5_BWM_WIFI_PS, PM3_EINVARG, NULL, 0); + break; + } + uint8_t action = packet->data.asBytes[0]; + uint8_t out[2] = { 0, BWM_WIFI_STATE_OFF }; + int res; + if (action == BWM_WIFI_PS_ACTION_GET) { + res = bwm_esp_get_wifi_ps(&out[0]); + } else if (action == BWM_WIFI_PS_ACTION_SET && packet->length >= 2 && packet->data.asBytes[1] <= BWM_WIFI_PS_MAX) { + res = bwm_esp_set_wifi_ps(packet->data.asBytes[1], &out[0]); + } else { + reply_ng(CMD_PM5_BWM_WIFI_PS, PM3_EINVARG, NULL, 0); + break; + } + if (res == PM3_SUCCESS) { + uint32_t ip = 0; + (void)bwm_wifi_forward_status(&out[1], &ip); // 0xFF when the WiFi stack is down + } + reply_ng(CMD_PM5_BWM_WIFI_PS, res, out, (res == PM3_SUCCESS) ? sizeof(out) : 0); +#else + reply_ng(CMD_PM5_BWM_WIFI_PS, PM3_ENOTIMPL, NULL, 0); #endif break; } case CMD_PM5_BWM_AUTOOFF: { - // Toggle automatic power-off on USB unplug (runtime, default on). - // Payload: 1 byte, non-zero = enable (default), zero = disable. + // Automatic power-off switch + idle timeout. Layouts: pm3_cmd.h. #ifdef WITH_PM5_AUTOOFF - g_autooff_enabled = (packet->length >= 1) ? (packet->data.asBytes[0] != 0) : true; - reply_ng(CMD_PM5_BWM_AUTOOFF, PM3_SUCCESS, (uint8_t *)&g_autooff_enabled, 1); + if (packet->length == 1) { + // old client: enable flag only + g_autooff_enabled = (packet->data.asBytes[0] != 0); + pm5_autooff_touch(); + pm5_autooff_save(); + } else if ((packet->length >= 6) && (packet->data.asBytes[0] == BWM_AUTOOFF_ACTION_SET)) { + uint8_t en = packet->data.asBytes[1]; + uint32_t idle_s; + memcpy(&idle_s, &packet->data.asBytes[2], sizeof(idle_s)); + if (en != BWM_AUTOOFF_KEEP_U8) { + g_autooff_enabled = (en != 0); + } + if (idle_s != BWM_AUTOOFF_KEEP_U32) { + g_autooff_idle_ms = MIN(idle_s, BWM_AUTOOFF_IDLE_MAX_S) * 1000; + } + if ((packet->length >= 7) && (packet->data.asBytes[6] != BWM_AUTOOFF_KEEP_U8)) { + g_autooff_unplug = (packet->data.asBytes[6] != 0); + } + pm5_autooff_touch(); // a new timeout counts from now + pm5_autooff_save(); + } + bwm_autooff_status_t reply; + pm5_autooff_get_status(&reply); + reply_ng(CMD_PM5_BWM_AUTOOFF, PM3_SUCCESS, (uint8_t *)&reply, sizeof(reply)); #else reply_ng(CMD_PM5_BWM_AUTOOFF, PM3_ENOTIMPL, NULL, 0); #endif break; } -#endif -#endif + case CMD_PM5_BWM_GET_BATTERY: { + bwm_battery_info_t info; + bwm_read_battery_info(&info); + reply_ng(CMD_PM5_BWM_GET_BATTERY, PM3_SUCCESS, (uint8_t *)&info, sizeof(info)); + break; + } +#endif // WITH_BWM_STATUS + case CMD_PM5_POWERSAVE: { + // Payload: 1 byte, non-zero = enable (the default), zero = disable. + pm5_power_set_enabled((packet->length >= 1) ? (packet->data.asBytes[0] != 0) : true); + uint8_t state = pm5_power_get_enabled() ? 1 : 0; + reply_ng(CMD_PM5_POWERSAVE, PM3_SUCCESS, &state, 1); + break; + } +#endif // PM5 default: { Dbprintf("%s: 0x%04x", "unknown command:", packet->cmd); break; @@ -4193,12 +4727,23 @@ void __attribute__((noreturn)) AppMain(void) { // Negotiate the link up from the boot baud; harmless no-op if the ESP is // older or the target is unreachable (stays at BWM_UART_BAUD). bwm_fwd_negotiate_baud(BWM_UART_BAUD_TARGET); + // The ESP only light-sleeps once it has seen a preamble, and ours went out + // while it was still booting if both powered up together: send it again. + bwm_uart_wake_next(); #endif #ifdef WITH_BWM_CHARGERKICK bwm_charger_kick(); #endif +#ifdef PM5 + pm5_power_init(); +#endif + +#ifdef WITH_CEP + cep_init(); // USART1/SPI1 + CC-controller I2C bring-up; AFTER usb_enable() +#endif + for (;;) { WDT_HIT(); @@ -4211,6 +4756,9 @@ void __attribute__((noreturn)) AppMain(void) { #ifdef WITH_BWM_LOWBATT_BEEP bwm_lowbatt_check(); #endif +#ifdef WITH_CEP + cep_attach_poll(); +#endif if (*_stack_start != 0xdeadbeef) { Dbprintf("DEBUG: increase stack size, currently " _YELLOW_("%d") " bytes", (uint32_t)_stack_end - (uint32_t)_stack_start); @@ -4220,13 +4768,22 @@ void __attribute__((noreturn)) AppMain(void) { while (1); } - // Check if there is a packet available + // Check if there is a packet available. receive_ng() zeroes the + // payload itself, once it knows a packet is actually arriving. PacketCommandNG rx; - memset(&rx.data, 0, sizeof(rx.data)); int ret = receive_ng(&rx); if (ret == PM3_SUCCESS) { +#ifdef PM5 + pm5_power_boost(); // commands assume the full 288 MHz clock +#endif PacketReceived(&rx); +#ifdef PM5 + pm5_power_unboost(); +#endif +#ifdef WITH_PM5_AUTOOFF + pm5_autooff_touch(); // a command, over any transport +#endif last_activity_label = GetTickCountLabel(); last_activity_tick = GetTickCount(); } else if (ret != PM3_ENODATA) { @@ -4247,6 +4804,11 @@ void __attribute__((noreturn)) AppMain(void) { // Press button for one second to enter a possible standalone mode button_status = BUTTON_HELD(1000); +#ifdef WITH_PM5_AUTOOFF + if (button_status != BUTTON_NO_CLICK) { + pm5_autooff_touch(); // any press is an interaction + } +#endif if (button_status == BUTTON_HOLD) { /* * So this is the trigger to execute a standalone mod. Generic entrypoint by following the standalone/standalone.h headerfile @@ -4315,5 +4877,20 @@ void __attribute__((noreturn)) AppMain(void) { #endif } + +#ifdef PM5 + // WFI sleep adds ~40-50ms of latency before the main loop notices a + // fresh byte on CEP's SPI1 - fine at idle, but it's what made the + // original attach handshake miss bytes (see cep_attach_poll()'s own + // comment on the attach-edge bug this caused, GH #3667). Skip the + // sleep entirely while a Flipper is attached so the loop polls as + // fast as the hardware allows; cep_is_attached() drops back to false + // within CEP_ACTIVITY_TIMEOUT_MS of the FAP going away, so this + // isn't a permanent always-on cost. +#ifdef WITH_CEP + if (!cep_is_attached()) +#endif + pm5_power_idle(); +#endif } } diff --git a/armsrc/bwm_charger.c b/armsrc/bwm_charger.c index c592b3cf4..fad827e2b 100644 --- a/armsrc/bwm_charger.c +++ b/armsrc/bwm_charger.c @@ -27,6 +27,7 @@ #include "i2c.h" #include "dbprint.h" #include "ticks_apis.h" // WaitMS / GetTickCount / GetTickCountDelta +#include "pm5_power.h" // pm5_power_boost / unboost around the low-batt poll #include "ansi.h" #ifdef WITH_BWM_LOWBATT_BEEP @@ -194,35 +195,31 @@ void bwm_print_battery_status(void) { } } - // --- fuel gauge (BQ27427) --- - uint16_t soc = 0, mv = 0, rem = 0, temp = 0, raw_i = 0; - if (bwm_gauge_read16(BWM_GAUGE_SOC, &soc) && bwm_gauge_read16(BWM_GAUGE_VOLTAGE, &mv)) { - bwm_gauge_read16(BWM_GAUGE_REMCAP, &rem); - bwm_gauge_read16(BWM_GAUGE_TEMP, &temp); - bwm_gauge_read16(BWM_GAUGE_CURRENT, &raw_i); - - int16_t cur = (int16_t)raw_i; // +charge / -discharge (verify polarity on hw) - int tempC10 = (int)temp - 2732; // 0.1 K -> 0.1 C - int tabs = (tempC10 < 0) ? -tempC10 : tempC10; - - Dbprintf(" Battery SoC......... %u %%", soc); - Dbprintf(" Battery voltage..... %u mV", mv); - Dbprintf(" Battery current..... %d mA %s", cur, - (cur > 5) ? _GREEN_("(charging)") : - (cur < -5) ? _YELLOW_("(discharging)") : "(idle)"); - Dbprintf(" Remaining capacity.. %u mAh", rem); + // --- fuel gauge (BQ27427) --- shared with bwm_read_battery_info() below, + // so the numbers hw status prints and CMD_PM5_BWM_GET_BATTERY returns + // can't drift apart. + bwm_battery_info_t info; + bwm_read_battery_info(&info); + if (info.gauge_ok) { + Dbprintf(" Battery SoC......... %u %%", info.soc_pct); + Dbprintf(" Battery voltage..... %u mV", info.voltage_mv); + Dbprintf(" Battery current..... %d mA %s", info.current_ma, + (info.current_ma > 5) ? _GREEN_("(charging)") : + (info.current_ma < -5) ? _YELLOW_("(discharging)") : "(idle)"); + Dbprintf(" Remaining capacity.. %u mAh", info.remaining_mah); // Measured drain / projected runtime: when running on battery the gauge // Current is negative (discharging); |cur| is the real system draw, so // remaining runtime ~= RemainingCapacity / draw. Only meaningful while // discharging - on charge or idle there is no drain figure to report. // (Projection is only as good as RemCap - provision Design Capacity first.) - if (cur < -5) { - uint16_t draw = (uint16_t)(-cur); // mA drawn from the battery - uint32_t mins = ((uint32_t)rem * 60) / draw; // RemCap/draw -> hours, *60 -> mins + if (info.current_ma < -5) { + uint16_t draw = (uint16_t)(-info.current_ma); // mA drawn from the battery + uint32_t mins = ((uint32_t)info.remaining_mah * 60) / draw; // RemCap/draw -> hours, *60 -> mins Dbprintf(" Battery drain....... %u mA (approx %u h %u min left)", draw, (unsigned)(mins / 60), (unsigned)(mins % 60)); } - Dbprintf(" Temp (gauge)........ %d.%d C", tempC10 / 10, tabs % 10); + int tabs = (info.temp_c10 < 0) ? -info.temp_c10 : info.temp_c10; + Dbprintf(" Temp (gauge)........ %d.%d C", info.temp_c10 / 10, tabs % 10); // Battery health: FullChargeCapacity (0x0E) vs the gauge's programmed Design // Capacity. FCC is the gauge's learned present full capacity; health = FCC/design. @@ -230,20 +227,66 @@ void bwm_print_battery_status(void) { // (a full charge/discharge). Before that it is an unconverged estimate. If Design // Capacity was never provisioned (hw bwm setcap), the ratio is against the gauge // default, not the fitted cell - so it can read wildly wrong. - uint16_t fcc = 0, design = 0; - if (bwm_gauge_read16(BWM_GAUGE_FCC, &fcc) && fcc > 0) { - if (bq_read_design_cap(&design) == false || design == 0) { - design = BWM_DEFAULT_DESIGN_CAP_MAH; // fall back to the fitted-cell rating - } - unsigned health = (unsigned)(((uint32_t)fcc * 100) / design); - Dbprintf(" Full charge cap..... %u mAh (design %u)", fcc, design); - Dbprintf(" Battery health...... %u", health); + if (info.full_charge_mah > 0) { + Dbprintf(" Full charge cap..... %u mAh (design %u)", info.full_charge_mah, info.design_cap_mah); + Dbprintf(" Battery health...... %u", info.health_pct); } } else { Dbprintf(" Fuel gauge.......... " _YELLOW_("not responding") " (BQ27427 absent or I2C down)"); } } +// See bwm_charger.h. Shares the fuel-gauge reads with bwm_print_battery_status() +// above; only adds two small charger-side reads (fault, charge status) that +// print doesn't already source from elsewhere. +bool bwm_read_battery_info(bwm_battery_info_t *out) { + bwm_battery_info_t info = {0}; + info.bwm_present = g_bwm_present; + + if (g_bwm_present) { + StartTicks(); + I2C_init(true); + WaitMS(2); // let the bus settle + + // Charger fault (REG09): read-on-clear, latched history on the 1st read, + // live state on the 2nd - see bwm_print_battery_status()'s fuller comment. + uint8_t f1 = 0, fault = 0, sysstat = 0; + I2C_BufferReadRaw(&f1, 1, BWM_CHG_REG_FAULT, BWM_CHG_ADDR); + if (I2C_BufferReadRaw(&fault, 1, BWM_CHG_REG_FAULT, BWM_CHG_ADDR) > 0) { + info.charger_fault = fault & 0x3F; + } + if (I2C_BufferReadRaw(&sysstat, 1, BWM_CHG_REG_SYSSTAT, BWM_CHG_ADDR) > 0) { + info.charge_status = (sysstat >> 3) & 0x03; + } + + uint16_t soc = 0, mv = 0, rem = 0, temp = 0, raw_i = 0; + info.gauge_ok = bwm_gauge_read16(BWM_GAUGE_SOC, &soc) && bwm_gauge_read16(BWM_GAUGE_VOLTAGE, &mv); + if (info.gauge_ok) { + bwm_gauge_read16(BWM_GAUGE_REMCAP, &rem); + bwm_gauge_read16(BWM_GAUGE_TEMP, &temp); + bwm_gauge_read16(BWM_GAUGE_CURRENT, &raw_i); + info.soc_pct = soc; + info.voltage_mv = mv; + info.current_ma = (int16_t)raw_i; + info.remaining_mah = rem; + info.temp_c10 = (int16_t)((int)temp - 2732); // 0.1 K -> 0.1 C + + uint16_t fcc = 0, design = 0; + if (bwm_gauge_read16(BWM_GAUGE_FCC, &fcc) && fcc > 0) { + if (bq_read_design_cap(&design) == false || design == 0) { + design = BWM_DEFAULT_DESIGN_CAP_MAH; + } + info.full_charge_mah = fcc; + info.design_cap_mah = design; + info.health_pct = (uint8_t)(((uint32_t)fcc * 100) / design); + } + } + } + + *out = info; + return g_bwm_present; +} + // --- BQ27427 provisioning: set Design Capacity for the fitted cell ------------- // One-time. The gauge ships with a ~1000+ mAh default profile, so RemainingCapacity // reads wrong for the fitted pack until Design Capacity is programmed. Invoked by the @@ -470,18 +513,12 @@ static void bwm_beep_low_batt(void) { // charging or if the BWM/gauge is not present. With WITH_PM5_LOWBATT_SHUTDOWN it // also powers the board off once the pack drops to the critical floor, confirmed // across several consecutive polls so a transient HF-field sag can't trip it. -void bwm_lowbatt_check(void) { - static uint32_t last_tick = 0; +static void bwm_lowbatt_poll(void) { #ifdef WITH_PM5_LOWBATT_SHUTDOWN static uint8_t crit = 0; static bool s_vusb_setup = false; #endif - if ((last_tick != 0) && (GetTickCountDelta(last_tick) < BWM_LOWBATT_PERIOD_MS)) { - return; - } - last_tick = GetTickCount(); - StartTicks(); I2C_init(true); @@ -539,4 +576,18 @@ void bwm_lowbatt_check(void) { bwm_beep_low_batt(); // BuzzerBeep() lazily sets the buzzer up on first use } + +void bwm_lowbatt_check(void) { + static uint32_t last_tick = 0; + + if ((last_tick != 0) && (GetTickCountDelta(last_tick) < BWM_LOWBATT_PERIOD_MS)) { + return; + } + last_tick = GetTickCount(); + + // Ticks timer, I2C and buzzer timing assume the full core clock. + pm5_power_boost(); + bwm_lowbatt_poll(); + pm5_power_unboost(); +} #endif // WITH_BWM_LOWBATT_BEEP diff --git a/armsrc/bwm_charger.h b/armsrc/bwm_charger.h index 0d4de3b1a..171f0a0a4 100644 --- a/armsrc/bwm_charger.h +++ b/armsrc/bwm_charger.h @@ -28,6 +28,7 @@ #define __BWM_CHARGER_H #include "common.h" +#include "pm3_cmd.h" // bwm_battery_info_t // Reference design capacity for the fitted cell (VXE 502540, 500 mAh / 3.7 V). // Used as the default target for `hw bwm setcap` and as the fall-back divisor for @@ -51,6 +52,13 @@ void bwm_detect_and_init(void); // detected by bwm_detect_and_init(). void bwm_print_battery_status(void); +// Fills in bwm_battery_info_t (pm3_cmd.h) for CMD_PM5_BWM_GET_BATTERY - same +// underlying reads as bwm_print_battery_status(), so the two can't drift on +// the numbers they share. Returns false (all fields zeroed) if no BWM was +// detected. A false gauge_ok with bwm_present true means the charger ACKed +// but the fuel gauge didn't. +bool bwm_read_battery_info(bwm_battery_info_t *out); + // One-time BQ27427 Design Capacity provisioning (CMD_PM5_BWM_SET_CAP / // `hw bwm setcap`). Idempotent - returns true without a CFGUPDATE cycle if the // value is already correct. Assumes the gauge is UNSEALED (factory default). diff --git a/armsrc/bwm_forward.c b/armsrc/bwm_forward.c index b7eaf6445..2470cd281 100644 --- a/armsrc/bwm_forward.c +++ b/armsrc/bwm_forward.c @@ -22,22 +22,6 @@ #define MIN(a, b) (((a) < (b)) ? (a) : (b)) #endif -// CRC-16/CCITT-FALSE, byte-identical to the BWM firmware's crc16_ccitt() -// (poly 0x1021, init 0xFFFF, MSB-first, no reflection, no xorout). -static uint16_t bwm_crc16(const uint8_t *data, size_t len, uint16_t crc) { - for (size_t i = 0; i < len; i++) { - crc ^= (uint16_t)data[i] << 8; - for (uint8_t b = 0; b < 8; b++) { - if (crc & 0x8000) { - crc = (uint16_t)((crc << 1) ^ BWM_CRC16_POLY); - } else { - crc = (uint16_t)(crc << 1); - } - } - } - return crc; -} - // --------------------------------------------------------------------------- // TX: wrap one reply frame into a SEND_FORWARD_DATA app_com frame. // A full NG/OLD frame is <= PM3_CMD_DATA_SIZE + a small header/postamble, well @@ -49,19 +33,78 @@ static uint16_t bwm_crc16(const uint8_t *data, size_t len, uint16_t crc) { static void bwm_pump(void); // fwd decl: TX gate pumps RX to collect forward-frame acks -// --- Flow control (ack window) --------------------------------------------- -// s_fwd_inflight: forward frames sent but not yet acked by the ESP. Bumped on -// send, decremented when a SLAVE_RESP echoing cmd=SEND_FORWARD_DATA arrives. -// We may send while it is below BWM_FC_WINDOW; at the cap we wait for an ack. -static volatile int16_t s_fwd_inflight = 0; +// --- Flow control (byte window) -------------------------------------------- +// Forward frames sent but not yet acked by the ESP: their lengths, oldest +// first (acks arrive in order), and their sum. Bumped on every forward frame, +// popped by the parser on the ESP's SLAVE_RESP. See BWM_FC_BYTES. +static volatile uint16_t s_fc_len[BWM_FC_MAX_FRAMES]; +static volatile uint8_t s_fc_head = 0; +static volatile uint8_t s_fc_count = 0; +static volatile uint32_t s_fc_bytes = 0; +static bwm_fc_stats_t s_fc_stats; // diagnostics since boot, see bwm_fwd_fc_stats() -// Set true by the parser when a SLAVE_RESP echoing BWM_CMD_SET_UART_BAUD arrives -// (the ESP's ack for a baud-set request). Consumed by bwm_fwd_negotiate_baud(). -static volatile bool s_baud_ack = false; +static void fc_reset(void) { + s_fc_head = 0; + s_fc_count = 0; + s_fc_bytes = 0; +} -// Set true by the parser on a SLAVE_RESP for BWM_CMD_GET_UART_BAUD - proof the -// ESP is alive and responding at the baud we just switched to (verify step). -static volatile bool s_getbaud_ack = false; +static void fc_push(uint16_t len) { + s_fc_stats.frames++; + s_fc_len[(uint8_t)((s_fc_head + s_fc_count) % BWM_FC_MAX_FRAMES)] = len; + s_fc_count++; + s_fc_bytes += len; + if (s_fc_bytes > s_fc_stats.bytes_max) { + s_fc_stats.bytes_max = s_fc_bytes; + } +} + +// Release the oldest frame: its ack (or CMD_ERROR) came, or the gate gave up on +// it. Acks are not matched to frames, so an ack that was eaten elsewhere (bwm_cmd() +// drains the ring, see #3648) or one that comes after the gate forgot its frame +// just shifts the window by one frame: the gate is one frame too pessimistic or +// too optimistic until the window drains, and drains it does after every command. +static void fc_pop(void) { + if (s_fc_count == 0) { + return; + } + s_fc_bytes -= s_fc_len[s_fc_head]; + s_fc_head = (uint8_t)((s_fc_head + 1) % BWM_FC_MAX_FRAMES); + s_fc_count--; +} + +void bwm_fwd_fc_stats(bwm_fc_stats_t *out) { + *out = s_fc_stats; + out->in_flight_frames = s_fc_count; + out->in_flight_bytes = s_fc_bytes; +} + +// Last LINK_STATE broadcast from the ESP: a client on BLE / on the TCP server. +static volatile uint8_t s_link_ble = 0; +static volatile uint8_t s_link_wifi = 0; + +bool bwm_fwd_link_connected(void) { + return (s_link_ble != 0) || (s_link_wifi != 0); +} + +void bwm_fwd_link_seed_ble(bool connected) { + s_link_ble = connected ? 1 : 0; +} + +void bwm_fwd_on_frame_ack(void) { + s_fc_stats.acks++; + fc_pop(); +} + +void bwm_fwd_on_frame_error(void) { + s_fc_stats.errors++; + fc_pop(); +} + +void bwm_fwd_on_link_state(uint8_t ble, uint8_t wifi) { + s_link_ble = ble; + s_link_wifi = wifi; +} int bwm_fwd_writebuffer_sync(const uint8_t *data, size_t len) { static uint8_t frame[BWM_TX_BUFSZ]; // single-threaded bare-metal: static OK @@ -70,199 +113,38 @@ int bwm_fwd_writebuffer_sync(const uint8_t *data, size_t len) { len = BWM_TX_MAX_PAYLOAD; // defensive; should never trigger } - size_t idx = 0; - // Flow control: block while the in-flight window is full, waiting for the - // ESP to ack an earlier forward frame. bwm_pump() drains the IRQ-filled RX - // ring, so acks are collected even while we sit inside a tight download loop - // (the reply_old firehose). The spin cap is a safety valve so a dead or - // disconnected ESP can't hard-hang us. A window >= 1 means single command - // replies never block - only sustained bursts hit the cap. + // Flow control: block while this frame would not fit the in-flight byte budget + // (or the length FIFO is full). bwm_pump() drains the IRQ-filled RX ring, so + // acks land even inside a tight download loop (the reply_old firehose). The + // time cap is a safety valve so a dead or disconnected ESP can't hard-hang us. { uint32_t t0 = GetTickCount(); - while (s_fwd_inflight >= BWM_FC_WINDOW) { + uint32_t need = (uint32_t)len + BWM_TX_OVERHEAD; + while ((s_fc_count >= BWM_FC_MAX_FRAMES) || (s_fc_bytes + need > BWM_FC_BYTES)) { bwm_pump(); if (GetTickCountDelta(t0) > BWM_FC_ACK_TIMEOUT_MS) { - s_fwd_inflight = 0; // best-effort: assume the pipe cleared, never hard-hang + s_fc_stats.timeouts++; + // Never hard-hang: make room for this frame only, so a stalled ESP + // gets one frame per timeout on top of its ring, not a second window. + while (s_fc_count && ((s_fc_count >= BWM_FC_MAX_FRAMES) || (s_fc_bytes + need > BWM_FC_BYTES))) { + fc_pop(); + s_fc_stats.forgotten++; + } break; } } } - frame[idx++] = BWM_HDR_HOST_CMD_1; - frame[idx++] = BWM_HDR_HOST_CMD_2; - frame[idx++] = (uint8_t)(BWM_CMD_SEND_FORWARD_DATA & 0xFF); - frame[idx++] = (uint8_t)((BWM_CMD_SEND_FORWARD_DATA >> 8) & 0xFF); - frame[idx++] = (uint8_t)(len & 0xFF); - frame[idx++] = (uint8_t)((len >> 8) & 0xFF); - if (len) { - memcpy(&frame[idx], data, len); - idx += len; + size_t n = bwm_frame_build(BWM_CMD_SEND_FORWARD_DATA, data, (uint16_t)len, + frame, sizeof(frame)); + if (n == 0) { + return PM3_EOVFLOW; } - uint16_t crc = bwm_crc16(frame, idx, BWM_CRC16_INIT); - frame[idx++] = (uint8_t)(crc & 0xFF); - frame[idx++] = (uint8_t)((crc >> 8) & 0xFF); - - int wr = bwm_uart_write(frame, idx); - s_fwd_inflight++; // one more forward frame awaiting its ack + int wr = bwm_uart_write(frame, n); + fc_push((uint16_t)n); // one more forward frame awaiting its ack return wr; } -// --------------------------------------------------------------------------- -// RX: persistent app_com de-framer. Feeds raw FPC bytes through a state machine -// and pushes the payloads of valid DATA_FORWARD (0xD2 0xD3 / cmd 8089) frames -// into a byte FIFO that bwm_read_ng() drains. Non-DATA_FORWARD frames (slave -// responses, forwarded logs, cmd-error reports) are validated and discarded. -// --------------------------------------------------------------------------- -#define BWM_DEFIFO_SZ 2048 // >= one full NG frame's payload -#define BWM_RXFRAME_MAX (PM3_CMD_DATA_SIZE + 64) - -typedef enum { - S_IDLE = 0, S_HDR2, S_CMD_LO, S_CMD_HI, S_LEN_LO, S_LEN_HI, S_PAYLOAD, S_CRC_LO, S_CRC_HI -} bwm_state_t; - -typedef struct { - bwm_state_t state; - uint8_t hdr1; - bool is_bcast; // header pair is 0xD2 0xD3 - uint16_t cmd; - uint16_t len; - uint16_t got; // payload bytes received - uint16_t crc_calc; // running CRC over hdr..payload - uint16_t crc_recv; - uint8_t payload[BWM_RXFRAME_MAX]; -} bwm_parser_t; - -static bwm_parser_t s_p = { .state = S_IDLE }; - -// De-framed payload ring -static uint8_t s_fifo[BWM_DEFIFO_SZ]; -static volatile uint16_t s_fifo_head = 0; // write -static volatile uint16_t s_fifo_tail = 0; // read - -static uint16_t fifo_count(void) { - return (uint16_t)((s_fifo_head - s_fifo_tail) & (BWM_DEFIFO_SZ - 1)); -} -static void fifo_push(uint8_t b) { - uint16_t next = (uint16_t)((s_fifo_head + 1) & (BWM_DEFIFO_SZ - 1)); - if (next != s_fifo_tail) { // drop on overflow rather than corrupt - s_fifo[s_fifo_head] = b; - s_fifo_head = next; - } -} -static uint8_t fifo_pop(void) { - uint8_t b = s_fifo[s_fifo_tail]; - s_fifo_tail = (uint16_t)((s_fifo_tail + 1) & (BWM_DEFIFO_SZ - 1)); - return b; -} - -static void bwm_reset_frame(bwm_parser_t *p) { - p->state = S_IDLE; -} - -// Update running CRC one byte at a time (mirrors the streaming update in the -// BWM firmware parser). -static void crc_step(bwm_parser_t *p, uint8_t byte) { - p->crc_calc = bwm_crc16(&byte, 1, p->crc_calc); -} - -static void bwm_feed_byte(bwm_parser_t *p, uint8_t byte) { - switch (p->state) { - case S_IDLE: - if (byte == BWM_HDR_SLAVE_BCAST_1) { - p->hdr1 = byte; - p->is_bcast = true; - p->state = S_HDR2; - } else if (byte == BWM_HDR_SLAVE_RESP_1) { - p->hdr1 = byte; - p->is_bcast = false; - p->state = S_HDR2; - } - // any other byte: stay idle (resync) - break; - - case S_HDR2: { - bool ok = (p->is_bcast && byte == BWM_HDR_SLAVE_BCAST_2) || - (!p->is_bcast && byte == BWM_HDR_SLAVE_RESP_2); - if (!ok) { - // header mismatch: reset and re-examine this byte as a potential SOF - p->state = S_IDLE; - bwm_feed_byte(p, byte); - return; - } - uint8_t hdr[2] = { p->hdr1, byte }; - p->crc_calc = bwm_crc16(hdr, 2, BWM_CRC16_INIT); - p->state = S_CMD_LO; - break; - } - - case S_CMD_LO: - p->cmd = byte; - crc_step(p, byte); - p->state = S_CMD_HI; - break; - case S_CMD_HI: - p->cmd |= (uint16_t)byte << 8; - crc_step(p, byte); - p->state = S_LEN_LO; - break; - case S_LEN_LO: - p->len = byte; - crc_step(p, byte); - p->state = S_LEN_HI; - break; - case S_LEN_HI: - p->len |= (uint16_t)byte << 8; - crc_step(p, byte); - p->got = 0; - if (p->len > BWM_RXFRAME_MAX) { // oversized -> drop frame - bwm_reset_frame(p); - } else { - p->state = (p->len == 0) ? S_CRC_LO : S_PAYLOAD; - } - break; - - case S_PAYLOAD: - p->payload[p->got++] = byte; - crc_step(p, byte); - if (p->got >= p->len) { - p->state = S_CRC_LO; - } - break; - - case S_CRC_LO: - p->crc_recv = byte; - p->state = S_CRC_HI; - break; - case S_CRC_HI: - p->crc_recv |= (uint16_t)byte << 8; - if (p->crc_recv == p->crc_calc) { - if (p->is_bcast && p->cmd == BWM_CMD_DATA_FORWARD) { - for (uint16_t i = 0; i < p->len; i++) { - fifo_push(p->payload[i]); - } - } else if ((p->is_bcast == false) && p->cmd == BWM_CMD_SEND_FORWARD_DATA) { - // SLAVE_RESP ack for a forward frame -> one slot freed - if (s_fwd_inflight > 0) { - s_fwd_inflight--; - } - } else if ((p->is_bcast == false) && p->cmd == BWM_CMD_SET_UART_BAUD) { - // SLAVE_RESP ack for a baud-set request (see negotiate below) - s_baud_ack = true; - } else if ((p->is_bcast == false) && p->cmd == BWM_CMD_GET_UART_BAUD) { - // SLAVE_RESP for our GET_BAUD verify probe - s_getbaud_ack = true; - } - } - // valid non-DATA_FORWARD frames and CRC failures alike: just resync - bwm_reset_frame(p); - break; - - default: - bwm_reset_frame(p); - break; - } -} - // Pull whatever raw framed bytes are waiting and run them through the parser. static void bwm_pump(void) { uint8_t scratch[64]; @@ -273,20 +155,20 @@ static void bwm_pump(void) { break; } for (uint32_t i = 0; i < n; i++) { - bwm_feed_byte(&s_p, scratch[i]); + bwm_frame_feed(scratch[i]); } avail = bwm_uart_rx_available(); } } uint16_t bwm_fwd_rxdata_available(void) { - if (fifo_count() > 0) { - return fifo_count(); + if (bwm_fifo_count() > 0) { + return bwm_fifo_count(); } // No de-framed payload yet, but raw frame bytes may be waiting; pump once so // receive_ng()'s gate reflects real forward data. bwm_pump(); - return fifo_count(); + return bwm_fifo_count(); } uint32_t bwm_read_ng(uint8_t *data, size_t len) { @@ -305,16 +187,16 @@ uint32_t bwm_read_ng(uint8_t *data, size_t len) { uint32_t out = 0; uint32_t try = 0; while (out < len) { - while (out < len && fifo_count() > 0) { - data[out++] = fifo_pop(); + while (out < len && bwm_fifo_count() > 0) { + data[out++] = bwm_fifo_pop(); try = 0; } if (out >= len) { break; } - uint16_t before = fifo_count(); + uint16_t before = bwm_fifo_count(); bwm_pump(); - if (fifo_count() != before) { + if (bwm_fifo_count() != before) { try = 0; continue; } @@ -325,7 +207,6 @@ uint32_t bwm_read_ng(uint8_t *data, size_t len) { return out; } - // --------------------------------------------------------------------------- // Runtime baud negotiation. // The ESP boots at BWM_UART_BAUD and accepts a HOST_CMD (cmd 1011) carrying a @@ -348,26 +229,15 @@ uint32_t bwm_read_ng(uint8_t *data, size_t len) { // i.e. it really is running at the baud we just switched to. Retried by the // caller so a single lost probe on a good link does not force a needless revert. static bool bwm_verify_baud(void) { - uint8_t f[2 + 2 + 2 + 2]; - size_t i = 0; - f[i++] = BWM_HDR_HOST_CMD_1; - f[i++] = BWM_HDR_HOST_CMD_2; - f[i++] = (uint8_t)(BWM_CMD_GET_UART_BAUD & 0xFF); - f[i++] = (uint8_t)((BWM_CMD_GET_UART_BAUD >> 8) & 0xFF); - f[i++] = 0; - f[i++] = 0; - uint16_t crc = bwm_crc16(f, i, BWM_CRC16_INIT); - f[i++] = (uint8_t)(crc & 0xFF); - f[i++] = (uint8_t)((crc >> 8) & 0xFF); - - s_getbaud_ack = false; - s_p.state = S_IDLE; - bwm_uart_write(f, i); + uint8_t f[8]; + size_t n = bwm_frame_build(BWM_CMD_GET_UART_BAUD, NULL, 0, f, sizeof(f)); + bwm_frame_clear_getbaud_ack(); + bwm_uart_write(f, n); uint32_t t0 = GetTickCount(); while (GetTickCountDelta(t0) < BWM_BAUD_VERIFY_MS) { bwm_pump(); - if (s_getbaud_ack) { + if (bwm_frame_getbaud_ack()) { return true; } } @@ -388,10 +258,8 @@ static bool bwm_probe_at(uint32_t baud, int tries) { // Reset framer, FIFO and flow control after a baud change. static void bwm_link_reset(void) { - s_p.state = S_IDLE; - s_fifo_head = 0; - s_fifo_tail = 0; - s_fwd_inflight = 0; + bwm_frame_reset(); + fc_reset(); } bool bwm_fwd_negotiate_baud(uint32_t target) { @@ -420,30 +288,21 @@ bool bwm_fwd_negotiate_baud(uint32_t target) { } // Build the SET_UART_BAUD host-command frame once (payload = u32 LE baud). - uint8_t frame[2 + 2 + 2 + 4 + 2]; - size_t idx = 0; - frame[idx++] = BWM_HDR_HOST_CMD_1; - frame[idx++] = BWM_HDR_HOST_CMD_2; - frame[idx++] = (uint8_t)(BWM_CMD_SET_UART_BAUD & 0xFF); - frame[idx++] = (uint8_t)((BWM_CMD_SET_UART_BAUD >> 8) & 0xFF); - frame[idx++] = (uint8_t)(4 & 0xFF); - frame[idx++] = (uint8_t)((4 >> 8) & 0xFF); - frame[idx++] = (uint8_t)(target & 0xFF); - frame[idx++] = (uint8_t)((target >> 8) & 0xFF); - frame[idx++] = (uint8_t)((target >> 16) & 0xFF); - frame[idx++] = (uint8_t)((target >> 24) & 0xFF); - uint16_t crc = bwm_crc16(frame, idx, BWM_CRC16_INIT); - frame[idx++] = (uint8_t)(crc & 0xFF); - frame[idx++] = (uint8_t)((crc >> 8) & 0xFF); + uint8_t payload[4]; + payload[0] = (uint8_t)(target & 0xFF); + payload[1] = (uint8_t)((target >> 8) & 0xFF); + payload[2] = (uint8_t)((target >> 16) & 0xFF); + payload[3] = (uint8_t)((target >> 24) & 0xFF); + uint8_t frame[12]; + size_t idx = bwm_frame_build(BWM_CMD_SET_UART_BAUD, payload, 4, frame, sizeof(frame)); for (int attempt = 0; attempt < BWM_BAUD_ATTEMPTS; attempt++) { - s_baud_ack = false; - s_p.state = S_IDLE; // drop any half-frame before we listen + bwm_frame_clear_baud_ack(); bwm_uart_write(frame, idx); for (int ms = 0; ms < BWM_BAUD_ACK_WAIT_MS; ms++) { bwm_pump(); // parser sets s_baud_ack on the SLAVE_RESP - if (s_baud_ack) { + if (bwm_frame_baud_ack()) { // ESP acked and is switching; verify it before trusting the // new baud, else fall back so both ends stay in sync. bool verified = bwm_probe_at(target, BWM_BAUD_VERIFY_TRIES); diff --git a/armsrc/bwm_forward.h b/armsrc/bwm_forward.h index 8d8e0515c..ba562e56a 100644 --- a/armsrc/bwm_forward.h +++ b/armsrc/bwm_forward.h @@ -10,20 +10,6 @@ //----------------------------------------------------------------------------- // Proxmark5 Battery Wireless Module (BWM) transport shim. // -// The BWM (ESP32-C2, RfidResearchGroup/Proxmark5_BWM_esp32) bridges the AT32 -// host <-> BLE/WiFi. Its ESP<->AT32 UART link does NOT carry raw PacketCommandNG; -// it uses a framed "app_com" protocol. Transparent host<->wireless traffic rides -// inside that framing: -// -// AT32 -> ESP (our reply, toward wireless host): -// [0x7C 0xC7] cmd=APP_CMD_SEND_FORWARD_DATA(5000) len(LE) payload CRC16(LE) -// ESP -> AT32 (command from wireless host): -// [0xD2 0xD3] cmd=APP_BROADCAST_DATA_FORWARD(8089) len(LE) payload CRC16(LE) -// -// Frame = HDR1 HDR2 | CMD(LE16) | LEN(LE16) | PAYLOAD[LEN] | CRC(LE16) -// CRC = CRC-16/CCITT-FALSE (poly 0x1021, init 0xFFFF, MSB-first, no xorout) -// over HDR..PAYLOAD. (NOT compute_crc(CRC_14443_A) - different CRC.) -// // This shim wraps outgoing NG/OLD reply bytes into a SEND_FORWARD_DATA frame and // de-frames incoming DATA_FORWARD frames back into a raw NG byte stream, so the // stock reply_ng()/receive_ng() paths work unchanged over the BWM link. @@ -35,49 +21,33 @@ #define __BWM_FORWARD_H #include "common.h" +#include "bwm_frame.h" -// app_com framing constants (verified against BWM firmware app_cmd_uart.[ch] / -// app_com_defs.h). -#define BWM_HDR_HOST_CMD_1 0x7C // AT32 -> ESP (host command) -#define BWM_HDR_HOST_CMD_2 0xC7 -#define BWM_HDR_SLAVE_BCAST_1 0xD2 // ESP -> AT32 (slave broadcast) -#define BWM_HDR_SLAVE_BCAST_2 0xD3 -#define BWM_HDR_SLAVE_RESP_1 0x2D // ESP -> AT32 (slave response; forward-frame ack) -#define BWM_HDR_SLAVE_RESP_2 0x3D - -#define BWM_CMD_SEND_FORWARD_DATA 5000 // host cmd: payload -> BLE/WiFi endpoint -#define BWM_CMD_DATA_FORWARD 8089 // slave bcast: payload came from endpoint -// System command: set the ESP<->AT32 UART baud (app_com_defs.h, enum @1000). -// SET is a HOST_CMD carrying u32 LE baud; the ESP replies with a SLAVE_RESP -// echoing this cmd (len 0) at the OLD baud, then commits to the new baud. -#define BWM_CMD_SET_UART_BAUD 1011 -#define BWM_CMD_GET_UART_BAUD 1009 // read back the ESP's live baud (negotiation verify) -// Flow control (ack window) - ARM-side only, no BWM firmware change required. -// The ESP already replies to every forward frame with a SLAVE_RESP echoing -// cmd=SEND_FORWARD_DATA, and it sends that ack only *after* app_ble_send() has -// drained the frame to BLE. So the un-acked count is a live measure of how far -// ahead of the wireless link we are. We allow up to BWM_FC_WINDOW frames in -// flight, then block for an ack before sending more - which paces us to the real -// BLE/WiFi rate and prevents the ESP UART-RX overrun that dropped bulk downloads. -// WINDOW frames must fit the ESP UART RX FIFO + wireless send buffer. -// Ceiling on un-acked forward frames. On a download the ESP acks steadily so -// this never bites; it only matters on a bidirectional UPLOAD, where the ESP -// defers the small acks while forwarding large incoming chunks. A tight value -// (4) let inflight hit the cap and stall the AT32 past the client timeout, so -// keep enough headroom to ride out delayed acks. Only ~1 response is ever -// really in flight during an upload, so this does not risk an ESP overrun. -#define BWM_FC_WINDOW 16 // max un-acked forward frames in flight +// Flow control (byte window). The ESP acks each forward frame with a SLAVE_RESP +// echoing SEND_FORWARD_DATA once it has taken the frame out of its UART ring +// (module firmware from the companion PR; older firmware acks after the radio, +// which also works, just slower), and acks come back in order, so un-acked bytes +// bound what that ring holds. The window is sized to the ring (UART_RX_BUF_SIZE +// in the BWM firmware's app_cmd_uart.h): keep BWM_ESP_UART_RX_BUF equal to it. +// Frames run ~30 B to ~2.1 KB, hence bytes. A frame the ESP cannot deliver is +// answered with CMD_ERROR instead and leaves the window the same way. When acks +// stall on a full window the gate waits BWM_FC_ACK_TIMEOUT_MS, then forgets just +// enough of the oldest frames to send this one. Acks are counted, not matched: +// a lost or late ack shifts the window by a frame until it drains at idle. +#define BWM_ESP_UART_RX_BUF 12288 +#define BWM_FC_BYTES (BWM_ESP_UART_RX_BUF - 1024) // in-flight bytes allowed; slack for the ESP's FIFO and parser lag +#define BWM_FC_MAX_FRAMES 64 // depth of the in-flight length FIFO; also caps tiny frames in flight #ifndef BWM_FC_ACK_TIMEOUT_MS // Hard cap (ms) on how long a forward write may block the main loop waiting for // acks. A spin COUNT was unbounded in wall-clock time and could hang the main // loop long enough that the client gives up and the device looks dead (USB still // enumerates on interrupts). Time-bounded => the main loop is always serviced. -#define BWM_FC_ACK_TIMEOUT_MS 50 // safety valve: proceed if acks stall, never hard-hang +// A full window that stays full this long means the ESP is stuck on the radio +// (a phone scanning stalls BLE for a few hundred ms); every timeout then leaks +// one frame into a full ring, so wait long enough for the usual stalls to pass. +#define BWM_FC_ACK_TIMEOUT_MS 200 // safety valve: proceed if acks stall, never hard-hang #endif // safety valve: give up waiting for credit (avoid hard hang) -#define BWM_CRC16_POLY 0x1021 -#define BWM_CRC16_INIT 0xFFFF - // Wrap `len` raw reply bytes (a whole PacketResponseNG/OLD frame) into one // SEND_FORWARD_DATA app_com frame and write it synchronously to the FPC USART. // Returns PM3_SUCCESS or the underlying usart error. Drop-in for the FPC @@ -92,6 +62,25 @@ uint32_t bwm_read_ng(uint8_t *data, size_t len); // >0 when raw bytes are waiting on the FPC USART (gate for receive_ng()). uint16_t bwm_fwd_rxdata_available(void); +// Flow-control diagnostics since boot (hw status at debug level). +typedef struct { + uint32_t frames; // forward frames sent + uint32_t acks; // SLAVE_RESP acks seen + uint32_t errors; // CMD_ERROR answers seen (undeliverable frames) + uint32_t timeouts; // gate waited BWM_FC_ACK_TIMEOUT_MS on a full window + uint32_t forgotten; // frames the gate stopped counting on those timeouts + uint32_t bytes_max; // peak bytes in flight + uint8_t in_flight_frames; // now + uint32_t in_flight_bytes; // now +} bwm_fc_stats_t; +void bwm_fwd_fc_stats(bwm_fc_stats_t *out); + +// True while the ESP reports a client on BLE or on its WiFi TCP server (the +// LINK_STATE broadcast, sent on change only). ESP firmware without it: never true. +bool bwm_fwd_link_connected(void); +// Seed the BLE half from a status query at boot (a client can outlive an AT32 reset). +void bwm_fwd_link_seed_ble(bool connected); + // Bring the ESP<->AT32 UART to `target` baud: adopt it if the ESP is already // there (its baud survives an AT32-only reset), else negotiate up via app_com // cmd 1011 and re-init UART4 to match. Returns true if the link runs at diff --git a/armsrc/bwm_frame.c b/armsrc/bwm_frame.c new file mode 100644 index 000000000..5e578ecb8 --- /dev/null +++ b/armsrc/bwm_frame.c @@ -0,0 +1,301 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// BWM app_com de-framer. See bwm_frame.h. +//----------------------------------------------------------------------------- + +#include "bwm_frame.h" + +// CRC-16/CCITT-FALSE, byte-identical to the BWM firmware's crc16_ccitt() +// (poly 0x1021, init 0xFFFF, MSB-first, no reflection, no xorout). +uint16_t bwm_crc16(const uint8_t *data, size_t len, uint16_t crc) { + for (size_t i = 0; i < len; i++) { + crc ^= (uint16_t)data[i] << 8; + for (uint8_t b = 0; b < 8; b++) { + if (crc & 0x8000) { + crc = (uint16_t)((crc << 1) ^ BWM_CRC16_POLY); + } else { + crc = (uint16_t)(crc << 1); + } + } + } + return crc; +} + +// --------------------------------------------------------------------------- +// RX: persistent app_com de-framer. Feeds raw FPC bytes through a state machine +// and pushes the payloads of valid DATA_FORWARD (0xD2 0xD3 / cmd 8089) frames +// into a byte FIFO that bwm_read_ng() drains. Non-DATA_FORWARD frames (slave +// responses, forwarded logs, cmd-error reports) are validated and discarded. +// --------------------------------------------------------------------------- +typedef enum { + S_IDLE = 0, S_HDR2, S_CMD_LO, S_CMD_HI, S_LEN_LO, S_LEN_HI, S_PAYLOAD, S_CRC_LO, S_CRC_HI +} bwm_state_t; + +typedef struct { + bwm_state_t state; + uint8_t hdr1; + bool is_bcast; // header pair is 0xD2 0xD3 + uint16_t cmd; + uint16_t len; + uint16_t got; // payload bytes received + uint16_t crc_calc; // running CRC over hdr..payload + uint16_t crc_recv; + uint8_t payload[BWM_FRAME_RX_MAX]; +} bwm_parser_t; + +static bwm_parser_t s_p = { .state = S_IDLE }; + +// De-framed payload ring +static uint8_t s_fifo[BWM_FIFO_SZ]; +static volatile uint16_t s_fifo_head = 0; // write +static volatile uint16_t s_fifo_tail = 0; // read + +// --- Flow control (ack window) --------------------------------------------- +// s_fwd_inflight: forward frames sent but not yet acked by the ESP. Bumped on +// send, decremented when a SLAVE_RESP echoing cmd=SEND_FORWARD_DATA arrives. +// We may send while it is below BWM_FC_WINDOW; at the cap we wait for an ack. +static volatile int16_t s_fwd_inflight = 0; +// Bootrom write path waits for this; OS only uses the inflight count. +static volatile bool s_fwd_ack = false; + +// Set true by the parser when a SLAVE_RESP echoing BWM_CMD_SET_UART_BAUD arrives +// (the ESP's ack for a baud-set request). Consumed by bwm_fwd_negotiate_baud(). +static volatile bool s_baud_ack = false; + +// Set true by the parser on a SLAVE_RESP for BWM_CMD_GET_UART_BAUD - proof the +// ESP is alive and responding at the baud we just switched to (verify step). +static volatile bool s_getbaud_ack = false; + +static uint16_t fifo_count(void) { + return (uint16_t)((s_fifo_head - s_fifo_tail) & (BWM_FIFO_SZ - 1)); +} +static void fifo_push(uint8_t b) { + uint16_t next = (uint16_t)((s_fifo_head + 1) & (BWM_FIFO_SZ - 1)); + if (next != s_fifo_tail) { // drop on overflow rather than corrupt + s_fifo[s_fifo_head] = b; + s_fifo_head = next; + } +} +static uint8_t fifo_pop(void) { + uint8_t b = s_fifo[s_fifo_tail]; + s_fifo_tail = (uint16_t)((s_fifo_tail + 1) & (BWM_FIFO_SZ - 1)); + return b; +} + +static void bwm_reset_frame(bwm_parser_t *p) { + p->state = S_IDLE; +} + +// Update running CRC one byte at a time (mirrors the streaming update in the +// BWM firmware parser). +static void crc_step(bwm_parser_t *p, uint8_t byte) { + p->crc_calc = bwm_crc16(&byte, 1, p->crc_calc); +} + +static void bwm_feed_byte(bwm_parser_t *p, uint8_t byte) { + switch (p->state) { + case S_IDLE: + if (byte == BWM_HDR_SLAVE_BCAST_1) { + p->hdr1 = byte; + p->is_bcast = true; + p->state = S_HDR2; + } else if (byte == BWM_HDR_SLAVE_RESP_1) { + p->hdr1 = byte; + p->is_bcast = false; + p->state = S_HDR2; + } + // any other byte: stay idle (resync) + break; + + case S_HDR2: { + bool ok = (p->is_bcast && byte == BWM_HDR_SLAVE_BCAST_2) || + (!p->is_bcast && byte == BWM_HDR_SLAVE_RESP_2); + if (!ok) { + // header mismatch: reset and re-examine this byte as a potential SOF + p->state = S_IDLE; + bwm_feed_byte(p, byte); + return; + } + uint8_t hdr[2] = { p->hdr1, byte }; + p->crc_calc = bwm_crc16(hdr, 2, BWM_CRC16_INIT); + p->state = S_CMD_LO; + break; + } + + case S_CMD_LO: + p->cmd = byte; + crc_step(p, byte); + p->state = S_CMD_HI; + break; + case S_CMD_HI: + p->cmd |= (uint16_t)byte << 8; + crc_step(p, byte); + p->state = S_LEN_LO; + break; + case S_LEN_LO: + p->len = byte; + crc_step(p, byte); + p->state = S_LEN_HI; + break; + case S_LEN_HI: + p->len |= (uint16_t)byte << 8; + crc_step(p, byte); + p->got = 0; + if (p->len > BWM_FRAME_RX_MAX) { // oversized -> drop frame + bwm_reset_frame(p); + } else { + p->state = (p->len == 0) ? S_CRC_LO : S_PAYLOAD; + } + break; + + case S_PAYLOAD: + p->payload[p->got++] = byte; + crc_step(p, byte); + if (p->got >= p->len) { + p->state = S_CRC_LO; + } + break; + + case S_CRC_LO: + p->crc_recv = byte; + p->state = S_CRC_HI; + break; + case S_CRC_HI: + p->crc_recv |= (uint16_t)byte << 8; + if (p->crc_recv == p->crc_calc) { + if (p->is_bcast && p->cmd == BWM_CMD_DATA_FORWARD) { + for (uint16_t i = 0; i < p->len; i++) { + fifo_push(p->payload[i]); + } + } else if ((p->is_bcast == false) && p->cmd == BWM_CMD_SEND_FORWARD_DATA) { + // SLAVE_RESP ack for a forward frame -> one slot freed + if (s_fwd_inflight > 0) { + s_fwd_inflight--; + } + s_fwd_ack = true; +#ifndef AS_BOOTROM + bwm_fwd_on_frame_ack(); +#endif + } else if (p->is_bcast && p->cmd == BWM_CMD_CMD_ERROR && p->len >= 2 && + (((uint16_t)p->payload[0] | ((uint16_t)p->payload[1] << 8)) == BWM_CMD_SEND_FORWARD_DATA)) { + // the ESP could not deliver a forward frame: this is its answer instead of the ack +#ifndef AS_BOOTROM + bwm_fwd_on_frame_error(); +#endif + } else if ((p->is_bcast == false) && p->cmd == BWM_CMD_SET_UART_BAUD) { + // SLAVE_RESP ack for a baud-set request (see negotiate below) + s_baud_ack = true; + } else if ((p->is_bcast == false) && p->cmd == BWM_CMD_GET_UART_BAUD) { + // SLAVE_RESP for our GET_BAUD verify probe + s_getbaud_ack = true; + } else if (p->is_bcast && p->cmd == BWM_CMD_LINK_STATE && p->len >= 2) { +#ifndef AS_BOOTROM + bwm_fwd_on_link_state(p->payload[0], p->payload[1]); +#endif + } + } + // valid non-DATA_FORWARD frames and CRC failures alike: just resync + bwm_reset_frame(p); + break; + + default: + bwm_reset_frame(p); + break; + } +} + +void bwm_frame_feed(uint8_t byte) { + bwm_feed_byte(&s_p, byte); +} + +uint16_t bwm_fifo_count(void) { + return fifo_count(); +} + +uint8_t bwm_fifo_pop(void) { + return fifo_pop(); +} + +int16_t bwm_frame_inflight(void) { + return s_fwd_inflight; +} + +void bwm_frame_inflight_inc(void) { + s_fwd_inflight++; +} + +void bwm_frame_inflight_zero(void) { + s_fwd_inflight = 0; +} + +bool bwm_frame_take_fwd_ack(void) { + if (s_fwd_ack == false) { + return false; + } + s_fwd_ack = false; + return true; +} + +bool bwm_frame_baud_ack(void) { + return s_baud_ack; +} + +void bwm_frame_clear_baud_ack(void) { + s_baud_ack = false; + s_p.state = S_IDLE; // drop any half-frame before we listen +} + +bool bwm_frame_getbaud_ack(void) { + return s_getbaud_ack; +} + +void bwm_frame_clear_getbaud_ack(void) { + s_getbaud_ack = false; + s_p.state = S_IDLE; +} + +void bwm_frame_reset(void) { + s_p.state = S_IDLE; + s_fifo_head = 0; + s_fifo_tail = 0; + s_fwd_inflight = 0; + s_fwd_ack = false; + s_baud_ack = false; + s_getbaud_ack = false; +} + +size_t bwm_frame_build(uint16_t cmd, const uint8_t *payload, uint16_t len, + uint8_t *out, size_t outsz) { + size_t idx = 0; + if (out == NULL || outsz < (size_t)(8 + len)) { + return 0; + } + out[idx++] = BWM_HDR_HOST_CMD_1; + out[idx++] = BWM_HDR_HOST_CMD_2; + out[idx++] = (uint8_t)(cmd & 0xFF); + out[idx++] = (uint8_t)((cmd >> 8) & 0xFF); + out[idx++] = (uint8_t)(len & 0xFF); + out[idx++] = (uint8_t)((len >> 8) & 0xFF); + if (len && payload) { + for (uint16_t i = 0; i < len; i++) { + out[idx++] = payload[i]; + } + } + uint16_t crc = bwm_crc16(out, idx, BWM_CRC16_INIT); + out[idx++] = (uint8_t)(crc & 0xFF); + out[idx++] = (uint8_t)((crc >> 8) & 0xFF); + return idx; +} diff --git a/armsrc/bwm_frame.h b/armsrc/bwm_frame.h new file mode 100644 index 000000000..a21cbb434 --- /dev/null +++ b/armsrc/bwm_frame.h @@ -0,0 +1,103 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// BWM app_com de-framer shared by the PM5 OS and bootrom. +// +// The BWM (ESP32-C2, RfidResearchGroup/Proxmark5_BWM_esp32) bridges the AT32 +// host <-> BLE/WiFi. Its ESP<->AT32 UART link does NOT carry raw PacketCommandNG; +// it uses a framed "app_com" protocol. Transparent host<->wireless traffic rides +// inside that framing: +// +// AT32 -> ESP (our reply, toward wireless host): +// [0x7C 0xC7] cmd=APP_CMD_SEND_FORWARD_DATA(5000) len(LE) payload CRC16(LE) +// ESP -> AT32 (command from wireless host): +// [0xD2 0xD3] cmd=APP_BROADCAST_DATA_FORWARD(8089) len(LE) payload CRC16(LE) +// +// Frame = HDR1 HDR2 | CMD(LE16) | LEN(LE16) | PAYLOAD[LEN] | CRC(LE16) +// CRC = CRC-16/CCITT-FALSE (poly 0x1021, init 0xFFFF, MSB-first, no xorout) +// over HDR..PAYLOAD. (NOT compute_crc(CRC_14443_A) - different CRC.) +//----------------------------------------------------------------------------- +#ifndef BWM_FRAME_H +#define BWM_FRAME_H + +#include "common.h" +#include "pm3_cmd.h" + +// app_com framing constants (verified against BWM firmware app_cmd_uart.[ch] / +// app_com_defs.h). +#define BWM_HDR_HOST_CMD_1 0x7C // AT32 -> ESP (host command) +#define BWM_HDR_HOST_CMD_2 0xC7 +#define BWM_HDR_SLAVE_BCAST_1 0xD2 // ESP -> AT32 (slave broadcast) +#define BWM_HDR_SLAVE_BCAST_2 0xD3 +#define BWM_HDR_SLAVE_RESP_1 0x2D // ESP -> AT32 (slave response; forward-frame ack) +#define BWM_HDR_SLAVE_RESP_2 0x3D + +#define BWM_CMD_SEND_FORWARD_DATA 5000 // host cmd: payload -> BLE/WiFi endpoint +#define BWM_CMD_DATA_FORWARD 8089 // slave bcast: payload came from endpoint +#define BWM_CMD_CMD_ERROR 8091 // slave bcast: command error report +#define BWM_CMD_LINK_STATE 8092 // slave bcast: [ble u8][wifi u8], 1 = a client is connected +// System command: set the ESP<->AT32 UART baud (app_com_defs.h, enum @1000). +// SET is a HOST_CMD carrying u32 LE baud; the ESP replies with a SLAVE_RESP +// echoing this cmd (len 0) at the OLD baud, then commits to the new baud. +#define BWM_CMD_SET_UART_BAUD 1011 +#define BWM_CMD_GET_UART_BAUD 1009 // read back the ESP's live baud (negotiation verify) + +#define BWM_CRC16_POLY 0x1021 +#define BWM_CRC16_INIT 0xFFFF + +#ifdef AS_BOOTROM +#ifndef BWM_FRAME_RX_MAX +#define BWM_FRAME_RX_MAX 576 +#endif +#ifndef BWM_FIFO_SZ +#define BWM_FIFO_SZ 1024 +#endif +#else +#ifndef BWM_FRAME_RX_MAX +#define BWM_FRAME_RX_MAX (PM3_CMD_DATA_SIZE + 64) // NG/OLD frame ceiling +#endif +#ifndef BWM_FIFO_SZ +#define BWM_FIFO_SZ 2048 // >= one full NG frame's payload +#endif +#endif + +uint16_t bwm_crc16(const uint8_t *data, size_t len, uint16_t crc); + +void bwm_frame_reset(void); +void bwm_frame_feed(uint8_t byte); + +uint16_t bwm_fifo_count(void); +uint8_t bwm_fifo_pop(void); + +int16_t bwm_frame_inflight(void); +void bwm_frame_inflight_inc(void); +void bwm_frame_inflight_zero(void); + +bool bwm_frame_take_fwd_ack(void); +bool bwm_frame_baud_ack(void); +void bwm_frame_clear_baud_ack(void); +bool bwm_frame_getbaud_ack(void); +void bwm_frame_clear_getbaud_ack(void); + +size_t bwm_frame_build(uint16_t cmd, const uint8_t *payload, uint16_t len, + uint8_t *out, size_t outsz); + +#ifndef AS_BOOTROM +void bwm_fwd_on_frame_ack(void); +void bwm_fwd_on_frame_error(void); +void bwm_fwd_on_link_state(uint8_t ble, uint8_t wifi); +#endif + +#endif diff --git a/armsrc/bwm_uart_at32.c b/armsrc/bwm_uart_at32.c index e796f1945..02088cfe2 100644 --- a/armsrc/bwm_uart_at32.c +++ b/armsrc/bwm_uart_at32.c @@ -21,6 +21,7 @@ #include "bwm_uart_at32.h" #include "pm3_cmd.h" +#include "ticks_apis.h" // GetTickCount / GetTickCountDelta / SpinDelay #include "at32f435_437.h" #include "at32f435_437_crm.h" #include "at32f435_437_gpio.h" @@ -52,6 +53,16 @@ static volatile uint16_t s_rx_tail = 0; // software read cursor; head comes fr static volatile bool s_inited = false; static volatile uint32_t s_cur_baud = BWM_UART_BAUD; +// The ESP light-sleeps BWM_ESP_AWAKE_MS after the last byte either way and loses +// the bytes whose edges wake it, so the first write, and any after +// BWM_ESP_WAKE_AFTER_MS of silence of ours (RX is not tracked, see bwm_uart_read), +// leads with a disposable preamble; ESP fw without light sleep resyncs past it. +#define BWM_ESP_AWAKE_MS 2000 // == UART_LINK_AWAKE_MS on the ESP +#define BWM_ESP_WAKE_AFTER_MS 1000 // preamble when quiet longer than this (margin for drift) +#define BWM_ESP_WAKE_SETTLE_MS 10 // light-sleep exit + UART driver back up +static volatile uint32_t s_last_traffic_tick = 0; +static volatile bool s_tx_ever = false; // nothing sent yet: the tick above means nothing + // Bytes the DMA controller has written so far, wrapped into the ring. // The channel's DTCNT counts DOWN from buffer_size and reloads to buffer_size // at wrap (loop mode), so head = size - remaining, always in [0, size-1]. @@ -138,7 +149,17 @@ uint32_t bwm_uart_get_baud(void) { return s_cur_baud; } -int bwm_uart_write(const uint8_t *data, size_t len) { +void bwm_uart_clock_update(void) { + if (s_inited == false) { + return; + } + // Recompute the baud divider for the new APB1 clock. usart_init() only + // rewrites the divider and the (unchanged) 8N1 frame bits; it does not + // touch the enable bits or the DMA request, so it is safe on a live port. + usart_init(BWM_UART, s_cur_baud, USART_DATA_8BITS, USART_STOP_1_BIT); +} + +static void bwm_uart_write_raw(const uint8_t *data, size_t len) { for (size_t i = 0; i < len; i++) { while (usart_flag_get(BWM_UART, USART_TDBE_FLAG) == RESET) { } @@ -146,9 +167,25 @@ int bwm_uart_write(const uint8_t *data, size_t len) { } while (usart_flag_get(BWM_UART, USART_TDC_FLAG) == RESET) { } +} + +int bwm_uart_write(const uint8_t *data, size_t len) { + if ((s_tx_ever == false) || (GetTickCountDelta(s_last_traffic_tick) > BWM_ESP_WAKE_AFTER_MS)) { + // 0x55 = five rising edges per byte; the ESP wakes after three. + static const uint8_t wake[4] = { 0x55, 0x55, 0x55, 0x55 }; + bwm_uart_write_raw(wake, sizeof(wake)); + SpinDelay(BWM_ESP_WAKE_SETTLE_MS); + } + bwm_uart_write_raw(data, len); + s_last_traffic_tick = GetTickCount(); + s_tx_ever = true; return PM3_SUCCESS; } +void bwm_uart_wake_next(void) { + s_tx_ever = false; +} + uint16_t bwm_uart_rx_available(void) { // An unhandled overrun (ROERR) latches on this USART and stops it feeding the // DMA - after one overrun every subsequent byte is lost until a re-init, which @@ -170,5 +207,7 @@ uint32_t bwm_uart_read(uint8_t *data, size_t len) { data[n++] = s_rx_ring[s_rx_tail]; s_rx_tail = (uint16_t)((s_rx_tail + 1) & (BWM_RX_RING_SZ - 1)); } + // RX does not refresh s_last_traffic_tick: the ring can be drained long after + // the ESP sent the bytes, so it says nothing about the module's awake window. return n; } diff --git a/armsrc/bwm_uart_at32.h b/armsrc/bwm_uart_at32.h index b5ead636d..080aac79e 100644 --- a/armsrc/bwm_uart_at32.h +++ b/armsrc/bwm_uart_at32.h @@ -36,8 +36,18 @@ void bwm_uart_set_baud(uint32_t baud); // Baud the link is currently running at (updated by bwm_uart_set_baud). uint32_t bwm_uart_get_baud(void); +// Re-derive the baud divider for the current APB1 clock. Called on every core +// clock switch (pm5_power.c); the divider set at 288 MHz is 6x off at 48 MHz. +void bwm_uart_clock_update(void); + +// Blocking write of one whole frame. On the first write, and after ~1 s without +// a write of our own, it first sends a wake preamble for the ESP's light sleep +// and waits ~10 ms (see the BWM_ESP_* defines in bwm_uart_at32.c). int bwm_uart_write(const uint8_t *data, size_t len); +// Lead the next write with the wake preamble, whatever the quiet time. +void bwm_uart_wake_next(void); + uint16_t bwm_uart_rx_available(void); uint32_t bwm_uart_read(uint8_t *data, size_t len); diff --git a/armsrc/bwm_wifi.c b/armsrc/bwm_wifi.c index 99636819f..ffff5921b 100644 --- a/armsrc/bwm_wifi.c +++ b/armsrc/bwm_wifi.c @@ -158,9 +158,13 @@ int bwm_cmd(uint16_t cmd, const uint8_t *req, uint16_t req_len, int32_t esp_err = 0; if (rlen >= 6) { esp_err = (int32_t)((uint32_t)pbuf[2] | ((uint32_t)pbuf[3] << 8) | - ((uint32_t)pbuf[4] << 16) | ((uint32_t)pbuf[5] << 24)); + ((uint32_t)pbuf[4] << 16) | ((uint32_t)pbuf[5] << 24)); + } + // Expected in places (e.g. a status query while WiFi is + // off): only worth seeing when debugging the link. + if (g_dbglevel >= DBG_DEBUG) { + Dbprintf("[bwm-wifi] cmd 0x%04x failed, esp_err=0x%08x", (unsigned)cmd, (unsigned)esp_err); } - Dbprintf("[bwm-wifi] cmd 0x%04x failed, esp_err=0x%08x", (unsigned)cmd, (unsigned)esp_err); return PM3_EFAILED; } } @@ -313,8 +317,149 @@ int bwm_wifi_forward_down(void) { // boot slot, so those get generous timeouts. // --------------------------------------------------------------------------- // Read the ESP's running firmware version string (APP_CMD_GET_VERSION_INFO). -int bwm_esp_get_version(uint8_t *buf, uint16_t *buflen) { - return bwm_cmd(BWM_CMD_GET_VERSION_INFO, NULL, 0, buf, buflen, 3000); +int bwm_esp_get_version(uint8_t *buf, uint16_t *buflen, uint32_t timeout_ms) { + return bwm_cmd(BWM_CMD_GET_VERSION_INFO, NULL, 0, buf, buflen, timeout_ms); +} + +// One u8-in / u8-out ESP setting round trip: send req (NULL/0 for a GET) and +// expect a one-byte reply in *out. PM3_EFAILED if the ESP acked without a payload. +static int bwm_esp_u8_cmd(uint16_t cmd, const uint8_t *req, uint16_t req_len, uint8_t *out, uint32_t timeout_ms) { + uint16_t len = 1; + int r = bwm_cmd(cmd, req, req_len, out, &len, timeout_ms); + if (r == PM3_SUCCESS && len < 1) { + r = PM3_EFAILED; + } + return r; +} + +int bwm_esp_get_power_save(uint8_t *state, uint32_t timeout_ms) { + return bwm_esp_u8_cmd(BWM_CMD_GET_SYS_POWER_SAVE, NULL, 0, state, timeout_ms); +} + +int bwm_esp_get_ble_state(uint8_t *state, uint32_t timeout_ms) { + return bwm_esp_u8_cmd(BWM_CMD_GET_BLE_SPP_STATUS, NULL, 0, state, timeout_ms); +} + +int bwm_esp_host_value_set(uint8_t id, uint32_t value, uint32_t timeout_ms) { + uint8_t req[5] = { id }; + memcpy(&req[1], &value, sizeof(value)); + return bwm_cmd(BWM_CMD_SET_SYS_HOST_VALUE, req, sizeof(req), NULL, NULL, timeout_ms); +} + +int bwm_esp_host_value_get(uint8_t id, uint32_t *value, uint32_t timeout_ms) { + uint8_t resp[5] = {0}; + uint16_t len = sizeof(resp); + int res = bwm_cmd(BWM_CMD_GET_SYS_HOST_VALUE, &id, 1, resp, &len, timeout_ms); + if (res != PM3_SUCCESS) { + return res; + } + if (len < sizeof(resp) || resp[0] == 0) { + return PM3_ENODATA; + } + memcpy(value, &resp[1], sizeof(*value)); + return PM3_SUCCESS; +} + +int bwm_esp_set_ble_enable(bool on, uint8_t *stored) { + uint8_t v = on ? 1 : 0; + return bwm_esp_u8_cmd(BWM_CMD_SET_BLE_ENABLE, &v, 1, stored, 3000); +} + +int bwm_esp_set_ble_bonding(bool on) { + uint8_t v = on ? 1 : 0; + return bwm_cmd(BWM_CMD_SET_BLE_BONDING_ENABLE, &v, 1, NULL, NULL, 3000); +} + +int bwm_esp_set_ble_key(const uint8_t key[6]) { + return bwm_cmd(BWM_CMD_SET_BLE_BONDING_KEY, key, 6, NULL, NULL, 3000); +} + +int bwm_esp_ble_forget(uint8_t idx) { + if (idx == 0xFF) { + return bwm_cmd(BWM_CMD_CLEAR_BLE_BONDED, NULL, 0, NULL, NULL, 3000); + } + return bwm_cmd(BWM_CMD_DEL_BLE_BONDED, &idx, 1, NULL, NULL, 3000); +} + +int bwm_esp_set_ble_txpower(uint8_t type, uint8_t level) { + uint8_t req[2] = { type, level }; + return bwm_cmd(BWM_CMD_SET_BLE_TX_POWER, req, sizeof(req), NULL, NULL, 3000); +} + +int bwm_esp_ble_restart(void) { + uint8_t state = 0; + int res = bwm_esp_get_ble_state(&state, 3000); + if (res != PM3_SUCCESS || state == 0) { + return res; // stopped (or switched off): nothing to restart + } + res = bwm_cmd(BWM_CMD_STOP_BLE_SPP, NULL, 0, NULL, NULL, 3000); + if (res != PM3_SUCCESS) { + return res; + } + return bwm_cmd(BWM_CMD_START_BLE_SPP, NULL, 0, NULL, NULL, 3000); +} + +int bwm_esp_ble_status(bwm_ble_status_t *st) { + memset(st, 0xFF, sizeof(*st)); + // The first query wakes a light-sleeping module; the rest land while it is up. + // Its timeout is also the only one we pay when no module answers at all. + int res = bwm_esp_get_ble_state(&st->state, 1500); + if (res == PM3_ETIMEOUT) { + return res; + } + (void)bwm_esp_u8_cmd(BWM_CMD_GET_BLE_ENABLE, NULL, 0, &st->enabled, 800); // older fw: CMD_ERROR or silence + (void)bwm_esp_u8_cmd(BWM_CMD_GET_BLE_BONDING_ENABLE, NULL, 0, &st->bonding, 1500); + uint16_t len = sizeof(st->passkey); + (void)bwm_cmd(BWM_CMD_GET_BLE_BONDING_KEY, NULL, 0, (uint8_t *)st->passkey, &len, 1500); + uint8_t type = 0; + (void)bwm_esp_u8_cmd(BWM_CMD_GET_BLE_TX_POWER, &type, 1, &st->txp_adv, 1500); + type = 1; + (void)bwm_esp_u8_cmd(BWM_CMD_GET_BLE_TX_POWER, &type, 1, &st->txp_conn, 1500); + len = sizeof(st->addr); + (void)bwm_cmd(BWM_CMD_GET_BLE_DEVICE_ADDR, NULL, 0, st->addr, &len, 1500); + memset(st->name, 0, sizeof(st->name)); + len = sizeof(st->name) - 1; + if (bwm_esp_get_ble_name((uint8_t *)st->name, &len) != PM3_SUCCESS) { + st->name[0] = 0; + } + st->bonded_count = 0; + uint8_t n = 0; + if (bwm_esp_u8_cmd(BWM_CMD_GET_BLE_BONDED_NUMS, NULL, 0, &n, 1500) == PM3_SUCCESS) { + for (uint8_t i = 0; i < n && i < BWM_BLE_BONDED_MAX; i++) { + len = 7; + if (bwm_cmd(BWM_CMD_GET_BLE_BONDED_ADDR, &i, 1, st->bonded[i], &len, 1500) == PM3_SUCCESS && len == 7) { + st->bonded_count++; + } else { + break; + } + } + } + return PM3_SUCCESS; +} + +int bwm_esp_set_power_save(bool on, uint8_t *state) { + // Applied at once on the ESP (no reboot) and saved to its NVS; the reply + // carries the state the ESP ended up in. + uint8_t v = on ? 1 : 0; + return bwm_esp_u8_cmd(BWM_CMD_SET_SYS_POWER_SAVE, &v, 1, state, 3000); +} + +int bwm_esp_get_wifi_ps(uint8_t *mode) { + return bwm_esp_u8_cmd(BWM_CMD_GET_WIFI_CFG_PS_MODE, NULL, 0, mode, 3000); +} + +int bwm_esp_set_wifi_ps(uint8_t mode, uint8_t *applied) { + return bwm_esp_u8_cmd(BWM_CMD_SET_WIFI_CFG_PS_MODE, &mode, 1, applied, 3000); +} + +int bwm_esp_get_ble_name(uint8_t *buf, uint16_t *buflen) { + return bwm_cmd(BWM_CMD_GET_BLE_DEVICE_NAME, NULL, 0, buf, buflen, 3000); +} + +int bwm_esp_set_ble_name(const uint8_t *name, uint16_t len) { + // The ESP validates length and stores the name in NVS; it applies at BLE + // startup, so the caller reboots the ESP afterwards to make it take effect. + return bwm_cmd(BWM_CMD_SET_BLE_DEVICE_NAME, name, len, NULL, NULL, 3000); } int bwm_esp_ota_begin(uint32_t total_size) { @@ -336,7 +481,7 @@ int bwm_esp_ota_begin(uint32_t total_size) { // and the AT32 on the other, after which every OTA_BEGIN times out. uint8_t p[4] = { - (uint8_t)(total_size & 0xFF), (uint8_t)((total_size >> 8) & 0xFF), + (uint8_t)(total_size & 0xFF), (uint8_t)((total_size >> 8) & 0xFF), (uint8_t)((total_size >> 16) & 0xFF), (uint8_t)((total_size >> 24) & 0xFF) }; return bwm_cmd(BWM_CMD_OTA_BEGIN, p, sizeof(p), NULL, NULL, BWM_OTA_BEGIN_TIMEOUT_MS); diff --git a/armsrc/bwm_wifi.h b/armsrc/bwm_wifi.h index d9528137c..23b34211d 100644 --- a/armsrc/bwm_wifi.h +++ b/armsrc/bwm_wifi.h @@ -10,6 +10,7 @@ #define BWM_WIFI_H #include "common.h" +#include "pm3_cmd.h" // bwm_ble_status_t // app_com command codes (authoritative, from BWM main/app_com_defs.h) #define BWM_CMD_SET_TO_WIFI_DISABLE_MODE 2000 // no payload: tear down WiFi, back to BLE-only @@ -34,7 +35,9 @@ #define BWM_CMD_SET_TCP_SERVER_PORT 2205 // payload: uint16 LE port #define BWM_WIFI_FORWARD_TCP_SERVER 0 // wifi_forward_type_t::WIFI_FORWARD_TCP_SERVER +#ifndef BWM_CMD_CMD_ERROR #define BWM_CMD_CMD_ERROR 8091 // slave bcast: command error report +#endif #define BWM_CMD_LOG_FORWARD_ENABLE 1014 // payload: u8 (0=stop, non-zero=start) #define BWM_CMD_LOG_MESSAGE 8090 // slave bcast: ESP_LOGx output (string) @@ -86,7 +89,59 @@ int bwm_wifi_forward_status(uint8_t *state, uint32_t *ip_out); #define BWM_CMD_GET_VERSION_INFO 1000 // resp: running firmware version string #define BWM_CMD_STOP_BLE_SPP 4022 // no payload: stop BLE during OTA (flash contention) #define BWM_CMD_START_BLE_SPP 4021 // no payload: restore BLE after OTA -int bwm_esp_get_version(uint8_t *buf, uint16_t *buflen); +#define BWM_CMD_SET_BLE_DEVICE_NAME 4002 // req: name bytes +#define BWM_CMD_GET_BLE_DEVICE_NAME 4003 // resp: current BLE device name string +// ESP power-save switch (DFS + light sleep + low-duty advertising), persisted on +// the ESP. Both return the ESP's applied state in *state. +#define BWM_CMD_SET_SYS_POWER_SAVE 1019 // req: u8 0=off 1=on; resp: u8 applied state +#define BWM_CMD_GET_SYS_POWER_SAVE 1020 // resp: u8 state +int bwm_esp_get_power_save(uint8_t *state, uint32_t timeout_ms); +// Host settings the module stores for us (app_host NVS); the ids are ours. +#define BWM_CMD_SET_SYS_HOST_VALUE 1021 // req: [id u8][value u32]; resp: u32 +#define BWM_CMD_GET_SYS_HOST_VALUE 1022 // req: [id u8]; resp: [present u8][value u32] +#define BWM_HOSTVAL_AUTOOFF_ENABLED 0 +#define BWM_HOSTVAL_AUTOOFF_IDLE_S 1 +#define BWM_HOSTVAL_AUTOOFF_UNPLUG 2 +int bwm_esp_host_value_set(uint8_t id, uint32_t value, uint32_t timeout_ms); +// PM3_SUCCESS with the value, PM3_ENODATA if never stored, else the link error. +int bwm_esp_host_value_get(uint8_t id, uint32_t *value, uint32_t timeout_ms); +#define BWM_CMD_GET_BLE_SPP_STATUS 4020 // resp: u8 0=stopped 1=advertising 2=client connected +#define BWM_BLE_STATE_CONNECTED 2 +int bwm_esp_get_ble_state(uint8_t *state, uint32_t timeout_ms); + +// BLE settings behind `hw bwm ble` (app_com_defs.h, BLE block @4000). +#define BWM_CMD_GET_BLE_DEVICE_ADDR 4007 // resp: 6 bytes +#define BWM_CMD_SET_BLE_BONDING_ENABLE 4008 // req: u8; takes effect at the next stack start +#define BWM_CMD_GET_BLE_BONDING_ENABLE 4009 // resp: u8 +#define BWM_CMD_SET_BLE_BONDING_KEY 4010 // req: 6 ASCII digits +#define BWM_CMD_GET_BLE_BONDING_KEY 4011 // resp: 6 ASCII digits +#define BWM_CMD_GET_BLE_BONDED_NUMS 4012 // resp: u8 count +#define BWM_CMD_GET_BLE_BONDED_ADDR 4013 // req: u8 index; resp: addr[6] + type +#define BWM_CMD_DEL_BLE_BONDED 4014 // req: u8 index +#define BWM_CMD_CLEAR_BLE_BONDED 4015 // no payload +#define BWM_CMD_SET_BLE_TX_POWER 4018 // req: [type][level] +#define BWM_CMD_GET_BLE_TX_POWER 4019 // req: u8 type; resp: u8 level +#define BWM_CMD_SET_BLE_ENABLE 4023 // req: u8 (persisted, applied at once); resp: u8 stored. Newer ESP fw only +#define BWM_CMD_GET_BLE_ENABLE 4024 // resp: u8 +int bwm_esp_set_ble_enable(bool on, uint8_t *stored); +int bwm_esp_set_ble_bonding(bool on); +int bwm_esp_set_ble_key(const uint8_t key[6]); +int bwm_esp_ble_forget(uint8_t idx); // 0xFF = all +int bwm_esp_set_ble_txpower(uint8_t type, uint8_t level); +// Stop + start the stack so a bonding change applies; no-op while it is stopped. +int bwm_esp_ble_restart(void); +// Best-effort snapshot for `hw bwm ble`; fields the module cannot answer read 0xFF. +// PM3_ETIMEOUT (nothing filled in) when the module does not answer the first query. +int bwm_esp_ble_status(bwm_ble_status_t *st); +// ESP WiFi modem power-save type (0 none, 1 min, 2 max), persisted on the ESP. +#define BWM_CMD_SET_WIFI_CFG_PS_MODE 2052 // req: u8 mode; resp: u8 applied mode +#define BWM_CMD_GET_WIFI_CFG_PS_MODE 2053 // resp: u8 mode +int bwm_esp_get_wifi_ps(uint8_t *mode); +int bwm_esp_set_wifi_ps(uint8_t mode, uint8_t *applied); +int bwm_esp_set_power_save(bool on, uint8_t *state); +int bwm_esp_get_version(uint8_t *buf, uint16_t *buflen, uint32_t timeout_ms); +int bwm_esp_get_ble_name(uint8_t *buf, uint16_t *buflen); +int bwm_esp_set_ble_name(const uint8_t *name, uint16_t len); int bwm_esp_ota_begin(uint32_t total_size); int bwm_esp_ota_write(const uint8_t *data, uint16_t len); int bwm_esp_ota_end(void); diff --git a/armsrc/cmd.c b/armsrc/cmd.c index d3c80b067..a2d210a0d 100644 --- a/armsrc/cmd.c +++ b/armsrc/cmd.c @@ -20,6 +20,14 @@ #ifdef WITH_BWM_FORWARD #include "bwm_forward.h" #endif +#ifdef WITH_CEP +#include "pm5_cep.h" +#else +// receive_ng_internal()'s `cep` parameter is always false without WITH_CEP, +// so this is never actually called - just keeps those call sites free of +// per-site #if defined(WITH_CEP) guards. +static inline void cep_spi_resync(void) {} +#endif #include "crc16.h" #include "string.h" #include "BigBuf.h" @@ -29,6 +37,8 @@ bool g_reply_with_crc_on_usb = false; bool g_reply_with_crc_on_fpc = true; // "Session" flag, to tell via which interface next msgs should be sent: USB or FPC USART bool g_reply_via_fpc = false; +// Independent of via_fpc - CEP (Flipper Zero, over SPI1) may be live at the same time as BWM/FPC. +bool g_reply_via_cep = false; // Largest NG payload the device will put on the CURRENT reply link. Over FPC the // BWM buffers are smaller than a full frame, so cap there; USB uses the full size. @@ -63,6 +73,9 @@ int reply_old(uint64_t cmd, uint64_t arg0, uint64_t arg1, uint64_t arg2, const v #if defined(WITH_FPC_USART_HOST) || defined(WITH_BWM_FORWARD) int resultfpc = PM3_EUNDEF; +#endif +#if defined(WITH_CEP) + int resultcep = PM3_EUNDEF; #endif int resultusb = PM3_EUNDEF; // Send frame and make sure all bytes are transmitted @@ -80,47 +93,64 @@ int reply_old(uint64_t cmd, uint64_t arg0, uint64_t arg1, uint64_t arg2, const v return PM3_EDEVNOTSUPP; #endif } - // we got two results, let's prioritize the faulty one and USB over FPC. + if (g_reply_via_cep) { +#if defined(WITH_CEP) + resultcep = cep_spi_write_sync((uint8_t *)&txcmd, sizeof(PacketResponseOLD)); + if (resultcep != PM3_SUCCESS) { + cep_spi_resync(); + } +#else + return PM3_EDEVNOTSUPP; +#endif + } + // we got multiple results, let's prioritize the faulty one and USB over FPC over CEP. if (g_reply_via_usb && (resultusb != PM3_SUCCESS)) return resultusb; #if defined(WITH_FPC_USART_HOST) || defined(WITH_BWM_FORWARD) if (g_reply_via_fpc && (resultfpc != PM3_SUCCESS)) return resultfpc; +#endif +#if defined(WITH_CEP) + if (g_reply_via_cep && (resultcep != PM3_SUCCESS)) return resultcep; #endif return PM3_SUCCESS; } -// TODO DXL 测试阶段,暂时通过SPI应答 -extern int cep_spi_write_sync(uint8_t *data, size_t len); - static int reply_ng_internal(uint16_t cmd, int8_t status, uint8_t reason, const uint8_t *data, size_t len, bool ng) { - PacketResponseNGRaw txBufferNG; + // The NG preamble is 10 bytes, so data[] would sit 2 past a word boundary + // and memcpy could never take its word path. Offsetting the whole frame by + // 2 lands data[] on a word boundary. The bytes on the wire are unchanged. + struct { + uint8_t pad[2]; + PacketResponseNGRaw raw; + } __attribute__((aligned(4))) frame; + PacketResponseNGRaw *tx = &frame.raw; size_t txBufferNGLen; // Compose the outgoing command frame - txBufferNG.pre.magic = RESPONSENG_PREAMBLE_MAGIC; - txBufferNG.pre.cmd = cmd; - txBufferNG.pre.status = status; - txBufferNG.pre.reason = reason; - txBufferNG.pre.ng = ng; + tx->pre.magic = RESPONSENG_PREAMBLE_MAGIC; + tx->pre.cmd = cmd; + tx->pre.status = status; + tx->pre.reason = reason; + tx->pre.ng = ng; if (len > PM3_CMD_DATA_SIZE) { len = PM3_CMD_DATA_SIZE; // overwrite status - txBufferNG.pre.status = PM3_EOVFLOW; + tx->pre.status = PM3_EOVFLOW; } // length is only 15bit (32768) - txBufferNG.pre.length = (len & 0x7FFF); + tx->pre.length = (len & 0x7FFF); // Add the (optional) content to the frame, with a maximum size of PM3_CMD_DATA_SIZE if (data && len) { - memcpy(txBufferNG.data, data, len); + memcpy(tx->data, data, len); } - PacketResponseNGPostamble *tx_post = (PacketResponseNGPostamble *)((uint8_t *)&txBufferNG + sizeof(PacketResponseNGPreamble) + len); + PacketResponseNGPostamble *tx_post = (PacketResponseNGPostamble *)((uint8_t *)tx + sizeof(PacketResponseNGPreamble) + len); // Note: if we send to both FPC & USB, we'll set CRC for both if any of them require CRC if ((g_reply_via_fpc && g_reply_with_crc_on_fpc) || ((g_reply_via_usb) && g_reply_with_crc_on_usb)) { uint8_t first, second; - compute_crc(CRC_14443_A, (uint8_t *)&txBufferNG, sizeof(PacketResponseNGPreamble) + len, &first, &second); + compute_crc(CRC_14443_A, (uint8_t *)tx, sizeof(PacketResponseNGPreamble) + len, &first, &second); tx_post->crc = ((first << 8) | second); } else { tx_post->crc = RESPONSENG_POSTAMBLE_MAGIC; @@ -129,27 +159,36 @@ static int reply_ng_internal(uint16_t cmd, int8_t status, uint8_t reason, const #if defined(WITH_FPC_USART_HOST) || defined(WITH_BWM_FORWARD) int resultfpc = PM3_EUNDEF; +#endif +#if defined(WITH_CEP) + int resultcep = PM3_EUNDEF; #endif int resultusb = PM3_EUNDEF; // Send frame and make sure all bytes are transmitted if (g_reply_via_usb) { - resultusb = usb_write((uint8_t *)&txBufferNG, txBufferNGLen); + resultusb = usb_write((uint8_t *)tx, txBufferNGLen); } if (g_reply_via_fpc) { - - // TODO DXL 测试阶段,暂时通过SPI应答 - // resultusb = cep_spi_write_sync((uint8_t *)&txBufferNG, txBufferNGLen); - #if defined(WITH_BWM_FORWARD) - resultfpc = bwm_fwd_writebuffer_sync((uint8_t *)&txBufferNG, txBufferNGLen); + resultfpc = bwm_fwd_writebuffer_sync((uint8_t *)tx, txBufferNGLen); #elif defined(WITH_FPC_USART_HOST) - resultfpc = usart_writebuffer_sync((uint8_t *)&txBufferNG, txBufferNGLen); + resultfpc = usart_writebuffer_sync((uint8_t *)tx, txBufferNGLen); #else return PM3_EDEVNOTSUPP; #endif } - // we got two results, let's prioritize the faulty one and USB over FPC. + if (g_reply_via_cep) { +#if defined(WITH_CEP) + resultcep = cep_spi_write_sync((uint8_t *)tx, txBufferNGLen); + if (resultcep != PM3_SUCCESS) { + cep_spi_resync(); + } +#else + return PM3_EDEVNOTSUPP; +#endif + } + // we got multiple results, let's prioritize the faulty one and USB over FPC over CEP. if (g_reply_via_usb && (resultusb != PM3_SUCCESS)) { return resultusb; } @@ -158,6 +197,11 @@ static int reply_ng_internal(uint16_t cmd, int8_t status, uint8_t reason, const if (g_reply_via_fpc && (resultfpc != PM3_SUCCESS)) { return resultfpc; } +#endif +#if defined(WITH_CEP) + if (g_reply_via_cep && (resultcep != PM3_SUCCESS)) { + return resultcep; + } #endif return PM3_SUCCESS; } @@ -171,7 +215,7 @@ int reply_reason(uint16_t cmd, int8_t status, int8_t reason, const uint8_t *data return reply_ng_internal(cmd, status, reason, data, len, true); } -static int receive_ng_internal(PacketCommandNG *rx, uint32_t read_ng(uint8_t *data, size_t len), bool usb, bool fpc) { +static int receive_ng_internal(PacketCommandNG *rx, uint32_t read_ng(uint8_t *data, size_t len), bool usb, bool fpc, bool cep) { PacketCommandNGRaw rx_raw; size_t bytes = read_ng((uint8_t *)&rx_raw.pre, sizeof(PacketCommandNGPreamble)); @@ -181,6 +225,7 @@ static int receive_ng_internal(PacketCommandNG *rx, uint32_t read_ng(uint8_t *da } if (bytes != sizeof(PacketCommandNGPreamble)) { + if (cep) cep_spi_resync(); return PM3_EIO; } @@ -192,21 +237,52 @@ static int receive_ng_internal(PacketCommandNG *rx, uint32_t read_ng(uint8_t *da if (rx->magic == COMMANDNG_PREAMBLE_MAGIC) { // New style NG command if (length > PM3_CMD_DATA_SIZE) { + if (cep) cep_spi_resync(); return PM3_EOVFLOW; } // Get the core and variable length payload bytes = read_ng((uint8_t *)&rx_raw.data, length); if (bytes != length) { + if (cep) cep_spi_resync(); return PM3_EIO; } + // Get the postamble + bytes = read_ng((uint8_t *)&rx_raw.foopost, sizeof(PacketCommandNGPostamble)); + if (bytes != sizeof(PacketCommandNGPostamble)) { + if (cep) cep_spi_resync(); + return PM3_EIO; + } + + // Check CRC, accept MAGIC as placeholder - a mismatch here is the + // AT32 errata's own recommended trigger to reset SPI (see + // cep_spi_resync()'s comment). + rx->crc = rx_raw.foopost.crc; + if (rx->crc != COMMANDNG_POSTAMBLE_MAGIC) { + uint8_t first, second; + compute_crc(CRC_14443_A, (uint8_t *)&rx_raw, sizeof(PacketCommandNGPreamble) + length, &first, &second); + if ((first << 8) + second != rx->crc) { + if (cep) cep_spi_resync(); + return PM3_EIO; + } + } + + // Zero the payload only once a packet is really coming in, and only + // after all wire reads: CEP's SPI receiver has no FIFO, so a stall + // between reads (this memset touches up to PM3_CMD_DATA_SIZE bytes) + // loses data. Both branches leave the tail of data untouched -- an + // NG command fills only its own length, an old style one only + // PM3_CMD_DATA_SIZE_OLD -- so what is not written has to start zero. + memset(&rx->data, 0, sizeof(rx->data)); + if (rx->ng) { memcpy(rx->data.asBytes, rx_raw.data, length); rx->length = length; } else { uint64_t arg[3] = {0}; if (length < sizeof(arg)) { + if (cep) cep_spi_resync(); return PM3_EIO; } @@ -218,24 +294,9 @@ static int receive_ng_internal(PacketCommandNG *rx, uint32_t read_ng(uint8_t *da rx->length = length - sizeof(arg); } - // Get the postamble - bytes = read_ng((uint8_t *)&rx_raw.foopost, sizeof(PacketCommandNGPostamble)); - if (bytes != sizeof(PacketCommandNGPostamble)) { - return PM3_EIO; - } - - // Check CRC, accept MAGIC as placeholder - rx->crc = rx_raw.foopost.crc; - if (rx->crc != COMMANDNG_POSTAMBLE_MAGIC) { - uint8_t first, second; - compute_crc(CRC_14443_A, (uint8_t *)&rx_raw, sizeof(PacketCommandNGPreamble) + length, &first, &second); - if ((first << 8) + second != rx->crc) { - return PM3_EIO; - } - } - g_reply_via_usb = usb; g_reply_via_fpc = fpc; + g_reply_via_cep = cep; } else { // Old style command PacketCommandOLD rx_old; @@ -247,6 +308,7 @@ static int receive_ng_internal(PacketCommandNG *rx, uint32_t read_ng(uint8_t *da g_reply_via_usb = usb; g_reply_via_fpc = fpc; + g_reply_via_cep = cep; rx->ng = false; rx->magic = 0; rx->crc = 0; @@ -255,34 +317,34 @@ static int receive_ng_internal(PacketCommandNG *rx, uint32_t read_ng(uint8_t *da rx->oldarg[1] = rx_old.arg[1]; rx->oldarg[2] = rx_old.arg[2]; rx->length = PM3_CMD_DATA_SIZE_OLD; + memset(&rx->data, 0, sizeof(rx->data)); memcpy(&rx->data, &rx_old.d.asBytes, rx->length); } return PM3_SUCCESS; } -// TODO DXL 临时在此处定义外部实现的CEP端口的SPI通信实现,做视频通信测试用的,后期需要重构设计 -// extern uint32_t cep_spi_read_ng(uint8_t *data, size_t len); -// extern bool cep_spi_data_available(void); - int receive_ng(PacketCommandNG *rx) { // Check if there is a packet available if (usb_poll_validate_length()) { - return receive_ng_internal(rx, usb_read_ng, true, false); + return receive_ng_internal(rx, usb_read_ng, true, false, false); } - // if (cep_spi_data_available()) { - // return receive_ng_internal(rx, cep_spi_read_ng, false, true); // TODO DXL 临时用fpc这种标志 - // } +#if defined(WITH_CEP) + // cep_is_active() gates this so an unattached/idle CEP link doesn't cost + // an SPI-timeout poll every single main-loop iteration. + if (cep_is_active() && cep_spi_data_available()) + return receive_ng_internal(rx, cep_spi_read_ng, false, false, true); +#endif #if defined(WITH_BWM_FORWARD) // De-frame inbound BWM app_com DATA_FORWARD packets into a raw NG stream. if (bwm_fwd_rxdata_available() > 0) - return receive_ng_internal(rx, bwm_read_ng, false, true); + return receive_ng_internal(rx, bwm_read_ng, false, true, false); #elif defined(WITH_FPC_USART_HOST) // Check if there is a FPC packet available if (usart_rxdata_available() > 0) - return receive_ng_internal(rx, usart_read_ng, false, true); + return receive_ng_internal(rx, usart_read_ng, false, true, false); #endif return PM3_ENODATA; } diff --git a/armsrc/desfire_crypto.c b/armsrc/desfire_crypto.c index afe66345e..5cf71d29d 100644 --- a/armsrc/desfire_crypto.c +++ b/armsrc/desfire_crypto.c @@ -335,6 +335,9 @@ void cmac(const desfirekey_t key, uint8_t *ivect, const uint8_t *data, size_t le } uint8_t *buffer = BigBuf_calloc(padded_data_length(len, kbs)); + if (buffer == NULL) { + return; + } memcpy(buffer, data, len); diff --git a/armsrc/desfiresim.c b/armsrc/desfiresim.c new file mode 100644 index 000000000..bbe3304aa --- /dev/null +++ b/armsrc/desfiresim.c @@ -0,0 +1,4162 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// MIFARE DESFire tag simulation. +// +// Serves the card image `hf mfdes eload` put in emulator memory. The layout is +// in include/desfire_em.h; nothing here parses json or knows about files on the +// host, it only walks that image. +// +// This file is the DESFire half only. Anticollision, RATS, framing and timing +// are SimulateIso14443aTag()'s job over in iso14443a.c, which activates tag +// type 3 from the identity in the image and hands every ISO 14443-4 I-block to +// desfire_sim_apdu(). Duplicating that loop here got the ATQA wrong and would +// have kept drifting from the one that is exercised by every other tag type. +// +// Two timing regimes, and they want opposite things: +// +// - Before RATS there is no negotiated frame waiting time, and a tag that +// encodes its answer inside the response window is late. ATQA, the UID +// cascades, SAK and ATS are therefore precompiled by SimulateIso14443aInit() +// exactly as every other 14a simulation does. +// +// - After RATS the EV1 ATS asks for FWI 8, which is 77.33 ms, about 3.7 +// million ARM cycles. Everything from SelectApplication onward is computed +// on demand from the image. A software AES block costs a fraction of a +// percent of that, so there is no reason to precompute answers and every +// reason not to: a precomputed card cannot answer a write. +// +// What is implemented so far is the unauthenticated half: a reader can find the +// card, read its version, enumerate applications and files, and read file +// settings. Anything else answers ILLEGAL_COMMAND_CODE, which is what a real +// PICC says to a command it does not have. +//----------------------------------------------------------------------------- + +#include "desfiresim.h" + +#include "string.h" +#include "proxmark3_arm.h" +#include "cmd.h" +#include "appmain.h" +#include "BigBuf.h" +#include "dbprint.h" +#include "util.h" +#include "iso14443a.h" +#include "crc16.h" +#include "crc32.h" +#include "crc.h" +#include "commonutil.h" +#include "fpga_apis.h" +#include "fpga_loader.h" +#include "rssi_apis.h" +#include "ticks_apis.h" +#include "protocols.h" +#include "desfire_em.h" +#include "desfire_crypto.h" + +#define DESFIRE_CRC32_POLY 0xEDB88320 + +// ISO 7816 wrapping of the DESFire command set: class byte on the way in, +// first status byte on the way back. +#define DESFIRE_SIM_ISO7816_CLA 0x90 +#define DESFIRE_SIM_ISO7816_SW1 0x91 + +// Largest answer built before the 14443-4 prologue and CRC are added. +// GetApplicationIDs on a full PICC is 28 * 3 bytes plus a status byte. +#define DESFIRE_SIM_MAX_RESP 128 + +// Largest write gathered across chained frames, header and secure messaging +// included. A reader that asks to write more than this in one command is +// refused rather than served a truncated write. +#define DESFIRE_SIM_WRITE_MAX 272 + + +typedef struct { + const desfire_em_hdr_t *hdr; + const desfire_em_app_t *apps; + const desfire_em_file_t *files; + const desfire_em_key_t *keys; + const uint8_t *base; + + int selected; // index into apps[], -1 when nothing is selected + uint8_t chain_cmd; // command being continued over 0xAF, 0 when none + uint8_t chain_step; // which frame of it comes next + + // ---- a read being handed out over several frames + // GetVersion and GetDFNames step through fixed records and only need + // chain_step. A file read has to remember where in the file it is, which + // file, and the mode the first frame settled on -- the access rights are + // evaluated once, when the command arrives, not again per frame. + int16_t chain_file; // index into files[], -1 when none + uint32_t chain_base; // where the read starts inside the file + uint32_t chain_datalen; // how many bytes of it the reader asked for + uint32_t chain_off; // position in the stream being handed out + uint32_t chain_end; // its total length + uint8_t chain_comm; // effective comm mode for the whole transfer + uint8_t chain_crc[4]; // CRC of an enciphered read, computed up front + uint8_t chain_crclen; // 4 for CRC32, 2 for the legacy CRC16 + + // ---- authentication + // auth_cmd is the handshake in flight, 0 when none. The second frame + // arrives as 0xAF, so the command has to be remembered across it. + uint8_t auth_cmd; + uint8_t auth_keynum; + uint8_t rndb[16]; + uint8_t rndlen; + uint8_t iv[16]; // runs through the handshake, then the session + struct desfire_key authkey; + + bool authenticated; + bool legacy; // the session came from 0x0A: DES MAC, CRC16, zero IVs + uint8_t auth_keyno; // the key number we authenticated with + struct desfire_key sesskey; + + // The session CMAC is taken a piece at a time, so up to one block of the + // message is held back between calls -- see desfire_sim_cmac_update(). + uint8_t cmac_pend[DESFIRE_MAX_CRYPTO_BLOCK_SIZE]; + uint8_t cmac_pendlen; + + // ---- a write being gathered over several frames + // A write is secured as one message, so none of it can be acted on until + // the last frame is in: the MAC covers the whole thing, and an enciphered + // write carries one CRC32 at the end of the lot. + uint8_t wbuf[DESFIRE_SIM_WRITE_MAX]; + uint16_t wlen; + uint16_t wexpect; // bytes the command says it is, 0 until known + uint8_t wcmd; // the command being gathered, 0 when none +} desfire_sim_state_t; + +// The simulation runs one card at a time, and the 14a loop calls in here from +// several places, so the state is a file static rather than something the +// caller has to carry around. +static desfire_sim_state_t s_st; +static bool s_ready = false; + +// ---------------------------------------------------------------- image walk + +static bool desfire_sim_load(desfire_sim_state_t *st) { + + const uint8_t *em = BigBuf_get_EM_addr(); + if (em == NULL) { + return false; + } + + const desfire_em_hdr_t *hdr = (const desfire_em_hdr_t *)em; + + if (hdr->magic != DESFIRE_EM_MAGIC) { + // Not an error: `hf 14a sim -t 3` with nothing loaded is a legitimate + // bare PICC that answers the anticollision and nothing else. The caller + // says so once, rather than this firing on every activation. + if (g_dbglevel >= DBG_EXTENDED) { + Dbprintf("No DESFire card image in emulator memory, magic is " _YELLOW_("%08x"), hdr->magic); + } + return false; + } + + if (hdr->layout != DESFIRE_EM_LAYOUT_VERSION) { + Dbprintf("Card image layout v%u, this firmware speaks v%u", hdr->layout, DESFIRE_EM_LAYOUT_VERSION); + return false; + } + + if (hdr->size > BigBuf_get_EM_size() || hdr->appcount == 0) { + Dbprintf("Card image does not fit the emulator memory it was loaded into"); + return false; + } + + st->base = em; + st->hdr = hdr; + st->apps = (const desfire_em_app_t *)(em + hdr->app_off); + st->files = (const desfire_em_file_t *)(em + hdr->file_off); + st->keys = (const desfire_em_key_t *)(em + hdr->key_off); + st->selected = 0; // a PICC comes up with AID 000000 selected + st->chain_cmd = 0; + st->chain_step = 0; + st->chain_file = -1; + return true; +} + +static uint32_t desfire_sim_aid(const desfire_em_app_t *a) { + return a->aid[0] | (a->aid[1] << 8) | (a->aid[2] << 16); +} + +static int desfire_sim_find_app(const desfire_sim_state_t *st, uint32_t aid) { + + for (uint8_t i = 0; i < st->hdr->appcount; i++) { + if ((st->apps[i].flags & DESFIRE_EM_APP_DELETED) == 0 && desfire_sim_aid(&st->apps[i]) == aid) { + return i; + } + } + return -1; +} + +// --------------------------------------------------------------- the answers + +// Build one DESFire answer: a status byte and optional payload. Returns the +// length written to `out`. +static uint16_t desfire_sim_status(uint8_t *out, uint8_t status) { + out[0] = status; + return 1; +} + +static uint16_t desfire_sim_payload(uint8_t *out, uint8_t status, const uint8_t *data, uint16_t len) { + out[0] = status; + if (len) { + memcpy(out + 1, data, len); + } + return len + 1; +} + +// ------------------------------------------------------------ authentication + +// Fixed tag nonce, the same approach the UL-C simulation takes. It makes a +// session reproducible, which is useful for testing, and means the simulation +// is replayable -- it is a simulation of a card, not a secure one. +static const uint8_t s_sim_rndb[16] = { + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 +}; + +#ifdef ENABLE_HFMFDESETEST +// Random bytes queued by the host, see `hf mfdes etest --random`. A byte +// stream, not blocks: RndB draws 8 or 16, a random id 3. Outside s_st because +// desfire_sim_init() wipes that at every activation. +static struct { + uint8_t buf[DESFIRE_SIM_TEST_RANDOM_MAX]; + uint8_t head; + uint8_t len; + bool underflow; // sticky: a draw wanted more than was queued +} s_rnd; + +static void desfire_sim_random_clear(void) { + memset(&s_rnd, 0, sizeof(s_rnd)); +} + +static bool desfire_sim_random_push(const uint8_t *src, uint16_t len) { + + if (len == 0 || len > sizeof(s_rnd.buf) - s_rnd.len) { + return false; + } + + if (s_rnd.head) { + memmove(s_rnd.buf, s_rnd.buf + s_rnd.head, s_rnd.len); + s_rnd.head = 0; + } + + memcpy(s_rnd.buf + s_rnd.len, src, len); + s_rnd.len += len; + return true; +} +#endif + +// A short queue gives nothing, so a half value never desynchronises the rest. +static bool desfire_sim_random(uint8_t *dst, uint8_t len) { + +#ifdef ENABLE_HFMFDESETEST + if (s_rnd.len < len) { + s_rnd.underflow = true; + return false; + } + + memcpy(dst, s_rnd.buf + s_rnd.head, len); + s_rnd.head += len; + s_rnd.len -= len; + return true; +#else + (void)dst; + (void)len; + return false; +#endif +} + +// rotate left by one byte, the RndA/RndB' transform of the handshake +static void desfire_sim_rol(uint8_t *data, uint8_t len) { + if (len < 2) { + return; + } + uint8_t first = data[0]; + memmove(data, data + 1, len - 1); + data[len - 1] = first; +} + +// The key material for (application, key number), or NULL when the image does +// not hold it. A key we only know the version of cannot authenticate: the +// image format keeps DESFIRE_EM_KEY_PRESENT apart from DESFIRE_EM_KEY_VERKNOWN +// exactly so a simulation refuses rather than authenticating with zeros. +static const desfire_em_key_t *desfire_sim_find_key(const desfire_sim_state_t *st, uint8_t app, uint8_t keyno) { + + for (uint16_t i = 0; i < st->hdr->keycount; i++) { + const desfire_em_key_t *k = &st->keys[i]; + if (k->app == app && k->num == keyno) { + return (k->flags & DESFIRE_EM_KEY_PRESENT) ? k : NULL; + } + } + return NULL; +} + +// Build a crypto key of the application's algorithm from stored key material. +// +// DES and 2K3DES keys are both stored as 16 bytes and the key itself decides +// which one the PICC uses: "If the 2nd half of the key string is equal to the +// 1st half, the key is handled as a single DES key by the PICC" (M134034 8.1). +// The all zero default key is the common case of that. It matters well beyond +// the cipher, because the same rule governs session key generation -- so a card +// that skips it authenticates fine, then MACs every later frame with a key the +// reader does not have. The comparison is over the stored bytes including the +// version bits, which is why it is done here rather than after any constructor +// that clears them. +static void desfire_sim_make_key(struct desfire_key *out, uint8_t algo, const uint8_t *value) { + + memset(out, 0, sizeof(*out)); + switch (algo) { + case T_DES: + Desfire_des_key_new(value, out); + break; + case T_3DES: + if (memcmp(value, value + 8, 8) == 0) { + Desfire_des_key_new(value, out); + } else { + Desfire_3des_key_new(value, out); + } + break; + case T_3K3DES: + Desfire_3k3des_key_new(value, out); + break; + case T_AES: + default: + Desfire_aes_key_new(value, out); + break; + } +} + +// Derive the session key from the two nonces. +// +// This does not call the tree's Desfire_session_key_new(): its 3K3DES branch +// passes the result through Desfire_3k3des_key_new(), which clears the low bit +// of the first eight bytes. In a stored key those bits carry the key version, +// but a session key has no version and the reader keeps the derived bytes as +// they are -- clearing them here would leave the two sides MACing under +// different keys. The layouts themselves are M134034 7.3.8. +static void desfire_sim_session_key(desfire_sim_state_t *st, const uint8_t *rnda, const uint8_t *rndb) { + + uint8_t buf[24] = {0}; + + switch (st->authkey.type) { + + case T_DES: + memcpy(buf, rnda, 4); + memcpy(buf + 4, rndb, 4); + Desfire_des_key_new_with_version(buf, &st->sesskey); + break; + + case T_3DES: + memcpy(buf, rnda, 4); + memcpy(buf + 4, rndb, 4); + memcpy(buf + 8, rnda + 4, 4); + memcpy(buf + 12, rndb + 4, 4); + Desfire_3des_key_new_with_version(buf, &st->sesskey); + break; + + case T_3K3DES: + memcpy(buf, rnda, 4); + memcpy(buf + 4, rndb, 4); + memcpy(buf + 8, rnda + 6, 4); + memcpy(buf + 12, rndb + 6, 4); + memcpy(buf + 16, rnda + 12, 4); + memcpy(buf + 20, rndb + 12, 4); + Desfire_3k3des_key_new_with_version(buf, &st->sesskey); + break; + + case T_AES: + default: + memcpy(buf, rnda, 4); + memcpy(buf + 4, rndb, 4); + memcpy(buf + 8, rnda + 12, 4); + memcpy(buf + 12, rndb + 12, 4); + Desfire_aes_key_new(buf, &st->sesskey); + break; + } +} + +// One CBC block chain in either direction, picking the cipher from the key. +static void desfire_sim_crypt(struct desfire_key *key, const uint8_t *in, uint8_t *out, + uint16_t len, uint8_t *iv, bool encrypt) { + + if (key->type == T_AES) { + if (encrypt) { + aes128_nxp_send(in, out, len, key->data, iv); + } else { + aes128_nxp_receive(in, out, len, key->data, iv); + } + return; + } + + // 2 key or 3 key triple DES; a single DES key is stored doubled + int keymode = (key->type == T_3K3DES) ? 3 : 2; + if (encrypt) { + tdes_nxp_send(in, out, len, key->data, iv, keymode); + } else { + tdes_nxp_receive(in, out, len, key->data, iv, keymode); + } +} + +// Undo a 0x0A reader token. In the legacy scheme the PICC only ever +// enciphers, so each block is enciphered and xored with the previous +// ciphertext block, from a zero IV. The reader built it the other way round. +static void desfire_sim_d40_receive(struct desfire_key *key, const uint8_t *in, uint8_t *out, uint16_t len) { + + uint8_t prev[8] = {0}; + + for (uint16_t off = 0; off + 8 <= len; off += 8) { + uint8_t block[8]; + uint8_t iv[8] = {0}; + memcpy(block, in + off, sizeof(block)); + desfire_sim_crypt(key, block, out + off, sizeof(block), iv, true); + for (uint8_t i = 0; i < sizeof(block); i++) { + out[off + i] ^= prev[i]; + } + memcpy(prev, in + off, sizeof(prev)); + } +} + +// How long the challenge is for a given algorithm. +static uint8_t desfire_sim_rndlen(uint8_t algo) { + return (algo == T_AES || algo == T_3K3DES) ? 16 : 8; +} + +// Drop any authenticated session. SelectApplication does this, and so does any +// command the PICC answers with an error. +static void desfire_sim_auth_clear(desfire_sim_state_t *st) { + st->auth_cmd = 0; + st->authenticated = false; + st->legacy = false; + st->auth_keyno = 0; + st->cmac_pendlen = 0; + memset(st->cmac_pend, 0, sizeof(st->cmac_pend)); + memset(st->iv, 0, sizeof(st->iv)); + memset(&st->sesskey, 0, sizeof(st->sesskey)); + memset(&st->authkey, 0, sizeof(st->authkey)); +} + +// First frame of the handshake: pick the key, answer with E(RndB). +static uint16_t desfire_sim_auth_start(desfire_sim_state_t *st, uint8_t cmd, + const uint8_t *in, uint16_t inlen, uint8_t *out) { + + if (inlen < 1) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + uint8_t keyno = in[0] & 0x0F; + const desfire_em_app_t *app = &st->apps[st->selected]; + + if (keyno >= (app->numkeysraw & 0x0F) && keyno != 0) { + return desfire_sim_status(out, MFDES_E_NO_SUCH_KEY); + } + + const desfire_em_key_t *k = desfire_sim_find_key(st, st->selected, keyno); + if (k == NULL) { + // we do not hold this key, so we cannot play the other half + if (g_dbglevel >= DBG_EXTENDED) { + Dbprintf("DESFire sim: no key %u for app index %d in the image", keyno, st->selected); + } + return desfire_sim_status(out, MFDES_E_AUTHENTICATION_ERROR); + } + + // the command has to match the application's key algorithm + uint8_t algo = app->keytype; + bool ok = ((cmd == MFDES_AUTHENTICATE && (algo == T_DES || algo == T_3DES)) || + (cmd == MFDES_AUTHENTICATE_ISO && (algo == T_DES || algo == T_3DES || algo == T_3K3DES)) || + (cmd == MFDES_AUTHENTICATE_AES && algo == T_AES)); + if (ok == false) { + return desfire_sim_status(out, MFDES_E_AUTHENTICATION_ERROR); + } + + desfire_sim_auth_clear(st); + desfire_sim_make_key(&st->authkey, algo, k->key); + + st->rndlen = desfire_sim_rndlen(algo); + if (desfire_sim_random(st->rndb, st->rndlen) == false) { + memcpy(st->rndb, s_sim_rndb, st->rndlen); + } + + // tdes_nxp_send() casts away const and XORs the IV into its *input* buffer, + // so anything handed to it is destroyed. With a zero IV and a single block + // that is a no-op, which is why 2TDEA survives it, but a 16 byte challenge + // is two blocks and the second one corrupts the stored RndB. Encrypt a copy. + uint8_t plain[16] = {0}; + uint8_t encrndb[16] = {0}; + memcpy(plain, st->rndb, st->rndlen); + memset(st->iv, 0, sizeof(st->iv)); + desfire_sim_crypt(&st->authkey, plain, encrndb, st->rndlen, st->iv, true); + + st->auth_cmd = cmd; + st->auth_keynum = keyno; + return desfire_sim_payload(out, MFDES_ADDITIONAL_FRAME, encrndb, st->rndlen); +} + +// Second frame: E(RndA || RndB'). Check RndB', answer E(RndA') and derive the +// session key. +static uint16_t desfire_sim_auth_finish(desfire_sim_state_t *st, const uint8_t *in, uint16_t inlen, uint8_t *out) { + + uint16_t want = st->rndlen * 2; + if (inlen < want) { + desfire_sim_auth_clear(st); + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + uint8_t both[32] = {0}; + if (st->auth_cmd == MFDES_AUTHENTICATE) { + desfire_sim_d40_receive(&st->authkey, in, both, want); + } else { + desfire_sim_crypt(&st->authkey, in, both, want, st->iv, false); + } + + const uint8_t *rnda = both; + const uint8_t *rndbprime = both + st->rndlen; + + uint8_t expect[16] = {0}; + memcpy(expect, st->rndb, st->rndlen); + desfire_sim_rol(expect, st->rndlen); + + if (memcmp(expect, rndbprime, st->rndlen) != 0) { + // the reader does not hold the key + desfire_sim_auth_clear(st); + return desfire_sim_status(out, MFDES_E_AUTHENTICATION_ERROR); + } + + uint8_t rndaprime[16] = {0}; + memcpy(rndaprime, rnda, st->rndlen); + desfire_sim_rol(rndaprime, st->rndlen); + + // a 0x0A cryptogram starts from a zero IV, nothing chains across frames + if (st->auth_cmd == MFDES_AUTHENTICATE) { + memset(st->iv, 0, sizeof(st->iv)); + } + + uint8_t encrndaprime[16] = {0}; + desfire_sim_crypt(&st->authkey, rndaprime, encrndaprime, st->rndlen, st->iv, true); + + // session key, and the CMAC subkeys the MACed mode will need + desfire_sim_session_key(st, rnda, st->rndb); + cmac_generate_subkeys(&st->sesskey); + + st->authenticated = true; + st->legacy = (st->auth_cmd == MFDES_AUTHENTICATE); + st->auth_keyno = st->auth_keynum; + st->auth_cmd = 0; + memset(st->iv, 0, sizeof(st->iv)); + + if (g_dbglevel >= DBG_EXTENDED) { + Dbprintf("DESFire sim: authenticated app index %d key %u", st->selected, st->auth_keyno); + } + + return desfire_sim_payload(out, MFDES_S_OPERATION_OK, encrndaprime, st->rndlen); +} + +// ---------------------------------------------------------- secure messaging + +// EV1 file communication modes, the raw 2 bit field of the file settings. +#define DESFIRE_SIM_COMM_PLAIN 0x00 +#define DESFIRE_SIM_COMM_MACED 0x01 +#define DESFIRE_SIM_COMM_PLAIN2 0x02 // a second plain encoding, EV1 9.3.1 +#define DESFIRE_SIM_COMM_FULL 0x03 + +// Access rights are four nibbles in one word: read, write, read-write and +// change, from the top down. 0x0E grants everyone, 0x0F denies everyone, and +// anything else names the key that has to be authenticated. +#define DESFIRE_SIM_AR_READ(r) (((r) >> 12) & 0x0F) +#define DESFIRE_SIM_AR_WRITE(r) (((r) >> 8) & 0x0F) +#define DESFIRE_SIM_AR_RW(r) (((r) >> 4) & 0x0F) +#define DESFIRE_SIM_AR_CHANGE(r) ((r) & 0x0F) + +#define DESFIRE_SIM_AR_FREE 0x0E +#define DESFIRE_SIM_AR_DENY 0x0F + +// Does this access right let the current session through? `keyed` is set when +// it was a key that granted it rather than free access, which the caller needs +// to pick the communication mode -- see desfire_sim_eff_comm(). +static bool desfire_sim_right_ok(const desfire_sim_state_t *st, uint8_t right, bool *keyed) { + + if (right == DESFIRE_SIM_AR_DENY) { + return false; + } + + if (right == DESFIRE_SIM_AR_FREE) { + return true; + } + + if (st->authenticated && st->auth_keyno == right) { + *keyed = true; + return true; + } + + return false; +} + +// The mode a file operation actually runs in. +// +// Measured on a DESFire EV2 2K, and the same on the ev1 channel: the PICC +// applies the file's communication mode only when a key right matching the +// authenticated key granted the operation. When free access (0x0E) granted it +// instead, the transfer is plain whatever the file settings say. Free access +// alone is not the trigger -- a keyed right that matches wins, so both rights +// have to be evaluated before deciding. +static bool desfire_sim_eff_comm(const desfire_sim_state_t *st, const desfire_em_file_t *f, + bool write, uint8_t *comm) { + + uint16_t r = f->rights; + bool keyed = false; + + // read and write are each granted by their own right or by read-write + bool a = desfire_sim_right_ok(st, write ? DESFIRE_SIM_AR_WRITE(r) : DESFIRE_SIM_AR_READ(r), &keyed); + bool b = desfire_sim_right_ok(st, DESFIRE_SIM_AR_RW(r), &keyed); + + if ((a || b) == false) { + return false; + } + + *comm = keyed ? (f->flags & DESFIRE_EM_FILE_COMM_MASK) : DESFIRE_SIM_COMM_PLAIN; + return true; +} + +// GetValue, Debit and LimitedCredit are granted by any of the three rights, +// Credit by read-write alone -- measured, EV1 9.5.6. The FreeValue option bit +// forces GetValue plain whatever the rights say. +static bool desfire_sim_value_comm(const desfire_sim_state_t *st, const desfire_em_file_t *f, + bool creditonly, uint8_t *comm) { + + uint16_t r = f->rights; + bool keyed = false; + bool ok; + + if (creditonly) { + ok = desfire_sim_right_ok(st, DESFIRE_SIM_AR_RW(r), &keyed); + } else { + bool a = desfire_sim_right_ok(st, DESFIRE_SIM_AR_READ(r), &keyed); + bool b = desfire_sim_right_ok(st, DESFIRE_SIM_AR_WRITE(r), &keyed); + bool c = desfire_sim_right_ok(st, DESFIRE_SIM_AR_RW(r), &keyed); + ok = (a || b || c); + } + + if (ok == false) { + return false; + } + + if ((creditonly == false) && (f->flags & DESFIRE_EM_FILE_FREEGETVAL)) { + *comm = DESFIRE_SIM_COMM_PLAIN; + return true; + } + + *comm = keyed ? (f->flags & DESFIRE_EM_FILE_COMM_MASK) : DESFIRE_SIM_COMM_PLAIN; + return true; +} + +// The session CMAC, taken a piece at a time. +// +// Two reasons it streams rather than taking a buffer. The tree's cmac() draws +// its scratch from BigBuf and never hands it back, which is fine for the +// one-shot reader path it was written for but would drain the buffer a block at +// a time over a session. And a chained read is MACed over the whole transfer, +// not per frame -- the client joins every frame and verifies once -- so the +// data is only ever seen in pieces and can be several hundred bytes in total. +// +// CMAC is CBC-MAC with the final block treated differently, so a complete block +// is only pushed through the chain once something is known to follow it. That +// leaves between 1 and one block of data pending at all times. + +static void desfire_sim_cmac_reset(desfire_sim_state_t *st) { + st->cmac_pendlen = 0; + memset(st->cmac_pend, 0, sizeof(st->cmac_pend)); +} + +static void desfire_sim_cmac_update(desfire_sim_state_t *st, const uint8_t *data, uint32_t len) { + + size_t kbs = key_block_size(&st->sesskey); + if (kbs == 0 || kbs > sizeof(st->cmac_pend)) { + return; + } + + while (len > 0) { + + // Being here with a full block held means more data follows it, so it + // is not the last block and can go through the chain now. Flushing at + // the top rather than the bottom is what makes a second call safe: the + // previous one returns with a full block pending whenever the data it + // was given filled one exactly, and consuming that first is the only + // way this loop makes progress. + if (st->cmac_pendlen == kbs) { + mifare_cypher_blocks_chained(NULL, &st->sesskey, st->iv, st->cmac_pend, kbs, MCD_SEND, MCO_ENCYPHER); + st->cmac_pendlen = 0; + } + + uint32_t room = kbs - st->cmac_pendlen; + uint32_t n = (len < room) ? len : room; + + memcpy(st->cmac_pend + st->cmac_pendlen, data, n); + st->cmac_pendlen += n; + data += n; + len -= n; + } +} + +static void desfire_sim_cmac_final(desfire_sim_state_t *st, uint8_t *mac) { + + size_t kbs = key_block_size(&st->sesskey); + if (kbs == 0 || kbs > sizeof(st->cmac_pend)) { + return; + } + + // a message that is a whole number of blocks takes the first subkey, one + // that has to be padded takes the second + if (st->cmac_pendlen == kbs) { + xor(st->cmac_pend, st->sesskey.cmac_sk1, kbs); + } else { + st->cmac_pend[st->cmac_pendlen++] = 0x80; + while (st->cmac_pendlen < kbs) { + st->cmac_pend[st->cmac_pendlen++] = 0x00; + } + xor(st->cmac_pend, st->sesskey.cmac_sk2, kbs); + } + + mifare_cypher_blocks_chained(NULL, &st->sesskey, st->iv, st->cmac_pend, kbs, MCD_SEND, MCO_ENCYPHER); + memcpy(mac, st->iv, kbs); + desfire_sim_cmac_reset(st); +} + +// ---- the legacy session, after a 0x0A authentication +// +// Its MAC is DES CBC under the session key from a zero IV over the data zero +// padded to whole blocks, the first four bytes of the last block. Taken in +// pieces like the CMAC, since a chained read is one MAC. Nothing carries over +// between commands, so there is no IV to keep in step. +static void desfire_sim_lmac_reset(desfire_sim_state_t *st) { + st->cmac_pendlen = 0; + memset(st->cmac_pend, 0, sizeof(st->cmac_pend)); + memset(st->iv, 0, sizeof(st->iv)); +} + +static void desfire_sim_lmac_update(desfire_sim_state_t *st, const uint8_t *data, uint32_t len) { + + while (len > 0) { + uint32_t room = 8 - st->cmac_pendlen; + uint32_t n = (len < room) ? len : room; + memcpy(st->cmac_pend + st->cmac_pendlen, data, n); + st->cmac_pendlen += n; + data += n; + len -= n; + + if (st->cmac_pendlen == 8) { + desfire_sim_crypt(&st->sesskey, st->cmac_pend, st->cmac_pend, 8, st->iv, true); + st->cmac_pendlen = 0; + } + } +} + +static void desfire_sim_lmac_final(desfire_sim_state_t *st, uint8_t *mac) { + + if (st->cmac_pendlen) { + memset(st->cmac_pend + st->cmac_pendlen, 0, 8 - st->cmac_pendlen); + desfire_sim_crypt(&st->sesskey, st->cmac_pend, st->cmac_pend, 8, st->iv, true); + } + memcpy(mac, st->iv, DESFIRE_MAC_LENGTH); + desfire_sim_lmac_reset(st); +} + +// the legacy modes use ISO 14443-A's CRC16, low byte first +static void desfire_sim_crc16(const uint8_t *data, uint16_t len, uint8_t *out) { + compute_crc(CRC_14443_A, data, len, out, out + 1); +} + +// The session CMAC runs over every command and every response, in order, so it +// has to be taken even when neither side puts it on the wire -- skipping one +// leaves the two IVs apart and every later MAC is wrong. This is the command +// half: `cmd` followed by its parameters, exactly as they arrived. +static void desfire_sim_cmac_command(desfire_sim_state_t *st, uint8_t cmd, const uint8_t *in, uint16_t inlen) { + + if (st->authenticated == false || st->legacy) { + return; + } + + uint8_t mac[DESFIRE_MAX_CRYPTO_BLOCK_SIZE] = {0}; + desfire_sim_cmac_reset(st); + desfire_sim_cmac_update(st, &cmd, 1); + desfire_sim_cmac_update(st, in, inlen); + desfire_sim_cmac_final(st, mac); +} + +// The response half: the CMAC covers the payload followed by the status byte, +// and its first 8 bytes are appended to the answer. An EV1 session MACs the +// response even for a plain transfer, which is why this is not conditional on +// the file's communication mode. +static uint16_t desfire_sim_maced(desfire_sim_state_t *st, uint8_t *out, uint8_t status, + const uint8_t *data, uint16_t len) { + + // a legacy session puts nothing on a plain answer + if (st->authenticated == false || st->legacy) { + return desfire_sim_payload(out, status, data, len); + } + + uint8_t mac[DESFIRE_MAX_CRYPTO_BLOCK_SIZE] = {0}; + desfire_sim_cmac_reset(st); + desfire_sim_cmac_update(st, data, len); + desfire_sim_cmac_update(st, &status, 1); + desfire_sim_cmac_final(st, mac); + + out[0] = status; + if (len) { + memcpy(out + 1, data, len); + } + memcpy(out + 1 + len, mac, DESFIRE_CMAC_LENGTH); + return len + 1 + DESFIRE_CMAC_LENGTH; +} + +// A fully enciphered response: plaintext, CRC32 over plaintext and the status +// byte, then zero padding to the block size, all encrypted under the session +// key with the running IV. +static uint16_t desfire_sim_enciphered(desfire_sim_state_t *st, uint8_t *out, uint8_t status, + const uint8_t *data, uint16_t len) { + + size_t kbs = key_block_size(&st->sesskey); + if (kbs == 0) { + return desfire_sim_payload(out, status, data, len); + } + + uint8_t buf[DESFIRE_SIM_MAX_RESP] = {0}; + size_t padded = padded_data_length(len + 4, kbs); + if (padded + 1 > sizeof(buf)) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + // the CRC is taken over the plaintext with the status byte appended, but + // only the plaintext and the CRC itself are sent + uint8_t crcbuf[DESFIRE_SIM_MAX_RESP] = {0}; + if (len) { + memcpy(crcbuf, data, len); + } + crcbuf[len] = status; + crc32_append(crcbuf, len + 1); + + if (len) { + memcpy(buf, data, len); + } + memcpy(buf + len, crcbuf + len + 1, 4); + + out[0] = status; + desfire_sim_crypt(&st->sesskey, buf, out + 1, padded, st->iv, true); + return padded + 1; +} + +// One frame of a chained answer. +// +// Intermediate frames carry no MAC. The client joins every frame of a transfer +// and verifies a single CMAC over the lot, taken against the status byte of the +// last frame, so the data feeds the running CMAC as it goes out and only the +// final frame carries the result. +static uint16_t desfire_sim_chained(desfire_sim_state_t *st, uint8_t *out, bool more, uint8_t comm, + const uint8_t *data, uint16_t len) { + + if (st->authenticated == false) { + return desfire_sim_payload(out, more ? MFDES_ADDITIONAL_FRAME : MFDES_S_OPERATION_OK, data, len); + } + + // a legacy session MACs a MACed transfer, four bytes on the last frame, and + // nothing else + if (st->legacy) { + + if (comm != DESFIRE_SIM_COMM_MACED) { + return desfire_sim_payload(out, more ? MFDES_ADDITIONAL_FRAME : MFDES_S_OPERATION_OK, data, len); + } + + desfire_sim_lmac_update(st, data, len); + + if (more) { + return desfire_sim_payload(out, MFDES_ADDITIONAL_FRAME, data, len); + } + + uint8_t mac[DESFIRE_MAX_CRYPTO_BLOCK_SIZE] = {0}; + desfire_sim_lmac_final(st, mac); + + out[0] = MFDES_S_OPERATION_OK; + if (len) { + memcpy(out + 1, data, len); + } + memcpy(out + 1 + len, mac, DESFIRE_MAC_LENGTH); + return len + 1 + DESFIRE_MAC_LENGTH; + } + + desfire_sim_cmac_update(st, data, len); + + if (more) { + return desfire_sim_payload(out, MFDES_ADDITIONAL_FRAME, data, len); + } + + uint8_t status = MFDES_S_OPERATION_OK; + uint8_t mac[DESFIRE_MAX_CRYPTO_BLOCK_SIZE] = {0}; + desfire_sim_cmac_update(st, &status, 1); + desfire_sim_cmac_final(st, mac); + + out[0] = status; + if (len) { + memcpy(out + 1, data, len); + } + memcpy(out + 1 + len, mac, DESFIRE_CMAC_LENGTH); + return len + 1 + DESFIRE_CMAC_LENGTH; +} + +// Wrap one answer in whatever the transfer's communication mode calls for. +static uint16_t desfire_sim_respond(desfire_sim_state_t *st, uint8_t *out, uint8_t status, + const uint8_t *data, uint16_t len, uint8_t comm) { + + if (st->authenticated && st->legacy) { + + // enciphered: data, CRC16 over it, zero padding, one CBC run from a zero IV + if (comm == DESFIRE_SIM_COMM_FULL) { + + uint8_t buf[DESFIRE_SIM_MAX_RESP] = {0}; + size_t padded = padded_data_length(len + 2, 8); + if (padded + 1 > sizeof(buf)) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + if (len) { + memcpy(buf, data, len); + } + desfire_sim_crc16(buf, len, buf + len); + + memset(st->iv, 0, sizeof(st->iv)); + out[0] = status; + desfire_sim_crypt(&st->sesskey, buf, out + 1, padded, st->iv, true); + return padded + 1; + } + + // MACed: four bytes behind the data, none behind a bare status + if (comm == DESFIRE_SIM_COMM_MACED && len) { + uint8_t mac[DESFIRE_MAX_CRYPTO_BLOCK_SIZE] = {0}; + desfire_sim_lmac_reset(st); + desfire_sim_lmac_update(st, data, len); + desfire_sim_lmac_final(st, mac); + + out[0] = status; + memcpy(out + 1, data, len); + memcpy(out + 1 + len, mac, DESFIRE_MAC_LENGTH); + return len + 1 + DESFIRE_MAC_LENGTH; + } + + return desfire_sim_payload(out, status, data, len); + } + + if (st->authenticated && comm == DESFIRE_SIM_COMM_FULL) { + return desfire_sim_enciphered(st, out, status, data, len); + } + + // plain and MACed are the same on the response side of an EV1 session + return desfire_sim_maced(st, out, status, data, len); +} + +// ------------------------------------------------ the reader's secure messaging + +// How many leading bytes of a command's parameters are the header, the part an +// enciphered command leaves in the clear. Same table the client keeps. +static uint8_t desfire_sim_hdrlen(uint8_t cmd) { + + switch (cmd) { + case MFDES_WRITE_DATA: + case MFDES_WRITE_DATA2: + case MFDES_WRITE_RECORD: + case MFDES_WRITE_RECORD2: + return 7; // file number, 3 byte offset, 3 byte length + case MFDES_UPDATE_RECORD: + case MFDES_UPDATE_RECORD2: + return 10; // and a 3 byte record number on top + case MFDES_CREDIT: + case MFDES_DEBIT: + case MFDES_LIMITED_CREDIT: + case MFDES_GET_VALUE: + case MFDES_CHANGE_FILE_SETTINGS: + case MFDES_CHANGE_KEY: + case MFDES_CHANGE_CONFIGURATION: + return 1; // file, key or option number only + default: + return 0; + } +} + +// Commands the reader puts a MAC on the wire for, when the transfer is MACed. +// Everything else calculates the MAC to move the IV along and sends nothing. +static bool desfire_sim_cmd_macs_request(uint8_t cmd) { + + switch (cmd) { + case MFDES_WRITE_DATA: + case MFDES_WRITE_DATA2: + case MFDES_WRITE_RECORD: + case MFDES_WRITE_RECORD2: + case MFDES_UPDATE_RECORD: + case MFDES_UPDATE_RECORD2: + case MFDES_CREDIT: + case MFDES_DEBIT: + case MFDES_LIMITED_CREDIT: + return true; + default: + return false; + } +} + +// Commands that carry data the reader secured, so they unwrap it themselves +// rather than going through the blanket command CMAC. +static bool desfire_sim_cmd_is_write(uint8_t cmd) { + return (desfire_sim_cmd_macs_request(cmd)); +} + +// The writes gather across frames; ChangeFileSettings arrives whole but is +// enciphered, and either way the command's own handler does the unwrapping and +// moves the IV along, so the blanket CMAC has to keep its hands off. +static bool desfire_sim_cmd_unwraps_own(uint8_t cmd) { + return (desfire_sim_cmd_is_write(cmd) || + cmd == MFDES_CHANGE_FILE_SETTINGS || + cmd == MFDES_CHANGE_KEY_SETTINGS || + cmd == MFDES_CHANGE_CONFIGURATION || + cmd == MFDES_CHANGE_KEY); +} + +// Take the reader's secure messaging off a gathered command. +// +// `buf`/`len` is the command's parameters as they arrived, header included and +// with whatever the transfer's mode added. On success the plain parameters are +// left in place and *len is trimmed to them. The session IV moves on either +// way -- that is the point of calculating a MAC nobody transmits. +static bool desfire_sim_unwrap(desfire_sim_state_t *st, uint8_t cmd, uint8_t comm, + uint8_t *buf, uint16_t *len) { + + uint8_t hdrlen = desfire_sim_hdrlen(cmd); + + if (st->authenticated == false) { + // no session, so nothing was added and nothing can be checked + return (comm != DESFIRE_SIM_COMM_FULL); + } + + if (st->legacy) { + + if (comm == DESFIRE_SIM_COMM_FULL) { + + if (*len < hdrlen) { + return false; + } + + uint16_t enclen = *len - hdrlen; + if (enclen == 0 || (enclen % 8) != 0 || enclen > DESFIRE_SIM_WRITE_MAX) { + return false; + } + + // the reader deciphered it, so the card enciphers it back + uint8_t plain[DESFIRE_SIM_WRITE_MAX] = {0}; + desfire_sim_d40_receive(&st->sesskey, buf + hdrlen, plain, enclen); + memcpy(buf + hdrlen, plain, enclen); + + // CRC16 over the data alone sits behind it, zero padding after it. + // The shortest data whose CRC fits and whose padding is all zero. + for (uint16_t datalen = 0; datalen + 2 <= enclen; datalen++) { + + uint8_t want[2] = {0}; + desfire_sim_crc16(buf + hdrlen, datalen, want); + if (memcmp(want, buf + hdrlen + datalen, 2) != 0) { + continue; + } + + bool zeros = true; + for (uint16_t i = datalen + 2; i < enclen; i++) { + zeros = zeros && (buf[hdrlen + i] == 0); + } + if (zeros) { + *len = hdrlen + datalen; + return true; + } + } + return false; + } + + // MACed: four bytes over the data behind the header + if (comm == DESFIRE_SIM_COMM_MACED && desfire_sim_cmd_macs_request(cmd)) { + + if (*len < hdrlen + DESFIRE_MAC_LENGTH) { + return false; + } + uint16_t plainlen = *len - DESFIRE_MAC_LENGTH; + + uint8_t mac[DESFIRE_MAX_CRYPTO_BLOCK_SIZE] = {0}; + desfire_sim_lmac_reset(st); + desfire_sim_lmac_update(st, buf + hdrlen, plainlen - hdrlen); + desfire_sim_lmac_final(st, mac); + + if (memcmp(mac, buf + plainlen, DESFIRE_MAC_LENGTH) != 0) { + return false; + } + + *len = plainlen; + return true; + } + + // plain carries nothing and nothing has to be kept in step + return true; + } + + if (comm == DESFIRE_SIM_COMM_FULL) { + + size_t kbs = key_block_size(&st->sesskey); + if (kbs == 0 || *len < hdrlen) { + return false; + } + + uint16_t enclen = *len - hdrlen; + if (enclen == 0 || (enclen % kbs) != 0) { + return false; + } + + // the header travels in the clear, the rest is one CBC run + desfire_sim_crypt(&st->sesskey, buf + hdrlen, buf + hdrlen, enclen, st->iv, false); + + // CRC32 covers the command byte, the header and the plain data, and + // sits directly behind the data with zero padding after it. The data + // length is not transmitted, so it is found by trying each candidate. + for (uint16_t datalen = 0; datalen + 4 <= enclen; datalen++) { + + uint8_t crcbuf[DESFIRE_SIM_WRITE_MAX + 8] = {0}; + uint16_t n = 0; + crcbuf[n++] = cmd; + memcpy(crcbuf + n, buf, hdrlen); + n += hdrlen; + memcpy(crcbuf + n, buf + hdrlen, datalen); + n += datalen; + + uint8_t want[4] = {0}; + crc32_ex(crcbuf, n, want); + + if (memcmp(want, buf + hdrlen + datalen, 4) == 0) { + *len = hdrlen + datalen; + return true; + } + } + + return false; + } + + if (comm == DESFIRE_SIM_COMM_MACED && desfire_sim_cmd_macs_request(cmd)) { + + if (*len < DESFIRE_CMAC_LENGTH) { + return false; + } + uint16_t plainlen = *len - DESFIRE_CMAC_LENGTH; + + uint8_t mac[DESFIRE_MAX_CRYPTO_BLOCK_SIZE] = {0}; + desfire_sim_cmac_reset(st); + desfire_sim_cmac_update(st, &cmd, 1); + desfire_sim_cmac_update(st, buf, plainlen); + desfire_sim_cmac_final(st, mac); + + if (memcmp(mac, buf + plainlen, DESFIRE_CMAC_LENGTH) != 0) { + return false; + } + + *len = plainlen; + return true; + } + + // plain inside a session: the MAC is calculated and thrown away, only so + // the next one starts from the right IV + uint8_t mac[DESFIRE_MAX_CRYPTO_BLOCK_SIZE] = {0}; + desfire_sim_cmac_reset(st); + desfire_sim_cmac_update(st, &cmd, 1); + desfire_sim_cmac_update(st, buf, *len); + desfire_sim_cmac_final(st, mac); + return true; +} + +// ------------------------------------------------------------------- files + + +// Find a live file by its file number within the selected application. +static const desfire_em_file_t *desfire_sim_find_file(const desfire_sim_state_t *st, uint8_t fileno) { + + for (uint16_t i = 0; i < st->hdr->filecount; i++) { + + const desfire_em_file_t *f = &st->files[i]; + if (f->app != st->selected || f->num != fileno) { + continue; + } + return (f->flags & DESFIRE_EM_FILE_DELETED) ? NULL : f; + } + return NULL; +} + +static int16_t desfire_sim_file_index(const desfire_sim_state_t *st, const desfire_em_file_t *f) { + return (int16_t)(f - st->files); +} + +// The most file data one frame can carry. The answer is a status byte, the +// payload and up to a CMAC or a block of padding behind it, and the whole thing +// has to fit DESFIRE_SIM_MAX_RESP as well as the reader's own frame size. +#define DESFIRE_SIM_READ_CHUNK 96 + +// What the reader said it can receive, set from the RATS parameter byte. Until +// RATS has been seen the ISO 14443-4 default of 32 bytes applies (FSDI 0 and 1 +// both mean a small frame, and 32 is the value a PICC assumes), but nothing +// this sizes is reachable before RATS anyway. +static uint16_t s_sim_readchunk = DESFIRE_SIM_READ_CHUNK; + +static void desfire_sim_set_fsd(uint8_t fsdi) { + + static const uint16_t fsdtbl[] = { 16, 24, 32, 40, 48, 64, 96, 128, 256 }; + + uint16_t fsd = (fsdi < ARRAYLEN(fsdtbl)) ? fsdtbl[fsdi] : 256; + + // room the frame needs around the payload: the 14443-4 prologue, the status + // byte, a CMAC or a block of padding, and the CRC + uint16_t room = (fsd > 16) ? (fsd - 16) : 0; + + // an enciphered read is handed out in whole cipher blocks, so the chunk has + // to be a multiple of the largest block size in play + room -= (room % 16); + + if (room > DESFIRE_SIM_READ_CHUNK) { + room = DESFIRE_SIM_READ_CHUNK; + } + + // A reader asking for frames below 32 bytes cannot be served: the status + // byte, a CMAC and the framing already cost twelve, and what is left will + // not hold a cipher block. One block is sent anyway rather than nothing, + // which is what the old fixed 96 did to every reader below 128. No reader + // in practice asks for less -- this card's own ATS advertises 64. + if (room < 16) { + room = 16; + } + + s_sim_readchunk = room; +} + +// Hand out the next slice of a file read, chaining with 0xAF while more is +// left. Shared by the first frame and every continuation. +static uint16_t desfire_sim_read_chunk(desfire_sim_state_t *st, uint8_t *out) { + + const desfire_em_file_t *f = &st->files[st->chain_file]; + const uint8_t *data = st->base + f->dataoff + st->chain_base; + + uint32_t left = st->chain_end - st->chain_off; + uint32_t n = (left > s_sim_readchunk) ? s_sim_readchunk : left; + + uint32_t at = st->chain_off; + st->chain_off += n; + + bool more = (st->chain_off < st->chain_end); + if (more == false) { + st->chain_cmd = 0; + st->chain_step = 0; + st->chain_file = -1; + } + + if (st->chain_comm != DESFIRE_SIM_COMM_FULL) { + return desfire_sim_chained(st, out, more, st->chain_comm, data + at, n); + } + + // An enciphered read is one CBC run over the file data, a CRC32 behind it + // and zero padding, split across frames with the init vector carried from + // one to the next -- "if the commands are queued due to a very long data + // stream, the init vector for the decipherment is always updated" (M134034 7.3.7). + uint8_t plain[DESFIRE_SIM_READ_CHUNK] = {0}; + + for (uint32_t i = 0; i < n; i++) { + + uint32_t p = at + i; + + if (p < st->chain_datalen) { + plain[i] = data[p]; + } else if (p < st->chain_datalen + st->chain_crclen) { + plain[i] = st->chain_crc[p - st->chain_datalen]; + } else { + plain[i] = 0x00; + } + } + + out[0] = more ? MFDES_ADDITIONAL_FRAME : MFDES_S_OPERATION_OK; + desfire_sim_crypt(&st->sesskey, plain, out + 1, n, st->iv, true); + return n + 1; +} + +// Set up a data or record read and answer its first frame. `unit` is 1 for a +// data file and the record size for a record file, so offset and length are +// counted in whatever the command counts in. +static uint16_t desfire_sim_read_start(desfire_sim_state_t *st, const desfire_em_file_t *f, + uint32_t off, uint32_t len, uint32_t unit, + uint32_t avail, uint8_t comm, uint8_t *out) { + + // A file whose contents were never read holds reserved space and nothing + // meaningful. "8 bytes of 00" and "we could not read 8 bytes" are + // different facts, so this answers an error rather than zeros. + if (f->flags & DESFIRE_EM_FILE_UNKNOWN) { + return desfire_sim_status(out, MFDES_E_FILE_NOT_FOUND); + } + + if (off > avail) { + return desfire_sim_status(out, MFDES_E_BOUNDARY); + } + + // zero length means "to the end", EV1 9.5.1 + if (len == 0) { + len = avail - off; + } + + if (off + len > avail) { + return desfire_sim_status(out, MFDES_E_BOUNDARY); + } + + st->chain_cmd = MFDES_READ_DATA; + st->chain_file = desfire_sim_file_index(st, f); + st->chain_base = off * unit; + st->chain_datalen = len * unit; + st->chain_off = 0; + st->chain_comm = comm; + + // the command CMAC has already been taken and its result discarded, so the + // running state starts empty for the response half + if (st->legacy) { + desfire_sim_lmac_reset(st); + } else { + desfire_sim_cmac_reset(st); + } + + if (st->chain_base + st->chain_datalen > f->datalen) { + st->chain_datalen = (f->datalen > st->chain_base) ? (f->datalen - st->chain_base) : 0; + } + + st->chain_end = st->chain_datalen; + st->chain_crclen = 4; + + // a legacy session enciphers the data and a CRC16 over it, from a zero IV + if (comm == DESFIRE_SIM_COMM_FULL && st->authenticated && st->legacy) { + const uint8_t *data = st->base + f->dataoff + st->chain_base; + desfire_sim_crc16(data, st->chain_datalen, st->chain_crc); + st->chain_crclen = 2; + st->chain_end = padded_data_length(st->chain_datalen + 2, 8); + return desfire_sim_read_chunk(st, out); + } + + if (comm == DESFIRE_SIM_COMM_FULL) { + + size_t kbs = key_block_size(&st->sesskey); + if (kbs == 0) { + return desfire_sim_status(out, MFDES_E_AUTHENTICATION_ERROR); + } + + // The CRC32 covers the data and the status byte the last frame will + // carry, so it is taken now and fed out with the rest of the stream. + const uint8_t *data = st->base + f->dataoff + st->chain_base; + + crc_t crc; + crc_init_ref(&crc, 32, DESFIRE_CRC32_POLY, 0xFFFFFFFF, 0, false, false); + + for (uint32_t i = 0; i < st->chain_datalen; i++) { + crc_update(&crc, data[i], 8); + } + crc_update(&crc, MFDES_S_OPERATION_OK, 8); + + uint32_t v = crc_finish(&crc); + st->chain_crc[0] = v & 0xFF; + st->chain_crc[1] = (v >> 8) & 0xFF; + st->chain_crc[2] = (v >> 16) & 0xFF; + st->chain_crc[3] = (v >> 24) & 0xFF; + + st->chain_end = padded_data_length(st->chain_datalen + 4, kbs); + } + + return desfire_sim_read_chunk(st, out); +} + +// --------------------------------------------------------------- the writes + +// Emulator memory is what the image lives in, and a write changes it in place +// so `hf mfdes esave` afterwards shows what the reader did. The parsed view is +// const because almost everything only reads it; this is the one way back. +static uint8_t *desfire_sim_wbase(void) { + return BigBuf_get_EM_addr(); +} + +// Where a file's writes land. Standard data files write straight through. +// Backup data, value and record files are covered by CommitTransaction, so +// writes go to the shadow region and only move across on commit -- EV1 9.5. +static uint16_t desfire_sim_write_region(const desfire_em_file_t *f) { + if (f->type == 0x00 || f->shadow_off == 0) { + return f->dataoff; + } + return f->shadow_off; +} + +static bool desfire_sim_file_is_backed(const desfire_em_file_t *f) { + return (f->type != 0x00 && f->shadow_off != 0); +} + +// Start a transaction on a file the first time it is written, so that an abort +// has something to discard and a commit something to move. +static void desfire_sim_mark_dirty(desfire_sim_state_t *st, const desfire_em_file_t *f) { + + if (desfire_sim_file_is_backed(f) == false || (f->flags & DESFIRE_EM_FILE_DIRTY)) { + return; + } + + desfire_em_file_t *w = (desfire_em_file_t *)f; + uint8_t *base = desfire_sim_wbase(); + + // the shadow starts as a copy, so a partial write leaves the rest of the + // file as it was rather than as zeros + memcpy(base + f->shadow_off, base + f->dataoff, f->datalen); + w->flags |= DESFIRE_EM_FILE_DIRTY; +} + +// CommitTransaction: every dirty file's shadow becomes the committed data. +static void desfire_sim_commit(desfire_sim_state_t *st) { + + uint8_t *base = desfire_sim_wbase(); + + for (uint16_t i = 0; i < st->hdr->filecount; i++) { + + desfire_em_file_t *f = (desfire_em_file_t *)&st->files[i]; + if (f->app != st->selected || (f->flags & DESFIRE_EM_FILE_DIRTY) == 0) { + continue; + } + + memcpy(base + f->dataoff, base + f->shadow_off, f->datalen); + f->flags &= ~DESFIRE_EM_FILE_DIRTY; + } +} + +// AbortTransaction: the shadows are dropped and nothing moves. +static void desfire_sim_abort(desfire_sim_state_t *st) { + + for (uint16_t i = 0; i < st->hdr->filecount; i++) { + desfire_em_file_t *f = (desfire_em_file_t *)&st->files[i]; + if (f->app == st->selected) { + f->flags &= ~DESFIRE_EM_FILE_DIRTY; + } + } +} + +// The value a value file currently holds, taking an uncommitted change into +// account -- a Debit followed by GetValue in the same transaction reads back +// the new value, EV1 9.5.6. +static uint32_t desfire_sim_value_get(const desfire_sim_state_t *st, const desfire_em_file_t *f) { + return f->u.value.value; +} + +static void desfire_sim_value_set(desfire_sim_state_t *st, const desfire_em_file_t *f, uint32_t v) { + desfire_em_file_t *w = (desfire_em_file_t *)f; + desfire_sim_mark_dirty(st, f); + w->u.value.value = v; +} + +// One GetDFNames record: AID, ISO file id, DF name. Applications without a DF +// name are not sent back at all (M134034 9.4.4), so this walks past them. +// +// Returns the length written, or 0 when there are no more records. `next` is +// the application index to resume from, `more` says whether another follows. +static uint16_t desfire_sim_dfname_record(const desfire_sim_state_t *st, uint8_t from, + uint8_t *buf, uint8_t *next, bool *more) { + + const desfire_em_hdr_t *hdr = st->hdr; + *more = false; + + for (uint8_t i = from; i < hdr->appcount; i++) { + + const desfire_em_app_t *a = &st->apps[i]; + if ((a->flags & DESFIRE_EM_APP_DELETED) || a->dfnamelen == 0) { + continue; + } + + uint8_t dfnamelen = a->dfnamelen; + if (dfnamelen > sizeof(a->dfname)) { + dfnamelen = sizeof(a->dfname); + } + + memcpy(buf, a->aid, 3); + uint16_t n = 3; + buf[n++] = a->isofid & 0xFF; + buf[n++] = (a->isofid >> 8) & 0xFF; + memcpy(buf + n, a->dfname, dfnamelen); + n += dfnamelen; + + for (uint8_t j = i + 1; j < hdr->appcount; j++) { + if ((st->apps[j].flags & DESFIRE_EM_APP_DELETED) == 0 && st->apps[j].dfnamelen) { + *more = true; + break; + } + } + + *next = i + 1; + return n; + } + + *next = hdr->appcount; + return 0; +} + +// ----------------------------------------------------------------- key change + +// Key length for an algorithm. A single DES key is carried and stored as its +// 16 byte doubled form, which is how the reader sends it too. +static uint8_t desfire_sim_keylen(uint8_t algo) { + return (algo == T_3K3DES) ? 24 : 16; +} + +// For everything but AES the key version lives in the low bit of each of the +// first eight key bytes -- the DES parity bits, which the cipher ignores. +static uint8_t desfire_sim_key_version(uint8_t algo, const uint8_t *key, uint8_t sent) { + + if (algo == T_AES) { + return sent; // AES carries the version as its own byte + } + + uint8_t ver = 0; + for (uint8_t i = 0; i < 8; i++) { + ver |= (key[i] & 1) << (7 - i); + } + return ver; +} + +// Find a key entry to write to, whether or not we hold its current value. +static desfire_em_key_t *desfire_sim_key_slot(desfire_sim_state_t *st, uint8_t app, uint8_t keyno) { + + for (uint16_t i = 0; i < st->hdr->keycount; i++) { + if (st->keys[i].app == app && st->keys[i].num == keyno) { + return (desfire_em_key_t *)&st->keys[i]; + } + } + return NULL; +} + +// ------------------------------------------------------------ file creation + +// Bytes the committed region of a file occupies, before any shadow. The same +// accounting eload uses, so an image a reader has added files to still agrees +// with itself. +static uint32_t desfire_sim_file_extent(uint8_t type, uint32_t size, + uint32_t recsize, uint32_t maxrec) { + + switch (type) { + case 0x00: + case 0x01: + return size; + case 0x02: + // the payload is a 4 byte value, but it is allocated and shadowed + // like anything else, so it gets a whole granule + return DESFIRE_EM_GRANULE; + case 0x03: + case 0x04: + // the declared extent, not the records that happen to exist, so + // WriteRecord never has to grow anything + return recsize * maxrec; + default: + return 0; + } +} + +// CommitTransaction covers everything but a standard data file, and what it +// covers needs a shadow region to write into -- EV1 9.6.10. +static bool desfire_sim_type_has_shadow(uint8_t type) { + return (type == 0x01 || type == 0x02 || type == 0x03 || type == 0x04); +} + +// Add a file to the selected application. +// +// The file table sits between the application table and the key table, so a new +// entry goes in where the key table starts and the keys move up by one entry. +// The file's data is taken off the other end, from the region growing down. +// +// Returns a DESFire status byte. +static uint8_t desfire_sim_file_create(desfire_sim_state_t *st, uint8_t fileno, uint8_t type, + uint8_t comm, uint16_t rights, uint16_t isofid, + uint32_t size, uint32_t recsize, uint32_t maxrec, + uint32_t lower, uint32_t upper, uint32_t value, + uint8_t options) { + + uint8_t *base = desfire_sim_wbase(); + desfire_em_hdr_t *hdr = (desfire_em_hdr_t *)base; + + if (st->selected == 0) { + return MFDES_E_PERMISSION_DENIED; + } + + if (fileno > 0x1F) { + return MFDES_E_PARAMETER_ERROR; + } + + if (hdr->filecount >= DESFIRE_EM_MAX_FILES) { + return MFDES_E_OUT_OF_EEPROM; + } + + if (desfire_sim_find_file(st, fileno) != NULL) { + return MFDES_E_DUPLICATE; + } + + uint32_t extent = DESFIRE_EM_ROUNDUP(desfire_sim_file_extent(type, size, recsize, maxrec)); + if (extent == 0) { + return MFDES_E_PARAMETER_ERROR; + } + + uint32_t reserve = desfire_sim_type_has_shadow(type) ? (extent * 2) : extent; + + if ((uint32_t)hdr->reserved + reserve > hdr->cardsize) { + return MFDES_E_OUT_OF_EEPROM; + } + + // the tables grow up and the file data grows down, and an allocation only + // has to leave the two apart -- here both move at once + uint32_t grow = sizeof(desfire_em_file_t); + if ((uint32_t)hdr->tables_end + grow + reserve > hdr->data_start) { + return MFDES_E_OUT_OF_EEPROM; + } + + // open a gap where the key table starts + uint16_t at = hdr->key_off; + memmove(base + at + grow, base + at, hdr->tables_end - at); + + desfire_em_file_t *f = (desfire_em_file_t *)(base + at); + memset(f, 0, sizeof(*f)); + f->app = st->selected; + f->num = fileno; + f->type = type; + f->flags = comm & DESFIRE_EM_FILE_COMM_MASK; + f->rights = rights; + f->isofid = isofid; + + hdr->key_off += grow; + hdr->tables_end += grow; + + // and take the data off the far end + hdr->data_start -= reserve; + hdr->reserved += reserve; + + f->dataoff = hdr->data_start; + f->datalen = extent; + f->shadow_off = desfire_sim_type_has_shadow(type) ? (hdr->data_start + extent) : 0; + + // a new file reads back as zeros, which is a fact about it rather than a + // gap in the dump, so it is not marked unknown + memset(base + hdr->data_start, 0, reserve); + + switch (type) { + case 0x00: + case 0x01: + f->u.data.size = size; + break; + case 0x02: + f->u.value.lower = lower; + f->u.value.upper = upper; + f->u.value.value = value; + if (options & 0x01) { + f->flags |= DESFIRE_EM_FILE_LIMCREDIT; + } + if (options & 0x02) { + f->flags |= DESFIRE_EM_FILE_FREEGETVAL; + } + break; + case 0x03: + case 0x04: + f->u.record.recordsize = recsize; + f->u.record.maxrecords = maxrec; + f->u.record.currecords = 0; + break; + default: + break; + } + + hdr->filecount++; + + // the key table moved, so the parsed view has to be taken again + int selected = st->selected; + desfire_sim_load(st); + st->selected = selected; + return MFDES_S_OPERATION_OK; +} + +// ------------------------------------------------------- applications + +// Room the card charges for an application: the application itself plus its +// keys, rounded to a granule. The same accounting eload uses, so an image the +// reader has added to still agrees with itself. +static uint16_t desfire_sim_app_cost(uint8_t numkeys, uint8_t keytype) { + + uint8_t keylen; + switch (keytype) { + case T_3K3DES: + keylen = 24; + break; + case T_DES: + case T_3DES: + case T_AES: + default: + keylen = 16; + break; + } + + return DESFIRE_EM_ROUNDUP(DESFIRE_EM_APP_OVERHEAD + (numkeys * keylen)); +} + +// Add an application to the image. +// +// The tables sit head to tail -- applications, then files, then keys -- so a new +// application entry goes in at the end of the application table, which is where +// the file table currently starts, and everything above it moves up by one +// entry. The new application's keys then go on the end of the key table. +// +// Returns a DESFire status byte. +static uint8_t desfire_sim_app_create(desfire_sim_state_t *st, uint32_t aid, uint8_t keysettings, + uint8_t numkeysraw, uint16_t isofid, + const uint8_t *dfname, uint8_t dfnamelen) { + + uint8_t *base = desfire_sim_wbase(); + desfire_em_hdr_t *hdr = (desfire_em_hdr_t *)base; + + if (hdr->appcount >= DESFIRE_EM_MAX_APPS) { + return MFDES_E_OUT_OF_EEPROM; + } + + uint8_t numkeys = numkeysraw & 0x0F; + if (numkeys > DESFIRE_EM_MAX_KEYS) { + return MFDES_E_PARAMETER_ERROR; + } + + // bits 6-7 of the key settings pick the cipher for the whole application + uint8_t keytype; + switch ((numkeysraw >> 6) & 0x03) { + case 0x01: + keytype = T_3K3DES; + break; + case 0x02: + keytype = T_AES; + break; + case 0x00: + keytype = T_3DES; + break; + default: + return MFDES_E_PARAMETER_ERROR; + } + + uint16_t cost = desfire_sim_app_cost(numkeys, keytype); + if ((uint32_t)hdr->reserved + cost > hdr->cardsize) { + return MFDES_E_OUT_OF_EEPROM; + } + + // the tables have to stay clear of the file data growing down at them + uint32_t grow = sizeof(desfire_em_app_t) + ((uint32_t)numkeys * sizeof(desfire_em_key_t)); + if ((uint32_t)hdr->tables_end + grow > hdr->data_start) { + return MFDES_E_OUT_OF_EEPROM; + } + + // open a gap where the file table starts, and put the new entry in it + uint16_t at = hdr->file_off; + memmove(base + at + sizeof(desfire_em_app_t), base + at, hdr->tables_end - at); + + desfire_em_app_t *a = (desfire_em_app_t *)(base + at); + memset(a, 0, sizeof(*a)); + a->aid[0] = aid & 0xFF; + a->aid[1] = (aid >> 8) & 0xFF; + a->aid[2] = (aid >> 16) & 0xFF; + a->keysettings = keysettings; + a->numkeysraw = numkeysraw; + a->keytype = keytype; + a->isofid = isofid; + + if (numkeysraw & 0x20) { + a->flags |= DESFIRE_EM_APP_ISOFIDS; + } + + if (dfnamelen > sizeof(a->dfname)) { + dfnamelen = sizeof(a->dfname); + } + if (dfnamelen) { + memcpy(a->dfname, dfname, dfnamelen); + } + a->dfnamelen = dfnamelen; + + hdr->file_off += sizeof(desfire_em_app_t); + hdr->key_off += sizeof(desfire_em_app_t); + hdr->tables_end += sizeof(desfire_em_app_t); + + // the application's keys go on the end of the key table, all zero, which is + // what a card gives a new application + uint8_t appidx = hdr->appcount; + desfire_em_key_t *k = (desfire_em_key_t *)(base + hdr->tables_end); + + for (uint8_t i = 0; i < numkeys; i++) { + memset(&k[i], 0, sizeof(desfire_em_key_t)); + k[i].app = appidx; + k[i].num = i; + k[i].flags = DESFIRE_EM_KEY_PRESENT | DESFIRE_EM_KEY_VERKNOWN; + } + + hdr->tables_end += numkeys * sizeof(desfire_em_key_t); + hdr->keycount += numkeys; + hdr->appcount++; + hdr->reserved += cost; + + // the tables moved, so the parsed view of them has to be taken again + int selected = st->selected; + desfire_sim_load(st); + st->selected = selected; + return MFDES_S_OPERATION_OK; +} + +// FormatPICC: every application and every file goes, and the memory they held +// comes back. The PICC master key and its settings are explicitly untouched +// (M134034 9.4.6), and so is the card identity, so what is left is the same +// card with nothing on it. +// +// Everywhere else a delete only sets a tombstone, because a real card does not +// hand the memory back either. This is the one command that reclaims, and here +// that means rebuilding the tables around the surviving PICC entry and putting +// both frontiers back where an empty card has them. +static void desfire_sim_format(desfire_sim_state_t *st) { + + uint8_t *base = desfire_sim_wbase(); + desfire_em_hdr_t *hdr = (desfire_em_hdr_t *)base; + + uint16_t oldkeys = hdr->keycount; + + // With no applications but the PICC and no files at all, the key table + // starts directly behind the one application entry. + uint16_t newoff = hdr->app_off + sizeof(desfire_em_app_t); + desfire_em_key_t *dst = (desfire_em_key_t *)(base + newoff); + + // Only the PICC's own keys survive, compacted to the front of the new + // table. Each one moves to an address at or below the one it came from -- + // the table start only ever moves down and the write index never runs ahead + // of the read index -- so copying forward cannot clobber a key not yet read. + uint8_t keepcount = 0; + for (uint16_t i = 0; i < oldkeys; i++) { + + if (st->keys[i].app != 0) { + continue; + } + + memmove(&dst[keepcount], &st->keys[i], sizeof(desfire_em_key_t)); + keepcount++; + } + + hdr->appcount = 1; + hdr->filecount = 0; + hdr->keycount = keepcount; + + hdr->file_off = newoff; // empty, so the key table starts here too + hdr->key_off = newoff; + hdr->tables_end = newoff + (keepcount * sizeof(desfire_em_key_t)); + + hdr->data_start = hdr->size; + hdr->reserved = 0; + + // the tables moved, so the parsed view of them has to be taken again + desfire_sim_load(st); +} + +// Act on a write once every frame of it has arrived. `buf`/`len` are the plain +// parameters, secure messaging already stripped. +static uint16_t desfire_sim_write_apply(desfire_sim_state_t *st, uint8_t cmd, + uint8_t *buf, uint16_t len, uint8_t comm, uint8_t *out) { + + const desfire_em_file_t *f = desfire_sim_find_file(st, buf[0]); + if (f == NULL) { + return desfire_sim_status(out, MFDES_E_FILE_NOT_FOUND); + } + + uint8_t *base = desfire_sim_wbase(); + + switch (cmd) { + + case MFDES_WRITE_DATA: + case MFDES_WRITE_DATA2: { + + if (f->type != 0x00 && f->type != 0x01) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + uint32_t off = buf[1] | (buf[2] << 8) | (buf[3] << 16); + uint32_t n = buf[4] | (buf[5] << 8) | (buf[6] << 16); + + if (len < 7 + n) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + if (off + n > f->u.data.size || off + n > f->datalen) { + return desfire_sim_status(out, MFDES_E_BOUNDARY); + } + + desfire_sim_mark_dirty(st, f); + memcpy(base + desfire_sim_write_region(f) + off, buf + 7, n); + + // contents are meaningful now even if the dump never read them + ((desfire_em_file_t *)f)->flags &= ~DESFIRE_EM_FILE_UNKNOWN; + return desfire_sim_maced(st, out, MFDES_S_OPERATION_OK, NULL, 0); + } + + case MFDES_WRITE_RECORD: + case MFDES_WRITE_RECORD2: { + + if (f->type != 0x03 && f->type != 0x04) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + uint32_t off = buf[1] | (buf[2] << 8) | (buf[3] << 16); + uint32_t n = buf[4] | (buf[5] << 8) | (buf[6] << 16); + uint32_t rs = f->u.record.recordsize; + + if (rs == 0 || len < 7 + n || off + n > rs) { + return desfire_sim_status(out, MFDES_E_BOUNDARY); + } + + // a linear file is full once it holds maxrecords; a cyclic one + // overwrites the oldest instead -- EV1 9.5.9 + uint32_t cur = f->u.record.currecords; + uint32_t max = f->u.record.maxrecords; + + if (f->type == 0x03 && cur >= max) { + return desfire_sim_status(out, MFDES_E_BOUNDARY); + } + + uint32_t slot = (cur < max) ? cur : (cur % max); + if ((slot + 1) * rs > f->datalen) { + return desfire_sim_status(out, MFDES_E_BOUNDARY); + } + + desfire_sim_mark_dirty(st, f); + memcpy(base + desfire_sim_write_region(f) + (slot * rs) + off, buf + 7, n); + + if (cur < max) { + ((desfire_em_file_t *)f)->u.record.currecords = cur + 1; + } + return desfire_sim_maced(st, out, MFDES_S_OPERATION_OK, NULL, 0); + } + + case MFDES_UPDATE_RECORD: + case MFDES_UPDATE_RECORD2: { + + if (f->type != 0x03 && f->type != 0x04) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + uint32_t rec = buf[1] | (buf[2] << 8) | (buf[3] << 16); + uint32_t off = buf[4] | (buf[5] << 8) | (buf[6] << 16); + uint32_t n = buf[7] | (buf[8] << 8) | (buf[9] << 16); + uint32_t rs = f->u.record.recordsize; + + if (rs == 0 || len < 10 + n || off + n > rs || rec >= f->u.record.currecords) { + return desfire_sim_status(out, MFDES_E_BOUNDARY); + } + if ((rec + 1) * rs > f->datalen) { + return desfire_sim_status(out, MFDES_E_BOUNDARY); + } + + desfire_sim_mark_dirty(st, f); + memcpy(base + desfire_sim_write_region(f) + (rec * rs) + off, buf + 10, n); + return desfire_sim_maced(st, out, MFDES_S_OPERATION_OK, NULL, 0); + } + + case MFDES_CREDIT: + case MFDES_DEBIT: + case MFDES_LIMITED_CREDIT: { + + if (f->type != 0x02 || len < 5) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + uint32_t delta = buf[1] | (buf[2] << 8) | (buf[3] << 16) | ((uint32_t)buf[4] << 24); + uint32_t v = desfire_sim_value_get(st, f); + + if (cmd == MFDES_DEBIT) { + if (delta > v || (v - delta) < f->u.value.lower) { + return desfire_sim_status(out, MFDES_E_BOUNDARY); + } + v -= delta; + } else { + if (delta > f->u.value.upper || (v + delta) > f->u.value.upper) { + return desfire_sim_status(out, MFDES_E_BOUNDARY); + } + v += delta; + } + + desfire_sim_value_set(st, f, v); + return desfire_sim_maced(st, out, MFDES_S_OPERATION_OK, NULL, 0); + } + + default: + return desfire_sim_status(out, MFDES_E_ILLEGAL_COMMAND_CODE); + } +} + +// Gather one frame of a write. A write is secured as a whole, so nothing is +// acted on until the reader stops chaining -- the MAC covers every byte of it +// and an enciphered write carries a single CRC32 at the end. +static uint16_t desfire_sim_write_gather(desfire_sim_state_t *st, uint8_t cmd, + const uint8_t *in, uint16_t inlen, uint8_t *out) { + + if (st->wcmd == 0) { + st->wcmd = cmd; + st->wlen = 0; + st->wexpect = 0; + } + + if ((uint32_t)st->wlen + inlen > sizeof(st->wbuf)) { + st->wcmd = 0; + st->wlen = 0; + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + memcpy(st->wbuf + st->wlen, in, inlen); + st->wlen += inlen; + + // How long the whole command is does not have to be guessed at from how + // full a frame looked: a write says so itself. WriteData, WriteRecord and + // UpdateRecord each carry a 3 byte length in their header, and the header + // is in the clear whatever the communication mode, enciphered included. So + // the total is known as soon as the header has arrived, and the card asks + // for more frames until it has exactly that many bytes. + if (st->wexpect == 0) { + + uint8_t hdrlen = desfire_sim_hdrlen(cmd); + + if (st->wlen < hdrlen) { + return desfire_sim_status(out, MFDES_ADDITIONAL_FRAME); + } + + uint32_t datalen; + switch (cmd) { + case MFDES_WRITE_DATA: + case MFDES_WRITE_DATA2: + case MFDES_WRITE_RECORD: + case MFDES_WRITE_RECORD2: + datalen = st->wbuf[4] | (st->wbuf[5] << 8) | (st->wbuf[6] << 16); + break; + case MFDES_UPDATE_RECORD: + case MFDES_UPDATE_RECORD2: + datalen = st->wbuf[7] | (st->wbuf[8] << 8) | (st->wbuf[9] << 16); + break; + default: + datalen = 4; // a value operation is always 4 bytes + break; + } + + // What that becomes on the wire depends on how the reader secured it, + // which is the file's business, so the file has to be looked at first. + const desfire_em_file_t *wf = desfire_sim_find_file(st, st->wbuf[0]); + if (wf == NULL) { + st->wcmd = 0; + st->wlen = 0; + return desfire_sim_status(out, MFDES_E_FILE_NOT_FOUND); + } + + uint8_t wcomm = DESFIRE_SIM_COMM_PLAIN; + bool wok = (wf->type == 0x02) + ? desfire_sim_value_comm(st, wf, (cmd == MFDES_CREDIT), &wcomm) + : desfire_sim_eff_comm(st, wf, true, &wcomm); + + if (wok == false) { + st->wcmd = 0; + st->wlen = 0; + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + uint32_t total = hdrlen + datalen; + + if (st->authenticated) { + if (wcomm == DESFIRE_SIM_COMM_FULL) { + // a legacy session carries a CRC16 in DES blocks, an EV1 one a CRC32 + size_t kbs = st->legacy ? 8 : key_block_size(&st->sesskey); + if (kbs == 0) { + st->wcmd = 0; + st->wlen = 0; + return desfire_sim_status(out, MFDES_E_AUTHENTICATION_ERROR); + } + total = hdrlen + padded_data_length(datalen + (st->legacy ? 2 : 4), kbs); + } else if (wcomm == DESFIRE_SIM_COMM_MACED && desfire_sim_cmd_macs_request(cmd)) { + total += st->legacy ? DESFIRE_MAC_LENGTH : DESFIRE_CMAC_LENGTH; + } + } + + if (total > sizeof(st->wbuf)) { + st->wcmd = 0; + st->wlen = 0; + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + st->wexpect = total; + } + + if (st->wlen < st->wexpect) { + return desfire_sim_status(out, MFDES_ADDITIONAL_FRAME); + } + + uint8_t wcmd = st->wcmd; + uint16_t wlen = st->wlen; + st->wcmd = 0; + st->wlen = 0; + st->wexpect = 0; + + if (wlen < 1) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + const desfire_em_file_t *f = desfire_sim_find_file(st, st->wbuf[0]); + if (f == NULL) { + return desfire_sim_status(out, MFDES_E_FILE_NOT_FOUND); + } + + uint8_t comm = DESFIRE_SIM_COMM_PLAIN; + bool ok = (f->type == 0x02) + ? desfire_sim_value_comm(st, f, (wcmd == MFDES_CREDIT), &comm) + : desfire_sim_eff_comm(st, f, true, &comm); + + if (ok == false) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + if (desfire_sim_unwrap(st, wcmd, comm, st->wbuf, &wlen) == false) { + desfire_sim_auth_clear(st); + return desfire_sim_status(out, MFDES_E_INTEGRITY_ERROR); + } + + return desfire_sim_write_apply(st, wcmd, st->wbuf, wlen, comm, out); +} + +// Dispatch one DESFire command. `cmd` is the command byte, `in`/`inlen` the +// parameters after it. Writes the answer to `out` and returns its length. +static uint16_t desfire_sim_command(desfire_sim_state_t *st, uint8_t cmd, const uint8_t *in, uint16_t inlen, uint8_t *out) { + + const desfire_em_hdr_t *hdr = st->hdr; + + // an additional frame only means anything while a command is being chained, + // a write is being gathered, or an authentication is half done + if (cmd == MFDES_ADDITIONAL_FRAME && st->chain_cmd == 0 && st->auth_cmd == 0 && st->wcmd == 0) { + return desfire_sim_status(out, MFDES_E_ILLEGAL_COMMAND_CODE); + } + + if (cmd != MFDES_ADDITIONAL_FRAME) { + st->chain_cmd = 0; + st->chain_step = 0; + st->chain_file = -1; + if (desfire_sim_cmd_is_write(cmd) == false) { + st->wcmd = 0; + st->wlen = 0; + } + + // a command arriving mid handshake abandons it + if (cmd != MFDES_AUTHENTICATE && cmd != MFDES_AUTHENTICATE_ISO && cmd != MFDES_AUTHENTICATE_AES) { + st->auth_cmd = 0; + } + } + + // The session CMAC covers every command and response in order, so it is + // taken here for all of them, before the command is acted on. The + // authentication handshake is the exception -- it is what establishes the + // session key, so it runs outside the chain. + // 0xAF is not a command in its own right, it continues one, and a chained + // transfer is secured as a single message -- the reader joins every frame + // and checks one MAC over the lot. MACing the continuation would reset the + // running calculation halfway through and leave the last frame's MAC wrong, + // so it is left to the auth, read and write paths that own the chain. + if (cmd != MFDES_AUTHENTICATE && cmd != MFDES_AUTHENTICATE_ISO && + cmd != MFDES_AUTHENTICATE_AES && cmd != MFDES_ADDITIONAL_FRAME && + st->auth_cmd == 0 && desfire_sim_cmd_unwraps_own(cmd) == false && st->wcmd == 0) { + desfire_sim_cmac_command(st, cmd, in, inlen); + } + + switch (cmd) { + + case MFDES_GET_VERSION: { + // three frames: hardware, software, then production. The first two + // are answered with ADDITIONAL_FRAME so the reader asks again. + st->chain_cmd = MFDES_GET_VERSION; + st->chain_step = 1; + desfire_sim_cmac_reset(st); + return desfire_sim_chained(st, out, true, DESFIRE_SIM_COMM_PLAIN, hdr->versionhw, hdr->versionhwlen); + } + + case MFDES_ADDITIONAL_FRAME: { + + if (st->auth_cmd != 0) { + return desfire_sim_auth_finish(st, in, inlen, out); + } + + if (st->chain_cmd == MFDES_GET_VERSION) { + + if (st->chain_step == 1) { + st->chain_step = 2; + return desfire_sim_chained(st, out, true, DESFIRE_SIM_COMM_PLAIN, hdr->versionsw, hdr->versionswlen); + } + + st->chain_cmd = 0; + st->chain_step = 0; + return desfire_sim_chained(st, out, false, DESFIRE_SIM_COMM_PLAIN, hdr->versionprod, hdr->versionprodlen); + } + + if (st->wcmd != 0) { + return desfire_sim_write_gather(st, st->wcmd, in, inlen, out); + } + + if (st->chain_cmd == MFDES_READ_DATA && st->chain_file >= 0) { + return desfire_sim_read_chunk(st, out); + } + + if (st->chain_cmd == MFDES_GET_DF_NAMES) { + + uint8_t buf[DESFIRE_SIM_MAX_RESP] = {0}; + uint8_t next = st->chain_step; + bool more = false; + uint16_t n = desfire_sim_dfname_record(st, st->chain_step, buf, &next, &more); + + if (n == 0) { + st->chain_cmd = 0; + st->chain_step = 0; + return desfire_sim_status(out, MFDES_S_OPERATION_OK); + } + + if (more) { + st->chain_step = next; + return desfire_sim_chained(st, out, true, DESFIRE_SIM_COMM_PLAIN, buf, n); + } + + st->chain_cmd = 0; + st->chain_step = 0; + return desfire_sim_chained(st, out, false, DESFIRE_SIM_COMM_PLAIN, buf, n); + } + + return desfire_sim_status(out, MFDES_E_ILLEGAL_COMMAND_CODE); + } + + case MFDES_AUTHENTICATE: + case MFDES_AUTHENTICATE_ISO: + case MFDES_AUTHENTICATE_AES: + return desfire_sim_auth_start(st, cmd, in, inlen, out); + + case MFDES_GET_DF_NAMES: { + // PICC level only (M134034 9.4.4), one application per frame + if (st->selected != 0) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + uint8_t buf[DESFIRE_SIM_MAX_RESP] = {0}; + uint8_t next = 1; + bool more = false; + uint16_t n = desfire_sim_dfname_record(st, 1, buf, &next, &more); + if (n == 0) { + return desfire_sim_status(out, MFDES_S_OPERATION_OK); + } + + desfire_sim_cmac_reset(st); + + if (more) { + st->chain_cmd = MFDES_GET_DF_NAMES; + st->chain_step = next; + return desfire_sim_chained(st, out, true, DESFIRE_SIM_COMM_PLAIN, buf, n); + } + return desfire_sim_chained(st, out, false, DESFIRE_SIM_COMM_PLAIN, buf, n); + } + + case MFDES_GET_ISOFILE_IDS: { + // application level: the ISO file ids of the files that have one. + // Value and transaction MAC files never carry one. + if (st->selected == 0) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + uint8_t buf[DESFIRE_SIM_MAX_RESP] = {0}; + uint16_t n = 0; + for (uint16_t i = 0; i < hdr->filecount && (n + 2) <= sizeof(buf); i++) { + + const desfire_em_file_t *f = &st->files[i]; + if (f->app != st->selected || (f->flags & DESFIRE_EM_FILE_DELETED)) { + continue; + } + if (f->type == 0x02 || f->type == 0x05 || f->isofid == 0) { + continue; + } + + buf[n++] = f->isofid & 0xFF; + buf[n++] = (f->isofid >> 8) & 0xFF; + } + + // "If there is no ISO File EF, only an error code can be returned" + if (n == 0) { + return desfire_sim_status(out, MFDES_E_FILE_NOT_FOUND); + } + return desfire_sim_maced(st, out, MFDES_S_OPERATION_OK, buf, n); + } + + case MFDES_GET_APPLICATION_IDS: { + // PICC level only + if (st->selected != 0) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + uint8_t buf[DESFIRE_SIM_MAX_RESP] = {0}; + uint16_t n = 0; + for (uint8_t i = 1; i < hdr->appcount && (n + 3) <= sizeof(buf); i++) { + if (st->apps[i].flags & DESFIRE_EM_APP_DELETED) { + continue; + } + memcpy(buf + n, st->apps[i].aid, 3); + n += 3; + } + return desfire_sim_maced(st, out, MFDES_S_OPERATION_OK, buf, n); + } + + case MFDES_SELECT_APPLICATION: { + + if (inlen < 3) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + uint32_t aid = in[0] | (in[1] << 8) | (in[2] << 16); + int idx = desfire_sim_find_app(st, aid); + if (idx < 0) { + return desfire_sim_status(out, MFDES_E_APPLICATION_NOT_FOUND); + } + + st->selected = idx; + + // "each SelectApplication command invalidates the current + // authentication status" -- M134034 9.4.5 + desfire_sim_auth_clear(st); + return desfire_sim_status(out, MFDES_S_OPERATION_OK); + } + + case MFDES_GET_FREE_MEMORY: { + // what the card has left, not what emulator memory has left. Three + // bytes, LSB first. + uint32_t freemem = (hdr->cardsize > hdr->reserved) ? (hdr->cardsize - hdr->reserved) : 0; + uint8_t buf[3] = { freemem & 0xFF, (freemem >> 8) & 0xFF, (freemem >> 16) & 0xFF }; + return desfire_sim_maced(st, out, MFDES_S_OPERATION_OK, buf, sizeof(buf)); + } + + case MFDES_CHANGE_CONFIGURATION: { + + // "Master key authentication on card level needs to be performed + // prior to the SetConfiguration command" -- M134034 9.4.9 + if (st->authenticated == false || st->selected != 0 || st->auth_keyno != 0) { + return desfire_sim_status(out, MFDES_E_AUTHENTICATION_ERROR); + } + + if (inlen < 1) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + // the option byte travels in the clear, the data behind it does not + uint8_t buf[DESFIRE_SIM_WRITE_MAX] = {0}; + if (inlen > sizeof(buf)) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + memcpy(buf, in, inlen); + uint16_t len = inlen; + + if (desfire_sim_unwrap(st, cmd, DESFIRE_SIM_COMM_FULL, buf, &len) == false) { + desfire_sim_auth_clear(st); + return desfire_sim_status(out, MFDES_E_INTEGRITY_ERROR); + } + + if (len < 2) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + desfire_em_hdr_t *w = (desfire_em_hdr_t *)hdr; + + switch (buf[0]) { + + case 0x00: { + // the configuration byte. Both bits it defines are one way + // on a card -- "cannot be reset" -- so they are only ever + // set here, never cleared. + w->flags |= (buf[1] & (DESFIRE_EM_PICC_NO_FORMAT | DESFIRE_EM_PICC_RANDOM_UID)); + break; + } + + case 0x02: { + // the user defined ATS, TL first and without the CRC the + // card appends. The spec checks its length and nothing + // else, so neither does this. + uint16_t n = len - 1; + if (n == 0 || n > sizeof(w->ats)) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + memset(w->ats, 0, sizeof(w->ats)); + memcpy(w->ats, buf + 1, n); + w->atslen = n; + break; + } + + case 0x01: + // the default key new applications are created with. Storing + // it needs two fields the card image does not have, and adding + // them moves every table in it, so this is refused rather than + // silently ignored -- a reader that sets a default key and then + // finds new applications keyed with zeros is worse off than one + // told the option is not there. + default: + return desfire_sim_status(out, MFDES_E_PARAMETER_ERROR); + } + + return desfire_sim_maced(st, out, MFDES_S_OPERATION_OK, NULL, 0); + } + + case MFDES_READSIG: { + + // one byte selects which signature, and EV1 only has the one + if (inlen < 1) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + if (in[0] != 0x00) { + return desfire_sim_status(out, MFDES_E_PARAMETER_ERROR); + } + + // An originality signature is not an EV1 feature. It is absent + // from M134034 entirely, the client only asks EV2 and later for one, + // and a genuine EV1 answers 91 1C to this command -- measured on + // MF3ICD81 UID 04 26 85 12 A2 56 80, which answers GetVersion in the + // same breath. So a card image of that generation says the same, + // whatever the image happens to carry. + if (hdr->generation == DESFIRE_EM_GEN_D40 || + hdr->generation == DESFIRE_EM_GEN_EV1 || + hdr->generation == DESFIRE_EM_GEN_UNKNOWN) { + return desfire_sim_status(out, MFDES_E_ILLEGAL_COMMAND_CODE); + } + + // A later card whose dump never read a signature has none to give, + // and 56 zero bytes would be a lie a reader cannot tell from a real + // answer. + if (hdr->signaturelen == 0) { + return desfire_sim_status(out, MFDES_E_ILLEGAL_COMMAND_CODE); + } + + uint8_t n = hdr->signaturelen; + if (n > sizeof(hdr->signature)) { + n = sizeof(hdr->signature); + } + + // ReadSignature answers 0x90 rather than 0x00, and that is the byte + // the response CMAC is taken over + return desfire_sim_maced(st, out, MFDES_S_SIGNATURE, hdr->signature, n); + } + + case MFDES_GET_KEY_VERSION: { + + if (inlen < 1) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + uint8_t keyno = in[0] & 0x3F; + const desfire_em_app_t *app = &st->apps[st->selected]; + + // "If AID = 0x00 is selected, the command returns the version of the + // PICC master key and therefore only KeyNo = 0x00 is valid" -- + // M134034 9.3.7 + if (st->selected == 0) { + if (keyno != 0) { + return desfire_sim_status(out, MFDES_E_NO_SUCH_KEY); + } + } else if (keyno >= (app->numkeysraw & 0x0F)) { + return desfire_sim_status(out, MFDES_E_NO_SUCH_KEY); + } + + const desfire_em_key_t *k = desfire_sim_key_slot(st, st->selected, keyno); + if (k == NULL) { + return desfire_sim_status(out, MFDES_E_NO_SUCH_KEY); + } + + // A key version is readable without knowing the key, which is why + // the image tracks the two apart. A version the dump never read + // comes back as 0, which is what a default key carries anyway. + uint8_t ver = k->ver; + return desfire_sim_maced(st, out, MFDES_S_OPERATION_OK, &ver, 1); + } + + case MFDES_GET_KEY_SETTINGS: { + const desfire_em_app_t *a = &st->apps[st->selected]; + uint8_t buf[2] = { a->keysettings, a->numkeysraw }; + return desfire_sim_maced(st, out, MFDES_S_OPERATION_OK, buf, sizeof(buf)); + } + + case MFDES_GET_FILE_IDS: { + + if (st->selected == 0) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + uint8_t buf[DESFIRE_SIM_MAX_RESP] = {0}; + uint16_t n = 0; + for (uint16_t i = 0; i < hdr->filecount && n < sizeof(buf); i++) { + if (st->files[i].app != st->selected) { + continue; + } + if (st->files[i].flags & DESFIRE_EM_FILE_DELETED) { + continue; + } + buf[n++] = st->files[i].num; + } + return desfire_sim_maced(st, out, MFDES_S_OPERATION_OK, buf, n); + } + + case MFDES_GET_FILE_SETTINGS: { + + if (inlen < 1) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + for (uint16_t i = 0; i < hdr->filecount; i++) { + + const desfire_em_file_t *f = &st->files[i]; + if (f->app != st->selected || f->num != in[0]) { + continue; + } + if (f->flags & DESFIRE_EM_FILE_DELETED) { + break; + } + + uint8_t buf[17] = {0}; + uint16_t n = 0; + buf[n++] = f->type; + buf[n++] = f->flags & DESFIRE_EM_FILE_COMM_MASK; + buf[n++] = f->rights & 0xFF; + buf[n++] = (f->rights >> 8) & 0xFF; + + switch (f->type) { + case 0x00: + case 0x01: { + // the size the file was created with, not the rounded + // allocation -- measured, a real card reports 1 for a + // file created with 1 + uint32_t v = f->u.data.size; + buf[n++] = v & 0xFF; + buf[n++] = (v >> 8) & 0xFF; + buf[n++] = (v >> 16) & 0xFF; + break; + } + case 0x02: { + const uint32_t vals[3] = { f->u.value.lower, f->u.value.upper, f->u.value.value }; + for (uint8_t v = 0; v < 3; v++) { + buf[n++] = vals[v] & 0xFF; + buf[n++] = (vals[v] >> 8) & 0xFF; + buf[n++] = (vals[v] >> 16) & 0xFF; + buf[n++] = (vals[v] >> 24) & 0xFF; + } + buf[n++] = (f->flags & DESFIRE_EM_FILE_LIMCREDIT) ? 1 : 0; + break; + } + case 0x03: + case 0x04: { + const uint32_t vals[3] = { f->u.record.recordsize, f->u.record.maxrecords, f->u.record.currecords }; + for (uint8_t v = 0; v < 3; v++) { + buf[n++] = vals[v] & 0xFF; + buf[n++] = (vals[v] >> 8) & 0xFF; + buf[n++] = (vals[v] >> 16) & 0xFF; + } + break; + } + default: + break; + } + + return desfire_sim_maced(st, out, MFDES_S_OPERATION_OK, buf, n); + } + + return desfire_sim_status(out, MFDES_E_FILE_NOT_FOUND); + } + + case MFDES_READ_DATA: + case MFDES_READ_DATA2: { + + // fileno, then a 3 byte offset and a 3 byte length + if (inlen < 7) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + const desfire_em_file_t *f = desfire_sim_find_file(st, in[0]); + if (f == NULL) { + return desfire_sim_status(out, MFDES_E_FILE_NOT_FOUND); + } + + if (f->type != 0x00 && f->type != 0x01) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + uint8_t comm = DESFIRE_SIM_COMM_PLAIN; + if (desfire_sim_eff_comm(st, f, false, &comm) == false) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + uint32_t off = in[1] | (in[2] << 8) | (in[3] << 16); + uint32_t len = in[4] | (in[5] << 8) | (in[6] << 16); + + return desfire_sim_read_start(st, f, off, len, 1, f->u.data.size, comm, out); + } + + case MFDES_READ_RECORDS: + case MFDES_READ_RECORDS2: { + + if (inlen < 7) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + const desfire_em_file_t *f = desfire_sim_find_file(st, in[0]); + if (f == NULL) { + return desfire_sim_status(out, MFDES_E_FILE_NOT_FOUND); + } + + if (f->type != 0x03 && f->type != 0x04) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + uint8_t comm = DESFIRE_SIM_COMM_PLAIN; + if (desfire_sim_eff_comm(st, f, false, &comm) == false) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + uint32_t off = in[1] | (in[2] << 8) | (in[3] << 16); + uint32_t num = in[4] | (in[5] << 8) | (in[6] << 16); + + // offset counts back from the newest record, so record 0 is the one + // written last -- EV1 9.5.8 + if (f->u.record.recordsize == 0) { + return desfire_sim_status(out, MFDES_E_FILE_NOT_FOUND); + } + + return desfire_sim_read_start(st, f, off, num, f->u.record.recordsize, + f->u.record.currecords, comm, out); + } + + case MFDES_GET_VALUE: { + + if (inlen < 1) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + const desfire_em_file_t *f = desfire_sim_find_file(st, in[0]); + if (f == NULL) { + return desfire_sim_status(out, MFDES_E_FILE_NOT_FOUND); + } + + if (f->type != 0x02) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + uint8_t comm = DESFIRE_SIM_COMM_PLAIN; + if (desfire_sim_value_comm(st, f, false, &comm) == false) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + uint32_t v = f->u.value.value; + uint8_t buf[4] = { v & 0xFF, (v >> 8) & 0xFF, (v >> 16) & 0xFF, (v >> 24) & 0xFF }; + return desfire_sim_respond(st, out, MFDES_S_OPERATION_OK, buf, sizeof(buf), comm); + } + + case MFDES_WRITE_DATA: + case MFDES_WRITE_DATA2: + case MFDES_WRITE_RECORD: + case MFDES_WRITE_RECORD2: + case MFDES_UPDATE_RECORD: + case MFDES_UPDATE_RECORD2: + case MFDES_CREDIT: + case MFDES_DEBIT: + case MFDES_LIMITED_CREDIT: + return desfire_sim_write_gather(st, cmd, in, inlen, out); + + case MFDES_CREATE_STD_DATA_FILE: + case MFDES_CREATE_BACKUP_DATA_FILE: + case MFDES_CREATE_VALUE_FILE: + case MFDES_CREATE_LINEAR_RECORD_FILE: + case MFDES_CREATE_CYCLIC_RECORD_FILE: { + + if (st->selected == 0) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + const desfire_em_app_t *app = &st->apps[st->selected]; + + // application key settings bit 2 clear means create and delete need + // the application master key (M134034 9.3.4) + if ((app->keysettings & 0x04) == 0) { + if (st->authenticated == false || st->auth_keyno != 0) { + return desfire_sim_status(out, MFDES_E_AUTHENTICATION_ERROR); + } + } + + // the ISO file id is only on the wire when the application was + // created with ISO file ids enabled + bool isofids = (app->flags & DESFIRE_EM_APP_ISOFIDS) != 0; + uint8_t type; + uint8_t need; + + switch (cmd) { + case MFDES_CREATE_STD_DATA_FILE: + type = 0x00; + need = isofids ? 9 : 7; + break; + case MFDES_CREATE_BACKUP_DATA_FILE: + type = 0x01; + need = isofids ? 9 : 7; + break; + case MFDES_CREATE_VALUE_FILE: + type = 0x02; + need = 17; // never carries an ISO file id + break; + case MFDES_CREATE_LINEAR_RECORD_FILE: + type = 0x03; + need = isofids ? 12 : 10; + break; + default: + type = 0x04; + need = isofids ? 12 : 10; + break; + } + + // every one of these is fixed length, so a frame that is not + // exactly the expected size is rejected rather than parsed from the + // wrong offset -- a reader that sends an ISO file id to an + // application that does not use them lands here + if (inlen != need) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + uint8_t fileno = in[0]; + uint16_t isofid = 0; + const uint8_t *p = in + 1; + + if (isofids && type != 0x02) { + isofid = p[0] | (p[1] << 8); + p += 2; + } + + uint8_t comm = p[0]; + uint16_t rights = p[1] | (p[2] << 8); + p += 3; + + uint32_t size = 0, recsize = 0, maxrec = 0; + uint32_t lower = 0, upper = 0, value = 0; + uint8_t options = 0; + + if (type == 0x00 || type == 0x01) { + + size = p[0] | (p[1] << 8) | (p[2] << 16); + + } else if (type == 0x02) { + + lower = p[0] | (p[1] << 8) | (p[2] << 16) | ((uint32_t)p[3] << 24); + upper = p[4] | (p[5] << 8) | (p[6] << 16) | ((uint32_t)p[7] << 24); + value = p[8] | (p[9] << 8) | (p[10] << 16) | ((uint32_t)p[11] << 24); + options = p[12]; + + // "The upper limit has to be higher than the lower limit, + // otherwise an error message would be sent by the PICC and thus + // the file would not be created" -- M134034 9.5.7, and the + // initial value has to sit between the two + if ((int32_t)upper <= (int32_t)lower || + (int32_t)value < (int32_t)lower || (int32_t)value > (int32_t)upper) { + return desfire_sim_status(out, MFDES_E_PARAMETER_ERROR); + } + + } else { + + recsize = p[0] | (p[1] << 8) | (p[2] << 16); + maxrec = p[3] | (p[4] << 8) | (p[5] << 16); + + if (recsize == 0 || maxrec == 0) { + return desfire_sim_status(out, MFDES_E_PARAMETER_ERROR); + } + } + + uint8_t res = desfire_sim_file_create(st, fileno, type, comm, rights, isofid, + size, recsize, maxrec, lower, upper, value, options); + if (res != MFDES_S_OPERATION_OK) { + return desfire_sim_status(out, res); + } + return desfire_sim_maced(st, out, MFDES_S_OPERATION_OK, NULL, 0); + } + + case MFDES_CHANGE_KEY_SETTINGS: { + + // "Additionally a successful preceding authentication with the + // master key is required (PICC master key if AID = 0x00, else with + // application master key)" -- M134034 9.3.4 + if (st->authenticated == false || st->auth_keyno != 0) { + return desfire_sim_status(out, MFDES_E_AUTHENTICATION_ERROR); + } + + const desfire_em_app_t *app = &st->apps[st->selected]; + + // "This command only succeeds if the configuration changeable bit + // of the current key settings was not cleared before". Clearing it + // is one way, which is the point of it. + if ((app->keysettings & 0x08) == 0) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + // one byte of new settings, enciphered with a CRC32 behind it, the + // same shape ChangeKey uses and nothing in the clear + uint8_t buf[DESFIRE_SIM_WRITE_MAX] = {0}; + if (inlen == 0 || inlen > sizeof(buf)) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + memcpy(buf, in, inlen); + uint16_t len = inlen; + + if (desfire_sim_unwrap(st, cmd, DESFIRE_SIM_COMM_FULL, buf, &len) == false) { + desfire_sim_auth_clear(st); + return desfire_sim_status(out, MFDES_E_INTEGRITY_ERROR); + } + + if (len < 1) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + ((desfire_em_app_t *)app)->keysettings = buf[0]; + return desfire_sim_maced(st, out, MFDES_S_OPERATION_OK, NULL, 0); + } + + case MFDES_CHANGE_KEY: { + + if (inlen < 1) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + if (st->authenticated == false) { + return desfire_sim_status(out, MFDES_E_AUTHENTICATION_ERROR); + } + + uint8_t keyno = in[0] & 0x3F; + const desfire_em_app_t *app = &st->apps[st->selected]; + uint8_t algo = app->keytype; + + // At PICC level the top two bits of the key number choose the + // algorithm the new master key is to be, since there is no + // application creation to fix it -- M134034 9.3.6. Inside an + // application the key type cannot change after creation. + if (st->selected == 0) { + + if (keyno != 0) { + return desfire_sim_status(out, MFDES_E_PARAMETER_ERROR); + } + + switch ((in[0] >> 6) & 0x03) { + case 0x01: + algo = T_3K3DES; + break; + case 0x02: + algo = T_AES; + break; + default: + algo = T_3DES; + break; + } + + } else if (keyno >= (app->numkeysraw & 0x0F)) { + return desfire_sim_status(out, MFDES_E_NO_SUCH_KEY); + } + + // Which key had to be authenticated: the master key changes only + // with the master key and only while it is still changeable, and + // everything else is governed by the change-key nibble of the + // application's key settings (M134034 9.3.4 and 9.3.6). + uint8_t ck = (app->keysettings >> 4) & 0x0F; + + if (keyno == 0) { + + if ((app->keysettings & 0x01) == 0) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + if (st->auth_keyno != 0) { + return desfire_sim_status(out, MFDES_E_AUTHENTICATION_ERROR); + } + + } else if (ck == 0x0F) { + + // every key but the master key is frozen + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + + } else if (ck == 0x0E) { + + // free: a key is changed by whoever authenticated with it + if (st->auth_keyno != keyno) { + return desfire_sim_status(out, MFDES_E_AUTHENTICATION_ERROR); + } + + } else if (st->auth_keyno != ck) { + return desfire_sim_status(out, MFDES_E_AUTHENTICATION_ERROR); + } + + desfire_em_key_t *slot = desfire_sim_key_slot(st, st->selected, keyno); + if (slot == NULL) { + return desfire_sim_status(out, MFDES_E_NO_SUCH_KEY); + } + + // The reader enciphers the key data under the session key. Its + // shape is fixed, so the length is known rather than searched for: + // the key, an AES version byte, the CRC32 over command, key number + // and that lot, and -- only when the key being changed is not the + // one the session was opened with -- a CRC32 of the new key on top. + // A legacy session carries CRC16s over the key data alone and the + // reader deciphered the lot; an EV1 session CRC32s and enciphers. + uint8_t keylen = desfire_sim_keylen(algo); + bool xored = (keyno != st->auth_keyno); + uint8_t crclen = st->legacy ? 2 : 4; + + uint16_t plainlen = keylen + ((algo == T_AES) ? 1 : 0) + crclen + (xored ? crclen : 0); + + size_t kbs = st->legacy ? 8 : key_block_size(&st->sesskey); + if (kbs == 0) { + return desfire_sim_status(out, MFDES_E_AUTHENTICATION_ERROR); + } + + uint16_t enclen = inlen - 1; + if (enclen != padded_data_length(plainlen, kbs)) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + uint8_t buf[DESFIRE_SIM_WRITE_MAX] = {0}; + if (enclen > sizeof(buf)) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + if (st->legacy) { + desfire_sim_d40_receive(&st->sesskey, in + 1, buf, enclen); + } else { + desfire_sim_crypt(&st->sesskey, in + 1, buf, enclen, st->iv, false); + } + + // the CRC32 covers the command byte, the key number as it arrived, + // and the plaintext up to but not including the CRC itself + uint16_t upto = keylen + ((algo == T_AES) ? 1 : 0); + + uint8_t want[4] = {0}; + if (st->legacy) { + desfire_sim_crc16(buf, upto, want); + } else { + uint8_t crcbuf[DESFIRE_SIM_WRITE_MAX + 8] = {0}; + crcbuf[0] = cmd; + crcbuf[1] = in[0]; + memcpy(crcbuf + 2, buf, upto); + crc32_ex(crcbuf, upto + 2, want); + } + + if (memcmp(want, buf + upto, crclen) != 0) { + desfire_sim_auth_clear(st); + return desfire_sim_status(out, MFDES_E_INTEGRITY_ERROR); + } + + uint8_t newkey[DESFIRE_MAX_KEY_SIZE] = {0}; + memcpy(newkey, buf, keylen); + + if (xored) { + + // what arrived is the new key XORed with the current one, so the + // card needs to hold the current one to recover it + if ((slot->flags & DESFIRE_EM_KEY_PRESENT) == 0) { + return desfire_sim_status(out, MFDES_E_AUTHENTICATION_ERROR); + } + + for (uint8_t i = 0; i < keylen; i++) { + newkey[i] ^= slot->key[i]; + } + + // and a CRC of the new key alone proves the XOR came apart + uint8_t want2[4] = {0}; + if (st->legacy) { + desfire_sim_crc16(newkey, keylen, want2); + } else { + crc32_ex(newkey, keylen, want2); + } + + if (memcmp(want2, buf + upto + crclen, crclen) != 0) { + desfire_sim_auth_clear(st); + return desfire_sim_status(out, MFDES_E_INTEGRITY_ERROR); + } + } + + memset(slot->key, 0, sizeof(slot->key)); + memcpy(slot->key, newkey, keylen); + slot->ver = desfire_sim_key_version(algo, newkey, (algo == T_AES) ? buf[keylen] : 0); + slot->flags |= DESFIRE_EM_KEY_PRESENT | DESFIRE_EM_KEY_VERKNOWN; + + // changing the PICC master key can change its algorithm with it + if (st->selected == 0 && algo != app->keytype) { + desfire_em_app_t *w = (desfire_em_app_t *)app; + w->keytype = algo; + w->numkeysraw = (w->numkeysraw & 0x3F) | + ((algo == T_AES) ? 0x80 : ((algo == T_3K3DES) ? 0x40 : 0x00)); + } + + // "After a successful change of the key used to reach the current + // authentication status, this authentication is invalidated" + // -- M134034 9.3.6. The answer to this one still carries its MAC, + // so the session is dropped after it is built. + if (xored == false) { + uint16_t n = desfire_sim_maced(st, out, MFDES_S_OPERATION_OK, NULL, 0); + desfire_sim_auth_clear(st); + return n; + } + + return desfire_sim_maced(st, out, MFDES_S_OPERATION_OK, NULL, 0); + } + + case MFDES_CHANGE_FILE_SETTINGS: { + + if (inlen < 1) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + if (st->selected == 0) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + const desfire_em_file_t *f = desfire_sim_find_file(st, in[0]); + if (f == NULL) { + return desfire_sim_status(out, MFDES_E_FILE_NOT_FOUND); + } + + uint8_t change = DESFIRE_SIM_AR_CHANGE(f->rights); + + // "This change only succeeds if the current Access Rights for + // Change Access Rights is different from never" -- M134034 9.5.4 + if (change == DESFIRE_SIM_AR_DENY) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + // "However, if the ChangeAccessRights Access Rights is set with the + // value free, no security mechanism is necessary and therefore the + // data is sent as plain text (5 byte overall length)." Otherwise it + // is enciphered under the key that right names. + uint8_t comm; + if (change == DESFIRE_SIM_AR_FREE) { + comm = DESFIRE_SIM_COMM_PLAIN; + } else { + if (st->authenticated == false || st->auth_keyno != change) { + return desfire_sim_status(out, MFDES_E_AUTHENTICATION_ERROR); + } + comm = DESFIRE_SIM_COMM_FULL; + } + + uint8_t buf[DESFIRE_SIM_WRITE_MAX] = {0}; + if (inlen > sizeof(buf)) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + memcpy(buf, in, inlen); + uint16_t len = inlen; + + if (desfire_sim_unwrap(st, cmd, comm, buf, &len) == false) { + desfire_sim_auth_clear(st); + return desfire_sim_status(out, MFDES_E_INTEGRITY_ERROR); + } + + // file number, the new communication settings, then the new rights + if (len < 4) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + desfire_em_file_t *w = (desfire_em_file_t *)f; + w->flags = (w->flags & ~DESFIRE_EM_FILE_COMM_MASK) | (buf[1] & DESFIRE_EM_FILE_COMM_MASK); + w->rights = buf[2] | (buf[3] << 8); + + return desfire_sim_maced(st, out, MFDES_S_OPERATION_OK, NULL, 0); + } + + case MFDES_DELETE_FILE: { + + if (inlen < 1) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + if (st->selected == 0) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + const desfire_em_app_t *app = &st->apps[st->selected]; + if ((app->keysettings & 0x04) == 0) { + if (st->authenticated == false || st->auth_keyno != 0) { + return desfire_sim_status(out, MFDES_E_AUTHENTICATION_ERROR); + } + } + + const desfire_em_file_t *f = desfire_sim_find_file(st, in[0]); + if (f == NULL) { + return desfire_sim_status(out, MFDES_E_FILE_NOT_FOUND); + } + + // a tombstone, like DeleteApplication: the memory stays spent and + // only FormatPICC hands it back + ((desfire_em_file_t *)f)->flags |= DESFIRE_EM_FILE_DELETED; + return desfire_sim_maced(st, out, MFDES_S_OPERATION_OK, NULL, 0); + } + + case MFDES_CREATE_APPLICATION: { + + // "This command requires that the currently selected AID is + // 0x00 00 00 which references the card level" -- M134034 9.4.1 + if (st->selected != 0) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + // AID, KeySettings1, KeySettings2, then optionally a 2 byte ISO + // file id and a DF name of up to 16 bytes + if (inlen < 5) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + // PICC key settings bit 2 clear means create needs the PICC master + // key; set means it is free (M134034 9.3.4) + const desfire_em_app_t *picc = &st->apps[0]; + if ((picc->keysettings & 0x04) == 0) { + if (st->authenticated == false || st->auth_keyno != 0) { + return desfire_sim_status(out, MFDES_E_AUTHENTICATION_ERROR); + } + } + + uint32_t aid = in[0] | (in[1] << 8) | (in[2] << 16); + if (aid == 0x000000) { + // reserved as the reference to the PICC itself + return desfire_sim_status(out, MFDES_E_PARAMETER_ERROR); + } + + if (desfire_sim_find_app(st, aid) >= 0) { + return desfire_sim_status(out, MFDES_E_DUPLICATE); + } + + uint16_t isofid = 0; + const uint8_t *dfname = NULL; + uint8_t dfnamelen = 0; + + if (inlen >= 7) { + isofid = in[5] | (in[6] << 8); + dfname = in + 7; + dfnamelen = inlen - 7; + } + + uint8_t res = desfire_sim_app_create(st, aid, in[3], in[4], isofid, dfname, dfnamelen); + if (res != MFDES_S_OPERATION_OK) { + return desfire_sim_status(out, res); + } + return desfire_sim_maced(st, out, MFDES_S_OPERATION_OK, NULL, 0); + } + + case MFDES_DELETE_APPLICATION: { + + if (inlen < 3) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + uint32_t aid = in[0] | (in[1] << 8) | (in[2] << 16); + if (aid == 0x000000) { + return desfire_sim_status(out, MFDES_E_PARAMETER_ERROR); + } + + int idx = desfire_sim_find_app(st, aid); + if (idx < 0) { + return desfire_sim_status(out, MFDES_E_APPLICATION_NOT_FOUND); + } + + // Either the PICC master key, or -- when the PICC leaves create and + // delete free -- the application's own master key, in which case + // that application has to be the selected and authenticated one + // (M134034 9.3.4, footnote to bit 2). + const desfire_em_app_t *picc = &st->apps[0]; + bool bypicc = (st->authenticated && st->selected == 0 && st->auth_keyno == 0); + bool byapp = (st->authenticated && st->selected == idx && st->auth_keyno == 0 && + (picc->keysettings & 0x04)); + + if (bypicc == false && byapp == false) { + return desfire_sim_status(out, MFDES_E_AUTHENTICATION_ERROR); + } + + // A tombstone, not a compaction: the memory stays spent, which is + // what a real card does -- only FormatPICC hands it back. + desfire_em_app_t *a = (desfire_em_app_t *)&st->apps[idx]; + a->flags |= DESFIRE_EM_APP_DELETED; + + for (uint16_t i = 0; i < hdr->filecount; i++) { + if (st->files[i].app == idx) { + ((desfire_em_file_t *)&st->files[i])->flags |= DESFIRE_EM_FILE_DELETED; + } + } + + // deleting the application you are sitting in drops you back to the + // PICC, and the session with it + if (st->selected == idx) { + st->selected = 0; + desfire_sim_auth_clear(st); + return desfire_sim_status(out, MFDES_S_OPERATION_OK); + } + + return desfire_sim_maced(st, out, MFDES_S_OPERATION_OK, NULL, 0); + } + + case MFDES_FORMAT_PICC: { + + // "This command always requires a preceding authentication with the + // PICC master key" -- M134034 9.4.6. Unlike create and delete it is + // not relaxed by the free create/delete key setting, so this checks + // the session rather than the application's key settings. + if (st->authenticated == false || st->selected != 0 || st->auth_keyno != 0) { + return desfire_sim_status(out, MFDES_E_AUTHENTICATION_ERROR); + } + + // SetConfiguration can switch this command off for good + if (hdr->flags & DESFIRE_EM_PICC_NO_FORMAT) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + desfire_sim_format(st); + return desfire_sim_maced(st, out, MFDES_S_OPERATION_OK, NULL, 0); + } + + case MFDES_COMMIT_TRANSACTION: { + + if (st->selected == 0) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + desfire_sim_commit(st); + return desfire_sim_maced(st, out, MFDES_S_OPERATION_OK, NULL, 0); + } + + case MFDES_ABORT_TRANSACTION: { + + if (st->selected == 0) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + desfire_sim_abort(st); + return desfire_sim_maced(st, out, MFDES_S_OPERATION_OK, NULL, 0); + } + + case MFDES_CLEAR_RECORD_FILE: { + + if (inlen < 1) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + const desfire_em_file_t *f = desfire_sim_find_file(st, in[0]); + if (f == NULL) { + return desfire_sim_status(out, MFDES_E_FILE_NOT_FOUND); + } + if (f->type != 0x03 && f->type != 0x04) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + uint8_t comm = DESFIRE_SIM_COMM_PLAIN; + if (desfire_sim_eff_comm(st, f, true, &comm) == false) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + // the records only go once the transaction is committed + desfire_sim_mark_dirty(st, f); + ((desfire_em_file_t *)f)->u.record.currecords = 0; + return desfire_sim_maced(st, out, MFDES_S_OPERATION_OK, NULL, 0); + } + + case MFDES_GET_UID: { + + // The real card answers the UID enciphered under the session key, + // so this needs an authenticated session and nothing else. + if (st->authenticated == false) { + return desfire_sim_status(out, MFDES_E_AUTHENTICATION_ERROR); + } + + uint8_t uidlen = hdr->uidlen; + if (uidlen > sizeof(hdr->uid)) { + uidlen = sizeof(hdr->uid); + } + + return desfire_sim_enciphered(st, out, MFDES_S_OPERATION_OK, hdr->uid, uidlen); + } + + default: + // Everything not implemented yet lands here, which is also the right + // answer for a command this generation genuinely does not have. + if (g_dbglevel >= DBG_EXTENDED) { + Dbprintf("DESFire sim: unhandled command " _YELLOW_("%02x"), cmd); + } + return desfire_sim_status(out, MFDES_E_ILLEGAL_COMMAND_CODE); + } +} + +//---------------------------------------------------------------- entry points + +static bool desfire_sim_init(void) { + + // Always re-parse rather than cache across calls: an eload between two + // simulations replaces the image in place, and a stale parse would serve + // the previous card. It is only pointer setup, so calling it twice during + // activation costs nothing. + s_ready = false; + memset(&s_st, 0, sizeof(s_st)); + + if (desfire_sim_load(&s_st) == false) { + return false; + } + + s_ready = true; + return true; +} + +// The three random id bytes, drawn when a simulation starts. +static uint8_t s_sim_randomid[3]; + +// Drawn at RF reset, host queued bytes first. A card without the option draws +// nothing, so the queue is left for the RndB that follows. +static void desfire_sim_draw_randomid(void) { + + if (s_ready == false || (s_st.hdr->flags & DESFIRE_EM_PICC_RANDOM_UID) == 0) { + return; + } + + if (desfire_sim_random(s_sim_randomid, sizeof(s_sim_randomid))) { + return; + } + + uint32_t seed = GetTickCount(); + s_sim_randomid[0] = (seed >> 16) & 0xFF; + s_sim_randomid[1] = (seed >> 8) & 0xFF; + s_sim_randomid[2] = seed & 0xFF; +} + +static void desfire_sim_identity(uint8_t *uid, uint8_t *uidlen, uint8_t *atqa, uint8_t *sak, uint8_t *ats, uint8_t *atslen) { + + if (s_ready == false) { + return; + } + + const desfire_em_hdr_t *hdr = s_st.hdr; + + // With random ID switched on, anticollision shows a 4 byte id whose first + // byte is the 0x08 random tag and whose other three are the random number, + // and a single cascade level is all that is used (M134034 6.5). The real + // UID is then only reachable through GetCardUID, which is what that command + // is for. A card draws the number at RF reset; the nearest thing here is + // the start of a simulation, since that is when the answers are built. + bool randomid = (hdr->flags & DESFIRE_EM_PICC_RANDOM_UID) != 0; + + if (uid) { + if (randomid) { + uid[0] = 0x08; + uid[1] = s_sim_randomid[0]; + uid[2] = s_sim_randomid[1]; + uid[3] = s_sim_randomid[2]; + } else if (hdr->uidlen <= sizeof(hdr->uid)) { + memcpy(uid, hdr->uid, hdr->uidlen); + } + } + + if (uidlen) { + *uidlen = randomid ? 4 : hdr->uidlen; + } + + if (atqa) { + atqa[0] = hdr->atqa[0]; + atqa[1] = hdr->atqa[1]; + + // the UID size bits of ATQA byte 0 have to follow the id actually shown + if (randomid) { + atqa[0] &= ~0xC0; + } + } + + if (sak) { + *sak = hdr->sak; + } + + if (ats && atslen) { + + // The image keeps the whole ATS frame the card sent, CRC included, + // because that is what round-trips through the dump file. The 14a layer + // appends its own CRC and checks the length against TL, so hand it the + // ATS proper. + uint8_t n = hdr->atslen; + if (n > 2 && hdr->ats[0] == n - 2) { + n -= 2; + } + + if (n > sizeof(hdr->ats)) { + n = sizeof(hdr->ats); + } + + memcpy(ats, hdr->ats, n); + *atslen = n; + } +} + +static void desfire_sim_reset(void) { + + if (s_ready == false) { + return; + } + + s_st.selected = 0; // a PICC comes up with AID 000000 selected + s_st.chain_cmd = 0; + s_st.chain_step = 0; + s_st.chain_file = -1; + desfire_sim_auth_clear(&s_st); +} + +// Run one command and apply the rule that outlives it: "The CMAC is not +// calculated and attached, if an error code is returned. Then the application of +// the PICC leaves the authenticated state and needs to be authenticated again" +// (M134034 7.3.4). Doing it here rather than at every error return means a new +// error path cannot forget it. 0x00, 0x0C, 0x90 and 0xAF are the four statuses +// that are not errors. +static uint16_t desfire_sim_dispatch(uint8_t cmd, const uint8_t *in, uint16_t inlen, uint8_t *out) { + + uint16_t n = desfire_sim_command(&s_st, cmd, in, inlen, out); + + if (n == 0) { + return 0; + } + + switch (out[0]) { + case MFDES_S_OPERATION_OK: + case MFDES_S_NO_CHANGES: + case MFDES_S_SIGNATURE: + case MFDES_S_ADDITIONAL_FRAME: + break; + default: + desfire_sim_auth_clear(&s_st); + break; + } + + return n; +} + +// ISO 7816 status words, the two bytes that end every answer on that path +#define ISO7816_SW_OK 0x9000 +#define ISO7816_SW_WRONG_LENGTH 0x6700 +#define ISO7816_SW_SECURITY 0x6982 +#define ISO7816_SW_NOT_FOUND 0x6A82 +#define ISO7816_SW_BAD_P1P2 0x6A86 +#define ISO7816_SW_BAD_INS 0x6D00 + +static uint16_t desfire_sim_sw(uint8_t *out, uint16_t sw) { + out[0] = sw >> 8; + out[1] = sw & 0xFF; + return 2; +} + +// The PICC's own DF name, what a reader selects to reach the card level +static const uint8_t s_sim_picc_dfname[7] = { 0xD2, 0x76, 0x00, 0x00, 0x85, 0x01, 0x00 }; + +// The ISO 7816 face of the card, as far as a reader that opens with a SELECT +// before it talks DESFire needs it: the PICC by its well known name or 3F00, +// an application by its DF name or ISO file id, a file by its ISO file id. +// Reading and writing through this layer are not here. +static uint16_t desfire_sim_iso7816(desfire_sim_state_t *st, const uint8_t *in, uint16_t inlen, uint8_t *out) { + + if (inlen < 4) { + return desfire_sim_sw(out, ISO7816_SW_WRONG_LENGTH); + } + + switch (in[1]) { + case 0xA4: // SELECT + break; + case 0xB0: // READ BINARY + case 0xB2: // READ RECORDS + case 0xD6: // UPDATE BINARY + case 0xE2: // APPEND RECORD + return desfire_sim_sw(out, ISO7816_SW_SECURITY); + default: + return desfire_sim_sw(out, ISO7816_SW_BAD_INS); + } + + // Lc says how much data follows; a frame shorter than that is a wrong + // length, and an Le behind the data is allowed + uint8_t lc = (inlen > 4) ? in[4] : 0; + const uint8_t *data = in + 5; + if (inlen < (uint16_t)(5 + lc) && lc) { + return desfire_sim_sw(out, ISO7816_SW_WRONG_LENGTH); + } + + int idx = -1; + uint16_t fid = (lc == 2) ? ((data[0] << 8) | data[1]) : 0; + + switch (in[2]) { + + case 0x04: // by DF name + if (lc == sizeof(s_sim_picc_dfname) && memcmp(data, s_sim_picc_dfname, lc) == 0) { + idx = 0; + break; + } + for (uint8_t i = 1; i < st->hdr->appcount && idx < 0; i++) { + const desfire_em_app_t *a = &st->apps[i]; + if ((a->flags & DESFIRE_EM_APP_DELETED) == 0 && a->dfnamelen == lc && memcmp(a->dfname, data, lc) == 0) { + idx = i; + } + } + break; + + case 0x00: // by file id: the MF, an application, or a file of the selected one + case 0x01: // a child DF + case 0x02: // a child EF + if (lc != 2) { + return desfire_sim_sw(out, ISO7816_SW_WRONG_LENGTH); + } + if (in[2] != 0x02) { + if (fid == 0x3F00) { + idx = 0; + break; + } + for (uint8_t i = 1; i < st->hdr->appcount && idx < 0; i++) { + const desfire_em_app_t *a = &st->apps[i]; + if ((a->flags & DESFIRE_EM_APP_DELETED) == 0 && a->isofid && a->isofid == fid) { + idx = i; + } + } + } + if (idx < 0 && in[2] != 0x01) { + for (uint16_t i = 0; i < st->hdr->filecount; i++) { + const desfire_em_file_t *f = &st->files[i]; + if (f->app == st->selected && (f->flags & DESFIRE_EM_FILE_DELETED) == 0 && f->isofid && f->isofid == fid) { + return desfire_sim_sw(out, ISO7816_SW_OK); + } + } + } + break; + + case 0x03: // the parent, always there + return desfire_sim_sw(out, ISO7816_SW_OK); + + default: + return desfire_sim_sw(out, ISO7816_SW_BAD_P1P2); + } + + if (idx < 0) { + return desfire_sim_sw(out, ISO7816_SW_NOT_FOUND); + } + + // selecting an application this way ends the session like SelectApplication does + st->selected = idx; + desfire_sim_auth_clear(st); + return desfire_sim_sw(out, ISO7816_SW_OK); +} + +static uint16_t desfire_sim_apdu(const uint8_t *in, uint16_t inlen, uint8_t *out) { + + if (s_ready == false || inlen < 1) { + return 0; + } + + // a class byte of 00 is ISO 7816 proper, not a wrapped DESFire command + if (in[0] == 0x00) { + return desfire_sim_iso7816(&s_st, in, inlen, out); + } + + // Two framings carry the same commands and a reader may use either. + // + // native -> + // ISO 7816 90 00 00 Lc Le -> 91 + // + // The proxmark client defaults to the wrapped form, so a simulation that + // only understands the native one answers ILLEGAL_COMMAND_CODE to + // everything -- it reads the 0x90 class byte as the command. + if (in[0] == DESFIRE_SIM_ISO7816_CLA && inlen >= 5) { + + uint8_t cmd = in[1]; + + // 5 bytes is CLA INS P1 P2 Le, no data. Longer means in[4] is Lc and + // the data follows, with Le after it. + uint8_t lc = 0; + const uint8_t *data = NULL; + if (inlen > 5) { + lc = in[4]; + data = in + 5; + if ((uint16_t)5 + lc > inlen) { + lc = inlen - 5; // truncated frame, use what arrived + } + } + + uint8_t native[DESFIRE_SIM_MAX_RESP] = {0}; + uint16_t n = desfire_sim_dispatch(cmd, data, lc, native); + if (n == 0) { + return 0; + } + + // status leads in the native answer and trails in the wrapped one + if (n > 1) { + memcpy(out, native + 1, n - 1); + } + out[n - 1] = DESFIRE_SIM_ISO7816_SW1; + out[n] = native[0]; + return n + 1; + } + + return desfire_sim_dispatch(in[0], in + 1, inlen - 1, out); +} + +static void desfire_sim_print_banner(void) { + + if (s_ready == false) { + return; + } + + const desfire_em_hdr_t *hdr = s_st.hdr; + + Dbprintf("Simulating DESFire, %u application(s), " _YELLOW_("%u") " bytes free" + , hdr->appcount - 1 + , (hdr->cardsize > hdr->reserved) ? (hdr->cardsize - hdr->reserved) : 0 + ); + + // The image carries whatever generation the card it came from was, and the + // version bytes we present say so. Only the EV1 command set is implemented, + // so a reader that follows those version bytes into an EV2 or EV3 command + // gets ILLEGAL_COMMAND_CODE. Say so rather than let it look like a bug. + if (hdr->generation != DESFIRE_EM_GEN_EV1 && hdr->generation != DESFIRE_EM_GEN_D40) { + Dbprintf(_YELLOW_("Only the EV1 command set is implemented")); + Dbprintf(_YELLOW_("A reader using a later command will get ILLEGAL_COMMAND_CODE 0x1C")); + } +} + +//-------------------------------------------------------- the simulation loop + +// ISO/IEC 14443-3 activation states. A real PICC only answers what its current +// state allows: after a HALT it hears WUPA but not REQA, it will not start +// cascade 2 before cascade 1 finished, and nothing at the 14443-4 layer is +// legal until RATS has been answered. +typedef enum { + DESF_NOFIELD = 0, // unpowered + DESF_IDLE, // powered, answers REQA and WUPA + DESF_READY1, // cascade level 1 in progress + DESF_READY2, // cascade level 2 in progress + DESF_ACTIVE, // selected, SAK sent, waiting for RATS + DESF_ISO4, // RATS answered, 14443-4 layer open + DESF_HALTED // answers WUPA only +} desfire_sim_pstate_t; + +// ISO/IEC 14443-4 block prologue. The low bit of an I-block PCB is the block +// number and has to be echoed back, or the reader reads our answer as a +// retransmission and stalls. +#define PCB_TYPE_MASK 0xC0 +#define PCB_TYPE_I 0x00 +#define PCB_TYPE_R 0x80 +#define PCB_TYPE_S 0xC0 +#define PCB_I_CHAINING 0x10 +#define PCB_BLOCKNUM 0x01 +#define PCB_CID_FOLLOWS 0x08 +#define PCB_NAD_FOLLOWS 0x04 +#define PCB_S_DESELECT 0xC2 + +// enough for a 2 byte ATQA: 9 bytes of modulation per byte, plus framing +#define ATQA_MODULATION_BUFFER_SIZE 32 + +void SimulateDesfireTag(void) { + + //------------------------------------------------------------------------- + // Get the bitstream in place before anything is allocated. iso14443a_setup() + // below would otherwise do it, and a bitstream download frees and clears + // BigBuf to get scratch space for the decompressor -- taking the emulator + // memory holding our card image and the precompiled anticollision answers + // with it. The pointers survive, the bytes behind them do not, and the tag + // then clocks out zeros. + //------------------------------------------------------------------------- + FpgaDownloadAndGo_keep_EM(FPGA_BITSTREAM_HF); + + // keep emulator memory, that is where eload put the card image + BigBuf_free_keep_EM(); + +#ifdef ENABLE_HFMFDESETEST + // bytes a host queued for etest must not reach a reader + desfire_sim_random_clear(); +#endif + + if (desfire_sim_init() == false) { + Dbprintf("No DESFire card image in emulator memory"); + Dbprintf("Load one with " _YELLOW_("`hf mfdes eload -f `")); + reply_ng(CMD_HF_DESFIRE_SIMULATE, PM3_EINVARG, NULL, 0); + return; + } + + // A card draws its random id at RF reset; a simulation draws it here, which + // is the moment the anticollision answers are built. + desfire_sim_draw_randomid(); + + uint8_t uid[10] = {0}; + uint8_t uidlen = 0; + uint8_t atqa[2] = {0}; + uint8_t sak = 0; + uint8_t ats[20] = {0}; + uint8_t atslen = 0; + desfire_sim_identity(uid, &uidlen, atqa, &sak, ats, &atslen); + + // The simulation runs at 106 kbit/s only. A genuine EV1's TA(1) offers + // 212, 424 and 848 and a reader takes the offer, after which nothing it + // sends can be decoded. On air TA(1) says 106; the image keeps the card's. + if (atslen >= 3 && (ats[1] & 0x10)) { + ats[2] = 0x00; + } + + uint16_t flags = FLAG_ATS_IN_DATA; + switch (uidlen) { + case 4: + // a random id is 4 bytes and uses a single cascade level + flags |= FLAG_4B_UID_IN_DATA; + break; + case 7: + flags |= FLAG_7B_UID_IN_DATA; + break; + case 10: + flags |= FLAG_10B_UID_IN_DATA; + break; + default: + Dbprintf("Card image has a %u byte UID, cannot simulate that", uidlen); + reply_ng(CMD_HF_DESFIRE_SIMULATE, PM3_EINVARG, NULL, 0); + return; + } + + tag_response_info_t *responses = NULL; + uint32_t cuid = 0; + uint8_t pages = 0; + + // tag type 3 gives the DESFire SAK and a DESFire shaped ATS; the ATS from + // the image replaces it because FLAG_ATS_IN_DATA is set + if (SimulateIso14443aInit(3, flags, uid, ats, atslen, &responses, &cuid, &pages, NULL) == false) { + BigBuf_free_keep_EM(); + reply_ng(CMD_HF_DESFIRE_SIMULATE, PM3_EINIT, NULL, 0); + return; + } + + // SimulateIso14443aInit() derives the ATQA from the tag type, so a 7 byte + // UID comes out 44 03 -- which is right for DESFire, but the image may say + // otherwise. Rebuild that one precompiled answer when it differs. + if ((atqa[0] || atqa[1]) && + (responses[RESP_INDEX_ATQA].response[0] != atqa[0] || + responses[RESP_INDEX_ATQA].response[1] != atqa[1])) { + + uint8_t *atqa_buf = BigBuf_calloc(ATQA_MODULATION_BUFFER_SIZE); + if (atqa_buf != NULL) { + + uint8_t *p = atqa_buf; + size_t avail = ATQA_MODULATION_BUFFER_SIZE; + + tag_response_info_t atqa_resp = { + .response = atqa, + .response_n = sizeof(atqa) + }; + + if (prepare_allocated_tag_modulation(&atqa_resp, &p, &avail)) { + responses[RESP_INDEX_ATQA] = atqa_resp; + } else { + Dbprintf(_RED_("Could not build the ATQA answer, using the default")); + } + } + } + + iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN); + + uint8_t receivedCmd[MAX_FRAME_SIZE] = {0}; + uint8_t receivedCmdPar[MAX_PARITY_SIZE] = {0}; + uint8_t answer[DESFIRE_SIM_MAX_RESP + 8] = {0}; + + // ISO 14443-4 keeps reader and card block numbers independently + uint8_t last_answer[DESFIRE_SIM_MAX_RESP + 8] = {0}; + uint16_t last_answer_len = 0; + uint8_t expected_pcd_block = 0; + uint8_t picc_block = 1; + + clear_trace(); + set_tracing(true); + LED_A_ON(); + + desfire_sim_print_banner(); + + int retval = PM3_SUCCESS; + uint32_t cmdcount = 0; + + // Field state. A DESFire is passively powered, so when the field goes away + // it loses the selected application, the authentication and anything a + // transaction had not committed. + // + // EmGetCmd() samples the field while it listens rather than before it, so + // there is no window where the simulation has stopped listening -- an + // ANTICOLL arrives a few hundred microseconds after our ATQA and a single + // RSSI conversion is long enough to miss it. This is the same call the + // MIFARE Classic simulation uses. + bool field_on = true; + desfire_sim_pstate_t pstate = DESF_IDLE; + uint32_t idle_counter = 0; + + for (;;) { + + WDT_HIT(); + + // Watch for the client asking us to stop, in this loop rather than + // relying on the one inside EmGetCmd(). With no field EmGetCmd() + // returns "field off" after 4 ms, which is long before its own check + // fires at 3 * 4000 iterations -- so a simulation sitting in front of + // no reader would never see CMD_BREAK_LOOP, and the device would stay + // in this loop after the client had gone. Same shape as Mifare1ksim. + if (idle_counter >= 1000) { + idle_counter = 0; + if (data_available()) { + retval = PM3_EOPABORTED; + break; + } + } else { + idle_counter++; + } + + if (BUTTON_PRESS()) { + retval = PM3_EOPABORTED; + break; + } + + uint16_t len = 0; + int res = EmGetCmd(receivedCmd, sizeof(receivedCmd), &len, receivedCmdPar); + + if (res == 2) { + // the reader took its field away, so the PICC lost power + if (field_on) { + field_on = false; + pstate = DESF_NOFIELD; + desfire_sim_reset(); + LED_A_OFF(); + if (g_dbglevel >= DBG_EXTENDED) { + DbpString("DESFire sim: field lost, PICC powered down"); + } + } + continue; + + } else if (res == 1) { + + if (g_dbglevel >= DBG_EXTENDED) { + Dbprintf("Button pressed"); + } + retval = PM3_EOPABORTED; + break; + } + + if (field_on == false) { + field_on = true; + pstate = DESF_IDLE; + LED_A_ON(); + } + + if (len == 0) { + continue; + } + + cmdcount++; + + // ---- ISO/IEC 14443-3 activation ---- + // + // Answer first, then do the bookkeeping. The frame delay time for a + // REQA/WUPA answer is fixed by the standard at 1172 or 1236 carrier + // periods and a reader rejects anything else, so nothing may sit + // between receiving the frame and sending the precompiled reply -- + // clearing the session alone costs enough to miss the window. This is + // the shape Mifare1ksim uses. + // + // Each frame is also only honoured in the state that allows it, so a + // half finished cascade is never answered as though it had completed. + + // REQA and WUPA are 7 bit frames. WUPA wakes a halted card, REQA does + // not -- that distinction is the whole point of having two of them. + // A selected card ignores both: a genuine EV1 stays silent and keeps + // its session, and a reader that hears an ATQA thinks a new card came. + bool polled = (pstate == DESF_IDLE || pstate == DESF_READY1 || pstate == DESF_READY2); + if (len == 1 && ((receivedCmd[0] == ISO14443A_CMD_WUPA && (polled || pstate == DESF_HALTED)) || + (receivedCmd[0] == ISO14443A_CMD_REQA && polled))) { + + EmSendPrecompiledCmd(&responses[RESP_INDEX_ATQA]); + desfire_sim_reset(); // a fresh activation reselects the PICC + pstate = DESF_READY1; + continue; + } + + if (len == 2 && receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT && receivedCmd[1] == 0x20 + && pstate == DESF_READY1) { + EmSendPrecompiledCmd(&responses[RESP_INDEX_UIDC1]); + continue; + } + + if (len == 9 && receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT && receivedCmd[1] == 0x70 + && pstate == DESF_READY1) { + + // a card only answers a SELECT that carries its own UID + if (memcmp(receivedCmd + 2, responses[RESP_INDEX_UIDC1].response, 4) != 0) { + continue; + } + EmSendPrecompiledCmd(&responses[RESP_INDEX_SAKC1]); + // a 7 or 10 byte UID needs another cascade level, a 4 byte one is done + pstate = (uidlen > 4) ? DESF_READY2 : DESF_ACTIVE; + continue; + } + + if (len == 2 && receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2 && receivedCmd[1] == 0x20 + && pstate == DESF_READY2) { + EmSendPrecompiledCmd(&responses[RESP_INDEX_UIDC2]); + continue; + } + + if (len == 9 && receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2 && receivedCmd[1] == 0x70 + && pstate == DESF_READY2) { + + if (memcmp(receivedCmd + 2, responses[RESP_INDEX_UIDC2].response, 4) != 0) { + continue; + } + EmSendPrecompiledCmd(&responses[RESP_INDEX_SAKC2]); + pstate = DESF_ACTIVE; + continue; + } + + if (len == 4 && receivedCmd[0] == ISO14443A_CMD_RATS && pstate == DESF_ACTIVE) { + + // The high nibble of the RATS parameter is FSDI, which says how big + // a frame this reader can receive. Answers are sized from it rather + // than from a constant picked to suit one reader -- a reader that + // asks for small frames has to be given small frames. + desfire_sim_set_fsd(receivedCmd[1] >> 4); + + EmSendPrecompiledCmd(&responses[RESP_INDEX_ATS]); + pstate = DESF_ISO4; + expected_pcd_block = 0; + picc_block = 1; + last_answer_len = 0; + continue; + } + + // PPS: only a request that keeps 106 kbit/s both ways is agreed to. + // PPS1, when PPS0 says it is there, carries the rates in its low nibble. + if ((receivedCmd[0] & 0xF0) == ISO14443A_CMD_PPS && pstate == DESF_ISO4) { + bool pps1 = (len >= 5) && (receivedCmd[1] & 0x10); + if (pps1 && (receivedCmd[2] & 0x0F)) { + continue; + } + EmSendPrecompiledCmd(&responses[RESP_INDEX_PPS]); + continue; + } + + if (len == 4 && receivedCmd[0] == ISO14443A_CMD_HALT) { + desfire_sim_reset(); + pstate = DESF_HALTED; + continue; // a halted tag says nothing + } + + if (pstate != DESF_ISO4) { + // nothing below here is legal until RATS has been answered + if (g_dbglevel >= DBG_EXTENDED) { + Dbprintf("DESFire sim: frame ignored in state %u, %d bytes", pstate, len); + } + continue; + } + + // ---- ISO/IEC 14443-4 ---- + + // a frame that did not survive the air is not a command + if (len < 3 || check_crc(CRC_14443_A, receivedCmd, len) == false) { + continue; + } + + if ((receivedCmd[0] & PCB_TYPE_MASK) == PCB_TYPE_S) { + + if (receivedCmd[0] == PCB_S_DESELECT) { + uint8_t r[3] = { PCB_S_DESELECT, 0, 0 }; + AddCrc14A(r, 1); + EmSendCmd(r, sizeof(r)); + desfire_sim_reset(); + pstate = DESF_ACTIVE; // out of 14443-4, RATS would be needed again + expected_pcd_block = 0; + picc_block = 1; + last_answer_len = 0; + } + continue; + + } else if ((receivedCmd[0] & PCB_TYPE_MASK) == PCB_TYPE_R) { + + uint8_t blocknum = receivedCmd[0] & PCB_BLOCKNUM; + if (blocknum == picc_block && last_answer_len) { + EmSendCmd(last_answer, last_answer_len); + continue; + } + + // A nonmatching R(NAK) is answered with R(ACK). There is no + // card-side chaining to continue for a nonmatching R(ACK). + if (receivedCmd[0] & 0x10) { + uint8_t r[3] = { (uint8_t)(0xA2 | picc_block), 0, 0 }; + AddCrc14A(r, 1); + EmSendCmd(r, sizeof(r)); + } + continue; + + } else if ((receivedCmd[0] & PCB_TYPE_MASK) == PCB_TYPE_I) { + + uint8_t prologue = 1; + if (receivedCmd[0] & PCB_CID_FOLLOWS) { + prologue++; + } + if (receivedCmd[0] & PCB_NAD_FOLLOWS) { + prologue++; + } + + // prologue + at least a command byte + CRC + if (len < prologue + 1 + 2) { + continue; + } + + uint8_t blocknum = receivedCmd[0] & PCB_BLOCKNUM; + if (blocknum != expected_pcd_block) { + uint8_t r[3] = { (uint8_t)(0xB2 | expected_pcd_block), 0, 0 }; + AddCrc14A(r, 1); + EmSendCmd(r, sizeof(r)); + continue; + } + expected_pcd_block ^= 1; + picc_block ^= 1; + + uint16_t n = desfire_sim_apdu(receivedCmd + prologue, len - prologue - 2, answer + prologue); + if (n == 0) { + continue; + } + + // Preserve CID/NAD, but use the card's own block number. + memcpy(answer, receivedCmd, prologue); + answer[0] &= ~(PCB_I_CHAINING | PCB_BLOCKNUM); + answer[0] |= picc_block; + + AddCrc14A(answer, prologue + n); + EmSendCmd(answer, prologue + n + 2); + + last_answer_len = prologue + n + 2; + memcpy(last_answer, answer, last_answer_len); + continue; + + } else { + if (g_dbglevel >= DBG_EXTENDED) { + Dbprintf("DESFire sim: unknown frame, %d bytes", len); + Dbhexdump(len, receivedCmd, false); + } + continue; + } + } + + if (g_dbglevel >= DBG_ERROR) { + Dbprintf("Emulator stopped. Trace length: %d", BigBuf_get_traceLen()); + } + if (g_dbglevel >= DBG_EXTENDED) { + Dbprintf("-[ commands received %u ]-", cmdcount); + } + + switch_off(); + set_tracing(false); + BigBuf_free_keep_EM(); + + reply_ng(CMD_HF_DESFIRE_SIMULATE, retval, NULL, 0); +} + +//------------------------------------------------------- host driven simulation + +#ifdef ENABLE_HFMFDESETEST +// SimulateDesfireTag() with the antenna replaced by USB: one operation per +// packet, the answer in the reply. Nothing here touches the FPGA. +void DesfireSimTest(PacketCommandNG *packet) { + + int16_t status = PM3_EINVARG; + const uint8_t *data = NULL; + uint16_t n = 0; + + iso14a_card_select_t card = {0}; + desfire_sim_test_state_t st = {0}; + uint8_t out[DESFIRE_SIM_MAX_RESP + 8] = {0}; + + if (packet->ng == false || packet->length < sizeof(desfire_sim_test_cmd_t)) { + reply_ng(CMD_HF_DESFIRE_SIM_TEST, status, NULL, 0); + return; + } + + const desfire_sim_test_cmd_t *p = (const desfire_sim_test_cmd_t *)packet->data.asBytes; + + if (p->len > packet->length - sizeof(desfire_sim_test_cmd_t)) { + reply_ng(CMD_HF_DESFIRE_SIM_TEST, status, NULL, 0); + return; + } + + switch (p->op) { + + // check the image is there, then wait for SCAN like a card waits for a field + case DESFIRE_SIM_TEST_BEGIN: + desfire_sim_random_clear(); + status = desfire_sim_init() ? PM3_SUCCESS : PM3_ENODATA; + s_ready = false; + break; + + case DESFIRE_SIM_TEST_END: + desfire_sim_random_clear(); + memset(&s_st, 0, sizeof(s_st)); + s_ready = false; + status = PM3_SUCCESS; + break; + + // field off. desfire_sim_init() is the RF reset, the image is re-read + case DESFIRE_SIM_TEST_FIELDOFF: + status = desfire_sim_init() ? PM3_SUCCESS : PM3_ENODATA; + s_ready = false; + break; + + // field on, anticollision, RATS with the largest FSDI + case DESFIRE_SIM_TEST_SCAN: + if (desfire_sim_init() == false) { + status = PM3_ENODATA; + break; + } + desfire_sim_reset(); + desfire_sim_draw_randomid(); + desfire_sim_set_fsd(8); + desfire_sim_identity(card.uid, &card.uidlen, card.atqa, &card.sak, card.ats, &card.ats_len); + data = (uint8_t *)&card; + n = sizeof(card); + status = PM3_SUCCESS; + break; + + // n == 0 is a card that stayed mute, which is an answer too + case DESFIRE_SIM_TEST_APDU: + if (s_ready == false || p->len == 0) { + break; + } + n = desfire_sim_apdu(p->data, p->len, out); + data = out; + status = PM3_SUCCESS; + break; + + case DESFIRE_SIM_TEST_RANDOM: + status = desfire_sim_random_push(p->data, p->len) ? PM3_SUCCESS : PM3_EOVFLOW; + break; + + case DESFIRE_SIM_TEST_STATE: + st.ready = s_ready; + st.random_remaining = s_rnd.len; + st.random_underflow = s_rnd.underflow; + if (s_ready) { + st.authenticated = s_st.authenticated; + st.auth_keyno = s_st.auth_keyno; + if (s_st.selected >= 0) { + memcpy(st.aid, s_st.apps[s_st.selected].aid, sizeof(st.aid)); + } + } + data = (uint8_t *)&st; + n = sizeof(st); + status = PM3_SUCCESS; + break; + + default: + break; + } + + reply_ng(CMD_HF_DESFIRE_SIM_TEST, status, data, n); +} +#endif diff --git a/armsrc/desfiresim.h b/armsrc/desfiresim.h new file mode 100644 index 000000000..704f719e4 --- /dev/null +++ b/armsrc/desfiresim.h @@ -0,0 +1,45 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// MIFARE DESFire tag simulation. +// +// Self contained: everything DESFire lives in desfiresim.c, including its own +// ISO 14443-A loop. It borrows the library helpers from iso14443a.c -- the +// precompiled activation answers, the receive call, the send calls -- but not +// SimulateIso14443aTag() itself, which is complicated enough without a DESFire +// state machine threaded through it. +//----------------------------------------------------------------------------- + +#ifndef __DESFIRESIM_H +#define __DESFIRESIM_H + +#include "common.h" +#include "pm3_cmd.h" + +// Simulate the DESFire card image sitting in emulator memory, as put there by +// `hf mfdes eload`. Self contained: this owns its own ISO 14443-A loop rather +// than hooking into SimulateIso14443aTag(), which is busy enough already. +// Runs until the button is pressed or the client breaks the loop, and answers +// on CMD_HF_DESFIRE_SIMULATE. +void SimulateDesfireTag(void); + +// Drive the same simulation from the host, one operation per packet and no +// RF: the command bytes arrive over USB and the answer goes back the same way. +// Answers on CMD_HF_DESFIRE_SIM_TEST, see desfire_sim_test_op_t. +#ifdef ENABLE_HFMFDESETEST +void DesfireSimTest(PacketCommandNG *packet); +#endif + +#endif // __DESFIRESIM_H diff --git a/armsrc/em4x50.c b/armsrc/em4x50.c index a2481738f..eeaf4d3d3 100644 --- a/armsrc/em4x50.c +++ b/armsrc/em4x50.c @@ -756,6 +756,17 @@ void em4x50_chk(const char *filename, bool ledcontrol) { uint32_t size = size_in_spiffs(filename); pwd_count = size / 4; uint8_t *pwds = BigBuf_calloc(size); + if (pwds == NULL) { + if (changed) { + rdv40_spiffs_lazy_unmount(); + } + BigBuf_free(); + if (ledcontrol) LEDsoff(); + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + StopTicks(); + reply_ng(CMD_LF_EM4X50_CHK, PM3_EMALLOC, (uint8_t *)&pwd, sizeof(pwd)); + return; + } rdv40_spiffs_read_as_filetype(filename, pwds, size, RDV40_SPIFFS_SAFETY_SAFE); diff --git a/armsrc/emvsim.c b/armsrc/emvsim.c index 605ec5244..19f1cd39e 100644 --- a/armsrc/emvsim.c +++ b/armsrc/emvsim.c @@ -303,7 +303,7 @@ void ExecuteEMVSim(uint8_t *receivedCmd, uint16_t receivedCmd_len, uint8_t *rece */ void EMVsim(uint16_t flags, uint8_t exitAfterNReads, uint8_t *uid, uint16_t atqa, uint8_t sak) { - tag_response_info_t *responses; + tag_response_info_t *responses = NULL; uint8_t cardSTATE = MFEMUL_NOFIELD; uint8_t uid_len = 0; // 7 uint32_t cuid = 0; @@ -362,7 +362,7 @@ void EMVsim(uint16_t flags, uint8_t exitAfterNReads, uint8_t *uid, uint16_t atqa if (counter == 3000) { if (data_available()) { - Dbprintf("----------- " _GREEN_("BREAKING") " ----------"); + Dbprintf("---- " _GREEN_("breaking")); break; } counter = 0; @@ -385,8 +385,9 @@ void EMVsim(uint16_t flags, uint8_t exitAfterNReads, uint8_t *uid, uint16_t atqa } else if (res == 1) { // button pressed FpgaDisableTracing(); button_pushed = true; - if (g_dbglevel >= DBG_EXTENDED) + if (g_dbglevel >= DBG_EXTENDED) { Dbprintf("Button pressed"); + } break; } diff --git a/armsrc/epa.c b/armsrc/epa.c index aff1d4bb4..7e5ab2e92 100644 --- a/armsrc/epa.c +++ b/armsrc/epa.c @@ -636,14 +636,15 @@ static int EPA_Setup(void) { // if we're here, there is no type A card, so we look for type B FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); // power up the field - iso14443b_setup(); - iso14b_card_select_t card_b_info; - int return_code = iso14443b_select_card(&card_b_info); + if (iso14443b_setup() == PM3_SUCCESS) { + iso14b_card_select_t card_b_info; + int return_code = iso14443b_select_card(&card_b_info); - if (return_code == 0) { - Dbprintf("ISO 14443 Type B"); - iso_type = 'b'; - return 0; + if (return_code == 0) { + Dbprintf("ISO 14443 Type B"); + iso_type = 'b'; + return 0; + } } } #endif diff --git a/armsrc/felica.c b/armsrc/felica.c index 2848d33e9..ed1bda1e9 100644 --- a/armsrc/felica.c +++ b/armsrc/felica.c @@ -29,7 +29,7 @@ #include "iso18.h" #define AddCrc(data, len) compute_crc(CRC_FELICA, (data), (len), (data)+(len)+1, (data)+(len)) -static uint8_t felica_select_card(felica_card_select_t *card); +static uint8_t felica_select_card(felica_card_select_t *card, uint16_t system_code, uint8_t request_code); //structure to hold outgoing NFC frame static uint8_t frameSpace[FELICA_MAX_RF_FRAME_SIZE]; @@ -244,15 +244,15 @@ void Process18092Byte(felica_frame_t *f, uint8_t bt, uint32_t byte_start_time) { * It expects 0-1 cards in the device's range. * return 0 if selection was successful */ -static uint8_t felica_select_card(felica_card_select_t *card) { +static uint8_t felica_select_card(felica_card_select_t *card, uint16_t system_code, uint8_t request_code) { // POLL command // 0xB2 0x4B = sync code // 0x06 = len // 0x00 = rfu - // 0xff = system code service - // 0xff = system code service - // 0x00 = request code + // system code service (high byte) + // system code service (low byte) + // request code // b7 = automatic switching of data rate // b6-b2 = reserved // b1 = fc/32 (414kbps) @@ -260,6 +260,9 @@ static uint8_t felica_select_card(felica_card_select_t *card) { // 0x00 = timeslot // 0x09 0x21 = crc uint8_t poll[10] = {0xb2, 0x4d, 0x06, FELICA_POLLING_REQ, 0xFF, 0xFF, 0x00, 0x00, 0x09, 0x21}; + poll[4] = (uint8_t)(system_code >> 8); + poll[5] = (uint8_t)system_code; + poll[6] = request_code; // Number of time slots offered to the card(s), the FeliCa polling TSN field. // Slot 0 only is what a single card wants, but when several cards share the @@ -692,8 +695,14 @@ void felica_sendraw(const PacketCommandNG *c) { bool do_connect = ((param & FELICA_CONNECT) == FELICA_CONNECT); bool no_disconnect = ((param & FELICA_NO_DISCONNECT) == FELICA_NO_DISCONNECT); + bool system_select = ((param & FELICA_SYSTEM_SELECT) == FELICA_SYSTEM_SELECT); bool replied = false; + if (system_select && (len != 2 || !do_connect || (param & (FELICA_RAW | FELICA_NO_SELECT)))) { + reply_ng(CMD_HF_FELICA_COMMAND, PM3_EINVARG, NULL, 0); + return; + } + // Signal probe. The FPGA hands us envelope peak-to-peak per 8 bit periods // instead of demodulated bits, so nothing will decode while this is on. // It is how you tell "tag out of range" apart from "demodulator not @@ -708,16 +717,17 @@ void felica_sendraw(const PacketCommandNG *c) { // Preserve compatibility with existing commands that do not send CONNECT: // set up reader path when starting from field-off state. - if (do_connect || felica_field_is_active() == false) { + if (!felica_field_is_active() || (do_connect && !system_select)) { iso18092_setup(FPGA_HF_ISO18092_FLAG_READER | FPGA_HF_ISO18092_FLAG_NOMOD); } if (do_connect && ((param & FELICA_NO_SELECT) != FELICA_NO_SELECT)) { // notify client selecting status. - // if failed selecting, turn off antenna and quit. + // on failed selection, retain the field only for system-specific polling. felica_card_select_t card = {0}; - uint8_t select_result = felica_select_card(&card); + uint16_t system_code = system_select ? ((uint16_t)payload[0] << 8) | payload[1] : 0xFFFF; + uint8_t select_result = felica_select_card(&card, system_code, system_select ? 0x01 : 0x00); int select_status = PM3_SUCCESS; switch (select_result) { @@ -744,7 +754,9 @@ void felica_sendraw(const PacketCommandNG *c) { reply_ng(CMD_HF_FELICA_COMMAND, select_status, (uint8_t *)&card, sizeof(felica_card_select_t)); replied = true; if (select_status != PM3_SUCCESS) { - felica_reset_frame_mode(); + if (!system_select || !no_disconnect) { + felica_reset_frame_mode(); + } return; } } diff --git a/armsrc/hfops.c b/armsrc/hfops.c index 1c38ae73a..9926c6eab 100644 --- a/armsrc/hfops.c +++ b/armsrc/hfops.c @@ -209,6 +209,12 @@ int HfSimulateTkm(const uint8_t *uid, uint8_t modulation, uint32_t timeout) { LEDsoff(); uint8_t *data = BigBuf_calloc(256); + if (data == NULL) { + DbpString("Failed to allocate memory"); + reply_ng(CMD_HF_TEXKOM_SIMULATE, PM3_EMALLOC, NULL, 0); + return PM3_EMALLOC; + } + uint32_t elen = HfEncodeTkm(uid, modulation, data); if (elen == 0) { DbpString("encode error"); diff --git a/armsrc/hfsnoop.c b/armsrc/hfsnoop.c index bd6c556d7..d3e68afb3 100644 --- a/armsrc/hfsnoop.c +++ b/armsrc/hfsnoop.c @@ -109,6 +109,15 @@ int HfSniff(uint32_t samplesToSkip, uint32_t triggersToSkip, uint16_t *len, uint *len = BigBuf_max_traceLen(); uint8_t *mem = BigBuf_calloc(*len); + if (mem == NULL) { + Dbprintf("Failed to allocate memory"); + FpgaUpdateFrameMode(8, true, true); + LED_D_OFF(); + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + BigBuf_free(); + *len = 0; + return PM3_EMALLOC; + } uint32_t trigger_cnt = 0; uint16_t r = 0, interval = 0; diff --git a/armsrc/hitag2.c b/armsrc/hitag2.c index 73cd36860..4d4ffc556 100644 --- a/armsrc/hitag2.c +++ b/armsrc/hitag2.c @@ -1519,7 +1519,9 @@ void SniffHitag2(bool ledcontrol, uint8_t threshold) { if (ledcontrol) LED_D_ON(); hitag_edges_reset(); - g_tx_samples = 0; g_tx_bails = 0; g_tx_frames = 0; + g_tx_samples = 0; + g_tx_bails = 0; + g_tx_frames = 0; FpgaDownloadAndGo(FPGA_BITSTREAM_LF); @@ -1726,6 +1728,13 @@ void SniffHitag2(bool ledcontrol, uint8_t threshold) { auth_table_pos = 0; auth_table = (uint8_t *)BigBuf_calloc(AUTH_TABLE_LENGTH); + if (auth_table == NULL) { + DbpString("Failed to allocate memory"); + if (ledcontrol) LEDsoff(); + switch_off(); + BigBuf_free_keep_EM(); + return; + } // Only for debug, if we want to see the edge timing of the captured frames uint8_t edges[100]; @@ -1976,10 +1985,10 @@ void SniffHitag2(bool ledcontrol, uint8_t threshold) { DBG Dbprintf("frames.......... %d", frame_count); for (uint8_t i = 0; i < d_tagf; i++) { DBG Dbprintf("TAGIV%u n=%u: %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u", i, d_tagn[i], - d_tag[i][0], d_tag[i][1], d_tag[i][2], d_tag[i][3], - d_tag[i][4], d_tag[i][5], d_tag[i][6], d_tag[i][7], - d_tag[i][8], d_tag[i][9], d_tag[i][10], d_tag[i][11], - d_tag[i][12], d_tag[i][13], d_tag[i][14], d_tag[i][15]); + d_tag[i][0], d_tag[i][1], d_tag[i][2], d_tag[i][3], + d_tag[i][4], d_tag[i][5], d_tag[i][6], d_tag[i][7], + d_tag[i][8], d_tag[i][9], d_tag[i][10], d_tag[i][11], + d_tag[i][12], d_tag[i][13], d_tag[i][14], d_tag[i][15]); } Dbprintf("Auth attempts... crypto %u, password %u", (unsigned)crypto_attempts, (unsigned)pwd_attempts); @@ -3045,7 +3054,7 @@ meas_done: s_wait[s_nsnap] = start_time - rx_end; } // Clock the answer off the reader's carrier, not our timer -hitag_tag_send_frame_mc4k_sync(tx, txlen, sof_bits, ledcontrol); + hitag_tag_send_frame_mc4k_sync(tx, txlen, sof_bits, ledcontrol); last_tx_end = TIMESTAMP; if (s_nsnap < SIMSNAP) { @@ -3225,16 +3234,16 @@ hitag_tag_send_frame_mc4k_sync(tx, txlen, sof_bits, ledcontrol); // transitions. The threshold has to sit between the shoulder and the tail, so // it is their separation that matters, not any one of them. DBG Dbprintf("THRSTAT thr=%u p50=%u p90=%u p99=%u max=%u n=%u", - active_threshold, d_p50, d_p90, d_p99, d_pmax, d_nsteps); + active_threshold, d_p50, d_p90, d_p99, d_pmax, d_nsteps); DBG Dbprintf("THRSTAT2 span=%u big=%u locked=%u post=%u", - d_span, d_nbig, thr_locked, post_thr); + d_span, d_nbig, thr_locked, post_thr); DBG Dbprintf("THRSTAT3 settle_t0=%u measured=%u rearmed=%u", d_meas, d_meas_n, d_rearm_n); DBG Dbprintf("POSTSTAT evaluated=%u", d_post_eval); DBG Dbprintf("SIMSTAT loops=%u edges=%u frames=%u start_auth=%u answers=%u tracelen=%u", - d_loops, (unsigned)g_hitag_edges, d_frames, d_bits5, d_answers, - (unsigned)BigBuf_get_traceLen()); + d_loops, (unsigned)g_hitag_edges, d_frames, d_bits5, d_answers, + (unsigned)BigBuf_get_traceLen()); DBG Dbprintf("SIMSTAT2 auth64=%u authshort=%u pwd_ok=%u read_ok=%u", - d_auth64, d_auth_short, d_pwd_ok, d_read_ok); + d_auth64, d_auth_short, d_pwd_ok, d_read_ok); hitag_cleanup(ledcontrol); @@ -3592,8 +3601,8 @@ void ReaderHitag(const lf_hitag_data_t *payload, bool ledcontrol) { if (d_nodec == 1) { DBG for (uint32_t k = 0; (k + 9) < g_ht2_per_n; k += 10) { Dbprintf("PER[%2u] %3u %3u %3u %3u %3u %3u %3u %3u %3u %3u", k, - g_ht2_per[k], g_ht2_per[k+1], g_ht2_per[k+2], g_ht2_per[k+3], g_ht2_per[k+4], - g_ht2_per[k+5], g_ht2_per[k+6], g_ht2_per[k+7], g_ht2_per[k+8], g_ht2_per[k+9]); + g_ht2_per[k], g_ht2_per[k + 1], g_ht2_per[k + 2], g_ht2_per[k + 3], g_ht2_per[k + 4], + g_ht2_per[k + 5], g_ht2_per[k + 6], g_ht2_per[k + 7], g_ht2_per[k + 8], g_ht2_per[k + 9]); } } // One frame we could not decode is not the end of the exchange. @@ -3636,16 +3645,21 @@ out: // release allocated memory from BigBuff. BigBuf_free(); + // Exactly one NG response per command. On the abort path (checked == -1, + // a new command arrived while the reader loop was still running) send only + // the abort reply - falling through to a second reply_ng left the transport + // with a stray unsolicited frame, which the higher-latency BLE/FPC bridge + // desyncs on (USB tolerates it). if (checked == -1) { reply_ng(CMD_LF_HITAG_READER, PM3_ESOFT, NULL, 0); + } else { + reply_ng(CMD_LF_HITAG_READER + , (bSuccessful) ? PM3_SUCCESS : PM3_EFAILED + , (uint8_t *)tag.sectors + , tag_size + ); } - reply_ng(CMD_LF_HITAG_READER - , (bSuccessful) ? PM3_SUCCESS : PM3_EFAILED - , (uint8_t *)tag.sectors - , tag_size - ); - } void WriterHitag(const lf_hitag_data_t *payload, bool ledcontrol) { @@ -3838,7 +3852,7 @@ void WriterHitag(const lf_hitag_data_t *payload, bool ledcontrol) { if ((writestate == WRITE_STATE_PROG) && (tearoff_hook() == PM3_ETEAROFF)) { reply_ng(CMD_LF_HITAG2_WRITE, PM3_ETEAROFF, NULL, 0); StopTimestamp(); - lf_finalize(ledcontrol); + lf_finalize(ledcontrol); BigBuf_free(); return; } @@ -3962,13 +3976,13 @@ void WriterHitag(const lf_hitag_data_t *payload, bool ledcontrol) { out: if (d_badpern) { DBG Dbprintf("WRXPER %u %u %u %u %u %u %u %u %u %u %u %u", - d_badper[0], d_badper[1], d_badper[2], d_badper[3], - d_badper[4], d_badper[5], d_badper[6], d_badper[7], - d_badper[8], d_badper[9], d_badper[10], d_badper[11]); + d_badper[0], d_badper[1], d_badper[2], d_badper[3], + d_badper[4], d_badper[5], d_badper[6], d_badper[7], + d_badper[8], d_badper[9], d_badper[10], d_badper[11]); } DBG Dbprintf("WRXSTAT silent=%u undecodable=%u bits: %u %u %u %u raw: %u %u %u %u", - d_noans, d_badn, d_badnrz[0], d_badnrz[1], d_badnrz[2], d_badnrz[3], - d_badraw[0], d_badraw[1], d_badraw[2], d_badraw[3]); + d_noans, d_badn, d_badnrz[0], d_badnrz[1], d_badnrz[2], d_badnrz[3], + d_badraw[0], d_badraw[1], d_badraw[2], d_badraw[3]); StopTimestamp(); lf_finalize(ledcontrol); @@ -3976,15 +3990,20 @@ out: // release allocated memory from BigBuff. BigBuf_free(); + // Exactly one NG response per command. On the abort path (checked == -1, + // a new command arrived while the reader loop was still running) send only + // the abort reply - falling through to a second reply_ng left the transport + // with a stray unsolicited frame, which the higher-latency BLE/FPC bridge + // desyncs on (USB tolerates it). if (checked == -1) { reply_ng(CMD_LF_HITAG2_WRITE, PM3_ESOFT, NULL, 0); + } else { + reply_ng(CMD_LF_HITAG2_WRITE + , (bSuccessful) ? PM3_SUCCESS : PM3_EFAILED + , (uint8_t *)tag.sectors + , tag_size + ); } - - reply_ng(CMD_LF_HITAG2_WRITE - , (bSuccessful) ? PM3_SUCCESS : PM3_EFAILED - , (uint8_t *)tag.sectors - , tag_size - ); } @@ -4455,7 +4474,8 @@ bool ht2_packbits(uint8_t *nrz_samples, size_t nrzs, uint8_t *rx, size_t *rxlen) *rxlen = len; return true; -}int ht2_read_uid(uint8_t *uid, bool ledcontrol, bool send_answer, bool keep_field_up) { +} +int ht2_read_uid(uint8_t *uid, bool ledcontrol, bool send_answer, bool keep_field_up) { g_logging = false; diff --git a/armsrc/hitag2_crack.c b/armsrc/hitag2_crack.c index 1c9af611e..c2007576a 100644 --- a/armsrc/hitag2_crack.c +++ b/armsrc/hitag2_crack.c @@ -344,6 +344,11 @@ void ht2_crack2(uint8_t *nrar_hex) { uint8_t *e_response = BigBuf_calloc(32); lf_hitag_crack2_t *c2 = (lf_hitag_crack2_t *)BigBuf_calloc(sizeof(lf_hitag_crack2_t)); + if (e_response == NULL || c2 == NULL) { + BigBuf_free(); + reply_ng(CMD_LF_HITAG2_CRACK_2, PM3_EMALLOC, NULL, 0); + return; + } g_logging = false; LEDsoff(); @@ -450,6 +455,11 @@ void ht2_crack2(uint8_t *nrar_hex) { Dbprintf("Recovered " _YELLOW_("%4i") " bits of keystream", kslen); lf_hitag_crack_response_t *packet = (lf_hitag_crack_response_t *)BigBuf_calloc(sizeof(lf_hitag_crack_response_t)); + if (packet == NULL) { + BigBuf_free(); + reply_ng(CMD_LF_HITAG2_CRACK_2, PM3_EMALLOC, NULL, 0); + return; + } packet->status = 1; binarray2hex(c2->keybits, kslen, packet->data); diff --git a/armsrc/hitag_common.c b/armsrc/hitag_common.c index cab89ea68..29510deb6 100644 --- a/armsrc/hitag_common.c +++ b/armsrc/hitag_common.c @@ -762,7 +762,7 @@ void hitag_tag_send_frame_mc4k_sync(const uint8_t *frame, size_t frame_len, int : TEST_BIT_MSB(frame, idx - (size_t)sof_bits); bool loaded = bit ? (phase < HITAG_T_TAG_HALF_PERIOD) - : (phase >= HITAG_T_TAG_HALF_PERIOD); + : (phase >= HITAG_T_TAG_HALF_PERIOD); // Shallower load: switch on for only the first s_mod_duty periods of the // loaded half bit. The envelope the reader sees is a low pass of this, @@ -1146,18 +1146,18 @@ void hitag_tag_send_frame_ex(const uint8_t *frame, size_t frame_len, int sof_bit } if (lead_in) - switch (modulation) { - case AC4K: - case MC8K: { - while (GetPrecisionCounter() < T0 * 40) {}; // FADV - break; + switch (modulation) { + case AC4K: + case MC8K: { + while (GetPrecisionCounter() < T0 * 40) {}; // FADV + break; + } + case AC2K: + case MC4K: { + while (GetPrecisionCounter() < T0 * 20) {}; // STD + ADV + break; + } } - case AC2K: - case MC4K: { - while (GetPrecisionCounter() < T0 * 20) {}; // STD + ADV - break; - } - } // SOF - send start of frame for (size_t i = 0; i < sof_bits; i++) { diff --git a/armsrc/hitag_common.h b/armsrc/hitag_common.h index 772c38b8b..5e0b8f09a 100644 --- a/armsrc/hitag_common.h +++ b/armsrc/hitag_common.h @@ -75,7 +75,7 @@ void hitag_reader_receive_frame(uint8_t *rx, size_t sizeofrx, size_t *rxlen, uin int hitag_reader_transfer(const uint8_t *tx, size_t txlen, uint8_t *rx, size_t sizeofrx, size_t *rxlen, int t_wait, bool ledcontrol, hitag_mod_t modulation, uint8_t sof_bits, uint8_t send_sof); void hitag_tag_receive_frame_ex(uint8_t *rx, size_t sizeofrx, size_t *rxlen, uint32_t *start_time, - bool ledcontrol, int *overflow, bool sof_is_bit); + bool ledcontrol, int *overflow, bool sof_is_bit); void hitag_tag_receive_frame(uint8_t *rx, size_t sizeofrx, size_t *rxlen, uint32_t *start_time, bool ledcontrol, int *overflow); void hitag_tag_send_bit_mc4k_sync(int bit, bool ledcontrol); void hitag_tag_set_mod_polarity(bool invert); diff --git a/armsrc/i2c.c b/armsrc/i2c.c index edb4a3487..d33533b12 100644 --- a/armsrc/i2c.c +++ b/armsrc/i2c.c @@ -1388,6 +1388,25 @@ void SmartCardRaw(const smart_card_raw_t *p) { } } + // A card runs the protocol its TD1 names until a PPS changes it, so an APDU + // framed as T=1 against a card that came up in T=0 gets no answer at all. + // Do the switch here rather than making every caller run `smart pps --t1` + // first. PPS is only legal straight after an ATR, so take one; the exchange + // could not have worked without the switch anyway, so nothing is lost. + if (((flags & SC_RAW_T1) == SC_RAW_T1) && (s_pps_proto_cmd != I2C_DEVICE_CMD_SEND_T1)) { + + smart_card_atr_t card; + s_pps.reapply = false; // this is the negotiation + bool got_atr = GetATR(&card, false); + s_pps.reapply = true; + + if (got_atr && ((s_card_protocols & SC_PROTO_T1) == SC_PROTO_T1)) { + if ((sc_pps(1, 0x11) == false) && (g_dbglevel >= DBG_ERROR)) { + DbpString("SC: " _YELLOW_("PPS to T=1 refused") ", sending it anyway"); + } + } + } + if (((flags & SC_RAW) == SC_RAW) || ((flags & SC_RAW_T0) == SC_RAW_T0) || ((flags & SC_RAW_T1) == SC_RAW_T1)) { diff --git a/armsrc/i2c.h b/armsrc/i2c.h index 52617f47b..3cca53bdb 100644 --- a/armsrc/i2c.h +++ b/armsrc/i2c.h @@ -72,8 +72,17 @@ //Old value was 20/22 (16 kHz) - increased to 4/2 (100 kHz) and seems to be working reliably. //It was previously reported that 5/7 (59 kHz) was too fast, but this was before SIM module firmware updates. //Values above 4/2 (100 kHz) have been tested to work successfully, but they seem to run slower than 4/2. +#ifndef PM5 #define I2C_DELAY_1CLK_US 4 #define I2C_DELAY_2CLK_US 2 +#endif + + +//Gating for PM5 old values as the new ones seems to be incompatible until further changes +#ifdef PM5 +#define I2C_DELAY_1CLK_US 20 +#define I2C_DELAY_2CLK_US 22 +#endif // Only one delay per bit is rise time critical: the one bracketing an SDA // transition, where a released line has to charge through the pull-up before diff --git a/armsrc/iclass.c b/armsrc/iclass.c index 0c4660838..77300fc27 100644 --- a/armsrc/iclass.c +++ b/armsrc/iclass.c @@ -455,6 +455,13 @@ int do_iclass_simulation(int simulationMode, uint8_t *reader_mac_buf) { // receive command uint8_t *receivedCmd = BigBuf_calloc(MAX_FRAME_SIZE); + if (resp_anticoll == NULL || resp_csn == NULL || resp_conf == NULL || resp_cc == NULL || + resp_ff == NULL || resp_aia == NULL || receivedCmd == NULL) { + if (g_dbglevel >= DBG_ERROR) DbpString("iClass sim: failed to allocate buffers"); + BigBuf_free_keep_EM(); + return true; + } + // Prepare card messages tosend_t *ts = get_tosend(); @@ -501,6 +508,12 @@ int do_iclass_simulation(int simulationMode, uint8_t *reader_mac_buf) { //Each bit is doubled when modulated for FPGA, and we also have SOF and EOF (2 bytes) uint8_t *data_response = BigBuf_calloc((34 * 2) + 3); + if (data_generic_trace == NULL || data_response == NULL) { + if (g_dbglevel >= DBG_ERROR) DbpString("iClass sim: failed to allocate buffers"); + BigBuf_free_keep_EM(); + return true; + } + enum { IDLE, ACTIVATED, SELECTED, HALTED } chip_state = IDLE; bool button_pressed = false; @@ -1098,6 +1111,13 @@ int do_iclass_simulation_nonsec(void) { // receive command uint8_t *receivedCmd = BigBuf_calloc(MAX_FRAME_SIZE); + if (resp_anticoll == NULL || resp_csn == NULL || resp_conf == NULL || + resp_aia == NULL || receivedCmd == NULL) { + if (g_dbglevel >= DBG_ERROR) DbpString("iClass sim nonsec: failed to allocate buffers"); + BigBuf_free_keep_EM(); + return true; + } + // Prepare card messages tosend_t *ts = get_tosend(); ts->max = 0; @@ -1135,6 +1155,12 @@ int do_iclass_simulation_nonsec(void) { //Each bit is doubled when modulated for FPGA, and we also have SOF and EOF (2 bytes) uint8_t *data_response = BigBuf_calloc((32 + 2) * 2 + 2); + if (data_generic_trace == NULL || data_response == NULL) { + if (g_dbglevel >= DBG_ERROR) DbpString("iClass sim nonsec: failed to allocate buffers"); + BigBuf_free_keep_EM(); + return true; + } + enum { IDLE, ACTIVATED, SELECTED, HALTED } chip_state = IDLE; bool button_pressed = false; @@ -1634,12 +1660,12 @@ void iClass_Raw(uint8_t *msg) { start_time = eof_time + DELAY_ICLASS_VICC_TO_VCD_READER; } else { switch_clock_to_countsspclk(); + start_time = GetCountSspClk(); } uint8_t resp[ICLASS_BUFFER_SIZE] = {0}; uint16_t resp_len = 0; - start_time = GetCountSspClk(); bool is_update = rawlen > 0 && ((raw[0] & 0x0F) == ICLASS_CMD_UPDATE); uint8_t tries = is_update ? 1 : 3; uint16_t timeout = is_update ? ICLASS_READER_TIMEOUT_UPDATE : ICLASS_READER_TIMEOUT_ACTALL; diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c index 04372b10e..c89130d95 100644 --- a/armsrc/iso14443a.c +++ b/armsrc/iso14443a.c @@ -226,12 +226,18 @@ void printHf14aConfig(void) { Dbprintf(" [m] Magsafe polling............ %s", (hf14aconfig.magsafe == 1) ? _GREEN_("enabled") : _YELLOW_("disabled") ); - Dbprintf(" [p] Polling loop annotation.... %s %*D", - (hf14aconfig.polling_loop_annotation.frame_length <= 0) ? _YELLOW_("disabled") : _GREEN_("enabled"), - hf14aconfig.polling_loop_annotation.frame_length, - hf14aconfig.polling_loop_annotation.frame, - "" - ); + + // no frame to show when it is off, and %*D defaults a zero width to 16 bytes + if (hf14aconfig.polling_loop_annotation.frame_length <= 0) { + Dbprintf(" [p] Polling loop annotation.... %s", _YELLOW_("disabled")); + } else { + Dbprintf(" [p] Polling loop annotation.... %s %*D", + _GREEN_("enabled"), + hf14aconfig.polling_loop_annotation.frame_length, + hf14aconfig.polling_loop_annotation.frame, + "" + ); + } } /** @@ -600,7 +606,9 @@ void Demod14aReset(void) { } void Demod14aInit(uint8_t *d, uint16_t n, uint8_t *par) { - Demod.output_len = n; + // No ISO14443-A frame can be longer than MAX_FRAME_SIZE (FSD/FSC max out at 256 bytes), + // while callers happily pass PM3_CMD_DATA_SIZE sized receive buffers + Demod.output_len = MIN(n, MAX_FRAME_SIZE); Demod.output = d; Demod.parity = par; Demod14aReset(); @@ -713,12 +721,16 @@ RAMFUNC int ManchesterDecoding(uint8_t bit, uint16_t offset, uint32_t non_real_t } // Thinfilm, Kovio mangles ISO14443A in the way that they don't use start bit nor parity bits. -static int ManchesterDecoding_Thinfilm(uint8_t bit) { +// non_real_time is the sample count to timestamp with when called from a DMA sniff +// loop, where GetCountSspClk() has already run on past the frame. 0 = read the clock. +RAMFUNC int ManchesterDecoding_Thinfilm(uint8_t bit, uint32_t non_real_time) { if (Demod.len == Demod.output_len) { - // Flush last parity bits - Demod.parityBits <<= (8 - (Demod.len & 0x0007)); // left align remaining parity bits - Demod.parity[Demod.parityLen++] = Demod.parityBits; // and store them + // Flush last parity bits. Thinfilm has no parity bits and passes a NULL buffer + if (Demod.parity != NULL) { + Demod.parityBits <<= (8 - (Demod.len & 0x0007)); // left align remaining parity bits + Demod.parity[Demod.parityLen++] = Demod.parityBits; // and store them + } return true; } @@ -746,7 +758,7 @@ static int ManchesterDecoding_Thinfilm(uint8_t bit) { else if ((Demod.twoBits & 0x00EE) == 0x00E0) Demod.syncBit = 0; if (Demod.syncBit != 0xFFFF) { - Demod.startTime = (GetCountSspClk() & 0xfffffff8); + Demod.startTime = non_real_time ? non_real_time : (GetCountSspClk() & 0xfffffff8); Demod.startTime -= Demod.syncBit; Demod.bitCount = 1; // number of decoded data bits Demod.shiftReg = 1; @@ -1774,21 +1786,43 @@ void SimulateIso14443aTagEx(uint8_t tagType, uint16_t flags, uint8_t *useruid, u uint8_t receivedCmd[MAX_FRAME_SIZE] = { 0x00 }; uint8_t receivedCmdPar[MAX_PARITY_SIZE] = { 0x00 }; + //----------------------------------------------------------------------------- + // Note: we call FpgaDownloadAndGo_keep_EM(FPGA_BITSTREAM_HF) here although the + // FPGA isn't needed yet. iso14443a_setup() below does it otherwise, and a + // bitstream download frees and clears BigBuf - which by then holds the + // Emulator Memory and the precompiled anticollision responses. + //----------------------------------------------------------------------------- + FpgaDownloadAndGo_keep_EM(FPGA_BITSTREAM_HF); + // free eventually allocated BigBuf memory but keep Emulator Memory BigBuf_free_keep_EM(); - // Allocate 512 bytes for the dynamic modulation, created when the reader queries for it + // clear trace before allocating. The response buffers come out of the same + // pool and BigBuf_malloc() won't hand out memory the trace still occupies. + clear_trace(); + + // Buffers for the dynamic response, created when the reader queries for it. // Such a response is less time critical, so we can prepare them on the fly #define DYNAMIC_RESPONSE_BUFFER_SIZE 64 -#define DYNAMIC_MODULATION_BUFFER_SIZE 512 uint16_t dynamic_response_buffer_size = DYNAMIC_RESPONSE_BUFFER_SIZE; - uint16_t dynamic_modulation_buffer_size = DYNAMIC_MODULATION_BUFFER_SIZE; if (tagType == 10) { dynamic_response_buffer_size = ST25TA_EML_NDEF_MAX + 4; - dynamic_modulation_buffer_size = 4096; } + // prepare_tag_modulation() memcpy's the encoded answer out of the ToSend + // buffer, and tosend_stuffbit() hard caps that at TOSEND_BUFFER_SIZE, so the + // modulation can never be larger than that however big the response is. + // Encoding costs 9 bytes per response byte -- 8 data bits plus a parity bit -- + // and 4 more for start, stop and the correction bit. + // + // ST25TA used to ask for a flat 4096 here, 1788 bytes more than ToSend can + // ever hand it, which made it the largest single allocation of any tag + // simulation. The 512 the other tag types got was 68 bytes short of what a + // full 64 byte dynamic response needs, so those were refused at modulation + // time with an out-of-bound message + uint16_t dynamic_modulation_buffer_size = MIN((9 * dynamic_response_buffer_size) + 4, TOSEND_BUFFER_SIZE); + uint8_t *dynamic_response_buffer = BigBuf_calloc(dynamic_response_buffer_size); if (dynamic_response_buffer == NULL) { BigBuf_free_keep_EM(); @@ -1878,7 +1912,6 @@ void SimulateIso14443aTagEx(uint8_t tagType, uint16_t flags, uint8_t *useruid, u bool odd_reply = true; - clear_trace(); set_tracing(true); LED_A_ON(); @@ -2205,7 +2238,7 @@ void SimulateIso14443aTagEx(uint8_t tagType, uint16_t flags, uint8_t *useruid, u num_to_bytes(nonce, 4, dynamic_response_info.response); dynamic_response_info.response_n = 4; - prepare_tag_modulation(&dynamic_response_info, DYNAMIC_MODULATION_BUFFER_SIZE); + prepare_tag_modulation(&dynamic_response_info, dynamic_modulation_buffer_size); p_response = &dynamic_response_info; order = ORDER_AUTH; } else if (receivedCmd[0] == ISO14443A_CMD_RATS && len == 4) { // Received a RATS request @@ -2243,7 +2276,7 @@ void SimulateIso14443aTagEx(uint8_t tagType, uint16_t flags, uint8_t *useruid, u // prepare to send dynamic_response_info.response_n = 1 + 8 + 2; - prepare_tag_modulation(&dynamic_response_info, DYNAMIC_MODULATION_BUFFER_SIZE); + prepare_tag_modulation(&dynamic_response_info, dynamic_modulation_buffer_size); p_response = &dynamic_response_info; order = ORDER_AUTH; @@ -2294,7 +2327,7 @@ void SimulateIso14443aTagEx(uint8_t tagType, uint16_t flags, uint8_t *useruid, u dynamic_response_info.response_n = 1 + 8 + 2; - prepare_tag_modulation(&dynamic_response_info, DYNAMIC_MODULATION_BUFFER_SIZE); + prepare_tag_modulation(&dynamic_response_info, dynamic_modulation_buffer_size); p_response = &dynamic_response_info; order = ORDER_NONE; @@ -2325,7 +2358,7 @@ void SimulateIso14443aTagEx(uint8_t tagType, uint16_t flags, uint8_t *useruid, u // prepare to send dynamic_response_info.response_n = 1 + 16 + 2; - prepare_tag_modulation(&dynamic_response_info, DYNAMIC_MODULATION_BUFFER_SIZE); + prepare_tag_modulation(&dynamic_response_info, dynamic_modulation_buffer_size); p_response = &dynamic_response_info; order = ORDER_AUTH; @@ -2379,7 +2412,7 @@ void SimulateIso14443aTagEx(uint8_t tagType, uint16_t flags, uint8_t *useruid, u dynamic_response_info.response_n = 1 + 16 + 2; - prepare_tag_modulation(&dynamic_response_info, DYNAMIC_MODULATION_BUFFER_SIZE); + prepare_tag_modulation(&dynamic_response_info, dynamic_modulation_buffer_size); p_response = &dynamic_response_info; order = ORDER_NONE; @@ -2409,7 +2442,7 @@ void SimulateIso14443aTagEx(uint8_t tagType, uint16_t flags, uint8_t *useruid, u dynamic_response_info.response[1] = pack_live[1]; AddCrc14A(dynamic_response_info.response, 2); dynamic_response_info.response_n = 4; // 2 PACK + 2 CRC - prepare_tag_modulation(&dynamic_response_info, DYNAMIC_MODULATION_BUFFER_SIZE); + prepare_tag_modulation(&dynamic_response_info, dynamic_modulation_buffer_size); p_response = &dynamic_response_info; } else { if (g_dbglevel >= DBG_DEBUG) Dbprintf("Password did not match, NACK_IV."); @@ -2706,6 +2739,7 @@ static void TransmitFor14443a(const uint8_t *cmd, uint16_t len, uint32_t *timing // If further research is needed, an oscilloscope needs to be used to observe the specific DOUT modulation status. // --- // Clear TXRDY: + while (!FPGA_SSC_TX_Ready()) {} FPGA_SSC_TX_Value(SEC_Y); uint16_t c = 0; @@ -2939,6 +2973,7 @@ int EmSendCmd14443aRaw(const uint8_t *resp, uint16_t respLen) { while ((ThisTransferTime = GetCountSspClk()) & 0x00000007); // Clear TXRDY: + while (!FPGA_SSC_TX_Ready()) {} FPGA_SSC_TX_Value(SEC_F); // send cycle @@ -2961,6 +2996,7 @@ int EmSendCmd14443aRaw(const uint8_t *resp, uint16_t respLen) { } } LastTimeProxToAirStart = ThisTransferTime + (correction_needed ? 8 : 0); + return PM3_SUCCESS; } @@ -3089,7 +3125,7 @@ bool GetIso14443aAnswerFromTag_Thinfilm(uint8_t *receivedResponse, uint16_t rec_ if (FPGA_SSC_RX_Ready()) { b = (uint8_t)FPGA_SSC_RX_Value(); - if (ManchesterDecoding_Thinfilm(b)) { + if (ManchesterDecoding_Thinfilm(b, 0)) { *received_len = Demod.len; LogTrace(receivedResponse, Demod.len, Demod.startTime * 16 - DELAY_AIR2ARM_AS_READER, Demod.endTime * 16 - DELAY_AIR2ARM_AS_READER, NULL, false); return true; @@ -3189,6 +3225,18 @@ static uint16_t ReaderReceiveOffset(uint8_t *receivedAnswer, uint16_t answer_len return Demod.len; } +// End of the last frame we transmitted, and start of the last frame we +// received, both in SSP clock ticks. Callers that need the tag's frame delay +// time take the difference; LogTrace scales the same values by 16 to get +// carrier periods. +uint32_t iso14a_last_tx_end(void) { + return LastTimeProxToAirStart + LastProxToAirDuration; +} + +uint32_t iso14a_last_rx_start(void) { + return Demod.startTime; +} + static uint16_t ReaderReceiveEx(uint8_t *receivedAnswer, uint16_t answer_maxlen, uint8_t *par, bool no_parity) { if (GetIso14443aAnswerFromTag(receivedAnswer, answer_maxlen, par, 0, no_parity) == false) { return 0; @@ -3202,10 +3250,255 @@ uint16_t ReaderReceive(uint8_t *receivedAnswer, uint16_t answer_maxlen, uint8_t return ReaderReceiveEx(receivedAnswer, answer_maxlen, par, false); } +// Number of symbols in a bit oriented ANTICOLLISION answer that starts `known` +// bits into the 40 bit UID+BCC of one cascade level. The byte the reader split +// is completed without a parity bit, every whole byte after it carries one. +static uint16_t anticoll_answer_symbols(uint8_t known) { + + uint16_t bits = 40 - known; + uint16_t split = known & 7; + uint16_t symbols = 0; + + if (split) { + uint16_t first = 8 - split; // completes the split byte, no parity + symbols += first; + bits -= first; + } + + // whole bytes from here on, one parity bit each + symbols += bits + (bits / 8); + return symbols; +} + +// Encode the tail of a bit oriented ANTICOLLISION answer: the `40 - known` bits +// of UID+BCC that the reader has not resolved yet. The byte the reader split is +// completed without a parity bit, every whole byte after it carries one, so +// CodeIso14443aAsTagPar() cannot build this - it only speaks whole bytes. +// known == 0 is the ordinary "send me the whole UID" answer. +// +// Every bit from `coll_from` on is sent as a collision instead of as data, and a +// byte holding one cannot carry a real parity bit either. coll_from == 40 is a +// clean answer, 0 collides the whole frame. +static void CodeIso14443aAsTagAnticollTail(const uint8_t *uid, uint8_t known, uint8_t coll_from) { + + tosend_reset(); + + tosend_t *ts = get_tosend(); + + // 1 correction byte + 1 start bit + 1 stop bit on top of the payload + if (3 + (int)anticoll_answer_symbols(known) > TOSEND_BUFFER_SIZE) { + Dbprintf("CodeIso14443aAsTagAnticollTail: frame too large (%u known)", known); + return; + } + + // Correction bit, might be removed when not needed + tosend_stuffbit(0); + tosend_stuffbit(0); + tosend_stuffbit(0); + tosend_stuffbit(0); + tosend_stuffbit(1); // <----- + tosend_stuffbit(0); + tosend_stuffbit(0); + tosend_stuffbit(0); + + // Send startbit + ts->buf[++ts->max] = SEC_D; + LastProxToAirDuration = 8 * ts->max - 4; + + uint8_t first = known >> 3; // byte the reader stopped in + uint8_t split = known & 7; // bits of it the reader already has + + for (uint8_t i = first; i < 5; i++) { + + uint8_t skip = (i == first) ? split : 0; + bool collided = false; + + for (uint8_t j = skip; j < 8; j++) { + + if (((i * 8) + j) >= coll_from) { + ts->buf[++ts->max] = SEC_COLL; + LastProxToAirDuration = 8 * ts->max; + collided = true; + } else if (uid[i] & (1 << j)) { + ts->buf[++ts->max] = SEC_D; + LastProxToAirDuration = 8 * ts->max - 4; + } else { + ts->buf[++ts->max] = SEC_E; + LastProxToAirDuration = 8 * ts->max; + } + } + + // no parity bit for the byte the reader split + if (skip) { + continue; + } + + if (collided) { + ts->buf[++ts->max] = SEC_COLL; + LastProxToAirDuration = 8 * ts->max; + } else if (oddparity8(uid[i])) { + ts->buf[++ts->max] = SEC_D; + LastProxToAirDuration = 8 * ts->max - 4; + } else { + ts->buf[++ts->max] = SEC_E; + LastProxToAirDuration = 8 * ts->max; + } + } + + // Send stopbit + ts->buf[++ts->max] = SEC_F; + + // Convert from last byte pos to length + ts->max++; +} + +// Store whatever CodeIso14443aAsTag*() just built into `buffer` and describe it +// in `response_info`, the way prepare_allocated_tag_modulation() does for the +// frames it can encode itself. +static bool antifuzz_store_modulation(tag_response_info_t *response_info, + uint8_t **buffer, size_t *max_buffer_size) { + + const tosend_t *ts = get_tosend(); + if (ts->max <= 0 || (size_t)ts->max > *max_buffer_size) { + return false; + } + + response_info->modulation = *buffer; + memcpy(response_info->modulation, ts->buf, ts->max); + response_info->modulation_n = ts->max; + response_info->ProxToAirDuration = LastProxToAirDuration; + + *buffer += ts->max; + *max_buffer_size -= ts->max; + return true; +} + +// Modulate an all-collision answer into `buffer` and describe it in +// `response_info`, the way prepare_allocated_tag_modulation() does for ordinary +// frames. CodeIso14443aAsTag() cannot build these: a bit oriented answer is not +// a whole number of bytes and every symbol in it is a collision. +// One place to notice a reader getting deeper than it has been in this +// anticollision attempt. `depth` counts 41 steps per cascade level - the 40 bit +// counts a reader can claim, plus the SELECT that follows them - so a reader +// climbing levels keeps making progress rather than restarting the count. +static void antifuzz_track_depth(uint8_t level, uint8_t known, uint16_t *depth, + uint8_t *max_level, uint8_t *max_known) { + + uint16_t step = ((uint16_t)(level - 1) * 41) + known + 1; + if (step > *depth) { + *depth = step; + LED_C_INV(); + } + + if (level > *max_level) { + *max_level = level; + *max_known = known; + } else if (level == *max_level && known > *max_known) { + *max_known = known; + } +} + +// Precomputed answers. Modulating a frame takes long enough that the reader's +// frame delay window is gone before the answer is ready - the same reason +// `hf 14a sim` builds its answers up front - so everything this loop can send is +// modulated before the field is even up. +#define ANTIFUZZ_MAX_LEVEL 7 // SEL 0x93..0x9F +#define ANTIFUZZ_NVB_COUNT 40 // 0..39 UID bits already known to the reader +// Collision mode keeps the UID clean up to here and collides everything from it +// on. Byte 0 is what a reader sanity checks a UID by, so leaving exactly that +// much alone is what lets the other 24 bits collide without the reader deciding +// the card is junk and dropping it - every branch of the tree still resolves to +// a UID starting with a real manufacturer byte. One collided bit costs the +// reader one round trip, so this is also what sets how hard it has to work. +#define ANTIFUZZ_COLL_FROM 8 +#define ANTIFUZZ_MAX_ANNOUNCED 3 // cascade levels ISO 14443-3 actually defines +#define ANTIFUZZ_RESP_ATQA 0 +#define ANTIFUZZ_RESP_SAK 1 +// One block of ANTIFUZZ_NVB_COUNT answers per UID the mode can hand out. Cascade +// mode has one UID per cascade level; collision mode only needs two, one with a +// cascade tag and one without, and puts its BCC answers above them. The two +// layouts overlap - only ever one of them is prepared. +#define ANTIFUZZ_RESP_BASE 2 +// Collision mode needs a block per announced cascade level plus one of filler, +// and above them one clean BCC answer per value it could owe a reader. Cascade +// mode uses a block per level and none of the BCC answers, so the two layouts +// overlap - only ever one of them is prepared. +#define ANTIFUZZ_MAX_BLOCKS (ANTIFUZZ_MAX_ANNOUNCED + 1) +#define ANTIFUZZ_RESP_BCC (ANTIFUZZ_RESP_BASE + (ANTIFUZZ_MAX_BLOCKS * ANTIFUZZ_NVB_COUNT)) +#define ANTIFUZZ_RESP_COUNT (ANTIFUZZ_RESP_BCC + 256 > ANTIFUZZ_RESP_BASE + (ANTIFUZZ_MAX_LEVEL * ANTIFUZZ_NVB_COUNT) \ + ? ANTIFUZZ_RESP_BCC + 256 \ + : ANTIFUZZ_RESP_BASE + (ANTIFUZZ_MAX_LEVEL * ANTIFUZZ_NVB_COUNT)) +// worst case is cascade mode: 1025 bytes of modulation per cascade level, plus +// the two fixed answers +#define ANTIFUZZ_MOD_SIZE ((ANTIFUZZ_MAX_LEVEL * 1025) + 128) + +// The UIDs `hf 14a antifuzz` hands out, one per ATQA size. A reader collects +// them three bytes at a time behind a cascade tag, until the last cascade level +// its ATQA announced, which carries four. +static const uint8_t antifuzz_uid_4b[4] = { 0x9B, 0x49, 0x03, 0x51 }; +static const uint8_t antifuzz_uid_7b[7] = { 0x04, 0x49, 0x03, 0x52, 0x92, 0x9C, 0x80 }; +static const uint8_t antifuzz_uid_10b[10] = { 0x04, 0x49, 0x03, 0x53, 0x92, 0x9C, 0xAB, 0xD1, 0x4F, 0x80 }; + +// Block b answers for cascade level b + 1, and the last block also answers for +// every level past it. +static uint8_t antifuzz_block_of(uint8_t count, uint8_t level) { + return (level <= count) ? (level - 1) : (count - 1); +} + +// The four UID bytes a cascade level hands out, with its BCC appended. Levels +// below the last announced one carry a cascade tag and three UID bytes, the last +// announced level carries four, and anything past it is off the end of the UID +// altogether - it is only ever reached because the SAK keeps claiming the UID is +// incomplete, so it gets filler that is obviously not part of the card. +static void antifuzz_level_uid(uint8_t *uid, uint8_t level, uint8_t announced_levels, const uint8_t *src) { + + if (level > announced_levels) { + // 0x88 would read as one more cascade tag and 0x08 as a random ID + uid[0] = 0x11; + uid[1] = level; + uid[2] = 0x01; + uid[3] = 0x00; + } else if (level < announced_levels) { + uid[0] = MIFARE_SELECT_CT; + memcpy(uid + 1, src + (3 * (level - 1)), 3); + } else { + memcpy(uid, src + (3 * (level - 1)), 4); + } + + uid[4] = uid[0] ^ uid[1] ^ uid[2] ^ uid[3]; +} + // This function misstreats the ISO 14443a anticollision procedure. -// by fooling the reader there is a collision and forceing the reader to -// increase the uid bytes. The might be an overflow, DoS will occur. -void iso14443a_antifuzz(uint32_t flags) { +// +// ANTIFUZZ_MODE_CASCADE +// Every SAK keeps the cascade bit set, i.e. "the UID is not complete yet", so +// a reader that believes the card asks for one more cascade level and keeps +// growing its UID buffer past the three levels ISO 14443-3 defines. We answer +// SEL bytes 0x93 up to 0x9F, so a reader that simply increments is followed +// all the way up. +// +// The UID matters only in that the reader has to accept it: a conforming +// reader counts the cascade levels the ATQA promised and throws the card away +// if it meets a cascade tag in the last of them, so the cascade tag is sent +// only below that level. +// +// ANTIFUZZ_MODE_COLLISION +// Byte 0 of the UID goes out clean and every bit after it collides, so the +// reader has to resolve 24 bits one round trip at a time. Whatever it picks +// along the way it tells us, which means that once it has all 32 bits the BCC +// it is owed is computable - so it gets a real one, its SELECT succeeds, and +// the SAK sends it round the same 26 frame exercise one cascade level up. +// +// Colliding byte 0 as well only ever produced a UID of all ones, which readers +// recognise as junk and drop before they even ask for the BCC. Leaving that +// one byte alone is what buys the other 24 bits: every branch of the tree +// still resolves to a UID starting with a real manufacturer byte, so there is +// never a reason to bail out early. +// +// Between them that is 183 answers per poll against the 3 a real card needs, +// and it leans on the bit tree walker, the NVB parser, the partial byte +// reassembler and the cascade handler all at once. +void iso14443a_antifuzz(uint32_t flags, uint8_t mode) { // We need to listen to the high-frequency, peak-detected path. iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN); @@ -3219,8 +3512,14 @@ void iso14443a_antifuzz(uint32_t flags) { // allocate buffers: uint8_t *received = BigBuf_calloc(MAX_FRAME_SIZE); uint8_t *receivedPar = BigBuf_calloc(MAX_PARITY_SIZE); - uint8_t *resp = BigBuf_calloc(20); - if (received == NULL || receivedPar == NULL || resp == NULL) { + tag_response_info_t *responses = (tag_response_info_t *)BigBuf_calloc(ANTIFUZZ_RESP_COUNT * sizeof(tag_response_info_t)); + uint8_t *respdata = BigBuf_calloc(64); + uint8_t *modulation = BigBuf_calloc(ANTIFUZZ_MOD_SIZE); + // one byte per possible BCC, so each precomputed answer has something stable + // to point its trace payload at + uint8_t *bcc_bytes = (mode == ANTIFUZZ_MODE_COLLISION) ? BigBuf_calloc(256) : respdata; + if (received == NULL || receivedPar == NULL || responses == NULL || respdata == NULL || + modulation == NULL || bcc_bytes == NULL) { if (g_dbglevel >= DBG_ERROR) DbpString("Anti-fuzz: failed to allocate buffers"); reply_ng(CMD_HF_ISO14443A_ANTIFUZZ, PM3_EMALLOC, NULL, 0); switch_off(); @@ -3228,56 +3527,190 @@ void iso14443a_antifuzz(uint32_t flags) { return; } - // BigBuf_calloc() already zeroed the receive buffers - memset(resp, 0xFF, 20); + // ATQA, bit 7..6 of the first byte announce the UID size, and that size is + // also how many cascade levels the reader expects to walk before the UID is + // complete: 1 for a 4 byte UID, 2 for 7 bytes, 3 for 10 bytes. + uint8_t atqa0 = 0x04; + uint8_t announced_levels = 1; + const uint8_t *uid_src = antifuzz_uid_4b; + if (IS_FLAG_UID_IN_DATA(flags, 7)) { + atqa0 = 0x44; + announced_levels = 2; + uid_src = antifuzz_uid_7b; + } else if (IS_FLAG_UID_IN_DATA(flags, 10)) { + atqa0 = 0x84; + announced_levels = 3; + uid_src = antifuzz_uid_10b; + } + uint8_t *free_buffer = modulation; + size_t free_size = ANTIFUZZ_MOD_SIZE; + uint8_t *d = respdata; + bool ok = true; + + responses[ANTIFUZZ_RESP_ATQA].response = d; + responses[ANTIFUZZ_RESP_ATQA].response_n = 2; + d[0] = atqa0; + d[1] = 0x00; + d += 2; + + // SAK with the cascade bit set - this, not the UID, is what keeps the reader + // asking for one more level + responses[ANTIFUZZ_RESP_SAK].response = d; + responses[ANTIFUZZ_RESP_SAK].response_n = 3; + d[0] = 0x04; + AddCrc14A(d, 1); + d += 3; + + ok = prepare_allocated_tag_modulation(&responses[ANTIFUZZ_RESP_ATQA], &free_buffer, &free_size) && + prepare_allocated_tag_modulation(&responses[ANTIFUZZ_RESP_SAK], &free_buffer, &free_size); + + // Cascade mode walks a reader past every level ISO 14443-3 defines, so it + // needs an answer for each. Collision mode makes the reader earn each level, + // and only needs the announced ones plus a block of filler beyond them. + uint8_t nblocks = (mode == ANTIFUZZ_MODE_COLLISION) ? (announced_levels + 1) : ANTIFUZZ_MAX_LEVEL; + uint8_t coll_from = (mode == ANTIFUZZ_MODE_COLLISION) ? ANTIFUZZ_COLL_FROM : ANTIFUZZ_NVB_COUNT; + + for (uint8_t b = 0; ok && b < nblocks; b++) { + + uint8_t *uid = d; + d += 5; + antifuzz_level_uid(uid, b + 1, announced_levels, uid_src); + + // One answer per NVB the reader can ask with. Cascade mode never + // collides, so a conforming reader only ever asks with NVB 0x20 there, + // but answering a bit oriented request with the whole UID hands it a + // frame of the wrong length and it drops the card. + for (uint8_t known = 0; ok && known < ANTIFUZZ_NVB_COUNT; known++) { + tag_response_info_t *ri = &responses[ANTIFUZZ_RESP_BASE + (b * ANTIFUZZ_NVB_COUNT) + known]; + ri->response = uid + (known >> 3); + ri->response_n = 5 - (known >> 3); + CodeIso14443aAsTagAnticollTail(uid, known, coll_from); + ok = antifuzz_store_modulation(ri, &free_buffer, &free_size); + } + } + + if (mode == ANTIFUZZ_MODE_COLLISION) { + + // The one answer in this mode that does not collide. By the time the + // reader asks with all 32 UID bits it has told us every one it settled + // on, so the BCC it is owed is just those four bytes XORed - whichever + // way it came down the tree. All 256 are ready, and none of them cares + // which cascade level or which UID it is answering for. + for (uint16_t b = 0; ok && b < 256; b++) { + tag_response_info_t *ri = &responses[ANTIFUZZ_RESP_BCC + b]; + bcc_bytes[b] = (uint8_t)b; + ri->response = &bcc_bytes[b]; + ri->response_n = 1; + ok = prepare_allocated_tag_modulation(ri, &free_buffer, &free_size); + } + } + + if (ok == false) { + if (g_dbglevel >= DBG_ERROR) DbpString("Anti-fuzz: failed to prepare tag answers"); + reply_ng(CMD_HF_ISO14443A_ANTIFUZZ, PM3_EMALLOC, NULL, 0); + switch_off(); + BigBuf_free_keep_EM(); + return; + } + + uint8_t max_level = 0; // deepest cascade level a reader was driven to + uint8_t max_known = 0; // and the most UID bits it claimed at that level + uint16_t rounds = 0; // anticollision attempts it started + uint16_t depth = 0; // how far into the current attempt it has got + + // LED A lit for the whole run + // LED B lit while an anticollision attempt is in progress, dark once the + // reader has given up on it and gone back to polling + // LED C flips every time the reader gets one step deeper than it has been + // in this attempt, so a fast flicker is a reader walking the UID tree + // LED D flips on every frame we answer LED_A_ON(); + LED_B_OFF(); + LED_C_OFF(); + for (;;) { WDT_HIT(); // Clean receive command buffer if (GetIso14443aCommandFromReader(received, MAX_FRAME_SIZE, receivedPar, &len) == false) { - Dbprintf("Anti-fuzz stopped. Trace length: %d ", BigBuf_get_traceLen()); + Dbprintf("Anti-fuzz stopped. " _YELLOW_("%u") " anticollision rounds, deepest was cascade level " + _YELLOW_("%u") " at " _YELLOW_("%u") " UID bits, trace length " _YELLOW_("%d"), + rounds, max_level, max_known, BigBuf_get_traceLen()); break; } - if (received[0] == ISO14443A_CMD_WUPA || received[0] == ISO14443A_CMD_REQA) { - resp[0] = 0x04; - resp[1] = 0x00; - if (IS_FLAG_UID_IN_DATA(flags, 7)) { - resp[0] = 0x44; - } - - EmSendCmd(resp, 2); - continue; - } - - // Received request for UID (cascade 1) - //if (received[1] >= 0x20 && received[1] <= 0x57 && received[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT) { - if (received[1] >= 0x20 && received[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT) { - resp[0] = 0xFF; - resp[1] = 0xFF; - resp[2] = 0xFF; - resp[3] = 0xFF; - resp[4] = resp[0] ^ resp[1] ^ resp[2] ^ resp[3]; - - if (IS_FLAG_UID_IN_DATA(flags, 7)) { - resp[0] = MIFARE_SELECT_CT; - } - - // trigger a faulty/collision response - EmSendCmdEx(resp, 5, true); - if (g_dbglevel >= DBG_EXTENDED) Dbprintf("ANTICOLL or SELECT %x", received[1]); + if (len == 1 && (received[0] == ISO14443A_CMD_WUPA || received[0] == ISO14443A_CMD_REQA)) { + // polling from scratch, so whatever the reader had collected is gone + LED_B_OFF(); + depth = 0; + EmSendPrecompiledCmd(&responses[ANTIFUZZ_RESP_ATQA]); LED_D_INV(); - continue; - } else if (received[1] == 0x20 && received[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2) { // Received request for UID (cascade 2) - if (g_dbglevel >= DBG_EXTENDED) Dbprintf("ANTICOLL or SELECT_2"); - } else if (received[1] == 0x70 && received[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT) { // Received a SELECT (cascade 1) - } else if (received[1] == 0x70 && received[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2) { // Received a SELECT (cascade 2) - } else { - Dbprintf("unknown command %x", received[0]); } + + // Everything below is a SEL frame. ISO 14443-3 only defines cascade + // levels 1..3 (0x93 / 0x95 / 0x97), the levels above them are the whole + // point of the exercise. + if (len < 2 || received[0] < ISO14443A_CMD_ANTICOLL_OR_SELECT || + received[0] > 0x9F || (received[0] & 1) == 0) { + // a frame we do not answer is never traced by EmLogTrace, and a + // reader that walked off somewhere unexpected is exactly what this + // command is looking for, so log it here + LogTrace(received, len, Uart.startTime * 16 - DELAY_AIR2ARM_AS_TAG, + Uart.endTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true); + if (g_dbglevel >= DBG_EXTENDED) Dbprintf("unknown command %02x (len %d)", received[0], len); + continue; + } + + uint8_t level = ((received[0] - ISO14443A_CMD_ANTICOLL_OR_SELECT) >> 1) + 1; + if (level > max_level && g_dbglevel >= DBG_INFO) { + Dbprintf("cascade level " _YELLOW_("%u") " (SEL %02x)", level, received[0]); + } + + if (depth == 0) { + rounds++; + LED_B_ON(); + } + + // worked out once, before the frame delay this has to answer inside + uint16_t block = ANTIFUZZ_RESP_BASE + (antifuzz_block_of(nblocks, level) * ANTIFUZZ_NVB_COUNT); + + uint8_t nvb = received[1]; + + // SELECT: SEL 70 uid0 uid1 uid2 uid3 bcc crc crc. The reader claims all + // 40 bits here, which is as deep as a cascade level goes. + if (nvb == 0x70) { + antifuzz_track_depth(level, 40, &depth, &max_level, &max_known); + EmSendPrecompiledCmd(&responses[ANTIFUZZ_RESP_SAK]); + LED_D_INV(); + continue; + } + + // ANTICOLLISION. NVB counts SEL and NVB themselves, so 0x20 means "no + // UID bits known" and 0x67 means "39 bits known". + if (nvb < 0x20 || nvb > 0x67 || (nvb & 0x0F) > 7) { + LogTrace(received, len, Uart.startTime * 16 - DELAY_AIR2ARM_AS_TAG, + Uart.endTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true); + if (g_dbglevel >= DBG_EXTENDED) Dbprintf("bad NVB %02x (SEL %02x)", nvb, received[0]); + continue; + } + + uint8_t known = (uint8_t)((((nvb >> 4) - 2) * 8) + (nvb & 0x0F)); + antifuzz_track_depth(level, known, &depth, &max_level, &max_known); + + // SEL 60 u0 u1 u2 u3 - the reader has resolved the whole UID and wants the + // BCC for it. Give it the real one: its SELECT then succeeds, and the + // SAK cascades it into the same exercise one level deeper. + if (mode == ANTIFUZZ_MODE_COLLISION && known == 32 && len >= 6) { + uint8_t bcc = received[2] ^ received[3] ^ received[4] ^ received[5]; + EmSendPrecompiledCmd(&responses[ANTIFUZZ_RESP_BCC + bcc]); + LED_D_INV(); + continue; + } + + EmSendPrecompiledCmd(&responses[block + known]); + LED_D_INV(); } reply_ng(CMD_HF_ISO14443A_ANTIFUZZ, PM3_SUCCESS, NULL, 0); @@ -3643,6 +4076,15 @@ int iso14443a_select_cardEx(uint8_t *uid_ptr, iso14a_card_select_t *p_card, uint return 0; } + // An ATS is TL, the bytes TL counts, and two CRC bytes on top. + // Anything shorter, like a 4 bit NAK is not ATS + if (len < 3 || resp[0] != len - 2) { + if (g_dbglevel >= DBG_INFO) { + Dbprintf("Card answered RATS with %i byte(s), not an ATS. Staying at ISO14443-3", len); + } + return 2; + } + if (p_card) { memcpy(p_card->ats, resp, sizeof(p_card->ats)); p_card->ats_len = len; @@ -3703,7 +4145,14 @@ int iso14443a_fast_select_card(const uint8_t *uid_ptr, uint8_t num_cascades) { void iso14443a_setup(uint8_t fpga_minor_mode) { set_session_channel(false); - FpgaDownloadAndGo(FPGA_BITSTREAM_HF); + + // keep_EM: a bitstream download frees and clears BigBuf to get scratch space + // for the decompressor, and the plain FpgaDownloadAndGo() takes the emulator + // memory with it. Every 14a command comes through here, so a card image that + // `eload` had just put in place was destroyed by the next `hf 14a` command + // whenever the HF bitstream was not already resident. The decompressor still + // has BigBuf below the emulator memory to work in. + FpgaDownloadAndGo_keep_EM(FPGA_BITSTREAM_HF); // Set up the synchronous serial port FpgaSetupSsc(FPGA_MAJOR_MODE_HF_ISO14443A); // connect Demodulated Signal to ADC: @@ -4780,9 +5229,21 @@ void SimulateIso14443aTagAID(uint8_t tagType, uint16_t flags, uint8_t *uid, return; } + //----------------------------------------------------------------------------- + // Note: we call FpgaDownloadAndGo_keep_EM(FPGA_BITSTREAM_HF) here although the + // FPGA isn't needed yet. iso14443a_setup() below does it otherwise, and a + // bitstream download frees and clears BigBuf - which by then holds the + // Emulator Memory and the precompiled anticollision responses. + //----------------------------------------------------------------------------- + FpgaDownloadAndGo_keep_EM(FPGA_BITSTREAM_HF); + // free eventually allocated BigBuf memory but keep Emulator Memory BigBuf_free_keep_EM(); + // clear trace before allocating. The response buffers come out of the same + // pool and BigBuf_malloc() won't hand out memory the trace still occupies. + clear_trace(); + // Response payloads must fit within the dynamic response buffer, // accounting for 1-byte IBlock header + 1-byte optional CID (offset 0 or 1) if (selectaid_response_len + 2 > DYNAMIC_RESPONSE_BUFFER2_SIZE || @@ -4828,7 +5289,6 @@ void SimulateIso14443aTagAID(uint8_t tagType, uint16_t flags, uint8_t *uid, int sentCount = 0; bool odd_reply = true; - clear_trace(); set_tracing(true); LED_A_ON(); diff --git a/armsrc/iso14443a.h b/armsrc/iso14443a.h index 2b4f070fa..faa467b11 100644 --- a/armsrc/iso14443a.h +++ b/armsrc/iso14443a.h @@ -142,6 +142,7 @@ void Uart14aReset(void); void Uart14aInit(uint8_t *d, uint16_t n, uint8_t *par); RAMFUNC bool MillerDecoding(uint8_t bit, uint32_t non_real_time); RAMFUNC int ManchesterDecoding(uint8_t bit, uint16_t offset, uint32_t non_real_time); +RAMFUNC int ManchesterDecoding_Thinfilm(uint8_t bit, uint32_t non_real_time); int RAMFUNC SniffIso14443a(uint8_t param); void SimulateIso14443aTag(uint8_t tagType, uint16_t flags, uint8_t *useruid, uint8_t exitAfterNReads); @@ -167,13 +168,15 @@ bool SimulateIso14443aInit(uint8_t tagType, uint16_t flags, uint8_t *data, uint8_t *ulc_key); bool GetIso14443aCommandFromReader(uint8_t *received, uint16_t received_maxlen, uint8_t *par, int *len); -void iso14443a_antifuzz(uint32_t flags); +void iso14443a_antifuzz(uint32_t flags, uint8_t mode); int GetATQA(uint8_t *resp, uint16_t resp_len, uint8_t *resp_par, const iso14a_polling_parameters_t *polling_parameters); void ReaderIso14443a(PacketCommandNG *c); void ReaderTransmit(const uint8_t *frame, uint16_t len, uint32_t *timing); void ReaderTransmitBitsPar(const uint8_t *frame, uint16_t bits, uint8_t *par, uint32_t *timing); void ReaderTransmitPar(const uint8_t *frame, uint16_t len, uint8_t *par, uint32_t *timing); uint16_t ReaderReceive(uint8_t *receivedAnswer, uint16_t answer_maxlen, uint8_t *par); +uint32_t iso14a_last_tx_end(void); +uint32_t iso14a_last_rx_start(void); void iso14443a_setup(uint8_t fpga_minor_mode); int iso14_apdu(uint8_t *cmd, uint16_t cmd_len, bool send_chaining, void *data, uint16_t data_len, uint8_t *res); diff --git a/armsrc/iso14443b.c b/armsrc/iso14443b.c index f2d4a6844..4102447ee 100644 --- a/armsrc/iso14443b.c +++ b/armsrc/iso14443b.c @@ -211,12 +211,18 @@ static hf14b_config_t hf14bconfig = { {{0}, 0, 0, 0} }; void printHf14bConfig(void) { DbpString(_CYAN_("HF 14b config")); - Dbprintf(" [p] Polling loop annotation.... %s %*D", - (hf14bconfig.polling_loop_annotation.frame_length <= 0) ? _YELLOW_("disabled") : _GREEN_("enabled"), - hf14bconfig.polling_loop_annotation.frame_length, - hf14bconfig.polling_loop_annotation.frame, - "" - ); + + // no frame to show when it is off, and %*D defaults a zero width to 16 bytes + if (hf14bconfig.polling_loop_annotation.frame_length <= 0) { + Dbprintf(" [p] Polling loop annotation.... %s", _YELLOW_("disabled")); + } else { + Dbprintf(" [p] Polling loop annotation.... %s %*D", + _GREEN_("enabled"), + hf14bconfig.polling_loop_annotation.frame_length, + hf14bconfig.polling_loop_annotation.frame, + "" + ); + } } void setHf14bConfig(const hf14b_config_t *hc) { @@ -820,6 +826,13 @@ void SimulateIso14443bTag(const uint8_t *pupi) { CodeIso14443bAsTag(respATQB, sizeof(respATQB)); uint8_t *encodedATQB = BigBuf_calloc(ts->max); uint16_t encodedATQBLen = ts->max; + + if (receivedCmd == NULL || encodedATQB == NULL) { + if (g_dbglevel >= DBG_ERROR) DbpString("14b sim: failed to allocate buffers"); + switch_off(); + return; + } + memcpy(encodedATQB, ts->buf, ts->max); @@ -827,6 +840,13 @@ void SimulateIso14443bTag(const uint8_t *pupi) { CodeIso14443bAsTag(respOK, sizeof(respOK)); uint8_t *encodedOK = BigBuf_calloc(ts->max); uint16_t encodedOKLen = ts->max; + + if (encodedOK == NULL) { + if (g_dbglevel >= DBG_ERROR) DbpString("14b sim: failed to allocate buffers"); + switch_off(); + return; + } + memcpy(encodedOK, ts->buf, ts->max); // Simulation loop @@ -2443,7 +2463,7 @@ static int iso14443b_select_picopass_card(picopass_hdr_t *hdr) { // Set up ISO 14443 Type B communication (similar to iso14443a_setup) // field is setup for "Sending as Reader" -void iso14443b_setup(void) { +int iso14443b_setup(void) { switch_off(); // disconnect raw SpinDelay(20); @@ -2454,8 +2474,16 @@ void iso14443b_setup(void) { BigBuf_free(); // Initialize Demod and Uart structs - Demod14bInit(BigBuf_calloc(MAX_FRAME_SIZE), MAX_FRAME_SIZE); - Uart14bInit(BigBuf_calloc(MAX_FRAME_SIZE)); + uint8_t *demod_buf = BigBuf_calloc(MAX_FRAME_SIZE); + uint8_t *uart_buf = BigBuf_calloc(MAX_FRAME_SIZE); + if (demod_buf == NULL || uart_buf == NULL) { + if (g_dbglevel >= DBG_ERROR) DbpString("14b setup: failed to allocate buffers"); + BigBuf_free(); + return PM3_EMALLOC; + } + + Demod14bInit(demod_buf, MAX_FRAME_SIZE); + Uart14bInit(uart_buf); // connect Demodulated Signal to ADC: SetAdcMuxFor(ADC_MUXSEL_HIPKD); @@ -2481,6 +2509,8 @@ void iso14443b_setup(void) { s_field_on = true; LED_D_ON(); + + return PM3_SUCCESS; } //----------------------------------------------------------------------------- @@ -2526,13 +2556,22 @@ int read_14b_srx_block(uint8_t blocknr, uint8_t *block) { } void read_14b_st_block(uint8_t blocknr) { - iso14443b_setup(); + if (iso14443b_setup() != PM3_SUCCESS) { + reply_ng(CMD_HF_SRI_READ, PM3_EMALLOC, NULL, 0); + return; + } set_tracing(true); uint8_t *data = BigBuf_calloc(ISO14B_BLOCK_SIZE); iso14b_card_select_t *card = (iso14b_card_select_t *) BigBuf_calloc(sizeof(iso14b_card_select_t)); + if (data == NULL || card == NULL) { + if (g_dbglevel >= DBG_ERROR) DbpString("14b st block: failed to allocate buffers"); + reply_ng(CMD_HF_SRI_READ, PM3_EMALLOC, NULL, 0); + goto out; + } + int res = iso14443b_select_srx_card(card); if (res != PM3_SUCCESS) { reply_ng(CMD_HF_SRI_READ, res, NULL, 0); @@ -2767,12 +2806,21 @@ static int tearoff_rand(void) { // - FpgaDownloadAndGo (bitstream already cached) // - BigBuf_free + BigBuf_calloc (demod buffers persist) // - 100ms field stabilization (tag only needs ~20ms to power up) -static void tearoff_field_on(void) { +static int tearoff_field_on(void) { // Reset the AT91 SSC PDC (DMA) receive buffer before each field-on // by mirroring iso14443b_setup() memory allocations for Demod14b/Uart14b. BigBuf_free(); - Demod14bInit(BigBuf_calloc(MAX_FRAME_SIZE), MAX_FRAME_SIZE); - Uart14bInit(BigBuf_calloc(MAX_FRAME_SIZE)); + + uint8_t *demod_buf = BigBuf_calloc(MAX_FRAME_SIZE); + uint8_t *uart_buf = BigBuf_calloc(MAX_FRAME_SIZE); + if (demod_buf == NULL || uart_buf == NULL) { + if (g_dbglevel >= DBG_ERROR) DbpString("14b tearoff: failed to allocate buffers"); + BigBuf_free(); + return PM3_EMALLOC; + } + + Demod14bInit(demod_buf, MAX_FRAME_SIZE); + Uart14bInit(uart_buf); SetAdcMuxFor(ADC_MUXSEL_HIPKD); FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER); // programs PDC with fresh BigBuf address @@ -2786,6 +2834,7 @@ static void tearoff_field_on(void) { StartCountSspClk(); iso14b_set_fwt(8); s_field_on = true; + return PM3_SUCCESS; } // Cut the RF field. @@ -2818,7 +2867,10 @@ static int tearoff_read_block(uint8_t block_address, uint32_t *block_value) { int res; iso14b_card_select_t card; - tearoff_field_on(); + res = tearoff_field_on(); + if (res != PM3_SUCCESS) { + return res; + } res = iso14443b_select_srx_card(&card); if (res != PM3_SUCCESS) { @@ -2859,7 +2911,9 @@ static void tearoff_write_block(uint8_t block_address, uint32_t data, uint16_t t block[2] = (data >> 16) & 0xFF; block[3] = (data >> 24) & 0xFF; - tearoff_field_on(); + if (tearoff_field_on() != PM3_SUCCESS) { + return; + } iso14b_card_select_t card; int res = iso14443b_select_srx_card(&card); @@ -3055,7 +3109,11 @@ void ST25TB_TearOff(const uint8_t *data) { // One-time full setup: loads FPGA bitstream, allocates demod buffers, // configures ADC mux and SSC. All subsequent field cycles use the // lightweight tearoff_field_on/off which skip the heavy initialization. - iso14443b_setup(); + if (iso14443b_setup() != PM3_SUCCESS) { + reply_ng(CMD_HF_ISO14443B_ST25TB_TEAROFF, PM3_EMALLOC, NULL, 0); + return; + } + set_tracing(true); tearoff_field_off(false); // Start with field off, tearoff_read_block will turn it on @@ -3205,7 +3263,10 @@ void SendRawCommand14443B(iso14b_raw_cmd_t *p) { } if ((p->flags & ISO14B_CONNECT) == ISO14B_CONNECT) { - iso14443b_setup(); + if (iso14443b_setup() != PM3_SUCCESS) { + reply_ng(CMD_HF_ISO14443B_COMMAND, PM3_EMALLOC, NULL, 0); + goto out; + } } if ((p->flags & ISO14B_SET_TIMEOUT) == ISO14B_SET_TIMEOUT) { diff --git a/armsrc/iso14443b.h b/armsrc/iso14443b.h index 0e509d000..8b63e9692 100644 --- a/armsrc/iso14443b.h +++ b/armsrc/iso14443b.h @@ -38,7 +38,7 @@ #define AddCrc15(data, len) compute_crc(CRC_ICLASS, (data), (len), (data)+(len), (data)+(len)+1) #endif -void iso14443b_setup(void); +int iso14443b_setup(void); int iso14443b_apdu(uint8_t const *msg, size_t msg_len, bool send_chaining, void *rxdata, uint16_t rxmaxlen, uint8_t *response_byte, uint16_t *responselen); int iso14443b_select_card(iso14b_card_select_t *card); diff --git a/armsrc/iso15693.c b/armsrc/iso15693.c index 1bc63df48..9af080e9e 100644 --- a/armsrc/iso15693.c +++ b/armsrc/iso15693.c @@ -196,6 +196,10 @@ static void CodeIso15693AsReaderEOF(void) { static int get_uid_slix(uint32_t start_time, uint32_t *eof_time, uint8_t *uid) { uint8_t *answer = BigBuf_calloc(ISO15693_MAX_RESPONSE_LENGTH); + if (answer == NULL) { + if (g_dbglevel >= DBG_ERROR) DbpString("Failed to allocate response buffer. Exiting"); + return PM3_EMALLOC; + } start_time = *eof_time + DELAY_ISO15693_VICC_TO_VCD_READER; @@ -1649,6 +1653,11 @@ void AcquireRawAdcSamplesIso15693(void) { LED_A_ON(); uint8_t *dest = BigBuf_calloc(4096); + if (dest == NULL) { + if (g_dbglevel >= DBG_ERROR) DbpString("Failed to allocate sample buffer. Exiting"); + LEDsoff(); + return; + } // switch field on FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER); @@ -2097,6 +2106,13 @@ void ReaderIso15693(iso15_card_select_t *p_card) { set_tracing(true); uint8_t *answer = BigBuf_calloc(ISO15693_MAX_RESPONSE_LENGTH); + if (answer == NULL) { + if (g_dbglevel >= DBG_ERROR) DbpString("Failed to allocate response buffer. Exiting"); + reply_ng(CMD_HF_ISO15693_READER, PM3_EMALLOC, NULL, 0); + switch_off(); + return; + } + memset(answer, 0x00, ISO15693_MAX_RESPONSE_LENGTH); // FIRST WE RUN AN INVENTORY TO GET THE TAG UID @@ -2340,6 +2356,7 @@ void SimTagIso15693(const uint8_t *uid, uint8_t block_size) { // remove the CRC from the cmd cmd_len -= 2; recvLen = 0; + error = 0; // inventory mask mismatch left it set tag->expectFast = ((cmd[0] & ISO15_REQ_DATARATE_HIGH) == ISO15_REQ_DATARATE_HIGH); tag->expectFsk = ((cmd[0] & ISO15_REQ_SUBCARRIER_TWO) == ISO15_REQ_SUBCARRIER_TWO); @@ -3186,51 +3203,322 @@ void LockPassSlixIso15693(uint32_t pass_id, uint32_t password) { // //----------------------------------------------------------------------------- +// Backdoor blocks of a magic "Gen1" tag, see doc/magic_cards_notes.md +#define ISO15_MAGIC_GEN1_BLK_UID_LO 0x38 +#define ISO15_MAGIC_GEN1_BLK_UID_HI 0x39 +#define ISO15_MAGIC_GEN1_BLK_UNLOCK_A 0x3E +#define ISO15_MAGIC_GEN1_BLK_UNLOCK_B 0x3F + +static const uint8_t g_magic_gen1_blank[4] = {0x00, 0x00, 0x00, 0x00}; +static const uint8_t g_magic_gen1_unlock_b[4] = {0x69, 0x96, 0x00, 0x00}; + +// true when every byte is zero +static bool magic_15_is_blank(const uint8_t *data, uint8_t len) { + for (uint8_t i = 0; i < len; i++) { + if (data[i] != 0x00) { + return false; + } + } + return true; +} + +// PM3_SUCCESS means the tag answered with block data, *data then points into +// the receive buffer and stays valid until the next command overwrites it. +static int magic_15_read_blk(uint8_t blockno, uint8_t **data, uint8_t *len, uint32_t *start_time, uint32_t *eof_time) { + + uint8_t cmd[5] = {ISO15_REQ_DATARATE_HIGH | ISO15_REQ_OPTION, ISO15693_READBLOCK, blockno, 0x00, 0x00}; + AddCrc15(cmd, 3); + + uint16_t recvlen = 0; + int res = SendDataTag(cmd, sizeof(cmd), false, true, s_iso15_recvbuf, sizeof(s_iso15_recvbuf), + *start_time, ISO15693_READER_TIMEOUT, eof_time, &recvlen); + + *start_time = *eof_time + DELAY_ISO15693_VICC_TO_VCD_READER; + + if (res != PM3_SUCCESS) { + return res; + } + + // flags + at least four data bytes + crc + if (recvlen < 7) { + return PM3_EWRONGANSWER; + } + + // GetIso15693AnswerFromTag() doesn't check the crc, so do it here + if (CheckCrc15(s_iso15_recvbuf, recvlen) == false) { + return PM3_ECRC; + } + + if ((s_iso15_recvbuf[0] & ISO15_RES_ERROR) == ISO15_RES_ERROR) { + return PM3_EWRONGANSWER; + } + + // the option flag makes the tag prepend a lock byte, blocks can be wider than four bytes + uint8_t offset = (recvlen > 7) ? 2 : 1; + *data = s_iso15_recvbuf + offset; + *len = recvlen - offset - 2; + return PM3_SUCCESS; +} + +// Unaddressed block write, leaves the field on for the next command +static int magic_15_write_blk(uint8_t blockno, const uint8_t *data, uint32_t *start_time, uint32_t *eof_time) { + + uint8_t cmd[9] = {ISO15_REQ_DATARATE_HIGH, ISO15693_WRITEBLOCK, blockno, data[0], data[1], data[2], data[3], 0x00, 0x00}; + AddCrc15(cmd, 7); + + uint16_t recvlen = 0; + int res = SendDataTag(cmd, sizeof(cmd), false, true, s_iso15_recvbuf, sizeof(s_iso15_recvbuf), + *start_time, ISO15693_READER_TIMEOUT_WRITE, eof_time, &recvlen); + + *start_time = *eof_time + DELAY_ISO15693_VICC_TO_VCD_READER; + + if (res != PM3_SUCCESS) { + return res; + } + + // flags + crc + if (recvlen < 3) { + return PM3_EWRONGANSWER; + } + + if (CheckCrc15(s_iso15_recvbuf, recvlen) == false) { + return PM3_ECRC; + } + + if ((s_iso15_recvbuf[0] & ISO15_RES_ERROR) == ISO15_RES_ERROR) { + return PM3_EWRONGANSWER; + } + return PM3_SUCCESS; +} + +// On a real Gen1 tag these four blocks sit outside the readable memory and the read fails. +// A tag that answers with data is a normal tag and we must not overwrite it. +static bool magic_gen1_is_backdoor(uint32_t *start_time, uint32_t *eof_time) { + + static const uint8_t blocks[4] = { + ISO15_MAGIC_GEN1_BLK_UID_LO, + ISO15_MAGIC_GEN1_BLK_UID_HI, + ISO15_MAGIC_GEN1_BLK_UNLOCK_A, + ISO15_MAGIC_GEN1_BLK_UNLOCK_B + }; + + for (uint8_t i = 0; i < ARRAYLEN(blocks); i++) { + + uint8_t *data = NULL; + uint8_t len = 0; + + if (magic_15_read_blk(blocks[i], &data, &len, start_time, eof_time) != PM3_SUCCESS) { + continue; + } + + if (magic_15_is_blank(data, len)) { + continue; + } + + // leftover of the unlock write of an earlier attempt on this same tag + if (blocks[i] == ISO15_MAGIC_GEN1_BLK_UNLOCK_B && len >= 4 && + memcmp(data, g_magic_gen1_unlock_b, 4) == 0) { + continue; + } + + if (g_dbglevel >= DBG_ERROR) { + Dbprintf("SetTag15693Uid: block 0x%02X holds data, not a magic Gen1 tag", blocks[i]); + } + return false; + } + return true; +} + +// Blank the four blocks again so a failed attempt leaves no unlock values behind +static void magic_gen1_rollback(uint32_t *start_time, uint32_t *eof_time) { + magic_15_write_blk(ISO15_MAGIC_GEN1_BLK_UID_LO, g_magic_gen1_blank, start_time, eof_time); + magic_15_write_blk(ISO15_MAGIC_GEN1_BLK_UID_HI, g_magic_gen1_blank, start_time, eof_time); + magic_15_write_blk(ISO15_MAGIC_GEN1_BLK_UNLOCK_A, g_magic_gen1_blank, start_time, eof_time); + magic_15_write_blk(ISO15_MAGIC_GEN1_BLK_UNLOCK_B, g_magic_gen1_blank, start_time, eof_time); +} + // Set the UID on Magic ISO15693 tag (based on Iceman's LUA-script). void SetTag15693Uid(const uint8_t *uid) { LED_A_ON(); - uint8_t cmd[4][9] = { - {ISO15_REQ_DATARATE_HIGH, ISO15693_WRITEBLOCK, 0x3e, 0x00, 0x00, 0x00, 0x00, 0xE9, 0x8F}, - {ISO15_REQ_DATARATE_HIGH, ISO15693_WRITEBLOCK, 0x3f, 0x69, 0x96, 0x00, 0x00, 0x8A, 0xBB}, - - // Command 3 : 02 21 38 u8u7u6u5 (where uX = uid byte X) - {ISO15_REQ_DATARATE_HIGH, ISO15693_WRITEBLOCK, 0x38, uid[7], uid[6], uid[5], uid[4]}, - - // Command 4 : 02 21 39 u4u3u2u1 (where uX = uid byte X) - {ISO15_REQ_DATARATE_HIGH, ISO15693_WRITEBLOCK, 0x39, uid[3], uid[2], uid[1], uid[0]} - }; - - - AddCrc15(cmd[2], 7); - AddCrc15(cmd[3], 7); - memset(s_iso15_recvbuf, 0, sizeof(s_iso15_recvbuf)); - uint32_t start_time = 0; - uint32_t eof_time = 0; - uint16_t recvlen = 0; + Iso15693InitReader(); + StartCountSspClk(); + uint32_t start_time = 0, eof_time = 0; - int res = PM3_SUCCESS; + uint8_t origuid[8] = {0}; + if (get_uid_slix(start_time, &eof_time, origuid) != PM3_SUCCESS) { + reply_ng(CMD_HF_ISO15693_CSETUID, PM3_ETIMEOUT, NULL, 0); + switch_off(); + return; + } + start_time = eof_time + DELAY_ISO15693_VICC_TO_VCD_READER; - for (int i = 0; i < 4; i++) { - res = SendDataTag( - cmd[i], - sizeof(cmd[i]), - (i == 0) ? true : false, - true, - s_iso15_recvbuf, - sizeof(s_iso15_recvbuf), - start_time, - ISO15693_READER_TIMEOUT_WRITE, - &eof_time, - &recvlen - ); - - start_time = eof_time + DELAY_ISO15693_VICC_TO_VCD_READER; + if (magic_gen1_is_backdoor(&start_time, &eof_time) == false) { + reply_ng(CMD_HF_ISO15693_CSETUID, PM3_EWRONGANSWER, NULL, 0); + switch_off(); + return; } - reply_ng(CMD_HF_ISO15693_CSETUID, res, NULL, 0); + const uint8_t uid_lo[4] = {uid[7], uid[6], uid[5], uid[4]}; + const uint8_t uid_hi[4] = {uid[3], uid[2], uid[1], uid[0]}; + + // the unlock writes are best-effort, a tag already unlocked rejects them + magic_15_write_blk(ISO15_MAGIC_GEN1_BLK_UNLOCK_A, g_magic_gen1_blank, &start_time, &eof_time); + magic_15_write_blk(ISO15_MAGIC_GEN1_BLK_UNLOCK_B, g_magic_gen1_unlock_b, &start_time, &eof_time); + + int res = magic_15_write_blk(ISO15_MAGIC_GEN1_BLK_UID_LO, uid_lo, &start_time, &eof_time); + if (res == PM3_SUCCESS) { + res = magic_15_write_blk(ISO15_MAGIC_GEN1_BLK_UID_HI, uid_hi, &start_time, &eof_time); + } + + // get_uid_slix answers LSB first, the requested uid is MSB first + uint8_t newuid[8] = {0}, revuid[8] = {0}; + int res_uid = get_uid_slix(start_time, &eof_time, newuid); + reverse_array_copy(newuid, sizeof(newuid), revuid); + start_time = eof_time + DELAY_ISO15693_VICC_TO_VCD_READER; + + if (res == PM3_SUCCESS && res_uid == PM3_SUCCESS && memcmp(revuid, uid, sizeof(revuid)) == 0) { + reply_ng(CMD_HF_ISO15693_CSETUID, PM3_SUCCESS, NULL, 0); + switch_off(); + return; + } + + // only roll back while the tag still shows its original UID, blanking the + // blocks after a UID change would destroy what we just wrote + if (res_uid == PM3_SUCCESS && memcmp(newuid, origuid, sizeof(newuid)) == 0) { + magic_gen1_rollback(&start_time, &eof_time); + } + + reply_ng(CMD_HF_ISO15693_CSETUID, PM3_ESOFT, NULL, 0); + switch_off(); +} + +// Magic "V3" tags answer with a signature in 0x14/0x15 while the UID is still changeable +#define ISO15_MAGIC_V3_BLK_UID_LO 0x10 +#define ISO15_MAGIC_V3_BLK_UID_HI 0x11 +#define ISO15_MAGIC_V3_BLK_SIG_A 0x14 +#define ISO15_MAGIC_V3_BLK_SIG_B 0x15 + +static const uint8_t g_magic_v3_sig_a[4] = {0xA5, 0x2B, 0x44, 0x2C}; +static const uint8_t g_magic_v3_sig_b[4] = {0x21, 0xAE, 0x93, 0x00}; +static const uint8_t g_magic_v3_fin_a[4] = {0xA5, 0x2B, 0x44, 0x2C}; +static const uint8_t g_magic_v3_fin_b[4] = {0x69, 0xE2, 0x5D, 0x00}; + +// Writing the finalize values to anything that is not an un-finalized V3 tag bricks it. +// PM3_SUCCESS means both signature blocks were read, *in_config says what they hold. +static int magic_v3_read_config(bool *in_config, uint32_t *start_time, uint32_t *eof_time) { + + uint8_t *data = NULL; + uint8_t len = 0; + + *in_config = false; + + // the second read overwrites the buffer, so compare 0x14 before asking for 0x15 + int res = magic_15_read_blk(ISO15_MAGIC_V3_BLK_SIG_A, &data, &len, start_time, eof_time); + if (res != PM3_SUCCESS) { + return res; + } + + bool sig_a = (len >= 4 && memcmp(data, g_magic_v3_sig_a, 4) == 0); + + res = magic_15_read_blk(ISO15_MAGIC_V3_BLK_SIG_B, &data, &len, start_time, eof_time); + if (res != PM3_SUCCESS) { + return res; + } + + *in_config = (sig_a && len >= 4 && memcmp(data, g_magic_v3_sig_b, 4) == 0); + return PM3_SUCCESS; +} + +// Set the UID on a magic "V3" tag, repeatable until the tag is finalized +void SetTag15693Uid_v3(const uint8_t *uid) { + + LED_A_ON(); + memset(s_iso15_recvbuf, 0, sizeof(s_iso15_recvbuf)); + + Iso15693InitReader(); + StartCountSspClk(); + uint32_t start_time = 0, eof_time = 0; + + uint8_t curuid[8] = {0}; + if (get_uid_slix(start_time, &eof_time, curuid) != PM3_SUCCESS) { + reply_ng(CMD_HF_ISO15693_CSETUID_V3, PM3_ETIMEOUT, NULL, 0); + switch_off(); + return; + } + start_time = eof_time + DELAY_ISO15693_VICC_TO_VCD_READER; + + bool in_config = false; + if (magic_v3_read_config(&in_config, &start_time, &eof_time) != PM3_SUCCESS || in_config == false) { + reply_ng(CMD_HF_ISO15693_CSETUID_V3, PM3_EWRONGANSWER, NULL, 0); + switch_off(); + return; + } + + const uint8_t uid_lo[4] = {uid[7], uid[6], uid[5], uid[4]}; + const uint8_t uid_hi[4] = {uid[3], uid[2], uid[1], uid[0]}; + + int res = magic_15_write_blk(ISO15_MAGIC_V3_BLK_UID_LO, uid_lo, &start_time, &eof_time); + if (res == PM3_SUCCESS) { + res = magic_15_write_blk(ISO15_MAGIC_V3_BLK_UID_HI, uid_hi, &start_time, &eof_time); + } + + if (res == PM3_SUCCESS) { + // get_uid_slix answers LSB first, the requested uid is MSB first + uint8_t newuid[8] = {0}, revuid[8] = {0}; + res = get_uid_slix(start_time, &eof_time, newuid); + reverse_array_copy(newuid, sizeof(newuid), revuid); + + if (res == PM3_SUCCESS && memcmp(revuid, uid, sizeof(revuid)) != 0) { + res = PM3_ESOFT; + } + } + + reply_ng(CMD_HF_ISO15693_CSETUID_V3, (res == PM3_SUCCESS) ? PM3_SUCCESS : PM3_ESOFT, NULL, 0); + switch_off(); +} + +// Lock the UID of a magic "V3" tag, irreversible +void FinalizeTag15693_v3(void) { + + LED_A_ON(); + memset(s_iso15_recvbuf, 0, sizeof(s_iso15_recvbuf)); + + Iso15693InitReader(); + StartCountSspClk(); + uint32_t start_time = 0, eof_time = 0; + + uint8_t curuid[8] = {0}; + if (get_uid_slix(start_time, &eof_time, curuid) != PM3_SUCCESS) { + reply_ng(CMD_HF_ISO15693_CFINALIZE_V3, PM3_ETIMEOUT, NULL, 0); + switch_off(); + return; + } + start_time = eof_time + DELAY_ISO15693_VICC_TO_VCD_READER; + + bool in_config = false; + if (magic_v3_read_config(&in_config, &start_time, &eof_time) != PM3_SUCCESS || in_config == false) { + reply_ng(CMD_HF_ISO15693_CFINALIZE_V3, PM3_EWRONGANSWER, NULL, 0); + switch_off(); + return; + } + + int res = magic_15_write_blk(ISO15_MAGIC_V3_BLK_SIG_A, g_magic_v3_fin_a, &start_time, &eof_time); + if (res == PM3_SUCCESS) { + res = magic_15_write_blk(ISO15_MAGIC_V3_BLK_SIG_B, g_magic_v3_fin_b, &start_time, &eof_time); + } + + // finalize wipes the memory, so the signature blocks must read back as something + // else. a read that fails proves nothing and counts as a failure too + if (res == PM3_SUCCESS) { + if (magic_v3_read_config(&in_config, &start_time, &eof_time) != PM3_SUCCESS || in_config) { + res = PM3_ESOFT; + } + } + + reply_ng(CMD_HF_ISO15693_CFINALIZE_V3, (res == PM3_SUCCESS) ? PM3_SUCCESS : PM3_ESOFT, NULL, 0); switch_off(); } diff --git a/armsrc/iso15693.h b/armsrc/iso15693.h index a3197bbd8..5a419e293 100644 --- a/armsrc/iso15693.h +++ b/armsrc/iso15693.h @@ -59,6 +59,8 @@ int SendDataTagEOF(uint8_t *recv, uint16_t max_recv_len, uint32_t start_time, ui void SetTag15693Uid(const uint8_t *uid); void SetTag15693Uid_v2(const uint8_t *uid); +void SetTag15693Uid_v3(const uint8_t *uid); +void FinalizeTag15693_v3(void); void WritePasswordSlixIso15693(const uint8_t *old_password, const uint8_t *new_password, uint8_t pwd_id); void DisablePrivacySlixIso15693(const uint8_t *password); diff --git a/armsrc/legicrfsim.c b/armsrc/legicrfsim.c index f66d2e3b6..923f35f7d 100644 --- a/armsrc/legicrfsim.c +++ b/armsrc/legicrfsim.c @@ -311,8 +311,10 @@ static int32_t init_card(uint8_t cardtype, legic_card_select_t *p_card) { } static void init_tag(void) { - // configure FPGA - FpgaDownloadAndGo(FPGA_BITSTREAM_HF); + // configure FPGA. _keep_EM because legic_mem below is emulator memory, which + // is where `hf legic eload` put the tag content -- the plain variant frees and + // clears the whole of BigBuf to decompress into and would wipe it + FpgaDownloadAndGo_keep_EM(FPGA_BITSTREAM_HF); FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_212K); SetAdcMuxFor(ADC_MUXSEL_HIPKD); diff --git a/armsrc/lfadc.c b/armsrc/lfadc.c index aef79d6fa..48389c272 100644 --- a/armsrc/lfadc.c +++ b/armsrc/lfadc.c @@ -99,7 +99,7 @@ void lf_sample_mean(void) { adc_avg = adc_sum >> 5; // division by 32 previous_adc_val = adc_avg; DBG Dbprintf("LF ADC average %u, max %u, min %u, diff %u (threshold is +/-%u counts)", - adc_avg, adc_max, adc_min, adc_max - adc_min, (unsigned)(LIMIT_DEV_Q5_REPORT / 32)); + adc_avg, adc_max, adc_min, adc_max - adc_min, (unsigned)(LIMIT_DEV_Q5_REPORT / 32)); } static size_t lf_count_edge_periods_ex(size_t max, bool wait, bool detect_gap) { diff --git a/armsrc/lfops.c b/armsrc/lfops.c index 559793272..f06142b4f 100644 --- a/armsrc/lfops.c +++ b/armsrc/lfops.c @@ -342,6 +342,11 @@ void loadT55xxConfig(void) { #ifdef WITH_FLASH uint8_t *buf = BigBuf_calloc(T55XX_CONFIG_LEN); + if (buf == NULL) { + if (g_dbglevel >= DBG_ERROR) DbpString("loadT55xxConfig: failed to allocate buffer"); + BigBuf_free(); + return; + } uint32_t size = 0; if (exists_in_spiffs(T55XX_CONFIG_FILE)) { @@ -536,7 +541,7 @@ void ReadTItag(bool ledcontrol) { #define FREQHI 134200 signed char *dest = (signed char *)BigBuf_get_addr(); - uint16_t n = BigBuf_max_traceLen(); + uint32_t n = BigBuf_max_traceLen(); // 128 bit shift register [shift3:shift2:shift1:shift0] uint32_t shift3 = 0, shift2 = 0, shift1 = 0, shift0 = 0; @@ -2948,6 +2953,12 @@ void Cotag(uint32_t arg0, bool ledcontrol) { } case 1: { uint8_t *dest = BigBuf_calloc(COTAG_BITS); + if (dest == NULL) { + if (g_dbglevel >= DBG_ERROR) DbpString("cotag: failed to allocate buffer"); + reply_ng(CMD_LF_COTAG_READ, PM3_EMALLOC, NULL, 0); + break; + } + uint16_t bits = doCotagAcquisitionManchester(dest, COTAG_BITS); reply_ng(CMD_LF_COTAG_READ, PM3_SUCCESS, dest, bits); break; diff --git a/armsrc/lfsampling.c b/armsrc/lfsampling.c index ed6f32658..c4fb9964a 100644 --- a/armsrc/lfsampling.c +++ b/armsrc/lfsampling.c @@ -152,6 +152,11 @@ void initSampleBufferEx(uint32_t *sample_size, bool use_malloc) { } else { *sample_size = MIN(*sample_size, BigBuf_max_traceLen()); data.buffer = BigBuf_calloc(*sample_size); + if (data.buffer == NULL) { + Dbprintf("Failed to allocate memory, using whole BigBuf"); + *sample_size = BigBuf_max_traceLen(); + data.buffer = BigBuf_get_addr(); + } } } else { @@ -455,6 +460,11 @@ uint32_t SampleLF(bool verbose, uint32_t sample_size, bool ledcontrol, bool cota * @param reader_field - true for reading tags, false for sniffing * @return sampling result **/ + +// how long the host is given to collect a streamed USB packet before the link is declared dead? +// ticks run at 1.5MHz, about 100ms +#define LF_REALTIME_USB_TIMEOUT (100 * 1500) + int ReadLF_realtime(bool reader_field, bool cotag, uint32_t sample_limit) { // parameters from config and constants const uint8_t bits_per_sample = config.bits_per_sample; @@ -543,10 +553,21 @@ int ReadLF_realtime(bool reader_field, bool cotag, uint32_t sample_limit) { last_byte = curr_byte; if (samples.total_saved == size_threshold) { - // Request USB transmission and change FIFO bank + + // Request USB transmission and change FIFO bank. + // A busy IN endpoint only means the host has not collected the previous packet yet, if (async_usb_write_requestWrite() == false) { - return_value = PM3_EIO; - goto out; + + uint32_t start_ticks = GetTicks(); + do { + + WDT_HIT(); + if (GetTicksDelta(start_ticks) > LF_REALTIME_USB_TIMEOUT) { + return_value = PM3_EIO; + goto out; + } + + } while (async_usb_write_requestWrite() == false); } // Reset sample @@ -568,9 +589,16 @@ int ReadLF_realtime(bool reader_field, bool cotag, uint32_t sample_limit) { } } - return_value = async_usb_write_stop(); - out: + // Always close the async write down, error paths included. Leaving it open + // strands the IN endpoint with a half filled FIFO, and every later usb_write() fails + { + int stop_value = async_usb_write_stop(); + if (return_value == PM3_SUCCESS) { + return_value = stop_value; + } + } + LED_D_OFF(); // DoAcquisition() end @@ -587,90 +615,6 @@ uint32_t SniffLF(bool verbose, uint32_t sample_size, bool ledcontrol) { return ReadLF(false, verbose, sample_size, ledcontrol, false); } -/** -* acquisition of T55x7 LF signal. Similar to other LF, but adjusted with @marshmellows thresholds -* the data is collected in BigBuf. -**/ -void doT55x7Acquisition(size_t sample_size, bool ledcontrol) { - -#define T55xx_READ_UPPER_THRESHOLD 128+60 // 60 grph -#define T55xx_READ_LOWER_THRESHOLD 128-60 // -60 grph -#define T55xx_READ_TOL 5 - - uint8_t *dest = BigBuf_get_addr(); - uint16_t bufsize = BigBuf_max_traceLen(); - - if (bufsize > sample_size) - bufsize = sample_size; - - uint8_t lastSample = 0; - uint16_t i = 0, skipCnt = 0; - bool startFound = false; - bool highFound = false; - bool lowFound = false; - - uint16_t checker = 0; - - if (g_dbglevel >= DBG_DEBUG) { - Dbprintf("doT55x7Acquisition - after init"); - print_stack_usage(); - } - - while (skipCnt < 1000 && (i < bufsize)) { - - if (BUTTON_PRESS()) - break; - - if (checker == 4000) { - if (data_available()) - break; - else - checker = 0; - } else { - ++checker; - } - - WDT_HIT(); - - if (ledcontrol && FPGA_SSC_TX_Ready()) { - LED_D_ON(); - } - - if (FPGA_SSC_RX_Ready()) { - volatile uint8_t sample = (uint8_t)FPGA_SSC_RX_Value(); - if (ledcontrol) LED_D_OFF(); - - // skip until the first high sample above threshold - if (!startFound && sample > T55xx_READ_UPPER_THRESHOLD) { - highFound = true; - } else if (!highFound) { - skipCnt++; - continue; - } - // skip until the first low sample below threshold - if (!startFound && sample < T55xx_READ_LOWER_THRESHOLD) { - lastSample = sample; - lowFound = true; - } else if (!lowFound) { - skipCnt++; - continue; - } - - // skip until first high samples begin to change - if (startFound || sample > T55xx_READ_LOWER_THRESHOLD + T55xx_READ_TOL) { - // if just found start - recover last sample - if (startFound == false) { - dest[i++] = lastSample; - startFound = true; - } - // collect samples - if (i < bufsize) { - dest[i++] = sample; - } - } - } - } -} /** * acquisition of Cotag LF signal. Similart to other LF, since the Cotag has such long datarate RF/384 * and is Manchester?, we directly gather the manchester data into bigbuff @@ -685,13 +629,14 @@ void doT55x7Acquisition(size_t sample_size, bool ledcontrol) { #endif void doCotagAcquisition(void) { - uint16_t bufsize = BigBuf_max_traceLen(); + uint32_t bufsize = BigBuf_max_traceLen(); uint8_t *dest = BigBuf_calloc(bufsize); dest[0] = 0; bool firsthigh = false, firstlow = false; - uint16_t i = 0, noise_counter = 0; + uint32_t i = 0; + uint16_t noise_counter = 0; uint16_t checker = 0; diff --git a/armsrc/lfsampling.h b/armsrc/lfsampling.h index 3ed11ca3e..ca28a9c4e 100644 --- a/armsrc/lfsampling.h +++ b/armsrc/lfsampling.h @@ -39,12 +39,6 @@ typedef struct { void doCotagAcquisition(void); uint16_t doCotagAcquisitionManchester(uint8_t *dest, uint16_t destlen); -/** -* acquisition of T55x7 LF signal. Similar to other LF, but adjusted with @marshmellows thresholds -* the data is collected in BigBuf. -**/ -void doT55x7Acquisition(size_t sample_size, bool ledcontrol); - /** * Initializes the FPGA for reader-mode (field on), and acquires the samples. * @return number of bits sampled diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index c35953ac0..b872b51d1 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -46,6 +46,18 @@ #ifndef HARDNESTED_PRE_AUTHENTICATION_LEADTIME # define HARDNESTED_PRE_AUTHENTICATION_LEADTIME 400 // some (non standard) cards need a pause after select before they are ready for first authentication #endif +// PM5/AT32: the 288 MHz AT32 issues the nested auth so soon after the first auth completes +// that the encrypted-nonce reception is intermittently corrupted, which defeats hardnested. +// A short settle delay before the nested read prevents it. Not applied on the slower RDV4. +#ifndef HARDNESTED_NESTED_TURNAROUND_DELAY_US +# define HARDNESTED_NESTED_TURNAROUND_DELAY_US 500 +#endif +// PM5's command buffer (PM3_CMD_DATA_SIZE 4064) holds ~450 nonce pairs per round vs ~68 on +// other platforms; a full ~450-pair round can outrun the client's 3 s reply wait and drop +// the link. Cap the round so the reply stays timely (no-op where the natural max is <= 68). +#ifndef MFC_ACQ_ROUND_MAX_PAIRS +# define MFC_ACQ_ROUND_MAX_PAIRS 68 +#endif // send an incomplete dummy response in order to trigger the card's authentication failure timeout #ifndef CHK_TIMEOUT @@ -873,14 +885,6 @@ void MifareUWriteBlockCompat(mful_writeblock_t *packet) { } } - // UL-AES authentication - if (useAESKey) { - if (mifare_ultra_aes_auth(0, packet->key, packet->use_schann, true, true, NULL) == 0) { - OnErrorNG(CMD_HF_MIFAREU_WRITEBL_COMPAT, PM3_ESOFT); - return; - } - } - // UL-EV1 / NTAG authentication if (usePwd) { uint8_t pack[4] = {0, 0, 0, 0}; @@ -991,9 +995,14 @@ void MifareAcquireNonces(const mf_acquire_nonces_t *payload) { uint8_t uid[10] = {0x00}; uint8_t answer[MAX_MIFARE_FRAME_SIZE] = {0x00}; uint8_t par[1] = {0x00}; - uint8_t buf[PM3_CMD_DATA_SIZE] = {0x00}; + + // collect straight into the reply buffer, no second copy on the stack + uint8_t respbuf[sizeof(mf_nonces_resp_t) + (MFC_MAX_NONCES * 4)] = {0x00}; + mf_nonces_resp_t *response = (mf_nonces_resp_t *)respbuf; + uint8_t *buf = response->nonces; + uint32_t cuid = 0; - int16_t isOK = 0; + int8_t isOK = PM3_SUCCESS; // reply_ng() takes int8_t, match it uint16_t num_nonces = 0; uint8_t cascade_levels = 0; uint8_t blockNo = payload->blockno; @@ -1018,12 +1027,14 @@ void MifareAcquireNonces(const mf_acquire_nonces_t *payload) { while (num_nonces < MFC_MAX_NONCES) { // Test if the action was cancelled - if (BUTTON_PRESS()) { - isOK = 2; + if (BUTTON_PRESS() || data_available()) { + isOK = PM3_EOPABORTED; field_off = true; break; } + WDT_HIT(); + if (!have_uid) { // need a full select cycle to get the uid first iso14a_card_select_t card_info; if (iso14443a_select_card(uid, &card_info, &cuid, true, 0, true) == 0) { @@ -1072,12 +1083,12 @@ void MifareAcquireNonces(const mf_acquire_nonces_t *payload) { LED_C_OFF(); LED_B_ON(); - uint8_t respbuf[PM3_CMD_DATA_SIZE] = {0x00}; - mf_nonces_resp_t *response = (mf_nonces_resp_t *)respbuf; + + // one bare 4 byte nonce per entry here, unlike the paired layout used by + // MifareAcquireEncryptedNonces. The loop above already caps num_nonces + uint16_t noncelen = num_nonces * 4; response->cuid = cuid; response->num_nonces = num_nonces; - uint16_t noncelen = MIN((uint16_t)(num_nonces * 4), (uint16_t)(MFC_MAX_NONCES * 4)); - memcpy(response->nonces, buf, noncelen); reply_ng(CMD_HF_MIFARE_ACQ_NONCES, isOK, respbuf, sizeof(mf_nonces_resp_t) + noncelen); LED_B_OFF(); @@ -1106,12 +1117,17 @@ void MifareAcquireEncryptedNonces(const mf_acquire_nonces_t *payload) { uint8_t uid[10] = {0x00}; uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00}; uint8_t par_enc[1] = {0x00}; - uint8_t buf[PM3_CMD_DATA_SIZE] = {0x00}; + + // collect straight into the reply buffer, no second copy on the stack + uint8_t respbuf[sizeof(mf_nonces_resp_t) + (MFC_MAX_NONCE_PAIRS * MFC_NONCE_PAIR_SIZE)] = {0x00}; + mf_nonces_resp_t *response = (mf_nonces_resp_t *)respbuf; + uint8_t *buf = response->nonces; uint64_t ui64Key = bytes_to_num(payload->key, 6); uint32_t cuid = 0; - int16_t isOK = PM3_SUCCESS; + int8_t isOK = PM3_SUCCESS; // reply_ng() takes int8_t, match it uint16_t num_nonces = 0; + uint16_t num_pairs = 0; uint8_t nt_par_enc = 0; uint8_t cascade_levels = 0; uint8_t blockNo = payload->blockno; @@ -1139,15 +1155,19 @@ void MifareAcquireEncryptedNonces(const mf_acquire_nonces_t *payload) { uint8_t prev_enc_nt[] = {0, 0, 0, 0}; uint8_t prev_counter = 0; - for (uint16_t i = 0; i <= (MFC_MAX_NONCES * 4) - 9;) { + const uint16_t max_pairs = MIN(MFC_MAX_NONCE_PAIRS, MFC_ACQ_ROUND_MAX_PAIRS); + + while (num_pairs < max_pairs) { // Test if the action was cancelled - if (BUTTON_PRESS()) { + if (BUTTON_PRESS() || data_available()) { isOK = PM3_EOPABORTED; field_off = true; break; } + WDT_HIT(); + if (have_uid == false) { // need a full select cycle to get the uid first iso14a_card_select_t card_info; if (iso14443a_select_card(uid, &card_info, &cuid, true, 0, true) == 0) { @@ -1184,6 +1204,13 @@ void MifareAcquireEncryptedNonces(const mf_acquire_nonces_t *payload) { continue; } +#if defined(PM5) + // Let the card settle after the first auth before grabbing the nested nonce; the + // AT32's fast turnaround otherwise corrupts the encrypted read. Field stays on and + // the crypto1 state (pcs) is unchanged by the wait. + SpinDelayUs(HARDNESTED_NESTED_TURNAROUND_DELAY_US); +#endif + // nested authentication uint16_t len = mifare_sendcmd_short(pcs, AUTH_NESTED, MIFARE_AUTH_KEYA + (targetKeyType & 0xF), targetBlockNo, receivedAnswer, sizeof(receivedAnswer), par_enc, NULL); @@ -1196,14 +1223,15 @@ void MifareAcquireEncryptedNonces(const mf_acquire_nonces_t *payload) { } num_nonces++; + uint16_t ofs = num_pairs * MFC_NONCE_PAIR_SIZE; if (num_nonces % 2) { - memcpy(buf + i, receivedAnswer, 4); + memcpy(buf + ofs, receivedAnswer, 4); nt_par_enc = par_enc[0] & 0xf0; } else { nt_par_enc |= par_enc[0] >> 4; - memcpy(buf + i + 4, receivedAnswer, 4); - memcpy(buf + i + 8, &nt_par_enc, 1); - i += 9; + memcpy(buf + ofs + 4, receivedAnswer, 4); + buf[ofs + 8] = nt_par_enc; + num_pairs++; } @@ -1231,12 +1259,12 @@ void MifareAcquireEncryptedNonces(const mf_acquire_nonces_t *payload) { LED_C_OFF(); crypto1_deinit(pcs); LED_B_ON(); - uint8_t respbuf[PM3_CMD_DATA_SIZE] = {0x00}; - mf_nonces_resp_t *response = (mf_nonces_resp_t *)respbuf; + + // only whole pairs are transferred. An abort or a static nonce bailout can + // leave a dangling first nonce, it has no parity nibble yet so it is dropped + uint16_t noncelen = num_pairs * MFC_NONCE_PAIR_SIZE; response->cuid = cuid; - response->num_nonces = num_nonces; - uint16_t noncelen = MIN((uint16_t)(num_nonces * 4), (uint16_t)(MFC_MAX_NONCES * 4)); - memcpy(response->nonces, buf, noncelen); + response->num_nonces = num_pairs * 2; reply_ng(CMD_HF_MIFARE_ACQ_ENCRYPTED_NONCES, isOK, respbuf, sizeof(mf_nonces_resp_t) + noncelen); LED_B_OFF(); @@ -1276,7 +1304,7 @@ int MifareAcquireStaticEncryptedNonces(uint32_t flags, const uint8_t *key, bool return PM3_EINVARG; } uint32_t cuid = 0; - int16_t isOK = PM3_SUCCESS; + int8_t isOK = PM3_SUCCESS; // reply_ng() takes int8_t, match it uint8_t cascade_levels = 0; bool have_uid = false; @@ -1719,6 +1747,16 @@ void MifareNested(uint8_t blockNo, uint8_t keyType, uint8_t targetBlockNo, uint8 auth2_time = auth1_time + delta_time; len = mifare_sendcmd_short(pcs, AUTH_NESTED, MIFARE_AUTH_KEYA + (targetKeyType & 0xF), targetBlockNo, receivedAnswer, sizeof(receivedAnswer), par, &auth2_time); + + // a NAK is the tag refusing this block, not a glitch. re-sending the + // identical frame only ever gets the identical answer back, so give up + // here instead of spinning until the client times us out + if (len == 1) { + if (g_dbglevel >= DBG_INFO) Dbprintf("Nested: Auth2 NAK, tag refused block " _YELLOW_("%d"), targetBlockNo); + isOK = PM3_EWRONGANSWER; + break; + } + if (len != 4) { if (g_dbglevel >= DBG_INFO) Dbprintf("Nested: Auth2 error len=%d", len); continue; @@ -1814,7 +1852,7 @@ void MifareStaticNested(uint8_t blockNo, uint8_t keyType, uint8_t targetBlockNo, BigBuf_Clear_ext(false); set_tracing(true); - int16_t isOK = PM3_ESOFT; + int8_t isOK = PM3_ESOFT; // reply_ng() takes int8_t, match it LED_C_ON(); // Main loop - get crypted nonces for target sector @@ -2485,6 +2523,17 @@ OUT: } uint8_t *tmp = BigBuf_calloc(480 + 10); + if (tmp == NULL) { + if (g_dbglevel >= DBG_ERROR) DbpString("ChkKeys fast: failed to allocate buffer"); + reply_ng(CMD_HF_MIFARE_CHKKEYS_FAST, PM3_EMALLOC, NULL, 0); + set_tracing(false); + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + BigBuf_free(); + BigBuf_Clear_ext(false); + g_dbglevel = oldbg; + return; + } + memcpy(tmp, k_sector, sectorcnt * sizeof(sector_t)); num_to_bytes(foo, 8, tmp + 480); tmp[488] = bar & 0xFF; @@ -2646,6 +2695,16 @@ void MifareChkKeys_file(uint8_t *fn) { int changed = rdv40_spiffs_lazy_mount(); uint32_t size = size_in_spiffs((char *)fn); uint8_t *mem = BigBuf_calloc(size); + if (mem == NULL) { + if (g_dbglevel >= DBG_ERROR) DbpString("ChkKeys file: failed to allocate buffer"); + if (changed) { + rdv40_spiffs_lazy_unmount(); + } + SpinOff(0); + reply_ng(CMD_HF_MIFARE_CHKKEYS, PM3_EMALLOC, NULL, 0); + BigBuf_free(); + return; + } rdv40_spiffs_read_as_filetype((char *)fn, mem, size, RDV40_SPIFFS_SAFETY_SAFE); @@ -2666,7 +2725,7 @@ void MifareChkKeys_file(uint8_t *fn) { //----------------------------------------------------------------------------- void MifarePersonalizeUID(uint8_t keyType, uint8_t perso_option, uint64_t key) { - uint16_t isOK = PM3_EUNDEF; + int8_t isOK = PM3_EUNDEF; // reply_ng() takes int8_t, match it uint8_t uid[10] = { 0 }; uint32_t cuid = 0; struct Crypto1State mpcs = {0, 0}; @@ -2730,6 +2789,20 @@ int MifareECardLoadExt(uint8_t sectorcnt, uint8_t keytype, uint8_t *key) { return retval; } +// Re-select the card and start a fresh crypto1 session on a sector. +// A read the card NAKs aborts the session, so this is the only way back. +static int mfec_reauth(struct Crypto1State *pcs, uint8_t *uid, uint8_t cascade_levels, + uint32_t cuid, uint8_t blockno, uint8_t keytype, uint64_t ui64Key) { + + if (iso14443a_fast_select_card(uid, cascade_levels) == 0) { + return PM3_ERFTRANS; + } + if (mifare_classic_auth(pcs, cuid, blockno, keytype, ui64Key, AUTH_FIRST)) { + return PM3_EFAILED; + } + return PM3_SUCCESS; +} + int MifareECardLoad(uint8_t sectorcnt, uint8_t keytype, uint8_t *key) { if ((keytype > MF_KEY_B) && (key == NULL)) { @@ -2768,6 +2841,10 @@ int MifareECardLoad(uint8_t sectorcnt, uint8_t keytype, uint8_t *key) { uint64_t ui64Key = emlGetKey(s, keytype); + // which key actually opened this sector. The auth fallback below and + // the read fallback further down can both move it to the other key + uint8_t auth_kt = keytype; + // MIFARE Classic 1K Ev1 , MIFARE Classic MINI Ev1 if (sectorcnt == 18) { // MFC 1K EV1, skip sector 16 since its lockdown @@ -2851,6 +2928,7 @@ int MifareECardLoad(uint8_t sectorcnt, uint8_t keytype, uint8_t *key) { } continue; } + auth_kt = MF_KEY_B; } @@ -2865,11 +2943,51 @@ int MifareECardLoad(uint8_t sectorcnt, uint8_t keytype, uint8_t *key) { for (; r < MAX_RETRIES; r++) { int res = mifare_classic_readblock(pcs, tb, data); + + // A NAK aborts the crypto1 session. The card leaves the + // authenticated state, so every later read in this sector comes + // back with len 0 and the retry loop just spins on it. That is + // what turned one unreadable block into a whole lost sector. + // + // Recover the session, and try the other key while we are here: + // the access conditions can deny a read with A and allow it with + // B, which is why the client side `hf mf dump` gets blocks this + // one does not. Only A/B can be swapped, a backdoor key has no + // counterpart. + if (res == 1 && keytype <= MF_KEY_B) { + + uint8_t other_kt = (auth_kt == MF_KEY_A) ? MF_KEY_B : MF_KEY_A; + bool recovered = false; + + if (mfec_reauth(pcs, uid, cascade_levels, cuid, FirstBlockOfSector(s), other_kt, emlGetKey(s, other_kt)) == PM3_SUCCESS) { + if (mifare_classic_readblock(pcs, tb, data) == 0) { + // stay on it, the rest of the sector reads the same way + auth_kt = other_kt; + recovered = true; + } + } + + if (recovered == false) { + retval |= PM3_EPARTIAL; + if (g_dbglevel >= DBG_ERROR) { + Dbprintf("Error No rights reading sector %2d block %2d", s, b); + } + // put the session back so the remaining blocks still read + mfec_reauth(pcs, uid, cascade_levels, cuid, FirstBlockOfSector(s), auth_kt, emlGetKey(s, auth_kt)); + break; + } + + res = 0; + } + if (res == 1) { retval |= PM3_EPARTIAL; if (g_dbglevel >= DBG_ERROR) { Dbprintf("Error No rights reading sector %2d block %2d", s, b); } + // the backdoor session is dead too, make the next sector + // re-select and re-auth instead of reading into the void + bd_authenticated = false; break; } // retry if wrong len. @@ -3204,9 +3322,17 @@ void MifareCIdent(bool is_mfc, uint8_t keytype, uint8_t *key) { uint8_t superGen1[9] = {0x0A, 0x00, 0x00, 0xA6, 0xB0, 0x00, 0x10, 0x14, 0x1D}; uint8_t uid[10]; uint8_t *par = BigBuf_calloc(MAX_PARITY_SIZE); - uint8_t *buf = BigBuf_calloc(PM3_CMD_DATA_SIZE); + uint8_t *buf = BigBuf_calloc(MAX_FRAME_SIZE); iso14a_card_select_t *card = (iso14a_card_select_t *) BigBuf_calloc(sizeof(iso14a_card_select_t)); + if (par == NULL || buf == NULL || card == NULL) { + if (g_dbglevel >= DBG_ERROR) DbpString("Magic ident: failed to allocate buffers"); + reply_ng(CMD_HF_MIFARE_CIDENT, PM3_EMALLOC, NULL, 0); + switch_off(); + BigBuf_free(); + return; + } + bool isGen2 = false; uint16_t flag = MAGIC_FLAG_NONE; uint32_t cuid = 0; @@ -3227,13 +3353,13 @@ void MifareCIdent(bool is_mfc, uint8_t keytype, uint8_t *key) { // check for GDM config ReaderTransmit(gen4gdmGetConf, sizeof(gen4gdmGetConf), NULL); - res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par); + res = ReaderReceive(buf, MAX_FRAME_SIZE, par); if (res > 1) { // could be ZUID or full USCUID, the magic blocks don't exist on ZUID so // a failure here indicates a feature limited chip like ZUID // check for GDM hidden block read ReaderTransmit(gen4gdmGetMagicBlock, sizeof(gen4gdmGetMagicBlock), NULL); - res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par); + res = ReaderReceive(buf, MAX_FRAME_SIZE, par); if (res > 1) { flag |= MAGIC_FLAG_GDM_WUP_40; } else { @@ -3250,7 +3376,7 @@ void MifareCIdent(bool is_mfc, uint8_t keytype, uint8_t *key) { // Get config should return 30 or 32 bytes AddCrc14A(gen4GetConf, sizeof(gen4GetConf) - 2); ReaderTransmit(gen4GetConf, sizeof(gen4GetConf), NULL); - res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par); + res = ReaderReceive(buf, MAX_FRAME_SIZE, par); if (res == 32 || res == 34) { flag |= MAGIC_FLAG_GEN_4GTU; } @@ -3298,7 +3424,7 @@ void MifareCIdent(bool is_mfc, uint8_t keytype, uint8_t *key) { // test for super card ReaderTransmit(superGen1, sizeof(superGen1), NULL); - res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par); + res = ReaderReceive(buf, MAX_FRAME_SIZE, par); if (res == 22) { uint8_t isGen = MAGIC_FLAG_SUPER_GEN1; @@ -3309,7 +3435,7 @@ void MifareCIdent(bool is_mfc, uint8_t keytype, uint8_t *key) { res = iso14443a_select_card(uid, NULL, &cuid, true, 0, true); if (res) { ReaderTransmit(rdbl00, sizeof(rdbl00), NULL); - res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par); + res = ReaderReceive(buf, MAX_FRAME_SIZE, par); if (res == 18) { isGen = MAGIC_FLAG_SUPER_GEN2; } @@ -3325,7 +3451,7 @@ void MifareCIdent(bool is_mfc, uint8_t keytype, uint8_t *key) { res = iso14443a_select_card(uid, NULL, &cuid, true, 0, true); if (res == 2) { ReaderTransmit(rdblf0, sizeof(rdblf0), NULL); - res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par); + res = ReaderReceive(buf, MAX_FRAME_SIZE, par); if (res == 18) { flag |= MAGIC_FLAG_NTAG21X; } @@ -3350,7 +3476,7 @@ void MifareCIdent(bool is_mfc, uint8_t keytype, uint8_t *key) { uint64_t tmpkey = bytes_to_num(key, 6); if (mifare_classic_authex(pcs, cuid, 0, keytype, tmpkey, AUTH_FIRST, NULL, NULL) == 0) { - if ((mifare_sendcmd_short(pcs, 1, ISO14443A_CMD_WRITEBLOCK, 0, buf, PM3_CMD_DATA_SIZE, par, NULL) == 1) && (buf[0] == 0x0A)) { + if ((mifare_sendcmd_short(pcs, 1, ISO14443A_CMD_WRITEBLOCK, 0, buf, MAX_FRAME_SIZE, par, NULL) == 1) && (buf[0] == 0x0A)) { flag |= MAGIC_FLAG_GEN_2; // turn off immediately to ensure nothing ever accidentally writes to the block FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); @@ -3366,7 +3492,7 @@ void MifareCIdent(bool is_mfc, uint8_t keytype, uint8_t *key) { res = iso14443a_select_card(uid, NULL, &cuid, true, 0, true); if (res) { ReaderTransmit(rdbl00, sizeof(rdbl00), NULL); - res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par); + res = ReaderReceive(buf, MAX_FRAME_SIZE, par); if (res == 18) { flag |= MAGIC_FLAG_GEN_3; } @@ -3378,7 +3504,7 @@ void MifareCIdent(bool is_mfc, uint8_t keytype, uint8_t *key) { res = iso14443a_select_card(uid, NULL, &cuid, true, 0, true); if (res) { ReaderTransmit(gen4gdmAuth, sizeof(gen4gdmAuth), NULL); - res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par); + res = ReaderReceive(buf, MAX_FRAME_SIZE, par); if (res == 4) { flag |= MAGIC_FLAG_GDM_AUTH; } @@ -3695,6 +3821,10 @@ int DoGen3Cmd(uint8_t *cmd, uint8_t cmd_len) { int retval = PM3_SUCCESS; uint8_t *par = BigBuf_calloc(MAX_PARITY_SIZE); uint8_t *buf = BigBuf_calloc(PM3_CMD_DATA_SIZE); + if (par == NULL || buf == NULL) { + if (g_dbglevel >= DBG_ERROR) DbpString("Gen3 cmd: failed to allocate buffers"); + return PM3_EMALLOC; + } LED_B_ON(); uint32_t save_iso14a_timeout = iso14a_get_timeout(); @@ -3721,6 +3851,13 @@ void MifareGen3UID(uint8_t uidlen, uint8_t *uid) { uint8_t *cmd = BigBuf_calloc(sizeof(uid_cmd) + uidlen + 2); iso14a_card_select_t *card_info = (iso14a_card_select_t *) BigBuf_calloc(sizeof(iso14a_card_select_t)); + if (old_uid == NULL || cmd == NULL || card_info == NULL) { + if (g_dbglevel >= DBG_ERROR) DbpString("Gen3 UID: failed to allocate buffers"); + reply_ng(CMD_HF_MIFARE_GEN3UID, PM3_EMALLOC, NULL, 0); + BigBuf_free(); + return; + } + LEDsoff(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); clear_trace(); @@ -3758,6 +3895,13 @@ void MifareGen3Blk(uint8_t block_len, uint8_t *block) { iso14a_card_select_t *card_info = (iso14a_card_select_t *) BigBuf_calloc(sizeof(iso14a_card_select_t)); + if (cmd == NULL || card_info == NULL) { + if (g_dbglevel >= DBG_ERROR) DbpString("Gen3 blk: failed to allocate buffers"); + reply_ng(CMD_HF_MIFARE_GEN3BLK, PM3_EMALLOC, NULL, 0); + BigBuf_free(); + return; + } + LEDsoff(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); clear_trace(); @@ -4004,7 +4148,7 @@ void MifareSetMod(uint8_t *datain) { uint64_t ui64Key = bytes_to_num(datain + 1, 6); // variables - uint16_t isOK = PM3_EUNDEF; + int8_t isOK = PM3_EUNDEF; // reply_ng() takes int8_t, match it uint8_t *uid = BigBuf_calloc(10); uint32_t cuid = 0; @@ -4014,6 +4158,13 @@ void MifareSetMod(uint8_t *datain) { uint8_t *buf = BigBuf_calloc(MAX_MIFARE_FRAME_SIZE); uint8_t *par = BigBuf_calloc(MAX_MIFARE_PARITY_SIZE); + if (uid == NULL || buf == NULL || par == NULL) { + if (g_dbglevel >= DBG_ERROR) DbpString("SetMod: failed to allocate buffers"); + reply_ng(CMD_HF_MIFARE_SETMOD, PM3_EMALLOC, NULL, 0); + BigBuf_free(); + return; + } + LEDsoff(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); diff --git a/armsrc/mifaresim.c b/armsrc/mifaresim.c index 29b69689a..88bc14529 100644 --- a/armsrc/mifaresim.c +++ b/armsrc/mifaresim.c @@ -33,6 +33,7 @@ #include "iso14443a.h" #include "BigBuf.h" +#include "fpga_loader.h" #include "string.h" #include "mifareutil.h" #include "fpga_apis.h" @@ -460,6 +461,11 @@ bool MifareSimInit(uint16_t flags, uint8_t *uid, uint16_t atqa, uint8_t sak, tag #define ALLOCATED_TAG_MODULATION_BUFFER_SIZE 571 uint8_t *free_buffer = BigBuf_calloc(ALLOCATED_TAG_MODULATION_BUFFER_SIZE); + if (free_buffer == NULL) { + Dbprintf("ERROR: " _RED_("Failed to allocate modulation buffer")); + return false; + } + // modulation buffer pointer and current buffer free space size uint8_t *free_buffer_pointer = free_buffer; size_t free_buffer_size = ALLOCATED_TAG_MODULATION_BUFFER_SIZE; @@ -541,8 +547,17 @@ void Mifare1ksim(uint16_t flags, uint8_t exitAfterNReads, uint8_t *uid, uint16_t const tUart14a *uart = GetUart14a(); + //----------------------------------------------------------------------------- + // Note: we call FpgaDownloadAndGo_keep_EM(FPGA_BITSTREAM_HF) here although the + // FPGA isn't needed yet. iso14443a_setup() below does it otherwise, and a + // bitstream download frees and clears BigBuf - which by then holds the + // Emulator Memory and the precompiled anticollision responses. + //----------------------------------------------------------------------------- + FpgaDownloadAndGo_keep_EM(FPGA_BITSTREAM_HF); + // free eventually allocated BigBuf memory but keep Emulator Memory BigBuf_free_keep_EM(); + clear_trace(); if (MifareSimInit(flags, uid, atqa, sak, &responses, &cuid, &uid_len, &rats, &rats_len) == false) { BigBuf_free_keep_EM(); @@ -552,8 +567,6 @@ void Mifare1ksim(uint16_t flags, uint8_t exitAfterNReads, uint8_t *uid, uint16_t // We need to listen to the high-frequency, peak-detected path. iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN); - // clear trace - clear_trace(); set_tracing(true); LED_D_ON(); ResetSspClk(); diff --git a/armsrc/mifaresniff_disabled.c b/armsrc/mifaresniff_disabled.c index 95f4bb61f..8a15a5b19 100644 --- a/armsrc/mifaresniff_disabled.c +++ b/armsrc/mifaresniff_disabled.c @@ -62,6 +62,10 @@ void RAMFUNC SniffMifare(uint8_t param) { // allocate the DMA buffer, used to stream samples from the FPGA uint8_t *dmaBuf = BigBuf_malloc(DMA_BUFFER_SIZE); + if (dmaBuf == NULL) { + if (g_dbglevel >= DBG_ERROR) Dbprintf("Failed to allocate memory"); + return; + } uint8_t *data = dmaBuf; uint8_t previous_data = 0; int dataLen, maxDataLen = 0; diff --git a/armsrc/pcf7931.c b/armsrc/pcf7931.c index 1a69eb0b6..a39fa7065 100644 --- a/armsrc/pcf7931.c +++ b/armsrc/pcf7931.c @@ -60,7 +60,7 @@ size_t DemodPCF7931(uint8_t **outBlocks, bool ledcontrol) { uint8_t bits[256] = {0x00}; uint8_t blocks[8][16]; uint8_t *dest = BigBuf_get_addr(); - uint16_t g_GraphTraceLen = BigBuf_max_traceLen(); + uint32_t g_GraphTraceLen = BigBuf_max_traceLen(); // limit g_GraphTraceLen to a little more than 2 data frames. // To make sure a complete dataframe is in the dataset. // 1 Frame is 16 Byte -> 128byte. at a T0 of 64 -> 8129 Samples per frame. diff --git a/armsrc/pm5_cep.c b/armsrc/pm5_cep.c new file mode 100644 index 000000000..1983d402a --- /dev/null +++ b/armsrc/pm5_cep.c @@ -0,0 +1,466 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// See pm5_cep.h. Extracted from the dead test_f0_com_by_usb_cep() / +// cep_spi_*() code in at32_unit_test.c (GH issue #3667) - the register-level +// handshake and SPI logic is dxl's original work, carried over near-verbatim +// except where noted below. +// +// Hardware-verified (real Flipper Zero, repeated app relaunches without a +// physical cable replug): USART1 handshake, the SPI1 mode below for the +// handshake reply, and the CC-controller I2C address 0x47 all confirmed +// working. Not yet exercised: the post-handshake NG-frame SPI transport +// (cep_spi_read_ng/write_sync) under an actual client command. +//----------------------------------------------------------------------------- + +#include "pm5_cep.h" + +#include "at32f435_437.h" +#include "at32f435_437_crm.h" +#include "at32f435_437_gpio.h" +#include "at32f435_437_usart.h" +#include "at32f435_437_spi.h" +#include "gpio_apis.h" +#include "i2c.h" +#include "ticks_apis.h" +#include "dbprint.h" +#include "pm3_cmd.h" +#include "string.h" + +#define CEP_CC_CONTROLLER_ADDR 0x47 +#define CEP_CC_STATUS_REG 0x09 +#define CEP_ATTACH_POLL_MS 50 // CC-controller I2C poll interval +#define CEP_HANDSHAKE_STRING "iamf0rupm5" +#define CEP_HANDSHAKE_STX 0x02 +#define CEP_SPI_BYTE_TIMEOUT 100000 // spin-wait iterations per byte (matches source) +// The Flipper master only clocks the bus in bursts roughly every ~120ms +// (its own idle poll cadence) - CEP_SPI_BYTE_TIMEOUT alone (~3-10ms real +// time) is far shorter than that gap, so the first reply byte - the one +// racing against the master's next poll - needs a budget that actually +// spans it. Once that byte clears, the master is mid-CS and keeps +// clocking continuously, so every later byte stays on the short timeout. +// Took measured CEP reply success from ~22% to ~100% in testing. +#define CEP_SPI_HEADER_BYTE_TIMEOUT 2000000 +#define CEP_SPI_RESPONSE_TIMEOUT_US (1000 * 1000) // 1s, matches source +#define CEP_HANDSHAKE_RX_TIMEOUT_MS 2000 // bail out of the receive loop rather than ever hang the main loop +#define CEP_HANDSHAKE_REPLY_MAX_RETRIES 3 // bound the stall-recovery loop below - still-attached isn't still-working forever + +// 0x55 filler the Flipper sends while its own SPI poll finds nothing new - +// discard it so the real length header is recognized as soon as it starts, +// instead of ever reading a 0x55 byte as (part of) a frame length. +#define CEP_SYNC_BYTE 0x55 +#define CEP_SYNC_MAX_DISCARD 600 + +// How long cep_attach_poll() will go without seeing a real SPI poll from the +// Flipper before deciding the FAP has quit (see the comment at its one use +// below) and letting AppMain() go back to sleeping between iterations. +#define CEP_ACTIVITY_TIMEOUT_MS 3000 + +static bool s_cep_active = false; // handshake completed, SPI transport live +static bool s_cep_attached = false; // CC controller reports a physical attach +static uint32_t s_last_spi_activity_tick = 0; // last time a real SPI poll was seen + +bool cep_is_active(void) { + return s_cep_active; +} + +bool cep_is_attached(void) { + return s_cep_attached; +} + +// --------------------------------------------------------------------------- +// One-time peripheral bring-up +// --------------------------------------------------------------------------- + +static void cep_usart_init(void) { + crm_periph_clock_enable(CRM_USART1_PERIPH_CLOCK, TRUE); + crm_periph_clock_enable(CRM_GPIOA_PERIPH_CLOCK, TRUE); + + gpio_init_type gpio_init_struct; + gpio_default_para_init(&gpio_init_struct); + gpio_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER; + gpio_init_struct.gpio_out_type = GPIO_OUTPUT_OPEN_DRAIN; + gpio_init_struct.gpio_mode = GPIO_MODE_MUX; + gpio_init_struct.gpio_pins = GPIO_PINS_9; + gpio_init_struct.gpio_pull = GPIO_PULL_UP; + gpio_init(GPIOA, &gpio_init_struct); + gpio_pin_mux_config(GPIOA, GPIO_PINS_SOURCE9, GPIO_MUX_7); + + usart_init(USART1, 2400, USART_DATA_8BITS, USART_STOP_1_BIT); + usart_parity_selection_config(USART1, USART_PARITY_NONE); + usart_transmitter_enable(USART1, FALSE); // RX only - the reply goes over SPI, not this UART + usart_receiver_enable(USART1, TRUE); + usart_single_line_halfduplex_select(USART1, TRUE); + usart_enable(USART1, TRUE); + + // PA10 (USB1_ID): read once to pick master/slave role for the SPI pin mux. + gpio_init_struct.gpio_pull = GPIO_PULL_NONE; + gpio_init_struct.gpio_mode = GPIO_MODE_INPUT; + gpio_init_struct.gpio_pins = GPIO_PINS_10; + gpio_init(GPIOA, &gpio_init_struct); +} + +static spi_master_slave_mode_type s_spi_mode; + +static void cep_spi_init(void) { + bool is_slave_mode = GpioInputStatus(GPIOA, GPIO_PINS_10); + gpio_inter_usb_spi_role_setup(); + if (is_slave_mode) { + Gpio_Inter_USB_SPI_Role_High(); + } else { + Gpio_Inter_USB_SPI_Role_Low(); + } + s_spi_mode = is_slave_mode ? SPI_MODE_SLAVE : SPI_MODE_MASTER; + + gpio_init_type gpio_init_struct; + crm_periph_clock_enable(CRM_GPIOA_PERIPH_CLOCK, TRUE); + + // CS (PA4) + gpio_init_struct.gpio_out_type = GPIO_OUTPUT_PUSH_PULL; + gpio_init_struct.gpio_pull = GPIO_PULL_UP; + gpio_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER; + if (s_spi_mode == SPI_MODE_MASTER) { + gpio_init_struct.gpio_mode = GPIO_MODE_OUTPUT; + } else { + gpio_init_struct.gpio_mode = GPIO_MODE_MUX; + gpio_pin_mux_config(GPIOA, GPIO_PINS_SOURCE4, GPIO_MUX_5); + } + gpio_init_struct.gpio_pins = GPIO_PINS_4; + gpio_init(GPIOA, &gpio_init_struct); + + // SCK (PA5) + gpio_init_struct.gpio_out_type = GPIO_OUTPUT_PUSH_PULL; + gpio_init_struct.gpio_pull = GPIO_PULL_DOWN; + gpio_init_struct.gpio_mode = GPIO_MODE_MUX; + gpio_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER; + gpio_init_struct.gpio_pins = GPIO_PINS_5; + gpio_init(GPIOA, &gpio_init_struct); + gpio_pin_mux_config(GPIOA, GPIO_PINS_SOURCE5, GPIO_MUX_5); + + // MISO (PA6) + gpio_init_struct.gpio_pull = GPIO_PULL_UP; + gpio_init_struct.gpio_pins = GPIO_PINS_6; + gpio_init(GPIOA, &gpio_init_struct); + gpio_pin_mux_config(GPIOA, GPIO_PINS_SOURCE6, GPIO_MUX_5); + + // MOSI (PA7) + gpio_init_struct.gpio_pull = GPIO_PULL_UP; + gpio_init_struct.gpio_pins = GPIO_PINS_7; + gpio_init(GPIOA, &gpio_init_struct); + gpio_pin_mux_config(GPIOA, GPIO_PINS_SOURCE7, GPIO_MUX_5); + + if (s_spi_mode == SPI_MODE_MASTER) { + gpio_bits_set(GPIOA, GPIO_PINS_4); // idle CS high, release the slave + } + + spi_init_type spi_init_struct; + crm_periph_clock_enable(CRM_SPI1_PERIPH_CLOCK, TRUE); + spi_default_para_init(&spi_init_struct); + spi_init_struct.transmission_mode = SPI_TRANSMIT_FULL_DUPLEX; + spi_init_struct.master_slave_mode = s_spi_mode; + spi_init_struct.mclk_freq_division = SPI_MCLK_DIV_1024; + // NOT YET HARDWARE-VERIFIED - see file header comment. + spi_init_struct.first_bit_transmission = SPI_FIRST_BIT_MSB; + spi_init_struct.frame_bit_num = SPI_FRAME_8BIT; + spi_init_struct.clock_polarity = SPI_CLOCK_POLARITY_LOW; + spi_init_struct.clock_phase = SPI_CLOCK_PHASE_1EDGE; + spi_init_struct.cs_mode_selection = (s_spi_mode == SPI_MODE_MASTER) ? SPI_CS_SOFTWARE_MODE : SPI_CS_HARDWARE_MODE; + spi_init(SPI1, &spi_init_struct); + spi_enable(SPI1, TRUE); +} + +// AT32F435/437 errata ES0003, "CS falling edge not synchronized in SPI +// slave hardware CS mode": the peripheral's internal clock sync isn't +// guaranteed to reset on every CS edge, so a bad sync can persist across +// transactions. Artery's documented recovery is to detect the corruption +// (we already do, via the NG frame's CRC) and reset SPI before retrying - +// a register re-init alone isn't enough, the peripheral needs resetting +// through the clock/reset controller to actually clear that state. +void cep_spi_resync(void) { + spi_enable(SPI1, FALSE); + crm_periph_reset(CRM_SPI1_PERIPH_RESET, TRUE); + crm_periph_reset(CRM_SPI1_PERIPH_RESET, FALSE); + cep_spi_init(); +} + +void cep_init(void) { + cep_usart_init(); + cep_spi_init(); + // I2C_init() must be preceded by StartTicks(), like everywhere else. + StartTicks(); + I2C_init(true); +} + +// --------------------------------------------------------------------------- +// Handshake +// --------------------------------------------------------------------------- + +// Blocking (bounded by the Flipper's own ~1.1s handshake timeout budget): +// waits for STX then the literal ASCII string, replies "yes" over SPI on a +// match. Only called once, right after cep_attach_poll() sees a fresh attach. +static bool cep_do_handshake(void) { + uint8_t data[sizeof(CEP_HANDSHAKE_STRING) - 1]; + uint8_t rx_len = 0; + uint32_t start_tick = GetTickCount(); + + while (1) { + if (GetTickCountDelta(start_tick) > CEP_HANDSHAKE_RX_TIMEOUT_MS) { + return false; + } + + if (usart_flag_get(USART1, USART_RDBF_FLAG) != RESET) { + uint8_t rx_data = usart_data_receive(USART1); + if (rx_data == CEP_HANDSHAKE_STX) { + // STX: restart the frame. Unlike the original unit-test code, + // do NOT discard an extra byte here - the FAP protocol has no + // byte between STX and the literal string, and doing an + // unconditional second usart_data_receive() without + // re-checking RDBF risked reading stale data and ate what + // should have been the string's first byte. + rx_len = 0; + continue; + } + if (rx_len < sizeof(data)) { + data[rx_len++] = rx_data; + } + } + + if (rx_len == sizeof(data)) { + if (memcmp(CEP_HANDSHAKE_STRING, data, sizeof(data)) == 0) { + break; + } + rx_len = 0; // no match, resync on the next STX + } + } + + uint8_t response[] = {0x04, 0x00, 'y', 'e', 's', 0x00}; + for (size_t i = 0; i < sizeof(response); i++) { + uint32_t wait_start = GetTicks(); + int recovery_attempts = 0; + while (spi_i2s_flag_get(SPI1, SPI_I2S_TDBE_FLAG) == RESET) { + if (GetTicks() - wait_start > CEP_SPI_RESPONSE_TIMEOUT_US) { + // Bound this: "still attached" isn't "still working" forever, + // and I2C_BufferReadRaw() needs the ticks timer running like + // every other call site (see cep_attach_poll()'s comment). + if (++recovery_attempts > CEP_HANDSHAKE_REPLY_MAX_RETRIES) { + return false; + } + StartTicks(); + I2C_init(true); + uint8_t cc_ctrl_data; + bool ret = I2C_BufferReadRaw(&cc_ctrl_data, 1, CEP_CC_STATUS_REG, CEP_CC_CONTROLLER_ADDR << 1); + if (!ret || ((cc_ctrl_data >> 6 & 0x03) == 0)) { + return false; // disconnected mid-reply, or can't tell - bail either way + } + wait_start = GetTicks(); + } + } + spi_i2s_data_transmit(SPI1, response[i]); + } + + return true; +} + +// --------------------------------------------------------------------------- +// Attach polling (non-blocking, rate-limited) +// --------------------------------------------------------------------------- + +void cep_attach_poll(void) { + static uint32_t last_tick = 0; + + if ((last_tick != 0) && (GetTickCountDelta(last_tick) < CEP_ATTACH_POLL_MS)) { + return; + } + last_tick = GetTickCount(); + + // I2C_init() must be preceded by StartTicks(), like everywhere else - + // LF/HF code calls StopTicks() when done, and this poll can land after + // that (see bwm_lowbatt_poll() for the same pattern). + StartTicks(); + I2C_init(true); + + uint8_t cc_ctrl_data; + bool ret = I2C_BufferReadRaw(&cc_ctrl_data, 1, CEP_CC_STATUS_REG, CEP_CC_CONTROLLER_ADDR << 1); + if (!ret) { + return; + } + + bool attached = ((cc_ctrl_data >> 6 & 0x03) != 0); + s_cep_attached = attached; + + if (!attached) { + s_cep_active = false; + } else { + // The FAP re-runs its handshake on every app launch, not just on a + // fresh physical attach - the CC controller's attach bits don't + // reliably blip on every relaunch (confirmed on hardware: sometimes + // they do, sometimes they don't), so gating the handshake listener on + // that edge alone missed real handshake attempts and required a + // physical unplug/replug to recover (GH #3667). Instead, watch for a + // fresh incoming byte any time we're attached, regardless of edge. + // cep_do_handshake() itself is timeout-bounded so a spurious byte + // can't hang the main loop. + if (usart_flag_get(USART1, USART_RDBF_FLAG) != RESET) { + s_cep_active = cep_do_handshake(); + if (s_cep_active) { + s_last_spi_activity_tick = GetTickCount(); + } + } + + // The FAP quitting doesn't touch the CC controller's attach bit - the + // cable stays connected, so `attached` alone can't tell us it's gone. + // Losing its SPI poll cadence (normally every 20-120ms) is what + // actually means it has - fall back to the slower/idle main loop + // once that cadence has been missing this long. + if (s_cep_active && (GetTickCountDelta(s_last_spi_activity_tick) > CEP_ACTIVITY_TIMEOUT_MS)) { + s_cep_active = false; + } + } + + uint8_t int_state = cc_ctrl_data >> 4 & 0x01; + if (int_state) { + cc_ctrl_data |= 1 << 4; // clear the CC controller's interrupt latch + I2C_BufferWrite(&cc_ctrl_data, 1, CEP_CC_STATUS_REG, CEP_CC_CONTROLLER_ADDR << 1); + } +} + +// --------------------------------------------------------------------------- +// SPI NG-frame transport (verbatim from the unit test - already correct) +// --------------------------------------------------------------------------- + +static bool cep_spi_read_byte(uint8_t *out) { + uint64_t timeout = 0; + while (spi_i2s_flag_get(SPI1, SPI_I2S_RDBF_FLAG) == RESET) { + if (timeout++ > CEP_SPI_BYTE_TIMEOUT) { + return false; + } + } + *out = spi_i2s_data_receive(SPI1); + return true; +} + +// Genuinely non-blocking - a single flag read, no spin-wait at all. For +// data_available()'s use (armsrc/util.c): a tight sampling loop calls that +// every pass purely to notice an incoming CMD_BREAK_LOOP promptly, so it +// needs to cost nothing when idle. cep_spi_data_available() isn't a fit +// here - it waits (bounded, but non-zero) for a first byte to actually +// arrive, which is fine for receive_ng()'s own cadence but would add that +// wait to every iteration of every LF/HF reader loop in the codebase. +bool cep_spi_rx_pending(void) { + return spi_i2s_flag_get(SPI1, SPI_I2S_RDBF_FLAG) != RESET; +} + +bool cep_spi_data_available(void) { + uint8_t len_header[2] = {0x00}; + size_t discarded = 0; + while (1) { + if (!cep_spi_read_byte(&len_header[0])) { + return false; + } + if (len_header[0] != CEP_SYNC_BYTE) { + break; + } + if (++discarded > CEP_SYNC_MAX_DISCARD) { + // More sync bytes than the FAP's real preamble (500) can only + // mean a desynced read (AT32 errata ES0003, see + // cep_spi_resync()) or bus noise - resync now rather than + // leaving SPI1 in that state until a later CRC/length check + // catches it, which may be a full frame away. + cep_spi_resync(); + return false; + } + } + if (!cep_spi_read_byte(&len_header[1])) { + return false; + } + s_last_spi_activity_tick = GetTickCount(); // FAP is still polling, valid frame or not + uint16_t data_len = (len_header[1] << 8) | len_header[0]; + if (data_len > PM3_CMD_DATA_SIZE * 2) { + // Same reasoning: an implausible length is itself evidence of a + // desynced read, not just "no frame yet." + cep_spi_resync(); + return false; + } + return true; +} + +uint32_t cep_spi_read_ng(uint8_t *data, size_t len) { + for (size_t i = 0; i < len; ++i) { + uint64_t timeout = 0; + while (spi_i2s_flag_get(SPI1, SPI_I2S_RDBF_FLAG) == RESET) { + if (timeout++ > CEP_SPI_BYTE_TIMEOUT) { + return i; + } + } + data[i] = spi_i2s_data_receive(SPI1); + } + return len; +} + +// PM5 is the SPI slave: TDBE only clears when the master is actively +// clocking, which happens on the Flipper's own ~20-120ms poll schedule, +// completely async to when PM5 has a reply ready. An unbounded wait here +// hangs the main loop forever (no recovery, not even a watchdog reset) the +// moment a reply is queued between two master polls - bound every wait so +// a slow/absent master degrades to a dropped reply, not a dead device. +static bool cep_spi_wait_tdbe(uint64_t timeout_limit) { + uint64_t timeout = 0; + while (spi_i2s_flag_get(SPI1, SPI_I2S_TDBE_FLAG) == RESET) { + if (timeout++ > timeout_limit) { + return false; + } + } + return true; +} + +int cep_spi_write_sync(uint8_t *data, size_t len) { + // These two length-header bytes are the ones racing against the + // master's next poll - see CEP_SPI_HEADER_BYTE_TIMEOUT's comment. + if (!cep_spi_wait_tdbe(CEP_SPI_HEADER_BYTE_TIMEOUT)) { + return PM3_EIO; + } + spi_i2s_data_transmit(SPI1, len & 0xFF); + + if (!cep_spi_wait_tdbe(CEP_SPI_HEADER_BYTE_TIMEOUT)) { + return PM3_EIO; + } + spi_i2s_data_transmit(SPI1, (len >> 8) & 0xFF); + + for (size_t i = 0; i < len; ++i) { + if (!cep_spi_wait_tdbe(CEP_SPI_BYTE_TIMEOUT)) { + return PM3_EIO; + } + spi_i2s_data_transmit(SPI1, data[i]); + } + + // Two trailing zero bytes: the agreed "no more data" idle marker. + if (!cep_spi_wait_tdbe(CEP_SPI_BYTE_TIMEOUT)) { + return PM3_EIO; + } + spi_i2s_data_transmit(SPI1, 0x00); + if (!cep_spi_wait_tdbe(CEP_SPI_BYTE_TIMEOUT)) { + return PM3_EIO; + } + spi_i2s_data_transmit(SPI1, 0x00); + + uint64_t timeout = 0; + while (spi_i2s_flag_get(SPI1, SPI_I2S_BF_FLAG) == SET) { + if (timeout++ > CEP_SPI_BYTE_TIMEOUT) { + return PM3_EIO; + } + } + + return PM3_SUCCESS; +} diff --git a/armsrc/pm5_cep.h b/armsrc/pm5_cep.h new file mode 100644 index 000000000..7185be426 --- /dev/null +++ b/armsrc/pm5_cep.h @@ -0,0 +1,84 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// Proxmark5 CEP (Type-C Extended Port) transport to the Flipper Zero FAP. +// +// USART1 (PA9, single-wire half-duplex, 2400 8N1) carries a one-shot ASCII +// handshake ("iamf0rupm5" -> "yes"); once attached, standard PM3 NG frames +// ride length-prefixed over SPI1 (PA4-7). See GH issue #3667 for the full +// protocol writeup this was extracted from (armsrc/at32_unit_test.c, dxl). +// +// Enabled by -DWITH_CEP. Independent of -DWITH_BWM_FORWARD - both may be +// compiled and running at the same time. +//----------------------------------------------------------------------------- + +#ifndef __PM5_CEP_H +#define __PM5_CEP_H + +#include "common.h" + +// Bring up the CC-controller I2C polling state. Call once from AppMain(), +// after usb_enable() (mirrors bwm_uart_init() placement). Never blocks. +void cep_init(void); + +// True once the Flipper handshake has completed and the SPI transport is +// expected to be live. Gate for receive_ng()/reply_ng_internal() so they +// don't pay an SPI-timeout poll on every idle main-loop iteration when no +// Flipper is attached. +bool cep_is_active(void); + +// True once the CC controller reports a Flipper physically attached, +// independent of whether the handshake/SPI transport is up yet. Gate for +// AppMain()'s WFI-skip (see appmain.c) - a Flipper merely being plugged in +// is reason enough to stop sleeping between main-loop iterations, before +// any handshake has even started. +bool cep_is_attached(void); + +// Rate-limited (see PM5_CEP_ATTACH_POLL_MS), non-blocking. Call once per +// AppMain() main-loop iteration, alongside bwm_autooff_check(). Detects the +// Flipper attach/detach transition via the CC controller and, on a fresh +// attach, runs the one-shot UART handshake. Safe no-op the rest of the time. +void cep_attach_poll(void); + +// Gate for receive_ng(): true once the length header of an inbound SPI frame +// has been seen. Blocks (with an internal timeout) waiting for the 2-byte +// length header - mirrors usart_rxdata_available()'s call shape, not a +// simple non-blocking peek. +bool cep_spi_data_available(void); + +// True if SPI1's receive-data register currently holds an unread byte - a +// single flag check, zero wait. Gate for data_available() (armsrc/util.c), +// which many LF/HF reader loops call every pass to notice an incoming +// CMD_BREAK_LOOP - that call site needs to cost nothing when idle, unlike +// cep_spi_data_available() above which waits (bounded) for a first byte. +bool cep_spi_rx_pending(void); + +// Read up to `len` raw NG bytes off SPI1. Returns the number of bytes +// actually read before an internal per-byte timeout gave up early. +uint32_t cep_spi_read_ng(uint8_t *data, size_t len); + +// Write `len` raw NG bytes (a whole PacketResponseNG/OLD frame) out over +// SPI1 as one length-prefixed packet. Returns PM3_EIO if the master isn't +// clocking within CEP_SPI_BYTE_TIMEOUT at any point - this can legitimately +// happen (PM5's reply is ready on its own schedule, not the master's), the +// caller just loses this one reply rather than hanging forever. +int cep_spi_write_sync(uint8_t *data, size_t len); + +// Hardware-reset SPI1 and bring it back up (see AT32F435/437 errata ES0003 +// in pm5_cep.c). Call on any CEP frame error so a corrupted CS-edge sync +// can't persist into the next transaction. +void cep_spi_resync(void); + +#endif // __PM5_CEP_H diff --git a/armsrc/pm5_power.c b/armsrc/pm5_power.c new file mode 100644 index 000000000..070d851b9 --- /dev/null +++ b/armsrc/pm5_power.c @@ -0,0 +1,241 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// Proxmark5 (AT32F435) power-save idle - see pm5_power.h. +// +// Idle: SCLK PLL-288 -> HICK-48, PLL off, LDO 1.3 -> 1.1 V (good to 144 MHz), +// FPGA CLKOUT1 parked low, core in WFI until an IRQ or a 1 ms SysTick wake. +// USB is crystal-less off HICK-48 (ACC-trimmed on the SOF, usb_cdc_at32.c) and +// the 1 kHz tick counter is on the ERTC (HEXT/20), so neither notices the PLL +// going away. Everything else keeps its 288 MHz assumption via the boost. +// +// Ported from the Fantasi firmware. +//----------------------------------------------------------------------------- +#include "pm5_power.h" + +#include "proxmark3_arm.h" +#include "dbprint.h" +#include "ticks_apis.h" +#include "fpga_apis.h" +#include "config_gpio_proxmark5.h" +#ifdef WITH_BWM_FORWARD +#include "bwm_uart_at32.h" +#endif + +#include "at32f435_437.h" +#include "at32f435_437_crm.h" +#include "at32f435_437_pwc.h" +#include "at32f435_437_gpio.h" + +// Full speed through USB enumeration and the rest of the boot. +#define PM5_POWER_BOOT_GRACE_MS 3000 +// Quiet time after the last boost before downclocking: back-to-back commands +// (autopwn, scripts, BWM forwarded traffic) don't pay the switch each time. +#define PM5_POWER_IDLE_MS 200 +#define PM5_POWER_CLK_WAIT 500000u + +static volatile uint32_t s_boost; // >0 = something holds 288 MHz +static volatile bool s_clk_high = true; // boot runs at 288 MHz +static bool s_powersave = true; +static uint32_t s_last_busy_tick; + +// Stats for `hw status`. +static uint32_t s_downclocks; +static uint32_t s_low_ms; +static uint32_t s_low_since_tick; +static uint32_t s_sleeps; +static uint32_t s_asleep_ms; +static uint32_t s_asleep_us_resid; + +static void pm5_fpga_clk_park(void) { + // Static low, not floating, while the PLL behind CLKOUT1 is off. + gpio_init_type gpio_init_struct; + gpio_default_para_init(&gpio_init_struct); + gpio_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER; + gpio_init_struct.gpio_out_type = GPIO_OUTPUT_PUSH_PULL; + gpio_init_struct.gpio_mode = GPIO_MODE_OUTPUT; + gpio_init_struct.gpio_pins = AT32_GPIO_FPGA_24M_CLK_PIN; + gpio_init_struct.gpio_pull = GPIO_PULL_NONE; + gpio_bits_reset(AT32_GPIO_FPGA_24M_CLK, AT32_GPIO_FPGA_24M_CLK_PIN); + gpio_init(AT32_GPIO_FPGA_24M_CLK, &gpio_init_struct); +} + +// Voltage-safe ordering: up = LDO before frequency, down = frequency before LDO. +// The LDO is only writable while SCLK is on HICK/HEXT, which holds on both paths. +// Runs with IRQs masked. +static void pm5_clk_apply(bool high) { + uint32_t i; + if (high) { + pwc_ldo_output_voltage_set(PWC_LDO_OUTPUT_1V3); + for (volatile uint32_t d = 0; d < 2000; d++) {} // LDO settle + + crm_clock_source_enable(CRM_CLOCK_SOURCE_PLL, TRUE); + for (i = 0; i < PM5_POWER_CLK_WAIT; i++) { + if (crm_flag_get(CRM_PLL_STABLE_FLAG) == SET) break; + } + crm_auto_step_mode_enable(TRUE); + crm_sysclk_switch(CRM_SCLK_PLL); + for (i = 0; i < PM5_POWER_CLK_WAIT; i++) { + if (crm_sysclk_switch_status_get() == CRM_SCLK_PLL) break; + } + crm_auto_step_mode_enable(FALSE); + system_core_clock_update(); + + FpgaSetup24MHzClk(); // CLKOUT1 back on PA8 + } else { + pm5_fpga_clk_park(); + + crm_clock_source_enable(CRM_CLOCK_SOURCE_HICK, TRUE); + for (i = 0; i < PM5_POWER_CLK_WAIT; i++) { + if (crm_flag_get(CRM_HICK_STABLE_FLAG) == SET) break; + } + crm_auto_step_mode_enable(TRUE); + crm_sysclk_switch(CRM_SCLK_HICK); + for (i = 0; i < PM5_POWER_CLK_WAIT; i++) { + if (crm_sysclk_switch_status_get() == CRM_SCLK_HICK) break; + } + crm_auto_step_mode_enable(FALSE); + crm_clock_source_enable(CRM_CLOCK_SOURCE_PLL, FALSE); + pwc_ldo_output_voltage_set(PWC_LDO_OUTPUT_1V1); + system_core_clock_update(); + } +#ifdef WITH_BWM_FORWARD + bwm_uart_clock_update(); // UART4 baud follows APB1 +#endif + s_clk_high = high; +} + +void pm5_power_init(void) { + // SCLK-from-HICK must be 48 MHz, not the 8 MHz reset default. usb_enable() + // already selects this for the crystal-less USB clock; make it explicit. + crm_hick_sclk_frequency_select(CRM_HICK_SCLK_48MHZ); + + // Free-running cycle counter: measures the time actually spent in WFI. + CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk; + DWT->CYCCNT = 0; + DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk; + + s_last_busy_tick = GetTickCount(); +} + +void pm5_power_boost(void) { + __disable_irq(); + if (s_boost++ == 0 && s_clk_high == false) { + pm5_clk_apply(true); + s_low_ms += GetTickCountDelta(s_low_since_tick); + } + __enable_irq(); +} + +void pm5_power_unboost(void) { + __disable_irq(); + if (s_boost > 0) { + s_boost--; + } + __enable_irq(); + // The downclock itself is left to pm5_power_idle() after PM5_POWER_IDLE_MS. + if (s_boost == 0) { + s_last_busy_tick = GetTickCount(); + } +} + +static bool pm5_power_may_downclock(void) { + if (s_boost != 0 || s_clk_high == false) { + return false; + } + if (GetTickCount() < PM5_POWER_BOOT_GRACE_MS) { + return false; + } + if (GetTickCountDelta(s_last_busy_tick) < PM5_POWER_IDLE_MS) { + return false; + } + // A reader field or emulation left running needs the FPGA clock. + return FpgaIsOff(); +} + +// Halt until the next IRQ, at most ~1 ms (one-shot SysTick, AHB/8 source like +// SpinDelayUs which reprograms SysTick anyway). IRQs stay masked across the +// WFI so the cycle delta measures only the sleep; the waking ISR runs after. +static void pm5_power_wfi(void) { + SysTick->CTRL = 0; + SysTick->LOAD = (system_core_clock / 8 / 1000) - 1; + SysTick->VAL = 0; + SysTick->CTRL = SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; + + __disable_irq(); + uint32_t t0 = DWT->CYCCNT; + __WFI(); + uint32_t cycles = DWT->CYCCNT - t0; + __enable_irq(); + + SysTick->CTRL = 0; + + s_sleeps++; + s_asleep_us_resid += cycles / (system_core_clock / 1000000); + if (s_asleep_us_resid >= 1000) { + s_asleep_ms += s_asleep_us_resid / 1000; + s_asleep_us_resid %= 1000; + } +} + +void pm5_power_idle(void) { + if (s_powersave == false) { + return; + } + if (pm5_power_may_downclock()) { + SpinDelayUs(10); // let a just-sent FPGA conf word land before its clock stops + __disable_irq(); + pm5_clk_apply(false); + __enable_irq(); + s_downclocks++; + s_low_since_tick = GetTickCount(); + } + pm5_power_wfi(); +} + +void pm5_power_set_enabled(bool on) { + s_powersave = on; + if (on == false && s_clk_high == false) { + __disable_irq(); + pm5_clk_apply(true); + __enable_irq(); + s_low_ms += GetTickCountDelta(s_low_since_tick); + } +} + +bool pm5_power_get_enabled(void) { + return s_powersave; +} + +// Per-mille of uptime, printed as a percentage with one decimal. +static uint32_t pm5_power_permille(uint32_t ms, uint32_t uptime_ms) { + if (uptime_ms == 0) { + return 0; + } + return (uint32_t)(((uint64_t)ms * 1000) / uptime_ms); +} + +void pm5_power_print_status(void) { + uint32_t uptime = GetTickCount(); + uint32_t low = pm5_power_permille(s_low_ms, uptime); + uint32_t asleep = pm5_power_permille(s_asleep_ms, uptime); + + DbpString(_CYAN_("Power")); + Dbprintf(" Power-save idle..... %s", s_powersave ? _GREEN_("enabled") : _YELLOW_("disabled")); + DbpString(" Core clock.......... 288 MHz active, 48 MHz idle ( PLL off, LDO 1.1 V )"); + Dbprintf(" Uptime.............. %u ms", uptime); + Dbprintf(" Idle at 48 MHz...... %u.%u %% ( %u downclocks )", low / 10, low % 10, s_downclocks); + Dbprintf(" Halted in WFI....... %u.%u %% ( %u sleeps )", asleep / 10, asleep % 10, s_sleeps); +} diff --git a/armsrc/pm5_power.h b/armsrc/pm5_power.h new file mode 100644 index 000000000..4221031c5 --- /dev/null +++ b/armsrc/pm5_power.h @@ -0,0 +1,46 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// Proxmark5 power-save idle: core clock scaling + WFI - see pm5_power.c. +//----------------------------------------------------------------------------- +#ifndef PM5_POWER_H__ +#define PM5_POWER_H__ + +#include "common.h" + +#ifdef PM5 + +// Call once from AppMain after USB is up. +void pm5_power_init(void); + +// Refcounted hold on the full 288 MHz core clock. Wrap anything with timing +// that assumes the boot clock (commands, standalone mode, I2C, buzzer). +void pm5_power_boost(void); +void pm5_power_unboost(void); + +// Main-loop idle step: drop to the idle clock when allowed, then halt the core +// until the next IRQ or the 1 ms wake tick. +void pm5_power_idle(void); + +// Runtime toggle (default on). Off = stay at 288 MHz and spin. +void pm5_power_set_enabled(bool on); +bool pm5_power_get_enabled(void); + +// `hw status` section. +void pm5_power_print_status(void); + +#endif // PM5 + +#endif // PM5_POWER_H__ diff --git a/armsrc/rgb_indicator.c b/armsrc/rgb_indicator.c index a616d32f3..ff1aff23c 100644 --- a/armsrc/rgb_indicator.c +++ b/armsrc/rgb_indicator.c @@ -21,6 +21,7 @@ #ifdef WITH_PM5_PWR_LED #include "rgb_apis.h" // RgbLedSet +#include "pm5_power.h" // pm5_power_boost / unboost #include "gpio_apis.h" // gpio_vusb_setup / Gpio_VUSB_Read (USB-present detection) #include "ticks_apis.h" // GetTickCount / GetTickCountDelta @@ -67,13 +68,19 @@ void rgb_indicator_update(void) { if (on_battery == last_state) { return; // edge-triggered: only write RGB when the state changes } - last_state = on_battery; - if (on_battery) { - RgbLedSet(0, 8, 0); // dim green: alive, on battery - } else { - RgbLedSet(0, 0, 0); // on USB: off (cable already signals power) + pm5_power_boost(); // I2C bit-bang timing assumes the full core clock + // Commit last_state only if the controller actually ACKed. On a cold boot the + // I2C RGB controller can still be powering up when the first write fires; if we + // latched last_state regardless, a NAK here would leave the LED dark until the + // next state change (which never comes on battery). Retrying next cycle costs + // one I2C poke and self-heals once the controller is ready. + bool ok = on_battery ? RgbLedSet(0, 8, 0) // dim green: alive, on battery + : RgbLedSet(0, 0, 0); // on USB: off (cable already signals power) + if (ok) { + last_state = on_battery; } + pm5_power_unboost(); } #endif // WITH_PM5_PWR_LED diff --git a/armsrc/sam_common.c b/armsrc/sam_common.c index db124f48f..f56351fd3 100644 --- a/armsrc/sam_common.c +++ b/armsrc/sam_common.c @@ -445,6 +445,10 @@ int sam_get_version(bool info) { uint8_t *response = BigBuf_calloc(ISO7816_MAX_FRAME); uint16_t response_len = ISO7816_MAX_FRAME; + if (response == NULL) { + res = PM3_EMALLOC; + goto out; + } uint8_t payload[] = { 0xa0, // <- SAM command @@ -543,6 +547,10 @@ int sam_get_serial_number(void) { uint8_t *response = BigBuf_calloc(ISO7816_MAX_FRAME); uint16_t response_len = ISO7816_MAX_FRAME; + if (response == NULL) { + res = PM3_EMALLOC; + goto out; + } uint8_t payload[] = { 0xa0, // <- SAM command @@ -658,6 +666,11 @@ void sam_append_asn1_node(const uint8_t *root, const uint8_t *node, uint8_t type void sam_send_ack(void) { uint8_t *response = BigBuf_calloc(ISO7816_MAX_FRAME); uint16_t response_len = ISO7816_MAX_FRAME; + if (response == NULL) { + if (g_dbglevel >= DBG_ERROR) DbpString(_RED_("SAM: failed to allocate buffer")); + BigBuf_free(); + return; + } uint8_t payload[] = { 0xa0, 0 }; uint16_t payload_len = sizeof(payload); diff --git a/armsrc/sam_picopass.c b/armsrc/sam_picopass.c index 0294b9140..49cb9b75e 100644 --- a/armsrc/sam_picopass.c +++ b/armsrc/sam_picopass.c @@ -548,6 +548,10 @@ static int sam_set_card_detected_picopass(const picopass_hdr_t *card_select) { } uint8_t *response = BigBuf_calloc(ISO7816_MAX_FRAME); uint16_t response_len = ISO7816_MAX_FRAME; + if (response == NULL) { + res = PM3_EMALLOC; + goto out; + } // a0 12 // ad 10 diff --git a/armsrc/sam_seos.c b/armsrc/sam_seos.c index 7fdb49a48..2c94598fb 100644 --- a/armsrc/sam_seos.c +++ b/armsrc/sam_seos.c @@ -63,6 +63,10 @@ static int sam_set_card_detected_seos(iso14a_card_select_t *card_select) { uint8_t *response = BigBuf_calloc(ISO7816_MAX_FRAME); uint16_t response_len = ISO7816_MAX_FRAME; + if (request == NULL || response == NULL) { + res = PM3_EMALLOC; + goto out; + } const uint8_t payload[] = { 0xa0, 8, // <- SAM command diff --git a/armsrc/spiffs.c b/armsrc/spiffs.c index 0b2799c5a..ca10c75f1 100644 --- a/armsrc/spiffs.c +++ b/armsrc/spiffs.c @@ -56,12 +56,20 @@ #include "spiffs.h" #include "BigBuf.h" #include "dbprint.h" +#include "pm3_cmd.h" +#include "string.h" ///// FLASH LEVEL R/W/E operations for feeding SPIFFS Driver///////////////// +// +// SPIFFS_CHECK_RES() only treats a NEGATIVE result as an error, so the 128 / 129 / 130 +// these used to return meant every flash failure was reported to SPIFFS as success. +// A failed erase that reads back as success is the worst of them: SPIFFS then writes +// into a sector that still holds the old content, and since a NOR write can only clear +// bits, page headers and file data silently AND together instead of being replaced. static s32_t rdv40_spiffs_llread(u32_t addr, u32_t size, u8_t *dst) { if (!Flash_ReadData(addr, dst, size)) { - return 128; + return SPIFFS_ERR_NOT_READABLE; } return SPIFFS_OK; } @@ -69,19 +77,50 @@ static s32_t rdv40_spiffs_llread(u32_t addr, u32_t size, u8_t *dst) { static s32_t rdv40_spiffs_llwrite(u32_t addr, u32_t size, u8_t *src) { if (FlashInit() == false) { - return 129; + return SPIFFS_ERR_NOT_WRITABLE; + } + + if (Flash_Write(addr, src, size) != size) { + return SPIFFS_ERR_NOT_WRITABLE; } - Flash_Write(addr, src, size); return SPIFFS_OK; } +// A sector erase that did not take - the chip was still busy, or the write enable +// latch was gone by the time the command arrived - leaves the old content in place. +// Flash_Erase4k() only reports that the command was sent, so read the sector back. +static bool flash_sector_is_erased(uint32_t addr) { + + static uint8_t buf[64]; + + for (uint32_t offset = 0; offset < SPIFFS_CFG_LOG_BLOCK_SZ; offset += sizeof(buf)) { + + if (Flash_ReadDataCont(addr + offset, buf, sizeof(buf)) != sizeof(buf)) { + return false; + } + + for (uint32_t i = 0; i < sizeof(buf); i++) { + if (buf[i] != 0xFF) { + if (g_dbglevel >= DBG_DEBUG) { + Dbprintf("SPIFFS erase verify failed at 0x%05x, read %02x", addr + offset + i, buf[i]); + } + return false; + } + } + } + return true; +} + static s32_t rdv40_spiffs_llerase(u32_t addr, u32_t size) { + (void)size; // always one SPIFFS_CFG_LOG_BLOCK_SZ sector + if (FlashInit() == false) { - return 130; + return SPIFFS_ERR_ERASE_FAIL; } if (g_dbglevel >= DBG_DEBUG) Dbprintf("LLERASEDBG : Orig addr : %d\n", addr); + uint32_t sector_addr = addr; uint8_t block, sector = 0; block = addr / RDV40_LLERASE_BLOCKSIZE; if (block) { @@ -91,18 +130,40 @@ static s32_t rdv40_spiffs_llerase(u32_t addr, u32_t size) { if (g_dbglevel >= DBG_DEBUG) Dbprintf("LLERASEDBG : Result addr : %d\n", addr); sector = addr / SPIFFS_CFG_LOG_BLOCK_SZ; - Flash_CheckBusy(BUSY_TIMEOUT); - Flash_WriteEnable(); if (g_dbglevel >= DBG_DEBUG) Dbprintf("LLERASEDBG : block : %d, sector : %d \n", block, sector); - uint8_t erased = Flash_Erase4k(block, sector); - Flash_CheckBusy(BUSY_TIMEOUT); - FlashStop(); + for (uint8_t attempt = 0; attempt < 2; attempt++) { - // iceman: SPIFFS_OK expands to 0, erased is bool from Flash_Erase4k, which returns TRUE if ok. - // so this return logic looks wrong. - return (SPIFFS_OK == erased); + // true == still busy when the timeout ran out + if (Flash_CheckBusy(BUSY_TIMEOUT)) { + Dbprintf("SPIFFS erase: flash still busy before erasing sector 0x%05x", sector_addr); + continue; + } + + Flash_WriteEnable(); + + if (Flash_Erase4k(block, sector) == false) { + Dbprintf("SPIFFS erase: bad sector address, block %u sector %u", block, sector); + break; + } + + if (Flash_CheckBusy(BUSY_TIMEOUT)) { + Dbprintf("SPIFFS erase: sector 0x%05x did not finish in %u us", sector_addr, BUSY_TIMEOUT); + continue; + } + + if (flash_sector_is_erased(sector_addr)) { + FlashStop(); + return SPIFFS_OK; + } + + Dbprintf("SPIFFS erase: sector 0x%05x did not erase, retrying", sector_addr); + } + + FlashStop(); + Dbprintf(_RED_("SPIFFS erase of sector 0x%05x failed, filesystem not written"), sector_addr); + return SPIFFS_ERR_ERASE_FAIL; } //////////////////////////////////////////////////////////////////////////////// @@ -114,6 +175,38 @@ static u8_t spiffs_cache_buf[RDV40_SPIFFS_CACHE_SZ] __attribute__((aligned)); static spiffs fs; +// One file descriptor held open across the packets of an upload. +// +// SPIFFS has no directory: SPIFFS_open() by name walks the object lookup page of +// every block and reads the header of each index page it meets to compare names. +// Doing that per packet makes an upload cost packets x filesystem size - measured +// on a 2MB filesystem, one open reads ~120KB of flash, so storing a 512KB file +// spent 16MB of reads finding the same file 131 times over. +// +// Only append_to_spiffs() fills this in. Every other path into the filesystem +// calls spiffs_close_cached() first, so a held descriptor can never be seen by +// another operation - the descriptor is closed, and its writes flushed, before +// anything else looks at the file. +static spiffs_file g_cached_fd = -1; +static char g_cached_fn[SPIFFS_OBJ_NAME_LEN] = {0}; + +static int rdv40_spiffs_mounted(void); + +static void spiffs_close_cached(void) { + + if (g_cached_fd < 0) { + return; + } + + // an unmount already invalidated it, do not touch the dead handle + if (rdv40_spiffs_mounted()) { + SPIFFS_close(&fs, g_cached_fd); + } + + g_cached_fd = -1; + g_cached_fn[0] = '\0'; +} + static enum spiffs_mount_status { RDV40_SPIFFS_UNMOUNTED, RDV40_SPIFFS_MOUNTED, @@ -173,6 +266,9 @@ int rdv40_spiffs_unmount(void) { return SPIFFS_ERR_NOT_MOUNTED; } + // the descriptor does not survive the unmount, flush it out first + spiffs_close_cached(); + SPIFFS_clearerr(&fs); SPIFFS_unmount(&fs); @@ -184,6 +280,7 @@ int rdv40_spiffs_unmount(void) { } int rdv40_spiffs_check(void) { + spiffs_close_cached(); rdv40_spiffs_lazy_mount(); SPIFFS_check(&fs); SPIFFS_gc_quick(&fs, 0); @@ -195,25 +292,64 @@ int rdv40_spiffs_check(void) { ///// Base RDV40_SPIFFS_SAFETY_NORMAL operations//////////////////////////////// +// RDV40_SPIFFS_SAFE_FUNCTION() returns the mount-change flag, not a result, so a +// failed write had no way of reaching the caller - the client happily reported +// "Wrote N bytes" for a file the device never stored. The last write result is +// kept here instead, see rdv40_spiffs_write_status() +static int g_spiffs_write_res = SPIFFS_OK; + +int rdv40_spiffs_write_status(void) { + return g_spiffs_write_res; +} + void write_to_spiffs(const char *filename, const uint8_t *src, uint32_t size) { + g_spiffs_write_res = SPIFFS_OK; + spiffs_close_cached(); spiffs_file fd = SPIFFS_open(&fs, filename, SPIFFS_CREAT | SPIFFS_TRUNC | SPIFFS_RDWR, 0); + if (fd < 0) { + g_spiffs_write_res = SPIFFS_errno(&fs); + Dbprintf("open errno %i\n", g_spiffs_write_res); + return; + } // Note: SPIFFS_write() doesn't declare third parameter as const (but should) if (SPIFFS_write(&fs, fd, (void *)src, size) < 0) { - Dbprintf("wr errno %i\n", SPIFFS_errno(&fs)); + g_spiffs_write_res = SPIFFS_errno(&fs); + Dbprintf("wr errno %i\n", g_spiffs_write_res); } SPIFFS_close(&fs, fd); } void append_to_spiffs(const char *filename, const uint8_t *src, uint32_t size) { - spiffs_file fd = SPIFFS_open(&fs, filename, SPIFFS_APPEND | SPIFFS_RDWR, 0); + g_spiffs_write_res = SPIFFS_OK; + + // reuse the descriptor when this is another packet of the same file + if ((g_cached_fd < 0) || (strncmp(filename, g_cached_fn, sizeof(g_cached_fn)) != 0)) { + + spiffs_close_cached(); + + spiffs_file fd = SPIFFS_open(&fs, filename, SPIFFS_APPEND | SPIFFS_RDWR, 0); + if (fd < 0) { + g_spiffs_write_res = SPIFFS_errno(&fs); + Dbprintf("open errno %i\n", g_spiffs_write_res); + return; + } + + g_cached_fd = fd; + strncpy(g_cached_fn, filename, sizeof(g_cached_fn) - 1); + g_cached_fn[sizeof(g_cached_fn) - 1] = '\0'; + } + // Note: SPIFFS_write() doesn't declare third parameter as const (but should) - if (SPIFFS_write(&fs, fd, (void *)src, size) < 0) { - Dbprintf("errno %i\n", SPIFFS_errno(&fs)); + if (SPIFFS_write(&fs, g_cached_fd, (void *)src, size) < 0) { + g_spiffs_write_res = SPIFFS_errno(&fs); + Dbprintf("errno %i\n", g_spiffs_write_res); + // do not hold on to a descriptor that just failed + spiffs_close_cached(); } - SPIFFS_close(&fs, fd); } void read_from_spiffs(const char *filename, uint8_t *dst, uint32_t size) { + spiffs_close_cached(); spiffs_file fd = SPIFFS_open(&fs, filename, SPIFFS_RDWR, 0); if (SPIFFS_read(&fs, fd, dst, size) < 0) { Dbprintf("errno %i\n", SPIFFS_errno(&fs)); @@ -222,18 +358,21 @@ void read_from_spiffs(const char *filename, uint8_t *dst, uint32_t size) { } static void rename_in_spiffs(const char *old_filename, const char *new_filename) { + spiffs_close_cached(); if (SPIFFS_rename(&fs, old_filename, new_filename) < 0) { Dbprintf("errno %i\n", SPIFFS_errno(&fs)); } } static void remove_from_spiffs(const char *filename) { + spiffs_close_cached(); if (SPIFFS_remove(&fs, filename) < 0) { Dbprintf("errno %i\n", SPIFFS_errno(&fs)); } } uint32_t size_in_spiffs(const char *filename) { + spiffs_close_cached(); spiffs_stat s; if (SPIFFS_stat(&fs, filename, &s) < 0) { Dbprintf("errno %i\n", SPIFFS_errno(&fs)); @@ -243,6 +382,7 @@ uint32_t size_in_spiffs(const char *filename) { } static rdv40_spiffs_fsinfo info_of_spiffs(void) { + spiffs_close_cached(); rdv40_spiffs_fsinfo fsinfo; fsinfo.blockSize = SPIFFS_CFG_LOG_BLOCK_SZ; fsinfo.pageSize = LOG_PAGE_SIZE; @@ -261,6 +401,7 @@ static rdv40_spiffs_fsinfo info_of_spiffs(void) { } int exists_in_spiffs(const char *filename) { + spiffs_close_cached(); spiffs_stat stat; int rc = SPIFFS_stat(&fs, filename, &stat); return (rc == SPIFFS_OK); @@ -268,7 +409,8 @@ int exists_in_spiffs(const char *filename) { static RDV40SpiFFSFileType filetype_in_spiffs(const char *filename) { RDV40SpiFFSFileType filetype = RDV40_SPIFFS_FILETYPE_UNKNOWN; - char symlinked[SPIFFS_OBJ_NAME_LEN]; + // SPIFFS_OBJ_NAME_LEN + 4 : a 31 char name plus ".lnk" and the terminator + char symlinked[SPIFFS_OBJ_NAME_LEN + 4]; sprintf(symlinked, "%s.lnk", filename); if (exists_in_spiffs(filename)) { @@ -301,20 +443,49 @@ static RDV40SpiFFSFileType filetype_in_spiffs(const char *filename) { } return filetype; } -/* -static int is_valid_filename(const char *filename) { - if (filename == NULL) { - return false; - } - uint32_t len = strlen(filename); - return len > 0 && len < SPIFFS_OBJ_NAME_LEN; -} -*/ + static void copy_in_spiffs(const char *src, const char *dst) { - uint32_t size = size_in_spiffs(src); - uint8_t *mem = BigBuf_calloc(size); - read_from_spiffs(src, (uint8_t *)mem, size); - write_to_spiffs(dst, (uint8_t *)mem, size); + + spiffs_close_cached(); + + // no BigBuf_calloc(filesize) here: a file can be bigger than BigBuf. Copy it + // in SPIFFS_WRITE_CHUNK_SIZE chunks instead, which is also what + // rdv40_spiffs_write() writes in + uint8_t *mem = BigBuf_calloc(SPIFFS_WRITE_CHUNK_SIZE); + if (mem == NULL) { + Dbprintf("error, cannot allocate copy buffer"); + return; + } + + spiffs_file fd = SPIFFS_open(&fs, src, SPIFFS_RDONLY, 0); + if (fd < 0) { + Dbprintf("errno %i\n", SPIFFS_errno(&fs)); + return; + } + + bool first = true; + while (true) { + + s32_t len = SPIFFS_read(&fs, fd, mem, SPIFFS_WRITE_CHUNK_SIZE); + if (len < 0) { + Dbprintf("errno %i\n", SPIFFS_errno(&fs)); + break; + } + + if (len == 0) { + break; + } + + // the first chunk creates / truncates the destination, the rest append to it + if (first) { + write_to_spiffs(dst, mem, (uint32_t)len); + first = false; + } else { + append_to_spiffs(dst, mem, (uint32_t)len); + } + } + + SPIFFS_close(&fs, fd); } //////////////////////////////////////////////////////////////////////////////// @@ -525,7 +696,7 @@ int rdv40_spiffs_is_symlink(const char *s) { return ret; } -// since FILENAME can't be longer than 32Bytes as of hard configuration, we're +// since FILENAME can't be longer than 32 Bytes as of hard configuration, we're // safe with Such maximum. So the "size" variable is actually the known/intended // size of DESTINATION file, may it be known (may we provide a "stat from // symlink ?") @@ -535,7 +706,7 @@ int rdv40_spiffs_read_as_symlink(const char *filename, uint8_t *dst, uint32_t si RDV40_SPIFFS_SAFE_FUNCTION( char linkdest[SPIFFS_OBJ_NAME_LEN]; - char linkfilename[SPIFFS_OBJ_NAME_LEN]; + char linkfilename[SPIFFS_OBJ_NAME_LEN + 4]; sprintf(linkfilename, "%s.lnk", filename); if (g_dbglevel >= DBG_DEBUG) @@ -564,7 +735,7 @@ int rdv40_spiffs_read_as_symlink(const char *filename, uint8_t *dst, uint32_t si // TODO : FORBID creating a symlink with a basename (before.lnk) which already exists as a file ! int rdv40_spiffs_make_symlink(const char *linkdest, const char *filename, RDV40SpiFFSSafetyLevel level) { RDV40_SPIFFS_SAFE_FUNCTION( - char linkfilename[SPIFFS_OBJ_NAME_LEN]; + char linkfilename[SPIFFS_OBJ_NAME_LEN + 4]; sprintf(linkfilename, "%s.lnk", filename); write_to_spiffs(linkfilename, (const uint8_t *)linkdest, SPIFFS_OBJ_NAME_LEN); ) @@ -600,6 +771,117 @@ int rdv40_spiffs_read_as_filetype(const char *filename, uint8_t *dst, uint32_t s ) } +// Resolve a filename to the real file it names, following a .lnk symlink the same +// way rdv40_spiffs_read_as_filetype() does. Expects the filesystem to be mounted. +static int resolve_in_spiffs(const char *filename, char *dst, uint16_t dstlen) { + + switch (filetype_in_spiffs(filename)) { + case RDV40_SPIFFS_FILETYPE_REAL: { + strncpy(dst, filename, dstlen - 1); + dst[dstlen - 1] = 0; + return PM3_SUCCESS; + } + case RDV40_SPIFFS_FILETYPE_SYMLINK: { + char linkfilename[SPIFFS_OBJ_NAME_LEN + 4]; + sprintf(linkfilename, "%s.lnk", filename); + read_from_spiffs(linkfilename, (uint8_t *)dst, MIN(dstlen, (uint16_t)SPIFFS_OBJ_NAME_LEN)); + dst[dstlen - 1] = 0; + return PM3_SUCCESS; + } + case RDV40_SPIFFS_FILETYPE_BOTH: + case RDV40_SPIFFS_FILETYPE_UNKNOWN: + default: { + break; + } + } + return PM3_EFILE; +} + +// Read a file out in chunks, handing each one to `cb` as it arrives. +// Expects the filesystem to be mounted. Returns bytes streamed, or a negative PM3_E* +static int stream_from_spiffs(const char *filename, uint32_t offset, uint32_t size, uint8_t *chunkbuf, uint16_t chunklen, spiffs_chunk_cb_t cb) { + + spiffs_close_cached(); + + char target[SPIFFS_OBJ_NAME_LEN] = {0}; + int res = resolve_in_spiffs(filename, target, sizeof(target)); + if (res != PM3_SUCCESS) { + return res; + } + + spiffs_file fd = SPIFFS_open(&fs, target, SPIFFS_RDONLY, 0); + if (fd < 0) { + Dbprintf("errno %i\n", SPIFFS_errno(&fs)); + return PM3_EFILE; + } + + if (offset && (SPIFFS_lseek(&fs, fd, offset, SPIFFS_SEEK_SET) < 0)) { + Dbprintf("errno %i\n", SPIFFS_errno(&fs)); + SPIFFS_close(&fs, fd); + return PM3_EFILE; + } + + res = PM3_SUCCESS; + uint32_t sent = 0; + + while (sent < size) { + + // SPIFFS_read clamps to the end of the file and returns 0 once there + s32_t len = SPIFFS_read(&fs, fd, chunkbuf, MIN(size - sent, (uint32_t)chunklen)); + if (len < 0) { + Dbprintf("errno %i\n", SPIFFS_errno(&fs)); + res = PM3_EFILE; + break; + } + + if (len == 0) { + break; + } + + // offsets are relative to the start of the transfer, not to the file + res = cb(sent, chunkbuf, (uint16_t)len); + if (res != PM3_SUCCESS) { + break; + } + + sent += (uint32_t)len; + } + + SPIFFS_close(&fs, fd); + return (res == PM3_SUCCESS) ? (int)sent : res; +} + +// Stream `size` bytes from `offset` of a file, one `chunklen` chunk at a time. +// +// The download path used to read the whole file into BigBuf first. That caps a +// download at what BigBuf holds, and back when BigBuf_calloc() took a uint16_t +// the request wrapped for files >= 64KB: a short buffer, then a full size read +// run straight past the end of it. Here the file is opened once and only one +// chunk is ever buffered, so file size no longer enters into it. +// +// Returns the number of bytes streamed, or a negative PM3_E* on failure. +// +// Not RDV40_SPIFFS_SAFE_FUNCTION() : that macro returns the mount-change flag, +// and the caller needs to know how much of the file actually went out. +int rdv40_spiffs_read_stream(const char *filename, uint32_t offset, uint32_t size, uint8_t *chunkbuf, uint16_t chunklen, spiffs_chunk_cb_t cb, RDV40SpiFFSSafetyLevel level) { + + if ((filename == NULL) || (chunkbuf == NULL) || (chunklen == 0) || (cb == NULL)) { + return PM3_EINVARG; + } + + int changed = 0; + if ((level == RDV40_SPIFFS_SAFETY_LAZY) || (level == RDV40_SPIFFS_SAFETY_SAFE)) { + changed = rdv40_spiffs_lazy_mount(); + } + + int res = stream_from_spiffs(filename, offset, size, chunkbuf, chunklen, cb); + + if (level == RDV40_SPIFFS_SAFETY_SAFE) { + rdv40_spiffs_lazy_mount_rollback(changed); + } + return res; +} + // TODO regarding reads/write and symlinks : // Provide a higher level readFile function which // - don't need a size to be provided, getting it from STAT call and using bigbuff malloc @@ -644,8 +926,17 @@ void rdv40_spiffs_safe_print_tree(void) { struct spiffs_dirent e; struct spiffs_dirent *pe = &e; + spiffs_close_cached(); + char *resolvedlink = (char *)BigBuf_calloc(11 + SPIFFS_OBJ_NAME_LEN); char *linkdest = (char *)BigBuf_calloc(SPIFFS_OBJ_NAME_LEN); + if (resolvedlink == NULL || linkdest == NULL) { + DbpString("Failed to allocate memory"); + rdv40_spiffs_lazy_mount_rollback(changed); + BigBuf_free(); + return; + } + bool printed = false; SPIFFS_opendir(&fs, "/", &d); @@ -677,6 +968,8 @@ void rdv40_spiffs_safe_print_tree(void) { void rdv40_spiffs_safe_wipe(void) { + spiffs_close_cached(); + int changed = rdv40_spiffs_lazy_mount(); spiffs_DIR d; diff --git a/armsrc/spiffs.h b/armsrc/spiffs.h index e0b5868da..9a5a1bee1 100644 --- a/armsrc/spiffs.h +++ b/armsrc/spiffs.h @@ -48,6 +48,11 @@ typedef struct rdv40_spiffs_fsinfo { int rdv40_spiffs_read_as_filetype(const char *filename, uint8_t *dst, uint32_t size, RDV40SpiFFSSafetyLevel level); +// one call per chunk read by rdv40_spiffs_read_stream(), `offset` is relative to +// the start of the transfer. Return PM3_SUCCESS to carry on, anything else stops +typedef int (*spiffs_chunk_cb_t)(uint32_t offset, const uint8_t *data, uint16_t len); +int rdv40_spiffs_read_stream(const char *filename, uint32_t offset, uint32_t size, uint8_t *chunkbuf, uint16_t chunklen, spiffs_chunk_cb_t cb, RDV40SpiFFSSafetyLevel level); + int rdv40_spiffs_check(void); int rdv40_spiffs_lazy_unmount(void); int rdv40_spiffs_lazy_mount(void); @@ -58,6 +63,9 @@ int rdv40_spiffs_rename(const char *old_filename, const char *new_filename, RDV4 int rdv40_spiffs_remove(const char *filename, RDV40SpiFFSSafetyLevel level); int rdv40_spiffs_read_as_symlink(const char *filename, uint8_t *dst, uint32_t size, RDV40SpiFFSSafetyLevel level); void write_to_spiffs(const char *filename, const uint8_t *src, uint32_t size); + +// SPIFFS_OK, or the SPIFFS errno of the last write_to_spiffs()/append_to_spiffs() +int rdv40_spiffs_write_status(void); void read_from_spiffs(const char *filename, uint8_t *dst, uint32_t size); void test_spiffs(void); void rdv40_spiffs_safe_print_tree(void); diff --git a/armsrc/string.c b/armsrc/string.c index b7e549ff1..6831875a8 100644 --- a/armsrc/string.c +++ b/armsrc/string.c @@ -17,13 +17,65 @@ //----------------------------------------------------------------------------- #include "string.h" +// The word view of the buffers has to be declared as aliasing, the tree builds +// with -fstrict-aliasing. +typedef uint32_t __attribute__((may_alias)) aliasing_u32; + void *memcpy(void *dest, const void *src, int len) { uint8_t *d = dest; const uint8_t *s = src; - while ((len--) > 0) { - *d = *s; - d++; - s++; + + if (len <= 0) { + return dest; + } + + // ARM7TDMI cannot do misaligned word access, so words are only usable when + // both sides sit at the same offset within a word + if ((((uintptr_t)d ^ (uintptr_t)s) & 3) == 0) { + + while ((((uintptr_t)d & 3) != 0) && (len > 0)) { + *d++ = *s++; + len--; + } + + aliasing_u32 *dw = (aliasing_u32 *)d; + const aliasing_u32 *sw = (const aliasing_u32 *)s; + + while (len >= 16) { + dw[0] = sw[0]; + dw[1] = sw[1]; + dw[2] = sw[2]; + dw[3] = sw[3]; + dw += 4; + sw += 4; + len -= 16; + } + + while (len >= 4) { + *dw++ = *sw++; + len -= 4; + } + + d = (uint8_t *)dw; + s = (const uint8_t *)sw; + } + + // Byte tail, and the whole copy when the two sides are misaligned against + // each other. Unrolled because at -Os the compiler keeps a counter and + // indexes off it, so loop overhead otherwise costs more than the copy. + while (len >= 4) { + d[0] = s[0]; + d[1] = s[1]; + d[2] = s[2]; + d[3] = s[3]; + d += 4; + s += 4; + len -= 4; + } + + while (len > 0) { + *d++ = *s++; + len--; } return dest; } @@ -44,11 +96,51 @@ void *memmove(void *dest, const void *src, size_t len) { } void *memset(void *dest, uint8_t c, int len) { + uint8_t *d = dest; - while ((len--) > 0) { - *d = c; - d++; + + if (len <= 0) { + return dest; } + + // Same treatment memcpy got, and simpler: with no source buffer there is no + // alignment to match, so a word fill is always available once the + // destination is aligned. ARM7TDMI cannot do a misaligned word access. + while ((((uintptr_t)d & 3) != 0) && (len > 0)) { + *d++ = c; + len--; + } + + uint32_t w = c; + w |= w << 8; + w |= w << 16; + + aliasing_u32 *dw = (aliasing_u32 *)d; + + // unrolled four ways, because at -Os the loop bookkeeping otherwise costs + // more than the stores + while (len >= 16) { + dw[0] = w; + dw[1] = w; + dw[2] = w; + dw[3] = w; + dw += 4; + len -= 16; + } + + while (len >= 4) { + *dw++ = w; + len -= 4; + } + + d = (uint8_t *)dw; + + // at most three bytes are left + while (len > 0) { + *d++ = c; + len--; + } + return dest; } diff --git a/armsrc/thinfilm.c b/armsrc/thinfilm.c index 96d8ef07d..34131fd6d 100644 --- a/armsrc/thinfilm.c +++ b/armsrc/thinfilm.c @@ -46,6 +46,13 @@ void ReadThinFilm(void) { uint8_t len = 0; uint8_t *buf = BigBuf_calloc(36); + if (buf == NULL) { + if (g_dbglevel >= DBG_ERROR) DbpString("Failed to allocate memory"); + reply_ng(CMD_HF_THINFILM_READ, PM3_EMALLOC, NULL, 0); + hf_field_off(); + set_tracing(false); + return; + } // power on and listen for answer. bool status = GetIso14443aAnswerFromTag_Thinfilm(buf, 36, &len); @@ -56,12 +63,184 @@ void ReadThinFilm(void) { BigBuf_free(); } +//----------------------------------------------------------------------------- +// Passively record the frames a Kovio / Thinfilm tag beams at a reader. +// Kovio is tag-talks-first and the reader never sends a command, so only the tag +// side is decoded. Use `hf 14a sniff` to watch a reader's poll loop. +//----------------------------------------------------------------------------- +int SniffThinFilm(void) { + + LEDsoff(); + + iso14443a_setup(FPGA_HF_ISO14443A_SNIFFER); + + BigBuf_free(); + BigBuf_Clear_ext(false); + clear_trace(); + set_tracing(true); + + // The frames (tag -> reader) that we are receiving. + uint8_t *resp = BigBuf_calloc(MAX_FRAME_SIZE); + uint8_t *resp_par = BigBuf_calloc(MAX_PARITY_SIZE); + + if (resp == NULL || resp_par == NULL) { + if (g_dbglevel >= DBG_ERROR) { + DbpString("Sniff thinfilm: failed to allocate buffers"); + } + BigBuf_free(); + return PM3_EMALLOC; + } + + Demod14aInit(resp, MAX_FRAME_SIZE, resp_par); + + if (g_dbglevel >= DBG_INFO) { + DbpString("Press " _GREEN_("pm3 button") " to abort sniffing"); + } + + // The DMA buffer, used to stream samples from the FPGA + dmabuf8_t *dma = get_dma8(); + uint8_t *data = dma->buf; + + if (FpgaSetupSscRxDmaRepeat((uint8_t *)dma->buf, DMA_BUFFER_SIZE) == false) { + if (g_dbglevel > DBG_ERROR) { + Dbprintf("FpgaSetupSscRxDmaRepeat failed. Exiting"); + } + BigBuf_free(); + return PM3_EIO; + } + + tDemod14a *demod = GetDemod14a(); + + uint8_t previous_data = 0; + uint32_t rx_samples = 0; + uint32_t overrun_skips = 0; + uint32_t dma_stalls = 0; + uint32_t frames = 0; + uint16_t checker = 12000; + int dataLen; + + // loop and listen + while (BUTTON_PRESS() == false) { + + WDT_HIT(); + LED_A_ON(); + + if (checker-- == 0) { + if (data_available()) { + break; + } + checker = 12000; + } + + register int readBufDataP = data - dma->buf; + register int dmaBufDataP = DMA_BUFFER_SIZE - FPGA_SSC_DMA_RX_Remaining_Count(); + if (readBufDataP <= dmaBufDataP) { + dataLen = dmaBufDataP - readBufDataP; + } else { + dataLen = DMA_BUFFER_SIZE - readBufDataP + dmaBufDataP; + } + + // DMA fully stalled: both buffers exhausted. Re-arm primary + secondary, + // resync the read pointer, and drop the in-flight frame. + if (FPGA_SSC_DMA_RX_Primary_Done()) { + FPGA_SSC_DMA_RX_Refresh_Both(dma->buf, DMA_BUFFER_SIZE); + data = dma->buf; + rx_samples += DMA_BUFFER_SIZE; + Demod14aReset(); + dma_stalls++; + continue; + } + + // Fell behind the DMA write pointer; skip to catch up rather than abort. + if (dataLen > (9 * DMA_BUFFER_SIZE / 10)) { + data = dma->buf + dmaBufDataP; + if (data == dma->buf + DMA_BUFFER_SIZE) { + data = dma->buf; + } + rx_samples += dataLen; + Demod14aReset(); + overrun_skips++; + continue; + } + + // The MCU is processing data fast enough that the DMA has not yet received any new data. + if (dataLen < 1) { + continue; + } + + // secondary buffer exhausted, primary still running - refill secondary + if (FPGA_SSC_DMA_RX_Secondary_Done()) { + FPGA_SSC_DMA_RX_Refresh_Secondary(dma->buf, DMA_BUFFER_SIZE); + } + + LED_A_OFF(); + + // Need two samples to feed the Manchester decoder + if (rx_samples & 0x01) { + + uint8_t tagdata = (previous_data << 4) | (*data & 0x0F); + + if (ManchesterDecoding_Thinfilm(tagdata, (rx_samples - 1) * 4)) { + + LED_B_ON(); + frames++; + + if (LogTrace(resp, + demod->len, + demod->startTime * 16 - DELAY_TAG_AIR2ARM_AS_SNIFFER, + demod->endTime * 16 - DELAY_TAG_AIR2ARM_AS_SNIFFER, + NULL, + false) == false) { + break; + } + + // ready to receive another frame + Demod14aReset(); + LED_B_OFF(); + } + } + + previous_data = *data; + rx_samples++; + data++; + if (data == dma->buf + DMA_BUFFER_SIZE) { + data = dma->buf; + } + } // end main loop + + FpgaDisableTracing(); + + if (g_dbglevel >= DBG_ERROR) { + Dbprintf("Thinfilm sniff, " _YELLOW_("%u") " frames | trace len " _YELLOW_("%d"), + frames, + BigBuf_get_traceLen() + ); + if (overrun_skips || dma_stalls) { + Dbprintf(_RED_("[!] sniffer dropped frames") " | overrun recoveries " _YELLOW_("%u") " | DMA stalls " _YELLOW_("%u"), + overrun_skips, dma_stalls); + } + } + + switch_off(); + set_tracing(false); + return PM3_SUCCESS; +} + #define SEC_D 0xf0 #define SEC_E 0x0f #define SEC_F 0x00 -static uint16_t ReadReaderField(void) { - return AdcRssiAvg(ADC_RSSI_CH_HF); +// A genuine Kovio tag repeats its frame every 65536 carrier periods - measured off +// `hf thinfilm sniff`, 2**16 because it clocks a 16 bit counter off the carrier. +// ssp_clk is carrier / 16, so hold 4096 ssp ticks from one frame start to the next. +#define THINFILM_FRAME_PERIOD_SSP 4096 + +// A 32 sample average costs about 3.8 ms, since every sample pays a 42.7 us ADC +// startup and a 40 us sample & hold. That is fine once, for the baseline, but in +// the send loop it costs more than the deliberate inter frame delay and nearly +// doubles the frame repeat period. Poll with far fewer samples. +static uint16_t ReadReaderField(uint8_t samples) { + return AdcRssiSum(ADC_RSSI_CH_HF, samples) / samples; } static void CodeThinfilmAsTag(const uint8_t *cmd, uint16_t len) { @@ -102,6 +281,7 @@ static int EmSendCmdThinfilmRaw(const uint8_t *resp, uint16_t respLen) { while ((ThisTransferTime = GetCountSspClk()) & 0x00000007); // Clear TXRDY: + while (!FPGA_SSC_TX_Ready()) {} FPGA_SSC_TX_Value(SEC_F); uint16_t FpgaSendQueueDelay = 0; @@ -148,13 +328,16 @@ void SimulateThinFilm(uint8_t *data, size_t len) { // allocate command receive buffer BigBuf_free(); + clear_trace(); + set_tracing(true); + Dbprintf("Simulate " _YELLOW_("%i-bit Thinfilm") " tag", len * 8); // connect Demodulated Signal to ADC: SetAdcMuxFor(ADC_MUXSEL_HIPKD); // Set up the synchronous serial port - FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER); + FpgaSetupSsc(FPGA_MAJOR_MODE_HF_ISO14443A); FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_MOD); @@ -163,17 +346,24 @@ void SimulateThinFilm(uint8_t *data, size_t len) { // Start the timer StartCountSspClk(); - uint16_t hf_baseline = ReadReaderField(); + uint16_t hf_baseline = ReadReaderField(32); + uint16_t hf_peak = hf_baseline; + uint32_t sends = 0; + + // let the first frame go out without waiting + uint32_t frame_start = GetCountSspClk() - THINFILM_FRAME_PERIOD_SSP; int8_t status = PM3_SUCCESS; CodeThinfilmAsTag(data, len); tosend_t *ts = get_tosend(); - for (int i = 0; i < ts->max; i += 16) { - Dbhexdump(16, ts->buf + i, false); + if (g_dbglevel >= DBG_DEBUG) { + for (int i = 0; i < ts->max; i += 16) { + Dbhexdump(MIN(16, ts->max - i), ts->buf + i, false); + } + DbpString("------------------------------------------"); } - DbpString("------------------------------------------"); LED_A_ON(); @@ -187,7 +377,7 @@ void SimulateThinFilm(uint8_t *data, size_t len) { break; } - uint16_t hf_av = ReadReaderField(); + uint16_t hf_av = ReadReaderField(4); /* TODO DXL: Do not use the ADC value directly, which will result in cross platform failure. if (hf_av < hf_baseline) { @@ -208,20 +398,43 @@ void SimulateThinFilm(uint8_t *data, size_t len) { if (hf_av < hf_baseline) { hf_baseline = hf_av; } else if (hf_av > hf_baseline) { + if (hf_av > hf_peak) { + hf_peak = hf_av; + } if (AdcRssiDataToMilliVolt(hf_av - hf_baseline, ADC_RSSI_CH_HF) > 1375) { - EmSendCmdThinfilmRaw(ts->buf, ts->max); - if (len == 16) { - // wait 3.6ms - SpinDelayUs(3600); - } else { - // wait 2.4ms - SpinDelayUs(2400); + + // hold the tag's repeat rate. Waiting on the frame start rather than + // delaying a fixed amount takes the field poll above out of the gap + // instead of adding it on top. + while ((GetCountSspClk() - frame_start) < THINFILM_FRAME_PERIOD_SSP) { + WDT_HIT(); + if (BUTTON_PRESS()) { + break; + } } + + frame_start = GetCountSspClk(); + EmSendCmdThinfilmRaw(ts->buf, ts->max); + sends++; + + // one tosend byte == one 106 kbit/s bit == 8 ssp clk ticks + LogTrace(data, len, frame_start * 16, (frame_start + (ts->max * 8)) * 16, NULL, false); } } } LED_A_OFF(); + + if (g_dbglevel >= DBG_INFO) { + Dbprintf("Thinfilm sim, sent " _YELLOW_("%u") " frames | field baseline %u, peak %u ( delta %u mV )", + sends, + hf_baseline, + hf_peak, + AdcRssiDataToMilliVolt(hf_peak - hf_baseline, ADC_RSSI_CH_HF) + ); + } + + set_tracing(false); reply_ng(CMD_HF_THINFILM_SIMULATE, status, NULL, 0); } diff --git a/armsrc/thinfilm.h b/armsrc/thinfilm.h index 7e7c5ac62..3880142a9 100644 --- a/armsrc/thinfilm.h +++ b/armsrc/thinfilm.h @@ -22,6 +22,7 @@ #include "common.h" void ReadThinFilm(void); +int SniffThinFilm(void); void SimulateThinFilm(uint8_t *data, size_t len); #endif /* __ISO14443A_H */ diff --git a/armsrc/util.c b/armsrc/util.c index 72333dd5b..cc7eb6b5e 100644 --- a/armsrc/util.c +++ b/armsrc/util.c @@ -25,6 +25,12 @@ #include "string.h" #include "usb_cdc_apis.h" #include "usart.h" +#ifdef WITH_BWM_FORWARD +#include "bwm_forward.h" +#endif +#ifdef WITH_CEP +#include "pm5_cep.h" +#endif #include "BigBuf.h" // trace_restart_timeline #ifdef WITH_SMARTCARD #include "i2c.h" // sc_log_trace_reset @@ -327,22 +333,42 @@ int BUTTON_HELD(int ms) { // This function returns false if no data is available or // the USB connection is invalid. bool data_available(void) { -#ifdef WITH_FPC_USART_HOST - return usb_poll_validate_length() || (usart_rxdata_available() > 0); + bool avail; +#if defined(WITH_BWM_FORWARD) + // The BWM (BLE / WiFi) link is the host connection on a Proxmark5, so it + // has to be polled here too or CMD_BREAK_LOOP is never seen over it. + avail = usb_poll_validate_length() || (bwm_fwd_rxdata_available() > 0); +#elif defined(WITH_FPC_USART_HOST) + avail = usb_poll_validate_length() || (usart_rxdata_available() > 0); #else - return usb_poll_validate_length(); + avail = usb_poll_validate_length(); #endif +#if defined(WITH_CEP) + // CEP is independent of BWM/FPC (both may be live at once) - a Flipper + // sending CMD_BREAK_LOOP into a running reader loop is otherwise + // invisible here, leaving the loop (and its RF field) running until an + // unrelated USB command happens to arrive. + avail = avail || cep_spi_rx_pending(); +#endif + return avail; } // This function doesn't check if the USB connection is valid. // In most of the cases, you should use data_available() unless // the timing is critical. bool data_available_fast(void) { -#ifdef WITH_FPC_USART_HOST - return usb_available_length() || (usart_rxdata_available() > 0); + bool avail; +#if defined(WITH_BWM_FORWARD) + avail = usb_available_length() || (bwm_fwd_rxdata_available() > 0); +#elif defined(WITH_FPC_USART_HOST) + avail = usb_available_length() || (usart_rxdata_available() > 0); #else - return usb_available_length(); + avail = usb_available_length(); #endif +#if defined(WITH_CEP) + avail = avail || cep_spi_rx_pending(); +#endif + return avail; } // Combined function to convert an unsigned int to an array of hex values corresponding to the last three bits of k1 diff --git a/bootrom/CMakeLists.txt b/bootrom/CMakeLists.txt index b4d50bb09..851da02b5 100644 --- a/bootrom/CMakeLists.txt +++ b/bootrom/CMakeLists.txt @@ -21,6 +21,7 @@ set(DEFAULT_VERSION_C ${CMAKE_CURRENT_LIST_DIR}/../common/default_version_pm3.c) set(VERSION_PM3_C ${CMAKE_CURRENT_BINARY_DIR}/version_pm3.c) set(INC_DIRS + ${CMAKE_CURRENT_LIST_DIR} ${CMAKE_CURRENT_LIST_DIR}/../include ${CMAKE_CURRENT_LIST_DIR}/../common ${CMAKE_CURRENT_LIST_DIR}/../common_arm/sys @@ -45,6 +46,11 @@ if (PM5) ${CMAKE_CURRENT_LIST_DIR}/../common_arm/flash_code/flash_code_hw_at32.c ) set(ASMSRC flash-reset-at32.s ram-reset-at32.s) + if ("${PLATFORM_DEFS}" MATCHES "WITH_BWM_FORWARD") + set(INC_DIRS ${INC_DIRS} ${CMAKE_CURRENT_LIST_DIR}/../armsrc) + set(THUMBSRC ${THUMBSRC} ${CMAKE_CURRENT_LIST_DIR}/bwm_boot.c + ${CMAKE_CURRENT_LIST_DIR}/../armsrc/bwm_frame.c) + endif () else () set(THUMBSRC ${THUMBSRC} ${CMAKE_CURRENT_LIST_DIR}/../common_arm/sys/sys_hw_at91.c diff --git a/bootrom/Makefile b/bootrom/Makefile index 519e14800..7aa360c3f 100644 --- a/bootrom/Makefile +++ b/bootrom/Makefile @@ -17,6 +17,18 @@ # Makefile for bootrom, see ../common_arm/Makefile.common for common settings #----------------------------------------------------------------------------- +# This Makefile might have been called directly, not via the root Makefile, so: +ifeq ($(PLTNAME),) + PLATFORM_FILE ?= ../Makefile.platform + -include $(PLATFORM_FILE) + -include ../.Makefile.options.cache + -include ../armsrc/Standalone/Makefile.hal + include ../common_arm/Makefile.hal + ifeq ($(PLATFORM_CHANGED), true) + $(error platform definitions have been changed, please "make clean" at the root of the project) + endif +endif + # Proxmark5 requires armlib. include ../armlib/Exports.mk @@ -48,6 +60,10 @@ endif # DO NOT use thumb mode in the phase 1 bootloader since that generates a section with glue code ARMSRC = THUMBSRC = bootrom.c $(SRC_SYS) $(SRC_TICKS) $(SRC_GPIO) $(SRC_USB_CDC) $(SRC_FLASH_CODE) usb_cdc_desc.c +ifneq (,$(findstring WITH_BWM_FORWARD,$(PLATFORM_DEFS))) + THUMBSRC += bwm_boot.c bwm_frame.c + APP_CFLAGS += -I../armsrc +endif ASMSRC = $(SRC_STARTUP) VERSIONSRC = version_pm3.c @@ -67,14 +83,29 @@ APP_CFLAGS += -fno-common APP_CFLAGS += $(ARMLIB_EXPORT_CFLAGS) ifneq (,$(findstring WITH_FLASH,$(PLATFORM_DEFS))) - APP_CFLAGS += -DWITH_FLASH - APP_CFLAGS += -I../common_arm + APP_CFLAGS += -DWITH_FLASH + APP_CFLAGS += -I../common_arm THUMBSRC += ticks_core.c flashmem_core.c $(SRC_FLASH_DATA) endif +ifneq (,$(findstring WITH_BWM_FORWARD,$(PLATFORM_DEFS))) + APP_CFLAGS += -DWITH_BWM_FORWARD +endif + +# PLATFORM_EXTRAS=BWM is a no-op unless Makefile.hal filled PLATFORM_DEFS. +ifneq (,$(findstring BWM,$(PLATFORM_EXTRAS))) +ifeq (,$(findstring WITH_BWM_FORWARD,$(PLATFORM_DEFS))) + $(error PLATFORM_EXTRAS=BWM did not set WITH_BWM_FORWARD. Build bootrom from the repo root (`make bootrom`) or let this Makefile include common_arm/Makefile.hal.) +endif +endif + # Do not move this inclusion before the definition of {THUMB,ASM,ARM}SRC include ../common_arm/Makefile.common +ifneq (,$(findstring WITH_BWM_FORWARD,$(PLATFORM_DEFS))) + VPATH += ../armsrc +endif + INSTALLFW = $(OBJDIR)/bootrom.elf OBJS = $(OBJDIR)/bootrom.s19 diff --git a/bootrom/bootrom.c b/bootrom/bootrom.c index 1c718cdba..814df4f7b 100644 --- a/bootrom/bootrom.c +++ b/bootrom/bootrom.c @@ -28,6 +28,9 @@ #ifdef WITH_FLASH #include "flashmem.h" #endif +#ifdef WITH_BWM_FORWARD +#include "bwm_boot.h" +#endif #define DEBUG 0 // At present, in the case of at32 with a flash size of 4m byte, a sector is 4096 bytes. @@ -52,6 +55,11 @@ flash_min_unit_data_t flash_min_unit_data; extern uint32_t _bootrom_start[], _bootrom_end[], _flash_start[], _flash_end[], __bss_start__[], __bss_end__[]; extern uint32_t _osimage_entry[], _stack_start[], _stack_end[]; +#ifdef WITH_BWM_FORWARD +static bool g_pkt_from_bwm; +static uint32_t s_fw_addr; +#endif + // Send an old frame response packet. static int reply_old(uint64_t cmd, uint64_t arg0, uint64_t arg1, uint64_t arg2, void *data, size_t len) { PacketResponseOLD txcmd; @@ -73,6 +81,11 @@ static int reply_old(uint64_t cmd, uint64_t arg0, uint64_t arg1, uint64_t arg2, } } +#ifdef WITH_BWM_FORWARD + if (g_pkt_from_bwm) { + return bwm_boot_write((uint8_t *)&txcmd, sizeof(PacketResponseOLD)); + } +#endif // Send frame and make sure all bytes are transmitted return usb_write((uint8_t *)&txcmd, sizeof(PacketResponseOLD)); } @@ -99,9 +112,11 @@ static void DbpString(char *str) { } #endif +#ifndef WITH_BWM_FORWARD static void Fatal(void) { for (;;) {}; } +#endif static void UsbPacketReceived(uint8_t *packet) { bool ack = true; @@ -122,12 +137,19 @@ static void UsbPacketReceived(uint8_t *packet) { DEVICE_INFO_FLAG_UNDERSTANDS_VERSION | DEVICE_INFO_FLAG_UNDERSTANDS_READ_MEM | DEVICE_INFO_FLAG_UNDERSTANDS_CHIP_TYPE; +#ifdef WITH_BWM_FORWARD + arg0 |= DEVICE_INFO_FLAG_UNDERSTANDS_BWM_STREAM; +#endif if (g_common_area.flags.osimage_present) { arg0 |= DEVICE_INFO_FLAG_OSIMAGE_PRESENT; } +#ifdef WITH_BWM_FORWARD + reply_old(CMD_DEVICE_INFO, arg0, 1, bwm_boot_baud(), 0, 0); +#else reply_old(CMD_DEVICE_INFO, arg0, 1, 2, 0, 0); +#endif } break; @@ -240,13 +262,40 @@ static void UsbPacketReceived(uint8_t *packet) { // than one erase/write unit (e.g. AT91 pages of 256 bytes), so always copy it in and flush // the whole units below instead of assuming the payload is no larger than one unit. bool copy_overflow = false; - for (int i = 0; i < usb_payload_u32_len; i++) { - // Check data buffer is no overflow. - if (flash_min_unit_data.count >= ARRAYLEN(flash_min_unit_data.data)) { - copy_overflow = true; +#ifdef WITH_BWM_FORWARD + if (g_pkt_from_bwm) { + // arg[2] is the byte offset in the unit. Place, don't append. + uint32_t off = (uint32_t)c->arg[2]; + uint32_t idx = off / sizeof(uint32_t); + if ((off % sizeof(c->d)) || + ((idx + usb_payload_u32_len) > ARRAYLEN(flash_min_unit_data.data))) { + ack = false; + flash_min_unit_data.count = 0; + reply_old(CMD_NACK, 0, PM3_EINVARG, 0, 0, 0); break; } - flash_min_unit_data.data[flash_min_unit_data.count++] = c->d.asDwords[i]; + if (flash_min_unit_data.count && (s_fw_addr != arg0)) { + flash_min_unit_data.count = 0; + } + s_fw_addr = arg0; + for (int i = 0; i < usb_payload_u32_len; i++) { + flash_min_unit_data.data[idx + i] = c->d.asDwords[i]; + } + uint32_t end = idx + usb_payload_u32_len; + if (end > flash_min_unit_data.count) { + flash_min_unit_data.count = end; + } + } else +#endif + { + for (int i = 0; i < usb_payload_u32_len; i++) { + // Check data buffer is no overflow. + if (flash_min_unit_data.count >= ARRAYLEN(flash_min_unit_data.data)) { + copy_overflow = true; + break; + } + flash_min_unit_data.data[flash_min_unit_data.count++] = c->d.asDwords[i]; + } } if (copy_overflow) { ack = false; @@ -269,6 +318,9 @@ static void UsbPacketReceived(uint8_t *packet) { // Call the cross-platform flash api to write firmware to flash. uint32_t status = 0x00; bool isok = FlashCodeEWriteMinUnit(flash_address, flash_min_unit_addr, _flash_start, &status); +#ifdef WITH_BWM_FORWARD + bwm_boot_pump(); +#endif if (!isok) { ack = false; reply_old(CMD_NACK, status, 0, 0, 0, 0); @@ -320,7 +372,11 @@ static void UsbPacketReceived(uint8_t *packet) { break; default: { +#ifdef WITH_BWM_FORWARD + ack = false; +#else Fatal(); +#endif } break; } @@ -355,22 +411,50 @@ static void flash_mode(void) { // wait for reset to be complete? SpinDelayUs(300 * 1000); // Wait for 300ms +#ifdef WITH_BWM_FORWARD + bwm_boot_init(); +#endif + for (;;) { WDT_HIT(); +#ifdef WITH_BWM_FORWARD + // Before the USB poll, not only after it: UART4 holds a single byte. + bwm_boot_pump(); +#endif + // Check if there is a usb packet available if (usb_poll_validate_length()) { if (usb_read(rx, sizeof(rx))) { +#ifdef WITH_BWM_FORWARD + g_pkt_from_bwm = false; +#endif UsbPacketReceived(rx); } } +#ifdef WITH_BWM_FORWARD + while (bwm_boot_poll(rx, sizeof(rx))) { + g_pkt_from_bwm = true; + UsbPacketReceived(rx); + } +#endif + bool button_state = BUTTON_PRESS(); +#ifdef WITH_BWM_FORWARD + // UART4 holds one byte and has no DMA. A 10 ms sleep on every loop + // would shred an inbound DATA_FORWARD, so only debounce on a press. + if (button_state) { + SpinDelayUs(10000); + button_state = BUTTON_PRESS(); + } +#else SpinDelayUs(10000); // ~10ms, prevent jitter if (button_state != BUTTON_PRESS()) { // in jitter state, ignore continue; } +#endif if (g_common_area.flags.button_pressed && button_state == false) { g_common_area.flags.button_pressed = 0; } @@ -421,7 +505,7 @@ static bool check_goto_flash_mode(void) { if (g_common_area.flags.button_pressed == 0 && BUTTON_PRESS()) { to_flash_mode = true; - + if (BOOTROM_BUTTON_HOLD_MS > 0) { for (int16_t ms = 0; ms < BOOTROM_BUTTON_HOLD_MS; ms++) { if (BUTTON_PRESS() == false) { diff --git a/bootrom/bwm_boot.c b/bootrom/bwm_boot.c new file mode 100644 index 000000000..25f60ccf5 --- /dev/null +++ b/bootrom/bwm_boot.c @@ -0,0 +1,259 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// Polled UART4 + app_com unwrap. No DMA, no RX FIFO: one byte in the receive +// register. Pump within one byte time (~10.8 us at 921600) or it is lost. +//----------------------------------------------------------------------------- + +#ifndef WITH_BWM_FORWARD +#error "bwm_boot.c requires WITH_BWM_FORWARD" +#endif + +#include "bwm_boot.h" + +#include "bwm_frame.h" +#include "commonutil.h" +#include "pm3_cmd.h" +#include "ticks_apis.h" +#include "at32f435_437.h" +#include "at32f435_437_crm.h" +#include "at32f435_437_gpio.h" +#include "at32f435_437_usart.h" + +extern uint32_t start_addr, end_addr; + +#define BWM_UART UART4 +#define BWM_UART_GPIO GPIOA +#define BWM_UART_TX_PIN GPIO_PINS_0 +#define BWM_UART_RX_PIN GPIO_PINS_1 +#define BWM_UART_TX_SRC GPIO_PINS_SOURCE0 +#define BWM_UART_RX_SRC GPIO_PINS_SOURCE1 +#define BWM_UART_MUX GPIO_MUX_8 + +// ESP UART baud is not persistent. Probe both; 921600 is the OS target. +static const uint32_t s_baud_candidates[] = { 921600u, 460800u }; + +#define BWM_PROBE_ROUNDS 3 + +// SpinDelayUs() uses SysTick. Do not bound these waits with GetTicks()/TMR5: +// that timer is otherwise unused here, and a dead counter would hang without +// WDT_HIT(). 1 us stays inside one byte time. +#define BWM_SPIN_US 1u +#define BWM_PROBE_WAIT_US 30000u +#define BWM_ACK_WAIT_US 50000u + +// Idle flush only: StartTicks() runs TMR5 at 1.5 MHz. If it never advances, +// the delta stays 0 and the flush does not fire. +#define BWM_TICKS_PER_MS 1500u +#define BWM_STAGE_IDLE_MS 1000u + +static uint8_t s_cmd[sizeof(PacketCommandOLD)]; +static uint16_t s_got; +static uint32_t s_stage_tick; +static uint32_t s_baud; + +static bool bwm_old_cmd_ok(const uint8_t *p) { + const PacketCommandOLD *c = (const PacketCommandOLD *)p; + uint32_t cmd = (uint32_t)c->cmd; + uint32_t a0 = (uint32_t)c->arg[0]; + if (c->cmd != cmd) { + return false; + } + switch (cmd) { + case CMD_DEVICE_INFO: + case CMD_HARDWARE_RESET: + case CMD_START_FLASH: + case CMD_CHIP_INFO: + case CMD_BL_VERSION: + case CMD_CHIP_TYPE: + case CMD_READ_MEM_DOWNLOAD: + return true; + case CMD_FINISH_WRITE: + return (start_addr != end_addr) && + (a0 >= start_addr) && + (a0 < end_addr); + default: + return false; + } +} + +static void uart_set_baud(uint32_t baud) { + crm_periph_clock_enable(CRM_GPIOA_PERIPH_CLOCK, TRUE); + crm_periph_clock_enable(CRM_UART4_PERIPH_CLOCK, TRUE); + + gpio_init_type gpio_init_struct; + gpio_default_para_init(&gpio_init_struct); + gpio_init_struct.gpio_mode = GPIO_MODE_MUX; + gpio_init_struct.gpio_out_type = GPIO_OUTPUT_PUSH_PULL; + gpio_init_struct.gpio_pull = GPIO_PULL_NONE; + gpio_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER; + gpio_init_struct.gpio_pins = BWM_UART_TX_PIN | BWM_UART_RX_PIN; + gpio_init(BWM_UART_GPIO, &gpio_init_struct); + gpio_pin_mux_config(BWM_UART_GPIO, BWM_UART_TX_SRC, BWM_UART_MUX); + gpio_pin_mux_config(BWM_UART_GPIO, BWM_UART_RX_SRC, BWM_UART_MUX); + + usart_enable(BWM_UART, FALSE); + usart_init(BWM_UART, baud, USART_DATA_8BITS, USART_STOP_1_BIT); + usart_parity_selection_config(BWM_UART, USART_PARITY_NONE); + usart_transmitter_enable(BWM_UART, TRUE); + usart_receiver_enable(BWM_UART, TRUE); + usart_enable(BWM_UART, TRUE); +} + +static int uart_getc(uint8_t *b) { + if (usart_flag_get(BWM_UART, USART_ROERR_FLAG) != RESET) { + (void)usart_data_receive(BWM_UART); + usart_flag_clear(BWM_UART, USART_ROERR_FLAG); + return 0; + } + if (usart_flag_get(BWM_UART, USART_RDBF_FLAG) == RESET) { + return 0; + } + *b = (uint8_t)usart_data_receive(BWM_UART); + return 1; +} + +void bwm_boot_pump(void) { + uint8_t b; + while (uart_getc(&b)) { + bwm_frame_feed(b); + } +} + +// Pump while waiting for TX: a 552 B frame is ~6 ms of deafness otherwise. +static void uart_write(const uint8_t *d, size_t n) { + for (size_t i = 0; i < n; i++) { + while (usart_flag_get(BWM_UART, USART_TDBE_FLAG) == RESET) { + bwm_boot_pump(); + } + usart_data_transmit(BWM_UART, d[i]); + } + while (usart_flag_get(BWM_UART, USART_TDC_FLAG) == RESET) { + bwm_boot_pump(); + } +} + +static void uart_drain(void) { + uint8_t dump; + while (uart_getc(&dump)) {} +} + +static bool bwm_probe_once(void) { + uint8_t f[8]; + size_t n = bwm_frame_build(BWM_CMD_GET_UART_BAUD, NULL, 0, f, sizeof(f)); + if (n == 0) { + return false; + } + bwm_frame_reset(); + uart_write(f, n); + for (uint32_t us = 0; us < BWM_PROBE_WAIT_US; us += BWM_SPIN_US) { + bwm_boot_pump(); + if (bwm_frame_getbaud_ack()) { + bwm_frame_clear_getbaud_ack(); + return true; + } + SpinDelayUs(BWM_SPIN_US); + } + return false; +} + +void bwm_boot_init(void) { + StartTicks(); + s_got = 0; + s_stage_tick = GetTicks(); + s_baud = 0; + for (uint8_t round = 0; round < BWM_PROBE_ROUNDS; round++) { + for (uint8_t i = 0; i < ARRAYLEN(s_baud_candidates); i++) { + uart_set_baud(s_baud_candidates[i]); + uart_drain(); + if (bwm_probe_once()) { + s_baud = s_baud_candidates[i]; + bwm_frame_reset(); + return; + } + } + } + uart_set_baud(s_baud_candidates[0]); + uart_drain(); + bwm_frame_reset(); +} + +uint32_t bwm_boot_baud(void) { + return s_baud; +} + +bool bwm_boot_poll(uint8_t *out, size_t outlen) { + if (out == NULL || outlen < sizeof(s_cmd)) { + return false; + } + bwm_boot_pump(); + uint16_t slides = 0; + for (;;) { + uint16_t before = s_got; + while (s_got < sizeof(s_cmd) && bwm_fifo_count() > 0) { + s_cmd[s_got++] = bwm_fifo_pop(); + } + if (s_got != before) { + s_stage_tick = GetTicks(); + } + if (s_got < sizeof(s_cmd)) { + // Zero padding of an OLD frame looks like CMD_DEVICE_INFO. Drop a + // stalled partial rather than lock onto a bogus offset. + if (s_got && ((GetTicks() - s_stage_tick) > (BWM_STAGE_IDLE_MS * BWM_TICKS_PER_MS))) { + s_got = 0; + } + return false; + } + if (bwm_old_cmd_ok(s_cmd)) { + for (size_t i = 0; i < sizeof(s_cmd); i++) { + out[i] = s_cmd[i]; + } + s_got = 0; + return true; + } + for (size_t i = 0; i < sizeof(s_cmd) - 1; i++) { + s_cmd[i] = s_cmd[i + 1]; + } + s_got = sizeof(s_cmd) - 1; + bwm_boot_pump(); + if (++slides >= sizeof(s_cmd)) { + return false; + } + } +} + +int bwm_boot_write(const uint8_t *data, size_t len) { + if (data == NULL || len == 0 || len > 0xFFFF) { + return PM3_EINVARG; + } + uint8_t frame[8 + sizeof(PacketResponseOLD)]; + size_t n = bwm_frame_build(BWM_CMD_SEND_FORWARD_DATA, data, (uint16_t)len, + frame, sizeof(frame)); + if (n == 0) { + return PM3_EOVFLOW; + } + (void)bwm_frame_take_fwd_ack(); + uart_write(frame, n); + bwm_frame_inflight_inc(); + for (uint32_t us = 0; us < BWM_ACK_WAIT_US; us += BWM_SPIN_US) { + bwm_boot_pump(); + if (bwm_frame_take_fwd_ack()) { + return PM3_SUCCESS; + } + SpinDelayUs(BWM_SPIN_US); + } + bwm_frame_inflight_zero(); + return PM3_ETIMEOUT; +} diff --git a/bootrom/bwm_boot.h b/bootrom/bwm_boot.h new file mode 100644 index 000000000..736dd83be --- /dev/null +++ b/bootrom/bwm_boot.h @@ -0,0 +1,31 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// PM5 bootrom BWM UART: DATA_FORWARD is a byte stream of PacketCommandOLD. +//----------------------------------------------------------------------------- +#ifndef BWM_BOOT_H +#define BWM_BOOT_H + +#include "common.h" + +void bwm_boot_init(void); +void bwm_boot_pump(void); +bool bwm_boot_poll(uint8_t *out, size_t outlen); +int bwm_boot_write(const uint8_t *data, size_t len); + +// Baud the ESP answered on, or 0 if none did. +uint32_t bwm_boot_baud(void); + +#endif diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index 403f67a49..6ccb4d98a 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -381,6 +381,7 @@ set (TARGET_SOURCES ${PM3_ROOT}/client/src/mifare/gen4.c ${PM3_ROOT}/client/src/mifare/lrpcrypto.c ${PM3_ROOT}/client/src/mifare/desfirecrypto.c + ${PM3_ROOT}/client/src/mifare/desfireem.c ${PM3_ROOT}/client/src/mifare/desfiresecurechan.c ${PM3_ROOT}/client/src/mifare/desfirecore.c ${PM3_ROOT}/client/src/mifare/desfiretest.c @@ -400,6 +401,7 @@ set (TARGET_SOURCES ${PM3_ROOT}/client/src/aidsearch.c ${PM3_ROOT}/client/src/atrs.c ${PM3_ROOT}/client/src/cmdanalyse.c + ${PM3_ROOT}/client/src/cmdbwm.c ${PM3_ROOT}/client/src/cmdcrc.c ${PM3_ROOT}/client/src/cmddata.c ${PM3_ROOT}/client/src/cmdflashmem.c @@ -498,6 +500,7 @@ set (TARGET_SOURCES ${PM3_ROOT}/client/src/comms.c ${PM3_ROOT}/client/src/fileutils.c ${PM3_ROOT}/client/src/flash.c + ${PM3_ROOT}/client/src/frame_data2.c ${PM3_ROOT}/client/src/frame_progress.c ${PM3_ROOT}/client/src/graph.c ${PM3_ROOT}/client/src/hidsio.c @@ -506,6 +509,13 @@ set (TARGET_SOURCES ${PM3_ROOT}/client/src/jsonutils.c ${PM3_ROOT}/client/src/lua_bitlib.c ${PM3_ROOT}/client/src/parsers/parsehrt.c + ${PM3_ROOT}/client/src/parsers/parsehid.c + ${PM3_ROOT}/client/src/parsers/parsevigik.c + ${PM3_ROOT}/client/src/parsers/parsehexact.c + ${PM3_ROOT}/client/src/parsers/parsemykey.c + ${PM3_ROOT}/client/src/parsers/parseproac.c + ${PM3_ROOT}/client/src/parsers/parserkf.c + ${PM3_ROOT}/client/src/parsers/parsenortic.c ${PM3_ROOT}/client/src/parsers/hrtparser/hrtparser.c ${PM3_ROOT}/client/src/pla.c ${PM3_ROOT}/client/src/preferences.c @@ -513,7 +523,6 @@ set (TARGET_SOURCES ${PM3_ROOT}/client/src/pm3_binlib.c ${PM3_ROOT}/client/src/pm3_bitlib.c ${PM3_ROOT}/client/src/pm3_dsp.c - ${PM3_ROOT}/client/src/pm3_fit.c ${PM3_ROOT}/client/src/pm3line.c ${PM3_ROOT}/client/src/pm3line_vocabulary.c @@ -964,6 +973,27 @@ endif (NOT SKIPPYTHON EQUAL 1) target_link_directories(proxmark3 PRIVATE ${ADDITIONAL_LNKDIRS}) install(TARGETS proxmark3 DESTINATION "bin") + +# Grant the capabilities the BLE connect-by-name scan needs (raw HCI: CAP_NET_RAW +# + CAP_NET_ADMIN). Linux + Bluez only, and non-fatal: if setcap is absent, the +# target filesystem lacks xattr support, or this is a staged/packaged install, +# it just warns. Connect-by-address (-p ble:) never needs this. +if (BLUEZ_FOUND AND CMAKE_SYSTEM_NAME STREQUAL "Linux") + find_program(SETCAP_EXECUTABLE setcap) + if (SETCAP_EXECUTABLE) + install(CODE " + set(_pm3_bin \"\$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}/bin/proxmark3\") + execute_process( + COMMAND \"${SETCAP_EXECUTABLE}\" cap_net_raw,cap_net_admin+eip \"\${_pm3_bin}\" + RESULT_VARIABLE _pm3_setcap_rc) + if (NOT _pm3_setcap_rc EQUAL 0) + message(WARNING \"setcap failed - BLE connect-by-name (-p ble:) will need sudo; connect-by-MAC is unaffected\") + endif () + ") + else () + message(STATUS "setcap not found - BLE connect-by-name will need sudo at runtime") + endif () +endif () install(DIRECTORY cmdscripts lualibs luascripts pyscripts resources dictionaries DESTINATION "share/proxmark3") add_custom_command(OUTPUT lualibs/pm3_cmd.lua diff --git a/client/Makefile b/client/Makefile index 0cac5c1a2..d1be39d84 100644 --- a/client/Makefile +++ b/client/Makefile @@ -737,6 +737,7 @@ SRCS = mifare/aiddesfire.c \ aidsearch.c \ atrs.c \ cmdanalyse.c \ + cmdbwm.c \ cmdcrc.c \ cmddata.c \ cmdflashmem.c \ @@ -868,6 +869,7 @@ SRCS = mifare/aiddesfire.c \ emrtd/emrtd_pacetest.c \ fileutils.c \ flash.c \ + frame_data2.c \ frame_progress.c \ generator.c \ graph.c \ @@ -889,11 +891,12 @@ SRCS = mifare/aiddesfire.c \ lua_bitlib.c \ mifare/lrpcrypto.c \ mifare/desfirecrypto.c \ + mifare/desfireem.c \ mifare/desfirecore.c \ mifare/desfiresecurechan.c \ mifare/desfiretest.c \ mifare/gallaghercore.c \ - mifare/gallaghertest.c \ + mifare/gallaghertest.c \ mifare/mad.c \ mifare/mad_test.c \ mifare/mfkey.c \ @@ -904,6 +907,13 @@ SRCS = mifare/aiddesfire.c \ mifare/gen4.c \ nfc/ndef.c \ parsers/parsehrt.c \ + parsers/parsehid.c \ + parsers/parsevigik.c \ + parsers/parsehexact.c \ + parsers/parsemykey.c \ + parsers/parseproac.c \ + parsers/parserkf.c \ + parsers/parsenortic.c \ parsers/hrtparser/hrtparser.c \ pm3.c \ pm3_binlib.c \ @@ -1062,8 +1072,13 @@ endif install: all $(info [@] Installing client to $(DESTDIR)$(PREFIX)...) ifneq (,$(INSTALLBIN)) - $(Q)$(INSTALLSUDO) $(MKDIR) $(DESTDIR)$(PREFIX)$(PATHSEP)$(INSTALLBINRELPATH) - $(Q)$(INSTALLSUDO) $(CP) $(INSTALLBIN) $(DESTDIR)$(PREFIX)$(PATHSEP)$(INSTALLBINRELPATH) + $(Q)$(INSTALLSUDO) $(MKDIR) $(DESTDIR)$(PREFIX)$(PATHSEP)$(INSTALLBINRELPATH) + $(Q)$(INSTALLSUDO) $(CP) $(INSTALLBIN) $(DESTDIR)$(PREFIX)$(PATHSEP)$(INSTALLBINRELPATH) + ifeq ($(platform),Linux) + ifneq ($(SKIP_SETCAP), 1) + $(Q)$(INSTALLSUDO) setcap 'cap_net_raw,cap_net_admin+eip' $(DESTDIR)$(PREFIX)$(PATHSEP)$(INSTALLBINRELPATH)$(PATHSEP)$(INSTALLBIN) || echo "[!] setcap failed - BLE connect-by-name (-p ble:) will need sudo; connect-by-MAC is unaffected" + endif + endif endif ifneq (,$(INSTALLSHARE)) $(Q)$(INSTALLSUDO) $(MKDIR) $(DESTDIR)$(PREFIX)$(PATHSEP)$(INSTALLSHARERELPATH) diff --git a/client/deps/openjpeg/invert.c b/client/deps/openjpeg/invert.c index ea23508c6..444d22b89 100644 --- a/client/deps/openjpeg/invert.c +++ b/client/deps/openjpeg/invert.c @@ -116,7 +116,7 @@ static OPJ_BOOL opj_lupDecompose(OPJ_FLOAT32 *matrix, OPJ_UINT32 lLastColum = nb_compo - 1; OPJ_UINT32 lSwapSize = nb_compo * (OPJ_UINT32)sizeof(OPJ_FLOAT32); OPJ_FLOAT32 *lTmpMatrix = matrix; - OPJ_FLOAT32 *lColumnMatrix, * lDestMatrix; + OPJ_FLOAT32 *lColumnMatrix, *lDestMatrix; OPJ_UINT32 offset = 1; OPJ_UINT32 lStride = nb_compo - 1; diff --git a/client/deps/openjpeg/j2k.c b/client/deps/openjpeg/j2k.c index 000426a62..a14e42aca 100644 --- a/client/deps/openjpeg/j2k.c +++ b/client/deps/openjpeg/j2k.c @@ -6404,10 +6404,10 @@ static OPJ_BOOL opj_j2k_add_mct(opj_tcp_t *p_tcp, opj_image_t *p_image, OPJ_UINT32 p_index) { OPJ_UINT32 i; opj_simple_mcc_decorrelation_data_t *l_mcc_record; - opj_mct_data_t *l_deco_array, * l_offset_array; + opj_mct_data_t *l_deco_array, *l_offset_array; OPJ_UINT32 l_data_size, l_mct_size, l_offset_size; OPJ_UINT32 l_nb_elem; - OPJ_UINT32 *l_offset_data, * l_current_offset_data; + OPJ_UINT32 *l_offset_data, *l_current_offset_data; opj_tccp_t *l_tccp; /* preconditions */ @@ -8518,10 +8518,10 @@ static OPJ_BOOL opj_j2k_mct_validation(opj_j2k_t *p_j2k, OPJ_BOOL opj_j2k_setup_mct_encoding(opj_tcp_t *p_tcp, opj_image_t *p_image) { OPJ_UINT32 i; OPJ_UINT32 l_indix = 1; - opj_mct_data_t *l_mct_deco_data = 00, * l_mct_offset_data = 00; + opj_mct_data_t *l_mct_deco_data = 00, *l_mct_offset_data = 00; opj_simple_mcc_decorrelation_data_t *l_mcc_data; OPJ_UINT32 l_mct_size, l_nb_elem; - OPJ_FLOAT32 *l_data, * l_current_data; + OPJ_FLOAT32 *l_data, *l_current_data; opj_tccp_t *l_tccp; /* preconditions */ diff --git a/client/deps/openjpeg/jp2.c b/client/deps/openjpeg/jp2.c index 8e0fd6d2d..5f2614cc3 100644 --- a/client/deps/openjpeg/jp2.c +++ b/client/deps/openjpeg/jp2.c @@ -633,7 +633,7 @@ static OPJ_BOOL opj_jp2_read_ihdr(opj_jp2_t *jp2, static OPJ_BYTE *opj_jp2_write_ihdr(opj_jp2_t *jp2, OPJ_UINT32 *p_nb_bytes_written ) { - OPJ_BYTE *l_ihdr_data, * l_current_ihdr_ptr; + OPJ_BYTE *l_ihdr_data, *l_current_ihdr_ptr; /* preconditions */ assert(jp2 != 00); @@ -687,7 +687,7 @@ static OPJ_BYTE *opj_jp2_write_bpcc(opj_jp2_t *jp2, OPJ_UINT32 i; /* room for 8 bytes for box and 1 byte for each component */ OPJ_UINT32 l_bpcc_size; - OPJ_BYTE *l_bpcc_data, * l_current_bpcc_ptr; + OPJ_BYTE *l_bpcc_data, *l_current_bpcc_ptr; /* preconditions */ assert(jp2 != 00); @@ -757,7 +757,7 @@ static OPJ_BYTE *opj_jp2_write_cdef(opj_jp2_t *jp2, OPJ_UINT32 *p_nb_bytes_written) { /* room for 8 bytes for box, 2 for n */ OPJ_UINT32 l_cdef_size = 10; - OPJ_BYTE *l_cdef_data, * l_current_cdef_ptr; + OPJ_BYTE *l_cdef_data, *l_current_cdef_ptr; OPJ_UINT32 l_value; OPJ_UINT16 i; @@ -808,7 +808,7 @@ static OPJ_BYTE *opj_jp2_write_colr(opj_jp2_t *jp2, ) { /* room for 8 bytes for box 3 for common data and variable upon profile*/ OPJ_UINT32 l_colr_size = 11; - OPJ_BYTE *l_colr_data, * l_current_colr_ptr; + OPJ_BYTE *l_colr_data, *l_current_colr_ptr; /* preconditions */ assert(jp2 != 00); @@ -1740,7 +1740,7 @@ static OPJ_BOOL opj_jp2_write_ftyp(opj_jp2_t *jp2, opj_event_mgr_t *p_manager) { OPJ_UINT32 i; OPJ_UINT32 l_ftyp_size; - OPJ_BYTE *l_ftyp_data, * l_current_data_ptr; + OPJ_BYTE *l_ftyp_data, *l_current_data_ptr; OPJ_BOOL l_result; /* preconditions */ diff --git a/client/dictionaries/mfc_default_keys.dic b/client/dictionaries/mfc_default_keys.dic index 11a811a9d..d54942901 100644 --- a/client/dictionaries/mfc_default_keys.dic +++ b/client/dictionaries/mfc_default_keys.dic @@ -873,7 +873,7 @@ F7A39753D018 # Data from TransPert 2031D1E57A3B 53C11F90822A -9189449EA24E +9189449EA24E # SmartRider, Western Australia # # data from Github 410B9B40B872 @@ -1091,7 +1091,7 @@ D3A297DC2698 0F318130ED18 114D6BE9440C 18E3A02B5EFF -19FC84A3784B +19FC84A3784B # Podorozhnik, St Petersburg 1B61B2E78C75 22052B480D11 3367BFAA91DB @@ -1129,7 +1129,7 @@ C76BF71A2509 D5524F591EED E328A1C7156D E4821A377B75 -E56AC127DD45 +E56AC127DD45 # Podorozhnik, St Petersburg EA0FD73CB149 FC0001877BF7 FD8705E721B0 @@ -1321,7 +1321,7 @@ A7FB4824ACBF 10F3BEBC01DF # # Transportes Insular La Palma -0172066B2F03 +0172066B2F03 # also Bonobus, Cadiz 0000085F0000 1A80B93F7107 70172066B2F0 @@ -2874,7 +2874,7 @@ E5051FAB4371 E861FDE1B59F E87E3554727E E9B376925A00 -E954024EE754 +E954024EE754 # Kazan FA4D2B3BAFEA FA8CA10C7D59 FE98F38F3EE2 @@ -2885,7 +2885,7 @@ F654D6C7004F F697E87E759D F7A545095C49 F833E24C3F1C -0CD464CDC100 +0CD464CDC100 # Kazan 0D61BA88789C 0E726E11CFCC 0FC4B1D2EBBA diff --git a/client/dictionaries/t55xx_default_pwds.dic b/client/dictionaries/t55xx_default_pwds.dic index 206e702f7..0f5d07c53 100644 --- a/client/dictionaries/t55xx_default_pwds.dic +++ b/client/dictionaries/t55xx_default_pwds.dic @@ -169,3 +169,5 @@ F1EA5EED 93C467E3 # natural log 27182818 +# EM4305 anti-clone card (login-protected, RF/64 emitter) +A1856618 diff --git a/client/experimental_lib/CMakeLists.txt b/client/experimental_lib/CMakeLists.txt index ea54e5577..d90053bef 100644 --- a/client/experimental_lib/CMakeLists.txt +++ b/client/experimental_lib/CMakeLists.txt @@ -307,6 +307,7 @@ set (TARGET_SOURCES ${PM3_ROOT}/client/src/mifare/gen4.c ${PM3_ROOT}/client/src/mifare/lrpcrypto.c ${PM3_ROOT}/client/src/mifare/desfirecrypto.c + ${PM3_ROOT}/client/src/mifare/desfireem.c ${PM3_ROOT}/client/src/mifare/desfiresecurechan.c ${PM3_ROOT}/client/src/mifare/desfirecore.c ${PM3_ROOT}/client/src/mifare/desfiretest.c @@ -327,6 +328,7 @@ set (TARGET_SOURCES ${PM3_ROOT}/client/src/aidsearch.c ${PM3_ROOT}/client/src/atrs.c ${PM3_ROOT}/client/src/cmdanalyse.c + ${PM3_ROOT}/client/src/cmdbwm.c ${PM3_ROOT}/client/src/cmdcrc.c ${PM3_ROOT}/client/src/cmddata.c ${PM3_ROOT}/client/src/cmdflashmem.c @@ -425,6 +427,7 @@ set (TARGET_SOURCES ${PM3_ROOT}/client/src/comms.c ${PM3_ROOT}/client/src/fileutils.c ${PM3_ROOT}/client/src/flash.c + ${PM3_ROOT}/client/src/frame_data2.c ${PM3_ROOT}/client/src/frame_progress.c ${PM3_ROOT}/client/src/graph.c ${PM3_ROOT}/client/src/hidsio.c @@ -433,6 +436,13 @@ set (TARGET_SOURCES ${PM3_ROOT}/client/src/jsonutils.c ${PM3_ROOT}/client/src/lua_bitlib.c ${PM3_ROOT}/client/src/parsers/parsehrt.c + ${PM3_ROOT}/client/src/parsers/parsehid.c + ${PM3_ROOT}/client/src/parsers/parsevigik.c + ${PM3_ROOT}/client/src/parsers/parsehexact.c + ${PM3_ROOT}/client/src/parsers/parsemykey.c + ${PM3_ROOT}/client/src/parsers/parseproac.c + ${PM3_ROOT}/client/src/parsers/parserkf.c + ${PM3_ROOT}/client/src/parsers/parsenortic.c ${PM3_ROOT}/client/src/parsers/hrtparser/hrtparser.c ${PM3_ROOT}/client/src/pla.c ${PM3_ROOT}/client/src/preferences.c diff --git a/client/include/pm3.h b/client/include/pm3.h index 92e99bacd..fb60b391e 100644 --- a/client/include/pm3.h +++ b/client/include/pm3.h @@ -26,4 +26,6 @@ const char *pm3_grabbed_output_get(pm3 *dev); const char *pm3_name_get(pm3 *dev); void pm3_close(pm3 *dev); pm3 *pm3_get_current_dev(void); +int pm3_flash(const char *port, const char *const *images, int nimages, + bool unlock_bootloader, bool force); #endif // LIBPM3_H diff --git a/client/luascripts/tests/lf_t55xx_writetest.lua b/client/luascripts/tests/lf_t55xx_writetest.lua index 436846bc0..05251def2 100644 --- a/client/luascripts/tests/lf_t55xx_writetest.lua +++ b/client/luascripts/tests/lf_t55xx_writetest.lua @@ -16,7 +16,7 @@ A strict T55x7 test suite: lf t55xx wipe lf t55xx write -b 1 -d 00000000 - lf t55xx write -b 2 -d ffffffff + lf t55xx write -b 2 -d aa5500ff lf t55xx write -b 3 -d 80000000 lf t55xx write -b 4 -d 00000001 @@ -24,6 +24,14 @@ Each row names the configuration word, what it means, what `lf t55xx detect` made of it and how many of the four data blocks read back intact. Markers are also written into the session log ( `rem [ERR:...]` and `rem [SUMMARY:...]` ) +Every block is read three times. A block that reads back differently between +those is marked `unstable`, which is the fault a single read cannot see: the +value is silently wrong rather than missing. A block that is wrong the same way +each time is named where it can be - `rol1`, `ror5`, `inverted`, `shr1` - because +a rotation points at the word boundary and an inversion at psk phase, and the two +want different fixes. Block 1 is `00000000`, which is equal to all of its own +rotations, so a rotated read of it cannot be told from a correct one. + Note: that the card is wiped before each modulation. Needs a T5577 in the field. @@ -161,30 +169,98 @@ local function prepare() return true end +-- a block is read this many times, so that a value which is silently wrong on +-- only some reads is not mistaken for one that is right +local READS = 3 + +local function rol32(v, n) + n = n % 32 + if n == 0 then return v end + return ((v << n) | (v >> (32 - n))) & 0xFFFFFFFF +end + --- --- Read blocks 1-4 back. Returns how many matched and a short note naming the --- ones that did not. +-- Name how `got` differs from `want`, when it can be named. A rotation says the +-- word boundary moved, an inversion says psk picked the opposite phase, and a +-- shift says a demodulation opened a bit early and padded with zero - different +-- faults wanting different fixes, so worth telling apart. A word equal to all of +-- its own rotations carries no boundary information and only gets 'differs'. +local function classify(want, got) + + if got == want then return 'ok' end + + if rol32(want, 1) == want then return 'differs' end + + for n = 1, 31 do + if rol32(want, n) == got then + return (n <= 16) and ('rol' .. n) or ('ror' .. (32 - n)) + end + end + + if (want ~ 0xFFFFFFFF) == got then return 'inverted' end + + for n = 1, 31 do + if (rol32(want, n) ~ 0xFFFFFFFF) == got then + return 'inv+' .. ((n <= 16) and ('rol' .. n) or ('ror' .. (32 - n))) + end + end + + for n = 1, 8 do + if ((want >> n) & 0xFFFFFFFF) == got then return 'shr' .. n end + if ((want << n) & 0xFFFFFFFF) == got then return 'shl' .. n end + end + + return 'differs' +end + +--- +-- Read blocks 1-4 back, READS times each. Returns how many matched on every +-- read and a short note naming what went wrong with the ones that did not. local function read_back(config) local good, bad = 0, {} for block, want in ipairs(DATA_BLOCKS) do - local data = core.t55xx_readblock(block, '0', '0', '') - local got = data and ('%08X'):format(data) or '' + local wantv = tonumber(want, 16) + local seen, first, stable = {}, nil, true - if got:lower() == want:lower() then + for _ = 1, READS do + local data = core.t55xx_readblock(block, '0', '0', '') + local v = data and (data & 0xFFFFFFFF) or nil + table.insert(seen, v) + if first == nil then + first = v + elseif v ~= first then + stable = false + end + end + + if stable and first == wantv then good = good + 1 else - table.insert(bad, tostring(block)) - core.console(format('rem [ERR:READ:%s:%d] block %d: read %s instead of %s', - config, block, block, got, want), false, true) + local what + if stable == false then + what = 'unstable' + else + what = classify(wantv, first) + end + + table.insert(bad, format('b%d %s', block, what)) + + local reads = {} + for _, v in ipairs(seen) do + table.insert(reads, v and ('%08X'):format(v) or '----') + end + core.console(format('rem [ERR:READ:%s:%d] block %d: %s, wanted %s, read %s', + config, block, block, what, want, + table.concat(reads, ' ')), false, true) end end local note = '' if #bad > 0 then - note = 'block ' .. table.concat(bad, ',') .. ' bad' + note = table.concat(bad, ' ') end return good, note end diff --git a/client/pm5_ble_bridge.py b/client/pm5_ble_bridge.py index c110c2355..38b648034 100644 --- a/client/pm5_ble_bridge.py +++ b/client/pm5_ble_bridge.py @@ -17,8 +17,8 @@ # WSL2 without admin, NAT networking: Windows can only make OUTBOUND # connections, but by default localhostForwarding lets Windows reach a WSL # listener at 127.0.0.1:PORT. So: -# WSL: python3 pm5_ble_bridge.py --relay --listen 7777 --pty /tmp/pm5-ble -# Windows: py pm5_ble_bridge.py -n Proxmark5 --connect 127.0.0.1:7777 +# WSL: python3 pm5_ble_bridge.py --relay --listen 18888 --pty /tmp/pm5-ble +# Windows: py pm5_ble_bridge.py -n Proxmark5 --connect 127.0.0.1:18888 # WSL: ./pm3 /tmp/pm5-ble # If localhostForwarding is off, point --connect at WSL's own IP # (WSL: `hostname -I`) instead of 127.0.0.1. diff --git a/client/pyscripts/mfulaes_mask_recovery.py b/client/pyscripts/mfulaes_mask_recovery.py index 363771b6b..0bb4811c4 100755 --- a/client/pyscripts/mfulaes_mask_recovery.py +++ b/client/pyscripts/mfulaes_mask_recovery.py @@ -80,7 +80,7 @@ def bruteforce_key(p, key_segment, idx, segment, retries=5, bitflips=2): sys.stdout.flush() key = construct_key(key_segment, segment) console_debug(p, - f'hf mfu aeschk -i {idx} ' + f'hf mfu chk -i {idx} ' f'-f mfulaes_segment_hw{bitflips}.dic ' f'--segment {segment} ' f'--key {key} ' diff --git a/client/pyscripts/pm5_battery_test.py b/client/pyscripts/pm5_battery_test.py index 45e8fed8c..ac7432630 100755 --- a/client/pyscripts/pm5_battery_test.py +++ b/client/pyscripts/pm5_battery_test.py @@ -168,4 +168,4 @@ def main(): if __name__ == '__main__': - main() \ No newline at end of file + main() diff --git a/client/pyscripts/pm5_battery_test_graph.py b/client/pyscripts/pm5_battery_test_graph.py index 50f972a41..c6f0989a8 100755 --- a/client/pyscripts/pm5_battery_test_graph.py +++ b/client/pyscripts/pm5_battery_test_graph.py @@ -106,4 +106,4 @@ def main(): if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/client/resources/aid_desfire.json b/client/resources/aid_desfire.json index 705baa24f..c45585bec 100644 --- a/client/resources/aid_desfire.json +++ b/client/resources/aid_desfire.json @@ -291,8 +291,8 @@ "AID": "F48EF1", "Vendor": "Salto Systems", "Country": "ES", - "Name": "Salto Systems", - "Description": "Access Control", + "Name": "Salto Systems / Uni Delft", + "Description": "Access Control. Also issued as the TU Delft (NL) student card", "Type": "pacs" }, { @@ -451,8 +451,8 @@ "AID": "F532F0", "Vendor": "Schlage via Allegion PLC", "Country": "US", - "Name": "Schlage Access Credential", - "Description": "FKA aptiQ Access Credential", + "Name": "Schlage Access Credential / LEAF", + "Description": "FKA aptiQ Access Credential. LEAF reuses this AID for backwards compatibility", "Type": "pacs" }, { @@ -511,14 +511,6 @@ "Description": "LEAF Cc Enterprise app found on Apple Wallet credentials", "Type": "pacs" }, - { - "AID": "F532F0", - "Vendor": "LEAF", - "Country": "US", - "Name": "LEAF Backwards Compat", - "Description": "LEAF Backwards Compat", - "Type": "pacs" - }, { "AID": "F51CDC", "Vendor": "LEAF", @@ -559,6 +551,14 @@ "Description": "Fermax Proximity Card/Keyring DESFire EV2/EV3 2k Credential", "Type": "pacs" }, + { + "AID": "FE69AE", + "Vendor": "Fermax Electronica SAU", + "Country": "ES", + "Name": "Fermax DESFire entry card", + "Description": "Fermax Proximity Card/Keyring DESFire EV2/EV3 2k Credential", + "Type": "pacs" + }, { "AID": "F518F0", "Vendor": "Telenot Electronic GmbH", @@ -855,14 +855,6 @@ "Description": "Besucherausweis", "Type": "student" }, - { - "AID": "F48EF1", - "Vendor": "TU Delft", - "Country": "NL", - "Name": "Uni Delft", - "Description": "", - "Type": "student" - }, { "AID": "F5217D", "Vendor": "TU Delft", @@ -1639,6 +1631,30 @@ "Description": "HEL/TLL/TAY HSL Card (New blue card after 2016)", "Type": "transport" }, + { + "AID": "EF2101", + "Vendor": "Tampereen seudun joukkoliikenne (Nysse)", + "Country": "FI", + "Name": "Nysse Card (TMP)", + "Description": "Tampere region travel card", + "Type": "transport" + }, + { + "AID": "AB1000", + "Vendor": "Waltti Solutions Oy", + "Country": "FI", + "Name": "Waltti Card", + "Description": "Finnish regional travel card used outside the HSL area", + "Type": "transport" + }, + { + "AID": "4B5443", + "Vendor": "Transports publics fribourgeois (TPF)", + "Country": "CH", + "Name": "TPF Card (FRI)", + "Description": "Fribourg public transport card, AID is ASCII \"KTC\"", + "Type": "transport" + }, { "AID": "F001D0", "Vendor": "Arabako Foru Aldundia", diff --git a/client/resources/aidlist.json b/client/resources/aidlist.json index 82b0135b7..051a11e55 100644 --- a/client/resources/aidlist.json +++ b/client/resources/aidlist.json @@ -1990,32 +1990,16 @@ "AID": "D040000013000001", "Vendor": "Austria Card", "Country": "Austria", - "Name": "DF_UNI_Kepler1", - "Description": "Domestic Loyalty Program (Version 2.0)", - "Type": "" - }, - { - "AID": "D040000013000001", - "Vendor": "Austria Card", - "Country": "Austria", - "Name": "DF_Schler1", - "Description": "Domestic Loyalty Program (Version 1.3)", + "Name": "DF_UNI_Kepler1 / DF_Schler1", + "Description": "Domestic Loyalty Program (Version 2.0, and DF_Schler1 as version 1.3)", "Type": "" }, { "AID": "D040000013000002", "Vendor": "Austria Card", "Country": "Austria", - "Name": "DF_UNI_Kepler2", - "Description": "Domestic Loyalty Program (Version 2.0)", - "Type": "" - }, - { - "AID": "D040000013000002", - "Vendor": "Austria Card", - "Country": "Austria", - "Name": "DF_Schler2", - "Description": "Domestic Loyalty Program (Version 1.3)", + "Name": "DF_UNI_Kepler2 / DF_Schler2", + "Description": "Domestic Loyalty Program (Version 2.0, and DF_Schler2 as version 1.3)", "Type": "" }, { @@ -2030,16 +2014,8 @@ "AID": "D040000015000001", "Vendor": "Austria Card", "Country": "Austria", - "Name": "DF_UNI_Ausweis", - "Description": "Domestic Loyalty Program (Version 2.0)", - "Type": "" - }, - { - "AID": "D040000015000001", - "Vendor": "Austria Card", - "Country": "Austria", - "Name": "DF_Ausweis", - "Description": "Domestic Loyalty Program (Version 1.3)", + "Name": "DF_UNI_Ausweis / DF_Ausweis", + "Description": "Domestic Loyalty Program (Version 2.0, and DF_Ausweis as version 1.3)", "Type": "" }, { diff --git a/client/resources/mad.json b/client/resources/mad.json index 6b8465f55..7be261320 100644 --- a/client/resources/mad.json +++ b/client/resources/mad.json @@ -6224,6 +6224,13 @@ "service_provider": "NORALSY", "system_integrator": "NORALSY" }, + { + "application": "(access control and security) VIGIK", + "company": "PROAC", + "mad": "0x4982", + "service_provider": "PROAC", + "system_integrator": "PROAC" + }, { "application": "Card Administration, cardholder administration, access control & security, company services, miscellaneous applications", "company": "Ministry of Defense", @@ -10004,6 +10011,13 @@ "service_provider": "Unisys", "system_integrator": "Unisys" }, + { + "application": "MICROHARD", + "company": "MICROHARD SRL", + "mad": "0x6938", + "service_provider": "MICROHARD SRL", + "system_integrator": "MICROHARD SRL" + }, { "application": "Access control, time attendance, bus ticket, hotel room card, VIP card f. club", "company": "Giga-TMS Inc", diff --git a/client/src/cmdbwm.c b/client/src/cmdbwm.c new file mode 100644 index 000000000..0fc028f7b --- /dev/null +++ b/client/src/cmdbwm.c @@ -0,0 +1,1248 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// BWM (battery/wireless module) commands +//----------------------------------------------------------------------------- + +#include +#include +#include +#include + +#include "cmdparser.h" // command_t +#include "cliparser.h" +#include "comms.h" +#include "usart_defs.h" +#include "ui.h" +#include "cmdbwm.h" +#include "cmdhw.h" +#include "commonutil.h" +#include "pm3_cmd.h" +#include "cmdflashmem.h" // get_signature.. +#include "fileutils.h" // loadFile_safe +#include "util_posix.h" + +static int CmdBwmAutoOff(const char *Cmd) { + // Positional sub-action (no dashes): hw bwm autooff [on|off] [--idle ] + char verb[16] = {0}; + int consumed = 0; + sscanf(Cmd, "%15s%n", verb, &consumed); + bool on = (strcmp(verb, "on") == 0); + bool off = (strcmp(verb, "off") == 0); + const char *rest = (on || off) ? Cmd + consumed : Cmd; + + CLIParserContext *ctx; + CLIParserInit(&ctx, "hw bwm autooff", + "Show or set automatic power-off (PM5 only). Two triggers:\n" + " - USB was present and the cable is pulled: off at once, so a BWM-equipped\n" + " PM5 doesn't silently drain the battery; --unplug off only restarts the\n" + " idle clock instead;\n" + " - on battery with no command, button press or BLE/WiFi client for --idle\n" + " seconds: off (0 = never, the default).\n" + "Button power-on is unaffected. Stored on the BWM; without a module, defaults.", + "hw bwm autooff --> show the current state\n" + "hw bwm autooff off --> disable both triggers\n" + "hw bwm autooff on --> re-enable\n" + "hw bwm autooff --idle 300 --> also off after 5 min idle on battery\n" + "hw bwm autooff --idle 0 --> USB-unplug trigger only (default)\n" + "hw bwm autooff --unplug off --idle 300 --> survive the unplug, off 5 min idle later"); + void *argtable[] = { + arg_param_begin, + arg_int0("i", "idle", "", "idle timeout on battery in seconds, 0 = never"), + arg_str0("u", "unplug", "", "power off when USB is pulled (default on)"), + arg_param_end + }; + CLIExecWithReturn(ctx, rest, argtable, true); + int idle = arg_get_int_def(ctx, 1, -1); + uint8_t ubuf[8] = {0}; + int ulen = 0; + int ures = CLIParamStrToBuf(arg_get_str(ctx, 2), ubuf, sizeof(ubuf) - 1, &ulen); + CLIParserFree(ctx); + if (ures) { + PrintAndLogEx(WARNING, "--unplug takes " _YELLOW_("on") " or " _YELLOW_("off")); + return PM3_EINVARG; + } + uint8_t unplug = BWM_AUTOOFF_KEEP_U8; + if (ulen) { + if (strcmp((char *)ubuf, "on") == 0) { + unplug = 1; + } else if (strcmp((char *)ubuf, "off") == 0) { + unplug = 0; + } else { + PrintAndLogEx(WARNING, "--unplug takes " _YELLOW_("on") " or " _YELLOW_("off")); + return PM3_EINVARG; + } + } + if ((idle < -1) || (idle > (int)BWM_AUTOOFF_IDLE_MAX_S)) { + PrintAndLogEx(WARNING, "idle must be 0 to %lu seconds", (unsigned long)BWM_AUTOOFF_IDLE_MAX_S); + return PM3_EINVARG; + } + + struct { + uint8_t action; + uint8_t enabled; + uint32_t idle_s; + uint8_t unplug; + } PACKED payload = { + .action = (on || off || (idle >= 0) || ulen) ? BWM_AUTOOFF_ACTION_SET : BWM_AUTOOFF_ACTION_GET, + .enabled = on ? 1 : (off ? 0 : BWM_AUTOOFF_KEEP_U8), + .idle_s = (idle >= 0) ? (uint32_t)idle : BWM_AUTOOFF_KEEP_U32, + .unplug = unplug, + }; + + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_AUTOOFF, (uint8_t *)&payload, sizeof(payload)); + PacketResponseNG resp; + if (WaitForResponseTimeout(CMD_PM5_BWM_AUTOOFF, &resp, 5000) == false) { + PrintAndLogEx(WARNING, "command timeout (is this a PM5?)"); + return PM3_ETIMEOUT; + } + if (resp.status == PM3_ENOTIMPL) { + PrintAndLogEx(WARNING, "firmware built without auto power-off support"); + return resp.status; + } + if (resp.status != PM3_SUCCESS) { + PrintAndLogEx(FAILED, "failed to set auto power-off"); + return resp.status; + } + bool enabled = (resp.length >= 1) && (resp.data.asBytes[0] != 0); + PrintAndLogEx(SUCCESS, "Auto power-off....... %s", enabled ? _GREEN_("on") : _YELLOW_("off")); + if (resp.length < 5) { + // firmware before the idle timeout: it only reports the switch + return PM3_SUCCESS; + } + uint32_t idle_s; + memcpy(&idle_s, &resp.data.asBytes[1], sizeof(idle_s)); + if (idle_s) { + PrintAndLogEx(INFO, "Idle timeout......... " _YELLOW_("%u") " s", idle_s); + } else { + PrintAndLogEx(INFO, "Idle timeout......... off"); + } + if (resp.length >= sizeof(bwm_autooff_status_t)) { + const bwm_autooff_status_t *st = (const bwm_autooff_status_t *)resp.data.asBytes; + const char *live = (st->ble_live == 2) ? "client connected" : (st->ble_live == 1) ? "advertising, no client" : (st->ble_live == 0) ? "off" : "no answer"; + PrintAndLogEx(INFO, "Unplug power-off..... %s", st->unplug ? "on" : _YELLOW_("off") " (an unplug only restarts the idle clock)"); + PrintAndLogEx(INFO, "Stored on module..... %s", st->persisted ? "yes" : _YELLOW_("no")); + PrintAndLogEx(INFO, "USB power............ %s", st->usb ? "present" : "absent"); + PrintAndLogEx(INFO, "USB seen since boot.. %s", st->usb_seen ? "yes" : "no"); + PrintAndLogEx(INFO, "Unplug trigger....... %s", (enabled && st->unplug && st->usb_seen) ? _GREEN_("armed") : "not armed"); + PrintAndLogEx(INFO, "Tracked client....... %s", st->link ? "connected (BLE or WiFi)" : "none"); + PrintAndLogEx(INFO, "Module BLE state..... %s", live); + PrintAndLogEx(INFO, "Idle for............. %u s", st->idle_now_s); + if (st->persisted == 0) { + PrintAndLogEx(HINT, "no module, or one too old to store it: the defaults return at the next boot"); + } + } + return PM3_SUCCESS; +} + +static int CmdBWMWifi(const char *Cmd) { + // Sub-actions that carry no other arguments are positional keywords now: + // hw bwm wifi status (was --status) + // hw bwm wifi stop (was --stop) + // Bringing WiFi up still takes value flags, so it stays the default + // (no-keyword) form: hw bwm wifi --ssid --pwd [--port ] + char verb[16] = {0}; + sscanf(Cmd, "%15s", verb); + + if (strcmp(verb, "status") == 0) { + uint8_t q[1] = { BWM_WIFI_ACTION_STATUS }; + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_WIFI, q, sizeof(q)); + PacketResponseNG r; + if (WaitForResponseTimeout(CMD_PM5_BWM_WIFI, &r, 5000) == false) { + PrintAndLogEx(WARNING, "command timeout (is this a PM5 with a BWM fitted?)"); + return PM3_ETIMEOUT; + } + if (r.status != PM3_SUCCESS) { + PrintAndLogEx(FAILED, "could not query BWM WiFi status (BWM present?)"); + return r.status; + } + uint8_t state = (r.length >= 1) ? r.data.asBytes[0] : 0xFF; + uint32_t ip = 0; + if (r.length >= 5) { + ip = r.data.asBytes[1] | (r.data.asBytes[2] << 8) | (r.data.asBytes[3] << 16) | ((uint32_t)r.data.asBytes[4] << 24); + } + switch (state) { + case 0xFF: + PrintAndLogEx(INFO, "BWM WiFi disabled (BLE-only). Bring it up with " _YELLOW_("hw bwm wifi --ssid --pwd ")); + break; + case 2: // connected + if (ip) { + PrintAndLogEx(SUCCESS, "BWM WiFi connected, IP " _YELLOW_("%u.%u.%u.%u"), + ip & 0xFF, (ip >> 8) & 0xFF, (ip >> 16) & 0xFF, (ip >> 24) & 0xFF); + PrintAndLogEx(HINT, "Connect with: " _YELLOW_("pm3 -p tcp:%u.%u.%u.%u:"), + ip & 0xFF, (ip >> 8) & 0xFF, (ip >> 16) & 0xFF, (ip >> 24) & 0xFF); + } else { + PrintAndLogEx(INFO, "BWM WiFi associated, waiting for a DHCP lease..."); + } + break; + case 1: // connecting + PrintAndLogEx(INFO, "BWM WiFi connecting..."); + break; + case 3: // reconnect wait + PrintAndLogEx(INFO, "BWM WiFi reconnecting..."); + break; + case 4: // task stopped + PrintAndLogEx(INFO, "BWM WiFi connect task stopped"); + break; + case 0: // disconnected + default: + PrintAndLogEx(INFO, "BWM WiFi configured but not connected"); + break; + } + return PM3_SUCCESS; + } + + if (strcmp(verb, "stop") == 0) { + uint8_t off[1] = { BWM_WIFI_ACTION_STOP }; + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_WIFI, off, sizeof(off)); + PacketResponseNG r; + if (WaitForResponseTimeout(CMD_PM5_BWM_WIFI, &r, 5000) == false) { + PrintAndLogEx(WARNING, "command timeout (is this a PM5 with a BWM fitted?)"); + return PM3_ETIMEOUT; + } + if (r.status != PM3_SUCCESS) { + PrintAndLogEx(FAILED, "failed to disable BWM WiFi"); + return r.status; + } + PrintAndLogEx(SUCCESS, "BWM WiFi disabled (back to BLE-only)"); + return PM3_SUCCESS; + } + + CLIParserContext *ctx; + CLIParserInit(&ctx, "hw bwm wifi", + "Bring up the BWM in STA + TCP-server mode: join a WiFi network and\n" + "start a TCP server so the client can connect over WiFi. PM5 only.\n" + "Sub-actions (no dashes): 'status' shows state, 'stop' tears WiFi down.", + "hw bwm wifi status --> show connection state + IP\n" + "hw bwm wifi stop --> tear down WiFi, back to BLE-only\n" + "hw bwm wifi --ssid Home --pwd secret --> bring up, port 18888\n" + "hw bwm wifi --ssid Home --pwd secret --port 9000"); + + void *argtable[] = { + arg_param_begin, + arg_str0(NULL, "ssid", "", "WiFi SSID to join"), + arg_str0(NULL, "pwd", "", "WiFi password (omit for open network)"), + arg_int0(NULL, "port", "", "TCP server listen port (default 18888)"), + arg_str0(NULL, "hostname", "", "DHCP hostname (default Proxmark5)"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + + uint8_t ssid[64] = {0}; + int ssid_len = 0; + CLIParamStrToBuf(arg_get_str(ctx, 1), ssid, sizeof(ssid) - 1, &ssid_len); + + uint8_t pwd[64] = {0}; + int pwd_len = 0; + CLIParamStrToBuf(arg_get_str(ctx, 2), pwd, sizeof(pwd) - 1, &pwd_len); + + int port = arg_get_int_def(ctx, 3, 18888); + + uint8_t host[33] = {0}; + int host_len = 0; + CLIParamStrToBuf(arg_get_str(ctx, 4), host, sizeof(host) - 1, &host_len); + if (host_len == 0) { + strcpy((char *)host, "Proxmark5"); + host_len = 9; + } + CLIParserFree(ctx); + + if (ssid_len == 0) { + PrintAndLogEx(FAILED, "an SSID is required (or " _YELLOW_("hw bwm wifi stop") " to tear down)"); + return PM3_EINVARG; + } + if (port < 1 || port > 65535) { + PrintAndLogEx(FAILED, "port must be 1..65535"); + return PM3_EINVARG; + } + + // payload: [action:u8][port:u16 LE][ssid\0][pwd\0][hostname\0] + uint8_t data[200] = {0}; + int n = 0; + data[n++] = BWM_WIFI_ACTION_START; + data[n++] = (uint8_t)(port & 0xFF); + data[n++] = (uint8_t)((port >> 8) & 0xFF); + memcpy(&data[n], ssid, ssid_len); + n += ssid_len; + data[n++] = 0; + memcpy(&data[n], pwd, pwd_len); + n += pwd_len; + data[n++] = 0; + memcpy(&data[n], host, host_len); + n += host_len; + data[n++] = 0; + + PrintAndLogEx(INFO, "Bringing up BWM WiFi (SSID \"%s\", port %d)... this can take ~15s", ssid, port); + + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_WIFI, data, n); + PacketResponseNG resp; + // ARM blocks during join + DHCP wait, so allow a long client timeout + if (WaitForResponseTimeout(CMD_PM5_BWM_WIFI, &resp, 60000) == false) { + PrintAndLogEx(WARNING, "command timeout (is this a PM5 with a BWM fitted?)"); + return PM3_ETIMEOUT; + } + if (resp.status != PM3_SUCCESS) { + PrintAndLogEx(FAILED, "BWM WiFi bring-up failed (check SSID/password and signal)"); + PrintAndLogEx(HINT, "If it may have joined after DHCP, check: " _YELLOW_("hw bwm wifi status")); + return resp.status; + } + + uint32_t ip = resp.data.asDwords[0]; + PrintAndLogEx(SUCCESS, "BWM on WiFi at %u.%u.%u.%u", + ip & 0xFF, (ip >> 8) & 0xFF, (ip >> 16) & 0xFF, (ip >> 24) & 0xFF); + PrintAndLogEx(HINT, "Connect with: " _YELLOW_("pm3 -p tcp:%u.%u.%u.%u:%d"), + ip & 0xFF, (ip >> 8) & 0xFF, (ip >> 16) & 0xFF, (ip >> 24) & 0xFF, port); + PrintAndLogEx(HINT, "Or by name (router-dependent): " _YELLOW_("pm3 -p tcp:%s:%d"), host, port); + PrintAndLogEx(HINT, "Or by mDNS (BWM fw with mDNS): " _YELLOW_("pm3 -p tcp:%s.local:%d"), host, port); + return PM3_SUCCESS; +} + +static int CmdBwmCharge(const char *Cmd) { + // Positional sub-action (no dashes): hw bwm charge on | off + char verb[16] = {0}; + sscanf(Cmd, "%15s", verb); + bool on = (strcmp(verb, "on") == 0); + bool off = (strcmp(verb, "off") == 0); + + if (!on && !off) { + // Not a recognised sub-action: render help (also serves -h / empty), + // or error on a stray token, then stop. + CLIParserContext *ctx; + CLIParserInit(&ctx, "hw bwm charge", + "Enable or disable BWM battery charging by clearing/setting the\n" + "AW32001E charge-enable bit (CEB, REG01[3]). PM5 only.\n" + _RED_("One-shot:") " the charger watchdog reverts this after ~160 s unless\n" + "serviced, so charging may stop on its own. Use to nudge a top-up.", + "hw bwm charge off --> disable charging\n" + "hw bwm charge on --> enable charging"); + void *argtable[] = { + arg_param_begin, + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + CLIParserFree(ctx); + PrintAndLogEx(WARNING, "specify " _YELLOW_("on") " or " _YELLOW_("off")); + return PM3_EINVARG; + } + + uint8_t payload = off ? 0 : 1; // on -> 1 (enable), off -> 0 (disable) + PrintAndLogEx(INFO, "%s BWM battery charging...", off ? "Disabling" : "Enabling"); + + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_CHARGE_EN, &payload, sizeof(payload)); + PacketResponseNG resp; + if (WaitForResponseTimeout(CMD_PM5_BWM_CHARGE_EN, &resp, 2500) == false) { + PrintAndLogEx(WARNING, "command timeout (is this a PM5 with a BWM fitted?)"); + return PM3_ETIMEOUT; + } + if (resp.status != PM3_SUCCESS) { + PrintAndLogEx(FAILED, "charger did not respond (check BWM present)"); + return resp.status; + } + PrintAndLogEx(SUCCESS, "Charging %s. Verify with " _YELLOW_("hw status") ".", + off ? "disabled" : "enabled"); + if (off == false) { + PrintAndLogEx(HINT, "Reverts on the charger watchdog (~160 s) if not serviced."); + } + return PM3_SUCCESS; +} + +static int CmdBwmVchg(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hw bwm vchg", + "Set the BWM charger (AW32001E) charge-voltage regulation target.\n" + "Lowering it below 4.2 V reduces top-of-charge stress and extends cell\n" + "life. Snaps to the nearest 15 mV step; clamped to 3600..4200 mV. This is\n" + "a runtime register write (reverts on the charger watchdog / POR); the\n" + "firmware re-applies the " _YELLOW_("4100 mV") " default at every boot. PM5 only.", + "hw bwm vchg --> set charge voltage to default 4100 mV (->4.095 V)\n" + "hw bwm vchg --mv 4200 --> set charge voltage to 4200 mV"); + + void *argtable[] = { + arg_param_begin, + arg_int0(NULL, "mv", "", "charge voltage in mV (default 4100, clamped 3600..4200)"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + int mv = arg_get_int_def(ctx, 1, 4100); + CLIParserFree(ctx); + + if (mv < 3600 || mv > 4200) { + PrintAndLogEx(WARNING, "charge voltage out of range (3600..4200 mV): %d", mv); + return PM3_EINVARG; + } + + uint8_t payload[2] = { (uint8_t)(mv & 0xFF), (uint8_t)((mv >> 8) & 0xFF) }; + PrintAndLogEx(INFO, "Setting BWM charge voltage to " _YELLOW_("%d mV") "...", mv); + + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_SET_VCHG, payload, sizeof(payload)); + PacketResponseNG resp; + if (WaitForResponseTimeout(CMD_PM5_BWM_SET_VCHG, &resp, 5000) == false) { + PrintAndLogEx(WARNING, "command timeout (is this a PM5 with a BWM fitted?)"); + return PM3_ETIMEOUT; + } + if (resp.status != PM3_SUCCESS) { + PrintAndLogEx(FAILED, "failed to set charge voltage - check BWM present"); + return resp.status; + } + uint16_t applied = (resp.length >= 2) ? (resp.data.asBytes[0] | (resp.data.asBytes[1] << 8)) : 0; + PrintAndLogEx(SUCCESS, "Charge voltage set to " _YELLOW_("%u.%03u V") " (nearest 15 mV step).", applied / 1000, applied % 1000); + return PM3_SUCCESS; +} + +static int CmdBwmSetCap(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hw bwm setcap", + "Program the BWM fuel gauge (BQ27427) Design Capacity for the fitted cell.\n" + "Run ONCE after fitting or replacing the battery. This triggers a gauge\n" + "config-update; do not run it repeatedly, as that disrupts the Impedance\n" + "Track learning cycle. PM5 only.", + "hw bwm setcap --> set design capacity to default 500 mAh\n" + "hw bwm setcap --cap 500 --> set design capacity to 500 mAh"); + + void *argtable[] = { + arg_param_begin, + arg_int0(NULL, "cap", "", "design capacity in mAh (default 500)"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + int cap = arg_get_int_def(ctx, 1, 500); + CLIParserFree(ctx); + + if (cap <= 0 || cap > 32000) { + PrintAndLogEx(WARNING, "capacity out of range: %d mAh", cap); + return PM3_EINVARG; + } + + uint8_t payload[2] = { (uint8_t)(cap & 0xFF), (uint8_t)((cap >> 8) & 0xFF) }; + PrintAndLogEx(INFO, "Programming BWM gauge design capacity to " _YELLOW_("%d mAh") "...", cap); + PrintAndLogEx(INFO, "Run this " _YELLOW_("once") "; then perform a full charge/discharge learning cycle."); + + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_SET_CAP, payload, sizeof(payload)); + PacketResponseNG resp; + if (WaitForResponseTimeout(CMD_PM5_BWM_SET_CAP, &resp, 5000) == false) { + PrintAndLogEx(WARNING, "command timeout (is this a PM5 with a BWM fitted?)"); + return PM3_ETIMEOUT; + } + if (resp.status != PM3_SUCCESS) { + PrintAndLogEx(FAILED, "gauge provisioning failed - check BWM present and gauge unsealed"); + return resp.status; + } + PrintAndLogEx(SUCCESS, "Design capacity programmed. `hw status` should now report sane capacity."); + return PM3_SUCCESS; +} + + +static void progressbar(long sent, long total, int style) { + int percent = (int)((double)sent / total * 100); + + // Use \r at the start to move the cursor back to the beginning of the line + printf("\rProgress: [%d%%]", percent); + + // Force stdout to print immediately without waiting for a newline + fflush(stdout); +} + +// One full OTA attempt: BEGIN -> WRITE... -> END. The BWM OTA has no resume +// (DEV.md 8.4): a dropped chunk can't be re-sent, so any failure here means the +// caller must restart the whole thing. +static int bwm_ota_once(const uint8_t *fw, size_t fwlen, uint32_t write_delay_ms) { + PacketResponseNG resp; + + // BEGIN: tell the BWM how many bytes are coming. The ESP erases the idle + // OTA slot here; that can take 20-40 s on a 4 MB ESP32-C2, so wait longer + // than the device-side 60 s timeout plus USB round-trip. + uint8_t beg[5] = { BWM_OTA_ACTION_BEGIN, + (uint8_t)(fwlen & 0xFF), (uint8_t)((fwlen >> 8) & 0xFF), + (uint8_t)((fwlen >> 16) & 0xFF), (uint8_t)((fwlen >> 24) & 0xFF) + }; + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_ESP_OTA, beg, sizeof(beg)); + if (WaitForResponseTimeout(CMD_PM5_BWM_ESP_OTA, &resp, 75000) == false) { + PrintAndLogEx(FAILED, "OTA begin timed out (ESP is likely still erasing the OTA slot)"); + PrintAndLogEx(HINT, "Wait a few seconds and retry; do not power-cycle mid-erase."); + return PM3_ETIMEOUT; + } + if (resp.status != PM3_SUCCESS) { + PrintAndLogEx(FAILED, "OTA begin failed (status %d)%s", resp.status, + (resp.status == PM3_ETIMEOUT) ? " - UART timeout waiting for ESP" : ""); + return resp.status; + } + PrintAndLogEx(INFO, "Uploading " _YELLOW_("%zu") " bytes of ESP firmware over the BWM link...", fwlen); + + // WRITE chunks. Bounded by BWM_OTA_CHUNK_MAX (the ESP forwards each WRITE over + // its own small app_com UART frame - see bwm_wifi.c), not just the USB frame. + size_t maxchunk = MIN((size_t)g_conn.max_cmd_data_size - 1, (size_t)BWM_OTA_CHUNK_MAX); + uint8_t *buf = calloc(1, maxchunk + 1); + if (buf == NULL) { + return PM3_EMALLOC; + } + size_t sent = 0; + while (sent < fwlen) { + size_t n = MIN(maxchunk, fwlen - sent); + buf[0] = BWM_OTA_ACTION_WRITE; + memcpy(buf + 1, fw + sent, n); + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_ESP_OTA, buf, (uint16_t)(n + 1)); + bool got = WaitForResponseTimeout(CMD_PM5_BWM_ESP_OTA, &resp, 25000); + if (!got || resp.status != PM3_SUCCESS) { + PrintAndLogEx(NORMAL, ""); + if (!got) { + PrintAndLogEx(WARNING, "OTA write stalled at offset %zu (no response)", sent); + } else if (resp.status == PM3_ETIMEOUT) { + PrintAndLogEx(WARNING, "OTA write timed out at offset %zu (ESP did not ACK that chunk)", sent); + } else { + PrintAndLogEx(WARNING, "OTA write rejected at offset %zu (status %d)", sent, resp.status); + } + free(buf); + return PM3_EFAILED; + } + sent += n; + progressbar(sent, fwlen, STYLE_MIXED); + + // Pace the stream. The client->AT32 hop (USB/BLE) is far faster than the + // AT32->ESP UART, so back-to-back writes can outrun the UART and drop a + // chunk -> esp_ota_end() then sees written < total and aborts. A small + // gap gives the UART time to drain. (BLE is naturally paced, which is why + // it "worked" and bursty USB did not - see nemanjan00.) + if (write_delay_ms) { + msleep(write_delay_ms); + } + } + free(buf); + PrintAndLogEx(NORMAL, ""); + + // END: finalize + set the new boot partition + uint8_t end[1] = { BWM_OTA_ACTION_END }; + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_ESP_OTA, end, sizeof(end)); + bool got_end = WaitForResponseTimeout(CMD_PM5_BWM_ESP_OTA, &resp, 30000); + if (got_end && (resp.status == PM3_SUCCESS)) { + return PM3_SUCCESS; + } + if (got_end) { + // The BWM answered END with an error. The common one is a size mismatch: + // esp_ota_end() found written < total, i.e. chunks were dropped in transit. + // That is a genuine failure (boot partition NOT switched) - restart, and + // hint at pacing, which is the usual cure. + PrintAndLogEx(WARNING, "OTA finalize rejected (status %d) - data was lost in transit", resp.status); + PrintAndLogEx(HINT, "Try a per-write delay: " _YELLOW_("hw bwm upgrade -f --delay 20")); + return PM3_EFAILED; + } + // No answer at all. Over BLE the END auto-reboot drops the link before the ack + // returns, so a timeout here means "reached END, reboot likely happened" - + // verify by version rather than discarding a possibly-good flash. + return PM3_ETIMEOUT; +} + +// Query the BWM's running firmware version string (APP_CMD_GET_VERSION_INFO). +static int bwm_get_version(char *out, size_t outlen) { + uint8_t a[1] = { BWM_OTA_ACTION_VERSION }; + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_ESP_OTA, a, sizeof(a)); + PacketResponseNG r; + if ((WaitForResponseTimeout(CMD_PM5_BWM_ESP_OTA, &r, 5000) == false) || (r.status != PM3_SUCCESS)) { + return PM3_EFAILED; + } + uint16_t n = (r.length < (uint16_t)(outlen - 1)) ? r.length : (uint16_t)(outlen - 1); + memcpy(out, r.data.asBytes, n); + out[n] = 0; + return PM3_SUCCESS; +} + +static int CmdBWMUpgrade(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hw bwm upgrade", + "Reflash the BWM (ESP32) firmware over the BWM link - no header, no soldering.\n" + "Requires a BWM that still responds; this updates a wrong-version ESP, it cannot\n" + "recover a fully bricked one (that still needs the 5-pin header + esptool).", + "hw bwm upgrade -f bwm_esp32.bin"); + void *argtable[] = { + arg_param_begin, + arg_str1("f", "file", "", "ESP32 firmware image (.bin)"), + arg_int0(NULL, "delay", "", "per-chunk delay to pace the slow AT32<->ESP UART (default 20)"), + arg_param_end, + }; + CLIExecWithReturn(ctx, Cmd, argtable, false); + int fnlen = 0; + char fn[FILE_PATH_SIZE] = {0}; + CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)fn, sizeof(fn), &fnlen); + uint32_t write_delay_ms = (uint32_t)arg_get_int_def(ctx, 2, 20); + CLIParserFree(ctx); + + if (fnlen == 0) { + PrintAndLogEx(FAILED, "no filename given"); + return PM3_EINVARG; + } + + uint8_t *fw = NULL; + size_t fwlen = 0; + if ((loadFile_safe(fn, "", (void **)&fw, &fwlen) != PM3_SUCCESS) || (fwlen == 0)) { + PrintAndLogEx(FAILED, "could not read " _YELLOW_("%s"), fn); + return PM3_EFILE; + } + + // Safeguard: refuse to flash anything that is not an ESP32-C2 app image. The + // BWM ESP is an ESP32-C2; a wrong/other-chip image would brick it. + // [0x00] == 0xE9 -> ESP image magic + // [0x0C..0x0D] == 0x000C -> chip_id ESP32-C2 (LE uint16) + // [0xABCD5432..0x20] == 0xABCD5432 -> app descriptor (LE uint32) + if (fwlen < 16) { + PrintAndLogEx(FAILED, "file is too small to be an ESP firmware image (%zu bytes)", fwlen); + free(fw); + return PM3_EFILE; + } + if (fw[0] != 0xE9) { + PrintAndLogEx(FAILED, "refusing to flash: not an ESP image (magic " _YELLOW_("0x%02X") ", expected 0xE9)", fw[0]); + free(fw); + return PM3_EFILE; + } + + // Check Chip ID at offset 0x0C (2 bytes, little-endian) + uint16_t chip_id = MemLeToUint2byte(fw + 0x0C); + if (chip_id != 0x000C) { + PrintAndLogEx(FAILED, "refusing to flash: image chip_id " _YELLOW_("0x%04X") " is not ESP32-C2 (0x000C)", chip_id); + free(fw); + return PM3_EFILE; + } + + // Check Application Signature at offset 0x20 (4 bytes, little-endian) + uint32_t app_sign = MemLeToUint4byte(fw + 0x20); + if (app_sign != 0xABCD5432) { + PrintAndLogEx(FAILED, "refusing to flash: image app_sign " _YELLOW_("0x%08X") " is invalid (expected 0xABCD5432)", app_sign); + free(fw); + return PM3_EFILE; + } + + // Record the running version first, so we can confirm the update actually took + // even when the finalize ack is lost (the case that used to discard a completed + // flash and restart from scratch). + char ver_before[64] = {0}; + bool have_before = (bwm_get_version(ver_before, sizeof(ver_before)) == PM3_SUCCESS); + if (have_before) { + PrintAndLogEx(INFO, "Current BWM firmware..... " _YELLOW_("%s"), ver_before); + } + + // No resume (DEV.md 8.4): a chunk lost mid-transfer restarts the whole upload. + const int max_attempts = 6; // a single dropped chunk restarts the whole upload; + // more attempts make an all-fail run rare until per-chunk + // retry (offset-idempotent ESP write) lands. + for (int attempt = 1; attempt <= max_attempts; attempt++) { + if (attempt > 1) { + // Abort the in-flight ESP OTA (if any) and give a slow erase a chance + // to finish before we BEGIN again. Otherwise attempt N's BEGIN races + // attempt N-1's still-running erase and times out. + PrintAndLogEx(INFO, "restarting OTA from the beginning (attempt " _YELLOW_("%d") "/%d)", attempt, max_attempts); + uint8_t ab[1] = { BWM_OTA_ACTION_ABORT }; + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_ESP_OTA, ab, sizeof(ab)); + PacketResponseNG abortr; + (void)WaitForResponseTimeout(CMD_PM5_BWM_ESP_OTA, &abortr, 8000); + msleep(3000); + } + int res = bwm_ota_once(fw, fwlen, write_delay_ms); + + // Failed during BEGIN/WRITE: image incomplete, restart the whole thing. + if ((res != PM3_SUCCESS) && (res != PM3_ETIMEOUT)) { + continue; + } + + // Reached OTA_END (acked, or ack lost). The image is written and the boot + // partition is set - reboot into it and confirm by version. + if (res == PM3_ETIMEOUT) { + PrintAndLogEx(INFO, "finalize ack not seen - all data was sent, confirming by version..."); + } + // Upload is complete and the ESP is rebooting into the new image. The + // AT32<->ESP link is now desynced (the ESP comes back at its boot-default + // baud), and the AT32 only re-negotiates on its own reset - so reset the PM5 + // to re-sync the link cleanly rather than trying to re-link in place. This + // drops the client link; the user reconnects to a cleanly re-linked PM5. + (void)have_before; + PrintAndLogEx(SUCCESS, "BWM firmware uploaded; resetting the PM5 to re-sync the link..."); + free(fw); + clearCommandBuffer(); + SendCommandNG(CMD_HARDWARE_RESET, NULL, 0); + PrintAndLogEx(INFO, "PM5 has been reset - reconnect, then run " _YELLOW_("hw status") " to confirm the new BWM version."); + return PM3_SUCCESS; + } + free(fw); + + // Exhausted retries without a confirmed update - restore the link and report. + PacketResponseNG resp; + uint8_t ab[1] = { BWM_OTA_ACTION_ABORT }; + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_ESP_OTA, ab, sizeof(ab)); + (void)WaitForResponseTimeout(CMD_PM5_BWM_ESP_OTA, &resp, 8000); + PrintAndLogEx(FAILED, "BWM firmware update could not be confirmed after %d attempts", max_attempts); + return PM3_EFAILED; +} +static int CmdHelpBwm(const char *Cmd); + +static int CmdBwmName(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hw bwm name", + "Get or set the BWM BLE advertising name (stored on the BWM, in NVS).\n" + "With no --set, prints the current name. Setting a name stores it and reboots\n" + "the BWM to apply it - this briefly drops a BLE/WiFi connection; reconnect after\n" + "a few seconds. Over USB the reboot is not noticeable.", + "hw bwm name --> show current BLE name\n" + "hw bwm name --set MyPM5 --> set BLE name to 'MyPM5'"); + void *argtable[] = { + arg_param_begin, + arg_str0(NULL, "set", "", "new BLE name (1-31 chars); omit to read current name"), + arg_param_end, + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + + uint8_t name[64] = {0}; + int nlen = sizeof(name) - 1; // CLIGetStrWithReturn does not guarantee NUL-termination + CLIGetStrWithReturn(ctx, 1, name, &nlen); + CLIParserFree(ctx); + + if (nlen == 0) { + // GET + uint8_t a[1] = { BWM_BLE_NAME_ACTION_GET }; + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_BLE_NAME, a, sizeof(a)); + PacketResponseNG r; + if ((WaitForResponseTimeout(CMD_PM5_BWM_BLE_NAME, &r, 5000) == false) || (r.status != PM3_SUCCESS)) { + PrintAndLogEx(FAILED, "failed to read BWM BLE name (is a responsive BWM fitted?)"); + return PM3_EFAILED; + } + char out[BWM_BLE_NAME_MAX_LEN + 1] = {0}; + uint16_t n = (r.length < sizeof(out) - 1) ? r.length : (uint16_t)(sizeof(out) - 1); + memcpy(out, r.data.asBytes, n); + PrintAndLogEx(SUCCESS, "BWM BLE name..... " _YELLOW_("%s"), out); + return PM3_SUCCESS; + } + + // SET + if (nlen > BWM_BLE_NAME_MAX_LEN) { + PrintAndLogEx(FAILED, "name too long: %d chars (max " _YELLOW_("%d") ")", nlen, BWM_BLE_NAME_MAX_LEN); + return PM3_EINVARG; + } + uint8_t payload[1 + BWM_BLE_NAME_MAX_LEN]; + payload[0] = BWM_BLE_NAME_ACTION_SET; + memcpy(payload + 1, name, nlen); + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_BLE_NAME, payload, (uint16_t)(1 + nlen)); + PacketResponseNG r; + if ((WaitForResponseTimeout(CMD_PM5_BWM_BLE_NAME, &r, 5000) == false) || (r.status != PM3_SUCCESS)) { + PrintAndLogEx(FAILED, "failed to set BWM BLE name (is a responsive BWM fitted?)"); + return PM3_EFAILED; + } + PrintAndLogEx(SUCCESS, "BWM BLE name set to " _YELLOW_("%s"), name); + + // The ESP applies the name at BLE start-up, so it reboots (device-side) to pick + // it up. That reboot leaves the AT32<->ESP link desynced (the ESP comes back at + // its boot-default baud, and the AT32 only re-negotiates on its own reset), so + // reset the PM5 to re-sync. This drops the client link - reconnect afterwards. + PrintAndLogEx(INFO, "Resetting the PM5 to apply the new name and re-sync the BWM link..."); + clearCommandBuffer(); + SendCommandNG(CMD_HARDWARE_RESET, NULL, 0); + PrintAndLogEx(INFO, "PM5 has been reset - reconnect after a few seconds."); + return PM3_SUCCESS; +} + +// Round trip for the BWM u8 settings (`hw bwm powersave`, `hw bwm wifipower`): +// send [action][value] (value only when has_value) and wait for the ESP's answer. +// Prints the generic failure messages; on PM3_SUCCESS resp holds >= 1 byte. +static int bwm_setting_txn(uint16_t cmd, uint8_t action, uint8_t value, bool has_value, + PacketResponseNG *resp, const char *what) { + uint8_t payload[2] = { action, value }; + clearCommandBuffer(); + SendCommandNG(cmd, payload, has_value ? 2 : 1); + if (WaitForResponseTimeout(cmd, resp, 8000) == false) { + PrintAndLogEx(WARNING, "command timeout (is this a PM5 with a responsive BWM?)"); + return PM3_ETIMEOUT; + } + if (resp->status == PM3_ENOTIMPL) { + PrintAndLogEx(WARNING, "firmware built without BWM link support"); + return resp->status; + } + if (resp->status != PM3_SUCCESS || resp->length < 1) { + PrintAndLogEx(FAILED, "BWM did not answer the %s command (BWM firmware too old?)", what); + return (resp->status != PM3_SUCCESS) ? resp->status : PM3_EFAILED; + } + return PM3_SUCCESS; +} + +static const char *bwm_wifi_state_name(uint8_t state) { + switch (state) { + case 0: + return "disconnected"; + case 1: + return "connecting"; + case 2: + return "connected"; + case 3: + return "reconnecting"; + case 4: + return "connect task stopped"; + default: + return "unknown state"; + } +} + +static int CmdBwmPowerSave(const char *Cmd) { + // Positional sub-action (no dashes): hw bwm powersave [on | off]; no verb shows the state + char verb[16] = {0}; + sscanf(Cmd, "%15s", verb); + bool on = (strcmp(verb, "on") == 0); + bool off = (strcmp(verb, "off") == 0); + bool show = (verb[0] == 0); + + if (!on && !off && !show) { + // Not a recognised sub-action: render help (also serves -h), or error on + // a stray token, then stop. + CLIParserContext *ctx; + CLIParserInit(&ctx, "hw bwm powersave", + "Show or set the BWM (ESP32) power-save switch, stored on the BWM in NVS.\n" + "Default is " _GREEN_("on") ": the ESP scales its clock down, light-sleeps between\n" + "link traffic, and after 30 s of fast advertising (boot, disconnect) advertises\n" + "once a second. " _YELLOW_("off") " pins it at full clock, no sleep, fast advertising\n" + "throughout. Applies at once and survives reboots. PM5 only.", + "hw bwm powersave --> show the current state\n" + "hw bwm powersave off --> stock always-on behaviour\n" + "hw bwm powersave on --> re-enable power saving"); + void *argtable[] = { + arg_param_begin, + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + CLIParserFree(ctx); + PrintAndLogEx(WARNING, "specify " _YELLOW_("on") ", " _YELLOW_("off") " or nothing to show the state"); + return PM3_EINVARG; + } + + PacketResponseNG resp; + int res = bwm_setting_txn(CMD_PM5_BWM_POWERSAVE, show ? BWM_POWERSAVE_ACTION_GET : BWM_POWERSAVE_ACTION_SET, + on ? 1 : 0, !show, &resp, "power-save"); + if (res != PM3_SUCCESS) { + return res; + } + bool state = (resp.data.asBytes[0] != 0); + PrintAndLogEx(SUCCESS, "BWM power save..... %s", state ? _GREEN_("on") : _YELLOW_("off")); + return PM3_SUCCESS; +} + +static const char *bwm_wifi_ps_name(uint8_t mode) { + switch (mode) { + case BWM_WIFI_PS_NONE: + return "none"; + case BWM_WIFI_PS_MIN: + return "min"; + case BWM_WIFI_PS_MAX: + return "max"; + default: + return "?"; + } +} + +static int CmdBwmWifiPower(const char *Cmd) { + // Positional sub-action (no dashes): hw bwm wifipower [off | none | min | max]; no verb shows the state + char verb[16] = {0}; + sscanf(Cmd, "%15s", verb); + int mode = -1; + if (verb[0] == 0) { + mode = -1; + } else if (strcmp(verb, "off") == 0) { + // WiFi fully off: same as `hw bwm wifi stop`. + return CmdBWMWifi("stop"); + } else if (strcmp(verb, "none") == 0) { + mode = BWM_WIFI_PS_NONE; + } else if (strcmp(verb, "min") == 0) { + mode = BWM_WIFI_PS_MIN; + } else if (strcmp(verb, "max") == 0) { + mode = BWM_WIFI_PS_MAX; + } else { + // Not a recognised sub-action: render help (also serves -h), or error on + // a stray token, then stop. + CLIParserContext *ctx; + CLIParserInit(&ctx, "hw bwm wifipower", + "Show or set how much power the BWM (ESP32) spends on WiFi.\n" + _YELLOW_("off") " turns WiFi fully off (BLE-only, persisted; the default state, same as\n" + "`hw bwm wifi stop`). Bring it back with " _YELLOW_("hw bwm wifi --ssid --pwd ") ".\n" + "The other three set the modem power-save type while WiFi is up, stored on the\n" + "BWM: " _GREEN_("min") " (default) sleeps between DTIM beacons, " _YELLOW_("max") " for the whole\n" + "listen interval, " _YELLOW_("none") " never. Independent of " _YELLOW_("hw bwm powersave") ". PM5 only.", + "hw bwm wifipower --> show whether WiFi is up and the power-save type\n" + "hw bwm wifipower off --> WiFi fully off, BLE-only\n" + "hw bwm wifipower none --> modem always on while WiFi is up\n" + "hw bwm wifipower min --> ESP-IDF default (DTIM sleep)\n" + "hw bwm wifipower max --> deepest modem sleep"); + void *argtable[] = { + arg_param_begin, + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + CLIParserFree(ctx); + PrintAndLogEx(WARNING, "specify " _YELLOW_("off") ", " _YELLOW_("none") ", " _YELLOW_("min") ", " _YELLOW_("max") " or nothing to show the state"); + return PM3_EINVARG; + } + + PacketResponseNG resp; + int res = bwm_setting_txn(CMD_PM5_BWM_WIFI_PS, (mode < 0) ? BWM_WIFI_PS_ACTION_GET : BWM_WIFI_PS_ACTION_SET, + (mode < 0) ? 0 : (uint8_t)mode, mode >= 0, &resp, "WiFi power"); + if (res != PM3_SUCCESS) { + return res; + } + uint8_t wifi_state = (resp.length >= 2) ? resp.data.asBytes[1] : BWM_WIFI_STATE_OFF; + if (wifi_state == BWM_WIFI_STATE_OFF) { + PrintAndLogEx(SUCCESS, "BWM WiFi................ " _GREEN_("off") " (BLE-only)"); + } else { + PrintAndLogEx(SUCCESS, "BWM WiFi................ " _YELLOW_("on") " (%s)", bwm_wifi_state_name(wifi_state)); + } + PrintAndLogEx(SUCCESS, "BWM WiFi power save..... " _YELLOW_("%s"), bwm_wifi_ps_name(resp.data.asBytes[0])); + return PM3_SUCCESS; +} + + +// --------------------------------------------------------------------------- +// hw bwm ble: the module's BLE settings (CMD_PM5_BWM_BLE) +// --------------------------------------------------------------------------- + +static const char *ble_state_str(uint8_t state) { + switch (state) { + case 0: + return "off"; + case 1: + return "advertising, no client"; + case 2: + return "client connected"; + default: + return "unknown"; + } +} + +// esp_power_level_t index <-> dBm: -24 dBm + 3 dB per step, index 15 = +20 dBm +static int ble_level_to_dbm(uint8_t level) { + if (level == 15) return 20; + return -24 + 3 * (int)level; +} + +static int ble_dbm_to_level(int dbm) { + if (dbm == 20) return 15; + if (dbm < -24 || dbm > 18 || ((dbm + 24) % 3) != 0) return -1; + return (dbm + 24) / 3; +} + +static void ble_print_status(const bwm_ble_status_t *st) { + PrintAndLogEx(INFO, "--- " _CYAN_("BWM BLE") " ---------------------------"); + if (st->enabled == 0xFF) { + PrintAndLogEx(INFO, "BLE................ %s " _YELLOW_("(module firmware without the on/off switch)"), ble_state_str(st->state)); + } else if (st->enabled == 0) { + PrintAndLogEx(INFO, "BLE................ " _YELLOW_("off") " (persisted; radio silent, USB/WiFi only)"); + } else { + PrintAndLogEx(INFO, "BLE................ " _GREEN_("on") ", %s", ble_state_str(st->state)); + } + if (st->name[0]) { + PrintAndLogEx(INFO, "Name............... " _YELLOW_("%s"), st->name); + } + if (st->addr[0] != 0xFF || st->addr[5] != 0xFF) { + PrintAndLogEx(INFO, "Address............ %02X:%02X:%02X:%02X:%02X:%02X", + st->addr[0], st->addr[1], st->addr[2], st->addr[3], st->addr[4], st->addr[5]); + } + if (st->bonding == 1) { + PrintAndLogEx(INFO, "Pairing............ " _GREEN_("required") " (LE Secure Connections, passkey " _YELLOW_("%.6s") ")", st->passkey); + if (memcmp(st->passkey, "123456", 6) == 0) { + PrintAndLogEx(WARNING, "the passkey is the factory default, change it: " _YELLOW_("hw bwm ble pairing -k <6 digits>")); + } + } else if (st->bonding == 0) { + PrintAndLogEx(INFO, "Pairing............ " _RED_("not required") " - anyone in range can connect and use the device"); + PrintAndLogEx(HINT, "enable it with " _YELLOW_("hw bwm ble pairing on")); + } + if (st->bonded_count != 0xFF) { + PrintAndLogEx(INFO, "Bonded devices..... %u%s", st->bonded_count, (st->bonded_count == BWM_BLE_BONDED_MAX) ? " (or more)" : ""); + for (uint8_t i = 0; i < st->bonded_count; i++) { + const uint8_t *a = st->bonded[i]; + PrintAndLogEx(INFO, " [%u] %02X:%02X:%02X:%02X:%02X:%02X (%s)", i, + a[0], a[1], a[2], a[3], a[4], a[5], (a[6] == 0) ? "public" : "random"); + } + } + if (st->txp_adv != 0xFF && st->txp_conn != 0xFF) { + PrintAndLogEx(INFO, "TX power........... advertising %d dBm, connection %d dBm", + ble_level_to_dbm(st->txp_adv), ble_level_to_dbm(st->txp_conn)); + } +} + +// One CMD_PM5_BWM_BLE round trip. Prints the status on success unless quiet. +static int ble_action(uint8_t action, const uint8_t *arg, size_t alen, bool quiet) { + uint8_t payload[1 + 8] = { action }; + if (alen > sizeof(payload) - 1) { + return PM3_EINVARG; + } + if (alen) { + memcpy(&payload[1], arg, alen); + } + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_BLE, payload, 1 + alen); + PacketResponseNG resp; + // Up to a dozen module round trips behind one reply, plus a light-sleep wake. + if (WaitForResponseTimeout(CMD_PM5_BWM_BLE, &resp, 8000) == false) { + PrintAndLogEx(WARNING, "command timeout (is this a PM5? over BLE, a pairing or on/off change drops your own link)"); + return PM3_ETIMEOUT; + } + if (resp.status == PM3_ENOTIMPL) { + PrintAndLogEx(WARNING, "firmware built without the BWM link"); + return resp.status; + } + if (resp.status != PM3_SUCCESS) { + PrintAndLogEx(FAILED, "module refused or did not answer (%s)", (resp.status == PM3_ETIMEOUT) ? "timeout" : "error"); + return resp.status; + } + if (resp.length < sizeof(bwm_ble_status_t)) { + PrintAndLogEx(FAILED, "short reply (%u bytes)", resp.length); + return PM3_EFAILED; + } + if (quiet == false) { + ble_print_status((const bwm_ble_status_t *)resp.data.asBytes); + } + return PM3_SUCCESS; +} + +static int CmdBwmBleStatus(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hw bwm ble status", + "Show the module's BLE settings: on/off, name, address, pairing and passkey,\n" + "bonded devices, TX power.", + "hw bwm ble status"); + void *argtable[] = { + arg_param_begin, + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + CLIParserFree(ctx); + return ble_action(BWM_BLE_ACTION_STATUS, NULL, 0, false); +} + +static int ble_set_enable(const char *Cmd, bool on) { + CLIParserContext *ctx; + CLIParserInit(&ctx, on ? "hw bwm ble on" : "hw bwm ble off", + "Switch the module's BLE radio on or off. Persisted on the module, applied at\n" + "once. Off means nothing can connect over BLE at all; the PM5 stays reachable\n" + "over USB (and WiFi if configured). Needs a BWM firmware with the BLE switch.\n" + _YELLOW_("Over BLE, `off` cuts your own connection."), + on ? "hw bwm ble on" : "hw bwm ble off"); + void *argtable[] = { + arg_param_begin, + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + CLIParserFree(ctx); + uint8_t v = on ? 1 : 0; + return ble_action(BWM_BLE_ACTION_ENABLE, &v, 1, false); +} + +static int CmdBwmBleOn(const char *Cmd) { + return ble_set_enable(Cmd, true); +} + +static int CmdBwmBleOff(const char *Cmd) { + return ble_set_enable(Cmd, false); +} + +static int CmdBwmBlePairing(const char *Cmd) { + // Positional sub-action (no dashes): hw bwm ble pairing [on|off] [-k ] + char verb[16] = {0}; + int consumed = 0; + sscanf(Cmd, "%15s%n", verb, &consumed); + bool on = (strcmp(verb, "on") == 0); + bool off = (strcmp(verb, "off") == 0); + const char *rest = (on || off) ? Cmd + consumed : Cmd; + + CLIParserContext *ctx; + CLIParserInit(&ctx, "hw bwm ble pairing", + "Require pairing before a BLE client can use the device. The module ships with\n" + "pairing " _RED_("off") ": anyone in range can connect and run commands. With it on, a\n" + "client must pair once with the 6-digit passkey (LE Secure Connections, MITM)\n" + "and the data characteristic only works over the encrypted link; paired\n" + "(bonded) devices reconnect without the key until you forget them.\n" + "Both settings persist on the module. A change of on/off restarts the BLE\n" + "stack, which " _YELLOW_("drops a connected client - reconnect (and pair) afterwards.") "\n" + "The factory passkey is 123456; set your own.", + "hw bwm ble pairing on --> require pairing\n" + "hw bwm ble pairing on -k 482913 --> require pairing with this passkey\n" + "hw bwm ble pairing -k 482913 --> change the passkey only\n" + "hw bwm ble pairing off --> open access again"); + void *argtable[] = { + arg_param_begin, + arg_str0("k", "key", "<6 digits>", "passkey a client must enter"), + arg_param_end + }; + CLIExecWithReturn(ctx, rest, argtable, true); + uint8_t key[8] = {0}; + int keylen = 0; + int kres = CLIParamStrToBuf(arg_get_str(ctx, 1), key, sizeof(key) - 1, &keylen); + CLIParserFree(ctx); + if (kres) { + PrintAndLogEx(WARNING, "the passkey must be exactly 6 digits"); + return PM3_EINVARG; + } + + if (keylen) { + bool ok = (keylen == 6); + for (int i = 0; ok && i < 6; i++) { + ok = isdigit(key[i]); + } + if (ok == false) { + PrintAndLogEx(WARNING, "the passkey must be exactly 6 digits"); + return PM3_EINVARG; + } + int res = ble_action(BWM_BLE_ACTION_KEY, key, 6, (on || off)); + if (res != PM3_SUCCESS) { + return res; + } + if (!on && !off) { + PrintAndLogEx(SUCCESS, "passkey set"); + return PM3_SUCCESS; + } + } else if (!on && !off) { + PrintAndLogEx(WARNING, "specify " _YELLOW_("on") ", " _YELLOW_("off") " and/or " _YELLOW_("-k <6 digits>")); + return PM3_EINVARG; + } + uint8_t v = on ? 1 : 0; + int res = ble_action(BWM_BLE_ACTION_PAIRING, &v, 1, false); + if (res == PM3_SUCCESS) { + PrintAndLogEx(SUCCESS, "pairing %s; the BLE stack is restarting, a connected client is dropped", on ? _GREEN_("required") : _YELLOW_("not required")); + } + return res; +} + +static int CmdBwmBleForget(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hw bwm ble forget", + "Remove bonded (paired) devices from the module, so they must pair again with\n" + "the passkey. Indexes are the ones `hw bwm ble status` lists.", + "hw bwm ble forget --all\n" + "hw bwm ble forget -i 0"); + void *argtable[] = { + arg_param_begin, + arg_int0("i", "idx", "", "index of the bonded device to remove"), + arg_lit0(NULL, "all", "remove all bonded devices"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + int idx = arg_get_int_def(ctx, 1, -1); + bool all = arg_get_lit(ctx, 2); + CLIParserFree(ctx); + if ((all && idx >= 0) || (!all && idx < 0)) { + PrintAndLogEx(WARNING, "specify either " _YELLOW_("-i ") " or " _YELLOW_("--all")); + return PM3_EINVARG; + } + if (idx > 254) { + PrintAndLogEx(WARNING, "index out of range"); + return PM3_EINVARG; + } + uint8_t v = all ? 0xFF : (uint8_t)idx; + return ble_action(BWM_BLE_ACTION_FORGET, &v, 1, false); +} + +static int CmdBwmBleTxPower(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hw bwm ble txpower", + "Set the module's BLE transmit power for advertising and/or connections.\n" + "Steps of 3 dB from -24 to 18 dBm, plus 20. Lower saves a little battery and\n" + "shrinks the range at which the device can be found. Persisted on the module.", + "hw bwm ble txpower -a 0 -c 0 --> 0 dBm for both\n" + "hw bwm ble txpower -a -6 --> quieter advertising only"); + void *argtable[] = { + arg_param_begin, + arg_int0("a", "adv", "", "advertising power"), + arg_int0("c", "conn", "", "connection power"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + bool has_adv = (arg_get_int_count(ctx, 1) > 0); + bool has_conn = (arg_get_int_count(ctx, 2) > 0); + int adv = arg_get_int_def(ctx, 1, 0); + int conn = arg_get_int_def(ctx, 2, 0); + CLIParserFree(ctx); + if ((has_adv == false) && (has_conn == false)) { + PrintAndLogEx(WARNING, "specify " _YELLOW_("-a ") " and/or " _YELLOW_("-c ")); + return PM3_EINVARG; + } + int la = has_adv ? ble_dbm_to_level(adv) : 0; + int lc = has_conn ? ble_dbm_to_level(conn) : 0; + if (la < 0 || lc < 0) { + PrintAndLogEx(WARNING, "valid values: -24, -21, ... 15, 18, 20 dBm"); + return PM3_EINVARG; + } + int res = PM3_SUCCESS; + if (has_adv) { + uint8_t v[2] = { 0, (uint8_t)la }; + res = ble_action(BWM_BLE_ACTION_TXPOWER, v, 2, has_conn); + } + if (res == PM3_SUCCESS && has_conn) { + uint8_t v[2] = { 1, (uint8_t)lc }; + res = ble_action(BWM_BLE_ACTION_TXPOWER, v, 2, false); + } + return res; +} + +static int CmdHelpBwmBle(const char *Cmd); +static command_t BwmBleCommandTable[] = { + {"help", CmdHelpBwmBle, AlwaysAvailable, "This help"}, + {"status", CmdBwmBleStatus, IfBwm, "Show BLE settings: on/off, pairing, bonded devices, TX power"}, + {"on", CmdBwmBleOn, IfBwm, "Switch BLE on (persisted)"}, + {"off", CmdBwmBleOff, IfBwm, "Switch BLE off (persisted) - nothing can connect"}, + {"pairing", CmdBwmBlePairing, IfBwm, "Require pairing with a passkey, set the passkey"}, + {"forget", CmdBwmBleForget, IfBwm, "Remove bonded devices"}, + {"txpower", CmdBwmBleTxPower, IfBwm, "Set advertising / connection TX power"}, + {NULL, NULL, NULL, NULL} +}; + +static int CmdHelpBwmBle(const char *Cmd) { + (void)Cmd; + CmdsHelp(BwmBleCommandTable); + return PM3_SUCCESS; +} + +static int CmdBwmBle(const char *Cmd) { + clearCommandBuffer(); + return CmdsParse(BwmBleCommandTable, Cmd); +} + +static command_t BwmCommandTable[] = { + {"help", CmdHelpBwm, AlwaysAvailable, "This help"}, + {"autooff", CmdBwmAutoOff, IfBwm, "Show/set auto power-off (USB unplug, idle on battery)"}, + {"ble", CmdBwmBle, IfBwm, "{ BLE: on/off, pairing, bonded devices, TX power... }"}, + {"charge", CmdBwmCharge, IfBwm, "Enable/disable battery charging (one-shot)"}, + {"name", CmdBwmName, IfBwm, "Get/set the BWM BLE advertising name"}, + {"powersave", CmdBwmPowerSave, IfBwm, "Show/set the BWM power-save switch (DFS, light sleep, slow adv)"}, + {"setcap", CmdBwmSetCap, IfBwm, "Set fuel-gauge design capacity (run once after battery change)"}, + {"upgrade", CmdBWMUpgrade, IfBwm, "Reflash BWM (ESP32) firmware over the BWM link, no header"}, + {"vchg", CmdBwmVchg, IfBwm, "Set charger charge-voltage target (default 4100 mV)"}, + {"wifi", CmdBWMWifi, IfBwm, "Bring up WiFi (STA + TCP server) for a tcp: connection"}, + {"wifipower", CmdBwmWifiPower, IfBwm, "WiFi fully off, or the modem power-save type (none/min/max)"}, + {NULL, NULL, NULL, NULL} +}; + +static int CmdHelpBwm(const char *Cmd) { + (void)Cmd; + CmdsHelp(BwmCommandTable); + return PM3_SUCCESS; +} + +int CmdBwm(const char *Cmd) { + clearCommandBuffer(); + return CmdsParse(BwmCommandTable, Cmd); +} diff --git a/client/src/cmdbwm.h b/client/src/cmdbwm.h new file mode 100644 index 000000000..bef3de7e9 --- /dev/null +++ b/client/src/cmdbwm.h @@ -0,0 +1,26 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// BWM (battery/wireless module) commands +//----------------------------------------------------------------------------- + +#ifndef CMDBWM_H__ +#define CMDBWM_H__ + +#include "common.h" + +int CmdBwm(const char *Cmd); + +#endif diff --git a/client/src/cmddata.c b/client/src/cmddata.c index 411515da9..3581c57d6 100644 --- a/client/src/cmddata.c +++ b/client/src/cmddata.c @@ -1883,6 +1883,13 @@ int getSamplesFromBufEx(uint8_t *data, size_t sample_num, uint8_t bits_per_sampl size_t max_num = MIN(sample_num, MAX_GRAPH_TRACE_LEN); + if (sample_num > MAX_GRAPH_TRACE_LEN) { + PrintAndLogEx(WARNING, "graph buffer holds " _YELLOW_("%d") " samples, dropping the last " _YELLOW_("%zu") + , MAX_GRAPH_TRACE_LEN + , sample_num - MAX_GRAPH_TRACE_LEN + ); + } + if (bits_per_sample < 8) { if (verbose) PrintAndLogEx(INFO, "Unpacking..."); @@ -2778,8 +2785,7 @@ static int try_detect_modulation(void) { clk = GetPskClock("", false); if (clk > 0) { // allow undo - buffer_savestate_t saveState = save_bufferS32(g_GraphBuffer, g_GraphTraceLen); - saveState.offset = g_GridOffset; + buffer_savestate_t saveState = save_graphbuffer(); // skip first 160 samples to allow antenna to settle in (psk gets inverted occasionally otherwise) CmdLtrim("-i 160"); if ((PSKDemod(0, 0, 6, false) == PM3_SUCCESS)) { @@ -2791,8 +2797,8 @@ static int try_detect_modulation(void) { tests[hits].carrier = GetPskCarrier(false); } //undo trim samples - restore_bufferS32(saveState, g_GraphBuffer); - g_GridOffset = saveState.offset; + restore_graphbuffer(saveState); + free_buffer_savestate(saveState); } } diff --git a/client/src/cmdflashmemspiffs.c b/client/src/cmdflashmemspiffs.c index 2176913aa..89acb7d62 100644 --- a/client/src/cmdflashmemspiffs.c +++ b/client/src/cmdflashmemspiffs.c @@ -22,6 +22,7 @@ #include "pmflash.h" #include "fileutils.h" //saveFile #include "comms.h" //getfromdevice +#include "util_posix.h" // msclock #include "cliparser.h" static int CmdHelp(const char *Cmd); @@ -41,9 +42,25 @@ int flashmem_spiffs_load(const char *destfn, const uint8_t *data, size_t datalen // fast push mode g_conn.block_after_ACK = true; + // One packet per frame, not per 256 byte flash page. SPIFFS pages the data + // itself, so FLASH_MEM_BLOCK_SIZE was never a transport limit - and every + // packet costs a SPIFFS_open() by name, which walks the object lookup tables + // of the whole filesystem. Measured on a 2MB (PM5) filesystem, storing 512KB + // reads 243MB of flash at 256 bytes a packet against 16MB at 4029 + uint32_t max_packet = FLASH_MEM_BLOCK_SIZE; + if (g_conn.max_cmd_data_size > sizeof(flashmem_write_t)) { + max_packet = g_conn.max_cmd_data_size - sizeof(flashmem_write_t); + } + + // inline feedback. Time based, not byte based: SPIFFS garbage collection can + // make a single packet take seconds on a full filesystem, and a counter that + // only moves every 16 packets is indistinguishable from a hang + const bool show_progress = (datalen > max_packet); + uint64_t last_update = 0; + while (bytes_remaining > 0) { - uint32_t bytes_in_packet = MIN(FLASH_MEM_BLOCK_SIZE, bytes_remaining); + uint32_t bytes_in_packet = MIN(max_packet, bytes_remaining); flashmem_write_t *payload = calloc(1, sizeof(flashmem_write_t) + bytes_in_packet); if (payload == NULL) { @@ -69,9 +86,6 @@ int flashmem_spiffs_load(const char *destfn, const uint8_t *data, size_t datalen free(payload); - bytes_remaining -= bytes_in_packet; - bytes_sent += bytes_in_packet; - uint8_t retry = 3; while (WaitForResponseTimeout(CMD_SPIFFS_WRITE, &resp, 2000) == false) { PrintAndLogEx(WARNING, "timeout while waiting for reply"); @@ -81,9 +95,38 @@ int flashmem_spiffs_load(const char *destfn, const uint8_t *data, size_t datalen goto out; } } + + // the device only counts a packet once SPIFFS took it + if (resp.status != PM3_SUCCESS) { + int32_t serr = (resp.length >= sizeof(int32_t)) ? (int32_t)resp.data.asDwords[0] : 0; + if (show_progress) { + PrintAndLogEx(NORMAL, ""); + } + PrintAndLogEx(FAILED, "device refused the write at " _YELLOW_("%u") " / " _YELLOW_("%zu") " bytes (spiffs errno %d)", bytes_sent, datalen, serr); + if (serr == SPIFFS_ERR_FULL_RDV) { + PrintAndLogEx(HINT, "Hint: filesystem is full, try `" _YELLOW_("mem spiffs tree") "` and remove what you don't need"); + } + ret_val = PM3_EFLASH; + goto out; + } + + bytes_remaining -= bytes_in_packet; + bytes_sent += bytes_in_packet; + + if (show_progress && ((msclock() - last_update > 100) || (bytes_remaining == 0))) { + PrintAndLogEx(INPLACE, "Sent " _YELLOW_("%u") " / " _YELLOW_("%zu") " bytes (" _YELLOW_("%u") "%%)" + , bytes_sent + , datalen + , (uint32_t)((bytes_sent * 100) / datalen) + ); + last_update = msclock(); + } } out: + if (show_progress) { + PrintAndLogEx(NORMAL, ""); + } clearCommandBuffer(); // turn off fast push mode @@ -532,9 +575,9 @@ static int CmdFlashMemSpiFFSUpload(const char *Cmd) { if (res == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "Wrote "_GREEN_("%zu") " bytes to file "_GREEN_("%s"), datalen, dst); + PrintAndLogEx(HINT, "Hint: Try `" _YELLOW_("mem spiffs tree") "` to verify"); } - PrintAndLogEx(HINT, "Hint: Try `" _YELLOW_("mem spiffs tree") "` to verify"); return res; } diff --git a/client/src/cmdfpga.c b/client/src/cmdfpga.c index 0cddbc290..76830373a 100644 --- a/client/src/cmdfpga.c +++ b/client/src/cmdfpga.c @@ -138,8 +138,8 @@ static int CmdFpgaSetPowerPWM(const char *Cmd) { arg_param_begin, arg_lit0("l", "lf", "Set the driver voltage for LF. When not specified as LF, default setting for HF."), arg_int0("c", "count", "", "PWM output low level counting used to control the voltage of the driver. " - "The larger the value, the higher the voltage; " - "the smaller the value, the lower the voltage."), + "The larger the value, the higher the voltage; " + "the smaller the value, the lower the voltage."), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, false); diff --git a/client/src/cmdhf.c b/client/src/cmdhf.c index 245853457..364bc6f43 100644 --- a/client/src/cmdhf.c +++ b/client/src/cmdhf.c @@ -93,7 +93,7 @@ int CmdHFSearch(const char *Cmd) { uint8_t success[COUNT_OF_PROTOCOLS] = {0}; PROMPT_CLEARLINE; - PrintAndLogEx(INPLACE, " Searching for ThinFilm tag..."); + PrintAndLogEx(INPLACE, "Searching for ThinFilm tag..."); if (IfPm3NfcBarcode()) { if (infoThinFilm(false) == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "\nValid " _GREEN_("Thinfilm tag") " found\n"); @@ -103,7 +103,7 @@ int CmdHFSearch(const char *Cmd) { } PROMPT_CLEARLINE; - PrintAndLogEx(INPLACE, " Searching for Topaz tag..."); + PrintAndLogEx(INPLACE, "Searching for Topaz tag..."); if (IfPm3Iso14443a()) { if (readTopazUid(false, false) == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "\nValid " _GREEN_("Topaz tag") " found\n"); @@ -113,7 +113,7 @@ int CmdHFSearch(const char *Cmd) { } PROMPT_CLEARLINE; - PrintAndLogEx(INPLACE, " Searching for LTO-CM tag..."); + PrintAndLogEx(INPLACE, "Searching for LTO-CM tag..."); if (IfPm3Iso14443a()) { if (reader_lto(false, false) == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "\nValid " _GREEN_("LTO-CM tag") " found\n"); @@ -123,7 +123,7 @@ int CmdHFSearch(const char *Cmd) { } PROMPT_CLEARLINE; - PrintAndLogEx(INPLACE, " Searching for ISO14443-A tag..."); + PrintAndLogEx(INPLACE, "Searching for ISO14443-A tag..."); if (IfPm3Iso14443a()) { int sel_state = infoHF14A(false, false, false); if (sel_state > 0) { @@ -152,7 +152,7 @@ int CmdHFSearch(const char *Cmd) { */ PROMPT_CLEARLINE; - PrintAndLogEx(INPLACE, " Searching for LEGIC tag..."); + PrintAndLogEx(INPLACE, "Searching for LEGIC tag..."); if (IfPm3Legicrf()) { if (readLegicUid(false, false) == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "\nValid " _GREEN_("LEGIC Prime tag") " found\n"); @@ -163,7 +163,7 @@ int CmdHFSearch(const char *Cmd) { // texkom PROMPT_CLEARLINE; - PrintAndLogEx(INPLACE, " Searching for TEXKOM tag..."); + PrintAndLogEx(INPLACE, "Searching for TEXKOM tag..."); if (read_texkom_uid(false, false) == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "\nValid " _GREEN_("TEXKOM tag") " found\n"); success[PROTO_TEXKOM] = true; @@ -172,7 +172,7 @@ int CmdHFSearch(const char *Cmd) { // xerox PROMPT_CLEARLINE; - PrintAndLogEx(INPLACE, " Searching for Fuji/Xerox tag..."); + PrintAndLogEx(INPLACE, "Searching for Fuji/Xerox tag..."); if (IfPm3Iso14443b()) { if (read_xerox_uid(false, false) == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "\nValid " _GREEN_("Fuji/Xerox tag") " found\n"); @@ -183,7 +183,7 @@ int CmdHFSearch(const char *Cmd) { // 14b is the longest test PROMPT_CLEARLINE; - PrintAndLogEx(INPLACE, " Searching for ISO14443-B tag..."); + PrintAndLogEx(INPLACE, "Searching for ISO14443-B tag..."); if (IfPm3Iso14443b()) { if (readHF14B(false, false, false) == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "\nValid " _GREEN_("ISO 14443-B tag") " found\n"); @@ -195,7 +195,7 @@ int CmdHFSearch(const char *Cmd) { // OBS! This triggers a swap to FPGA_BITSTREAM_HF_15 == 1.5sec delay PROMPT_CLEARLINE; - PrintAndLogEx(INPLACE, " Searching for ISO15693 tag..."); + PrintAndLogEx(INPLACE, "Searching for ISO15693 tag..."); if (IfPm3Iso15693()) { if (readHF15Uid(false, true)) { PrintAndLogEx(SUCCESS, "Valid " _GREEN_("ISO 15693 tag") " found\n"); @@ -205,7 +205,7 @@ int CmdHFSearch(const char *Cmd) { } PROMPT_CLEARLINE; - PrintAndLogEx(INPLACE, " Searching for iCLASS / PicoPass tag..."); + PrintAndLogEx(INPLACE, "Searching for iCLASS / PicoPass tag..."); if (IfPm3Iclass()) { if (read_iclass_csn(false, false, false) == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "\nValid " _GREEN_("iCLASS tag / PicoPass tag") " found\n"); @@ -217,7 +217,7 @@ int CmdHFSearch(const char *Cmd) { // OBS! This triggers a swap to FPGA_BITSTREAM_HF_FELICA == 1.5sec delay PROMPT_CLEARLINE; - PrintAndLogEx(INPLACE, " Searching for FeliCa tag..."); + PrintAndLogEx(INPLACE, "Searching for FeliCa tag..."); if (IfPm3Felica()) { if (read_felica_uid(false, false) == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "\nValid " _GREEN_("ISO 18092 / FeliCa tag") " found\n"); @@ -232,7 +232,7 @@ int CmdHFSearch(const char *Cmd) { /* PROMPT_CLEARLINE; - PrintAndLogEx(INPLACE, " Searching for CryptoRF tag..."); + PrintAndLogEx(INPLACE, "Searching for CryptoRF tag..."); if (IfPm3Iso14443b()) { if (readHFCryptoRF(false, false) == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "\nValid " _GREEN_("CryptoRF tag") " found\n"); @@ -374,13 +374,13 @@ int CmdHFTune(const char *Cmd) { return PM3_ETIMEOUT; } - // All three modes of this command answer under the same command id + // All three modes of this command answer under the same command id // and there is no sequence number if ((resp.status != PM3_SUCCESS) || (resp.length != 0)) { PrintAndLogEx(WARNING, "unexpected reply to HF initialization (status %d, %u bytes)", resp.status, (unsigned)resp.length - ); + ); } mode[0] = 2; diff --git a/client/src/cmdhf14a.c b/client/src/cmdhf14a.c index 808f39d2c..124420f29 100644 --- a/client/src/cmdhf14a.c +++ b/client/src/cmdhf14a.c @@ -735,7 +735,7 @@ int Hf14443_4aGetCardData(iso14a_card_select_t *card) { // Annex C uses CRC-B and continuous frames without parity. static int hf14a_timeslot_exchange(const uint8_t *data, uint16_t len, bool request, - PacketResponseNG *resp, uint16_t *rlen) { + PacketResponseNG *resp, uint16_t *rlen) { uint8_t frame[11]; if (len > sizeof(frame) - 2) { return PM3_EINVARG; @@ -753,7 +753,7 @@ static int hf14a_timeslot_exchange(const uint8_t *data, uint16_t len, bool reque clearCommandBuffer(); // Timeouts in 128/fc units; inter-frame delay in microseconds. SendIso14aReaderEx(flags, frame, len, len, request ? 7 : 0, - request ? 79 : 547, request ? 0 : 1100); + request ? 79 : 547, request ? 0 : 1100); if (WaitForIso14aReply(resp, 1500, rlen, NULL) == false || *rlen == 0) { return PM3_ETIMEOUT; } @@ -2049,20 +2049,28 @@ static int CmdHF14AAntiFuzz(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hf 14a antifuzz", - "Tries to fuzz the ISO14443a anticollision phase", - "hf 14a antifuzz -4\n"); + "Tries to fuzz the ISO14443a anticollision phase.\n" + "Default keeps the cascade bit set in every SAK, so the reader asks for\n" + "one more cascade level until its UID buffer gives up. With --coll only\n" + "the first UID byte goes out clean and every bit after it collides, so the\n" + "reader has to resolve 24 bits one round trip at a time; it is then given a\n" + "BCC that checks out, and the SAK sends it round again one level deeper.", + "hf 14a antifuzz -4\n" + "hf 14a antifuzz --10 --coll\n"); void *argtable[] = { arg_param_begin, - arg_lit0("4", NULL, "4 byte uid"), - arg_lit0("7", NULL, "7 byte uid"), - arg_lit0(NULL, "10", "10 byte uid"), + arg_lit0("4", NULL, "4 byte uid"), + arg_lit0("7", NULL, "7 byte uid"), + arg_lit0(NULL, "10", "10 byte uid"), + arg_lit0(NULL, "coll", "collision storm instead of cascade overflow"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, false); struct { uint8_t flag; + uint8_t mode; } PACKED param; param.flag = 0; FLAG_SET_UID_IN_DATA(param.flag, 4); @@ -2072,10 +2080,32 @@ static int CmdHF14AAntiFuzz(const char *Cmd) { if (arg_get_lit(ctx, 3)) { FLAG_SET_UID_IN_DATA(param.flag, 10); } + param.mode = arg_get_lit(ctx, 4) ? ANTIFUZZ_MODE_COLLISION : ANTIFUZZ_MODE_CASCADE; CLIParserFree(ctx); clearCommandBuffer(); SendCommandNG(CMD_HF_ISO14443A_ANTIFUZZ, (uint8_t *)¶m, sizeof(param)); + + PrintAndLogEx(INFO, "Press " _GREEN_("pm3 button") " or " _GREEN_("") " to abort"); + + PacketResponseNG resp; + bool keypress = kbd_enter_pressed(); + while (keypress == false) { + keypress = kbd_enter_pressed(); + + if (WaitForResponseTimeout(CMD_HF_ISO14443A_ANTIFUZZ, &resp, 500)) { + break; + } + } + + if (keypress) { + // inform device to break the fuzz loop since the client has exited + SendCommandNG(CMD_BREAK_LOOP, NULL, 0); + WaitForResponse(CMD_HF_ISO14443A_ANTIFUZZ, &resp); + } + + PrintAndLogEx(INFO, "Done!"); + PrintAndLogEx(HINT, "Hint: Try `" _YELLOW_("hf 14a list") "` to view the fuzzed anticollision"); return PM3_SUCCESS; } @@ -2964,9 +2994,11 @@ int infoHF14A(bool verbose, bool do_nack_test, bool do_aid_search) { return PM3_ETIMEOUT; } - memcpy(card.ats, resp.data.asBytes, rlen_2863); - card.ats_len = rlen_2863; // note: ats_len includes CRC Bytes - if (card.ats_len > 3) { + // Only a well formed ATS, TL plus the bytes TL counts plus CRC, means the + // PICC entered ISO14443-4. A 4 bit NAK to RATS is not an ATS. + if ((rlen_2863 > 3) && (resp.data.asBytes[0] == rlen_2863 - 2)) { + memcpy(card.ats, resp.data.asBytes, rlen_2863); + card.ats_len = rlen_2863; // note: ats_len includes CRC Bytes select_status = 4; } } @@ -3222,7 +3254,7 @@ int infoHF14A(bool verbose, bool do_nack_test, bool do_aid_search) { int16_t fsci = card.ats[1] & 0x0f; PrintAndLogEx(INFO, " ..." _YELLOW_("%02X") "............ T0 TA1 is%s present, TB1 is%s present, " - "TC1 is%s present, FSCI is %d (FSC = %d)", + "TC1 is%s present, FSCI is %d (FSC = %d)", card.ats[1], (ta1 ? "" : _RED_(" NOT")), (tb1 ? "" : _RED_(" NOT")), @@ -3244,7 +3276,7 @@ int infoHF14A(bool verbose, bool do_nack_test, bool do_aid_search) { if (strlen(ds) != 0) ds[strlen(ds) - 2] = '\0'; if (strlen(dr) != 0) dr[strlen(dr) - 2] = '\0'; PrintAndLogEx(INFO, " ......" _YELLOW_("%02X") "......... TA1 different divisors are%s supported, " - "DR: [%s], DS: [%s]", + "DR: [%s], DS: [%s]", card.ats[pos], ((card.ats[pos] & 0x80) ? _RED_(" NOT") : ""), dr, diff --git a/client/src/cmdhf14b.c b/client/src/cmdhf14b.c index 2f4432e6f..01adb3097 100644 --- a/client/src/cmdhf14b.c +++ b/client/src/cmdhf14b.c @@ -37,6 +37,7 @@ #include "cmdhf.h" // handle HF plot #include "atrs.h" // atqbToEmulatedAtr #include "pla.h" // ECP parsing +#include "parsers/parsemykey.h" // MyKey / COGES #define MAX_14B_TIMEOUT_MS (4949U) @@ -922,6 +923,18 @@ static void print_sr_blocks(uint8_t *data, size_t len, const uint8_t *uid, bool print_footer(); } +// Everything `hf 14b view` shows for an SRx tag once the block data is in hand. +// Shared so a dump read straight off the card gets the same treatment as one +// loaded from a file - the MyKey decode used to be reachable only via a file. +static void sr_view_dump(uint8_t *data, size_t len, const uint8_t *uid, bool dense_output) { + + print_sr_blocks(data, len, uid, dense_output); + + if (is_valid_mykey_card(data, len)) { + (void)mykey_parser_parse(data, len, uid); + } +} + static void print_std_blocks(uint8_t *data, size_t len, const uint8_t *uid, uint8_t uidlen, bool dense_output) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(INFO, "-------- " _CYAN_("ISO14443-B Standard tag memory") " ---------"); @@ -2483,7 +2496,7 @@ static int CmdHF14BDump(const char *Cmd) { return PM3_ESOFT; } - print_sr_blocks(data, cardsize, card.uid, dense_output); + sr_view_dump(data, cardsize, card.uid, dense_output); if (nosave) { PrintAndLogEx(INFO, "Called with no save option"); @@ -2619,153 +2632,6 @@ static int CmdHF14BRestore(const char *Cmd) { return PM3_SUCCESS; } -/* - -static uint32_t srix4kEncode(uint32_t value) { - // vv = value - // pp = position - // vv vv vv pp - // 4 bytes : 00 1A 20 01 - // only the lower crumbs. - uint8_t block = (value & 0xFF); - uint8_t i = 0; - uint8_t valuebytes[] = {0, 0, 0}; - Uint3byteToMemBe(valuebytes, value >> 8); - - uint32_t value_x = (value >> 8); - PrintAndLogEx(INFO, "value...... %08x %06x", value, value_x); - PrintAndLogEx(INFO, "3b value... %s", sprint_hex_inrow(valuebytes, sizeof(valuebytes))); - PrintAndLogEx(INFO, "block no... %02x", block); - - // Scrambled part - // Crumb swapping of value. - uint32_t foo = 0; - foo |= CRUMB(value_x, 22) << 28; - foo |= CRUMB(value_x, 14) << 26; - foo |= CRUMB(value_x, 6) << 24; - - foo |= CRUMB(value_x, 20) << 20; - foo |= CRUMB(value_x, 12) << 18; - foo |= CRUMB(value_x, 4) << 16; - - foo |= CRUMB(value_x, 18) << 12; - foo |= CRUMB(value_x, 10) << 10; - foo |= CRUMB(value_x, 2) << 8; - - foo |= CRUMB(value_x, 16) << 4; - foo |= CRUMB(value_x, 8) << 2; - foo |= CRUMB(value_x, 0) << 0; - - PrintAndLogEx(INFO, "hex........ %02x %02x %02x", CRUMB(value_x, 22), CRUMB(value_x, 14), CRUMB(value_x, 6)); - PrintAndLogEx(INFO, "hex........ %02x %02x %02x", CRUMB(value_x, 20), CRUMB(value_x, 12), CRUMB(value_x, 4)); - PrintAndLogEx(INFO, "hex........ %02x %02x %02x", CRUMB(value_x, 18), CRUMB(value_x, 10), CRUMB(value_x, 2)); - PrintAndLogEx(INFO, "hex........ %02x %02x %02x", CRUMB(value_x, 16), CRUMB(value_x, 8), CRUMB(value_x, 0)); - - PrintAndLogEx(INFO, "hex........ %08x", foo); - - // chksum part - uint32_t chksum = 0xFF - block; - - // chksum is reduced by each nibbles of value. - for (i = 0; i < 3; ++i) { - chksum -= NIBBLE_HIGH(valuebytes[i]); - chksum -= NIBBLE_LOW(valuebytes[i]); - } - - // base4 conversion and left shift twice - i = 3; - uint8_t base4[] = {0, 0, 0, 0}; - while (chksum != 0) { - base4[i--] = (chksum % 4 << 2); - chksum /= 4; - } - PrintAndLogEx(INFO, "%s", sprint_hex_inrow(base4, sizeof(base4))); - - // merge scambled and chksum parts - uint32_t encvalue = 0; - - (NIBBLE_LOW(base4[0]) << 28) | - (NIBBLE_HIGH(temp[0]) << 24) | - - (NIBBLE_LOW(base4[1]) << 20) | - (NIBBLE_LOW(temp[0]) << 16) | - - (NIBBLE_LOW(base4[2]) << 12) | - (NIBBLE_HIGH(temp[1]) << 8) | - - (NIBBLE_LOW(base4[3]) << 4) | - NIBBLE_LOW(temp[1]); - - PrintAndLogEx(NORMAL, "ICE encoded | %08X -> %08X", value, encvalue); - return encvalue; -} -*/ - -static uint32_t srix4k_decode_counter(uint32_t num) { - uint32_t value = ~num; - ++value; - return value; -} -/* -static uint32_t srix4kDecode(uint32_t value) { - switch (value) { - case 0xC04F42C5: - return 0x003139; - case 0xC1484807: - return 0x002943; - case 0xC0C60848: - return 0x001A20; - } - return 0; -} -*/ - -static uint32_t srix4k_get_magicbytes(uint64_t uid, uint32_t block6, uint32_t block18, uint32_t block19) { -#define MASK 0xFFFFFFFF; - uint32_t uid32 = uid & MASK; - uint32_t counter = srix4k_decode_counter(block6); - uint32_t decodedBlock18 = 0; - uint32_t decodedBlock19 = 0; -// uint32_t decodedBlock18 = srix4kDecode(block18); -// uint32_t decodedBlock19 = srix4kDecode(block19); - uint32_t doubleBlock = (decodedBlock18 << 16 | decodedBlock19) + 1; - - uint32_t result = (uid32 * doubleBlock * counter) & MASK; - PrintAndLogEx(SUCCESS, "Magic bytes | %08X", result); - return result; -} - -static int CmdSRIX4kValid(const char *Cmd) { - CLIParserContext *ctx; - CLIParserInit(&ctx, "hf 14b valid", - "SRIX checksum test", - "hf 14b valid\n" - ); - - void *argtable[] = { - arg_param_begin, - arg_param_end - }; - CLIExecWithReturn(ctx, Cmd, argtable, false); - CLIParserFree(ctx); - - uint64_t uid = 0xD00202501A4532F9; - uint32_t block6 = 0xFFFFFFFF; - uint32_t block18 = 0xC04F42C5; - uint32_t block19 = 0xC1484807; - uint32_t block21 = 0xD1BCABA4; - - uint32_t test_b18 = 0x001A2001; // 0x00313918; - uint32_t test_b18_enc = 0; - // uint32_t test_b18_enc = srix4kEncode(test_b18); - // uint32_t test_b18_dec = srix4kDecode(test_b18_enc); - PrintAndLogEx(SUCCESS, "ENCODE & CHECKSUM | %08X -> %08X (%s)", test_b18, test_b18_enc, ""); - - uint32_t magic = srix4k_get_magicbytes(uid, block6, block18, block19); - PrintAndLogEx(SUCCESS, "BLOCK 21 | %08X -> %08X (no XOR)", block21, magic ^ block21); - return PM3_SUCCESS; -} - int select_card_14443b_4(bool disconnect, iso14b_card_select_t *card) { if (card) { memset(card, 0, sizeof(iso14b_card_select_t)); @@ -3132,7 +2998,7 @@ static int CmdHF14BAPDU(const char *Cmd) { arg_lit0("t", "tlv", "executes TLV decoder if it possible"), arg_lit0(NULL, "decode", "decode apdu request if it possible"), arg_str0("m", "make", "", "make apdu with head from this field and data from data field.\n" - " must be 4 bytes: "), + " must be 4 bytes: "), arg_lit0("e", "extended", "make extended length apdu if `m` parameter included"), arg_int0("l", "le", "", "Le apdu parameter if `m` parameter included"), arg_str1("d", "data", "", " if `m` parameter included"), @@ -3471,13 +3337,15 @@ static int CmdHF14BView(const char *Cmd) { "note:\n" " - command expects the filename to contain a UID\n" " which is needed to determine card memory type", - "hf 14b view -f hf-14b-01020304-dump.bin" + "hf 14b view -f hf-14b-01020304-dump.bin\n" + "hf 14b view --selftest" ); void *argtable[] = { arg_param_begin, - arg_str1("f", "file", "", "Specify a filename for dump file"), + arg_str0("f", "file", "", "Specify a filename for dump file"), arg_lit0("v", "verbose", "verbose output"), arg_lit0("z", "dense", "dense dump output style"), + arg_lit0(NULL, "selftest", "Run the dump parsers self tests and exit"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, false); @@ -3486,8 +3354,18 @@ static int CmdHF14BView(const char *Cmd) { CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen); bool verbose = arg_get_lit(ctx, 2); bool dense_output = (g_session.dense_output || arg_get_lit(ctx, 3)); + bool selftest = arg_get_lit(ctx, 4); CLIParserFree(ctx); + if (selftest) { + return mykey_selftest(); + } + + if (fnlen == 0) { + PrintAndLogEx(ERR, "Specify a filename with `" _YELLOW_("-f") "` or run `" _YELLOW_("--selftest") "`"); + return PM3_EINVARG; + } + // read dump file uint8_t *dump = NULL; size_t bytes_read = (ST25TB_SR_BLOCK_SIZE * 0x100); @@ -3504,7 +3382,7 @@ static int CmdHF14BView(const char *Cmd) { // figure out a way to identify the different dump files. // STD/SR/CT is difference - print_sr_blocks(dump, bytes_read, get_uid_from_filename(filename), dense_output); + sr_view_dump(dump, bytes_read, get_uid_from_filename(filename), dense_output); //print_std_blocks(dump, bytes_read); //print_ct_blocks(dump, bytes_read); @@ -3739,7 +3617,6 @@ static command_t CommandTable[] = { {"wrbl", CmdHF14BSriWrbl, IfPm3Iso14443b, "Write data to a SRI512/SRIX4 tag"}, {"tearoff", CmdHF14BSriTearoff, IfPm3Iso14443b, "Tear-off attack on ST25TB/SRx counter blocks"}, {"view", CmdHF14BView, AlwaysAvailable, "Display content from tag dump file"}, - {"valid", CmdSRIX4kValid, AlwaysAvailable, "SRIX4 checksum test"}, {"---------", CmdHelp, IfPm3Iso14443b, "------------------ " _CYAN_("ASK CTS / C-ticket") " ------------------"}, {"ctdump", CmdHF14BCtsDump, IfPm3Iso14443b, "Dump ASK CTS/C-ticket"}, {"ctrdbl", CmdHF14BCtRdBl, IfPm3Iso14443b, "Read ASK CTS/C-ticket block"}, diff --git a/client/src/cmdhf15.c b/client/src/cmdhf15.c index fa69da62e..3bfa55a05 100644 --- a/client/src/cmdhf15.c +++ b/client/src/cmdhf15.c @@ -49,7 +49,6 @@ #define Logic0 Iso15693Logic0 #define Logic1 Iso15693Logic1 #define FrameEOF Iso15693FrameEOF -#define CARD_MEMORY_SIZE 4096 #ifndef ISO15_ERROR_HANDLING_RESPONSE #define ISO15_ERROR_HANDLING_RESPONSE { \ @@ -3325,79 +3324,6 @@ static int CmdHF15Restore(const char *Cmd) { return PM3_SUCCESS; } -// ISO15693 magic "V3" tag support -#define ISO15_MAGIC_V3_BLK_UID_LO 0x10 -#define ISO15_MAGIC_V3_BLK_UID_HI 0x11 -#define ISO15_MAGIC_V3_BLK_SIG_A 0x14 -#define ISO15_MAGIC_V3_BLK_SIG_B 0x15 - -// signature check in block 0x14/0x15 -static const uint8_t iso15_magic_v3_sig_a[4] = {0xA5, 0x2B, 0x44, 0x2C}; -static const uint8_t iso15_magic_v3_sig_b[4] = {0x21, 0xAE, 0x93, 0x00}; - -// finalize command write in block 0x14/0x15 -// hf 15 raw -wac -d 022114A52B442C -// hf 15 raw -wac -d 02211569E25D00 -static const uint8_t iso15_magic_v3_fin_a[4] = {0xA5, 0x2B, 0x44, 0x2C}; -static const uint8_t iso15_magic_v3_fin_b[4] = {0x69, 0xE2, 0x5D, 0x00}; - -// Read one 4-byte block from a magic V3 tag in unaddressed mode. -static int hf15_magic_v3_read_blk(uint8_t blockno, uint8_t out[4]) { - - uint16_t approxlen = 2 + 1 + 2; - iso15_raw_cmd_t *packet = (iso15_raw_cmd_t *)calloc(1, sizeof(iso15_raw_cmd_t) + approxlen); - if (packet == NULL) { - PrintAndLogEx(WARNING, "Failed to allocate memory"); - return PM3_EMALLOC; - } - - // enforce OPTION flag so we get the lock byte, keeping data at offset 2 - packet->raw[packet->rawlen++] = arg_get_raw_flag(0, true, false, true); - packet->raw[packet->rawlen++] = ISO15693_READBLOCK; - packet->raw[packet->rawlen++] = blockno; - AddCrc15(packet->raw, packet->rawlen); - packet->rawlen += 2; - packet->flags = (ISO15_CONNECT | ISO15_READ_RESPONSE); - - clearCommandBuffer(); - SendCommandNG(CMD_HF_ISO15693_COMMAND, (uint8_t *)packet, ISO15_RAW_LEN(packet->rawlen)); - free(packet); - - PacketResponseNG resp; - if (WaitForResponseTimeout(CMD_HF_ISO15693_COMMAND, &resp, 2000) == false) { - PrintAndLogEx(DEBUG, "iso15693 timeout"); - return PM3_ETIMEOUT; - } - - ISO15_ERROR_HANDLING_RESPONSE - - uint8_t *d = resp.data.asBytes; - - ISO15_ERROR_HANDLING_CARD_RESPONSE(d, resp.length) - - memcpy(out, d + 2, 4); - return PM3_SUCCESS; -} - -// Write one 4-byte block to a magic V3 tag in unaddressed mode. -static int hf15_magic_v3_write_blk(uint8_t blockno, const uint8_t *data) { - uint16_t flags = arg_get_raw_flag(0, true, false, false); - return hf_15_write_blk(NULL, flags, NULL, true, blockno, data, 4); -} - -// Detect an un-finalized magic V3 tag by its configuration-mode signature. -static bool hf15_magic_v3_is_config_mode(void) { - uint8_t a[4] = {0}; - uint8_t b[4] = {0}; - if (hf15_magic_v3_read_blk(ISO15_MAGIC_V3_BLK_SIG_A, a) != PM3_SUCCESS) { - return false; - } - if (hf15_magic_v3_read_blk(ISO15_MAGIC_V3_BLK_SIG_B, b) != PM3_SUCCESS) { - return false; - } - return (memcmp(a, iso15_magic_v3_sig_a, 4) == 0) && (memcmp(b, iso15_magic_v3_sig_b, 4) == 0); -} - /** * Commandline handling: HF15 CMD CSETUID * Set UID for magic Chinese card @@ -3407,6 +3333,8 @@ static int CmdHF15CSetUID(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hf 15 csetuid", "Set UID for magic Chinese card (only works with such cards)\n" + "Gen1 and V3 probe their backdoor blocks first and refuse to write if they\n" + "read back real data, to avoid corrupting a normal (non-magic) tag.\n" "For magic 'V3' tags this writes the UID configuration only and is repeatable;\n" "run `" _YELLOW_("hf 15 cfinalize") "` afterwards to lock the UID permanently.", "hf 15 csetuid -u E011223344556677 -> use gen1 command\n" @@ -3460,38 +3388,50 @@ static int CmdHF15CSetUID(const char *Cmd) { PrintAndLogEx(INFO, "Writing..."); - if (use_v3) { - /* - for example id: E011223344556677 - [=] 16 | 77 66 55 44 | 0 | wfUD - [=] 17 | 33 22 11 E0 | 0 | 3".. - */ - uint8_t blk_lo[4] = {0}; - uint8_t blk_hi[4] = {0}; - reverse_array_copy(payload.uid + 4, 4, blk_lo); - reverse_array_copy(payload.uid, 4, blk_hi); + PacketResponseNG resp; + clearCommandBuffer(); - if (hf15_magic_v3_write_blk(ISO15_MAGIC_V3_BLK_UID_LO, blk_lo) != PM3_SUCCESS || - hf15_magic_v3_write_blk(ISO15_MAGIC_V3_BLK_UID_HI, blk_hi) != PM3_SUCCESS) { - PrintAndLogEx(FAILED, "Setting new UID ( " _RED_("fail") " )"); - PrintAndLogEx(NORMAL, ""); - return PM3_ESOFT; - } + uint16_t cmd = CMD_HF_ISO15693_CSETUID; + if (use_v2) { + cmd = CMD_HF_ISO15693_CSETUID_V2; + } else if (use_v3) { + cmd = CMD_HF_ISO15693_CSETUID_V3; + } - } else { - PacketResponseNG resp; - clearCommandBuffer(); + SendCommandNG(cmd, (uint8_t *)&payload, sizeof(payload)); + if (WaitForResponseTimeout(cmd, &resp, 2000) == false) { + PrintAndLogEx(WARNING, "timeout while waiting for reply"); + DropField(); + return PM3_ESOFT; + } - uint16_t cmd = CMD_HF_ISO15693_CSETUID; - if (use_v2) { - cmd = CMD_HF_ISO15693_CSETUID_V2; - } + // Gen1 and V3 identify the tag and verify the new UID on the device, V2 has neither + if (use_v2 == false) { - SendCommandNG(cmd, (uint8_t *)&payload, sizeof(payload)); - if (WaitForResponseTimeout(cmd, &resp, 2000) == false) { - PrintAndLogEx(WARNING, "timeout while waiting for reply"); - DropField(); - return PM3_ESOFT; + switch (resp.status) { + case PM3_SUCCESS: + break; + + case PM3_ETIMEOUT: + PrintAndLogEx(FAILED, "no tag found"); + return PM3_ESOFT; + + case PM3_EWRONGANSWER: + if (use_v3) { + PrintAndLogEx(FAILED, "tag is not an un-finalized magic " _YELLOW_("V3") " tag"); + PrintAndLogEx(HINT, "Hint: signature in blocks 0x14/0x15 not found"); + PrintAndLogEx(HINT, "already finalized or not a V3 tag"); + } else { + PrintAndLogEx(FAILED, "tag doesn't look like a blank/magic " _YELLOW_("Gen1") " tag ( " _RED_("fail") " )"); + PrintAndLogEx(HINT, "Hint: block 0x38/0x39/0x3E/0x3F must be unreadable or blank"); + PrintAndLogEx(HINT, "refusing to risk overwriting a normal tag"); + } + return PM3_ESOFT; + + default: + PrintAndLogEx(FAILED, "Setting new UID ( " _RED_("fail") " )"); + PrintAndLogEx(NORMAL, ""); + return PM3_ESOFT; } } @@ -3526,8 +3466,8 @@ static int CmdHF15CFinalize(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hf 15 cfinalize", "Finalize a magic ISO15693 'V3' tag.\n" - _RED_("This operation is irreversible.") " After finalize the configuration\n" - "area is erased and the UID can no longer be changed. Set the UID with\n" + _RED_("This operation is irreversible.") " It locks the UID for good,\n" + "clears the configuration blocks and shifts the block numbering. Set it with\n" "`" _YELLOW_("hf 15 csetuid --v3") "` first, then lock it in with this command.", "hf 15 cfinalize -y" ); @@ -3541,34 +3481,36 @@ static int CmdHF15CFinalize(const char *Cmd) { bool confirmed = arg_get_lit(ctx, 1); CLIParserFree(ctx); - PrintAndLogEx(INFO, "Get current tag"); - - uint8_t carduid[ISO15693_UID_LENGTH] = {0x00}; - if (getUID(true, false, carduid) != PM3_SUCCESS) { - PrintAndLogEx(FAILED, "no tag found"); - return PM3_ESOFT; - } - - // Safety: only proceed on a tag that is actually an un-finalized magic V3. - // Writing the finalize values to any other tag may permanently brick it. - if (hf15_magic_v3_is_config_mode() == false) { - PrintAndLogEx(FAILED, "tag is not an un-finalized magic " _YELLOW_("V3") " tag"); - PrintAndLogEx(HINT, "Hint: signature in blocks 0x14/0x15 not found - already finalized or not a V3 tag"); - return PM3_ESOFT; - } - - PrintAndLogEx(SUCCESS, "Magic " _GREEN_("V3") " tag in configuration mode ( " _GREEN_("ok") " )"); - if (confirmed == false) { - PrintAndLogEx(WARNING, _RED_("This operation is irreversible!") " The UID will be locked permanently."); + PrintAndLogEx(WARNING, _RED_("This operation is irreversible!") " The UID is locked and the blocks move."); PrintAndLogEx(WARNING, "Add " _YELLOW_("-y") " to confirm and proceed."); return PM3_EINVARG; } PrintAndLogEx(INFO, "Finalizing..."); - if (hf15_magic_v3_write_blk(ISO15_MAGIC_V3_BLK_SIG_A, iso15_magic_v3_fin_a) != PM3_SUCCESS || - hf15_magic_v3_write_blk(ISO15_MAGIC_V3_BLK_SIG_B, iso15_magic_v3_fin_b) != PM3_SUCCESS) { + PacketResponseNG resp; + clearCommandBuffer(); + SendCommandNG(CMD_HF_ISO15693_CFINALIZE_V3, NULL, 0); + if (WaitForResponseTimeout(CMD_HF_ISO15693_CFINALIZE_V3, &resp, 2000) == false) { + PrintAndLogEx(WARNING, "timeout while waiting for reply"); + DropField(); + return PM3_ESOFT; + } + + if (resp.status == PM3_ETIMEOUT) { + PrintAndLogEx(FAILED, "no tag found"); + return PM3_ESOFT; + } + + if (resp.status == PM3_EWRONGANSWER) { + PrintAndLogEx(FAILED, "tag is not an un-finalized magic " _YELLOW_("V3") " tag"); + PrintAndLogEx(HINT, "Hint: signature in blocks 0x14/0x15 not found"); + PrintAndLogEx(HINT, "already finalized or not a V3 tag"); + return PM3_ESOFT; + } + + if (resp.status != PM3_SUCCESS) { PrintAndLogEx(FAILED, "Finalize ( " _RED_("fail") " )"); PrintAndLogEx(NORMAL, ""); return PM3_ESOFT; diff --git a/client/src/cmdhfepa.c b/client/src/cmdhfepa.c index 2cd8092c2..7c0106c39 100644 --- a/client/src/cmdhfepa.c +++ b/client/src/cmdhfepa.c @@ -81,7 +81,7 @@ static int CmdHFEPACollectPACENonces(const char *Cmd) { return PM3_ESOFT; } - const epa_result_t *r = (const epa_result_t *)resp.data.asBytes; + const epa_result_t *r = (const epa_result_t *)(const void *)resp.data.asBytes; if (r->step != 0) { PrintAndLogEx(FAILED, "Error in step %u, Return code: %d", r->step, r->func_return); @@ -211,7 +211,7 @@ static int CmdHFEPAPACEReplay(const char *Cmd) { return PM3_ESOFT; } - const epa_result_t *rr = (const epa_result_t *)resp.data.asBytes; + const epa_result_t *rr = (const epa_result_t *)(const void *)resp.data.asBytes; if (rr->step != 0) { PrintAndLogEx(SUCCESS, "\nPACE replay failed in step %u!", rr->step); @@ -273,7 +273,7 @@ static int CmdHFEPAPACESimulate(const char *Cmd) { return PM3_ESOFT; } - const epa_result_t *sr = (const epa_result_t *)resp.data.asBytes; + const epa_result_t *sr = (const epa_result_t *)(const void *)resp.data.asBytes; const uint32_t *data = sr->timings; if (sr->step != 0) { diff --git a/client/src/cmdhffelica.c b/client/src/cmdhffelica.c index 19a4a3397..9efb6e350 100644 --- a/client/src/cmdhffelica.c +++ b/client/src/cmdhffelica.c @@ -66,6 +66,8 @@ #define FELICA_OPTIONAL_CMD_RETRIES 3U // Per FeliCa spec, Polling max response at 16 timeslots is ~25ms; keep extra margin. #define FELICA_POLLING_TIMEOUT_MS 100U +#define FELICA_READER_SYSTEM_POLL_TIMEOUT_MS 2500U +#define FELICA_READER_SYSTEM_POLL_ATTEMPTS 4U #define FELICA_SEAC_POLL_TIMEOUT_MS 200U #define FELICA_SEAC_POLL_RETRY_COUNT 5U #define FELICA_SEAC_POLL_FRAME_LEN 6U @@ -466,6 +468,7 @@ typedef enum { static int CmdHelp(const char *Cmd); static void clear_and_send_command(uint8_t flags, uint16_t datalen, uint8_t *data, bool verbose); +static void clear_and_send_command_ex(uint8_t flags, uint16_t datalen, uint8_t *data, uint16_t numbits, bool verbose, bool normalize_frame); static int send_felica_payload_with_retries(uint8_t flags, uint16_t datalen, uint8_t *data, bool verbose, int expected_response_cmd, uint32_t timeout_ms, uint32_t retries, uint32_t backoff_ms, bool logging, PacketResponseNG *resp, const char *request_name); @@ -550,10 +553,10 @@ static void print_status_flag1_interpretation(void) { PrintAndLogEx(INFO, "----+--------------------------------------------------------------------------------------------------------------------"); PrintAndLogEx(INFO, " 00 | Indicates the successful completion of a command."); PrintAndLogEx(INFO, " FF | If an error occurs during the processing of a command that includes no list in the command packet, \n" - " | or if an error occurs independently of any list, the card returns a response by setting FFh to Status Flag1."); + " | or if an error occurs independently of any list, the card returns a response by setting FFh to Status Flag1."); PrintAndLogEx(INFO, " XX | If an error occurs while processing a command that includes Service Code List or Block List \n" - " | in the command packet, the card returns a response by setting a number in the list to Status Flag1,\n" - " | indicating the location of the error."); + " | in the command packet, the card returns a response by setting a number in the list to Status Flag1,\n" + " | indicating the location of the error."); PrintAndLogEx(INFO, "----+--------------------------------------------------------------------------------------------------------------------"); } @@ -562,28 +565,28 @@ static void print_status_flag2_interpration(void) { PrintAndLogEx(INFO, "----+--------------------------------------------------------------------------------------------------------------------"); PrintAndLogEx(INFO, " 00 | Indicates the successful completion of a command."); PrintAndLogEx(INFO, " 01 | The calculated result is either less than zero when the purse data is decremented, or exceeds 4\n" - " | Bytes when the purse data is incremented."); + " | Bytes when the purse data is incremented."); PrintAndLogEx(INFO, " 02 | The specified data exceeds the value of cashback data at cashback of purse."); PrintAndLogEx(INFO, " 70 | Memory error (fatal error)."); PrintAndLogEx(INFO, " 71 | The number of memory rewrites exceeds the upper limit (this is only a warning; data writing is performed as normal).\n" - " | The maximum number of rewrites can differ, depending on the product being used.\n" - " | In addition, Status Flag1 is either 00h or FFh depending on the product being used."); + " | The maximum number of rewrites can differ, depending on the product being used.\n" + " | In addition, Status Flag1 is either 00h or FFh depending on the product being used."); PrintAndLogEx(INFO, " A1 | Illegal Number of Service| Number of Service or Number of Node specified by the command \n" - " | falls outside the range of the prescribed value."); + " | falls outside the range of the prescribed value."); PrintAndLogEx(INFO, " A2 | Illegal command packet (specified Number of Block) : Number of Block specified by the \n" - " | command falls outside the range of the prescribed values for the product."); + " | command falls outside the range of the prescribed values for the product."); PrintAndLogEx(INFO, " A3 | Illegal Block List (specified order of Service) : Service Code List Order specified by \n" - " | Block List Element falls outside the Number of Service specified by the command \n" - " | (or the Number of Service specified at the times of mutual authentication)."); + " | Block List Element falls outside the Number of Service specified by the command \n" + " | (or the Number of Service specified at the times of mutual authentication)."); PrintAndLogEx(INFO, " A4 | Illegal Service type : Area Attribute specified by the command or Service Attribute of Service Code is incorrect."); PrintAndLogEx(INFO, " A5 | Access is not allowed : Area or Service specified by the command cannot be accessed.\n" - " | The parameter specified by the command does not satisfy the conditions for success."); + " | The parameter specified by the command does not satisfy the conditions for success."); PrintAndLogEx(INFO, " A6 | Illegal Service Code List : Target to be accessed, identified by Service Code List Order, specified by Block\n" - " | List Element does not exist. Or, Node specified by Node Code List does not exist."); + " | List Element does not exist. Or, Node specified by Node Code List does not exist."); PrintAndLogEx(INFO, " A7 | Illegal Block List (Access Mode) : Access Mode specified by Block List Element is incorrect."); PrintAndLogEx(INFO, " A8 | Illegal Block Number Block Number (access to the specified data is inhibited) :\n" - " | specified by Block List Element exceeds the number of Blocks assigned to Service."); + " | specified by Block List Element exceeds the number of Blocks assigned to Service."); PrintAndLogEx(INFO, " A9 | Data write failure : This is the error that occurs in issuance commands."); PrintAndLogEx(INFO, " AA | Key-change failure : Key change failed."); PrintAndLogEx(INFO, " AB | Illegal Package Parity or illegal Package MAC : This is the error that occurs in issuance commands."); @@ -591,7 +594,7 @@ static void print_status_flag2_interpration(void) { PrintAndLogEx(INFO, " AD | Service exists already : This is the error that occurs in issuance commands."); PrintAndLogEx(INFO, " AE | Illegal System Code : This is the error that occurs in issuance commands."); PrintAndLogEx(INFO, " AF | Too many simultaneous cyclic write operations : Number of simultaneous write Blocks\n" - " | specified by the command to Cyclic Service exceeds the number of Blocks assigned to Service."); + " | specified by the command to Cyclic Service exceeds the number of Blocks assigned to Service."); PrintAndLogEx(INFO, " C0 | Illegal Package Identifier : This is the error that occurs in issuance commands."); PrintAndLogEx(INFO, " C1 | Discrepancy of parameters inside and outside Package : This is the error that occurs in issuance commands."); PrintAndLogEx(INFO, " C2 | Command is disabled already : This is the error that occurs in issuance commands."); @@ -615,16 +618,16 @@ static void print_number_of_service_constraints(void) { static void print_number_of_block_constraints(void) { PrintAndLogEx(INFO, " - Number of Block: shall be less than or equal to the maximum number of Blocks that can be read simultaneously.\n" - " The maximum number of Blocks that can be read simultaneously can differ, depending on the product being used.\n" - " Use as default 01"); + " The maximum number of Blocks that can be read simultaneously can differ, depending on the product being used.\n" + " Use as default 01"); } static void print_service_code_list_constraints(void) { PrintAndLogEx(INFO, " - Service Code List: For Service Code List, only Service Code existing in the product shall be specified:"); PrintAndLogEx(INFO, " - Even when Service Code exists in the product, Service Code not referenced from Block List shall not \n" - " be specified to Service Code List."); + " be specified to Service Code List."); PrintAndLogEx(INFO, " - For existence or nonexistence of Service in a product, please check using the Request Service \n" - " (or Request Service v2) command."); + " (or Request Service v2) command."); } /* @@ -1937,8 +1940,8 @@ static void felica_info_process_system_services(int level, uint8_t flags, json_t *data_json = json_object_get(node_json, "data"); const bool has_data_matchers = json_is_object(data_json) && (json_object_size(data_json) > 0); const size_t matcher_count = felica_parse_service_node_matchers(node_json, - nodes[node_count].matchers, - ARRAYLEN(nodes[node_count].matchers)); + nodes[node_count].matchers, + ARRAYLEN(nodes[node_count].matchers)); if (has_data_matchers && matcher_count == 0) { continue; } @@ -2345,9 +2348,9 @@ static int discover_systems(uint8_t flags, const uint8_t *primary_idm, for (uint32_t attempt = 0; attempt < attempts; attempt++) { felica_syscode_response_t system_code_response; const int request_system_code_status = send_request_system_code(flags, - sizeof(request_system_code_request), (uint8_t *)&request_system_code_request, - false, FELICA_OPTIONAL_CMD_TIMEOUT_MS, 0, false, - &system_code_response); + sizeof(request_system_code_request), (uint8_t *)&request_system_code_request, + false, FELICA_OPTIONAL_CMD_TIMEOUT_MS, 0, false, + &system_code_response); if (request_system_code_status != PM3_SUCCESS) { continue; @@ -2685,27 +2688,79 @@ int read_felica_uid(bool loop, bool verbose) { return res; } +static int read_felica_system(uint16_t system_code, bool loop, bool verbose) { + uint8_t system_bytes[2]; + felica_system_code_to_bytes(system_code, system_bytes); + const uint8_t flags = FELICA_CONNECT | FELICA_CLEARTRACE | FELICA_NO_DISCONNECT | FELICA_SYSTEM_SELECT; + int res = PM3_ETIMEOUT; + + for (uint32_t attempt = 0; loop || attempt < FELICA_READER_SYSTEM_POLL_ATTEMPTS; attempt++) { + clear_and_send_command_ex(flags, sizeof(system_bytes), system_bytes, 0, false, false); + PacketResponseNG resp; + if (WaitForResponseTimeout(CMD_HF_FELICA_COMMAND, &resp, FELICA_READER_SYSTEM_POLL_TIMEOUT_MS) && + resp.status == PM3_SUCCESS && resp.length >= sizeof(felica_card_select_t)) { + felica_card_select_t card; + memcpy(&card, resp.data.asBytes, sizeof(card)); + set_last_known_card(card); + if (verbose) { + PrintAndLogEx(SUCCESS, "IDm: " _GREEN_("%s"), sprint_hex_inrow(card.IDm, sizeof(card.IDm))); + } + res = PM3_SUCCESS; + if (loop == false) { + break; + } + } + if (kbd_enter_pressed()) { + if (res != PM3_SUCCESS) { + res = PM3_EOPABORTED; + } + break; + } + } + + DropField(); + return res; +} + static int CmdHFFelicaReader(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hf felica reader", "Act as a ISO 18092 / FeliCa reader. Look for FeliCa tags until Enter or the pm3 button is pressed", - "hf felica reader -@ -> Continuous mode"); + "hf felica reader -@\n" + "hf felica reader --sys 0003 -@ -> Continuous polling for system 0003"); void *argtable[] = { arg_param_begin, arg_lit0("s", "silent", "silent (no messages)"), arg_lit0("@", NULL, "optional - continuous reader mode"), + arg_str0(NULL, "sys", "", "poll a specific 2-byte system code (4 attempts, or continuous with -@)"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, true); bool verbose = (arg_get_lit(ctx, 1) == false); bool cm = arg_get_lit(ctx, 2); + struct arg_str *system_arg = arg_get_str(ctx, 3); + bool has_system = system_arg->count > 0; + uint8_t system_bytes[2] = {0}; + int system_len = 0; + int parse_status = has_system ? CLIParamHexToBuf(system_arg, system_bytes, sizeof(system_bytes), &system_len) : PM3_SUCCESS; + bool invalid_system = parse_status != PM3_SUCCESS || + (has_system && (strlen(system_arg->sval[0]) != 4 || system_len != 2)); CLIParserFree(ctx); + if (invalid_system) { + PrintAndLogEx(ERR, "System code must be exactly 4 hex digits"); + return PM3_EINVARG; + } + if (cm) { PrintAndLogEx(INFO, "Press " _GREEN_("") " to exit"); } + if (has_system) { + uint16_t system_code = felica_system_code_from_bytes(system_bytes); + return read_felica_system(system_code, cm, verbose); + } return read_felica_uid(cm, verbose); } @@ -5152,7 +5207,7 @@ static int felica_discover_nodes(const uint8_t *idm, bool discovered = false; if (info->method == FELICA_NODE_DISCOVERY_READ_WITHOUT_ENCRYPTION) { discovered = felica_discover_nodes_with_read_without_encryption_ex(flags, idm, retry_count, pmm, - visitor, ctx, &discovered_count, &stop_status); + visitor, ctx, &discovered_count, &stop_status); } else { discovered = info->run(flags, idm, retry_count, visitor, ctx, &discovered_count, &stop_status); } @@ -5313,13 +5368,12 @@ static void felica_scsvcode_print_footer(const felica_scsvcode_context_t *scsv_c return; } - char bar[128]; - size_t pos = 0; - pos += snprintf(bar + pos, sizeof(bar) - pos, "└"); - for (int i = 0; i < scsv_ctx->depth - 1 && pos < sizeof(bar); i++) { - pos += snprintf(bar + pos, sizeof(bar) - pos, "───┴"); + char bar[128] = {0}; + str_append(bar, sizeof(bar), "└"); + for (int i = 0; i < scsv_ctx->depth - 1; i++) { + str_append(bar, sizeof(bar), "───┴"); } - snprintf(bar + pos, sizeof(bar) - pos, "───────────────────────"); + str_append(bar, sizeof(bar), "───────────────────────"); PrintAndLogEx(INFO, "%s", bar); } @@ -7157,7 +7211,8 @@ static int CmdHFFelicaDump(const char *Cmd) { if (res != PM3_SUCCESS || discovered_systems.count == 0) { DropField(); PrintAndLogEx(FAILED, "Unable to discover FeliCa systems."); - return res; + // discovery can succeed and still find nothing, res is PM3_SUCCESS then + return (res != PM3_SUCCESS) ? res : PM3_ESOFT; } PrintAndLogEx(INFO, "Discovered " _GREEN_("%u") " system(s).", (unsigned int)discovered_systems.count); @@ -8369,7 +8424,7 @@ static int CmdHFFelicaSim(const char *Cmd) { arg_param_begin, arg_str1("f", "file", "", "JSON dump file"), arg_str0(NULL, "read-without-encryption-error-location-indication", - "", "Read Without Encryption error location indication (default: mask)"), + "", "Read Without Encryption error location indication (default: mask)"), arg_lit0("v", "verbose", "verbose output"), arg_param_end }; diff --git a/client/src/cmdhffmcos.c b/client/src/cmdhffmcos.c index 02972c914..91b815ac4 100644 --- a/client/src/cmdhffmcos.c +++ b/client/src/cmdhffmcos.c @@ -32,6 +32,7 @@ #include "protocols.h" #include "mbedtls/des.h" #include +#include "commonutil.h" // ARRAYLEN static int CmdHelp(const char *Cmd); @@ -3873,7 +3874,6 @@ static int CmdHFFmcosHistory(const char *Cmd) { {0x07, "OD limit upd"}, {0x09, "Compound pur"}, }; - const size_t ntypes = sizeof(tx_types) / sizeof(tx_types[0]); PrintAndLogEx(INFO, " # | Date | Time | Type | Amount | OD Limit | Serial | Terminal"); PrintAndLogEx(INFO, "---+------------+----------+--------------+------------+----------+--------+-------------------"); @@ -3924,7 +3924,7 @@ static int CmdHFFmcosHistory(const char *Cmd) { char type_hex_buf[13]; snprintf(type_hex_buf, sizeof(type_hex_buf), "0x%02X ", tx_type); const char *type_name = type_hex_buf; - for (size_t i = 0; i < ntypes; i++) { + for (size_t i = 0; i < ARRAYLEN(tx_types); i++) { if (tx_types[i].code == tx_type) { type_name = tx_types[i].name; break; diff --git a/client/src/cmdhfgallagher.c b/client/src/cmdhfgallagher.c index 7a94c6e06..c965d8acc 100644 --- a/client/src/cmdhfgallagher.c +++ b/client/src/cmdhfgallagher.c @@ -161,7 +161,7 @@ static int authenticate(DesfireContext_t *ctx, bool verbose) { int res = DesfireAuthenticate(ctx, DACEV1, false); if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Desfire authenticate " _RED_("error") ". Result: [%d] %s", + PrintAndLogEx(FAILED, "Desfire authentication " _RED_("failed") ". Result [%d] %s", res, DesfireAuthErrorToStr(res) ); @@ -426,7 +426,7 @@ static int hfgal_create_creds_app(DesfireContext_t *ctx, uint8_t *site_key, uint DesfireSetKeyNoClear(ctx, 0, T_AES, blank_key); DesfireSetKdf(ctx, MFDES_KDF_ALGO_NONE, NULL, 0); res = authenticate(ctx, verbose); - PM3_RET_IF_ERR_WITH_MSG(res, "Desfire authenticate error. Result: [%d] %s", res, DesfireAuthErrorToStr(res)); + PM3_RET_IF_ERR(res); // authenticate() already reported the reason // Change key DesfireSetCommMode(ctx, DCMEncryptedPlain); diff --git a/client/src/cmdhficlass.c b/client/src/cmdhficlass.c index 2166159f4..6ee9d9ff8 100644 --- a/client/src/cmdhficlass.c +++ b/client/src/cmdhficlass.c @@ -1338,7 +1338,7 @@ static int CmdHFiClassTagSim(const char *Cmd) { wiegand_card_t card; memset(&card, 0, sizeof(wiegand_card_t)); card.FacilityCode = arg_get_u32_def(ctx, 2, 0); - card.CardNumber = arg_get_u32_def(ctx, 3, 0); + card.CardNumber = arg_get_u64_def(ctx, 3, 0); card.IssueLevel = arg_get_u32_def(ctx, 4, 0); // --- binary string @@ -2017,9 +2017,9 @@ static int CmdHFiClassESave(const char *Cmd) { CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen); uint16_t bytes = arg_get_int_def(ctx, 2, 256); - if (bytes > 4096) { - PrintAndLogEx(WARNING, "Emulator memory is max 4096bytes. Truncating %u to 4096", bytes); - bytes = 4096; + if (bytes > g_conn.em_size) { + PrintAndLogEx(WARNING, "Emulator memory is max %u bytes. Truncating %u to %u", g_conn.em_size, bytes, g_conn.em_size); + bytes = g_conn.em_size; } CLIParserFree(ctx); @@ -2077,9 +2077,9 @@ static int CmdHFiClassEView(const char *Cmd) { CLIParserFree(ctx); - if (bytes > 4096) { - PrintAndLogEx(WARNING, "Emulator memory is max 4096bytes. Truncating %u to 4096", bytes); - bytes = 4096; + if (bytes > g_conn.em_size) { + PrintAndLogEx(WARNING, "Emulator memory is max %u bytes. Truncating %u to %u", g_conn.em_size, bytes, g_conn.em_size); + bytes = g_conn.em_size; } if (bytes % 8 != 0) { @@ -4315,9 +4315,9 @@ static int CmdHFiClass_TearBlock(const char *Cmd) { } if (tearoff_loop > 1) { - PrintAndLogEx(INPLACE, " Tear off delay "_YELLOW_("%u")" / "_YELLOW_("%d")" us - "_YELLOW_("%3u")" iter", params.delay_us, (tearoff_end & 0xFFFF), loop_count + 1); + PrintAndLogEx(INPLACE, "Tear off delay "_YELLOW_("%u")" / "_YELLOW_("%d")" us - "_YELLOW_("%3u")" iter", params.delay_us, (tearoff_end & 0xFFFF), loop_count + 1); } else { - PrintAndLogEx(INPLACE, " Tear off delay "_YELLOW_("%u")" / "_YELLOW_("%d")" us", params.delay_us, (tearoff_end & 0xFFFF)); + PrintAndLogEx(INPLACE, "Tear off delay "_YELLOW_("%u")" / "_YELLOW_("%d")" us", params.delay_us, (tearoff_end & 0xFFFF)); } // write block - don't check the return value. As a tear-off occurred, the write failed. @@ -4814,9 +4814,9 @@ static int CmdHFiClass_BlackTears(const char *Cmd) { } if (tearoff_loop > 1) { - PrintAndLogEx(INPLACE, " Tear off delay "_YELLOW_("%u")" / "_YELLOW_("%d")" us - "_YELLOW_("%3u")" iter", params.delay_us, (tearoff_end & 0xFFFF), loop_count + 1); + PrintAndLogEx(INPLACE, "Tear off delay "_YELLOW_("%u")" / "_YELLOW_("%d")" us - "_YELLOW_("%3u")" iter", params.delay_us, (tearoff_end & 0xFFFF), loop_count + 1); } else { - PrintAndLogEx(INPLACE, " Tear off delay "_YELLOW_("%u")" / "_YELLOW_("%d")" us", params.delay_us, (tearoff_end & 0xFFFF)); + PrintAndLogEx(INPLACE, "Tear off delay "_YELLOW_("%u")" / "_YELLOW_("%d")" us", params.delay_us, (tearoff_end & 0xFFFF)); } // write block - don't check the return value. As a tear-off occurred, the write failed. @@ -5293,6 +5293,10 @@ static void print_iclass_sio_decoded(uint8_t *sio, size_t sio_len) { break; } default: + // Surface tags we don't decode yet instead of dropping them silently. + // Real credentials (e.g. SR) carry context tags such as [5]/[9] that + // would otherwise be invisible here; `--verbose` shows the full ASN1 TLV. + PrintAndLogEx(INFO, " Unknown tag 0x%02X : " _YELLOW_("%s"), tag, sprint_hex_inrow(val, len)); break; } } @@ -7675,7 +7679,7 @@ static int CmdHFiClassEncode(const char *Cmd) { memset(&card, 0, sizeof(wiegand_card_t)); card.FacilityCode = arg_get_u32_def(ctx, 8, 0); - card.CardNumber = arg_get_u32_def(ctx, 9, 0); + card.CardNumber = arg_get_u64_def(ctx, 9, 0); card.IssueLevel = arg_get_u32_def(ctx, 10, 0); char format[16] = {0}; diff --git a/client/src/cmdhfjooki.c b/client/src/cmdhfjooki.c index 1956c606f..56fe623b9 100644 --- a/client/src/cmdhfjooki.c +++ b/client/src/cmdhfjooki.c @@ -557,7 +557,7 @@ static int CmdHF14AJookiSim(const char *Cmd) { uint16_t chunk_size = MIN(max_avail_blocks, datalen); uint16_t blocks_to_send = chunk_size / blockwidth; - if (mf_eml_set_mem_xt(data + counter, blockno, blocks_to_send, blockwidth) != PM3_SUCCESS) { + if (mf_eml_set_mem_xt(data + counter, blockno, blocks_to_send, blockwidth, 0) != PM3_SUCCESS) { PrintAndLogEx(FAILED, "Cant set emul block: %3d", blockno); free(data); return PM3_ESOFT; diff --git a/client/src/cmdhflegic.c b/client/src/cmdhflegic.c index 816a1c754..119bb383a 100644 --- a/client/src/cmdhflegic.c +++ b/client/src/cmdhflegic.c @@ -570,7 +570,7 @@ static int decode_and_print_memory(uint16_t card_size, const uint8_t *input_buff // for printing the complete segment we need at least wrc + wrp_len + remain_seg_payload_len bytes if ((i + wrc + wrp_len + remain_seg_payload_len) > card_size) { PrintAndLogEx(FAILED, "Cannot read segment body, because the input buffer is too small. " - "Please check that the data is correct and properly aligned. "); + "Please check that the data is correct and properly aligned. "); return_value = PM3_EOUTOFBOUND; goto out; } @@ -654,7 +654,7 @@ static int decode_and_print_memory(uint16_t card_size, const uint8_t *input_buff // for printing the complete segment we need at least wrc + wrp_len + remain_seg_payload_len bytes if ((i + wrc + wrp_len + remain_seg_payload_len) > card_size) { PrintAndLogEx(FAILED, "Cannot read segment body, because the input buffer is too small. " - "Please check that the data is correct and properly aligned. "); + "Please check that the data is correct and properly aligned. "); return_value = PM3_EOUTOFBOUND; goto out; } diff --git a/client/src/cmdhflist.c b/client/src/cmdhflist.c index f2019fbc0..a4e903dd3 100644 --- a/client/src/cmdhflist.c +++ b/client/src/cmdhflist.c @@ -49,7 +49,12 @@ enum MifareAuthSeq { static enum MifareAuthSeq MifareAuthState; static AuthData_t AuthData; +// Set while the previous reader frame was a bit oriented ANTICOLLISION, whose +// answer completes a split byte and so carries no CRC either. +static bool gs_14a_anticoll_answer = false; + void ClearAuthData(void) { + gs_14a_anticoll_answer = false; AuthData.uid = 0; AuthData.nt = 0; AuthData.first_auth = true; @@ -74,6 +79,29 @@ static uint8_t *gs_mfuc_key = NULL; */ uint8_t iso14443A_CRC_check(bool isResponse, uint8_t *d, uint8_t n) { + + // Neither half of a bit oriented ANTICOLLISION exchange carries a CRC: the + // request stops mid byte and the answer completes it. NVB counts SEL and + // NVB themselves, so 0x20..0x67 is the anticollision range and only a + // SELECT, NVB 0x70, ends in a CRC. `hf 14a antifuzz` pushes a reader past + // cascade level 3, hence the whole odd 0x93..0x9F range. + // + // The answer carries nothing that identifies it, so it is recognised by the + // request it follows - frames reach us in order. + if (isResponse == false) { + gs_14a_anticoll_answer = (n >= 2 && + (d[0] & 1) && + d[0] >= ISO14443A_CMD_ANTICOLL_OR_SELECT && + d[0] <= 0x9F && + d[1] >= 0x20 && d[1] <= 0x67); + if (gs_14a_anticoll_answer) { + return 2; + } + } else if (gs_14a_anticoll_answer) { + gs_14a_anticoll_answer = false; + return 2; + } + if (n < 3) { return 2; } @@ -82,11 +110,6 @@ uint8_t iso14443A_CRC_check(bool isResponse, uint8_t *d, uint8_t n) { return 2; } - if (d[1] == 0x50 && - d[0] >= ISO14443A_CMD_ANTICOLL_OR_SELECT && - d[0] <= ISO14443A_CMD_ANTICOLL_OR_SELECT_3) { - return 2; - } return check_crc(CRC_14443_A, d, n); } @@ -266,40 +289,45 @@ int applyIso14443a(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize, bool i case ISO14443A_CMD_WUPA: snprintf(exp, size, "WUPA"); break; - case ISO14443A_CMD_ANTICOLL_OR_SELECT: { - // 93 20 = Anticollision (usage: 9320 - answer: 4bytes UID+1byte UID-bytes-xor) - // 93 50 = Bit oriented anti-collision (usage: 9350+ up to 5bytes, 9350 answer - up to 5bytes UID+BCC) - // 93 70 = Select (usage: 9370+5bytes 9370 answer - answer: 1byte SAK) - if (cmd[1] == 0x70) - snprintf(exp, size, "SELECT_UID"); - else if (cmd[1] == 0x20 || cmd[1] == 0x50) - snprintf(exp, size, "ANTICOLL"); - else - snprintf(exp, size, "SELECT_XXX"); - break; - } - case ISO14443A_CMD_ANTICOLL_OR_SELECT_2: { - //95 20 = Anticollision of cascade level2 - //95 50 = Bit oriented anti-collision level2 - //95 70 = Select of cascade level2 - if (cmd[1] == 0x70) - snprintf(exp, size, "SELECT_UID-2"); - else if (cmd[1] == 0x20 || cmd[1] == 0x50) - snprintf(exp, size, "ANTICOLL-2"); - else - snprintf(exp, size, "SELECT_XXX-2"); - break; - } - case ISO14443A_CMD_ANTICOLL_OR_SELECT_3: { - //97 20 = Anticollision of cascade level3 - //97 50 = Bit oriented anti-collision level3 - //97 70 = Select of cascade level3 - if (cmd[1] == 0x70) - snprintf(exp, size, "SELECT_UID-3"); - else if (cmd[1] == 0x20 || cmd[1] == 0x50) - snprintf(exp, size, "ANTICOLL-3"); - else - snprintf(exp, size, "SELECT_XXX-3"); + // 93 20 = Anticollision (usage: 9320 - answer: 4bytes UID+1byte UID-bytes-xor) + // 93 50 = Bit oriented anti-collision (usage: 9350+ up to 5bytes, 9350 answer - up to 5bytes UID+BCC) + // 93 70 = Select (usage: 9370+5bytes 9370 answer - answer: 1byte SAK) + // 95 xx / 97 xx are the same for cascade level 2 and 3. ISO 14443-3 + // defines no level above 3, but `hf 14a antifuzz` walks a reader up + // the whole odd 0x93..0x9F range, so decode that range too. + case ISO14443A_CMD_ANTICOLL_OR_SELECT: + case ISO14443A_CMD_ANTICOLL_OR_SELECT_2: + case ISO14443A_CMD_ANTICOLL_OR_SELECT_3: + case 0x99: + case 0x9B: + case 0x9D: + case 0x9F: { + // one suffix for every level past the first, so an ordinary + // trace keeps reading "ANTICOLL" / "SELECT_UID" + char lvl[8] = {0}; + uint8_t level = ((cmd[0] - ISO14443A_CMD_ANTICOLL_OR_SELECT) >> 1) + 1; + if (level > 1) { + snprintf(lvl, sizeof(lvl), "-%u", level); + } + + if (cmdsize < 2) { + snprintf(exp, size, "SELECT_XXX%s", lvl); + } else if (cmd[1] == 0x70) { + snprintf(exp, size, "SELECT_UID%s", lvl); + } else if (cmd[1] >= 0x20 && cmd[1] <= 0x67 && (cmd[1] & 0x0F) < 8) { + // NVB counts SEL and NVB themselves, so 0x20 is "no UID bits + // known" and 0x67 is "39 known". Anything in between is a + // bit oriented request, and how far the reader has got is + // the whole story of a collision storm. + uint8_t known = (uint8_t)((((cmd[1] >> 4) - 2) * 8) + (cmd[1] & 0x0F)); + if (known) { + snprintf(exp, size, "ANTICOLL%s(" _MAGENTA_("%u") " bit%s)", lvl, known, (known == 1) ? "" : "s"); + } else { + snprintf(exp, size, "ANTICOLL%s", lvl); + } + } else { + snprintf(exp, size, "SELECT_XXX%s", lvl); + } break; } case ISO14443A_CMD_REQA: diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index 7bf3519a3..94c4a2c79 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -43,6 +43,11 @@ #include "proxendian.h" #include "preferences.h" #include "mifare/gen4.h" +#include "parsers/parsehid.h" +#include "parsers/parsevigik.h" +#include "parsers/parsehexact.h" +#include "parsers/parseproac.h" +#include "parsers/parserkf.h" #include "generator.h" // keygens. #include "fpga.h" #include "mifare/mifarehost.h" @@ -67,9 +72,21 @@ typedef struct { static int CmdHelp(const char *Cmd); -static int HFMFAutoPwnSEN(sector_t *e_sector, size_t sector_cnt) { +static int HFMFAutoPwnSEN(sector_t *e_sector, size_t sector_cnt, const char *suffix, bool no_save) { DropField(); - return HFMFSENRecover(false, false, false, false, 0, 0x1, true, e_sector, sector_cnt); + return HFMFSENRecover(false, false, false, false, 0, 0x1, true, e_sector, sector_cnt, suffix, no_save); +} + +// look for a known backdoor key which can read block 0 +static bool mf_find_backdoor_key(uint8_t *key) { + uint8_t blockdata[MFBLOCK_SIZE] = {0}; + for (uint8_t i = 0; i < ARRAYLEN(fm11_backdoor_keys); i++) { + if (mf_read_block(0, MF_KEY_BD, fm11_backdoor_keys[i], blockdata) == PM3_SUCCESS) { + memcpy(key, fm11_backdoor_keys[i], MIFARE_KEY_SIZE); + return true; + } + } + return false; } // Static array for Saflok key levels @@ -401,9 +418,11 @@ int mf_read_uid(uint8_t *uid, int *uidlen, int *nxptype) { return PM3_ETIMEOUT; } - memcpy(card.ats, resp.data.asBytes, rlen_398); - card.ats_len = rlen_398; // note: ats_len includes CRC Bytes - if (card.ats_len > 3) { + // Only a well formed ATS, TL plus the bytes TL counts plus CRC, means the + // PICC entered ISO14443-4. A 4 bit NAK to RATS is not an ATS. + if ((rlen_398 > 3) && (resp.data.asBytes[0] == rlen_398 - 2)) { + memcpy(card.ats, resp.data.asBytes, rlen_398); + card.ats_len = rlen_398; // note: ats_len includes CRC Bytes select_status = 4; } } @@ -859,6 +878,45 @@ static void mf_analyse_acl(uint16_t n, uint8_t *d) { } } +// Everything `hf mf view` shows once the block data is in hand. Shared so a dump +// read straight off the card gets the same treatment as one loaded from a file - +// the key extraction and the VIGIK decode used to be reachable only via a file. +static int mf_view_dump(uint8_t *dump, size_t bytes_read, uint16_t block_cnt, bool verbose, bool save_keys) { + + mf_print_blocks(block_cnt, dump, verbose); + + if (verbose) { + mf_print_keys(block_cnt, dump); + mf_analyse_acl(block_cnt, dump); + } + + if (save_keys) { + mf_save_keys_from_arr(block_cnt, dump); + } + + if (is_valid_hid_card(dump, bytes_read)) { + (void)hid_parser_parse(dump, bytes_read); + } + + if (is_valid_vigik_card(dump, bytes_read)) { + (void)vigik_parser_parse(dump, bytes_read); + } + + if (is_valid_hexact_card(dump, bytes_read)) { + (void)hexact_parser_parse(dump, bytes_read); + } + + if (is_valid_proac_card(dump, bytes_read)) { + (void)proac_parser_parse(dump, bytes_read); + } + + if (is_valid_rkf_card(dump, bytes_read)) { + (void)rkf_parser_parse(dump, bytes_read); + } + + return PM3_SUCCESS; +} + /* Sector trailer sanity checks. Warn if ACL is strict read-only, or invalid ACL. @@ -1655,6 +1713,7 @@ static int CmdHF14AMfDump(const char *Cmd) { arg_lit0(NULL, "4k", "MIFARE Classic 4k / S70"), arg_lit0(NULL, "ns", "no save to file"), arg_lit0("v", "verbose", "verbose output"), + arg_lit0(NULL, "sk", "Save extracted keys to binary file"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, true); @@ -1673,6 +1732,7 @@ static int CmdHF14AMfDump(const char *Cmd) { bool m4 = arg_get_lit(ctx, 6); bool nosave = arg_get_lit(ctx, 7); bool verbose = arg_get_lit(ctx, 8); + bool save_keys = arg_get_lit(ctx, 9); CLIParserFree(ctx); uint64_t t1 = msclock(); @@ -1725,12 +1785,7 @@ static int CmdHF14AMfDump(const char *Cmd) { PrintAndLogEx(SUCCESS, "time: %" PRIu64 " seconds\n", (msclock() - t1) / 1000); - mf_print_blocks(block_cnt, mem, verbose); - - if (verbose) { - mf_print_keys(block_cnt, mem); - mf_analyse_acl(block_cnt, mem); - } + mf_view_dump(mem, bytes, block_cnt, verbose, save_keys); // Skip saving card data to file if (nosave) { @@ -2197,6 +2252,9 @@ static int CmdHF14AMfNested(const char *Cmd) { //TODO: single mode broken? can't case PM3_EFAILED: PrintAndLogEx(FAILED, "Tag isn't vulnerable to Nested Attack (PRNG is not predictable).\n"); break; + case PM3_EWRONGANSWER: + PrintAndLogEx(FAILED, "Tag refused the nested authentication for block " _YELLOW_("%u") "\n", trgBlockNo); + break; case PM3_ESOFT: PrintAndLogEx(FAILED, "No valid key found"); break; @@ -2300,6 +2358,11 @@ static int CmdHF14AMfNested(const char *Cmd) { //TODO: single mode broken? can't case PM3_EFAILED : PrintAndLogEx(FAILED, "Tag isn't vulnerable to Nested Attack (PRNG is not predictable)\n"); break; + case PM3_EWRONGANSWER: + // tag refused this block, nothing to gain by retrying it + PrintAndLogEx(FAILED, "Tag refused the nested authentication for sector " _YELLOW_("%u") "\n", sectorNo); + calibrate = false; + continue; case PM3_ESOFT: //key not found calibrate = false; @@ -2911,6 +2974,20 @@ static int CmdHF14AMfNestedHard(const char *Cmd) { return isOK; } +// how many keys are in hand right now. a sector that can't be cracked should +// not cost the ones that already came out +static uint8_t mfc_found_key_count(const sector_t *e_sector, uint8_t sector_cnt) { + uint8_t n = 0; + for (uint8_t i = 0; i < sector_cnt; i++) { + for (uint8_t j = MF_KEY_A; j <= MF_KEY_B; j++) { + if (e_sector[i].foundKey[j]) { + n++; + } + } + } + return n; +} + static int CmdHF14AMfAutoPWN(const char *Cmd) { CLIParserContext *ctx; @@ -3141,9 +3218,11 @@ static int CmdHF14AMfAutoPWN(const char *Cmd) { return PM3_ETIMEOUT; } - memcpy(card.ats, resp.data.asBytes, rlen_3120); - card.ats_len = rlen_3120; // note: ats_len includes CRC Bytes - if (card.ats_len > 3) { + // Only a well formed ATS, TL plus the bytes TL counts plus CRC, means the + // PICC entered ISO14443-4. A 4 bit NAK to RATS is not an ATS. + if ((rlen_3120 > 3) && (resp.data.asBytes[0] == rlen_3120 - 2)) { + memcpy(card.ats, resp.data.asBytes, rlen_3120); + card.ats_len = rlen_3120; // note: ats_len includes CRC Bytes select_status = 4; } } @@ -3295,12 +3374,17 @@ static int CmdHF14AMfAutoPWN(const char *Cmd) { if (known_key) { has_staticnonce = detect_classic_static_encrypted_nonce(loopupblk, keytype, key); } else { - has_staticnonce = detect_classic_static_encrypted_nonce(0, MF_KEY_A, g_mifare_default_key); + uint8_t bdkey[MIFARE_KEY_SIZE] = {0}; + if (mf_find_backdoor_key(bdkey)) { + has_staticnonce = detect_classic_static_encrypted_nonce(0, MF_KEY_BD, bdkey); + } else { + has_staticnonce = detect_classic_static_encrypted_nonce(0, MF_KEY_A, g_mifare_default_key); + } } } if (has_staticnonce == NONCE_STATIC_ENC) { - int sen_res = HFMFAutoPwnSEN(e_sector, sector_cnt); + int sen_res = HFMFAutoPwnSEN(e_sector, sector_cnt, outfnlen ? outfilename : NULL, no_save); free(e_sector); free(fptr); return sen_res; @@ -3470,7 +3554,7 @@ static int CmdHF14AMfAutoPWN(const char *Cmd) { if (known_key && ((has_staticnonce == NONCE_NORMAL) || (has_staticnonce == NONCE_FAIL))) { has_staticnonce = detect_classic_static_encrypted_nonce(mfFirstBlockOfSector(sectorno), keytype, key); if (has_staticnonce == NONCE_STATIC_ENC) { - int sen_res = HFMFAutoPwnSEN(e_sector, sector_cnt); + int sen_res = HFMFAutoPwnSEN(e_sector, sector_cnt, outfnlen ? outfilename : NULL, no_save); free(keyBlock); free(e_sector); free(fptr); @@ -3546,7 +3630,7 @@ noValidKeyFound: if (known_key && has_staticnonce == NONCE_NORMAL) { has_staticnonce = detect_classic_static_encrypted_nonce(mfFirstBlockOfSector(sectorno), keytype, key); if (has_staticnonce == NONCE_STATIC_ENC) { - int sen_res = HFMFAutoPwnSEN(e_sector, sector_cnt); + int sen_res = HFMFAutoPwnSEN(e_sector, sector_cnt, outfnlen ? outfilename : NULL, no_save); free(keyBlock); free(e_sector); free(fptr); @@ -3559,9 +3643,15 @@ noValidKeyFound: num_to_bytes(0, MIFARE_KEY_SIZE, tmp_key); bool nested_failed = false; + // a refused sector prints a single line, so it should not be wrapped in the + // blank line that separates the multi line output of a real attack + bool skipped_last = false; + // Iterate over each sector and key(A/B) for (current_sector_i = 0; current_sector_i < sector_cnt; current_sector_i++) { + skipped_last = false; + for (current_key_type_i = MF_KEY_A; current_key_type_i <= MF_KEY_B; current_key_type_i++) { // If the key is already known, just skip it @@ -3662,7 +3752,10 @@ skipReadBKey: if (prng_type && (nested_failed == false)) { uint8_t retries = 0; - PrintAndLogEx(NORMAL, ""); + if (skipped_last == false) { + PrintAndLogEx(NORMAL, ""); + } + if (verbose) { PrintAndLogEx(INFO, "--- " _CYAN_("Enter nested key recovery mode") " -----------------------------"); PrintAndLogEx(INFO, "Sector " _YELLOW_("%3d") " key type " _YELLOW_("%c"), @@ -3675,10 +3768,30 @@ tryNested: switch (isOK) { case PM3_ETIMEOUT: { PrintAndLogEx(ERR, "\nError: No response from Proxmark3."); + + uint8_t havekeys = mfc_found_key_count(e_sector, sector_cnt); + if (havekeys) { + PrintAndLogEx(INFO, "Keeping the " _YELLOW_("%u") " key%s recovered so far", + havekeys, + (havekeys == 1) ? "" : "s" + ); + goto all_found; + } + free(e_sector); free(fptr); return isOK; } + case PM3_EWRONGANSWER: { + // the tag NAKed the nested auth for this block. it is a + // refusal, so move on rather than grind the same sector + PrintAndLogEx(FAILED, "Tag refused the nested authentication, skipping sector " _YELLOW_("%3d") " key type " _YELLOW_("%c"), + current_sector_i, + (current_key_type_i == MF_KEY_B) ? 'B' : 'A' + ); + skipped_last = true; + continue; + } case PM3_EOPABORTED: { PrintAndLogEx(WARNING, "\nButton pressed. Aborted."); free(e_sector); @@ -3707,7 +3820,7 @@ tryNested: case PM3_ESTATIC_NONCE: { e_sector[current_sector_i].Key[current_key_type_i] = 0xffffffffffff; e_sector[current_sector_i].foundKey[current_key_type_i] = false; - int sen_res = HFMFAutoPwnSEN(e_sector, sector_cnt); + int sen_res = HFMFAutoPwnSEN(e_sector, sector_cnt, outfnlen ? outfilename : NULL, no_save); free(e_sector); free(fptr); return sen_res; @@ -3765,7 +3878,7 @@ tryHardnested: // If the nested attack fails then we try the hardnested attack case PM3_ESTATIC_NONCE: { e_sector[current_sector_i].Key[current_key_type_i] = 0xffffffffffff; e_sector[current_sector_i].foundKey[current_key_type_i] = false; - int sen_res = HFMFAutoPwnSEN(e_sector, sector_cnt); + int sen_res = HFMFAutoPwnSEN(e_sector, sector_cnt, outfnlen ? outfilename : NULL, no_save); free(e_sector); free(fptr); return sen_res; @@ -5126,7 +5239,7 @@ void printKeyTableEx(size_t sectorscnt, sector_t *e_sector, uint8_t start_sector _YELLOW_("H") ":Hardnested / " _YELLOW_("C") ":statiCnested / " _YELLOW_("A") ":keyA " - " )" + " )" ); if (sectorscnt == 18) { PrintAndLogEx(INFO, "( " _MAGENTA_("*") " ) These sectors used for signature. Lays outside of user memory"); @@ -5448,7 +5561,11 @@ int CmdHF14AMfELoad(const char *Cmd) { uint16_t chunk_size = MIN(max_avail_blocks, bytes_read); uint16_t blocks_to_send = chunk_size / block_width; - if (mf_eml_set_mem_xt(data + offset, cnt, blocks_to_send, block_width) != PM3_SUCCESS) { + // the first chunk zeroes the emulator memory device side, so a dump smaller + // than the previous one can't leave a tail behind that reads back as card data + uint8_t flags = (cnt == 0) ? MFEMUL_MEMSET_CLEAR : 0; + + if (mf_eml_set_mem_xt(data + offset, cnt, blocks_to_send, block_width, flags) != PM3_SUCCESS) { PrintAndLogEx(FAILED, "Can't set emulator mem at block: %3d", cnt); free(data); return PM3_ESOFT; @@ -6857,41 +6974,11 @@ static int CmdHF14AMfMAD(const char *Cmd) { bool haveMAD2 = false; MAD1DecodeAndPrint(s0, swapmad, verbose, &haveMAD2); - int sector = DetectHID(s0, 0x484d); - if (sector > -1) { - - // decode it - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(INFO, "------------------------- " _CYAN_("Wiegand") " ---------------------------"); - PrintAndLogEx(INFO, _CYAN_("HID PACS detected")); - - size_t pacs_off = mfFirstBlockOfSector(sector) * MFBLOCK_SIZE; - uint8_t pacs_sector[MFBLOCK_SIZE * 3] = {0}; - if (pacs_off + sizeof(pacs_sector) <= bytes_read) { - memcpy(pacs_sector, dump + pacs_off, sizeof(pacs_sector)); - } - - if (pacs_sector[16] == 0x02) { - - PrintAndLogEx(SUCCESS, "Raw...... " _GREEN_("%s"), sprint_hex_inrow(pacs_sector + 24, 8)); - - //todo: remove preamble/sentinel - uint32_t top = 0, mid = 0, bot = 0; - char hexstr[16 + 1] = {0}; - hex_to_buffer((uint8_t *)hexstr, pacs_sector + 24, 8, sizeof(hexstr) - 1, 0, 0, true); - hexstring_to_u96(&top, &mid, &bot, hexstr); - - char binstr[64 + 1]; - hextobinstring(binstr, hexstr); - char *pbin = binstr; - while (strlen(pbin) && *(++pbin) == '0'); - - PrintAndLogEx(SUCCESS, "Binary... " _GREEN_("%s"), pbin); - - decode_wiegand(top, mid, bot, 0); - } + if (is_valid_hid_card(dump, bytes_read)) { + (void)hid_parser_parse(dump, bytes_read); } + int sector = -1; sector = DetectHID(s0, 0x4910); if (sector > -1) { // decode it @@ -8466,13 +8553,15 @@ static int CmdHF14AMfView(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hf mf view", "Print a MIFARE Classic dump file (bin/eml/json)", - "hf mf view -f hf-mf-01020304-dump.bin" + "hf mf view -f hf-mf-01020304-dump.bin\n" + "hf mf view --selftest" ); void *argtable[] = { arg_param_begin, - arg_str1("f", "file", "", "Specify a filename for dump file"), + arg_str0("f", "file", "", "Specify a filename for dump file"), arg_lit0("v", "verbose", "verbose output"), arg_lit0(NULL, "sk", "Save extracted keys to binary file"), + arg_lit0(NULL, "selftest", "Run the dump parsers self tests and exit"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, false); @@ -8481,8 +8570,26 @@ static int CmdHF14AMfView(const char *Cmd) { CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen); bool verbose = arg_get_lit(ctx, 2); bool save_keys = arg_get_lit(ctx, 3); + bool selftest = arg_get_lit(ctx, 4); CLIParserFree(ctx); + if (selftest) { + int res = vigik_selftest(); + if (res != PM3_SUCCESS) { + return res; + } + res = hexact_selftest(); + if (res != PM3_SUCCESS) { + return res; + } + return rkf_selftest(); + } + + if (fnlen == 0) { + PrintAndLogEx(ERR, "Specify a filename with `-f` or run `--selftest`"); + return PM3_EINVARG; + } + // read dump file uint8_t *dump = NULL; size_t bytes_read = 0; @@ -8506,64 +8613,9 @@ static int CmdHF14AMfView(const char *Cmd) { PrintAndLogEx(INFO, "File size %zu bytes, file blocks %d (0x%x)", bytes_read, block_cnt, block_cnt); } - mf_print_blocks(block_cnt, dump, verbose); - - if (verbose) { - mf_print_keys(block_cnt, dump); - mf_analyse_acl(block_cnt, dump); - } - - if (save_keys) { - mf_save_keys_from_arr(block_cnt, dump); - } - - const mad1_sector_t *vigik_s0 = (bytes_read >= sizeof(mad1_sector_t)) ? (const mad1_sector_t *)dump : NULL; - - int sector = vigik_s0 ? DetectHID(vigik_s0, 0x4910) : -1; - if (sector > -1) { - // decode it - PrintAndLogEx(INFO, ""); - PrintAndLogEx(INFO, _CYAN_("VIGIK PACS detected")); - - mad_entry_list_t mad_list = {0}; - res = MADDecode(vigik_s0, NULL, &mad_list, false, true); - if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "can't decode MAD"); - return res; - } - - typedef union UDATA { - uint8_t *bytes; - mfc_vigik_t *vigik; - } UDATA; - UDATA d; - d.bytes = calloc(bytes_read, sizeof(uint8_t)); - if (d.bytes == NULL) { - PrintAndLogEx(WARNING, "Failed to allocate memory"); - return PM3_EMALLOC; - } - uint16_t dlen = 0; - - // vigik structure sector 0 - memcpy(d.bytes + dlen, dump, MFBLOCK_SIZE * 3); - dlen += MFBLOCK_SIZE * 3; - - for (size_t i = 0; i < mad_list.len; i++) { - if (0x4910 == mad_list.entries[i].aid || 0x4916 == mad_list.entries[i].aid) { - uint8_t sno = mad_list.entries[i].sector; - uint32_t offset = sno * MFBLOCK_SIZE * 4; - memcpy(d.bytes + dlen, dump + offset, MFBLOCK_SIZE * 3); - dlen += MFBLOCK_SIZE * 3; - } - } - -// convert_mfc_2_arr(pdump, bytes_read, d, &dlen); - vigik_annotate(d.vigik); - free(d.bytes); - } - + res = mf_view_dump(dump, bytes_read, block_cnt, verbose, save_keys); free(dump); - return PM3_SUCCESS; + return res; } static int parse_gtu_cfg(uint8_t *d, size_t n) { @@ -9423,7 +9475,7 @@ static int CmdHF14AGen4Save(const char *Cmd) { uint16_t chunk_size = MIN(max_avail_blocks, bytes_left); uint16_t blocks_to_send = chunk_size / MFBLOCK_SIZE; - if (mf_eml_set_mem_xt(dump + offset, cnt, blocks_to_send, MFBLOCK_SIZE) != PM3_SUCCESS) { + if (mf_eml_set_mem_xt(dump + offset, cnt, blocks_to_send, MFBLOCK_SIZE, 0) != PM3_SUCCESS) { PrintAndLogEx(FAILED, "Can't set emulator mem at block: %3d", cnt); free(dump); return PM3_ESOFT; @@ -11329,7 +11381,7 @@ static int CmdHFMFHidEncode(const char *Cmd) { wiegand_card_t card; memset(&card, 0, sizeof(wiegand_card_t)); card.FacilityCode = arg_get_u32_def(ctx, 4, 0); - card.CardNumber = arg_get_u32_def(ctx, 5, 0); + card.CardNumber = arg_get_u64_def(ctx, 5, 0); char format[16] = {0}; int format_len = 0; @@ -11513,9 +11565,11 @@ static int CmdHF14AMfInfo(const char *Cmd) { return PM3_ETIMEOUT; } - memcpy(card.ats, resp.data.asBytes, rlen_11266); - card.ats_len = rlen_11266; // note: ats_len includes CRC Bytes - if (card.ats_len > 3) { + // Only a well formed ATS, TL plus the bytes TL counts plus CRC, means the + // PICC entered ISO14443-4. A 4 bit NAK to RATS is not an ATS. + if ((rlen_11266 > 3) && (resp.data.asBytes[0] == rlen_11266 - 2)) { + memcpy(card.ats, resp.data.asBytes, rlen_11266); + card.ats_len = rlen_11266; // note: ats_len includes CRC Bytes select_status = 4; } } diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 6d05b8b50..0bfb76fb9 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -35,6 +35,7 @@ #include "crypto/duoxcrypto.h" #include "protocols.h" #include "parsers/parsehrt.h" +#include "parsers/parsenortic.h" #include "cmdtrace.h" #include "cliparser.h" #include "iso7816/apduinfo.h" // APDU manipulation / errorcodes @@ -52,11 +53,20 @@ #include "generator.h" #include "mifare/aiddesfire.h" #include "mifare/prime.h" +#include "mifare/desfireem.h" // emulator memory card image #include "util.h" #include "crypto/originality.h" +// How many distinct candidates `hf mfdes detect` remembers per key number so it +// does not send the same cipher to the card twice. +#define MFDES_DETECT_TRIED_MAX 256 + #define MAX_KEY_LEN 24 #define MAX_KEYS_LIST_LEN 1024 +// how many errors in a row from the card before we give up on a key number +#define MFDES_CHK_MAX_ERRORS 10 +// bundled dictionary used when no -f is given +#define MFDES_DEFAULT_DICT "mfdes_default_keys" #define MFDES_BRUTEAID_RESELECT_ATTEMPTS 5 #define MFDES_BRUTEAID_RESELECT_WAIT_MS 200 #define MFDES_BRUTEAID_MAD_START 0xF0000FU @@ -656,7 +666,14 @@ static int DesfirePCRun(DesfireContext_t *dctx, const uint8_t proximity_key[MFDE size_t prepare_resp_len = 0; uint8_t respcode = 0xFF; res = DesfireExchangeEx(activate_field, dctx, MFDES_PREPARE_PC, NULL, 0, &respcode, prepare_resp, &prepare_resp_len, true, 0); - if (res != PM3_SUCCESS) { + if (res != PM3_SUCCESS || respcode != MFDES_S_OPERATION_OK) { + // DesfireExchangeEx reports the transport result; the card's own status + // comes back in respcode and an error there still reads as success. It + // also ends the authentication, so drop our side of the session. + if (res == PM3_SUCCESS) { + res = PM3_EAPDU_FAIL; + } + DesfireClearSession(dctx); uint16_t sw = status(respcode); PrintAndLogEx(ERR, "Prepare proximity check command failed. Result: %d %s", res, DesfireGetErrorString(res, &sw)); goto out; @@ -710,7 +727,11 @@ static int DesfirePCRun(DesfireContext_t *dctx, const uint8_t proximity_key[MFDE respcode = 0xFF; res = DesfireExchange(dctx, MFDES_PROXIMITY_CHECK, round_payload, challenge_part_len + 1, &respcode, round_resp, &round_resp_len); - if (res != PM3_SUCCESS) { + if (res != PM3_SUCCESS || respcode != MFDES_S_OPERATION_OK) { + if (res == PM3_SUCCESS) { + res = PM3_EAPDU_FAIL; + } + DesfireClearSession(dctx); uint16_t sw = status(respcode); PrintAndLogEx(ERR, "Proximity check round %u command failed. Result: %d %s", (unsigned int)round + 1, res, DesfireGetErrorString(res, &sw)); goto out; @@ -762,7 +783,11 @@ static int DesfirePCRun(DesfireContext_t *dctx, const uint8_t proximity_key[MFDE size_t verify_resp_len = 0; respcode = 0xFF; res = DesfireExchange(dctx, MFDES_VERIFY_PC, verify_cmd_mac, sizeof(verify_cmd_mac), &respcode, verify_resp, &verify_resp_len); - if (res != PM3_SUCCESS) { + if (res != PM3_SUCCESS || respcode != MFDES_S_OPERATION_OK) { + if (res == PM3_SUCCESS) { + res = PM3_EAPDU_FAIL; + } + DesfireClearSession(dctx); uint16_t sw = status(respcode); PrintAndLogEx(ERR, "Verify proximity check command failed. Result: %d %s", res, DesfireGetErrorString(res, &sw)); goto out; @@ -818,14 +843,14 @@ static int CmdHF14ADesDefault(const char *Cmd) { void *argtable[] = { arg_param_begin, - arg_int0("n", "keyno", "", "Key number"), - arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), - arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), - arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), - arg_str0("m", "cmode", "", "Communicaton mode"), - arg_str0("c", "ccset", "", "Communicaton command set"), - arg_str0(NULL, "schann", "", "Secure channel"), + arg_int0("n", "keyno", "", "Key number"), + arg_str0("t", "algo", "", "Crypt algo"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), + arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), + arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), + arg_str0("m", "cmode", "", "Communicaton mode"), + arg_str0("c", "ccset", "", "Communicaton command set"), + arg_str0(NULL, "schann", "", "Secure channel"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, true); @@ -856,14 +881,14 @@ static int CmdHF14ADesDefault(const char *Cmd) { PrintAndLogEx(INFO, "-----------" _CYAN_("Default parameters") "---------------------------------"); - PrintAndLogEx(INFO, "Key Num : %d", defaultKeyNum); - PrintAndLogEx(INFO, "Algo : %s", CLIGetOptionListStr(DesfireAlgoOpts, defaultAlgoId)); - PrintAndLogEx(INFO, "Key : %s", sprint_hex(defaultKey, desfire_get_key_length(defaultAlgoId))); - PrintAndLogEx(INFO, "KDF algo : %s", CLIGetOptionListStr(DesfireKDFAlgoOpts, defaultKdfAlgo)); - PrintAndLogEx(INFO, "KDF input : [%d] %s", defaultKdfInputLen, sprint_hex(defaultKdfInput, defaultKdfInputLen)); - PrintAndLogEx(INFO, "Secure chan : %s", CLIGetOptionListStr(DesfireSecureChannelOpts, defaultSecureChannel)); - PrintAndLogEx(INFO, "Command set : %s", CLIGetOptionListStr(DesfireCommandSetOpts, defaultCommSet)); - PrintAndLogEx(INFO, "Comm mode : %s", CLIGetOptionListStr(DesfireCommunicationModeOpts, defaultCommMode)); + PrintAndLogEx(INFO, "Key num........ %d", defaultKeyNum); + PrintAndLogEx(INFO, "Algo........... %s", CLIGetOptionListStr(DesfireAlgoOpts, defaultAlgoId)); + PrintAndLogEx(INFO, "Key............ %s", sprint_hex_inrow(defaultKey, desfire_get_key_length(defaultAlgoId))); + PrintAndLogEx(INFO, "KDF algo....... %s", CLIGetOptionListStr(DesfireKDFAlgoOpts, defaultKdfAlgo)); + PrintAndLogEx(INFO, "KDF input...... [%d] %s", defaultKdfInputLen, sprint_hex_inrow(defaultKdfInput, defaultKdfInputLen)); + PrintAndLogEx(INFO, "Sec chann...... %s", CLIGetOptionListStr(DesfireSecureChannelOpts, defaultSecureChannel)); + PrintAndLogEx(INFO, "Command set.... %s", CLIGetOptionListStr(DesfireCommandSetOpts, defaultCommSet)); + PrintAndLogEx(INFO, "Command mode... %s", CLIGetOptionListStr(DesfireCommunicationModeOpts, defaultCommMode)); return PM3_SUCCESS; } @@ -897,7 +922,6 @@ static bool DesfirePrintVersionInfo(const mfdes_info_res_t *info, nxp_cardtype_t if (local_cardtype == NXP_UNKNOWN && prodtype == DESFIRE_UNKNOWN_PROD) { PrintAndLogEx(INFO, "HW Version.. %s", sprint_hex_inrow(info->versionHW, sizeof(info->versionHW))); PrintAndLogEx(INFO, "SW Version.. %s", sprint_hex_inrow(info->versionSW, sizeof(info->versionSW))); - PrintAndLogEx(INFO, "Version data identification failed. Report to Iceman!"); return false; } @@ -1272,14 +1296,113 @@ static void DesFill2bPattern( (*startPattern)++; } +static void DesChkPrependKey(uint8_t *keyList, size_t stride, uint32_t *keyListLen, const uint8_t *key) { + + uint32_t len = *keyListLen; + if (len >= MAX_KEYS_LIST_LEN) { + len = MAX_KEYS_LIST_LEN - 1; + } + + memmove(keyList + stride, keyList, len * stride); + memcpy(keyList, key, stride); + *keyListLen = len + 1; +} + +// Try every key in `keyList` against every key number the `usedkeys` map marks as +// in use on the currently selected application. Found keys are stored in `found`. +// Returns PM3_SUCCESS, or an error when the application can no longer be selected. +static int AuthCheckDesfireKeyType(DesfireContext_t *dctx, + DesfireSecureChannel secureChannel, + uint32_t curaid, + DesfireCryptoAlgorithm keytype, + const char *keytypestr, + const uint8_t *keyList, size_t keyListStride, uint32_t keyListLen, + const int *usedkeys, + desfire_app_keys_t *found, + bool *result) { + + size_t keylen = desfire_get_key_length(keytype); + + for (uint8_t keyno = 0; keyno < DESFIRE_MAX_KEY_COUNT; keyno++) { + + if (usedkeys[keyno] != 1 || found->keys[keytype][keyno][0] != 0) { + continue; + } + + size_t errcount = 0; + + for (uint32_t curkey = 0; curkey < keyListLen; curkey++) { + + const uint8_t *key = &keyList[curkey * keyListStride]; + + DesfireSetKeyNoClear(dctx, keyno, keytype, (uint8_t *)key); + + int res = DesfireAuthenticate(dctx, secureChannel, false); + if (res == PM3_SUCCESS) { + // the AID is already on the "Checking aid" line above + PrintAndLogEx(SUCCESS, "Found " _GREEN_("%s") " Key %02u... " _GREEN_("%s"), + keytypestr, keyno, sprint_hex_inrow(key, keylen)); + + found->keys[keytype][keyno][0] = 0x01; + memcpy(&found->keys[keytype][keyno][1], key, keylen); + *result = true; + + // EV2 and LRP turn an authenticated context into a "non first" + // auth for the next key number. Start each one clean instead. + DesfireClearSession(dctx); + break; + } + + // anything below 7 means the card gave up before the crypto stage, + // the channel is gone and the application has to be selected again + if (res < 7) { + DropField(); + int selres = DesfireSelectAIDHex(dctx, curaid, false, 0); + if (selres != PM3_SUCCESS) { + return selres; + } + } + + // 4 - answer length doesn't match the algo + // 50 - PICC didn't answer AES, 51 - PICC didn't answer LRP + // the application doesn't use this key type, skip the rest of it + if (res == 4 || res == 50 || res == 51) { + return PM3_SUCCESS; + } + + // 3 - invalid key number. Every key fails the same way, but the + // remaining key numbers are still worth checking + if (res == 3) { + break; + } + + // 1, 2, 5, 6 - transmit or local crypto error. Carry on with the next + // key and only give up on this key number after a run of them + if (res < 7) { + errcount++; + if (errcount > MFDES_CHK_MAX_ERRORS) { + if (g_debugMode) { + PrintAndLogEx(DEBUG, "AID 0x%06X, %s key %02u... too many errors from card, skipping", curaid, keytypestr, keyno); + } + break; + } + } else { + errcount = 0; + } + } + } + + return PM3_SUCCESS; +} + static int AuthCheckDesfire(DesfireContext_t *dctx, DesfireSecureChannel secureChannel, const uint8_t *aid, uint8_t deskeyList[MAX_KEYS_LIST_LEN][8], uint32_t deskeyListLen, uint8_t aeskeyList[MAX_KEYS_LIST_LEN][16], uint32_t aeskeyListLen, uint8_t k3kkeyList[MAX_KEYS_LIST_LEN][24], uint32_t k3kkeyListLen, - uint8_t cmdKdfAlgo, uint8_t kdfInputLen, uint8_t *kdfInput, - uint8_t foundKeys[4][0xE][24 + 1], + bool autoschann, + desfire_app_keys_t *found, bool *result, bool verbose) { @@ -1292,204 +1415,189 @@ static int AuthCheckDesfire(DesfireContext_t *dctx, return PM3_ESOFT; } - int usedkeys[0xF] = {0}; + int usedkeys[DESFIRE_MAX_KEY_COUNT + 1] = {0}; bool des = false; bool tdes = false; bool aes = false; bool k3kdes = false; + bool uselrp = false; + uint8_t numkeys = 0; + uint8_t data[250] = {0}; size_t datalen = 0; res = DesfireGetKeySettings(dctx, data, &datalen); - if (res != PM3_SUCCESS && datalen < 2) { - PrintAndLogEx(ERR, "Could not get key settings"); - return res; - } - uint8_t num_keys = data[1]; - switch (num_keys >> 6) { - case 0: + if (res == PM3_SUCCESS && datalen >= 2) { + + numkeys = data[1] & 0x0F; + + switch (data[1] >> 6) { + case 0: + des = true; + tdes = true; + break; + case 1: + k3kdes = true; + break; + case 2: + aes = true; + break; + default: + break; + } + + } else { + + // key settings are not readable. Ask the card which AUTH commands it + // answers instead, the same way `hf mfdes detect` does + AuthCommandsChk_t authCmdCheck = {0}; + DesfireCheckAuthCommands(ISW6bAID, curaid, NULL, 0, &authCmdCheck); + + if (authCmdCheck.checked == false) { + PrintAndLogEx(ERR, "AID 0x%06X, could not get key settings", curaid); + DropField(); + return PM3_ESOFT; + } + + if (authCmdCheck.auth) { des = true; tdes = true; - break; - case 1: + } + + // 0x1A covers DES, 2TDEA and 3TDEA alike, so it cannot tell them apart + // but it is the only command a 3TDEA application answers at all. + if (authCmdCheck.authISO) { k3kdes = true; - break; - case 2: + } + + if (authCmdCheck.authAES || authCmdCheck.authEV2) { aes = true; - break; - default: - break; + } + + if (authCmdCheck.authLRP) { + aes = true; + uselrp = true; + } + + if (des == false && tdes == false && aes == false && k3kdes == false) { + PrintAndLogEx(ERR, "AID 0x%06X, card answers no known auth command", curaid); + DropField(); + return PM3_ESOFT; + } + + // the probe dropped the field behind us + res = DesfireSelectAIDHex(dctx, curaid, false, 0); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "AID 0x%06X, can't re-select after the auth command probe", curaid); + DropField(); + return PM3_ESOFT; + } } // always check master key usedkeys[0] = 1; - if (curaid != 0) { - FileList_t fileList = {{0}}; - size_t filescount = 0; - bool isopresent = 0; - res = DesfireFillFileList(dctx, fileList, &filescount, &isopresent); - if (res == PM3_SUCCESS) { - if (filescount > 0) { - for (int i = 0; i < filescount; i++) { - if (fileList[i].fileSettings.rAccess < 0x0e) - usedkeys[fileList[i].fileSettings.rAccess] = 1; - if (fileList[i].fileSettings.wAccess < 0x0e) - usedkeys[fileList[i].fileSettings.wAccess] = 1; - if (fileList[i].fileSettings.rwAccess < 0x0e) - usedkeys[fileList[i].fileSettings.rwAccess] = 1; - if (fileList[i].fileSettings.chAccess < 0x0e) - usedkeys[fileList[i].fileSettings.chAccess] = 1; - } - } else { - for (int i = 0; i < 0xE; i++) - usedkeys[i] = 1; - } - } else { - for (int i = 0; i < 0xE; i++) - usedkeys[i] = 1; + if (numkeys > 0) { + + uint8_t keynolast = (numkeys <= DESFIRE_MAX_KEY_COUNT) ? numkeys : DESFIRE_MAX_KEY_COUNT; + for (uint8_t k = 0; k < keynolast; k++) { + usedkeys[k] = 1; } + + } else if (curaid != 0) { + + // Key settings were not readable, which means the application master key + // settings deny it without authentication. The same bit gates GetFileIDs + // and GetFileSettings, so the file access rights cannot name the key + // numbers either. GetKeyVersion is not gated by it at all, so ask the + // application which key numbers it actually has + uint8_t keyvercount = 0; + for (uint8_t k = 0; k < DESFIRE_MAX_KEY_COUNT; k++) { + + uint8_t keyno = k; + uint8_t kvbuf[250] = {0}; + size_t kvbuflen = 0; + + if (DesfireGetKeyVersion(dctx, &keyno, 1, kvbuf, &kvbuflen) == PM3_SUCCESS) { + usedkeys[k] = 1; + keyvercount++; + } + } + + // the card named none of them, so there is nothing to narrow it down with + if (keyvercount == 0) { + for (int i = 0; i < DESFIRE_MAX_KEY_COUNT; i++) { + usedkeys[i] = 1; + } + } + } + + // An AES application runs either the EV1/EV2 channel or LRP and the key + // settings don't say which, so it takes one probe to tell them apart. + if (autoschann && aes && uselrp == false) { + + uselrp = DesfireCheckAuthCmd(ISW6bAID, curaid, 0, MFDES_AUTHENTICATE_EV2F, true); + + // the probe dropped the field behind us + res = DesfireSelectAIDHex(dctx, curaid, false, 0); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "AID 0x%06X, can't re-select after the LRP probe", curaid); + DropField(); + return PM3_ESOFT; + } + } + + if (autoschann && uselrp) { + secureChannel = DACLRP; } if (verbose) { PrintAndLogEx(INFO, "Check: %s %s %s %s " NOLF, (des) ? "DES" : "", (tdes) ? "2TDEA" : "", (k3kdes) ? "3TDEA" : "", (aes) ? "AES" : ""); + PrintAndLogEx(NORMAL, "channel: %s " NOLF, CLIGetOptionListStr(DesfireSecureChannelOpts, secureChannel)); PrintAndLogEx(NORMAL, "keys: " NOLF); - for (int i = 0; i < 0xE; i++) - if (usedkeys[i] == 1) + for (int i = 0; i < DESFIRE_MAX_KEY_COUNT; i++) { + if (usedkeys[i] == 1) { PrintAndLogEx(NORMAL, "%02x " NOLF, i); + } + } PrintAndLogEx(NORMAL, ""); } - bool badlen = false; + const struct { + bool check; + DesfireCryptoAlgorithm keytype; + const char *name; + const uint8_t *list; + size_t stride; + uint32_t len; + } checks[] = { + { des, T_DES, "DES", (const uint8_t *)deskeyList, sizeof(deskeyList[0]), deskeyListLen }, + { tdes, T_3DES, "2TDEA", (const uint8_t *)aeskeyList, sizeof(aeskeyList[0]), aeskeyListLen }, + { aes, T_AES, "AES", (const uint8_t *)aeskeyList, sizeof(aeskeyList[0]), aeskeyListLen }, + { k3kdes, T_3K3DES, "3TDEA", (const uint8_t *)k3kkeyList, sizeof(k3kkeyList[0]), k3kkeyListLen }, + }; - if (des) { + for (size_t i = 0; i < ARRAYLEN(checks); i++) { - for (uint8_t keyno = 0; keyno < 0xE; keyno++) { + if (checks[i].check == false) { + continue; + } - if (usedkeys[keyno] == 1 && foundKeys[0][keyno][0] == 0) { - for (uint32_t curkey = 0; curkey < deskeyListLen; curkey++) { - DesfireSetKeyNoClear(dctx, keyno, T_DES, deskeyList[curkey]); - res = DesfireAuthenticate(dctx, secureChannel, false); - if (res == PM3_SUCCESS) { - PrintAndLogEx(SUCCESS, "AID 0x%06X, Found DES Key %02u... " _GREEN_("%s"), curaid, keyno, sprint_hex(deskeyList[curkey], 8)); - foundKeys[0][keyno][0] = 0x01; - *result = true; - memcpy(&foundKeys[0][keyno][1], deskeyList[curkey], 8); - break; - } else if (res < 7) { - badlen = true; - DropField(); - res = DesfireSelectAIDHex(dctx, curaid, false, 0); - if (res != PM3_SUCCESS) { - return res; - } - break; - } - } - if (badlen == true) { - badlen = false; - break; - } - } + // LRP only ever carries AES keys + if (secureChannel == DACLRP && checks[i].keytype != T_AES) { + continue; + } + + res = AuthCheckDesfireKeyType(dctx, secureChannel, curaid, checks[i].keytype, checks[i].name, + checks[i].list, checks[i].stride, checks[i].len, + usedkeys, found, result); + if (res != PM3_SUCCESS) { + DropField(); + return res; } } - if (tdes) { - - for (uint8_t keyno = 0; keyno < 0xE; keyno++) { - - if (usedkeys[keyno] == 1 && foundKeys[1][keyno][0] == 0) { - for (uint32_t curkey = 0; curkey < aeskeyListLen; curkey++) { - DesfireSetKeyNoClear(dctx, keyno, T_3DES, aeskeyList[curkey]); - res = DesfireAuthenticate(dctx, secureChannel, false); - if (res == PM3_SUCCESS) { - PrintAndLogEx(SUCCESS, "AID 0x%06X, Found 2TDEA Key %02u... " _GREEN_("%s"), curaid, keyno, sprint_hex_inrow(aeskeyList[curkey], 16)); - foundKeys[1][keyno][0] = 0x01; - *result = true; - memcpy(&foundKeys[1][keyno][1], aeskeyList[curkey], 16); - break; - } else if (res < 7) { - badlen = true; - DropField(); - res = DesfireSelectAIDHex(dctx, curaid, false, 0); - if (res != PM3_SUCCESS) { - return res; - } - break; - } - } - if (badlen == true) { - badlen = false; - break; - } - } - } - } - - if (aes) { - - for (uint8_t keyno = 0; keyno < 0xE; keyno++) { - - if (usedkeys[keyno] == 1 && foundKeys[2][keyno][0] == 0) { - for (uint32_t curkey = 0; curkey < aeskeyListLen; curkey++) { - DesfireSetKeyNoClear(dctx, keyno, T_AES, aeskeyList[curkey]); - res = DesfireAuthenticate(dctx, secureChannel, false); - if (res == PM3_SUCCESS) { - PrintAndLogEx(SUCCESS, "AID 0x%06X, Found AES Key %02u... " _GREEN_("%s"), curaid, keyno, sprint_hex_inrow(aeskeyList[curkey], 16)); - foundKeys[2][keyno][0] = 0x01; - *result = true; - memcpy(&foundKeys[2][keyno][1], aeskeyList[curkey], 16); - break; - } else if (res < 7) { - badlen = true; - DropField(); - res = DesfireSelectAIDHex(dctx, curaid, false, 0); - if (res != PM3_SUCCESS) { - return res; - } - break; - } - } - if (badlen == true) { - badlen = false; - break; - } - } - } - } - - if (k3kdes) { - - for (uint8_t keyno = 0; keyno < 0xE; keyno++) { - - if (usedkeys[keyno] == 1 && foundKeys[3][keyno][0] == 0) { - for (uint32_t curkey = 0; curkey < k3kkeyListLen; curkey++) { - DesfireSetKeyNoClear(dctx, keyno, T_3K3DES, k3kkeyList[curkey]); - res = DesfireAuthenticate(dctx, secureChannel, false); - if (res == PM3_SUCCESS) { - PrintAndLogEx(SUCCESS, "AID 0x%06X, Found 3TDEA Key %02u... " _GREEN_("%s"), curaid, keyno, sprint_hex_inrow(k3kkeyList[curkey], 24)); - foundKeys[3][keyno][0] = 0x01; - *result = true; - memcpy(&foundKeys[3][keyno][1], k3kkeyList[curkey], 16); - break; - } else if (res < 7) { - badlen = true; - DropField(); - res = DesfireSelectAIDHex(dctx, curaid, false, 0); - if (res != PM3_SUCCESS) { - return res; - } - break; - } - } - - if (badlen == true) { - break; - } - } - } - } DropField(); return PM3_SUCCESS; } @@ -1502,22 +1610,23 @@ static int CmdHF14aDesChk(const char *Cmd) { uint32_t deskeyListLen = 0; uint32_t aeskeyListLen = 0; uint32_t k3kkeyListLen = 0; - uint8_t foundKeys[4][0xE][24 + 1] = {{{0}}}; CLIParserContext *ctx; CLIParserInit(&ctx, "hf mfdes chk", "Checks keys with MIFARE DESFire card.", - "hf mfdes chk --aid 123456 -k 000102030405060708090a0b0c0d0e0f -> check key on aid 0x123456\n" - "hf mfdes chk -f mfdes_default_keys -> check keys against all existing aid on card\n" - "hf mfdes chk -f mfdes_default_keys --aid 123456 -> check keys against aid 0x123456\n" - "hf mfdes chk --aid 123456 --pattern1b -j keys -> check all 1-byte keys pattern on aid 0x123456 and save found keys to `keys.json`\n" - "hf mfdes chk --aid 123456 --pattern2b --startp2b FA00 -> check all 2-byte keys pattern on aid 0x123456. Start from key FA00FA00...FA00"); + "hf mfdes chk -f mfdes_default_keys -> check keys against all existing AID on card\n" + "hf mfdes chk --aid 123456 -f mfdes_default_keys -> check keys against AID 0x123456\n" + "hf mfdes chk --aid 123456 --pattern1b -j keys -> check all 1-byte keys pattern on AID 0x123456 and save found keys to `keys.json`\n" + "hf mfdes chk --aid 123456 --pattern2b --startp2b FA00 -> check all 2-byte keys pattern on AID 0x123456. Start from key FA00FA00...FA00\n" + "hf mfdes chk --aid 123456 -k 000102030405060708090a0b0c0d0e0f -> check key on AID 0x123456\n" + "hf mfdes chk -f mfdes_default_keys --schann lrp -> check keys, forcing the LRP secure channel\n" + ); void *argtable[] = { arg_param_begin, arg_str0(NULL, "aid", "", "Use specific AID (3 hex bytes, big endian)"), - arg_str0("k", "key", "", "Key for checking (HEX 16 bytes)"), - arg_str0("f", "file", "", "Filename of dictionary"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), + arg_str0("f", "file", "", "Filename of dictionary (default: `" MFDES_DEFAULT_DICT "`)"), arg_lit0(NULL, "pattern1b", "Check all 1-byte combinations of key (0000...0000, 0101...0101, 0202...0202, ...)"), arg_lit0(NULL, "pattern2b", "Check all 2-byte combinations of key (0000...0000, 0001...0001, 0002...0002, ...)"), arg_str0(NULL, "startp2b", "", "Start key (2-byte HEX) for 2-byte search (use with `--pattern2b`)"), @@ -1525,10 +1634,11 @@ static int CmdHF14aDesChk(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0(NULL, "kdf", "<0|1|2>", "Key Derivation Function (KDF) (0=None, 1=AN10922, 2=Gallagher)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), + arg_str0(NULL, "schann", "", "Secure channel (default: detected per application)"), arg_lit0("a", "apdu", "Show APDU requests and responses"), arg_param_end }; - CLIExecWithReturn(ctx, Cmd, argtable, false); + CLIExecWithReturn(ctx, Cmd, argtable, true); int aidlength = 0; uint8_t aid[3] = {0}; @@ -1536,7 +1646,7 @@ static int CmdHF14aDesChk(const char *Cmd) { swap24(aid); - uint8_t vkey[16] = {0}; + uint8_t vkey[MAX_KEY_LEN] = {0}; int vkeylen = 0; CLIGetHexWithReturn(ctx, 2, vkey, &vkeylen); @@ -1548,7 +1658,7 @@ static int CmdHF14aDesChk(const char *Cmd) { memcpy(&aeskeyList[aeskeyListLen], vkey, 16); aeskeyListLen++; } else if (vkeylen == 24) { - memcpy(&k3kkeyList[k3kkeyListLen], vkey, 16); + memcpy(&k3kkeyList[k3kkeyListLen], vkey, 24); k3kkeyListLen++; } else { PrintAndLogEx(ERR, "Specified key must have 8, 16 or 24 bytes length."); @@ -1568,6 +1678,12 @@ static int CmdHF14aDesChk(const char *Cmd) { bool pattern1b = arg_get_lit(ctx, 4); bool pattern2b = arg_get_lit(ctx, 5); + // No dictionary and no pattern asked for means the bundled DESFire + // dictionary, which is what `hf mfdes detect` already falls back to. + if (dict_filenamelen == 0 && pattern1b == false && pattern2b == false) { + dict_filenamelen = snprintf((char *)dict_filename, sizeof(dict_filename), "%s", MFDES_DEFAULT_DICT); + } + if (pattern1b && pattern2b) { PrintAndLogEx(ERR, "Pattern search mode must be 2-byte or 1-byte only."); CLIParserFree(ctx); @@ -1614,7 +1730,19 @@ static int CmdHF14aDesChk(const char *Cmd) { int kdfInputLen = 0; CLIGetHexWithReturn(ctx, 10, kdfInput, &kdfInputLen); - bool APDULogging = arg_get_lit(ctx, 11); + // the secure channel is detected per application unless the user pins one + DesfireSecureChannel secureChannel = DACEV1; + bool autoschann = (arg_get_str(ctx, 11)->count == 0); + if (autoschann == false) { + int schann = DACEV1; + if (CLIGetOptionList(arg_get_str(ctx, 11), DesfireSecureChannelOpts, &schann)) { + CLIParserFree(ctx); + return PM3_EINVARG; + } + secureChannel = schann; + } + + bool APDULogging = arg_get_lit(ctx, 12); CLIParserFree(ctx); SetAPDULogging(APDULogging); @@ -1640,7 +1768,7 @@ static int CmdHF14aDesChk(const char *Cmd) { } bool result = false; - uint8_t app_ids[78] = {0}; + uint8_t app_ids[DESFIRE_MAX_APP_COUNT * 3] = {0}; size_t app_ids_len = 0; clearCommandBuffer(); @@ -1649,7 +1777,6 @@ static int CmdHF14aDesChk(const char *Cmd) { DesfireSetKdf(&dctx, cmdKDFAlgo, kdfInput, kdfInputLen); DesfireSetCommandSet(&dctx, DCCNativeISO); DesfireSetCommMode(&dctx, DCMPlain); - DesfireSecureChannel secureChannel = DACEV1; // save card UID to dctx DesfireGetCardUID(&dctx); @@ -1662,11 +1789,28 @@ static int CmdHF14aDesChk(const char *Cmd) { } - res = DesfireGetAIDList(&dctx, app_ids, &app_ids_len); - if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Can't get list of applications on tag"); - DropField(); - return PM3_ESOFT; + // AID 000000 is the PICC level. + // GetApplicationIDs never lists it, so it has to be seeded manually + memset(app_ids, 0x00, 3); + app_ids_len = 3; + + uint8_t aidbuf[250] = {0}; + size_t aidbuflen = 0; + res = DesfireGetAIDList(&dctx, aidbuf, &aidbuflen); + if (res == PM3_SUCCESS) { + + if (aidbuflen > sizeof(app_ids) - 3) { + PrintAndLogEx(WARNING, "Card returned " _YELLOW_("%zu") " applications, only checking the first " _YELLOW_("%d"), aidbuflen / 3, DESFIRE_MAX_APP_COUNT - 1); + aidbuflen = sizeof(app_ids) - 3; + } + + memcpy(&app_ids[3], aidbuf, aidbuflen); + app_ids_len += aidbuflen; + + } else { + // the application list is gated by PICC key settings bit 1, so a locked + // card refuses it without auth. That is no reason to give up on the PICC master key + PrintAndLogEx(WARNING, "Can't get list of applications on tag, checking PICC level only"); } if (aidlength != 0) { @@ -1730,11 +1874,24 @@ static int CmdHF14aDesChk(const char *Cmd) { } } + desfire_keys_dump_t *dump = calloc(1, sizeof(desfire_keys_dump_t)); + if (dump == NULL) { + PrintAndLogEx(ERR, "Failed to allocate memory"); + DropField(); + return PM3_EMALLOC; + } + dump->appcount = app_ids_len / 3; + for (uint32_t x = 0; x < app_ids_len / 3; x++) { uint32_t curaid = (app_ids[x * 3] & 0xFF) + ((app_ids[(x * 3) + 1] & 0xFF) << 8) + ((app_ids[(x * 3) + 2] & 0xFF) << 16); PrintAndLogEx(INFO, "Checking aid " _YELLOW_("%06X"), curaid); + // found keys are tracked per application. A key number recovered on one + // AID must not stop us from checking the same key number on the next one + desfire_app_keys_t *found = &dump->app[x]; + found->aid = curaid; + bool loadedAllKeys = false; size_t desReadStart = 0; size_t desReadEnd = 1; @@ -1791,23 +1948,43 @@ static int CmdHF14aDesChk(const char *Cmd) { } } } else { - // single key given with --key + // only the key given with --key, inserted below + deskeyListLen = 0; + aeskeyListLen = 0; + k3kkeyListLen = 0; loadedAllKeys = true; } - res = AuthCheckDesfire(&dctx, secureChannel, &app_ids[x * 3], deskeyList, deskeyListLen, aeskeyList, aeskeyListLen, k3kkeyList, k3kkeyListLen, cmdKDFAlgo, kdfInputLen, kdfInput, foundKeys, &foundKeyThisRound, verbose); - if (res == PM3_EOPABORTED) { - break; + // the fills above reset the lengths and refill from index 0, so the + // key given with `--key` goes back to the head of its list every + // round. First tried, and never the one that gets dropped + if (vkeylen == 8) { + DesChkPrependKey((uint8_t *)deskeyList, sizeof(deskeyList[0]), &deskeyListLen, vkey); + } else if (vkeylen == 16) { + DesChkPrependKey((uint8_t *)aeskeyList, sizeof(aeskeyList[0]), &aeskeyListLen, vkey); + } else if (vkeylen == 24) { + DesChkPrependKey((uint8_t *)k3kkeyList, sizeof(k3kkeyList[0]), &k3kkeyListLen, vkey); } - result = (result || foundKeyThisRound); + if (deskeyListLen || aeskeyListLen || k3kkeyListLen) { - if (foundKeyThisRound == true && verbose == false) { - if (pattern1b || pattern2b) { - PrintAndLogEx(NORMAL, "p" NOLF); - } else if (dict_filenamelen) { - PrintAndLogEx(NORMAL, "d" NOLF); + res = AuthCheckDesfire(&dctx, + secureChannel, + &app_ids[x * 3], + deskeyList, deskeyListLen, + aeskeyList, aeskeyListLen, + k3kkeyList, k3kkeyListLen, + autoschann, + found, + &foundKeyThisRound, + verbose + ); + + if (res == PM3_EOPABORTED) { + break; } + + result = (result || foundKeyThisRound); } } @@ -1816,8 +1993,8 @@ static int CmdHF14aDesChk(const char *Cmd) { } } - if (verbose == false) { - PrintAndLogEx(NORMAL, ""); + if (result == false) { + PrintAndLogEx(WARNING, "No keys found"); } // save keys to json @@ -1829,31 +2006,19 @@ static int CmdHF14aDesChk(const char *Cmd) { uint8_t sel_1813 = 0; if (WaitForIso14aReply(&resp, 2500, NULL, &sel_1813) == false) { PrintAndLogEx(WARNING, "timeout while waiting for reply"); + free(dump); return PM3_ETIMEOUT; } - iso14a_card_select_t card; - memcpy(&card, (iso14a_card_select_t *)resp.data.asBytes, sizeof(iso14a_card_select_t)); - uint64_t select_status = sel_1813; // 0: couldn't read, 1: OK, with ATS, 2: OK, no ATS, 3: proprietary Anticollision - - uint8_t data[10 + 1 + 2 + 1 + 256 + (4 * 0xE * (24 + 1))] = {0}; - uint8_t atslen = 0; if (select_status == 1 || select_status == 2) { - memcpy(data, card.uid, card.uidlen); - data[10] = card.sak; - data[11] = card.atqa[1]; - data[12] = card.atqa[0]; - atslen = card.ats_len; - data[13] = atslen; - memcpy(&data[14], card.ats, atslen); + memcpy(&dump->card_info, (iso14a_card_select_t *)resp.data.asBytes, sizeof(iso14a_card_select_t)); } - // length: UID(10b)+SAK(1b)+ATQA(2b)+ATSlen(1b)+ATS(atslen)+foundKeys[2][64][AES_KEY_LEN + 1] - memcpy(&data[14 + atslen], foundKeys, 4 * 0xE * (24 + 1)); - saveFileJSON((char *)jsonname, jsfMfDesfireKeys, data, 0xE, NULL); + saveFileJSON((char *)jsonname, jsfMfDesfireKeys_v2, (uint8_t *)dump, sizeof(desfire_keys_dump_t), NULL); } + free(dump); DropField(); return PM3_SUCCESS; } @@ -1869,35 +2034,45 @@ static int DesfireAuthCheck(DesfireContext_t *dctx, DesfireISOSelectWay way, uin if (res == PM3_SUCCESS) { memcpy(dctx->key, key, desfire_get_key_length(dctx->keyType)); return PM3_SUCCESS; - } else if (res < 7) { + } + + // 4 - the challenge the PICC sent is the wrong length for this algo + // 50 - PICC didn't answer AES, 51 - PICC didn't answer LRP + // the application holds no key of this type, so every key in the list fails + // the same way and there is nothing to learn from trying the rest + bool wrongalgo = (res == 4 || res == 50 || res == 51); + + if (res < 7) { DropField(); - res = DesfireSelect(dctx, way, appID, NULL); - if (res != PM3_SUCCESS) { + if (DesfireSelect(dctx, way, appID, NULL) != PM3_SUCCESS) { return -10; } - return -11; + return (wrongalgo) ? -12 : -11; } - return -1; + + return (wrongalgo) ? -12 : -1; } static int CmdHF14aDesDetect(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hf mfdes detect", - "Detect key type and tries to find one from the list.", - "hf mfdes detect -> detect key 0 from PICC level\n" - "hf mfdes detect --schann d40 -> detect key 0 from PICC level via secure channel D40\n" - "hf mfdes detect -f mfdes_default_keys -> detect key 0 from PICC level with help of the standard dictionary\n" - "hf mfdes detect --aid 123456 -n 2 --save -> detect key 2 from app 123456 and if succeed - save params to defaults (`default` command)\n" - "hf mfdes detect --isoid df01 --save -> detect key 0 and save to defaults with card in the LRP mode"); + "Detect PICC master key, key type, communication mode, command set and channel mode.\n" + "Uses `mfdes_default_keys.dic` per default\n" + " `--save` it saves details to be used with `hf mfdes default`\n", + "hf mfdes detect\n" + "hf mfdes detect --schann d40 -> detect from PICC level via secure channel D40\n" + "hf mfdes detect -f my_keys -> detect from PICC level with your own dictionary\n" + "hf mfdes detect --aid 123456 -n 2 --save -> detect key 2 from app 123456 and save params to defaults\n" + "hf mfdes detect --isoid df01 --save -> detect and save to defaults with card in the LRP mode"); void *argtable[] = { arg_param_begin, arg_lit0("a", "apdu", "Show APDU requests and responses"), arg_lit0("v", "verbose", "Verbose output"), - arg_int0("n", "keyno", "", "Key number"), + arg_int0("n", "keyno", "", "Key number (def: all)"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -1906,7 +2081,7 @@ static int CmdHF14aDesDetect(const char *Cmd) { arg_str0(NULL, "aid", "", "Application ID (3 hex bytes, big endian)"), arg_str0(NULL, "isoid", "", "Application ISO ID (ISO DF ID) (2 hex bytes, big endian)."), arg_str0(NULL, "dfname", "", "Application ISO DF Name (5-16 hex bytes, big endian)"), - arg_str0("f", "file", "", "Filename of dictionary"), + arg_str0("f", "file", "", "Filename of dictionary (default: `" MFDES_DEFAULT_DICT "`)"), arg_lit0(NULL, "save", "Save found key and parameters to defaults"), arg_param_end }; @@ -1935,6 +2110,19 @@ static int CmdHF14aDesDetect(const char *Cmd) { bool save = arg_get_lit(ctx, 15); + // whether the user pinned a secure channel, or we get to detect one + bool schannset = (arg_get_str(ctx, 10)->count > 0); + + // whether the user asked for one key number, or we sweep the application + bool keynoset = (arg_get_int_count(ctx, 3) > 0); + + // no dictionary given - use the bundled DESFire one. The built-in + // g_mifare_plus_default_keys list is 16 byte AES only, so it can produce + // neither the DES nor the 3K3DES defaults this card family ships with + if (dict_filenamelen == 0) { + dict_filenamelen = snprintf((char *)dict_filename, sizeof(dict_filename), "%s", MFDES_DEFAULT_DICT); + } + SetAPDULogging(APDULogging); CLIParserFree(ctx); @@ -1942,12 +2130,12 @@ static int CmdHF14aDesDetect(const char *Cmd) { res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, true, verbose); if (res != PM3_SUCCESS) { DropField(); - PrintAndLogEx(FAILED, "Select or authentication %s " _RED_("failed") ". Result [%d] %s", DesfireWayIDStr(selectway, id), res, DesfireAuthErrorToStr(res)); return res; } bool keytypes[4] = {0}; bool uselrp = false; + uint8_t numkeys = 0; uint8_t data[250] = {0}; size_t datalen = 0; @@ -1956,6 +2144,7 @@ static int CmdHF14aDesDetect(const char *Cmd) { if (res == PM3_SUCCESS && datalen >= 2) { uint8_t num_keys = data[1]; + numkeys = num_keys & 0x0F; switch (num_keys >> 6) { case 0: { @@ -1986,10 +2175,13 @@ static int CmdHF14aDesDetect(const char *Cmd) { if (authCmdCheck.auth) { keytypes[T_DES] = true; keytypes[T_3DES] = true; + } - if (authCmdCheck.authISO) { - keytypes[T_3K3DES] = true; - } + // 0x1A covers DES, 2TDEA and 3TDEA alike, so it cannot tell them + // apart - but it is the only command a 3TDEA application answers at + // all. Read it on its own or such an application names no key type + if (authCmdCheck.authISO) { + keytypes[T_3K3DES] = true; } if (authCmdCheck.authAES || authCmdCheck.authEV2) { @@ -2010,19 +2202,74 @@ static int CmdHF14aDesDetect(const char *Cmd) { res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, true, verbose); if (res != PM3_SUCCESS) { DropField(); - PrintAndLogEx(FAILED, "Select or authentication %s " _RED_("failed") ". Result [%d] %s", DesfireWayIDStr(selectway, id), res, DesfireAuthErrorToStr(res)); return res; } } - if (verbose) { + // An AES application runs either the EV1/EV2 channel or LRP, and the key + // settings byte reads the same for both, so it takes one probe to tell them + // apart. Without this an LRP card is only caught when the key settings + // happen to be unreadable and the fallback above runs. + if (schannset == false && uselrp == false && keytypes[T_AES]) { - if (DesfireMFSelected(selectway, id)) { - PrintAndLogEx(INFO, "Check PICC key num: %d (0x%02x)", dctx.keyNum, dctx.keyNum); - } else { - PrintAndLogEx(INFO, "Check: %s key num: %d (0x%02x)", DesfireWayIDStr(selectway, id), dctx.keyNum, dctx.keyNum); + uselrp = DesfireCheckAuthCmd(selectway, id, dctx.keyNum, MFDES_AUTHENTICATE_EV2F, true); + if (uselrp) { + securechann = DACLRP; } + // the probe dropped the field behind us + res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, true, verbose); + if (res != PM3_SUCCESS) { + DropField(); + return res; + } + } + + // Without -n we sweep every key number the application declares. + // All keys in one DESFire application share an algo + uint8_t keynofirst = dctx.keyNum; + uint8_t keynolast = dctx.keyNum; + if (keynoset == false) { + keynofirst = 0; + keynolast = (numkeys > 0 && numkeys <= DESFIRE_MAX_KEY_COUNT) ? (numkeys - 1) : (DESFIRE_MAX_KEY_COUNT - 1); + } + + char algostr[64] = {0}; + size_t algolen = 0; + for (uint8_t t = T_DES; t <= T_AES; t++) { + if (keytypes[t] == false) { + continue; + } + + int n = snprintf(algostr + algolen, sizeof(algostr) - algolen, "%s%s", (algolen) ? "/" : "", CLIGetOptionListStr(DesfireAlgoOpts, t)); + if (n < 0) { + break; + } + algolen += (size_t)n; + if (algolen >= sizeof(algostr)) { + algolen = sizeof(algostr) - 1; + break; + } + } + if (algolen == 0) { + snprintf(algostr, sizeof(algostr), "unknown"); + } + + char keynostr[32] = {0}; + if (keynofirst == keynolast) { + snprintf(keynostr, sizeof(keynostr), _YELLOW_("0x%02x"), keynofirst); + } else { + snprintf(keynostr, sizeof(keynostr), _YELLOW_("0x%02x") ".." _YELLOW_("0x%02x"), keynofirst, keynolast); + } + + PrintAndLogEx(INFO, "%s... key num %s, algo " _YELLOW_("%s") ", channel " _YELLOW_("%s"), + (DesfireMFSelected(selectway, id)) ? "PICC level" : DesfireWayIDStr(selectway, id), + keynostr, + algostr, + CLIGetOptionListStr(DesfireSecureChannelOpts, securechann) + ); + + if (verbose) { PrintAndLogEx(INFO, "keys: DES: %s 2TDEA: %s 3TDEA: %s AES: %s LRP: %s", keytypes[T_DES] ? _GREEN_("YES") : _RED_("NO"), keytypes[T_3DES] ? _GREEN_("YES") : _RED_("NO"), @@ -2032,72 +2279,46 @@ static int CmdHF14aDesDetect(const char *Cmd) { ); } - // for key types - bool found = false; - size_t errcount = 0; - for (uint8_t ktype = T_DES; ktype <= T_AES; ktype++) { + uint8_t foundcount = 0; + uint8_t totalkeys = keynolast - keynofirst + 1; + bool nocard = false; - if (keytypes[ktype] == false) { - continue; - } + // the first key we find is what --save stores + DesfireContext_t savedctx = {0}; + bool savedctxvalid = false; - dctx.keyType = ktype; + for (uint8_t keyno = keynofirst; keyno <= keynolast && nocard == false; keyno++) { - if (verbose) { - PrintAndLogEx(INFO, "Scan key type: %s", CLIGetOptionListStr(DesfireAlgoOpts, dctx.keyType)); - } + dctx.keyNum = keyno; + bool found = false; + uint8_t tried[MFDES_DETECT_TRIED_MAX][1 + DESFIRE_MAX_KEY_SIZE] = {0}; + uint16_t triedcount = 0; + uint32_t skipped = 0; - if (dict_filenamelen == 0) { - // keys from mifaredefault.h - for (int i = 0; i < g_mifare_plus_default_keys_len; i++) { + // for key types + for (uint8_t ktype = T_DES; ktype <= T_AES && found == false; ktype++) { - uint8_t key[DESFIRE_MAX_KEY_SIZE] = {0}; - if (hex_to_bytes(g_mifare_plus_default_keys[i], key, 16) != 16) { - continue; - } - - if (ktype == T_3K3DES) { - memcpy(&key[16], key, 8); - } - - res = DesfireAuthCheck(&dctx, selectway, id, securechann, key); - if (res == PM3_SUCCESS) { - found = true; - break; // all the params already in the dctx - } - - if (res == -10) { - - if (verbose) { - PrintAndLogEx(ERR, "Can't select AID. There is no connection with card."); - } - - found = false; - break; // we can't select app after invalid 1st auth stages - } - - if (res == -11) { - - if (errcount > 10) { - if (verbose) { - PrintAndLogEx(ERR, "Too much errors (%zu) from card", errcount); - } - break; - } - errcount++; - - } else { - errcount = 0; - } + if (keytypes[ktype] == false) { + continue; } - } else { - // keys from file + dctx.keyType = ktype; + + if (verbose) { + PrintAndLogEx(INFO, "Scan key num %d (0x%02x) type: %s", keyno, keyno, CLIGetOptionListStr(DesfireAlgoOpts, dctx.keyType)); + } + + // candidate keys come from the dictionary uint8_t keyList[MAX_KEYS_LIST_LEN * MAX_KEY_LEN] = {0}; uint32_t keyListLen = 0; size_t keylen = desfire_get_key_length(dctx.keyType); size_t endFilePosition = 0; + // errors are counted per key type. A bad run on one must not cut + // the next one short before it has tried a single key + size_t errcount = 0; + bool wrongalgo = false; + while (found == false) { res = loadFileDICTIONARYEx((char *)dict_filename, keyList, sizeof(keyList), NULL, keylen, &keyListLen, endFilePosition, &endFilePosition, verbose); @@ -2105,9 +2326,50 @@ static int CmdHF14aDesDetect(const char *Cmd) { break; } - for (int i = 0; i < keyListLen; i++) { + for (uint32_t i = 0; i < keyListLen; i++) { - res = DesfireAuthCheck(&dctx, selectway, id, securechann, &keyList[i * keylen]); + uint8_t *candidate = &keyList[i * keylen]; + + // fingerprint: the cipher this key really drives + uint8_t fp[1 + DESFIRE_MAX_KEY_SIZE] = {0}; + uint8_t fplen; + + if (dctx.keyType == T_DES || + ( + (dctx.keyType == T_3DES) && + (keylen == 16) && + (memcmp(candidate, candidate + 8, 8) == 0) + )) { + + fp[0] = T_DES; // single DES, however it was written + memcpy(fp + 1, candidate, 8); + fplen = 1 + 8; + + } else { + fp[0] = dctx.keyType; + memcpy(fp + 1, candidate, keylen); + fplen = 1 + keylen; + } + + bool already = false; + for (uint16_t d = 0; d < triedcount; d++) { + if (memcmp(tried[d], fp, fplen) == 0) { + already = true; + break; + } + } + + if (already) { + skipped++; + continue; + } + + if (triedcount < MFDES_DETECT_TRIED_MAX) { + memcpy(tried[triedcount], fp, sizeof(fp)); + triedcount++; + } + + res = DesfireAuthCheck(&dctx, selectway, id, securechann, candidate); if (res == PM3_SUCCESS) { found = true; break; // all the params already in the dctx @@ -2118,10 +2380,20 @@ static int CmdHF14aDesDetect(const char *Cmd) { PrintAndLogEx(ERR, "Can't select AID. There is no connection with card."); } - found = false; + nocard = true; break; // we can't select app after invalid 1st auth stages } + if (res == -12) { + if (verbose) { + PrintAndLogEx(INFO, "Key type %s is not used by this application, skipping it", + CLIGetOptionListStr(DesfireAlgoOpts, dctx.keyType)); + } + + wrongalgo = true; + break; + } + if (res == -11) { if (errcount > 10) { @@ -2135,51 +2407,73 @@ static int CmdHF14aDesDetect(const char *Cmd) { } else { errcount = 0; } + } + if (nocard || wrongalgo) { + break; } if (endFilePosition == 0) { break; } } + } + if (verbose && skipped) { + PrintAndLogEx(INFO, "Skipped " _YELLOW_("%u") " duplicate keys", skipped); } if (found) { - break; + + foundcount++; + + if (DesfireMFSelected(selectway, id)) { + PrintAndLogEx(INFO, _GREEN_("Found") " key num: %d (0x%02x)", dctx.keyNum, dctx.keyNum); + } else { + PrintAndLogEx(INFO, "Found key for: %s key num: %d (0x%02x)", DesfireWayIDStr(selectway, id), dctx.keyNum, dctx.keyNum); + } + + PrintAndLogEx(INFO, "Channel " _GREEN_("%s") " key " _GREEN_("%s") " [%d]: " _GREEN_("%s"), + CLIGetOptionListStr(DesfireSecureChannelOpts, securechann), + CLIGetOptionListStr(DesfireAlgoOpts, dctx.keyType), + desfire_get_key_length(dctx.keyType), + sprint_hex_inrow(dctx.key, desfire_get_key_length(dctx.keyType)) + ); + + // every key in an application uses the same algo, so the rest of + // the key numbers only have to try the one that just worked + for (uint8_t t = T_DES; t <= T_AES; t++) { + keytypes[t] = (t == dctx.keyType); + } + + if (savedctxvalid == false) { + savedctx = dctx; + savedctxvalid = true; + } + + } else if (verbose && nocard == false) { + PrintAndLogEx(INFO, "Key num: %d (0x%02x) " _RED_("not found"), keyno, keyno); } } - if (found) { - - if (DesfireMFSelected(selectway, id)) { - PrintAndLogEx(INFO, _GREEN_("Found") " key num: %d (0x%02x)", dctx.keyNum, dctx.keyNum); - } else { - PrintAndLogEx(INFO, "Found key for: %s key num: %d (0x%02x)", DesfireWayIDStr(selectway, id), dctx.keyNum, dctx.keyNum); - } - - PrintAndLogEx(INFO, "channel " _GREEN_("%s") " key " _GREEN_("%s") " [%d]: " _GREEN_("%s"), - CLIGetOptionListStr(DesfireSecureChannelOpts, securechann), - CLIGetOptionListStr(DesfireAlgoOpts, dctx.keyType), - desfire_get_key_length(dctx.keyType), - sprint_hex(dctx.key, desfire_get_key_length(dctx.keyType))); - - } else { + if (foundcount == 0) { PrintAndLogEx(INFO, "Key " _RED_("not found")); + } else if (totalkeys > 1) { + PrintAndLogEx(INFO, "Found " _GREEN_("%u") " of %u keys", foundcount, totalkeys); } DropField(); - if (found && save) { + if (savedctxvalid && save) { - defaultKeyNum = dctx.keyNum; - defaultAlgoId = dctx.keyType; - memcpy(defaultKey, dctx.key, DESFIRE_MAX_KEY_SIZE); - defaultKdfAlgo = dctx.kdfAlgo; - defaultKdfInputLen = dctx.kdfInputLen; - memcpy(defaultKdfInput, dctx.kdfInput, sizeof(dctx.kdfInput)); + defaultKeyNum = savedctx.keyNum; + defaultAlgoId = savedctx.keyType; + memcpy(defaultKey, savedctx.key, DESFIRE_MAX_KEY_SIZE); + defaultKdfAlgo = savedctx.kdfAlgo; + defaultKdfInputLen = savedctx.kdfInputLen; + memcpy(defaultKdfInput, savedctx.kdfInput, sizeof(savedctx.kdfInput)); defaultSecureChannel = securechann; - defaultCommSet = dctx.cmdSet; + defaultCommSet = savedctx.cmdSet; PrintAndLogEx(INFO, "-----------" _CYAN_("Default parameters") "---------------------------------"); PrintAndLogEx(INFO, "Key Num....... %d", defaultKeyNum); @@ -2215,7 +2509,7 @@ static int CmdHF14aDesMAD(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -2389,7 +2683,7 @@ static int CmdHF14ADesSelectApp(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -2980,6 +3274,7 @@ static int DesfireGetDelegatedInfoNoFieldOn(DesfireContext_t *dctx, uint16_t dam } if (respcode != MFDES_S_OPERATION_OK) { + DesfireClearSession(dctx); return PM3_EAPDU_FAIL; } @@ -3235,7 +3530,6 @@ static int CmdHF14ADesBruteISOFIDs(const char *Cmd) { res = DesfireSelectAndAuthenticateW(&dctx, securechann, selectway, appid, false, 0, true, verbose); if (res != PM3_SUCCESS) { DropField(); - PrintAndLogEx(FAILED, "Select or authentication %s " _RED_("failed") ". Result [%d] %s", DesfireWayIDStr(selectway, appid), res, DesfireAuthErrorToStr(res)); return res; } @@ -3332,7 +3626,7 @@ static int CmdHF14ADesBruteDAMSlots(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number (default: 0 / PICC key)"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -3538,7 +3832,7 @@ static int CmdHF14ADesAuth(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -3573,7 +3867,6 @@ static int CmdHF14ADesAuth(const char *Cmd) { res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, false, verbose); if (res != PM3_SUCCESS) { DropField(); - PrintAndLogEx(FAILED, "Select or authentication %s " _RED_("failed") ". Result [%d] %s", DesfireWayIDStr(selectway, id), res, DesfireAuthErrorToStr(res)); return res; } @@ -3637,7 +3930,7 @@ static int CmdHF14ADesSetConfiguration(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -3708,12 +4001,6 @@ static int CmdHF14ADesSetConfiguration(const char *Cmd) { res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, false, verbose); if (res != PM3_SUCCESS) { DropField(); - PrintAndLogEx(FAILED, "Select or authentication ( %s ) Result [%d] %s %s", - DesfireWayIDStr(selectway, id), - res, - DesfireAuthErrorToStr(res), - _RED_("failed") - ); return res; } @@ -3735,8 +4022,8 @@ static int CmdHF14ADesChangeKey(const char *Cmd) { "Change crypto algorithm for PICC key is possible, \n" "but for APP keys crypto algorithm is set by createapp command and can't be changed wo application delete\n" "\n" - "hf mfdes changekey --aid 123456 -> execute with default factory setup. change des key 0 in the app 123456 from 00..00 to 00..00\n" - "hf mfdes changekey --isoid df01 -t aes --schann lrp --newkeyno 01 -> change key 01 via lrp channel" + "hf mfdes changekey --aid 123456 -> execute with default factory setup. change des key 0 in the app 123456 from 00..00 to 00..00\n" + "hf mfdes changekey --isoid df01 -t aes --schann lrp --newkeyno 01 -> change key 01 via lrp channel" "hf mfdes changekey -t des --newalgo aes --newkey 11223344556677889900112233445566 --newver a5 -> change card master key to AES one\n" "hf mfdes changekey --aid 123456 -t aes --key 00000000000000000000000000000000 --newkey 11223344556677889900112233445566 -> change app master key\n" "hf mfdes changekey --aid 123456 -t des -n 0 --newkeyno 1 --oldkey 5555555555555555 --newkey 1122334455667788 -> change key 1 with auth from key 0\n" @@ -3748,7 +4035,7 @@ static int CmdHF14ADesChangeKey(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -3850,7 +4137,6 @@ static int CmdHF14ADesChangeKey(const char *Cmd) { res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, false, verbose); if (res != PM3_SUCCESS) { DropField(); - PrintAndLogEx(FAILED, "Select or authentication %s " _RED_("failed") ". Result [%d] %s", DesfireWayIDStr(selectway, id), res, DesfireAuthErrorToStr(res)); return res; } @@ -3910,7 +4196,7 @@ static int CmdHF14ADesCreateApp(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -4087,7 +4373,7 @@ static int CmdHF14ADesCreateDelegateApp(const char *Cmd) { arg_lit0("a", "apdu", "Show APDU requests and responses"), arg_lit0("v", "verbose", "Verbose output"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -4404,7 +4690,7 @@ static int CmdHF14ADesGetDelegateAppInfo(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number (default: 0 / PICC key)"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -4496,7 +4782,7 @@ static int CmdHF14ADesDeleteApp(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -4560,7 +4846,7 @@ static int CmdHF14ADesGetUID(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -4592,7 +4878,6 @@ static int CmdHF14ADesGetUID(const char *Cmd) { res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, false, verbose); if (res != PM3_SUCCESS) { DropField(); - PrintAndLogEx(FAILED, "Select or authentication %s " _RED_("failed") ". Result [%d] %s", DesfireWayIDStr(selectway, id), res, DesfireAuthErrorToStr(res)); return res; } @@ -4723,7 +5008,7 @@ static int CmdHF14ADesFormatPICC(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -4780,7 +5065,7 @@ static int CmdHF14ADesGetFreeMem(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -4845,7 +5130,7 @@ static int CmdHF14ADesChKeySettings(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -4919,7 +5204,7 @@ static int CmdHF14ADesGetKeyVersions(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number for authentication"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -4974,7 +5259,6 @@ static int CmdHF14ADesGetKeyVersions(const char *Cmd) { res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, noauth, verbose); if (res != PM3_SUCCESS) { DropField(); - PrintAndLogEx(FAILED, "Select or authentication %s " _RED_("failed") ". Result [%d] %s", DesfireWayIDStr(selectway, id), res, DesfireAuthErrorToStr(res)); return res; } @@ -5024,7 +5308,7 @@ static int CmdHF14ADesGetKeySettings(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -5104,7 +5388,7 @@ static int CmdHF14ADesGetAIDs(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -5176,7 +5460,7 @@ static int CmdHF14ADesGetAppNames(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -5239,9 +5523,10 @@ static int CmdHF14ADesGetFileIDs(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hf mfdes getfileids", "Get File IDs list from card. Master key needs to be provided or flag --no-auth set.", - "hf mfdes getfileids --aid 123456 -> execute with defaults from `default` command\n" - "hf mfdes getfileids -n 0 -t des -k 0000000000000000 --kdf none --aid 123456 -> execute with default factory setup\n" - "hf mfdes getfileids --dfname D2760000850100 -> select DF by name and get file IDs"); + "hf mfdes getfileids --aid 123456 -> execute with defaults from `default` command\n" + "hf mfdes getfileids --dfname D2760000850100 -> select DF by name and get file IDs\n" + "hf mfdes getfileids -n 0 -t des -k 0000000000000000 --aid 123456 -> execute with default factory setup\n" + ); void *argtable[] = { arg_param_begin, @@ -5249,7 +5534,7 @@ static int CmdHF14ADesGetFileIDs(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -5283,7 +5568,6 @@ static int CmdHF14ADesGetFileIDs(const char *Cmd) { res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, noauth, verbose); if (res != PM3_SUCCESS) { DropField(); - PrintAndLogEx(FAILED, "Select or authentication %s " _RED_("failed") ". Result [%d] %s", DesfireWayIDStr(selectway, id), res, DesfireAuthErrorToStr(res)); return res; } @@ -5326,7 +5610,7 @@ static int CmdHF14ADesGetFileISOIDs(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -5360,7 +5644,6 @@ static int CmdHF14ADesGetFileISOIDs(const char *Cmd) { res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, noauth, verbose); if (res != PM3_SUCCESS) { DropField(); - PrintAndLogEx(FAILED, "Select or authentication %s " _RED_("failed") ". Result [%d] %s", DesfireWayIDStr(selectway, id), res, DesfireAuthErrorToStr(res)); return res; } @@ -5401,7 +5684,7 @@ static int CmdHF14ADesGetFileSettings(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -5442,7 +5725,6 @@ static int CmdHF14ADesGetFileSettings(const char *Cmd) { res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, noauth, verbose); if (res != PM3_SUCCESS) { DropField(); - PrintAndLogEx(FAILED, "Select or authentication %s " _RED_("failed") ". Result [%d] %s", DesfireWayIDStr(selectway, id), res, DesfireAuthErrorToStr(res)); return res; } @@ -5572,7 +5854,7 @@ static int CmdHF14ADesChFileSettings(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -5645,7 +5927,6 @@ static int CmdHF14ADesChFileSettings(const char *Cmd) { res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, noauth, verbose); if (res != PM3_SUCCESS) { DropField(); - PrintAndLogEx(FAILED, "Select or authentication %s " _RED_("failed") ". Result [%d] %s", DesfireWayIDStr(selectway, id), res, DesfireAuthErrorToStr(res)); return res; } @@ -5715,7 +5996,7 @@ static int CmdHF14ADesCreateFile(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -5853,7 +6134,7 @@ static int CmdHF14ADesCreateValueFile(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo (deft: 2TDEA)"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -5979,7 +6260,7 @@ static int CmdHF14ADesCreateRecordFile(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -6098,7 +6379,7 @@ static int CmdHF14ADesCreateTrMACFile(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -6180,7 +6461,6 @@ static int CmdHF14ADesCreateTrMACFile(const char *Cmd) { res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, noauth, verbose); if (res != PM3_SUCCESS) { DropField(); - PrintAndLogEx(FAILED, "Select or authentication %s " _RED_("failed") ". Result [%d] %s", DesfireWayIDStr(selectway, id), res, DesfireAuthErrorToStr(res)); return res; } @@ -6215,7 +6495,7 @@ static int CmdHF14ADesDeleteFile(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -6260,7 +6540,6 @@ static int CmdHF14ADesDeleteFile(const char *Cmd) { res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, noauth, verbose); if (res != PM3_SUCCESS) { DropField(); - PrintAndLogEx(FAILED, "Select or authentication %s " _RED_("failed") ". Result [%d] %s", DesfireWayIDStr(selectway, id), res, DesfireAuthErrorToStr(res)); return res; } @@ -6277,6 +6556,23 @@ static int CmdHF14ADesDeleteFile(const char *Cmd) { return PM3_SUCCESS; } +// Which access rights can grant each value file operation. Credit needs read&write +// only, the others are granted by any of read / write / read&write. The FreeValue +// option bit makes GetValue free whatever the rights say. +// Measured on DESFire EV2 hw, `ev1` and `ev2` secure channels. +static DesfireCommunicationMode DesfireValueOpCommMode(DesfireContext_t *dctx, const FileSettings_t *fsettings, uint8_t vop) { + if (vop == MFDES_GET_VALUE && (fsettings->limitedCredit & 0x02) != 0) + return DCMPlain; + + if (vop == MFDES_CREDIT) { + const uint8_t rwonly[] = { fsettings->rwAccess }; + return DesfireEffectiveCommMode(dctx, fsettings->commMode, rwonly, ARRAYLEN(rwonly)); + } + + const uint8_t anyright[] = { fsettings->rAccess, fsettings->wAccess, fsettings->rwAccess }; + return DesfireEffectiveCommMode(dctx, fsettings->commMode, anyright, ARRAYLEN(anyright)); +} + static int CmdHF14ADesValueOperations(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hf mfdes value", @@ -6293,7 +6589,7 @@ static int CmdHF14ADesValueOperations(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo (deft: 2TDEA)"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -6351,26 +6647,57 @@ static int CmdHF14ADesValueOperations(const char *Cmd) { res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, noauth, verbose); if (res != PM3_SUCCESS) { DropField(); - PrintAndLogEx(FAILED, "Select or authentication ( %s )" _RED_("failed") " Result [%d] %s", DesfireWayIDStr(selectway, id), res, DesfireAuthErrorToStr(res)); return res; } if (verbose) PrintAndLogEx(INFO, "%s file %02x operation: %s value: 0x%08x", DesfireWayIDStr(selectway, id), fileid, CLIGetOptionListStr(DesfireValueFileOperOpts, op), value); + // the PICC picks the communication mode from the file settings and the access rights, + // so read them instead of guessing from the command line + FileSettings_t fsettings = {0}; + bool havesettings = false; + + DesfireCommunicationMode chmode = dctx.commMode; + DesfireSetCommMode(&dctx, DCMMACed); + res = DesfireFileSettingsStruct(&dctx, fileid, &fsettings); + DesfireSetCommMode(&dctx, chmode); + + if (res == PM3_SUCCESS) { + havesettings = true; + + if (fsettings.fileType != 0x02) { + PrintAndLogEx(WARNING, "File %02x is " _RED_("not") " a value file, got %s", fileid, GetDesfireFileType(fsettings.fileType)); + } + + if (verbose) { + PrintAndLogEx(INFO, "Value file %02x comm mode: %s", fileid, CLIGetOptionListStr(DesfireCommunicationModeOpts, fsettings.commMode)); + } + + } else { + PrintAndLogEx(WARNING, "GetFileSettings error. Can't get the file communication mode."); + } + if (op != 0xff) { + if (havesettings) { + DesfireSetCommMode(&dctx, DesfireValueOpCommMode(&dctx, &fsettings, op)); + } + res = DesfireValueFileOperations(&dctx, fileid, op, &value); if (res != PM3_SUCCESS) { PrintAndLogEx(ERR, "Desfire ValueFileOperations (0x%02x) command ( " _RED_("error") " ) Result: %d", op, res); DropField(); return PM3_ESOFT; } - if (verbose) + + if (verbose) { PrintAndLogEx(INFO, "Operation ( %s )" _GREEN_("ok"), CLIGetOptionListStr(DesfireValueFileOperOpts, op)); + } if (op == MFDES_GET_VALUE) { PrintAndLogEx(SUCCESS, "Value: " _GREEN_("%d (0x%08x)"), value, value); } else { + DesfireSetCommMode(&dctx, DCMMACed); res = DesfireCommitTransaction(&dctx, false, 0); if (res != PM3_SUCCESS) { @@ -6378,44 +6705,32 @@ static int CmdHF14ADesValueOperations(const char *Cmd) { DropField(); return PM3_ESOFT; } - if (verbose) + + if (verbose) { PrintAndLogEx(INFO, "Commit ( " _GREEN_("ok") " )"); + } PrintAndLogEx(SUCCESS, "Value changed " _GREEN_("successfully")); } } else { - DesfireCommunicationMode fileCommMode = dctx.commMode; + if (havesettings == false || fsettings.fileType != 0x02) { + PrintAndLogEx(ERR, "Need the value file settings to clear it"); + DropField(); + return PM3_ESOFT; + } + DesfireSetCommMode(&dctx, DesfireValueOpCommMode(&dctx, &fsettings, MFDES_GET_VALUE)); res = DesfireValueFileOperations(&dctx, fileid, MFDES_GET_VALUE, &value); if (res != PM3_SUCCESS) { PrintAndLogEx(ERR, "Desfire GetValue command ( " _RED_("error") ") Result: %d", res); DropField(); return PM3_ESOFT; } - if (verbose) + if (verbose) { PrintAndLogEx(INFO, _YELLOW_("GetValue") " command is " _GREEN_("ok") ". Current value: 0x%08x", value); - - uint8_t buf[250] = {0}; - size_t buflen = 0; - - DesfireSetCommMode(&dctx, DCMMACed); - res = DesfireGetFileSettings(&dctx, fileid, buf, &buflen); - if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Desfire GetFileSettings command ( " _RED_("error") " ) Result: %d", res); - DropField(); - return PM3_ESOFT; } - if (verbose) - PrintAndLogEx(INFO, _YELLOW_("GetFileSettings") " is " _GREEN_("ok") " . File settings[%zu]: %s", buflen, sprint_hex(buf, buflen)); - - if (buflen < 8 || buf[0] != 0x02) { - PrintAndLogEx(ERR, "Desfire GetFileSettings command returns " _RED_("wrong") " data"); - DropField(); - return PM3_ESOFT; - } - - int32_t minvalue = (int)MemLeToUint4byte(&buf[4]); + int32_t minvalue = (int)fsettings.lowerLimit; uint32_t delta = ((int64_t)value > minvalue) ? value - minvalue : 0; if (verbose) { PrintAndLogEx(INFO, "value: 0x%08x (%d)", value, value); @@ -6424,10 +6739,11 @@ static int CmdHF14ADesValueOperations(const char *Cmd) { } if (delta > 0) { - DesfireSetCommMode(&dctx, fileCommMode); + DesfireSetCommMode(&dctx, DesfireValueOpCommMode(&dctx, &fsettings, MFDES_DEBIT)); uint32_t maxdelta = 0x7fffffff; if (delta > maxdelta) { + res = DesfireValueFileOperations(&dctx, fileid, MFDES_DEBIT, &maxdelta); if (res != PM3_SUCCESS) { PrintAndLogEx(ERR, "Desfire Debit maxdelta operation ( " _RED_("error") " ) Result: %d", res); @@ -6449,8 +6765,9 @@ static int CmdHF14ADesValueOperations(const char *Cmd) { return PM3_ESOFT; } - if (verbose) + if (verbose) { PrintAndLogEx(INFO, "Value debited " _GREEN_("ok")); + } DesfireSetCommMode(&dctx, DCMMACed); res = DesfireCommitTransaction(&dctx, false, 0); @@ -6460,11 +6777,13 @@ static int CmdHF14ADesValueOperations(const char *Cmd) { return PM3_ESOFT; } - if (verbose) + if (verbose) { PrintAndLogEx(INFO, "Transaction :" _GREEN_("committed")); + } } else { - if (verbose) + if (verbose) { PrintAndLogEx(INFO, "Nothing to clear. Value already in the minimum level."); + } } PrintAndLogEx(SUCCESS, "Value cleared " _GREEN_("successfully")); @@ -6478,7 +6797,7 @@ static int CmdHF14ADesClearRecordFile(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hf mfdes clearrecfile", "Clear record file. Master key needs to be provided or flag --no-auth set (depend on cards settings).", - "hf mfdes clearrecfile --aid 123456 --fid 01 -> clear record file for: app=123456, file=01 with defaults from `default` command\n" + "hf mfdes clearrecfile --aid 123456 --fid 01 -> clear record file for: app=123456, file=01 with defaults from `default` command\n" "hf mfdes clearrecfile --isoid df01 --fid 01 --schann lrp -t aes -n 3 -> clear record file for lrp channel with key number 3"); void *argtable[] = { @@ -6487,7 +6806,7 @@ static int CmdHF14ADesClearRecordFile(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -6532,7 +6851,6 @@ static int CmdHF14ADesClearRecordFile(const char *Cmd) { res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, noauth, verbose); if (res != PM3_SUCCESS) { DropField(); - PrintAndLogEx(FAILED, "Select or authentication %s " _RED_("failed") ". Result [%d] %s", DesfireWayIDStr(selectway, id), res, DesfireAuthErrorToStr(res)); return res; } @@ -6658,7 +6976,7 @@ static int CmdHF14ADesMakeMFCLicense(const char *Cmd) { void *argtable[] = { arg_param_begin, arg_lit0("v", "verbose", "Show more output"), - arg_str0("k", "key", "", "Key for computing the MAC, must be HEX 16(AES)"), + arg_str0("k", "key", "", "Key for computing the MAC (16 hex bytes)"), arg_str0("b", "blk", "[,[,...]]", "The MFC blocks to map, must be given in ascending order (use the special value 'all' for all blocks)"), arg_lit0(NULL, "ka", "Allow updating key A from inside sector trailers mapped to DESFire files"), arg_lit0(NULL, "kb", "Allow updating key B from inside sector trailers mapped to DESFire files"), @@ -6893,7 +7211,7 @@ static int CmdHF14ADesCreateMFCMapping(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -7064,7 +7382,6 @@ static int CmdHF14ADesCreateMFCMapping(const char *Cmd) { res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, false, verbose); if (res != PM3_SUCCESS) { DropField(); - PrintAndLogEx(FAILED, "Select or authentication %s " _RED_("failed") ". Result [%d] %s", DesfireWayIDStr(selectway, id), res, DesfireAuthErrorToStr(res)); return res; } @@ -7225,15 +7542,19 @@ static int DesfileReadFileAndPrint(DesfireContext_t *dctx, } } - commMode = fsettings.commMode; + // free access (0x0e) makes the PICC answer in plain, whatever the file comm mode is + if (filetype == RFTValue) { + commMode = DesfireValueOpCommMode(dctx, &fsettings, MFDES_GET_VALUE); + } else { + const uint8_t rrights[] = { fsettings.rAccess, fsettings.rwAccess }; + commMode = DesfireEffectiveCommMode(dctx, fsettings.commMode, rrights, ARRAYLEN(rrights)); + } + // lrp needs to point exact mode if (dctx->secureChannel == DACLRP) { // read right == free if (fsettings.rAccess == 0xe) commMode = DCMPlain; - // get value access == free - if (filetype == RFTValue && (fsettings.limitedCredit & 0x02) != 0) - commMode = DCMPlain; } // calc max length @@ -7256,7 +7577,7 @@ static int DesfileReadFileAndPrint(DesfireContext_t *dctx, PrintAndLogEx(INFO, _CYAN_("File type:") " %s Option: %s comm mode: %s", GetDesfireFileType(fsettings.fileType), CLIGetOptionListStr(DesfireReadFileTypeOpts, filetype), - CLIGetOptionListStr(DesfireCommunicationModeOpts, fsettings.commMode) + CLIGetOptionListStr(DesfireCommunicationModeOpts, commMode) ); } } else { @@ -7410,7 +7731,7 @@ static int CmdHF14ADesReadData(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -7488,7 +7809,6 @@ static int CmdHF14ADesReadData(const char *Cmd) { res = DesfireSelectAndAuthenticateW(&dctx, securechann, selectway, id, fileisoidpresent, fileisoid, noauth, verbose); if (res != PM3_SUCCESS) { DropField(); - PrintAndLogEx(FAILED, "Select or authentication %s " _RED_("failed") ". Result [%d] %s", DesfireWayIDStr(selectway, id), res, DesfireAuthErrorToStr(res)); return res; } @@ -7582,7 +7902,7 @@ static int CmdHF14ADesWriteData(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -7691,7 +8011,6 @@ static int CmdHF14ADesWriteData(const char *Cmd) { res = DesfireSelectAndAuthenticateW(&dctx, securechann, selectway, id, fileisoidpresent, fileisoid, noauth, verbose); if (res != PM3_SUCCESS) { DropField(); - PrintAndLogEx(FAILED, "Select or authentication %s " _RED_("failed") ". Result [%d] %s", DesfireWayIDStr(selectway, id), res, DesfireAuthErrorToStr(res)); return res; } @@ -7708,8 +8027,9 @@ static int CmdHF14ADesWriteData(const char *Cmd) { return res; } - // get file settings - if (op == RFTAuto) { + // get file settings. Needed for the file type in `auto` mode, and always for the + // communication mode the PICC expects for this operation + { FileSettings_t fsettings; DesfireCommunicationMode commMode = dctx.commMode; @@ -7718,38 +8038,46 @@ static int CmdHF14ADesWriteData(const char *Cmd) { DesfireSetCommMode(&dctx, commMode); if (res == PM3_SUCCESS) { - switch (fsettings.fileType) { - case 0x00: - case 0x01: { - op = RFTData; - if (!commit) - commit = (fsettings.fileType == 0x01); - break; - } - case 0x02: { - op = RFTValue; - commit = true; - break; - } - case 0x03: - case 0x04: { - op = RFTRecord; - commit = true; - if (datalen > fsettings.recordSize) - PrintAndLogEx(WARNING, "Record size (%d) " _RED_("is less") " than data length (%d)", fsettings.recordSize, datalen); - break; - } - case 0x05: { - op = RFTMAC; - commit = false; - break; - } - default: { - break; + if (op == RFTAuto) { + switch (fsettings.fileType) { + case 0x00: + case 0x01: { + op = RFTData; + if (!commit) + commit = (fsettings.fileType == 0x01); + break; + } + case 0x02: { + op = RFTValue; + commit = true; + break; + } + case 0x03: + case 0x04: { + op = RFTRecord; + commit = true; + if (datalen > fsettings.recordSize) + PrintAndLogEx(WARNING, "Record size (%d) " _RED_("is less") " than data length (%d)", fsettings.recordSize, datalen); + break; + } + case 0x05: { + op = RFTMAC; + commit = false; + break; + } + default: { + break; + } } } - DesfireSetCommMode(&dctx, fsettings.commMode); + // free access (0x0e) makes the PICC expect the command in plain, whatever the file comm mode is + if (op == RFTValue) { + DesfireSetCommMode(&dctx, DesfireValueOpCommMode(&dctx, &fsettings, (debit) ? MFDES_DEBIT : MFDES_CREDIT)); + } else { + const uint8_t wrights[] = { fsettings.wAccess, fsettings.rwAccess }; + DesfireSetCommMode(&dctx, DesfireEffectiveCommMode(&dctx, fsettings.commMode, wrights, ARRAYLEN(wrights))); + } if (fsettings.fileCommMode != 0 && noauth) PrintAndLogEx(WARNING, "File needs communication mode `%s` but there is no authentication", CLIGetOptionListStr(DesfireCommunicationModeOpts, fsettings.commMode)); @@ -7764,7 +8092,7 @@ static int CmdHF14ADesWriteData(const char *Cmd) { PrintAndLogEx(INFO, "Got file type: %s. Option: %s. comm mode: %s", GetDesfireFileType(fsettings.fileType), CLIGetOptionListStr(DesfireReadFileTypeOpts, op), - CLIGetOptionListStr(DesfireCommunicationModeOpts, fsettings.commMode)); + CLIGetOptionListStr(DesfireCommunicationModeOpts, dctx.commMode)); } else { PrintAndLogEx(WARNING, "GetFileSettings error. Can't get file type."); } @@ -7922,7 +8250,7 @@ static int CmdHF14ADesLsFiles(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -7956,7 +8284,6 @@ static int CmdHF14ADesLsFiles(const char *Cmd) { res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, noauth, verbose); if (res != PM3_SUCCESS) { DropField(); - PrintAndLogEx(FAILED, "Select or authentication %s " _RED_("failed") ". Result [%d] %s", DesfireWayIDStr(selectway, id), res, DesfireAuthErrorToStr(res)); return res; } @@ -7976,8 +8303,13 @@ static int CmdHF14ADesLsFiles(const char *Cmd) { } PrintAndLogEx(INFO, "------------------------------------------ " _CYAN_("File list") " -----------------------------------------------------"); - for (int i = 0; i < filescount; i++) + for (int i = 0; i < filescount; i++) { + if (FileList[i].fileSettingsRead == false) { + PrintAndLogEx(WARNING, "File " _YELLOW_("0x%02x") " settings could not be read", FileList[i].fileNum); + continue; + } DesfirePrintFileSettingsTable((i == 0), FileList[i].fileNum, isopresent, FileList[i].fileISONum, &FileList[i].fileSettings); + } DropField(); return PM3_SUCCESS; @@ -7997,7 +8329,7 @@ static int CmdHF14ADesLsApp(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -8050,11 +8382,395 @@ static int CmdHF14ADesLsApp(const char *Cmd) { return PM3_SUCCESS; } +//----------------------------------------------------------------------------- +// DESFire card image collection. +// +// `hf mfdes dump` walks the whole PICC into a desfire_dump_t and writes it out +// as a jsfMfDesfire_v1 json file. `hf mfdes view` reads one back. +// See doc/mfdes_dump_format.md for the on-disk schema. +//----------------------------------------------------------------------------- + +// the 14a select answer carries UID/ATQA/SAK/ATS, none of which the DESFire +// layer keeps around +static int DesfireDumpFillCardInfo(iso14a_card_select_t *card_info) { + + DropField(); + SendIso14aReader(ISO14A_CONNECT | ISO14A_CLEARTRACE, NULL, 0); + + PacketResponseNG resp; + uint8_t select_status = 0; + if (WaitForIso14aReply(&resp, 2500, NULL, &select_status) == false) { + PrintAndLogEx(WARNING, "timeout while waiting for card select"); + return PM3_ETIMEOUT; + } + + // 0: couldn't read, 1: OK with ATS, 2: OK no ATS, 3: proprietary anticollision + if (select_status != 1 && select_status != 2) { + return PM3_ESOFT; + } + + memcpy(card_info, (iso14a_card_select_t *)resp.data.asBytes, sizeof(iso14a_card_select_t)); + return PM3_SUCCESS; +} + +// record a key we authenticated with. The algo is the application's, not the +// key's, so it is not stored here -- see desfire_dump_app_t.keytype +static void DesfireDumpStoreKey(desfire_dump_app_t *app, uint8_t keyno, uint8_t algo, const uint8_t *key) { + + if (keyno >= DESFIRE_MAX_KEY_COUNT) { + return; + } + + app->keytype = algo; + app->keys.present[keyno] = 1; + memcpy(app->keys.key[keyno], key, desfire_get_key_length(algo)); +} + +// pull keyno for `aid` out of a `hf mfdes chk` key file, NULL when we have none +static const uint8_t *DesfireDumpFindKey(const desfire_keys_dump_t *keyfile, uint32_t aid, uint8_t algo, uint8_t keyno) { + + if (keyfile == NULL || keyno >= DESFIRE_MAX_KEY_COUNT || algo >= DESFIRE_MAX_ALGO_COUNT) { + return NULL; + } + + for (uint8_t i = 0; i < keyfile->appcount && i < DESFIRE_MAX_APP_COUNT; i++) { + if (keyfile->app[i].aid != aid) { + continue; + } + if (keyfile->app[i].keys[algo][keyno][0] == 0) { + return NULL; + } + return &keyfile->app[i].keys[algo][keyno][1]; + } + return NULL; +} + +static void DesfireDumpFillAppMeta(desfire_dump_app_t *app, const AppListElm_t *src) { + + app->aid = src->appNum; + app->isofid = src->appISONum; + app->keysettings = src->keySettings; + app->numkeysraw = src->numKeysRaw; + app->numkeys = src->numberOfKeys; + app->keytype = src->keyType; + app->settings_ok = (src->numKeysRaw != 0); + + for (uint8_t i = 0; i < src->numberOfKeys && i < DESFIRE_MAX_KEY_COUNT; i++) { + app->keys.version[i] = src->keyVersions[i]; + app->keys.versionknown[i] = 1; + } + + app->dfnamelen = str_nlen((char *)src->appDFName, sizeof(src->appDFName)); + memcpy(app->dfname, src->appDFName, app->dfnamelen); +} + +// find the application the user named on the command line in the PICC's own +// list, so an --isoid or --dfname dump still records the AID and key settings +static int DesfireDumpFindApp(const AppListS appList, size_t appcount, const DesfireContext_t *dctx, + DesfireISOSelectWay selectway, uint32_t id) { + + for (size_t i = 0; i < appcount && i < DESFIRE_MAX_APP_COUNT; i++) { + + switch (selectway) { + case ISW6bAID: + if (appList[i].appNum == id) { + return i; + } + break; + case ISWIsoID: + if (appList[i].appISONum == id) { + return i; + } + break; + case ISWDFName: + if (dctx->selectedDFNameLen > 0 && + memcmp(appList[i].appDFName, dctx->selectedDFName, dctx->selectedDFNameLen) == 0) { + return i; + } + break; + case ISWMF: + break; + } + } + return -1; +} + +static void DesfireDumpFillFileSettings(const FileSettings_t *fs, desfire_dump_file_t *f, bool settings_ok) { + + // Settings we never read are not a 0 byte standard data file. Leave the + // whole record at its defaults and say so, the same way read_ok does for + // contents -- a simulator built from this image must not invent a file. + if (settings_ok == false) { + f->settings_ok = false; + return; + } + + f->type = fs->fileType; + f->commmode = fs->fileCommMode; + f->accessrights = fs->rawAccessRights; + f->size = fs->fileSize; + f->lowerlimit = fs->lowerLimit; + f->upperlimit = fs->upperLimit; + f->limitedcredit = fs->limitedCredit; + f->recordsize = fs->recordSize; + f->maxrecords = fs->maxRecordCount; + f->currecords = fs->curRecordCount; + + f->addrights_len = fs->additionalAccessRightsLength; + if (f->addrights_len > ARRAYLEN(f->addrights)) { + f->addrights_len = ARRAYLEN(f->addrights); + } + for (uint8_t i = 0; i < f->addrights_len; i++) { + f->addrights[i] = fs->additionalAccessRights[i]; + } + + f->settings_ok = true; +} + +// read one file into the image. Leaves f->read_ok false when the contents +// could not be fetched -- the caller must not turn that into zeroed data +static int DesfireDumpReadFile(DesfireContext_t *dctx, const FileSettings_t *fs, desfire_dump_file_t *f, + uint32_t maxdatafilelength, bool verbose) { + + f->read_ok = false; + + int filetype; + switch (fs->fileType) { + case 0x00: + case 0x01: + filetype = RFTData; + break; + case 0x02: + filetype = RFTValue; + break; + case 0x03: + case 0x04: + filetype = RFTRecord; + break; + case 0x05: + filetype = RFTMAC; + break; + default: + // nothing was sent, the session is still good + return PM3_EINVARG; + } + + // iso chaining works in the lrp mode + dctx->isoChaining |= (dctx->secureChannel == DACLRP); + + DesfireCommunicationMode commMode; + if (filetype == RFTValue) { + commMode = DesfireValueOpCommMode(dctx, fs, MFDES_GET_VALUE); + } else { + const uint8_t rrights[] = { fs->rAccess, fs->rwAccess }; + commMode = DesfireEffectiveCommMode(dctx, fs->commMode, rrights, ARRAYLEN(rrights)); + } + + // lrp needs to point exact mode + if (dctx->secureChannel == DACLRP && fs->rAccess == 0x0e) { + commMode = DCMPlain; + } + + if (fs->rAccess == 0x0f && fs->rwAccess == 0x0f) { + if (verbose) { + PrintAndLogEx(INFO, "File 0x%02x read access is denied (0x0F), skipping contents", f->num); + } + // nothing was sent, the session is still good + return PM3_EINVARG; + } + + DesfireSetCommMode(dctx, commMode); + + if (filetype == RFTValue) { + uint32_t value = 0; + if (DesfireValueFileOperations(dctx, f->num, MFDES_GET_VALUE, &value) != PM3_SUCCESS) { + return PM3_ESOFT; + } + f->value = value; + f->read_ok = true; + return PM3_SUCCESS; + } + + uint8_t *resp = calloc(DESFIRE_BUFFER_SIZE, sizeof(uint8_t)); + if (resp == NULL) { + PrintAndLogEx(WARNING, "Failed to allocate memory"); + return PM3_EMALLOC; + } + size_t resplen = 0; + int res; + + if (filetype == RFTRecord) { + + size_t reclen = fs->recordSize; + res = DesfireReadRecords(dctx, f->num, 0, 0, resp, &resplen); + if (res != PM3_SUCCESS) { + free(resp); + return PM3_ESOFT; + } + + if (reclen == 0 && resplen > 0) { + reclen = resplen; + } + f->recordsize = reclen; + + } else { + uint32_t length = 0; + if (filetype == RFTData && maxdatafilelength && (maxdatafilelength < fs->fileSize)) { + length = maxdatafilelength; + } + + res = DesfireReadFile(dctx, f->num, 0, length, resp, &resplen); + if (res != PM3_SUCCESS) { + free(resp); + return PM3_ESOFT; + } + } + + if (resplen == 0) { + // an empty answer is a successful read of nothing, keep read_ok true + // so a reader can tell it apart from "we never got there" + free(resp); + f->read_ok = true; + return PM3_SUCCESS; + } + + f->data = calloc(resplen, sizeof(uint8_t)); + if (f->data == NULL) { + PrintAndLogEx(WARNING, "Failed to allocate memory"); + free(resp); + return PM3_EMALLOC; + } + + memcpy(f->data, resp, resplen); + f->datalen = resplen; + f->read_ok = true; + free(resp); + return PM3_SUCCESS; +} + +static void DesfireDumpPrintFile(const desfire_dump_file_t *f, bool isopresent) { + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--------------------------------- " _CYAN_("File %02x") " ----------------------------------", f->num); + PrintAndLogEx(SUCCESS, "File ID : " _GREEN_("%02x"), f->num); + if (isopresent) { + if (f->isofid != 0) { + PrintAndLogEx(SUCCESS, "File ISO ID : %04x", f->isofid); + } else { + PrintAndLogEx(SUCCESS, "File ISO ID : " _YELLOW_("n/a")); + } + } + + if (f->read_ok == false) { + PrintAndLogEx(WARNING, "Contents : " _YELLOW_("not read")); + return; + } + + if (f->type == 0x02) { + PrintAndLogEx(SUCCESS, "Value : %u (0x%08x)", f->value, f->value); + return; + } + + if (f->datalen == 0) { + PrintAndLogEx(SUCCESS, "Contents : " _YELLOW_("empty")); + return; + } + + if ((f->type == 0x03 || f->type == 0x04) && f->recordsize > 0 && (f->datalen % f->recordsize) == 0) { + uint32_t reccount = f->datalen / f->recordsize; + PrintAndLogEx(SUCCESS, "Read %u bytes from file 0x%02x, %u record(s) of %u bytes", f->datalen, f->num, reccount, f->recordsize); + for (uint32_t i = 0; i < reccount; i++) { + if (i != 0) { + PrintAndLogEx(SUCCESS, "Record %u", i); + } + print_buffer_with_offset(f->data + (i * f->recordsize), f->recordsize, 0, (i == 0)); + } + return; + } + + PrintAndLogEx(SUCCESS, "Read %u bytes from file 0x%02x", f->datalen, f->num); + print_buffer_with_offset(f->data, f->datalen, 0, true); +} + +// collect one application. The caller has already selected and authenticated +static int DesfireDumpCollectApp(DesfireContext_t *dctx, desfire_dump_app_t *app, uint32_t maxlength, + DesfireISOSelectWay selectway, uint32_t id, int securechann, + bool noauth, bool verbose) { + + FileList_t FileList = {{0}}; + size_t filescount = 0; + bool isopresent = false; + + int res = DesfireFillFileList(dctx, FileList, &filescount, &isopresent); + if (res != PM3_SUCCESS) { + PrintAndLogEx(WARNING, "Can't get file list for application " _YELLOW_("%06X"), app->aid); + return res; + } + + // the ISO file id probe in DesfireFillFileList makes the PICC end the session on + // applications without ISO file ids, so get it back before reading the files + if (noauth == false && DesfireIsAuthenticated(dctx) == false) { + DesfireSetCommMode(dctx, DCMPlain); + res = DesfireSelectAndAuthenticateAppW(dctx, securechann, selectway, id, noauth, verbose); + if (res != PM3_SUCCESS) { + return res; + } + } + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(SUCCESS, "Application " _CYAN_("%s") " have " _GREEN_("%zu") " files", DesfireWayIDStr(selectway, id), filescount); + + if (selectway == ISW6bAID) { + DesfirePrintAIDFunctions(id); + } + + app->filecount = 0; + bool session_lost = false; + + for (size_t i = 0; i < filescount && i < DESFIRE_MAX_FILE_COUNT; i++) { + + // a refused exchange ends the PICC session, re-open it before the next file. + // a file we chose not to read never reached the card and costs us nothing + if (session_lost) { + DesfireSetCommMode(dctx, DCMPlain); + if (DesfireSelectAndAuthenticateAppW(dctx, securechann, selectway, id, noauth, verbose) != PM3_SUCCESS) { + PrintAndLogEx(WARNING, "Lost the session on application " _YELLOW_("%06X") ", stopping here", app->aid); + break; + } + session_lost = false; + } + + desfire_dump_file_t *f = &app->files[app->filecount]; + f->num = FileList[i].fileNum; + f->isofid = FileList[i].fileISONum; + DesfireDumpFillFileSettings(&FileList[i].fileSettings, f, FileList[i].fileSettingsRead); + app->filecount++; + + if (FileList[i].fileSettingsRead == false) { + // without the settings we do not know the file's type, so there is + // no sensible read command to send + PrintAndLogEx(WARNING, "File " _YELLOW_("0x%02x") " settings could not be read, contents skipped", f->num); + continue; + } + + session_lost = (DesfireDumpReadFile(dctx, &FileList[i].fileSettings, f, maxlength, verbose) == PM3_ESOFT); + + DesfireDumpPrintFile(f, isopresent); + DesfirePrintFileSettingsExtended(&FileList[i].fileSettings); + } + + return PM3_SUCCESS; +} + static int CmdHF14ADesDump(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hf mfdes dump", - "For each application show fil list and then file content. Key needs to be provided for authentication or flag --no-auth set (depend on cards settings).", - "hf mfdes dump --aid 123456 -> show file dump for: app=123456 with channel defaults from `default` command/n" + "Dump a DESFire card to a json file. Walks every application and every file\n" + "unless an application is named with --aid / --isoid / --dfname.\n" + "Key needs to be provided for authentication or flag --no-auth set (depend on cards settings).", + "hf mfdes dump -> dump the whole PICC with channel defaults from `default` command\n" + "hf mfdes dump --aid 123456 -> dump only application 123456\n" + "hf mfdes dump --keys hf-mfdes-0102030405-keys.json -> use recovered keys per application\n" "hf mfdes dump --isoid df01 --schann lrp -t aes --length 000090 -> lrp default settings with length limit"); void *argtable[] = { @@ -8063,7 +8779,7 @@ static int CmdHF14ADesDump(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -8074,6 +8790,9 @@ static int CmdHF14ADesDump(const char *Cmd) { arg_str0(NULL, "dfname", "", "Application ISO DF Name (5-16 hex bytes, big endian)"), arg_str0("l", "length", "", "Maximum length for read data files (3 hex bytes, big endian)"), arg_lit0(NULL, "no-auth", "Execute without authentication"), + arg_str0("f", "file", "", "Save dump to file, if no UID will be used as filename"), + arg_str0(NULL, "keys", "", "Load application keys from a `hf mfdes chk` key file"), + arg_lit0(NULL, "ns", "No save to file"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, false); @@ -8082,6 +8801,21 @@ static int CmdHF14ADesDump(const char *Cmd) { bool verbose = arg_get_lit(ctx, 2); bool noauth = arg_get_lit(ctx, 15); + // an application was named on the command line? then dump only that one + bool single_app = (arg_get_str(ctx, 11)->count > 0) || + (arg_get_str(ctx, 12)->count > 0) || + (arg_get_str(ctx, 13)->count > 0); + + int fnlen = 0; + char filename[FILE_PATH_SIZE] = {0}; + CLIParamStrToBuf(arg_get_str(ctx, 16), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen); + + int keyfnlen = 0; + char keyfilename[FILE_PATH_SIZE] = {0}; + CLIParamStrToBuf(arg_get_str(ctx, 17), (uint8_t *)keyfilename, FILE_PATH_SIZE, &keyfnlen); + + bool nosave = arg_get_lit(ctx, 18); + DesfireContext_t dctx = {0}; int securechann = defaultSecureChannel; uint32_t id = 0x000000; @@ -8101,60 +8835,1017 @@ static int CmdHF14ADesDump(const char *Cmd) { SetAPDULogging(APDULogging); CLIParserFree(ctx); - res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, noauth, verbose); + desfire_dump_t *dump = calloc(1, sizeof(desfire_dump_t)); + if (dump == NULL) { + PrintAndLogEx(ERR, "Failed to allocate memory"); + return PM3_EMALLOC; + } + + // UID / ATQA / SAK / ATS come from the 14a layer, grab them before we talk DESFire + DesfireDumpFillCardInfo(&dump->card_info); + DropField(); + + // no --keys given? look for the key file this card would have been saved + // under, the same `hf-mfdes--...` template the dump itself uses + bool autokeys = false; + if (keyfnlen == 0 && dump->card_info.uidlen > 0) { + strcat(keyfilename, "hf-mfdes-"); + FillFileNameByUID(keyfilename, dump->card_info.uid, "-keys", dump->card_info.uidlen); + keyfnlen = strlen(keyfilename); + autokeys = true; + } + + // optional key file from `hf mfdes chk` + desfire_keys_dump_t *keyfile = NULL; + if (keyfnlen > 0) { + keyfile = calloc(1, sizeof(desfire_keys_dump_t)); + if (keyfile == NULL) { + PrintAndLogEx(ERR, "Failed to allocate memory"); + free(dump); + return PM3_EMALLOC; + } + + // a key file we went looking for on our own is not expected to exist, + // so probe quietly first rather than let loadFileJSON complain + char *found = NULL; + bool exists = (searchFile(&found, RESOURCES_SUBDIR, keyfilename, ".json", autokeys) == PM3_SUCCESS); + free(found); + + size_t klen = 0; + if (exists == false || loadFileJSON(keyfilename, keyfile, sizeof(desfire_keys_dump_t), &klen, NULL) != PM3_SUCCESS) { + if (autokeys == false) { + PrintAndLogEx(WARNING, "Could not load key file `" _YELLOW_("%s") "`, continuing without it", keyfilename); + } else if (verbose) { + PrintAndLogEx(INFO, "No key file `" _YELLOW_("%s") "` found", keyfilename); + } + free(keyfile); + keyfile = NULL; + } else { + PrintAndLogEx(INFO, "Loaded keys for " _YELLOW_("%u") " application(s) from `" _YELLOW_("%s") "`", keyfile->appcount, keyfilename); + } + } + + uint8_t buf[255] = {0}; + size_t buflen = 0; + + // GetVersion and the originality signature are answered unauthenticated. + // Asking for them from inside the authenticated session instead would put + // them in the wrong communication mode and every answer would come back + // looking like a MAC failure + DesfireContext_t plainctx = {0}; + plainctx.commMode = DCMPlain; + plainctx.cmdSet = DCCNative; + + if (DesfireAnticollision(verbose) == PM3_SUCCESS) { + + // GetVersion answers 7 + 7 + 14 bytes over three chained frames. Split + // them here rather than storing one blob: the third frame is not the + // same shape across generations, and HW major/minor is what identifies + // which generation we are impersonating + if (DesfireGetVersion(&plainctx, buf, &buflen) == PM3_SUCCESS) { + + size_t off = 0; + struct { + uint8_t *dst; + uint8_t *dstlen; + size_t want; + } part[] = { + { dump->versionhw, &dump->versionhwlen, sizeof(dump->versionhw) }, + { dump->versionsw, &dump->versionswlen, sizeof(dump->versionsw) }, + { dump->versionprod, &dump->versionprodlen, sizeof(dump->versionprod) }, + }; + + for (size_t i = 0; i < ARRAYLEN(part) && off < buflen; i++) { + size_t n = MIN(part[i].want, buflen - off); + memcpy(part[i].dst, buf + off, n); + *part[i].dstlen = n; + off += n; + } + } + + buflen = 0; + if (DesfireReadSignature(&plainctx, 0x00, buf, &buflen) == PM3_SUCCESS && buflen <= sizeof(dump->signature)) { + memcpy(dump->signature, buf, buflen); + dump->signaturelen = buflen; + } + } + + DropField(); + + res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, ISW6bAID, 0x000000, noauth, verbose); if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "PICC level select/auth " _RED_("failed")); DropField(); - PrintAndLogEx(FAILED, "Select or authentication %s " _RED_("failed") ". Result [%d] %s", DesfireWayIDStr(selectway, id), res, DesfireAuthErrorToStr(res)); + free(keyfile); + free(dump); return res; } - FileList_t FileList = {{0}}; - size_t filescount = 0; - bool isopresent = false; - res = DesfireFillFileList(&dctx, FileList, &filescount, &isopresent); + // the PICC level is application 000000 + dump->picc.aid = 0x000000; + dump->picc.auth_ok = (noauth == false); + if (dump->picc.auth_ok) { + DesfireDumpStoreKey(&dump->picc, dctx.keyNum, dctx.keyType, dctx.key); + } + + // DesfireFillAppList() -> DesfireFillPICCInfo() already asks for free memory, + // key settings and key version 0, so don't ask a second time + PICCInfo_t PICCInfo = {0}; + AppListS AppList = {{0}}; + DesfireFillAppList(&dctx, &PICCInfo, AppList, false, false, true); + + // DesfireFillPICCInfo() reports a refused GetFreeMem as 0xffffffff + dump->freemem_ok = (PICCInfo.freemem != 0xffffffff); + if (dump->freemem_ok) { + dump->freemem = PICCInfo.freemem; + } + + dump->picc.keysettings = PICCInfo.keySettings; + dump->picc.numkeysraw = PICCInfo.numKeysRaw; + dump->picc.numkeys = PICCInfo.numberOfKeys; + dump->picc.settings_ok = true; + + // the PICC only hands out the version of key 0 + dump->picc.keys.version[0] = PICCInfo.keyVersion0; + dump->picc.keys.versionknown[0] = 1; + + PrintAndLogEx(NORMAL, ""); + DesfirePrintPICCInfo(&dctx, &PICCInfo); + + if (single_app) { + + // only the application the user named + desfire_dump_app_t *app = &dump->app[0]; + dump->appcount = 1; + + int idx = DesfireDumpFindApp(AppList, PICCInfo.appCount, &dctx, selectway, id); + if (idx >= 0) { + DesfireDumpFillAppMeta(app, &AppList[idx]); + } else { + // not in the PICC's list, record what the selector told us + app->aid = (selectway == ISW6bAID) ? id : 0; + app->isofid = (selectway == ISWIsoID) ? id : 0; + app->dfnamelen = dctx.selectedDFNameLen; + memcpy(app->dfname, dctx.selectedDFName, app->dfnamelen); + } + + res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, noauth, verbose); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Select/auth of %s " _RED_("failed"), DesfireWayIDStr(selectway, id)); + DropField(); + desfire_dump_free(dump); + free(keyfile); + free(dump); + return res; + } + + app->auth_ok = (noauth == false); + if (app->auth_ok) { + DesfireDumpStoreKey(app, dctx.keyNum, dctx.keyType, dctx.key); + } + + DesfireDumpCollectApp(&dctx, app, maxlength, selectway, id, securechann, noauth, verbose); + + } else { + + uint8_t appcount = (PICCInfo.appCount > DESFIRE_MAX_APP_COUNT) ? DESFIRE_MAX_APP_COUNT : PICCInfo.appCount; + if (PICCInfo.appCount > DESFIRE_MAX_APP_COUNT) { + PrintAndLogEx(WARNING, "PICC has %zu applications, dumping the first %d", PICCInfo.appCount, DESFIRE_MAX_APP_COUNT); + } + + dump->appcount = appcount; + + // the key we authenticated the PICC with is the fallback for every + // application, so keep a copy -- picking a key out of the key file for + // one application must not carry over into the next + uint8_t basekey[DESFIRE_MAX_KEY_SIZE] = {0}; + memcpy(basekey, dctx.key, sizeof(basekey)); + DesfireCryptoAlgorithm basealgo = dctx.keyType; + + for (uint8_t i = 0; i < appcount; i++) { + + desfire_dump_app_t *app = &dump->app[i]; + DesfireDumpFillAppMeta(app, &AppList[i]); + + // a key from the key file beats the one on the command line + // DesfireSetKey() would clear the whole context -- command set, + // comm mode, KDF and UID all came from the command line and have to + // survive, so only the key itself is swapped + const uint8_t *appkey = DesfireDumpFindKey(keyfile, app->aid, app->keytype, dctx.keyNum); + if (appkey != NULL) { + DesfireSetKeyNoClear(&dctx, dctx.keyNum, app->keytype, (uint8_t *)appkey); + if (verbose) { + PrintAndLogEx(INFO, "Application " _YELLOW_("%06X") " using key %u from the key file", app->aid, dctx.keyNum); + } + } else { + DesfireSetKeyNoClear(&dctx, dctx.keyNum, basealgo, basekey); + } + + res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, ISW6bAID, app->aid, noauth, verbose); + if (res != PM3_SUCCESS) { + PrintAndLogEx(WARNING, "Application " _YELLOW_("%06X") " select/auth " _RED_("failed") ", skipping", app->aid); + continue; + } + + app->auth_ok = (noauth == false); + if (app->auth_ok) { + DesfireDumpStoreKey(app, dctx.keyNum, dctx.keyType, dctx.key); + } + + DesfireDumpCollectApp(&dctx, app, maxlength, ISW6bAID, app->aid, securechann, noauth, verbose); + } + } + + DropField(); + + if (nosave) { + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "Called with no save option"); + PrintAndLogEx(NORMAL, ""); + desfire_dump_free(dump); + free(keyfile); + free(dump); + return PM3_SUCCESS; + } + + if (fnlen < 1) { + if (dump->card_info.uidlen == 0) { + PrintAndLogEx(WARNING, "No UID to build a filename from, use " _YELLOW_("-f ")); + desfire_dump_free(dump); + free(keyfile); + free(dump); + return PM3_ESOFT; + } + PrintAndLogEx(INFO, "Using UID as filename"); + strcat(filename, "hf-mfdes-"); + FillFileNameByUID(filename, dump->card_info.uid, "-dump", dump->card_info.uidlen); + } + + PrintAndLogEx(NORMAL, ""); + pm3_save_dump_json(filename, (uint8_t *)dump, sizeof(desfire_dump_t), jsfMfDesfire_v1); + + desfire_dump_free(dump); + free(keyfile); + free(dump); + return PM3_SUCCESS; +} + +static void DesfireViewPrintKeys(const desfire_dump_app_t *app) { + + for (uint8_t keyno = 0; keyno < DESFIRE_MAX_KEY_COUNT; keyno++) { + + const desfire_dump_keys_t *keys = &app->keys; + + if (keys->versionknown[keyno] == 0 && keys->present[keyno] == 0) { + continue; + } + + char ver[16] = "??"; + if (keys->versionknown[keyno]) { + snprintf(ver, sizeof(ver), "%02X", keys->version[keyno]); + } + + if (keys->present[keyno]) { + PrintAndLogEx(SUCCESS, " Key %02u (ver %s). " _GREEN_("%s") + , keyno + , ver + , sprint_hex_inrow(keys->key[keyno], desfire_get_key_length(app->keytype)) + ); + } else { + PrintAndLogEx(SUCCESS, " Key %02u (ver %s). " _YELLOW_("not recovered"), keyno, ver); + } + } +} + +// the PICC is application 000000 and prints the same way as the rest +static void DesfireViewPrintApp(const desfire_dump_app_t *app) { + + PrintAndLogEx(NORMAL, ""); + if (app->aid == 0x000000) { + PrintAndLogEx(INFO, "--- " _CYAN_("AID 000000") " ( PICC level ) ---------------------"); + } else { + // name it from the aid_desfire dictionary when we know it + const char *known = AIDDFGetCommentStr(app->aid); + if (known && known[0] != '\0') { + PrintAndLogEx(INFO, "--- " _CYAN_("AID %06X") " --- " _YELLOW_("%s"), app->aid, known); + } else { + PrintAndLogEx(INFO, "--- " _CYAN_("AID %06X") " --------------------------------", app->aid); + } + } + + if (app->isofid != 0) { + PrintAndLogEx(SUCCESS, " ISO DF ID.... %04X", app->isofid); + } + if (app->dfnamelen > 0) { + // DF names are often plain ascii, show both the way `lsapp` does + PrintAndLogEx(SUCCESS, " DF name...... " _YELLOW_("%s") " ( %s )" + , sprint_ascii(app->dfname, app->dfnamelen) + , sprint_hex_inrow(app->dfname, app->dfnamelen) + ); + } + if (app->settings_ok) { + PrintAndLogEx(SUCCESS, " Key settings. %02X, %u %s key(s)" + , app->keysettings + , app->numkeys + , CLIGetOptionListStr(DesfireAlgoOpts, app->keytype) + ); + } + PrintAndLogEx(SUCCESS, " Authenticated %s", app->auth_ok ? _GREEN_("yes") : _YELLOW_("no")); + + DesfireViewPrintKeys(app); + + PrintAndLogEx(SUCCESS, " Files........ %u", app->filecount); + + for (uint8_t n = 0; n < app->filecount && n < DESFIRE_MAX_FILE_COUNT; n++) { + + const desfire_dump_file_t *f = &app->files[n]; + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(SUCCESS, " File " _GREEN_("%02X") " - %s", f->num, GetDesfireFileType(f->type)); + + if (f->isofid != 0) { + PrintAndLogEx(SUCCESS, " ISO file ID.. %04X", f->isofid); + } + + if (f->settings_ok) { + // f->commmode is the raw file comm mode byte, not a DesfireCommunicationMode + PrintAndLogEx(SUCCESS, " Comm mode.... %s", CLIGetOptionListStr(DesfireCommunicationModeOpts, DesfireFileCommModeToCommMode(f->commmode))); + PrintAndLogEx(SUCCESS, " Access rights %04X", f->accessrights); + } + + switch (f->type) { + case 0x00: + case 0x01: + PrintAndLogEx(SUCCESS, " File size.... %u", f->size); + break; + case 0x02: + PrintAndLogEx(SUCCESS, " Limits....... %u ... %u", f->lowerlimit, f->upperlimit); + break; + case 0x03: + case 0x04: + PrintAndLogEx(SUCCESS, " Records...... %u of %u, %u bytes each", f->currecords, f->maxrecords, f->recordsize); + break; + default: + break; + } + + if (f->read_ok == false) { + PrintAndLogEx(WARNING, " Contents..... " _YELLOW_("not read")); + continue; + } + + if (f->type == 0x02) { + PrintAndLogEx(SUCCESS, " Value........ " _GREEN_("%u") " (0x%08X)", f->value, f->value); + continue; + } + + if (f->datalen == 0) { + PrintAndLogEx(SUCCESS, " Contents..... " _YELLOW_("empty")); + continue; + } + + PrintAndLogEx(NORMAL, ""); + if ((f->type == 0x03 || f->type == 0x04) && f->recordsize > 0 && (f->datalen % f->recordsize) == 0) { + for (uint32_t r = 0; r < f->datalen / f->recordsize; r++) { + PrintAndLogEx(SUCCESS, " Record %u", r); + print_buffer_with_offset(f->data + (r * f->recordsize), f->recordsize, 0, (r == 0)); + } + } else { + print_buffer_with_offset(f->data, f->datalen, 0, true); + } + } +} + +static int CmdHF14ADesSim(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hf mfdes sim", + "Simulate the DESFire card image currently in emulator memory.\n" + "Load one first with `hf mfdes eload`, and read back what a reader\n" + "changed with `hf mfdes esave`.\n" + "\n" + "UID, ATQA, SAK and ATS all come out of the loaded image", + "hf mfdes sim"); + + void *argtable[] = { + arg_param_begin, + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + CLIParserFree(ctx); + + clearCommandBuffer(); + SendCommandNG(CMD_HF_DESFIRE_SIMULATE, NULL, 0); + + PrintAndLogEx(INFO, "Press " _GREEN_("pm3 button") " or " _GREEN_("") " to abort simulation"); + + PacketResponseNG resp; + bool keypress = kbd_enter_pressed(); + while (keypress == false) { + + keypress = kbd_enter_pressed(); + + if (WaitForResponseTimeout(CMD_HF_DESFIRE_SIMULATE, &resp, 1500) == false) { + continue; + } + + if (resp.status != PM3_SUCCESS) { + PrintAndLogEx(WARNING, "Simulation stopped, no card image in emulator memory?"); + PrintAndLogEx(HINT, "Hint: load one with " _YELLOW_("`hf mfdes eload -f `")); + return resp.status; + } + break; + } + + if (keypress) { + SendCommandNG(CMD_BREAK_LOOP, NULL, 0); + } + + PrintAndLogEx(INFO, "Done!"); + PrintAndLogEx(HINT, "Hint: try " _YELLOW_("`hf mfdes esave`") " to see what a reader changed"); + return PM3_SUCCESS; +} + +// One `hf mfdes etest` operation: send it and hand back the answer +static int desfire_etest_exchange(uint8_t op, const uint8_t *data, uint16_t len, PacketResponseNG *resp) { + + uint8_t buf[PM3_CMD_DATA_SIZE] = {0}; + desfire_sim_test_cmd_t *cmd = (desfire_sim_test_cmd_t *)buf; + + if (len > sizeof(buf) - sizeof(*cmd)) { + return PM3_EINVARG; + } + + cmd->op = op; + cmd->len = len; + if (len) { + memcpy(cmd->data, data, len); + } + + clearCommandBuffer(); + SendCommandNG(CMD_HF_DESFIRE_SIM_TEST, buf, sizeof(*cmd) + len); + + if (WaitForResponseTimeout(CMD_HF_DESFIRE_SIM_TEST, resp, 2000) == false) { + return PM3_ETIMEOUT; + } + + return resp->status; +} + +// uppercase hex into a caller's buffer, sprint_hex_inrow() has one static one +static void desfire_etest_hex(char *dst, size_t dstlen, const uint8_t *src, size_t n) { + size_t i = 0; + for (; i < n && (2 * i + 2) < dstlen; i++) { + snprintf(dst + 2 * i, dstlen - 2 * i, "%02X", src[i]); + } + dst[2 * i] = 0; +} + +static int CmdHF14ADesETest(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hf mfdes etest", + "Drive the DESFire simulation from the host over USB, no RF involved.\n" + "The card image in emulator memory answers each --apdu, native or ISO 7816\n" + "wrapped, as `hf mfdes sim` would over the air. Bytes given with --random are\n" + "drawn in order by the next random UID (3, at --scan on a random-id image) and\n" + "RndB (8 or 16, at the next authentication), so a recorded session can be replayed.\n" + "\n" + "One action per call. Load an image first with `hf mfdes eload`", + "hf mfdes etest --begin\n" + "hf mfdes etest --scan\n" + "hf mfdes etest --random 0102030405060708\n" + "hf mfdes etest --apdu 900A0000010000 -j\n" + "hf mfdes etest --state -j\n" + "hf mfdes etest --end"); + + void *argtable[] = { + arg_param_begin, + arg_lit0(NULL, "begin", "Check the image, clear the random queue"), + arg_lit0(NULL, "end", "Drop the state and the random queue"), + arg_lit0(NULL, "scan", "RF reset and activation, show UID/ATQA/SAK/ATS"), + arg_str0(NULL, "apdu", "", "Send one command, show the answer"), + arg_str0(NULL, "random", "", "Queue bytes for the next RndB / random UID draws"), + arg_lit0(NULL, "fieldoff", "RF reset, session dropped"), + arg_lit0(NULL, "state", "Show session and random queue state"), + arg_lit0("j", "json", "One line of JSON instead of text"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, false); + + bool begin = arg_get_lit(ctx, 1); + bool end = arg_get_lit(ctx, 2); + bool scan = arg_get_lit(ctx, 3); + bool has_apdu = (arg_get_str(ctx, 4)->count > 0); + bool has_random = (arg_get_str(ctx, 5)->count > 0); + bool fieldoff = arg_get_lit(ctx, 6); + bool state = arg_get_lit(ctx, 7); + bool json = arg_get_lit(ctx, 8); + + int apdulen = 0; + uint8_t apdu[PM3_CMD_DATA_SIZE - sizeof(desfire_sim_test_cmd_t)] = {0}; + if (CLIParamHexToBuf(arg_get_str(ctx, 4), apdu, sizeof(apdu), &apdulen)) { + CLIParserFree(ctx); + return PM3_EINVARG; + } + + int rndlen = 0; + uint8_t rnd[DESFIRE_SIM_TEST_RANDOM_MAX] = {0}; + if (CLIParamHexToBuf(arg_get_str(ctx, 5), rnd, sizeof(rnd), &rndlen)) { + CLIParserFree(ctx); + return PM3_EINVARG; + } + CLIParserFree(ctx); + + if (begin + end + scan + has_apdu + has_random + fieldoff + state != 1) { + PrintAndLogEx(WARNING, "Give exactly one action"); + return PM3_EINVARG; + } + + if ((has_apdu && apdulen == 0) || (has_random && rndlen == 0)) { + PrintAndLogEx(WARNING, "Need at least one byte"); + return PM3_EINVARG; + } + + uint8_t op; + const char *name; + const uint8_t *data = NULL; + uint16_t len = 0; + + if (begin) { + op = DESFIRE_SIM_TEST_BEGIN; + name = "begin"; + } else if (end) { + op = DESFIRE_SIM_TEST_END; + name = "end"; + } else if (scan) { + op = DESFIRE_SIM_TEST_SCAN; + name = "scan"; + } else if (has_apdu) { + op = DESFIRE_SIM_TEST_APDU; + name = "apdu"; + data = apdu; + len = apdulen; + } else if (has_random) { + op = DESFIRE_SIM_TEST_RANDOM; + name = "random"; + data = rnd; + len = rndlen; + } else if (fieldoff) { + op = DESFIRE_SIM_TEST_FIELDOFF; + name = "fieldoff"; + } else { + op = DESFIRE_SIM_TEST_STATE; + name = "state"; + } + + PacketResponseNG resp; + int res = desfire_etest_exchange(op, data, len, &resp); + + // the JSON fields of a successful answer, nothing for the plain acks + char fields[2 * PM3_CMD_DATA_SIZE + 128] = {0}; + + if (res == PM3_SUCCESS && op == DESFIRE_SIM_TEST_SCAN) { + if (resp.length < sizeof(iso14a_card_select_t)) { + res = PM3_EFAILED; + } else { + iso14a_card_select_t card; + memcpy(&card, resp.data.asBytes, sizeof(card)); + + char uid[2 * sizeof(card.uid) + 1]; + char atqa[2 * sizeof(card.atqa) + 1]; + char ats[2 * sizeof(card.ats) + 1]; + desfire_etest_hex(uid, sizeof(uid), card.uid, card.uidlen); + desfire_etest_hex(atqa, sizeof(atqa), card.atqa, sizeof(card.atqa)); + desfire_etest_hex(ats, sizeof(ats), card.ats, card.ats_len); + + if (json) { + snprintf(fields, sizeof(fields), ",\"uid\":\"%s\",\"atqa\":\"%s\",\"sak\":\"%02X\",\"ats\":\"%s\"", uid, atqa, card.sak, ats); + } else { + PrintAndLogEx(SUCCESS, "UID.... %s", uid); + PrintAndLogEx(SUCCESS, "ATQA... %s", atqa); + PrintAndLogEx(SUCCESS, "SAK.... %02X", card.sak); + PrintAndLogEx(SUCCESS, "ATS.... %s", ats); + } + } + } + + if (res == PM3_SUCCESS && op == DESFIRE_SIM_TEST_APDU) { + char hex[2 * PM3_CMD_DATA_SIZE + 1]; + desfire_etest_hex(hex, sizeof(hex), resp.data.asBytes, resp.length); + if (json) { + snprintf(fields, sizeof(fields), ",\"data\":\"%s\"", hex); + } else { + PrintAndLogEx(INFO, "<- %s", resp.length ? hex : "(no answer)"); + } + } + + if (res == PM3_SUCCESS && op == DESFIRE_SIM_TEST_STATE) { + if (resp.length < sizeof(desfire_sim_test_state_t)) { + res = PM3_EFAILED; + } else { + desfire_sim_test_state_t st; + memcpy(&st, resp.data.asBytes, sizeof(st)); + if (json) { + snprintf(fields, sizeof(fields), + ",\"ready\":%s,\"authenticated\":%s,\"auth_keyno\":%u,\"aid\":\"%02X%02X%02X\",\"random_remaining\":%u,\"random_underflow\":%s", + st.ready ? "true" : "false", + st.authenticated ? "true" : "false", + st.auth_keyno, + st.aid[0], st.aid[1], st.aid[2], + st.random_remaining, + st.random_underflow ? "true" : "false"); + } else { + PrintAndLogEx(SUCCESS, "Ready............ %s", st.ready ? _GREEN_("yes") : _RED_("no")); + PrintAndLogEx(SUCCESS, "Selected AID..... %02X%02X%02X", st.aid[0], st.aid[1], st.aid[2]); + PrintAndLogEx(SUCCESS, "Authenticated.... %s", st.authenticated ? _GREEN_("yes") : "no"); + if (st.authenticated) { + PrintAndLogEx(SUCCESS, "Key number....... %u", st.auth_keyno); + } + PrintAndLogEx(SUCCESS, "Random queued.... %u byte(s)", st.random_remaining); + PrintAndLogEx(SUCCESS, "Random underflow. %s", st.random_underflow ? _RED_("yes") : "no"); + } + } + } + if (res != PM3_SUCCESS) { - DropField(); + const char *why; + switch (res) { + case PM3_ENODATA: + why = "no card image in emulator memory"; + break; + case PM3_EOVFLOW: + why = "random queue full"; + break; + case PM3_ETIMEOUT: + why = "no answer, firmware too old or built without DESFire simulation"; + break; + case PM3_EFAILED: + why = "short answer"; + break; + default: + why = (op == DESFIRE_SIM_TEST_APDU) ? "not activated, --scan first" : "invalid request"; + break; + } + + if (json) { + PrintAndLogEx(NORMAL, "{\"command\":\"%s\",\"ok\":false,\"error\":\"%s\"}", name, why); + } else { + PrintAndLogEx(FAILED, "%s failed, %s", name, why); + if (res == PM3_ENODATA) { + PrintAndLogEx(HINT, "Hint: load one with " _YELLOW_("`hf mfdes eload -f `")); + } + } + return res; + } + + bool plain_ack = (op == DESFIRE_SIM_TEST_BEGIN || op == DESFIRE_SIM_TEST_END || + op == DESFIRE_SIM_TEST_RANDOM || op == DESFIRE_SIM_TEST_FIELDOFF); + if (json) { + PrintAndLogEx(NORMAL, "{\"command\":\"%s\",\"ok\":true%s}", name, fields); + } else if (plain_ack) { + PrintAndLogEx(SUCCESS, "%s ( " _GREEN_("ok") " )", name); + } + + return PM3_SUCCESS; +} + +static int CmdHF14ADesELoad(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hf mfdes eload", + "Load a DESFire card dump into emulator memory.\n" + "The dump is packed into the on-device card image, see doc/mfdes_dump_format.md", + "hf mfdes eload -f hf-mfdes-01020304050607-dump.json"); + + void *argtable[] = { + arg_param_begin, + arg_str1("f", "file", "", "Filename of dump"), + arg_lit0("v", "verbose", "Verbose output"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, false); + + int fnlen = 0; + char filename[FILE_PATH_SIZE] = {0}; + CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen); + bool verbose = arg_get_lit(ctx, 2); + CLIParserFree(ctx); + + desfire_dump_t *dump = calloc(1, sizeof(desfire_dump_t)); + if (dump == NULL) { + PrintAndLogEx(ERR, "Failed to allocate memory"); + return PM3_EMALLOC; + } + + size_t dlen = 0; + int res = loadFileJSON(filename, dump, sizeof(desfire_dump_t), &dlen, NULL); + if (res != PM3_SUCCESS) { + free(dump); + return res; + } + + if (dlen != sizeof(desfire_dump_t)) { + PrintAndLogEx(ERR, "`" _YELLOW_("%s") "` is not a DESFire card dump", filename); + desfire_dump_free(dump); + free(dump); + return PM3_EINVARG; + } + + // the device tells us how much emulator memory it has, so a platform with + // more of it holds a bigger card with no change here + size_t emsize = g_conn.em_size; + if (emsize == 0) { + PrintAndLogEx(ERR, "Device did not report an emulator memory size"); + desfire_dump_free(dump); + free(dump); + return PM3_EDEVNOTSUPP; + } + + uint8_t *img = calloc(emsize, sizeof(uint8_t)); + if (img == NULL) { + PrintAndLogEx(ERR, "Failed to allocate memory"); + desfire_dump_free(dump); + free(dump); + return PM3_EMALLOC; + } + + size_t used = 0; + res = desfire_em_pack(dump, img, emsize, &used); + desfire_dump_free(dump); + free(dump); + + if (res != PM3_SUCCESS) { + free(img); + return res; + } + + if (verbose) { + desfire_em_print(img, emsize); + } + + res = desfire_em_upload(img, emsize); + free(img); + + if (res != PM3_SUCCESS) { + return res; + } + + PrintAndLogEx(SUCCESS, "Done!"); + PrintAndLogEx(HINT, "Hint: try " _YELLOW_("`hf mfdes eview`") " to verify"); + return PM3_SUCCESS; +} + +static int CmdHF14ADesESave(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hf mfdes esave", + "Save the card image in emulator memory to a dump file.\n" + "Shows what a reader left behind if one has been talking to the simulation.\n" + "A deleted application or file is kept in the image as a tombstone, because the\n" + "memory it held stays spent until a FormatPICC. By default those are left out, so\n" + "the dump is the card as a reader sees it. Use `--keep` to save them as well, which\n" + "is what you want to see everything a reader did rather than only the result", + "hf mfdes esave -f myfile\n" + "hf mfdes esave -f myfile --keep -> keep applications and files a reader deleted"); + + void *argtable[] = { + arg_param_begin, + arg_str0("f", "file", "", "Filename, if no UID will be used as filename"), + arg_lit0("v", "verbose", "Verbose output"), + arg_lit0(NULL, "keep", "Keep applications and files that were deleted"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + + int fnlen = 0; + char filename[FILE_PATH_SIZE] = {0}; + CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen); + bool verbose = arg_get_lit(ctx, 2); + bool keep_deleted = arg_get_lit(ctx, 3); + CLIParserFree(ctx); + + size_t emsize = g_conn.em_size; + if (emsize == 0) { + PrintAndLogEx(ERR, "Device did not report an emulator memory size"); + return PM3_EDEVNOTSUPP; + } + + uint8_t *img = calloc(emsize, sizeof(uint8_t)); + if (img == NULL) { + PrintAndLogEx(ERR, "Failed to allocate memory"); + return PM3_EMALLOC; + } + + int res = desfire_em_download(img, emsize); + if (res != PM3_SUCCESS) { + free(img); + return res; + } + + if (verbose) { + desfire_em_print(img, emsize); + } + + desfire_dump_t *dump = calloc(1, sizeof(desfire_dump_t)); + if (dump == NULL) { + PrintAndLogEx(ERR, "Failed to allocate memory"); + free(img); + return PM3_EMALLOC; + } + + res = desfire_em_unpack_ex(img, emsize, dump, keep_deleted); + free(img); + + if (res != PM3_SUCCESS) { + PrintAndLogEx(HINT, "Hint: emulator memory holds no DESFire card image, try " _YELLOW_("`hf mfdes eload`")); + free(dump); + return res; + } + + if (fnlen < 1) { + if (dump->card_info.uidlen == 0) { + PrintAndLogEx(WARNING, "No UID to build a filename from, use " _YELLOW_("-f ")); + desfire_dump_free(dump); + free(dump); + return PM3_ESOFT; + } + PrintAndLogEx(INFO, "Using UID as filename"); + strcat(filename, "hf-mfdes-"); + FillFileNameByUID(filename, dump->card_info.uid, "-dump", dump->card_info.uidlen); + } + + pm3_save_dump_json(filename, (uint8_t *)dump, sizeof(desfire_dump_t), jsfMfDesfire_v1); + + desfire_dump_free(dump); + free(dump); + return PM3_SUCCESS; +} + +static int CmdHF14ADesEView(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hf mfdes eview", + "Show the DESFire card image currently in emulator memory", + "hf mfdes eview"); + + void *argtable[] = { + arg_param_begin, + arg_lit0("v", "verbose", "Also print every application and file"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + bool verbose = arg_get_lit(ctx, 1); + CLIParserFree(ctx); + + size_t emsize = g_conn.em_size; + if (emsize == 0) { + PrintAndLogEx(ERR, "Device did not report an emulator memory size"); + return PM3_EDEVNOTSUPP; + } + + uint8_t *img = calloc(emsize, sizeof(uint8_t)); + if (img == NULL) { + PrintAndLogEx(ERR, "Failed to allocate memory"); + return PM3_EMALLOC; + } + + int res = desfire_em_download(img, emsize); + if (res != PM3_SUCCESS) { + free(img); return res; } PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(SUCCESS, "Application " _CYAN_("%s") " have " _GREEN_("%zu") " files", DesfireWayIDStr(selectway, id), filescount); + desfire_em_print(img, emsize); - if (selectway == ISW6bAID) - DesfirePrintAIDFunctions(id); + if (verbose) { + desfire_dump_t *dump = calloc(1, sizeof(desfire_dump_t)); + if (dump != NULL) { + if (desfire_em_unpack(img, emsize, dump) == PM3_SUCCESS) { + DesfireViewPrintApp(&dump->picc); + for (uint8_t i = 0; i < dump->appcount && i < DESFIRE_MAX_APP_COUNT; i++) { + DesfireViewPrintApp(&dump->app[i]); + } + } + desfire_dump_free(dump); + free(dump); + } + } - if (filescount == 0) { - PrintAndLogEx(INFO, "There is no files in the application %s", DesfireWayIDStr(selectway, id)); - DropField(); + free(img); + PrintAndLogEx(NORMAL, ""); + return PM3_SUCCESS; +} + +static int CmdHF14ADesView(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hf mfdes view", + "Print a DESFire card dump file (json)", + "hf mfdes view -f hf-mfdes-01020304050607-dump.json\n" + "hf mfdes view --selftest"); + + void *argtable[] = { + arg_param_begin, + arg_str0("f", "file", "", "Filename of dump"), + arg_lit0("v", "verbose", "Verbose output"), + arg_lit0(NULL, "selftest", "Run the dump parsers self tests and exit"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, false); + + int fnlen = 0; + char filename[FILE_PATH_SIZE] = {0}; + CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen); + bool verbose = arg_get_lit(ctx, 2); + bool selftest = arg_get_lit(ctx, 3); + CLIParserFree(ctx); + + if (selftest) { + return nortic_selftest(); + } + + if (fnlen == 0) { + PrintAndLogEx(ERR, "Specify a filename with `-f` or run `--selftest`"); + return PM3_EINVARG; + } + + desfire_dump_t *dump = calloc(1, sizeof(desfire_dump_t)); + if (dump == NULL) { + PrintAndLogEx(ERR, "Failed to allocate memory"); + return PM3_EMALLOC; + } + + size_t dlen = 0; + int res = loadFileJSON(filename, dump, sizeof(desfire_dump_t), &dlen, NULL); + if (res != PM3_SUCCESS) { + free(dump); return res; } - res = PM3_SUCCESS; - for (int i = 0; i < filescount; i++) { - if (res != PM3_SUCCESS) { - DesfireSetCommMode(&dctx, DCMPlain); - res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, noauth, verbose); - if (res != PM3_SUCCESS) { - DropField(); - return res; - } - } - - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(INFO, "--------------------------------- " _CYAN_("File %02x") " ----------------------------------", FileList[i].fileNum); - PrintAndLogEx(SUCCESS, "File ID : " _GREEN_("%02x"), FileList[i].fileNum); - if (isopresent) { - if (FileList[i].fileISONum != 0) - PrintAndLogEx(SUCCESS, "File ISO ID : %04x", FileList[i].fileISONum); - else - PrintAndLogEx(SUCCESS, "File ISO ID : " _YELLOW_("n/a")); - } - DesfirePrintFileSettingsExtended(&FileList[i].fileSettings); - - res = DesfileReadFileAndPrint(&dctx, FileList[i].fileNum, RFTAuto, 0, 0, maxlength, noauth, verbose); + if (dlen != sizeof(desfire_dump_t)) { + PrintAndLogEx(ERR, "`" _YELLOW_("%s") "` is not a DESFire card dump", filename); + desfire_dump_free(dump); + free(dump); + return PM3_EINVARG; } - DropField(); + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Tag Information") " ---------------------------"); + + if (dump->card_info.uidlen > 0) { + PrintAndLogEx(SUCCESS, "UID.............. " _GREEN_("%s"), sprint_hex_inrow(dump->card_info.uid, dump->card_info.uidlen)); + // the file keeps ATQA in wire order, `hf 14a info` prints it the other way round + PrintAndLogEx(SUCCESS, "ATQA............. %02X %02X", dump->card_info.atqa[1], dump->card_info.atqa[0]); + PrintAndLogEx(SUCCESS, "SAK.............. %02X", dump->card_info.sak); + if (dump->card_info.ats_len > 0) { + PrintAndLogEx(SUCCESS, "ATS.............. %s", sprint_hex_inrow(dump->card_info.ats, dump->card_info.ats_len)); + } + } + + if (dump->versionhwlen > 0) { + PrintAndLogEx(SUCCESS, "Version HW....... %s", sprint_hex_inrow(dump->versionhw, dump->versionhwlen)); + if (dump->versionhwlen >= 5) { + PrintAndLogEx(SUCCESS, " %s", mifare_prime_get_version_str(dump->versionhw[1], dump->versionhw[3], dump->versionhw[4])); + } + if (dump->versionhwlen >= 6) { + PrintAndLogEx(SUCCESS, " Storage size... %s", mifare_prime_get_card_size_str(dump->versionhw[5])); + } + } + + if (dump->versionswlen > 0) { + PrintAndLogEx(SUCCESS, "Version SW....... %s", sprint_hex_inrow(dump->versionsw, dump->versionswlen)); + } + + if (dump->versionprodlen > 0) { + PrintAndLogEx(SUCCESS, "Production....... %s", sprint_hex_inrow(dump->versionprod, dump->versionprodlen)); + } + + if (dump->signaturelen > 0) { + PrintAndLogEx(SUCCESS, "Signature........ %s", sprint_hex_inrow(dump->signature, dump->signaturelen)); + } + + if (dump->freemem_ok) { + PrintAndLogEx(SUCCESS, "Free memory...... " _GREEN_("%u") " bytes", dump->freemem); + } + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Applications") " ------------------------------"); + PrintAndLogEx(SUCCESS, "%u application(s) plus the PICC level", dump->appcount); + + DesfireViewPrintApp(&dump->picc); + + for (uint8_t i = 0; i < dump->appcount && i < DESFIRE_MAX_APP_COUNT; i++) { + DesfireViewPrintApp(&dump->app[i]); + } + + if (is_valid_nortic_card(dump)) { + (void)nortic_parser_parse(dump); + } + + if (verbose) { + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "Loaded `" _YELLOW_("%s") "`", filename); + } + + PrintAndLogEx(NORMAL, ""); + desfire_dump_free(dump); + free(dump); return PM3_SUCCESS; } @@ -9413,7 +11104,7 @@ static int CmdHF14ADesVerifyCert(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), // 3 arg_int0("n", "keyno", "", "Key number for DESFire authentication"), // 4 arg_str0("t", "algo", "", "DESFire auth crypt algo"), // 5 - arg_str0("k", "key", "", "DESFire authentication key"), // 6 + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), // 6 arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), // 7 arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), // 8 arg_str0("m", "cmode", "", "Communication mode"), // 9 @@ -9424,8 +11115,7 @@ static int CmdHF14ADesVerifyCert(const char *Cmd) { arg_str0(NULL, "dfname", "", "Certificate application DF name (1-16 bytes)"), // 14 arg_str0(NULL, "fid", "", "Certificate file ID (1 byte)"), // 15 arg_lit0(NULL, "no-auth", "Read certificate file without authentication"), // 16 - arg_strn(NULL, "ca", "", 0, MFDES_VERIFYCERT_MAX_CAS, - "CA input, or `skip` to skip certificate signature validation. Repeat --ca for multiple entries"), // 17 + arg_strn(NULL, "ca", "", 0, MFDES_VERIFYCERT_MAX_CAS, "CA input, or `skip` to skip validation"), // 17 arg_str0(NULL, "keyaid", "", "Key application ID (default: cert app)"), // 18 arg_str0(NULL, "keyisoid", "", "Key application ISO DF ID (2 bytes)"), // 19 arg_str0(NULL, "keydfname", "", "Key application DF name (default: cert app)"), // 20 @@ -9811,6 +11501,12 @@ static command_t CommandTable[] = { {"getfileisoids", CmdHF14ADesGetFileISOIDs, IfPm3Iso14443a, "Get File ISO IDs list"}, {"lsfiles", CmdHF14ADesLsFiles, IfPm3Iso14443a, "Show all files list"}, {"dump", CmdHF14ADesDump, IfPm3Iso14443a, "Dump all files"}, + {"view", CmdHF14ADesView, AlwaysAvailable, "Display content from tag dump file"}, + {"eload", CmdHF14ADesELoad, IfPm3Iso14443a, "Upload file into emulator memory"}, + {"esave", CmdHF14ADesESave, IfPm3Iso14443a, "Save emulator memory to file"}, + {"eview", CmdHF14ADesEView, IfPm3Iso14443a, "View emulator memory"}, + {"sim", CmdHF14ADesSim, IfPm3Iso14443a, "Simulate DESFire card from emulator memory"}, + {"etest", CmdHF14ADesETest, IfPm3Iso14443a, "Drive the simulation from the host, no RF"}, {"createfile", CmdHF14ADesCreateFile, IfPm3Iso14443a, "Create Standard/Backup File"}, {"createvaluefile", CmdHF14ADesCreateValueFile, IfPm3Iso14443a, "Create Value File"}, {"createrecordfile", CmdHF14ADesCreateRecordFile, IfPm3Iso14443a, "Create Linear/Cyclic Record File"}, diff --git a/client/src/cmdhfmfhard.c b/client/src/cmdhfmfhard.c index 3f3f47b1b..88204437f 100644 --- a/client/src/cmdhfmfhard.c +++ b/client/src/cmdhfmfhard.c @@ -1733,9 +1733,18 @@ static int acquire_nonces(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_ if (initialize == false) { const mf_nonces_resp_t *nresp = (const mf_nonces_resp_t *)resp.data.asBytes; - uint16_t num_sampled_nonces = nresp->num_nonces; + uint16_t num_sampled_nonces = nresp->num_nonces & ~1; // nonces come in pairs const uint8_t *bufp = nresp->nonces; + if (resp.length < sizeof(mf_nonces_resp_t) + ((num_sampled_nonces / 2) * MFC_NONCE_PAIR_SIZE)) { + PrintAndLogEx(FAILED, "Truncated nonce reply, got %u bytes for %u nonces", resp.length, num_sampled_nonces); + if (nonce_file_write) { + fclose(fnonces); + } + DropField(); + return PM3_ESOFT; + } + for (uint16_t i = 0; i < num_sampled_nonces; i += 2) { uint32_t nt_enc1 = bytes_to_num(bufp, 4); uint32_t nt_enc2 = bytes_to_num(bufp + 4, 4); @@ -1760,10 +1769,10 @@ static int acquire_nonces(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_ num_acquired_nonces += add_res; if (nonce_file_write) { - fwrite(bufp, 1, 9, fnonces); + fwrite(bufp, 1, MFC_NONCE_PAIR_SIZE, fnonces); fflush(fnonces); } - bufp += 9; + bufp += MFC_NONCE_PAIR_SIZE; } //total_num_nonces += num_sampled_nonces; diff --git a/client/src/cmdhfmfsen.c b/client/src/cmdhfmfsen.c index f0c4e315f..0ab3a22bd 100644 --- a/client/src/cmdhfmfsen.c +++ b/client/src/cmdhfmfsen.c @@ -2729,12 +2729,29 @@ static void fm11_print_key_table(const uint64_t keys_found[FM11RF08S_SECTORS][2] PrintAndLogEx(NORMAL, ""); } +// `hf-mf--[-]`, matching the template `hf mf autopwn` uses +static void fm11_build_filename(char *dst, size_t dst_len, const iso14a_card_select_t *card, const char *base, const char *suffix) { + + snprintf(dst, dst_len, "hf-mf-%s-%s%s%s" + , sprint_hex_inrow(card->uid, card->uidlen) + , base + , (suffix != NULL && suffix[0] != '\0') ? "-" : "" + , (suffix != NULL) ? suffix : "" + ); +} + static int fm11_save_recovery_outputs(const iso14a_card_select_t *card, const iso14a_fm11rf08s_nonces_with_data_t *nonces, const uint64_t keys_found[FM11RF08S_SECTORS][2], const bool found_key[FM11RF08S_SECTORS][2], - bool no_oob, bool has_data) { + bool no_oob, bool has_data, const char *suffix, bool no_save) { + + if (no_save) { + PrintAndLogEx(INFO, "Called with no save option"); + return PM3_SUCCESS; + } + char fn[FILE_PATH_SIZE] = {0}; - snprintf(fn, sizeof(fn), "hf-mf-%s-key", sprint_hex_inrow(card->uid, card->uidlen)); + fm11_build_filename(fn, sizeof(fn), card, "key", suffix); const uint64_t unknown_key = bytes_to_num(g_mifare_default_key, MIFARE_KEY_SIZE); uint8_t sector_count = FM11RF08S_NORMAL_SECTORS + (no_oob ? 0 : 1); @@ -2771,8 +2788,8 @@ static int fm11_save_recovery_outputs(const iso14a_card_select_t *card, const is num_to_bytes(ka, MIFARE_KEY_SIZE, dump + trailer * MFBLOCK_SIZE); num_to_bytes(kb, MIFARE_KEY_SIZE, dump + trailer * MFBLOCK_SIZE + 10); } - snprintf(fn, sizeof(fn), "hf-mf-%s-dump", sprint_hex_inrow(card->uid, card->uidlen)); - return saveFileEx(fn, ".bin", dump, sizeof(dump), spDump); + fm11_build_filename(fn, sizeof(fn), card, "dump", suffix); + return pm3_save_mf_dump(fn, dump, sizeof(dump), jsfCardMemory); } static int fm11_select_mifare_classic(iso14a_card_select_t *card_out) { @@ -2869,7 +2886,10 @@ static int fm11_select_mifare_classic(iso14a_card_select_t *card_out) { return PM3_SUCCESS; } -int HFMFSENRecover(bool keep_nonces, bool no_oob, bool reader_mode, bool offline_only, int max_online_candidates, uint8_t parity_mask, bool skip_default_key_check, const sector_t *known_sectors, size_t known_sector_count) { +int HFMFSENRecover(bool keep_nonces, bool no_oob, bool reader_mode, bool offline_only, + int max_online_candidates, uint8_t parity_mask, bool skip_default_key_check, + const sector_t *known_sectors, size_t known_sector_count, const char *suffix, + bool no_save) { iso14a_card_select_t card = {0}; iso14a_fm11rf08s_nonces_with_data_t nonces = {0}; @@ -2930,15 +2950,18 @@ int HFMFSENRecover(bool keep_nonces, bool no_oob, bool reader_mode, bool offline } uint32_t nonce_count = FM11RF08S_SECTORS * 2; - char activity[80]; - snprintf(activity, sizeof(activity), "Loaded card UID %08X using %s key %s", uid, - collected_with_backdoor ? "backdoor" : "dictionary", - sprint_hex_inrow(active_key, MIFARE_KEY_SIZE)); + char activity[80] = {0}; + snprintf(activity, sizeof(activity), "Loaded card UID %08X using %s key %s" + , uid + , collected_with_backdoor ? "backdoor" : "dictionary" + , sprint_hex_inrow(active_key, MIFARE_KEY_SIZE) + ); + fm11_sen_progress(nonce_count, activity, 0, 0); + if (keep_nonces) { char nonce_fn[FILE_PATH_SIZE] = {0}; - snprintf(nonce_fn, sizeof(nonce_fn), "hf-mf-%s-nonces%s", sprint_hex_inrow(card.uid, card.uidlen), - collected_with_data ? "_with_data" : ""); + fm11_build_filename(nonce_fn, sizeof(nonce_fn), &card, collected_with_data ? "nonces_with_data" : "nonces", suffix); pm3_save_fm11rf08s_nonces(nonce_fn, &nonces, collected_with_data); fm11_sen_progress(nonce_count, "Saved nonce/data evidence JSON", 0, 0); } @@ -2967,6 +2990,7 @@ int HFMFSENRecover(bool keep_nonces, bool no_oob, bool reader_mode, bool offline (void)fm11_keylist_add_unique(&confirmed_reuse_keys, known_key); } } + if (seeded_known > 0) { fm11_sen_progress(nonce_count, "Seed known keys from earlier autopwn stages", seeded_known, 0); } @@ -2989,24 +3013,30 @@ int HFMFSENRecover(bool keep_nonces, bool no_oob, bool reader_mode, bool offline if (skip_default_key_check) { fm11_sen_progress(nonce_count, "Skip default-key dictionary check already done by autopwn", seeded_known, 0); } else { + fm11_sen_progress(nonce_count, "Check default-key dictionary against nonce evidence", default_keys.count, 0); + retval = fm11_check_default_keys(uid, nonce_count, &nonces, &default_keys, parity_mask, keys_found, found_key); if (retval != PM3_SUCCESS) { goto out; } + for (uint8_t sec = 0; sec < FM11RF08S_SECTORS; sec++) { for (uint8_t kt = 0; kt < 2; kt++) { if (found_key[sec][kt] == false) { continue; } + uint64_t key = keys_found[sec][kt] & 0xFFFFFFFFFFFFULL; if (fm11_keylist_has_key(&confirmed_reuse_keys, key)) { continue; } + retval = fm11_keylist_add_unique(&confirmed_reuse_keys, key); if (retval != PM3_SUCCESS) { goto out; } + uint32_t reuse_found = fm11_propagate_key_reuse_online(nonce_count, key, keys_found, found_key); if (reuse_found > 0) { snprintf(activity, sizeof(activity), "Key re-use propagation confirmed %u additional key slots", reuse_found); @@ -3022,12 +3052,16 @@ int HFMFSENRecover(bool keep_nonces, bool no_oob, bool reader_mode, bool offline } fm11_sen_progress(nonce_count, "Generate first-pass candidates from nT/{nT}/parity", 0, 0); + for (uint8_t sec = 0; sec < FM11RF08S_SECTORS; sec++) { + uint8_t real_sec = fm11_real_sector(sec); for (uint8_t kt = 0; kt < 2; kt++) { + if (found_key[sec][kt]) { continue; } + uint32_t nt = fm11_bytes_to_u32(nonces.nt[sec][kt]); uint32_t nt_enc = fm11_bytes_to_u32(nonces.nt_enc[sec][kt]); int res = fm11_generate_1nt_candidates(uid, nt, nt_enc, nonces.par_err[sec][kt], parity_mask, &candidates[sec][kt]); @@ -3037,19 +3071,23 @@ int HFMFSENRecover(bool keep_nonces, bool no_oob, bool reader_mode, bool offline } fm11_prioritize_defaults(&candidates[sec][kt], &default_keys); } + uint32_t nt_a = fm11_bytes_to_u32(nonces.nt[sec][0]); uint32_t nt_b = fm11_bytes_to_u32(nonces.nt[sec][1]); + if (nt_a != nt_b && found_key[sec][0] == false && found_key[sec][1] == false) { int res = fm11_intersect_pair(nt_a, &candidates[sec][0], nt_b, &candidates[sec][1]); if (res != PM3_SUCCESS) { retval = res; goto out; } + res = fm11_prioritize_by_paired_seed(&candidates[sec][0], &candidates[sec][1]); if (res != PM3_SUCCESS) { retval = res; goto out; } + res = fm11_prioritize_by_paired_seed(&candidates[sec][1], &candidates[sec][0]); if (res != PM3_SUCCESS) { retval = res; @@ -3057,27 +3095,37 @@ int HFMFSENRecover(bool keep_nonces, bool no_oob, bool reader_mode, bool offline } fm11_sort_candidates_by_seed_bucket(&candidates[sec][0], &candidates[sec][1]); } + fm11_prioritize_defaults(&candidates[sec][0], &default_keys); fm11_prioritize_defaults(&candidates[sec][1], &default_keys); + if (real_sec == 32) { fm11_prioritize_0000_prefix(&candidates[sec][1]); } - snprintf(activity, sizeof(activity), "Prepared sec %03u candidates (A %u / B %u)", - real_sec, candidates[sec][0].count, candidates[sec][1].count); + snprintf(activity, sizeof(activity), "Prepared sec %03u candidates (A %u / B %u)" + , real_sec + , candidates[sec][0].count + , candidates[sec][1].count + ); fm11_sen_progress(nonce_count, activity, candidates[sec][0].count + candidates[sec][1].count, 0); } if (reader_mode) { + uint32_t accepted = fm11_apply_reader_material(&nonces, candidates, keys_found, found_key, reader_keys, reader_found); if (accepted > 0) { + snprintf(activity, sizeof(activity), "Applied %u reader-recovered key%s", accepted, (accepted == 1) ? "" : "s"); fm11_sen_progress(nonce_count, activity, accepted, 0); + uint32_t reduced = 0; uint32_t derived = fm11_offline_fixpoint(&nonces, candidates, keys_found, found_key, &reduced, offline_only); + if (reduced > 0) { snprintf(activity, sizeof(activity), "Reduced paired candidate sets by %u keys", reduced); fm11_sen_progress(nonce_count, activity, reduced, 0); } + if (derived > 0) { snprintf(activity, sizeof(activity), "Derived %u paired keys from reader material", derived); fm11_sen_progress(nonce_count, activity, derived, 0); @@ -3090,12 +3138,14 @@ int HFMFSENRecover(bool keep_nonces, bool no_oob, bool reader_mode, bool offline total_candidates += candidates[sec][0].count; total_candidates += candidates[sec][1].count; } + uint32_t duplicate_candidates = 0; uint32_t duplicate_prefix[FM11RF08S_SECTORS][2] = {{0}}; retval = fm11_prioritize_duplicates(candidates, duplicate_prefix, &duplicate_candidates); if (retval != PM3_SUCCESS) { goto out; } + uint32_t verify_eta = (total_candidates / 2 / FM11RF08S_FCHK_KEYS_PER_SECOND) + 5; snprintf(activity, sizeof(activity), "Prioritized candidates (%u duplicate-priority)", duplicate_candidates); fm11_sen_progress(nonce_count, activity, total_candidates, verify_eta); @@ -3104,6 +3154,7 @@ int HFMFSENRecover(bool keep_nonces, bool no_oob, bool reader_mode, bool offline if (retval != PM3_SUCCESS) { goto out; } + snprintf(activity, sizeof(activity), "Indexed %u candidate refs for key-reuse cascades", reuse_index.ref_count); fm11_sen_progress(nonce_count, activity, reuse_index.ref_count, 0); @@ -3114,22 +3165,29 @@ int HFMFSENRecover(bool keep_nonces, bool no_oob, bool reader_mode, bool offline fm11_keylist_free(&priority); goto out; } + uint32_t found_before = fm11_count_found_keys(found_key); uint32_t priority_count = priority.count; + if (priority_count > 0) { - snprintf(activity, sizeof(activity), "Batch-check top %u/%u cross-sector reuse keys with fchk", - priority_count, reuse_eligible); + + snprintf(activity, sizeof(activity), "Batch-check top %u/%u cross-sector reuse keys with fchk", priority_count, reuse_eligible); + fm11_sen_progress(nonce_count, activity, priority_count, (priority_count / FM11RF08S_FCHK_KEYS_PER_SECOND) + 2); + retval = fm11_verify_global_priority_keys(&priority, keys_found, found_key); fm11_keylist_free(&priority); + if (retval != PM3_SUCCESS) { goto out; } + uint32_t found_after = fm11_count_found_keys(found_key); if (found_after > found_before) { snprintf(activity, sizeof(activity), "Reuse-priority fchk recovered %u normal-sector keys", found_after - found_before); fm11_sen_progress(nonce_count, activity, found_after - found_before, 0); } + } else { fm11_keylist_free(&priority); } @@ -3140,21 +3198,29 @@ int HFMFSENRecover(bool keep_nonces, bool no_oob, bool reader_mode, bool offline fm11_keylist_free(&priority); goto out; } + found_before = fm11_count_found_keys(found_key); priority_count = priority.count; + if (priority_count > 0 && priority_count <= FM11RF08S_MAX_GLOBAL_PRIORITY_KEYS) { + snprintf(activity, sizeof(activity), "Batch-check %u duplicate-priority keys with fchk", priority_count); fm11_sen_progress(nonce_count, activity, priority_count, (priority_count / FM11RF08S_FCHK_KEYS_PER_SECOND) + 2); + retval = fm11_verify_global_priority_keys(&priority, keys_found, found_key); + fm11_keylist_free(&priority); + if (retval != PM3_SUCCESS) { goto out; } + uint32_t found_after = fm11_count_found_keys(found_key); if (found_after > found_before) { snprintf(activity, sizeof(activity), "Batch fchk recovered %u normal-sector keys", found_after - found_before); fm11_sen_progress(nonce_count, activity, found_after - found_before, 0); } + } else { fm11_keylist_free(&priority); if (priority_count > FM11RF08S_MAX_GLOBAL_PRIORITY_KEYS) { @@ -3162,6 +3228,7 @@ int HFMFSENRecover(bool keep_nonces, bool no_oob, bool reader_mode, bool offline fm11_sen_progress(nonce_count, activity, priority_count, 0); } } + uint32_t propagated = fm11_propagate_found_keys(&nonces, candidates, keys_found, found_key); if (propagated > 0) { snprintf(activity, sizeof(activity), "Propagated %u reused candidate key matches", propagated); @@ -3174,6 +3241,7 @@ int HFMFSENRecover(bool keep_nonces, bool no_oob, bool reader_mode, bool offline snprintf(activity, sizeof(activity), "Reduced paired candidate sets by %u keys", reduced); fm11_sen_progress(nonce_count, activity, reduced, 0); } + if (derived > 0) { snprintf(activity, sizeof(activity), "Derived %u paired keys from matching FM11RF08S seeds", derived); fm11_sen_progress(nonce_count, activity, derived, 0); @@ -3183,22 +3251,24 @@ int HFMFSENRecover(bool keep_nonces, bool no_oob, bool reader_mode, bool offline if (retval != PM3_SUCCESS) { goto out; } + snprintf(activity, sizeof(activity), "Refreshed %u candidate refs for key-reuse cascades", reuse_index.ref_count); fm11_sen_progress(nonce_count, activity, reuse_index.ref_count, 0); total_candidates = fm11_count_unfound_candidates(candidates, found_key); if (max_online_candidates > 0 && (int)total_candidates > max_online_candidates) { - PrintAndLogEx(WARNING, "Total unfound candidates (%u) exceeds --max-online-candidates limit (%d), stopping", - total_candidates, max_online_candidates); + PrintAndLogEx(WARNING, "Total unfound candidates (%u) exceeds --max-online-candidates limit (%d), stopping", total_candidates, max_online_candidates); goto out; } + if (offline_only) { fm11_sen_progress_footer(); fm11_print_key_table(keys_found, found_key); - retval = fm11_save_recovery_outputs(&card, &nonces, keys_found, found_key, no_oob, collected_with_data); + retval = fm11_save_recovery_outputs(&card, &nonces, keys_found, found_key, no_oob, collected_with_data, suffix, no_save); PrintAndLogEx(SUCCESS, "time in sen " _YELLOW_("%.0f") " seconds", (float)(msclock() - t1) / 1000.0); goto out; } + verify_eta = (total_candidates / 2 / FM11RF08S_FCHK_KEYS_PER_SECOND) + 5; fm11_sen_progress(nonce_count, "Measurement: score unresolved candidate paths", total_candidates, 0); fm11_measure_candidate_paths(&nonces, candidates, keys_found, found_key, nonce_count); @@ -3210,20 +3280,25 @@ int HFMFSENRecover(bool keep_nonces, bool no_oob, bool reader_mode, bool offline */ bool exhausted[FM11RF08S_SECTORS][2] = {{false}}; uint32_t probe_pos = 0; + while (true) { + if (kbd_enter_pressed()) { retval = PM3_EOPABORTED; goto out; } - /* find the cheapest unfound, non-exhausted (sec, kt) pair */ + + // find the cheapest unfound, non-exhausted (sec, kt) pair uint8_t best_sec = 0xFF, best_kt = 0; uint32_t best_cost = UINT32_MAX; uint32_t best_count = UINT32_MAX; + for (uint8_t sec = 0; sec < FM11RF08S_SECTORS; sec++) { for (uint8_t kt = 0; kt < 2; kt++) { if (found_key[sec][kt] || exhausted[sec][kt]) { continue; } + uint32_t cnt = candidates[sec][kt].count; uint32_t cost = fm11_estimate_candidate_path_cost(&nonces, candidates, keys_found, found_key, sec, kt); if (sec == FM11RF08S_SECTORS - 1 && kt == 1 && cnt > 0) { @@ -3232,6 +3307,7 @@ int HFMFSENRecover(bool keep_nonces, bool no_oob, bool reader_mode, bool offline cost = best_cost > 0 ? best_cost - 1 : 0; } } + if (cost < best_cost || (cost == best_cost && cnt < best_count)) { best_cost = cost; best_count = cnt; @@ -3240,87 +3316,112 @@ int HFMFSENRecover(bool keep_nonces, bool no_oob, bool reader_mode, bool offline } } } + + // all sectors/keys found or exhausted if (best_sec == 0xFF) { - break; /* all sectors/keys found or exhausted */ + break; } + uint8_t sec = best_sec; uint8_t kt = best_kt; uint8_t real_sec = fm11_real_sector(sec); + if (found_key[sec][kt ^ 1]) { + uint32_t nt_target = fm11_bytes_to_u32(nonces.nt[sec][kt]); uint32_t nt_known = fm11_bytes_to_u32(nonces.nt[sec][kt ^ 1]); + if (nt_target != nt_known) { + uint16_t seed = fm11_compute_seednt16_nt32(nt_known, keys_found[sec][kt ^ 1]); uint32_t old_count = 0; uint32_t new_count = 0; + int filter_res = fm11_filter_candidates_by_seed(&candidates[sec][kt], nt_target, seed, &old_count, &new_count); if (filter_res != PM3_SUCCESS) { retval = filter_res; goto out; } + if (old_count > new_count) { snprintf(activity, sizeof(activity), "Reduced paired candidate set by %u keys", old_count - new_count); fm11_sen_progress(nonce_count, activity, old_count - new_count, 0); } + } else { fm11_keylist_promote_existing(&candidates[sec][kt], keys_found[sec][kt ^ 1]); } } - snprintf(activity, sizeof(activity), "sec %03u key %c - checking %u candidates", real_sec, kt ? 'B' : 'A', candidates[sec][kt].count); - fm11_sen_progress(nonce_count, activity, candidates[sec][kt].count, - (candidates[sec][kt].count / 2 / FM11RF08S_FCHK_KEYS_PER_SECOND) + 1); + snprintf(activity, sizeof(activity), "sec %03u key %c - checking %u candidates", real_sec, kt ? 'B' : 'A', candidates[sec][kt].count); + fm11_sen_progress(nonce_count, activity, candidates[sec][kt].count, (candidates[sec][kt].count / 2 / FM11RF08S_FCHK_KEYS_PER_SECOND) + 1); + uint64_t key = 0; int res = fm11_verify_candidates(real_sec, kt, &candidates[sec][kt], &key); if (res == PM3_SUCCESS) { + propagated = fm11_accept_found_key_global(&nonces, candidates, keys_found, found_key, &reuse_index, sec, kt, key, &probe_queue); fm11_print_key_hit_row(nonce_count, sec, kt, key, found_key); + uint32_t reuse_found = 0; if (fm11_keylist_has_key(&confirmed_reuse_keys, key) == false) { (void)fm11_keylist_add_unique(&confirmed_reuse_keys, key); reuse_found = fm11_propagate_key_reuse_online(nonce_count, key, keys_found, found_key); } + if (reuse_found > 0) { snprintf(activity, sizeof(activity), "Key re-use propagation confirmed %u additional key slots", reuse_found); fm11_sen_progress(nonce_count, activity, reuse_found, 0); propagated += fm11_accept_found_key_global(&nonces, candidates, keys_found, found_key, &reuse_index, sec, kt, key, &probe_queue); } + if (propagated > 1) { snprintf(activity, sizeof(activity), "Propagated %u reused candidate key matches", propagated - 1); fm11_sen_progress(nonce_count, activity, propagated - 1, 0); } + reduced = 0; derived = fm11_offline_fixpoint(&nonces, candidates, keys_found, found_key, &reduced, false); if (reduced > 0) { snprintf(activity, sizeof(activity), "Reduced paired candidate sets by %u keys", reduced); fm11_sen_progress(nonce_count, activity, reduced, 0); } + if (derived > 0) { snprintf(activity, sizeof(activity), "Derived %u additional paired keys", derived); fm11_sen_progress(nonce_count, activity, derived, 0); } + while (probe_pos < probe_queue.count) { uint8_t ps = probe_queue.entries[probe_pos].sec; uint8_t pk = probe_queue.entries[probe_pos].key_type; uint64_t pkey = probe_queue.entries[probe_pos].key; + probe_pos++; if (found_key[ps][pk]) { continue; } + fm11_keylist_t single = {0}; + if (fm11_keylist_push(&single, pkey, 0) == PM3_SUCCESS) { + uint8_t real_ps = fm11_real_sector(ps); uint64_t out_key = 0; + if (fm11_verify_candidates(real_ps, pk, &single, &out_key) == PM3_SUCCESS) { + uint32_t prop = fm11_accept_found_key_global(&nonces, candidates, keys_found, found_key, &reuse_index, ps, pk, out_key, &probe_queue); if (prop > 0) { fm11_print_key_hit_row(nonce_count, ps, pk, out_key, found_key); } + uint32_t reuse_extra = 0; if (fm11_keylist_has_key(&confirmed_reuse_keys, out_key) == false) { (void)fm11_keylist_add_unique(&confirmed_reuse_keys, out_key); reuse_extra = fm11_propagate_key_reuse_online(nonce_count, out_key, keys_found, found_key); } + if (reuse_extra > 0) { snprintf(activity, sizeof(activity), "Key re-use propagation confirmed %u additional key slots", reuse_extra); fm11_sen_progress(nonce_count, activity, reuse_extra, 0); @@ -3330,37 +3431,46 @@ int HFMFSENRecover(bool keep_nonces, bool no_oob, bool reader_mode, bool offline } } total_candidates = fm11_count_unfound_candidates(candidates, found_key); + } else if (res == PM3_ETIMEOUT || res == PM3_EOPABORTED) { retval = res; goto out; } else { - /* candidate set exhausted without finding a key */ + // candidate set exhausted without finding a key exhausted[sec][kt] = true; } } - /* drain probe queue: verify single-key probes scheduled by fm11_accept_found_key_global */ + // drain probe queue: verify single-key probes scheduled by fm11_accept_found_key_global for (uint32_t pi = probe_pos; pi < probe_queue.count; pi++) { + uint8_t ps = probe_queue.entries[pi].sec; uint8_t pk = probe_queue.entries[pi].key_type; uint64_t pkey = probe_queue.entries[pi].key; + if (found_key[ps][pk]) { continue; } + fm11_keylist_t single = {0}; if (fm11_keylist_push(&single, pkey, 0) == PM3_SUCCESS) { + uint8_t real_ps = fm11_real_sector(ps); uint64_t out_key = 0; + if (fm11_verify_candidates(real_ps, pk, &single, &out_key) == PM3_SUCCESS) { + uint32_t prop = fm11_accept_found_key_global(&nonces, candidates, keys_found, found_key, &reuse_index, ps, pk, out_key, &probe_queue); if (prop > 0) { fm11_print_key_hit_row(nonce_count, ps, pk, out_key, found_key); } + uint32_t reuse_extra = 0; if (fm11_keylist_has_key(&confirmed_reuse_keys, out_key) == false) { (void)fm11_keylist_add_unique(&confirmed_reuse_keys, out_key); reuse_extra = fm11_propagate_key_reuse_online(nonce_count, out_key, keys_found, found_key); } + if (reuse_extra > 0) { snprintf(activity, sizeof(activity), "Key re-use propagation confirmed %u additional key slots", reuse_extra); fm11_sen_progress(nonce_count, activity, reuse_extra, 0); @@ -3372,7 +3482,7 @@ int HFMFSENRecover(bool keep_nonces, bool no_oob, bool reader_mode, bool offline fm11_sen_progress_footer(); fm11_print_key_table(keys_found, found_key); - retval = fm11_save_recovery_outputs(&card, &nonces, keys_found, found_key, no_oob, collected_with_data); + retval = fm11_save_recovery_outputs(&card, &nonces, keys_found, found_key, no_oob, collected_with_data, suffix, no_save); PrintAndLogEx(SUCCESS, "time in sen " _YELLOW_("%.0f") " seconds", (float)(msclock() - t1) / 1000.0); out: @@ -3393,7 +3503,9 @@ int CmdHF14AMfSEN(const char *Cmd) { "hf mf sen\n" "hf mf sen --keep-nonces\n" "hf mf sen --no-oob\n" - "hf mf sen --reader\n"); + "hf mf sen --reader\n" + "hf mf sen --suffix mycard\n" + "hf mf sen --ns\n"); void *argtable[] = { arg_param_begin, arg_lit0(NULL, "keep-nonces", "save collected nonce/data JSON evidence"), @@ -3403,6 +3515,8 @@ int CmdHF14AMfSEN(const char *Cmd) { arg_lit0(NULL, "online-confirm", "only do online confirmation (skip generation if nonces loaded)"), arg_int0(NULL, "max-online-candidates", "", "abort online phase if total candidates exceed this limit"), arg_str0(NULL, "parity-mask", "", "parity filter mask 1..F (default 1 = vetted staticnested_1nt behavior)"), + arg_str0(NULL, "suffix", "", "Add this suffix to generated files"), + arg_lit0(NULL, "ns", "no save to file (--keep-nonces still writes its evidence file)"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, true); @@ -3412,10 +3526,12 @@ int CmdHF14AMfSEN(const char *Cmd) { bool offline_only = arg_get_lit(ctx, 4); bool online_confirm = arg_get_lit(ctx, 5); int max_online_candidates = arg_get_int_def(ctx, 6, 0); + /* Only bit 0 (byte 0 parity) carries reliable data leakage from FM11RF08S. * Bits 1-3 are not valid keystream leakage for this card variant - using * them filters out correct keys. Override via --parity-mask if needed for - * any weird chinese clones, normally you should never use this parameter. */ + * any weird chinese clones, normally you should never use this parameter. + */ uint8_t parity_mask = 0x1; { int pm_len = 0; @@ -3429,7 +3545,12 @@ int CmdHF14AMfSEN(const char *Cmd) { } } (void)online_confirm; + + int sfxlen = 0; + char suffix[FILE_PATH_SIZE] = {0}; + CLIParamStrToBuf(arg_get_str(ctx, 8), (uint8_t *)suffix, FILE_PATH_SIZE, &sfxlen); + bool no_save = arg_get_lit(ctx, 9); CLIParserFree(ctx); - return HFMFSENRecover(keep_nonces, no_oob, reader_mode, offline_only, max_online_candidates, parity_mask, false, NULL, 0); + return HFMFSENRecover(keep_nonces, no_oob, reader_mode, offline_only, max_online_candidates, parity_mask, false, NULL, 0, suffix, no_save); } diff --git a/client/src/cmdhfmfsen.h b/client/src/cmdhfmfsen.h index 7f0c502a1..6053b7513 100644 --- a/client/src/cmdhfmfsen.h +++ b/client/src/cmdhfmfsen.h @@ -34,7 +34,7 @@ extern "C" { extern const uint8_t fm11_backdoor_keys[FM11_BACKDOOR_KEY_COUNT][MIFARE_KEY_SIZE]; int fm11_collect_nonces(const uint8_t *key, iso14a_card_select_t *card, iso14a_fm11rf08s_nonces_with_data_t *nonces); -int HFMFSENRecover(bool keep_nonces, bool no_oob, bool reader_mode, bool offline_only, int max_online_candidates, uint8_t parity_mask, bool skip_default_key_check, const sector_t *known_sectors, size_t known_sector_count); +int HFMFSENRecover(bool keep_nonces, bool no_oob, bool reader_mode, bool offline_only, int max_online_candidates, uint8_t parity_mask, bool skip_default_key_check, const sector_t *known_sectors, size_t known_sector_count, const char *suffix, bool no_save); int CmdHF14AMfSEN(const char *Cmd); #ifdef __cplusplus diff --git a/client/src/cmdhfmfu.c b/client/src/cmdhfmfu.c index fc918c4d5..0b0a667f7 100644 --- a/client/src/cmdhfmfu.c +++ b/client/src/cmdhfmfu.c @@ -65,8 +65,20 @@ #define MAX_ST25TN512 0x3F #define MAX_ST25TN01K 0x3F +// UL-C key pages +#define MFU_ULC_KEY0_PAGE 0x2C + +// UL-AES fixed memory map, MF0AES(H)20 +#define MFU_AES_USER_FIRST 0x04 +#define MFU_AES_USER_LAST 0x27 +#define MFU_AES_LOCK_PAGE 0x28 +#define MFU_AES_CFG0_PAGE 0x29 +#define MFU_AES_CFG1_PAGE 0x2A +#define MFU_AES_KEY0_PAGE 0x30 + #define MIFAREU3P_KEY_SIZE 16 #define MIFAREULC_KEY_INDEX 3 +#define MFU_DEFAULT_KEY_DIC "mfulc_default_keys.dic" // The Capability Container sits in block 3, the NDEF data area starts at block 4 // and READ takes a one byte block number, so block 255 is the last one reachable. @@ -1179,6 +1191,15 @@ static int ulc_print_3deskey(uint8_t *data) { return PM3_SUCCESS; } +static int ulaes_print_key(uint8_t *data) { + PrintAndLogEx(INFO, " aeskey [48/0x30]: %s [%s]", sprint_hex(data, 4), sprint_ascii(data, 4)); + PrintAndLogEx(INFO, " aeskey [49/0x31]: %s [%s]", sprint_hex(data + 4, 4), sprint_ascii(data + 4, 4)); + PrintAndLogEx(INFO, " aeskey [50/0x32]: %s [%s]", sprint_hex(data + 8, 4), sprint_ascii(data + 8, 4)); + PrintAndLogEx(INFO, " aeskey [51/0x33]: %s [%s]", sprint_hex(data + 12, 4), sprint_ascii(data + 12, 4)); + PrintAndLogEx(INFO, "aes key: " _GREEN_("%s"), sprint_hex_inrow(SwapEndian64(data, 16, 16), 16)); + return PM3_SUCCESS; +} + // Only takes 16 bytes of data. Now key data available here static int ulc_print_configuration(uint8_t *data) { @@ -1217,7 +1238,7 @@ static int ulc_print_configuration(uint8_t *data) { static int ulaes_print_configuration(uint8_t *data, uint8_t start_page) { // first call - if (start_page == 0x2C) { + if (start_page == 0x29) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(INFO, "--- " _CYAN_("UL-AES Configuration") " --------------------------"); @@ -1678,8 +1699,11 @@ static uint64_t ul_magic_test(void) { // check for GEN1A, GEN1B and NTAG21x PacketResponseNG resp; clearCommandBuffer(); - uint8_t payload[] = { 0 }; - SendCommandNG(CMD_HF_MIFARE_CIDENT, payload, sizeof(payload)); + mf_chinese_ident_t payload = { + .is_mfc = false, + .keytype = MF_KEY_A, + }; + SendCommandNG(CMD_HF_MIFARE_CIDENT, (uint8_t *)&payload, sizeof(payload)); uint16_t is_generation = MAGIC_FLAG_NONE; if (WaitForResponseTimeout(CMD_HF_MIFARE_CIDENT, &resp, 1500)) { @@ -1816,7 +1840,7 @@ typedef struct { } mfu_otp_identify_t; static mfu_otp_identify_t mfu_otp_ident_table[] = { - { "SALTO Systems card", 12, 4, "534C544F", ul_c_otpgenA, "report to iceman!" }, + { "SALTO Systems card", 12, 4, "534C544F", ul_c_otpgenA, NULL }, { NULL, 0, 0, NULL, NULL, NULL} // must be the last item }; @@ -2798,10 +2822,14 @@ static int CmdHF14AMfUInfo(const char *Cmd) { uint8_t startconfigblock = 0; uint8_t ulev1_conf[16] = {0x00}; - for (uint8_t i = 1; i < ARRAYLEN(UL_TYPES_ARRAY); i++) { - if ((tagtype & UL_TYPES_ARRAY[i]) == UL_TYPES_ARRAY[i]) { - startconfigblock = UL_MEMORY_ARRAY[i] - 3; - break; + // UL-AES config doesn't sit in the last four pages, those are the AES keys. + // Its config pages are read further down + if ((tagtype & MFU_TT_UL_AES) != MFU_TT_UL_AES) { + for (uint8_t i = 1; i < ARRAYLEN(UL_TYPES_ARRAY); i++) { + if ((tagtype & UL_TYPES_ARRAY[i]) == UL_TYPES_ARRAY[i]) { + startconfigblock = UL_MEMORY_ARRAY[i] - 3; + break; + } } } @@ -4035,6 +4063,7 @@ static int CmdHF14AMfURestore(const char *Cmd) { "hf mfu restore -f myfile -s -> special write\n" "hf mfu restore -f myfile -k AABBCCDD -s -> special write, use key\n" "hf mfu restore -f myfile -k AABBCCDD -ser -> special write, use key, write dump pwd, ...\n" + "hf mfu restore -f myfile -k 00112233445566778899AABBCCDDEEFF -> UL-C / UL-AES, use key\n" "\n" "Note: Restoring a NTAG/UL dump to a UMC will likely result in incorrect PWD and PACK\n" ); @@ -4042,7 +4071,7 @@ static int CmdHF14AMfURestore(const char *Cmd) { void *argtable[] = { arg_param_begin, arg_str1("f", "file", "", "Specify a filename for dump file"), - arg_str0("k", "key", "", "key for authentication (UL-C 16 bytes, EV1/NTAG 4 bytes)"), + arg_str0("k", "key", "", "key for authentication (UL-C/UL-AES 16 bytes, EV1/NTAG 4 bytes)"), arg_lit0("l", NULL, "swap entered key's endianness"), arg_lit0("s", NULL, "enable special write UID -MAGIC TAG ONLY-"), arg_lit0("e", NULL, "enable special write version/signature -MAGIC NTAG 21* ONLY-"), @@ -4134,6 +4163,8 @@ static int CmdHF14AMfURestore(const char *Cmd) { return PM3_ESOFT; } + bool is_ulaes = ((tagtype & MFU_TT_UL_AES) == MFU_TT_UL_AES); + if ((tagtype & MFU_TT_UL_C) == MFU_TT_UL_C) { if ((has_key == true) && (ak_len != 16)) { PrintAndLogEx(ERR, "UL-C key must be 16 bytes"); @@ -4164,12 +4195,6 @@ static int CmdHF14AMfURestore(const char *Cmd) { } } - if ((tagtype & MFU_TT_UL_AES) == MFU_TT_UL_AES) { - PrintAndLogEx(ERR, "Sorry, UL-AES not yet supported. Feel free to implement!"); - free(dump); - return PM3_ENOTIMPL; - } - PrintAndLogEx(INFO, "Restoring " _YELLOW_("%s")" to card", filename); mfu_print_dump(mem, pages, 0, dense_output); @@ -4271,7 +4296,19 @@ static int CmdHF14AMfURestore(const char *Cmd) { // write all other data // Skip block 0,1,2,3 (only magic tags can write to them) // Skip last 5 blocks usually is configuration - for (uint8_t b = 4; b < pages - 5; b++) { + uint8_t first_page = 4; + uint8_t last_page = pages - 5; + + if (is_ulaes) { + // UL-AES user memory stops before the lock, config and key pages + first_page = MFU_AES_USER_FIRST; + last_page = MFU_AES_USER_LAST + 1; + if (pages < last_page) { + last_page = pages; + } + } + + for (uint8_t b = first_page; b < last_page; b++) { //Send write Block memcpy(packetw.data, mem->data + (b * 4), 4); @@ -4298,8 +4335,19 @@ static int CmdHF14AMfURestore(const char *Cmd) { // otp, uid, lock, dynlockbits, cfg0, cfg1 uint8_t blocks[] = {3, 0, 1, 2, pages - 5, pages - 4, pages - 3}; #endif - for (uint8_t i = 0; i < ARRAYLEN(blocks); i++) { - uint8_t b = blocks[i]; + // otp, uid, lock, cfg0, cfg1. + // RFU pages (0x2B, 0x2C) and the key lock bits (0x2D) are left alone, they are one way + uint8_t ulaes_blocks[] = {3, 0, 1, 2, MFU_AES_LOCK_PAGE, MFU_AES_CFG0_PAGE, MFU_AES_CFG1_PAGE}; + + uint8_t *pblocks = blocks; + uint8_t blockcnt = ARRAYLEN(blocks); + if (is_ulaes) { + pblocks = ulaes_blocks; + blockcnt = ARRAYLEN(ulaes_blocks); + } + + for (uint8_t i = 0; i < blockcnt; i++) { + uint8_t b = pblocks[i]; memcpy(packetw.data, mem->data + (b * 4), 4); packetw.block_no = b; clearCommandBuffer(); @@ -4311,6 +4359,12 @@ static int CmdHF14AMfURestore(const char *Cmd) { DropField(); free(dump); + + if (is_ulaes) { + PrintAndLogEx(INFO, "Key pages 0x%02X..0x%02X not restored", MFU_AES_KEY0_PAGE, MAX_UL_AES); + PrintAndLogEx(HINT, "Hint: Try `" _YELLOW_("hf mfu setkey -k <16 hex bytes>") "` to restore the AES keys"); + } + PrintAndLogEx(HINT, "Hint: Try `" _YELLOW_("hf mfu dump --ns") "` to verify"); PrintAndLogEx(INFO, "Done!"); return PM3_SUCCESS; @@ -4718,57 +4772,12 @@ static int CmdHF14AMfUCAuth(const char *Cmd) { return isok; } -static int CmdHF14AMfUCAuthChk(const char *Cmd) { - CLIParserContext *ctx; - CLIParserInit(&ctx, "hf mfu cchk", - "It checks MIFARE Ultralight C tags keys against a dictionary file with keys\n", - "hf mfu cchk -f mfulc_default_keys.dic"); - - void *argtable[] = { - arg_param_begin, - arg_str0("f", "file", "", "filename of dictionary"), - arg_int0("s", "segment", "<0..3>", "Segment index (full key if not specified)"), - arg_int0("r", "retries", "<0..255>", "Number of retries (def: 0)"), - arg_str0("k", "key", "", "Starting key, 16 hex bytes (def: zero key), for segment check"), - arg_lit0("x", "xor", "XOR starting key with segment candidates (def: override)"), - arg_lit0("n", "nocheck", "Skip checking tag answer correctness"), - arg_lit0("0", "read0", "Use fast READ0 (skip anticol)"), - arg_param_end - }; - CLIExecWithReturn(ctx, Cmd, argtable, true); - - int fnlen = 0; - char filename[FILE_PATH_SIZE] = {0}; - CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen); - int segment = arg_get_int_def(ctx, 2, -1); // -1 means full key - int retries = arg_get_int_def(ctx, 3, 0); - int ref_keylen = 0; - uint8_t ref_key[16] = {0}; - CLIGetHexWithReturn(ctx, 4, ref_key, &ref_keylen); - bool xor_ref_key = arg_get_lit(ctx, 5); - bool check_answer = !arg_get_lit(ctx, 6); - bool use_fastread0 = arg_get_lit(ctx, 7); - CLIParserFree(ctx); - - if (fnlen == 0) { - PrintAndLogEx(ERR, "No dictionary file specified"); - return PM3_EFILE; - } - if (segment < -1 || segment > 3) { - PrintAndLogEx(ERR, "Invalid segment (must be 0..3)"); - return PM3_EINVARG; - } - if (retries < 0 || retries > 255) { - PrintAndLogEx(ERR, "Invalid retries (must be 0..255)"); - return PM3_EINVARG; - } - if (ref_keylen && ref_keylen != MIFAREU3P_KEY_SIZE) { - PrintAndLogEx(WARNING, "Key must be %i hex bytes. Got %d", MIFAREU3P_KEY_SIZE, ref_keylen); - return PM3_EINVARG; - } - if (ref_keylen == 0) { - ref_keylen = MIFAREU3P_KEY_SIZE; - } +// Runs one dictionary against one key slot. The device can only hold a few keys +// per frame, so the dictionary is fed to it in chunks: the first chunk selects the +// card, the last one drops the field. +static int mfu_auth_chk(uint8_t key_index, const char *filename, int fnlen, int segment, + int retries, uint8_t *ref_key, bool xor_ref_key, bool check_answer, + bool use_fastread0) { uint8_t *keyBlock = NULL; uint32_t keycnt = 0; @@ -4789,9 +4798,6 @@ static int CmdHF14AMfUCAuthChk(const char *Cmd) { max_chunk = MIFAREU3P_CHKKEY_MAX_KEYS; } uint32_t chunksize = (keycnt > max_chunk) ? max_chunk : keycnt; - bool firstChunk = true, lastChunk = false; - - int i = 0; // time uint32_t auths = 0; @@ -4799,7 +4805,12 @@ static int CmdHF14AMfUCAuthChk(const char *Cmd) { // main keychunk loop for (int r = 0; r < retries + 1; r++) { - for (i = 0; i < keycnt; i += chunksize) { + + // every pass needs its own select and its own teardown + bool firstChunk = true, lastChunk = false; + + for (uint32_t i = 0; i < keycnt; i += chunksize) { + if (kbd_enter_pressed()) { clearCommandBuffer(); SendCommandNG(CMD_BREAK_LOOP, NULL, 0); @@ -4809,22 +4820,22 @@ static int CmdHF14AMfUCAuthChk(const char *Cmd) { goto out; } - uint32_t nkeys = ((keycnt - i) > chunksize) ? chunksize : keycnt - i; + uint32_t nkeys = ((keycnt - i) > chunksize) ? chunksize : keycnt - i; // last chunk? if (nkeys == keycnt - i) { lastChunk = true; } - int res = mfu_3pass_check_keys(MIFAREULC_KEY_INDEX, firstChunk, lastChunk, nkeys, segment, ref_key, xor_ref_key, keyBlock + (i * keysize), false, true, &auths, &ms, check_answer, use_fastread0); - if (firstChunk) - firstChunk = false; + + int res = mfu_3pass_check_keys(key_index, firstChunk, lastChunk, nkeys, segment, ref_key, xor_ref_key, keyBlock + (i * keysize), false, true, &auths, &ms, check_answer, use_fastread0); + firstChunk = false; // all keys, aborted if (res == PM3_SUCCESS || res == 2) { PrintAndLogEx(NORMAL, ""); goto out; } - PrintAndLogEx(INPLACE, "Testing %5i/%5i ( " _YELLOW_("%02.1f %%") " )", i, keycnt, (float)i * 100 / keycnt); + PrintAndLogEx(INPLACE, "Testing %5u/%5u ( " _YELLOW_("%02.1f %%") " )", i, keycnt, (float)i * 100 / keycnt); } // end chunks of keys } PrintAndLogEx(NORMAL, ""); @@ -4837,6 +4848,102 @@ out: PrintAndLogEx(NORMAL, ""); return PM3_SUCCESS; } + +static int CmdHF14AMfUAuthChk(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hf mfu chk", + "Checks MIFARE Ultralight C / Ultralight AES tag keys against a dictionary file.\n" + "The tag type is read off the card and picks the key slot to attack.\n" + " UL-C ..... single 3DES key, --idx does not apply\n" + " UL-AES ... key index 0 DataProtKey (default)\n" + " key index 1 UIDRetrKey\n" + " key index 2 OriginalityKey\n" + "Without -f, " _YELLOW_(MFU_DEFAULT_KEY_DIC) " is used for both tag types.\n" + "A segment check (-s) holds 4 byte keys, so it needs its own dictionary via -f.", + "hf mfu chk\n" + "hf mfu chk -f mfulc_default_keys.dic\n" + "hf mfu chk -f mfulaes_hw1.dic --idx 1\n" + "hf mfu chk -f mfulc_segment_hw1.dic -s 0"); + + void *argtable[] = { + arg_param_begin, + arg_str0("f", "file", "", "filename of dictionary"), + arg_int0("i", "idx", "<0..2>", "Key index, Ultralight AES only (def: 0)"), + arg_int0("s", "segment", "<0..3>", "Segment index (full key if not specified)"), + arg_int0("r", "retries", "<0..255>", "Number of retries (def: 0)"), + arg_str0("k", "key", "", "Starting key, 16 hex bytes (def: zero key), for segment check"), + arg_lit0("x", "xor", "XOR starting key with segment candidates (def: override)"), + arg_lit0("n", "nocheck", "Skip checking tag answer correctness"), + arg_lit0("0", "read0", "Use fast READ0 (skip anticol)"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + + int fnlen = 0; + char filename[FILE_PATH_SIZE] = {0}; + CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen); + int key_idx = arg_get_int_def(ctx, 2, -1); // -1 means not given + int segment = arg_get_int_def(ctx, 3, -1); // -1 means full key + int retries = arg_get_int_def(ctx, 4, 0); + int ref_keylen = 0; + uint8_t ref_key[16] = {0}; + CLIGetHexWithReturn(ctx, 5, ref_key, &ref_keylen); + bool xor_ref_key = arg_get_lit(ctx, 6); + bool check_answer = !arg_get_lit(ctx, 7); + bool use_fastread0 = arg_get_lit(ctx, 8); + CLIParserFree(ctx); + + if (key_idx < -1 || key_idx > 2) { + PrintAndLogEx(ERR, "Invalid key index (must be 0..2)"); + return PM3_EINVARG; + } + if (segment < -1 || segment > 3) { + PrintAndLogEx(ERR, "Invalid segment (must be 0..3)"); + return PM3_EINVARG; + } + if (retries < 0 || retries > 255) { + PrintAndLogEx(ERR, "Invalid retries (must be 0..255)"); + return PM3_EINVARG; + } + if (ref_keylen && ref_keylen != MIFAREU3P_KEY_SIZE) { + PrintAndLogEx(WARNING, "Key must be %i hex bytes. Got %d", MIFAREU3P_KEY_SIZE, ref_keylen); + return PM3_EINVARG; + } + + if (fnlen == 0) { + if (segment != -1) { + PrintAndLogEx(ERR, "A segment check needs a segment dictionary, pass one with " _YELLOW_("-f")); + PrintAndLogEx(HINT, "Hint: Try `" _YELLOW_("mfulc_segment_hw1.dic") "` or `" _YELLOW_("mfulaes_segment_hw1.dic") "`"); + return PM3_EFILE; + } + fnlen = snprintf(filename, sizeof(filename), MFU_DEFAULT_KEY_DIC); + PrintAndLogEx(INFO, "No dictionary given, using " _YELLOW_("%s"), filename); + } + + uint64_t tagtype = GetHF14AMfU_Type(); + if (tagtype == MFU_TT_UL_ERROR) { + PrintAndLogEx(WARNING, "No Ultralight tag found"); + return PM3_ESOFT; + } + ul_print_type(tagtype, 0); + + uint8_t key_index; + if ((tagtype & MFU_TT_UL_AES) == MFU_TT_UL_AES) { + key_index = (key_idx == -1) ? 0 : (uint8_t)key_idx; + } else if ((tagtype & MFU_TT_UL_C) == MFU_TT_UL_C) { + if (key_idx != -1) { + PrintAndLogEx(ERR, "Ultralight C holds a single key, " _YELLOW_("--idx") " is for Ultralight AES"); + return PM3_EINVARG; + } + key_index = MIFAREULC_KEY_INDEX; + } else { + PrintAndLogEx(ERR, "Tag is neither Ultralight C nor Ultralight AES"); + PrintAndLogEx(HINT, "Hint: Try `" _YELLOW_("hf mfu info") "` to see what this tag is"); + return PM3_EINVARG; + } + + return mfu_auth_chk(key_index, filename, fnlen, segment, retries, ref_key, xor_ref_key, check_answer, use_fastread0); +} //------------------------------------------------------------------------------- // Ultralight AES Methods //------------------------------------------------------------------------------- @@ -4928,134 +5035,6 @@ static int CmdHF14AMfUAESAuth(const char *Cmd) { -static int CmdHF14AMfUAESAuthChk(const char *Cmd) { - CLIParserContext *ctx; - CLIParserInit(&ctx, "hf mfu aeschk", - "It checks MIFARE Ultralight AES tags keys against a dictionary file with keys\n" - " Key index 0... DataProtKey (default)\n" - " Key index 1... UIDRetrKey\n" - " Key index 2... OriginalityKey\n", - "hf mfu aeschk -f mfulaes_default_keys.dic"); - - void *argtable[] = { - arg_param_begin, - arg_str0("f", "file", "", "filename of dictionary"), - arg_int0("i", "idx", "<0..2>", "Key index (def: 0)"), - arg_int0("s", "segment", "<0..3>", "Segment index (full key if not specified)"), - arg_int0("r", "retries", "<0..255>", "Number of retries (def: 0)"), - arg_str0("k", "key", "", "Starting key, 16 hex bytes (def: zero key), for segment check"), - arg_lit0("x", "xor", "XOR starting key with segment candidates (def: override)"), - arg_lit0("n", "nocheck", "Skip checking tag answer correctness"), - arg_lit0("0", "read0", "Use fast READ0 (skip anticol)"), - arg_param_end - }; - CLIExecWithReturn(ctx, Cmd, argtable, true); - - int fnlen = 0; - char filename[FILE_PATH_SIZE] = {0}; - CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen); - int key_index = arg_get_int_def(ctx, 2, 0); - int segment = arg_get_int_def(ctx, 3, -1); // -1 means full key - int retries = arg_get_int_def(ctx, 4, 0); - int ref_keylen = 0; - uint8_t ref_key[16] = {0}; - CLIGetHexWithReturn(ctx, 5, ref_key, &ref_keylen); - bool xor_ref_key = arg_get_lit(ctx, 6); - bool check_answer = !arg_get_lit(ctx, 7); - bool use_fastread0 = arg_get_lit(ctx, 8); - CLIParserFree(ctx); - - if (fnlen == 0) { - PrintAndLogEx(ERR, "No dictionary file specified"); - return PM3_EFILE; - } - if (key_index < 0 || key_index > 2) { - PrintAndLogEx(ERR, "Invalid key index (must be 0..2)"); - return PM3_EINVARG; - } - if (segment < -1 || segment > 3) { - PrintAndLogEx(ERR, "Invalid segment (must be 0..3)"); - return PM3_EINVARG; - } - if (retries < 0 || retries > 255) { - PrintAndLogEx(ERR, "Invalid retries (must be 0..255)"); - return PM3_EINVARG; - } - if (ref_keylen && ref_keylen != MIFAREU3P_KEY_SIZE) { - PrintAndLogEx(WARNING, "Key must be %i hex bytes. Got %d", MIFAREU3P_KEY_SIZE, ref_keylen); - return PM3_EINVARG; - } - if (ref_keylen == 0) { - ref_keylen = MIFAREU3P_KEY_SIZE; - } - - uint8_t *keyBlock = NULL; - uint32_t keycnt = 0; - int keysize = segment != -1 ? MIFAREU3P_KEY_SIZE / 4 : MIFAREU3P_KEY_SIZE; - int ret = mfu_3pass_load_keys(&keyBlock, &keycnt, filename, fnlen, keysize); - if (ret != PM3_SUCCESS) { - return ret; - } - if (keycnt == 0) { - PrintAndLogEx(ERR, "Dictionary contains no keys"); - free(keyBlock); - return PM3_ESOFT; - } - - // cap by what fits in one frame, then by what the nkeys field can announce - uint32_t max_chunk = (g_conn.max_cmd_data_size - MIFAREU3P_CHKKEY_HEADER) / keysize; - if (max_chunk > MIFAREU3P_CHKKEY_MAX_KEYS) { - max_chunk = MIFAREU3P_CHKKEY_MAX_KEYS; - } - uint32_t chunksize = (keycnt > max_chunk) ? max_chunk : keycnt; - bool firstChunk = true, lastChunk = false; - - int i = 0; - - uint32_t auths = 0; - uint32_t ms = 0; - - // main keychunk loop - for (int r = 0; r < retries + 1; r++) { - for (i = 0; i < keycnt; i += chunksize) { - if (kbd_enter_pressed()) { - clearCommandBuffer(); - SendCommandNG(CMD_BREAK_LOOP, NULL, 0); - SendCommandNG(CMD_FPGA_MAJOR_MODE_OFF, NULL, 0); // field is still ON if not on last chunk - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(WARNING, "\naborted via keyboard!"); - goto out; - } - - uint32_t nkeys = ((keycnt - i) > chunksize) ? chunksize : keycnt - i; - - // last chunk? - if (nkeys == keycnt - i) { - lastChunk = true; - } - - int res = mfu_3pass_check_keys(key_index, firstChunk, lastChunk, nkeys, segment, ref_key, xor_ref_key, keyBlock + (i * keysize), false, true, &auths, &ms, check_answer, use_fastread0); - if (firstChunk) - firstChunk = false; - - // all keys, aborted - if (res == PM3_SUCCESS || res == 2) { - PrintAndLogEx(NORMAL, ""); - goto out; - } - PrintAndLogEx(INPLACE, "Testing %5i/%5i ( " _YELLOW_("%02.1f %%") " )", i, keycnt, (float)i * 100 / keycnt); - } // end chunks of keys - } - PrintAndLogEx(NORMAL, ""); -out: - PrintAndLogEx(INFO, "Time spent " _YELLOW_("%.1fs"), (float)(ms / 1000.0)); - PrintAndLogEx(INFO, "Authentication attempts: %u", auths); - PrintAndLogEx(INFO, "Speed: %.1f auths/s", (float)(auths * 1000.0 / ms)); - - free(keyBlock); - PrintAndLogEx(NORMAL, ""); - return PM3_SUCCESS; -} static int CmdHF14AMfUAESGetUID(const char *Cmd) { CLIParserContext *ctx; @@ -6873,7 +6852,7 @@ static int CmdHF14AMfuEv1CounterTearoff(const char *Cmd) { post_tear_check = (post_tear == 0xBD); a = (pre[0] | pre[1] << 8 | pre[2] << 16); b = (post[0] | post[1] << 8 | post[2] << 16); - PrintAndLogEx(INPLACE, " Delay: " _YELLOW_("%d") " Tear: %s Counter: " _YELLOW_("%s") "" + PrintAndLogEx(INPLACE, "Delay: " _YELLOW_("%d") " Tear: %s Counter: " _YELLOW_("%s") "" , delay_bd , sprint_hex_inrow(tear, sizeof(tear)) , poststr @@ -6926,7 +6905,9 @@ static int CmdHF14AMfuEv1CounterTearoff(const char *Cmd) { } } - } else if (fixed != -1) delay_bd = fixed; + } else if (fixed != -1) { + delay_bd = fixed; + } if (ul_select(&card) == false) { PrintAndLogEx(NORMAL, ""); @@ -6984,7 +6965,7 @@ static int CmdHF14AMfuEv1CounterTearoff(const char *Cmd) { post_tear_check = (post_tear == 0xBD); - PrintAndLogEx(INPLACE, " Delay: " _YELLOW_("%d") " Tear: %s Counter: " _YELLOW_("%s") "" + PrintAndLogEx(INPLACE, "Delay: " _YELLOW_("%d") " Tear: %s Counter: " _YELLOW_("%s") "" , delay_00 , sprint_hex_inrow(tear, sizeof(tear)) , poststr @@ -8353,6 +8334,71 @@ static int CmdHF14AMfuESave(const char *Cmd) { return res; } +// Derive the tag type from the dump header, version bytes and page count. +// Uses the same version byte signatures as ul_select_card() does on a live tag. +static uint64_t mfu_dump_get_tagtype(const mfu_dump_t *card) { + + if (memcmp(card->version, "\x00\x04\x03\x01\x04\x00\x0F\x03", 8) == 0 || + memcmp(card->version, "\x00\x04\x03\x02\x04\x00\x0F\x03", 8) == 0 || + memcmp(card->version, "\x00\x04\x03\x03\x04\x00\x0F\x03", 8) == 0) { + return MFU_TT_UL_AES; + } + + // UL-C has no GET_VERSION, the dump holds zeroes there + bool version_zero = true; + for (uint8_t i = 0; i < ARRAYLEN(card->version); i++) { + if (card->version[i] != 0x00) { + version_zero = false; + break; + } + } + + if (version_zero && card->pages == MAX_ULC_BLOCKS) { + return MFU_TT_UL_C; + } + + return MFU_TT_UNKNOWN; +} + +// `hf mfu dump` appends the authentication key to the dump when one was given. +// UL-C: pages 0x2C..0x2F, stored as SwapEndian64(key, 16, 8) +// UL-AES: pages 0x30..0x33, stored as SwapEndian64(key, 16, 16) +static void mfu_print_dump_keys(mfu_dump_t *card, uint16_t block_cnt) { + + uint64_t tagtype = mfu_dump_get_tagtype(card); + + uint8_t page; + if ((tagtype == MFU_TT_UL_C) && (block_cnt > (MFU_ULC_KEY0_PAGE + 3))) { + page = MFU_ULC_KEY0_PAGE; + } else if ((tagtype == MFU_TT_UL_AES) && (block_cnt > (MFU_AES_KEY0_PAGE + 3))) { + page = MFU_AES_KEY0_PAGE; + } else { + return; + } + + uint8_t *key = card->data + (page * MFU_BLOCK_SIZE); + + PrintAndLogEx(NORMAL, ""); + if (tagtype == MFU_TT_UL_C) { + PrintAndLogEx(INFO, "--- " _CYAN_("UL-C 3DES key") " -------------------------"); + } else { + PrintAndLogEx(INFO, "--- " _CYAN_("UL-AES key") " ----------------------------"); + } + + uint8_t zeros[MIFAREU3P_KEY_SIZE] = {0x00}; + if (memcmp(key, zeros, sizeof(zeros)) == 0) { + PrintAndLogEx(INFO, " " _RED_("n/a") " - page %u..%u is all zero", page, page + 3); + PrintAndLogEx(HINT, "Hint: Try `" _YELLOW_("hf mfu dump -k ") "` to store the key in the dump"); + return; + } + + if (tagtype == MFU_TT_UL_C) { + ulc_print_3deskey(key); + } else { + ulaes_print_key(key); + } +} + static int CmdHF14AMfuView(const char *Cmd) { CLIParserContext *ctx; @@ -8406,6 +8452,10 @@ static int CmdHF14AMfuView(const char *Cmd) { mfu_dump_t *p = (mfu_dump_t *)dump; mfu_print_dump(p, block_cnt, 0, dense_output); + if (verbose) { + mfu_print_dump_keys(p, block_cnt); + } + // we need to skip prefix if (ndef_detect_message(p->data, block_cnt * MFU_BLOCK_SIZE)) { PrintAndLogEx(HINT, "Hint: Try `" _YELLOW_("hf mfu ndefread")"`"); @@ -9059,7 +9109,7 @@ static int CmdHF14AMfUeSetBlk(const char *Cmd) { // MFU emulator page data starts after the 56-byte mfu_dump_t prefix, so shift the // page index by MFU_DUMP_PREFIX_LENGTH/MFU_BLOCK_SIZE (=14), width = MFU_BLOCK_SIZE (4). - res = mf_eml_set_mem_xt(data, blk + (MFU_DUMP_PREFIX_LENGTH / MFU_BLOCK_SIZE), count, MFU_BLOCK_SIZE); + res = mf_eml_set_mem_xt(data, blk + (MFU_DUMP_PREFIX_LENGTH / MFU_BLOCK_SIZE), count, MFU_BLOCK_SIZE, 0); if (res != PM3_SUCCESS) { PrintAndLogEx(FAILED, "Failed to set emulator memory"); return res; @@ -9078,11 +9128,10 @@ static command_t CommandTable[] = { {"otptear", CmdHF14AMfuOtpTearoff, IfPm3Iso14443a, "Tear-off test on OTP bits"}, {"countertear", CmdHF14AMfuEv1CounterTearoff, IfPm3Iso14443a, "Tear-off test on Ev1/NTAG Counter bits"}, {"-----------", CmdHelp, IfPm3Iso14443a, "----------------------- " _CYAN_("operations") " -----------------------"}, + {"chk", CmdHF14AMfUAuthChk, IfPm3Iso14443a, "Ultralight C/AES - Authentication dictionary check"}, {"cauth", CmdHF14AMfUCAuth, IfPm3Iso14443a, "Ultralight-C - Authentication"}, - {"cchk", CmdHF14AMfUCAuthChk, IfPm3Iso14443a, "Ultralight-C - Authentication dictionary check"}, {"desbrute", CmdHF14AMfUCDesBrute, AlwaysAvailable, "Ultralight-C - 3DES key segment brute force"}, {"aesauth", CmdHF14AMfUAESAuth, IfPm3Iso14443a, "Ultralight-AES - Authentication"}, - {"aeschk", CmdHF14AMfUAESAuthChk, IfPm3Iso14443a, "Ultralight-AES - Authentication dictionary check"}, {"aesgetuid", CmdHF14AMfUAESGetUID, IfPm3Iso14443a, "Ultralight-AES - Get UID when RID in use"}, {"setkey", CmdHF14AMfUSetKey, IfPm3Iso14443a, "Ultralight C/AES - Set 3DES/AES keys"}, {"dump", CmdHF14AMfUDump, IfPm3Iso14443a, "Dump MIFARE Ultralight family tag to binary file"}, diff --git a/client/src/cmdhfntag424.c b/client/src/cmdhfntag424.c index 92639f864..a670c6742 100644 --- a/client/src/cmdhfntag424.c +++ b/client/src/cmdhfntag424.c @@ -48,6 +48,8 @@ #define NTAG424_CMD_MORE_DATA 0xAF #define NTAG424_CMD_GET_VERSION 0x60 #define NTAG424_CMD_GET_SIGNATURE 0x3C +#define NTAG424_CMD_GET_TT_STATUS 0xF7 +#define NTAG424_CMD_SET_CONFIGURATION 0x5C // // Original from https://github.com/rfidhacking/node-sdm/ @@ -148,6 +150,11 @@ typedef struct { ntag424_production_information_t production; } ntag424_full_version_information_t; +typedef struct { + uint8_t perm; + uint8_t curr; +} ntag424_tag_tamper_status_t; + static void ntag424_print_version_information(ntag424_version_information_t *version, bool is_hw) { PrintAndLogEx(INFO, " vendor id: " _GREEN_("%02X"), version->vendor_id); @@ -856,6 +863,39 @@ static int ntag424_read_data(uint8_t fileno, uint16_t offset, uint16_t num_bytes return PM3_SUCCESS; } +static const char *tt_status_str(uint8_t status) { + switch (status) { + case 'C': + return "Close"; + case 'O': + return "Open"; + case 'I': + return "Invalid"; + default: + return "Unknown"; + } +} + +static int ntag424_get_tt_status(ntag424_tag_tamper_status_t *status, ntag424_communication_mode_t comm_mode, ntag424_session_keys_t *session_keys) { + APDU_t apdu = { + .cla = 0x90, + .ins = NTAG424_CMD_GET_TT_STATUS, + .lc = 0 + }; + + // align_up(sizeof(ntag424_tag_tamper_status_t) + 1, 16) + sizeof(mac) + sizeof(status_word) + int response_length = 16 + 8 + 2; + uint8_t response[response_length]; + + int res = ntag424_exchange_apdu(apdu, 0, response, &response_length, comm_mode, session_keys, 0x91, 0x00); + if (res != PM3_SUCCESS) { + return res; + } + + memcpy(status, response, sizeof(*status)); + return PM3_SUCCESS; +} + static int ntag424_get_version(ntag424_full_version_information_t *version) { APDU_t apdu = { .cla = 0x90, @@ -913,6 +953,25 @@ static int ntag424_get_signature(uint8_t *signature_out) { return PM3_SUCCESS; } +static int ntag424_set_configuration(uint8_t option, const uint8_t *data, int data_len, ntag424_session_keys_t *session_keys) { + uint8_t cmd_buffer[64]; + cmd_buffer[0] = option; + memcpy(&cmd_buffer[1], data, data_len); + + APDU_t apdu = { + .cla = 0x90, + .ins = NTAG424_CMD_SET_CONFIGURATION, + .lc = 1 + data_len, + .data = cmd_buffer + }; + + // No response data, only MAC and status word + int response_length = 8 + 2; + uint8_t response[response_length]; + + return ntag424_exchange_apdu(apdu, 1, response, &response_length, COMM_FULL, session_keys, 0x91, 0x00); +} + static int ntag424_change_key(uint8_t keyno, const uint8_t *new_key, const uint8_t *old_key, uint8_t version, ntag424_session_keys_t *session_keys) { // -------- Calculate xor and crc uint8_t key[16] = {0}; @@ -1513,7 +1572,13 @@ static int CmdHF_ntag424_changekey(const char *Cmd) { }; CLIExecWithReturn(ctx, Cmd, argtable, false); - uint8_t version = arg_get_int(ctx, 6); + int kv = arg_get_int(ctx, 5); + if (kv < 0 || kv > 0xFF) { + PrintAndLogEx(ERR, "Key version must be 0..255, got ( %d )", kv); + CLIParserFree(ctx); + return PM3_EINVARG; + } + uint8_t version = (uint8_t)kv; int keyno = arg_get_int(ctx, 1); uint8_t oldkey[16] = {0}; @@ -1573,6 +1638,136 @@ static int CmdHF_ntag424_changekey(const char *Cmd) { return res; } +static int CmdHF_ntag424_getttstatus(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hf ntag424 gettt", + "Read and print Tag Tamper status. Will authenticate if key information is provided.", + "hf ntag424 gettt --keyno 0 -k 00000000000000000000000000000000"); + + void *argtable[] = { + arg_param_begin, + arg_int0(NULL, "keyno", "", "Key number"), + arg_str0("k", "key", "", "Key for authentication (HEX 16 bytes)"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + + int keyno = 0; + uint8_t key[16] = {0}; + bool auth = arg_get_str(ctx, 2)->count > 0; + if (auth && ntag424_cli_get_auth_information(ctx, 1, 2, &keyno, key) != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Could not get key settings"); + CLIParserFree(ctx); + return PM3_EINVARG; + } + + CLIParserFree(ctx); + + if (SelectCard14443A_4(false, true, NULL) != PM3_SUCCESS) { + DropField(); + PrintAndLogEx(ERR, "Failed to select card"); + return PM3_ERFTRANS; + } + + if (ntag424_select_application() != PM3_SUCCESS) { + DropField(); + return PM3_ESOFT; + } + + int res = PM3_SUCCESS; + ntag424_session_keys_t session_keys = {0}; + if (auth) { + res = ntag424_authenticate_ev2_first(keyno, key, &session_keys); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Auth key %d ( " _RED_("fail") " )", keyno); + DropField(); + return res; + } else { + PrintAndLogEx(SUCCESS, "Auth key %d ( " _GREEN_("ok") " )", keyno); + } + } + + ntag424_tag_tamper_status_t tt_status = {0}; + res = ntag424_get_tt_status(&tt_status, auth ? COMM_FULL : COMM_PLAIN, &session_keys); + DropField(); + if (res == PM3_SUCCESS) { + PrintAndLogEx(SUCCESS, "--- " _CYAN_("Tag Tamper status:")); + PrintAndLogEx(SUCCESS, " TTPermStatus: " _GREEN_("%02X (%s)"), tt_status.perm, tt_status_str(tt_status.perm)); + PrintAndLogEx(SUCCESS, " TTCurrStatus: " _GREEN_("%02X (%s)"), tt_status.curr, tt_status_str(tt_status.curr)); + } + return res; +} + +static int CmdHF_ntag424_setconfig(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hf ntag424 setconfig", + "Change a PICC configuration option.\n" + "Several options are one-way, see the datasheet before using this.", + "hf ntag424 setconfig -k 00000000000000000000000000000000 --option 07 -d 0100"); + + void *argtable[] = { + arg_param_begin, + arg_str1("k", "key0", "", "Authentication key (must be key 0, HEX 16 bytes)"), + arg_str1(NULL, "option", "", "Configuration option (HEX 1 byte)"), + arg_strx1("d", "data", "", "Option data (HEX, 1..47 bytes)"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, false); + + uint8_t key[16] = {0}; + if (ntag424_cli_get_auth_information(ctx, 0, 1, NULL, key) != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Could not get key settings"); + CLIParserFree(ctx); + return PM3_EINVARG; + } + + uint8_t option[1] = {0}; + int optionlen = sizeof(option); + if (CLIParamHexToBuf(arg_get_str(ctx, 2), option, sizeof(option), &optionlen) || (optionlen != sizeof(option))) { + PrintAndLogEx(ERR, "Option must be 1 byte"); + CLIParserFree(ctx); + return PM3_EINVARG; + } + + uint8_t data[47] = {0}; + int datalen = sizeof(data); + if (CLIParamHexToBuf(arg_get_str(ctx, 3), data, sizeof(data), &datalen) || (datalen < 1)) { + PrintAndLogEx(ERR, "Data must be 1..%zu bytes", sizeof(data)); + CLIParserFree(ctx); + return PM3_EINVARG; + } + CLIParserFree(ctx); + + if (SelectCard14443A_4(false, true, NULL) != PM3_SUCCESS) { + DropField(); + PrintAndLogEx(ERR, "Failed to select card"); + return PM3_ERFTRANS; + } + + if (ntag424_select_application() != PM3_SUCCESS) { + DropField(); + return PM3_ESOFT; + } + + ntag424_session_keys_t session = {0}; + int res = ntag424_authenticate_ev2_first(0, key, &session); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Auth key 0 ( " _RED_("fail") " )"); + DropField(); + return res; + } + PrintAndLogEx(SUCCESS, "Auth key 0 ( " _GREEN_("ok") " )"); + + res = ntag424_set_configuration(option[0], data, datalen, &session); + DropField(); + if (res == PM3_SUCCESS) { + PrintAndLogEx(SUCCESS, "Set configuration option %02X ( " _GREEN_("ok") " )", option[0]); + } else { + PrintAndLogEx(ERR, "Set configuration option %02X ( " _RED_("fail") " )", option[0]); + } + return res; +} + static command_t CommandTable[] = { {"help", CmdHelp, AlwaysAvailable, "This help"}, {"-----------", CmdHelp, IfPm3Iso14443a, "----------------------- " _CYAN_("operations") " -----------------------"}, @@ -1584,6 +1779,8 @@ static command_t CommandTable[] = { {"getfs", CmdHF_ntag424_getfilesettings, IfPm3Iso14443a, "Get file settings"}, {"changefs", CmdHF_ntag424_changefilesettings, IfPm3Iso14443a, "Change file settings"}, {"changekey", CmdHF_ntag424_changekey, IfPm3Iso14443a, "Change key"}, + {"gettt", CmdHF_ntag424_getttstatus, IfPm3Iso14443a, "Get Tag Tamper status"}, + {"setconfig", CmdHF_ntag424_setconfig, IfPm3Iso14443a, "Set PICC configuration option"}, {NULL, NULL, NULL, NULL} }; diff --git a/client/src/cmdhfst25ta.c b/client/src/cmdhfst25ta.c index a34d8d086..0f299d5d3 100644 --- a/client/src/cmdhfst25ta.c +++ b/client/src/cmdhfst25ta.c @@ -462,7 +462,7 @@ static int st25ta_upload_sim_data(const uint8_t *uid, uint8_t uid_len, const uin for (uint16_t offset = 0; offset < data_len;) { uint8_t chunk_len = MIN(data_len - offset, UINT8_MAX); - int res = mf_eml_set_mem_xt(data + offset, offset, chunk_len, 1); + int res = mf_eml_set_mem_xt(data + offset, offset, chunk_len, 1, 0); if (res != PM3_SUCCESS) { return res; } diff --git a/client/src/cmdhftexkom.c b/client/src/cmdhftexkom.c index 8a6cee6f2..6efaeebc6 100644 --- a/client/src/cmdhftexkom.c +++ b/client/src/cmdhftexkom.c @@ -30,6 +30,8 @@ #include "graph.h" #define TEXKOM_NOISE_THRESHOLD (10) +#define TEXKOM_BITSTRING_SIZE 256 +#define TEXKOM_MAX_INTERVALS (TEXKOM_BITSTRING_SIZE - 1) static inline uint32_t GetGraphBuffer(uint32_t indx) { if (g_GraphBuffer[indx] < -128) @@ -461,9 +463,9 @@ static int texkom_get_type(texkom_card_select_t *card, bool verbose) { } // decode samples to 8 bytes - char bitstring[256] = {0}; + char bitstring[TEXKOM_BITSTRING_SIZE] = {0}; char cbitstring[128] = {0}; - char genbitstring[256] = {0}; + char genbitstring[TEXKOM_BITSTRING_SIZE] = {0}; int found = TexkomModError; uint32_t sindx = 0; @@ -493,7 +495,7 @@ static int texkom_get_type(texkom_card_select_t *card, bool verbose) { noiselvl = TEXKOM_NOISE_THRESHOLD; } - uint32_t implengths[256] = { 0 }; + uint32_t implengths[TEXKOM_BITSTRING_SIZE] = { 0 }; uint32_t implengthslen = 0; uint32_t impulseindx = 0; uint32_t impulsecnt = 0; @@ -502,7 +504,7 @@ static int texkom_get_type(texkom_card_select_t *card, bool verbose) { impulsecnt++; if (impulseindx != 0) { - if (implengthslen < 256) { + if (implengthslen < TEXKOM_MAX_INTERVALS) { implengths[implengthslen++] = sindx + i - impulseindx; } } @@ -678,9 +680,9 @@ static int CmdHFTexkomReader(const char *Cmd) { } } - char bitstring[256] = {0}; + char bitstring[TEXKOM_BITSTRING_SIZE] = {0}; char cbitstring[128] = {0}; - char genbitstring[256] = {0}; + char genbitstring[TEXKOM_BITSTRING_SIZE] = {0}; int codefound = TexkomModError; uint32_t sindx = 0; while (sindx < samplesCount - 5) { @@ -707,7 +709,7 @@ static int CmdHFTexkomReader(const char *Cmd) { //PrintAndLogEx(WARNING, "--- indx: %d, len: %d, max: %d, noise: %d", sindx, slen, maxlvl, noiselvl); - uint32_t implengths[256] = { 0 }; + uint32_t implengths[TEXKOM_BITSTRING_SIZE] = { 0 }; uint32_t implengthslen = 0; uint32_t impulseindx = 0; uint32_t impulsecnt = 0; @@ -716,7 +718,7 @@ static int CmdHFTexkomReader(const char *Cmd) { impulsecnt++; if (impulseindx != 0) { - if (implengthslen < 256) + if (implengthslen < TEXKOM_MAX_INTERVALS) implengths[implengthslen++] = sindx + i - impulseindx; } impulseindx = sindx + i; diff --git a/client/src/cmdhfthinfilm.c b/client/src/cmdhfthinfilm.c index fa7921dc6..54e4699a2 100644 --- a/client/src/cmdhfthinfilm.c +++ b/client/src/cmdhfthinfilm.c @@ -35,10 +35,9 @@ static int CmdHelp(const char *Cmd); // https://github.com/nfc-tools/libnfc/blob/master/utils/nfc-barcode.c static int print_barcode(uint8_t *barcode, const size_t barcode_len, bool verbose) { - PrintAndLogEx(NORMAL, ""); // remove start bit uint8_t mb = barcode[0] & ~0x80; - PrintAndLogEx(SUCCESS, " Manufacturer : "_YELLOW_("%s") "[0x%02X]", getTagInfo(mb), mb); + PrintAndLogEx(SUCCESS, " Manufacturer : "_YELLOW_("%s")" ( %02X )", getTagInfo(mb), mb); if (verbose) { PrintAndLogEx(SUCCESS, " Data format : "_YELLOW_("%02X"), barcode[1]); @@ -52,9 +51,10 @@ static int print_barcode(uint8_t *barcode, const size_t barcode_len, bool verbos PrintAndLogEx(SUCCESS, " Checksum : "_YELLOW_("too few data for checksum")" - " _RED_("fail")); } PrintAndLogEx(SUCCESS, " Data len (bits) : "_YELLOW_("%zu")" ( %s )", barcode_len * 8, (barcode_len == 16 || barcode_len == 32) ? _GREEN_("ok") : _YELLOW_("warning")); - PrintAndLogEx(SUCCESS, " Raw data : "_YELLOW_("%s"), sprint_hex(barcode, barcode_len)); - if (barcode_len < 4) // too few to go to next decoding stages + PrintAndLogEx(SUCCESS, " Raw data : "_YELLOW_("%s"), sprint_hex_inrow(barcode, barcode_len)); + if (barcode_len < 4) { // too few to go to next decoding stages return PM3_ESOFT; + } } char s[45]; @@ -205,6 +205,59 @@ int CmdHfThinFilmSim(const char *Cmd) { return PM3_SUCCESS; } +static int CmdHfThinFilmSniff(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hf thinfilm sniff", + "Sniff the frames a Thinfilm / NFC Barcode tag beams at a reader.\n" + "The tag talks first and the reader sends nothing, so only the tag side\n" + "is decoded. Use `hf thinfilm list` to view collected data.", + "hf thinfilm sniff\n" + "hf thinfilm sniff -i" + ); + + void *argtable[] = { + arg_param_begin, + arg_lit0("i", "interactive", "Console will not be returned until sniff finishes or is aborted"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + + bool interactive = arg_get_lit(ctx, 1); + CLIParserFree(ctx); + + clearCommandBuffer(); + SendCommandNG(CMD_HF_THINFILM_SNIFF, NULL, 0); + + if (interactive == false) { + PrintAndLogEx(INFO, "Press " _GREEN_("pm3 button") " to abort sniffing"); + return PM3_SUCCESS; + } + + PrintAndLogEx(INFO, "Press " _GREEN_("pm3 button") " or " _GREEN_("") " to abort sniffing"); + + PacketResponseNG resp; + bool keypress = kbd_enter_pressed(); + + while (keypress == false) { + keypress = kbd_enter_pressed(); + + if (WaitForResponseTimeout(CMD_HF_THINFILM_SNIFF, &resp, 500)) { + break; + } + } + + if (keypress) { + // inform device to break the sniff loop since client has exited + SendCommandNG(CMD_BREAK_LOOP, NULL, 0); + WaitForResponse(CMD_HF_THINFILM_SNIFF, &resp); + } + + PrintAndLogEx(INFO, "Done!"); + PrintAndLogEx(HINT, "Hint: Try `" _YELLOW_("hf thinfilm list") "` to view captured tracelog"); + PrintAndLogEx(HINT, "Hint: Try `" _YELLOW_("trace save -h") "` to save tracelog for later analysing"); + return PM3_SUCCESS; +} + static int CmdHfThinFilmList(const char *Cmd) { return CmdTraceListAlias(Cmd, "hf thinfilm", "thinfilm"); } @@ -212,8 +265,9 @@ static int CmdHfThinFilmList(const char *Cmd) { static command_t CommandTable[] = { {"help", CmdHelp, AlwaysAvailable, "This help"}, {"info", CmdHfThinFilmInfo, IfPm3NfcBarcode, "Tag information"}, - {"list", CmdHfThinFilmList, AlwaysAvailable, "List NFC Barcode / Thinfilm history - not correct"}, + {"list", CmdHfThinFilmList, AlwaysAvailable, "List NFC Barcode / Thinfilm history"}, {"sim", CmdHfThinFilmSim, IfPm3NfcBarcode, "Fake Thinfilm tag"}, + {"sniff", CmdHfThinFilmSniff, IfPm3NfcBarcode, "Sniff Thinfilm tag communication"}, {NULL, NULL, NULL, NULL} }; diff --git a/client/src/cmdhw.c b/client/src/cmdhw.c index 7d33f7245..386f3f556 100644 --- a/client/src/cmdhw.c +++ b/client/src/cmdhw.c @@ -36,6 +36,7 @@ #include "ui.h" #include "fpga.h" #include "cmdhw.h" +#include "cmdbwm.h" #include "cmdfpga.h" #include "cmddata.h" #include "commonutil.h" @@ -1507,357 +1508,6 @@ static int CmdTearoff(const char *Cmd) { return handle_tearoff(¶ms, !silent); } -static int CmdBwmAutoOff(const char *Cmd) { - // Positional sub-action (no dashes): hw bwm autooff on | off - char verb[16] = {0}; - sscanf(Cmd, "%15s", verb); - bool on = (strcmp(verb, "on") == 0); - bool off = (strcmp(verb, "off") == 0); - - if (!on && !off) { - // Not a recognised sub-action: render help (also serves -h / empty), - // or error on a stray token, then stop. - CLIParserContext *ctx; - CLIParserInit(&ctx, "hw bwm autooff", - "Toggle automatic power-off when the PM5 is unplugged from USB (BWM only).\n" - "Default is " _GREEN_("on") ". When on, the board powers itself down ~10s after\n" - "USB is removed, so a BWM-equipped PM5 doesn't silently drain the battery.\n" - "Button power-on is unaffected. Disable for standalone/BLE use on battery.\n" - _YELLOW_("Runtime only:") " resets to on at each boot.", - "hw bwm autooff off --> disable auto power-off\n" - "hw bwm autooff on --> re-enable auto power-off"); - void *argtable[] = { - arg_param_begin, - arg_param_end - }; - CLIExecWithReturn(ctx, Cmd, argtable, true); - CLIParserFree(ctx); - PrintAndLogEx(WARNING, "specify " _YELLOW_("on") " or " _YELLOW_("off")); - return PM3_EINVARG; - } - - uint8_t payload = off ? 0 : 1; // on -> 1 (enable), off -> 0 (disable) - - clearCommandBuffer(); - SendCommandNG(CMD_PM5_BWM_AUTOOFF, &payload, sizeof(payload)); - PacketResponseNG resp; - if (WaitForResponseTimeout(CMD_PM5_BWM_AUTOOFF, &resp, 2500) == false) { - PrintAndLogEx(WARNING, "command timeout (is this a PM5?)"); - return PM3_ETIMEOUT; - } - if (resp.status == PM3_ENOTIMPL) { - PrintAndLogEx(WARNING, "firmware built without auto power-off support"); - return resp.status; - } - if (resp.status != PM3_SUCCESS) { - PrintAndLogEx(FAILED, "failed to set auto power-off"); - return resp.status; - } - PrintAndLogEx(SUCCESS, "Auto power-off %s.", payload ? _GREEN_("enabled") : _YELLOW_("disabled")); - return PM3_SUCCESS; -} - -static int CmdBWMWifi(const char *Cmd) { - // Sub-actions that carry no other arguments are positional keywords now: - // hw bwm wifi status (was --status) - // hw bwm wifi stop (was --stop) - // Bringing WiFi up still takes value flags, so it stays the default - // (no-keyword) form: hw bwm wifi --ssid --pwd [--port ] - char verb[16] = {0}; - sscanf(Cmd, "%15s", verb); - - if (strcmp(verb, "status") == 0) { - uint8_t q[1] = { BWM_WIFI_ACTION_STATUS }; - clearCommandBuffer(); - SendCommandNG(CMD_PM5_BWM_WIFI, q, sizeof(q)); - PacketResponseNG r; - if (WaitForResponseTimeout(CMD_PM5_BWM_WIFI, &r, 5000) == false) { - PrintAndLogEx(WARNING, "command timeout (is this a PM5 with a BWM fitted?)"); - return PM3_ETIMEOUT; - } - if (r.status != PM3_SUCCESS) { - PrintAndLogEx(FAILED, "could not query BWM WiFi status (BWM present?)"); - return r.status; - } - uint8_t state = (r.length >= 1) ? r.data.asBytes[0] : 0xFF; - uint32_t ip = 0; - if (r.length >= 5) { - ip = r.data.asBytes[1] | (r.data.asBytes[2] << 8) | (r.data.asBytes[3] << 16) | ((uint32_t)r.data.asBytes[4] << 24); - } - switch (state) { - case 0xFF: - PrintAndLogEx(INFO, "BWM WiFi disabled (BLE-only). Bring it up with " _YELLOW_("hw bwm wifi --ssid --pwd ")); - break; - case 2: // connected - if (ip) { - PrintAndLogEx(SUCCESS, "BWM WiFi connected, IP " _YELLOW_("%u.%u.%u.%u"), - ip & 0xFF, (ip >> 8) & 0xFF, (ip >> 16) & 0xFF, (ip >> 24) & 0xFF); - PrintAndLogEx(HINT, "Connect with: " _YELLOW_("pm3 -p tcp:%u.%u.%u.%u:"), - ip & 0xFF, (ip >> 8) & 0xFF, (ip >> 16) & 0xFF, (ip >> 24) & 0xFF); - } else { - PrintAndLogEx(INFO, "BWM WiFi associated, waiting for a DHCP lease..."); - } - break; - case 1: // connecting - PrintAndLogEx(INFO, "BWM WiFi connecting..."); - break; - case 3: // reconnect wait - PrintAndLogEx(INFO, "BWM WiFi reconnecting..."); - break; - case 4: // task stopped - PrintAndLogEx(INFO, "BWM WiFi connect task stopped"); - break; - case 0: // disconnected - default: - PrintAndLogEx(INFO, "BWM WiFi configured but not connected"); - break; - } - return PM3_SUCCESS; - } - - if (strcmp(verb, "stop") == 0) { - uint8_t off[1] = { BWM_WIFI_ACTION_STOP }; - clearCommandBuffer(); - SendCommandNG(CMD_PM5_BWM_WIFI, off, sizeof(off)); - PacketResponseNG r; - if (WaitForResponseTimeout(CMD_PM5_BWM_WIFI, &r, 5000) == false) { - PrintAndLogEx(WARNING, "command timeout (is this a PM5 with a BWM fitted?)"); - return PM3_ETIMEOUT; - } - if (r.status != PM3_SUCCESS) { - PrintAndLogEx(FAILED, "failed to disable BWM WiFi"); - return r.status; - } - PrintAndLogEx(SUCCESS, "BWM WiFi disabled (back to BLE-only)"); - return PM3_SUCCESS; - } - - CLIParserContext *ctx; - CLIParserInit(&ctx, "hw bwm wifi", - "Bring up the BWM in STA + TCP-server mode: join a WiFi network and\n" - "start a TCP server so the client can connect over WiFi. PM5 only.\n" - "Sub-actions (no dashes): 'status' shows state, 'stop' tears WiFi down.", - "hw bwm wifi status --> show connection state + IP\n" - "hw bwm wifi stop --> tear down WiFi, back to BLE-only\n" - "hw bwm wifi --ssid Home --pwd secret --> bring up, port 7777\n" - "hw bwm wifi --ssid Home --pwd secret --port 9000"); - - void *argtable[] = { - arg_param_begin, - arg_str0(NULL, "ssid", "", "WiFi SSID to join"), - arg_str0(NULL, "pwd", "", "WiFi password (omit for open network)"), - arg_int0(NULL, "port", "", "TCP server listen port (default 7777)"), - arg_str0(NULL, "hostname", "", "DHCP hostname (default Proxmark5)"), - arg_param_end - }; - CLIExecWithReturn(ctx, Cmd, argtable, true); - - uint8_t ssid[64] = {0}; - int ssid_len = 0; - CLIParamStrToBuf(arg_get_str(ctx, 1), ssid, sizeof(ssid) - 1, &ssid_len); - - uint8_t pwd[64] = {0}; - int pwd_len = 0; - CLIParamStrToBuf(arg_get_str(ctx, 2), pwd, sizeof(pwd) - 1, &pwd_len); - - int port = arg_get_int_def(ctx, 3, 7777); - - uint8_t host[33] = {0}; - int host_len = 0; - CLIParamStrToBuf(arg_get_str(ctx, 4), host, sizeof(host) - 1, &host_len); - if (host_len == 0) { - strcpy((char *)host, "Proxmark5"); - host_len = 9; - } - CLIParserFree(ctx); - - if (ssid_len == 0) { - PrintAndLogEx(FAILED, "an SSID is required (or " _YELLOW_("hw bwm wifi stop") " to tear down)"); - return PM3_EINVARG; - } - if (port < 1 || port > 65535) { - PrintAndLogEx(FAILED, "port must be 1..65535"); - return PM3_EINVARG; - } - - // payload: [action:u8][port:u16 LE][ssid\0][pwd\0][hostname\0] - uint8_t data[200] = {0}; - int n = 0; - data[n++] = BWM_WIFI_ACTION_START; - data[n++] = (uint8_t)(port & 0xFF); - data[n++] = (uint8_t)((port >> 8) & 0xFF); - memcpy(&data[n], ssid, ssid_len); - n += ssid_len; - data[n++] = 0; - memcpy(&data[n], pwd, pwd_len); - n += pwd_len; - data[n++] = 0; - memcpy(&data[n], host, host_len); - n += host_len; - data[n++] = 0; - - PrintAndLogEx(INFO, "Bringing up BWM WiFi (SSID \"%s\", port %d)... this can take ~15s", ssid, port); - - clearCommandBuffer(); - SendCommandNG(CMD_PM5_BWM_WIFI, data, n); - PacketResponseNG resp; - // ARM blocks during join + DHCP wait, so allow a long client timeout - if (WaitForResponseTimeout(CMD_PM5_BWM_WIFI, &resp, 60000) == false) { - PrintAndLogEx(WARNING, "command timeout (is this a PM5 with a BWM fitted?)"); - return PM3_ETIMEOUT; - } - if (resp.status != PM3_SUCCESS) { - PrintAndLogEx(FAILED, "BWM WiFi bring-up failed (check SSID/password and signal)"); - PrintAndLogEx(HINT, "If it may have joined after DHCP, check: " _YELLOW_("hw bwm wifi status")); - return resp.status; - } - - uint32_t ip = resp.data.asDwords[0]; - PrintAndLogEx(SUCCESS, "BWM on WiFi at %u.%u.%u.%u", - ip & 0xFF, (ip >> 8) & 0xFF, (ip >> 16) & 0xFF, (ip >> 24) & 0xFF); - PrintAndLogEx(HINT, "Connect with: " _YELLOW_("pm3 -p tcp:%u.%u.%u.%u:%d"), - ip & 0xFF, (ip >> 8) & 0xFF, (ip >> 16) & 0xFF, (ip >> 24) & 0xFF, port); - PrintAndLogEx(HINT, "Or by name (router-dependent): " _YELLOW_("pm3 -p tcp:%s:%d"), host, port); - return PM3_SUCCESS; -} - -static int CmdBwmCharge(const char *Cmd) { - // Positional sub-action (no dashes): hw bwm charge on | off - char verb[16] = {0}; - sscanf(Cmd, "%15s", verb); - bool on = (strcmp(verb, "on") == 0); - bool off = (strcmp(verb, "off") == 0); - - if (!on && !off) { - // Not a recognised sub-action: render help (also serves -h / empty), - // or error on a stray token, then stop. - CLIParserContext *ctx; - CLIParserInit(&ctx, "hw bwm charge", - "Enable or disable BWM battery charging by clearing/setting the\n" - "AW32001E charge-enable bit (CEB, REG01[3]). PM5 only.\n" - _RED_("One-shot:") " the charger watchdog reverts this after ~160 s unless\n" - "serviced, so charging may stop on its own. Use to nudge a top-up.", - "hw bwm charge off --> disable charging\n" - "hw bwm charge on --> enable charging"); - void *argtable[] = { - arg_param_begin, - arg_param_end - }; - CLIExecWithReturn(ctx, Cmd, argtable, true); - CLIParserFree(ctx); - PrintAndLogEx(WARNING, "specify " _YELLOW_("on") " or " _YELLOW_("off")); - return PM3_EINVARG; - } - - uint8_t payload = off ? 0 : 1; // on -> 1 (enable), off -> 0 (disable) - PrintAndLogEx(INFO, "%s BWM battery charging...", off ? "Disabling" : "Enabling"); - - clearCommandBuffer(); - SendCommandNG(CMD_PM5_BWM_CHARGE_EN, &payload, sizeof(payload)); - PacketResponseNG resp; - if (WaitForResponseTimeout(CMD_PM5_BWM_CHARGE_EN, &resp, 2500) == false) { - PrintAndLogEx(WARNING, "command timeout (is this a PM5 with a BWM fitted?)"); - return PM3_ETIMEOUT; - } - if (resp.status != PM3_SUCCESS) { - PrintAndLogEx(FAILED, "charger did not respond (check BWM present)"); - return resp.status; - } - PrintAndLogEx(SUCCESS, "Charging %s. Verify with " _YELLOW_("hw status") ".", - off ? "disabled" : "enabled"); - if (off == false) { - PrintAndLogEx(HINT, "Reverts on the charger watchdog (~160 s) if not serviced."); - } - return PM3_SUCCESS; -} - -static int CmdBwmVchg(const char *Cmd) { - CLIParserContext *ctx; - CLIParserInit(&ctx, "hw bwm vchg", - "Set the BWM charger (AW32001E) charge-voltage regulation target.\n" - "Lowering it below 4.2 V reduces top-of-charge stress and extends cell\n" - "life. Snaps to the nearest 15 mV step; clamped to 3600..4200 mV. This is\n" - "a runtime register write (reverts on the charger watchdog / POR); the\n" - "firmware re-applies the " _YELLOW_("4100 mV") " default at every boot. PM5 only.", - "hw bwm vchg --> set charge voltage to default 4100 mV (->4.095 V)\n" - "hw bwm vchg --mv 4200 --> set charge voltage to 4200 mV"); - - void *argtable[] = { - arg_param_begin, - arg_int0(NULL, "mv", "", "charge voltage in mV (default 4100, clamped 3600..4200)"), - arg_param_end - }; - CLIExecWithReturn(ctx, Cmd, argtable, true); - int mv = arg_get_int_def(ctx, 1, 4100); - CLIParserFree(ctx); - - if (mv < 3600 || mv > 4200) { - PrintAndLogEx(WARNING, "charge voltage out of range (3600..4200 mV): %d", mv); - return PM3_EINVARG; - } - - uint8_t payload[2] = { (uint8_t)(mv & 0xFF), (uint8_t)((mv >> 8) & 0xFF) }; - PrintAndLogEx(INFO, "Setting BWM charge voltage to " _YELLOW_("%d mV") "...", mv); - - clearCommandBuffer(); - SendCommandNG(CMD_PM5_BWM_SET_VCHG, payload, sizeof(payload)); - PacketResponseNG resp; - if (WaitForResponseTimeout(CMD_PM5_BWM_SET_VCHG, &resp, 5000) == false) { - PrintAndLogEx(WARNING, "command timeout (is this a PM5 with a BWM fitted?)"); - return PM3_ETIMEOUT; - } - if (resp.status != PM3_SUCCESS) { - PrintAndLogEx(FAILED, "failed to set charge voltage - check BWM present"); - return resp.status; - } - uint16_t applied = (resp.length >= 2) ? (resp.data.asBytes[0] | (resp.data.asBytes[1] << 8)) : 0; - PrintAndLogEx(SUCCESS, "Charge voltage set to " _YELLOW_("%u.%03u V") " (nearest 15 mV step).", applied / 1000, applied % 1000); - return PM3_SUCCESS; -} - -static int CmdBwmSetCap(const char *Cmd) { - CLIParserContext *ctx; - CLIParserInit(&ctx, "hw bwm setcap", - "Program the BWM fuel gauge (BQ27427) Design Capacity for the fitted cell.\n" - "Run ONCE after fitting or replacing the battery. This triggers a gauge\n" - "config-update; do not run it repeatedly, as that disrupts the Impedance\n" - "Track learning cycle. PM5 only.", - "hw bwm setcap --> set design capacity to default 500 mAh\n" - "hw bwm setcap --cap 500 --> set design capacity to 500 mAh"); - - void *argtable[] = { - arg_param_begin, - arg_int0(NULL, "cap", "", "design capacity in mAh (default 500)"), - arg_param_end - }; - CLIExecWithReturn(ctx, Cmd, argtable, true); - int cap = arg_get_int_def(ctx, 1, 500); - CLIParserFree(ctx); - - if (cap <= 0 || cap > 32000) { - PrintAndLogEx(WARNING, "capacity out of range: %d mAh", cap); - return PM3_EINVARG; - } - - uint8_t payload[2] = { (uint8_t)(cap & 0xFF), (uint8_t)((cap >> 8) & 0xFF) }; - PrintAndLogEx(INFO, "Programming BWM gauge design capacity to " _YELLOW_("%d mAh") "...", cap); - PrintAndLogEx(INFO, "Run this " _YELLOW_("once") "; then perform a full charge/discharge learning cycle."); - - clearCommandBuffer(); - SendCommandNG(CMD_PM5_BWM_SET_CAP, payload, sizeof(payload)); - PacketResponseNG resp; - if (WaitForResponseTimeout(CMD_PM5_BWM_SET_CAP, &resp, 5000) == false) { - PrintAndLogEx(WARNING, "command timeout (is this a PM5 with a BWM fitted?)"); - return PM3_ETIMEOUT; - } - if (resp.status != PM3_SUCCESS) { - PrintAndLogEx(FAILED, "gauge provisioning failed - check BWM present and gauge unsealed"); - return resp.status; - } - PrintAndLogEx(SUCCESS, "Design capacity programmed. `hw status` should now report sane capacity."); - return PM3_SUCCESS; -} - static int CmdTia(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hw tia", @@ -2382,289 +2032,51 @@ static int CmdPM5QCTest(const char *Cmd) { return PM3_SUCCESS; } -static void progressbar(long sent, long total, int style) { - int percent = (int)((double)sent / total * 100); - - // Use \r at the start to move the cursor back to the beginning of the line - printf("\rProgress: [%d%%]", percent); - - // Force stdout to print immediately without waiting for a newline - fflush(stdout); -} -// One full OTA attempt: BEGIN -> WRITE... -> END. The BWM OTA has no resume -// (DEV.md 8.4): a dropped chunk can't be re-sent, so any failure here means the -// caller must restart the whole thing. -static int bwm_ota_once(const uint8_t *fw, size_t fwlen, uint32_t write_delay_ms) { - PacketResponseNG resp; +static int CmdPowerSave(const char *Cmd) { + // Positional sub-action (no dashes): hw powersave on | off + char verb[16] = {0}; + sscanf(Cmd, "%15s", verb); + bool on = (strcmp(verb, "on") == 0); + bool off = (strcmp(verb, "off") == 0); - // BEGIN: tell the BWM how many bytes are coming. The ESP erases the idle - // OTA slot here; that can take 20-40 s on a 4 MB ESP32-C2, so wait longer - // than the device-side 60 s timeout plus USB round-trip. - uint8_t beg[5] = { BWM_OTA_ACTION_BEGIN, - (uint8_t)(fwlen & 0xFF), (uint8_t)((fwlen >> 8) & 0xFF), - (uint8_t)((fwlen >> 16) & 0xFF), (uint8_t)((fwlen >> 24) & 0xFF) }; - clearCommandBuffer(); - SendCommandNG(CMD_PM5_BWM_ESP_OTA, beg, sizeof(beg)); - if (WaitForResponseTimeout(CMD_PM5_BWM_ESP_OTA, &resp, 75000) == false) { - PrintAndLogEx(FAILED, "OTA begin timed out (ESP is likely still erasing the OTA slot)"); - PrintAndLogEx(HINT, "Wait a few seconds and retry; do not power-cycle mid-erase."); - return PM3_ETIMEOUT; - } - if (resp.status != PM3_SUCCESS) { - PrintAndLogEx(FAILED, "OTA begin failed (status %d)%s", resp.status, - (resp.status == PM3_ETIMEOUT) ? " - UART timeout waiting for ESP" : ""); - return resp.status; - } - PrintAndLogEx(INFO, "Uploading " _YELLOW_("%zu") " bytes of ESP firmware over the BWM link...", fwlen); - - // WRITE chunks. Bounded by BWM_OTA_CHUNK_MAX (the ESP forwards each WRITE over - // its own small app_com UART frame - see bwm_wifi.c), not just the USB frame. - size_t maxchunk = MIN((size_t)g_conn.max_cmd_data_size - 1, (size_t)BWM_OTA_CHUNK_MAX); - uint8_t *buf = calloc(1, maxchunk + 1); - if (buf == NULL) { - return PM3_EMALLOC; - } - size_t sent = 0; - while (sent < fwlen) { - size_t n = MIN(maxchunk, fwlen - sent); - buf[0] = BWM_OTA_ACTION_WRITE; - memcpy(buf + 1, fw + sent, n); - clearCommandBuffer(); - SendCommandNG(CMD_PM5_BWM_ESP_OTA, buf, (uint16_t)(n + 1)); - bool got = WaitForResponseTimeout(CMD_PM5_BWM_ESP_OTA, &resp, 25000); - if (!got || resp.status != PM3_SUCCESS) { - PrintAndLogEx(NORMAL, ""); - if (!got) { - PrintAndLogEx(WARNING, "OTA write stalled at offset %zu (no response)", sent); - } else if (resp.status == PM3_ETIMEOUT) { - PrintAndLogEx(WARNING, "OTA write timed out at offset %zu (ESP did not ACK that chunk)", sent); - } else { - PrintAndLogEx(WARNING, "OTA write rejected at offset %zu (status %d)", sent, resp.status); - } - free(buf); - return PM3_EFAILED; - } - sent += n; - progressbar(sent, fwlen, STYLE_MIXED); - - // Pace the stream. The client->AT32 hop (USB/BLE) is far faster than the - // AT32->ESP UART, so back-to-back writes can outrun the UART and drop a - // chunk -> esp_ota_end() then sees written < total and aborts. A small - // gap gives the UART time to drain. (BLE is naturally paced, which is why - // it "worked" and bursty USB did not - see nemanjan00.) - if (write_delay_ms) { - msleep(write_delay_ms); - } - } - free(buf); - PrintAndLogEx(NORMAL, ""); - - // END: finalize + set the new boot partition - uint8_t end[1] = { BWM_OTA_ACTION_END }; - clearCommandBuffer(); - SendCommandNG(CMD_PM5_BWM_ESP_OTA, end, sizeof(end)); - bool got_end = WaitForResponseTimeout(CMD_PM5_BWM_ESP_OTA, &resp, 30000); - if (got_end && (resp.status == PM3_SUCCESS)) { - return PM3_SUCCESS; - } - if (got_end) { - // The BWM answered END with an error. The common one is a size mismatch: - // esp_ota_end() found written < total, i.e. chunks were dropped in transit. - // That is a genuine failure (boot partition NOT switched) - restart, and - // hint at pacing, which is the usual cure. - PrintAndLogEx(WARNING, "OTA finalize rejected (status %d) - data was lost in transit", resp.status); - PrintAndLogEx(HINT, "Try a per-write delay: " _YELLOW_("hw bwm upgrade -f --delay 20")); - return PM3_EFAILED; - } - // No answer at all. Over BLE the END auto-reboot drops the link before the ack - // returns, so a timeout here means "reached END, reboot likely happened" - - // verify by version rather than discarding a possibly-good flash. - return PM3_ETIMEOUT; -} - -// Query the BWM's running firmware version string (APP_CMD_GET_VERSION_INFO). -static int bwm_get_version(char *out, size_t outlen) { - uint8_t a[1] = { BWM_OTA_ACTION_VERSION }; - clearCommandBuffer(); - SendCommandNG(CMD_PM5_BWM_ESP_OTA, a, sizeof(a)); - PacketResponseNG r; - if ((WaitForResponseTimeout(CMD_PM5_BWM_ESP_OTA, &r, 5000) == false) || (r.status != PM3_SUCCESS)) { - return PM3_EFAILED; - } - uint16_t n = (r.length < (uint16_t)(outlen - 1)) ? r.length : (uint16_t)(outlen - 1); - memcpy(out, r.data.asBytes, n); - out[n] = 0; - return PM3_SUCCESS; -} - -static int CmdBWMUpgrade(const char *Cmd) { - CLIParserContext *ctx; - CLIParserInit(&ctx, "hw bwm upgrade", - "Reflash the BWM (ESP32) firmware over the BWM link - no header, no soldering.\n" - "Requires a BWM that still responds; this updates a wrong-version ESP, it cannot\n" - "recover a fully bricked one (that still needs the 5-pin header + esptool).", - "hw bwm upgrade -f bwm_esp32.bin"); - void *argtable[] = { - arg_param_begin, - arg_str1("f", "file", "", "ESP32 firmware image (.bin)"), - arg_int0(NULL, "delay", "", "per-chunk delay to pace the slow AT32<->ESP UART (default 20)"), - arg_param_end, - }; - CLIExecWithReturn(ctx, Cmd, argtable, false); - int fnlen = 0; - char fn[FILE_PATH_SIZE] = {0}; - CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)fn, sizeof(fn), &fnlen); - uint32_t write_delay_ms = (uint32_t)arg_get_int_def(ctx, 2, 20); - CLIParserFree(ctx); - - if (fnlen == 0) { - PrintAndLogEx(FAILED, "no filename given"); + if (!on && !off) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hw powersave", + "Toggle the PM5 power-save idle. Default is " _GREEN_("on") ": between commands the\n" + "core drops from 288 to 48 MHz with the PLL off, the FPGA clock stopped and the\n" + "CPU halted (WFI) until the next interrupt or the 1 ms wake tick. Commands run\n" + "at full speed; turn it off to keep the core at 288 MHz and spinning.\n" + _YELLOW_("Runtime only:") " resets to on at each boot. See `hw status` for the idle stats.", + "hw powersave off --> stay at 288 MHz, no idle sleep\n" + "hw powersave on --> re-enable the power-save idle"); + void *argtable[] = { + arg_param_begin, + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + CLIParserFree(ctx); + PrintAndLogEx(WARNING, "specify " _YELLOW_("on") " or " _YELLOW_("off")); return PM3_EINVARG; } - uint8_t *fw = NULL; - size_t fwlen = 0; - if ((loadFile_safe(fn, "", (void **)&fw, &fwlen) != PM3_SUCCESS) || (fwlen == 0)) { - PrintAndLogEx(FAILED, "could not read " _YELLOW_("%s"), fn); - return PM3_EFILE; - } + uint8_t payload = off ? 0 : 1; - // Safeguard: refuse to flash anything that is not an ESP32-C2 app image. The - // BWM ESP is an ESP32-C2; a wrong/other-chip image would brick it. - // [0x00] == 0xE9 -> ESP image magic - // [0x0C..0x0D] == 0x000C -> chip_id ESP32-C2 (LE uint16) - // [0xABCD5432..0x20] == 0xABCD5432 -> app descriptor (LE uint32) - if (fwlen < 16) { - PrintAndLogEx(FAILED, "file is too small to be an ESP firmware image (%zu bytes)", fwlen); - free(fw); - return PM3_EFILE; - } - if (fw[0] != 0xE9) { - PrintAndLogEx(FAILED, "refusing to flash: not an ESP image (magic " _YELLOW_("0x%02X") ", expected 0xE9)", fw[0]); - free(fw); - return PM3_EFILE; - } - - // Check Chip ID at offset 0x0C (2 bytes, little-endian) - uint16_t chip_id = MemLeToUint2byte(fw + 0x0C); - if (chip_id != 0x000C) { - PrintAndLogEx(FAILED, "refusing to flash: image chip_id " _YELLOW_("0x%04X") " is not ESP32-C2 (0x000C)", chip_id); - free(fw); - return PM3_EFILE; - } - - // Check Application Signature at offset 0x20 (4 bytes, little-endian) - uint32_t app_sign = MemLeToUint4byte(fw + 0x20); - if (app_sign != 0xABCD5432) { - PrintAndLogEx(FAILED, "refusing to flash: image app_sign " _YELLOW_("0x%08X") " is invalid (expected 0xABCD5432)", app_sign); - free(fw); - return PM3_EFILE; - } - - // Record the running version first, so we can confirm the update actually took - // even when the finalize ack is lost (the case that used to discard a completed - // flash and restart from scratch). - char ver_before[64] = {0}; - bool have_before = (bwm_get_version(ver_before, sizeof(ver_before)) == PM3_SUCCESS); - if (have_before) { - PrintAndLogEx(INFO, "Current BWM firmware..... " _YELLOW_("%s"), ver_before); - } - - // No resume (DEV.md 8.4): a chunk lost mid-transfer restarts the whole upload. - const int max_attempts = 6; // a single dropped chunk restarts the whole upload; - // more attempts make an all-fail run rare until per-chunk - // retry (offset-idempotent ESP write) lands. - for (int attempt = 1; attempt <= max_attempts; attempt++) { - if (attempt > 1) { - // Abort the in-flight ESP OTA (if any) and give a slow erase a chance - // to finish before we BEGIN again. Otherwise attempt N's BEGIN races - // attempt N-1's still-running erase and times out. - PrintAndLogEx(INFO, "restarting OTA from the beginning (attempt " _YELLOW_("%d") "/%d)", attempt, max_attempts); - uint8_t ab[1] = { BWM_OTA_ACTION_ABORT }; - clearCommandBuffer(); - SendCommandNG(CMD_PM5_BWM_ESP_OTA, ab, sizeof(ab)); - PacketResponseNG abortr; - (void)WaitForResponseTimeout(CMD_PM5_BWM_ESP_OTA, &abortr, 8000); - msleep(3000); - } - int res = bwm_ota_once(fw, fwlen, write_delay_ms); - - // Failed during BEGIN/WRITE: image incomplete, restart the whole thing. - if ((res != PM3_SUCCESS) && (res != PM3_ETIMEOUT)) { - continue; - } - - // Reached OTA_END (acked, or ack lost). The image is written and the boot - // partition is set - reboot into it and confirm by version. - if (res == PM3_ETIMEOUT) { - PrintAndLogEx(INFO, "finalize ack not seen - all data was sent, confirming by version..."); - } - // The device's OTA_END handler already reboots the ESP into the new image - // (that is what drops the finalize ack over BLE). Just wait for it to come - // back and re-link, then confirm by version. - PrintAndLogEx(INFO, "BWM rebooting into the new image (link drops briefly)..."); - msleep(8000); // reboot + re-negotiate baud + re-link - - char ver_after[64] = {0}; - bool have_after = (bwm_get_version(ver_after, sizeof(ver_after)) == PM3_SUCCESS); - - if (have_after && have_before) { - if (strncmp(ver_before, ver_after, sizeof(ver_before)) != 0) { - PrintAndLogEx(SUCCESS, "BWM firmware updated: %s -> " _YELLOW_("%s"), ver_before, ver_after); - free(fw); - return PM3_SUCCESS; - } - PrintAndLogEx(WARNING, "BWM still reports " _YELLOW_("%s") " - update did not take, retrying", ver_after); - continue; - } - if (have_after) { - PrintAndLogEx(SUCCESS, "BWM now running " _YELLOW_("%s"), ver_after); - free(fw); - return PM3_SUCCESS; - } - // Could not re-read the version (link dropped on reboot, common over BLE). - // All data was uploaded, so treat as done and let the user confirm. - PrintAndLogEx(WARNING, "Could not re-read BWM version after reboot (link dropped?)"); - PrintAndLogEx(HINT, "Reconnect and run " _YELLOW_("hw status") " to confirm the version."); - free(fw); - return PM3_SUCCESS; - } - free(fw); - - // Exhausted retries without a confirmed update - restore the link and report. + clearCommandBuffer(); + SendCommandNG(CMD_PM5_POWERSAVE, &payload, sizeof(payload)); PacketResponseNG resp; - uint8_t ab[1] = { BWM_OTA_ACTION_ABORT }; - clearCommandBuffer(); - SendCommandNG(CMD_PM5_BWM_ESP_OTA, ab, sizeof(ab)); - (void)WaitForResponseTimeout(CMD_PM5_BWM_ESP_OTA, &resp, 8000); - PrintAndLogEx(FAILED, "BWM firmware update could not be confirmed after %d attempts", max_attempts); - return PM3_EFAILED; -} -static int CmdHelpBwm(const char *Cmd); - -static command_t BwmCommandTable[] = { - {"help", CmdHelpBwm, AlwaysAvailable, "This help"}, - {"autooff", CmdBwmAutoOff, IfPm5, "Toggle auto power-off on USB unplug"}, - {"charge", CmdBwmCharge, IfPm5, "Enable/disable battery charging (one-shot)"}, - {"setcap", CmdBwmSetCap, IfPm5, "Set fuel-gauge design capacity (run once after battery change)"}, - {"upgrade", CmdBWMUpgrade, IfPm5, "Reflash BWM (ESP32) firmware over the BWM link, no header"}, - {"vchg", CmdBwmVchg, IfPm5, "Set charger charge-voltage target (default 4100 mV)"}, - {"wifi", CmdBWMWifi, IfPm5, "Bring up WiFi (STA + TCP server) for a tcp: connection"}, - {NULL, NULL, NULL, NULL} -}; - -static int CmdHelpBwm(const char *Cmd) { - (void)Cmd; - CmdsHelp(BwmCommandTable); + if (WaitForResponseTimeout(CMD_PM5_POWERSAVE, &resp, 2500) == false) { + PrintAndLogEx(WARNING, "command timeout (is this a PM5?)"); + return PM3_ETIMEOUT; + } + if (resp.status != PM3_SUCCESS) { + PrintAndLogEx(FAILED, "failed to set power-save idle"); + return resp.status; + } + PrintAndLogEx(SUCCESS, "Power-save idle %s.", payload ? _GREEN_("enabled") : _YELLOW_("disabled")); return PM3_SUCCESS; } -static int CmdBwm(const char *Cmd) { - clearCommandBuffer(); - return CmdsParse(BwmCommandTable, Cmd); -} - static command_t CommandTable[] = { {"help", CmdHelp, AlwaysAvailable, "This help"}, {"-------------", CmdHelp, AlwaysAvailable, "----------------------- " _CYAN_("Operation") " -----------------------"}, @@ -2686,6 +2098,7 @@ static command_t CommandTable[] = { {"lcd", CmdLCD, IfPm3Lcd, "Send command/data to LCD"}, {"lcdreset", CmdLCDReset, IfPm3Lcd, "Hardware reset LCD"}, {"ping", CmdPing, IfPm3Present, "Test if the Proxmark3 is responsive"}, + {"powersave", CmdPowerSave, IfPm5, "Enable/disable the PM5 power-save idle"}, {"readmem", CmdReadmem, IfPm3Present, "Read from MCU flash"}, {"reset", CmdReset, IfPm3Present, "Reset the device"}, {"setlfdivisor", CmdSetDivisor, IfPm3Lf, "Drive LF antenna at 12MHz / (divisor + 1)"}, @@ -2693,7 +2106,7 @@ static command_t CommandTable[] = { {"setmux", CmdSetMux, IfPm3Present, "Set the ADC mux to a specific value"}, {"standalone", CmdStandalone, IfPm3Present, "Start installed standalone mode on device"}, {"tia", CmdTia, IfPm3Present, "Trigger a Timing Interval Acquisition to re-adjust the RealTimeCounter divider"}, - {"bwm", CmdBwm, IfPm5, "{ BWM (battery/wireless module) commands... }"}, + {"bwm", CmdBwm, IfBwm, "{ BWM (battery/wireless module) commands... }"}, {"tune", CmdTune, IfPm3Lf, "Measure tuning of device antenna"}, {"decay", CmdDecay, IfPm3Present, "Measure HF antenna decay after field-off"}, {NULL, NULL, NULL, NULL} diff --git a/client/src/cmdlf.c b/client/src/cmdlf.c index bf8186d73..aa6bb2ad6 100644 --- a/client/src/cmdlf.c +++ b/client/src/cmdlf.c @@ -808,6 +808,7 @@ static int lf_read_internal(bool realtime, bool verbose, uint64_t samples, bool size_t sample_bytes = samples * bits_per_sample; sample_bytes = (sample_bytes / 8) + (sample_bytes % 8 != 0); + const size_t expected_bytes = sample_bytes; // In real-time mode, the LF bitstream should be loaded before receiving raw data. // Otherwise, the first batch of raw data might contain the response of CMD_WTX. @@ -831,12 +832,25 @@ static int lf_read_internal(bool realtime, bool verbose, uint64_t samples, bool sample_bytes = WaitForRawDataTimeout(realtimeBuf, sample_bytes, 1000, true, false); } samples = sample_bytes * 8 / bits_per_sample; - PrintAndLogEx(INFO, "Done: %" PRIu64 " samples (%zu bytes)", samples, sample_bytes); + // the inline "Received x / y bytes" counter already says the transfer is + // done, so only repeat it in samples when asked + if (verbose) { + PrintAndLogEx(INFO, "Done: %" PRIu64 " samples (%zu bytes)", samples, sample_bytes); + } if (samples != 0) { getSamplesFromBufEx(realtimeBuf, samples, bits_per_sample, verbose); } free(realtimeBuf); + + if (sample_bytes < expected_bytes) { + // keep what did arrive, but don't let it look like a complete read + PrintAndLogEx(WARNING, "transfer stopped early, got " _YELLOW_("%zu") " of " _YELLOW_("%zu") " bytes" + , sample_bytes + , expected_bytes + ); + return PM3_ETIMEOUT; + } } else { SendCommandNG(CMD_LF_ACQ_RAW_ADC, (uint8_t *)&payload, sizeof(payload)); PacketResponseNG resp; @@ -891,6 +905,13 @@ int CmdLFRead(const char *Cmd) { bool cm = arg_get_lit(ctx, 3); CLIParserFree(ctx); + // anything past the graph buffer is streamed and then thrown away by + // getSamplesFromBufEx(), so don't spend the transfer time on it + if (samples > MAX_GRAPH_TRACE_LEN) { + PrintAndLogEx(INFO, "Capping to " _YELLOW_("%d") " samples, the graph buffer size", MAX_GRAPH_TRACE_LEN); + samples = MAX_GRAPH_TRACE_LEN; + } + // it should be the result of BigBuf_max_traceLen(), // but IDK how to get it. bool realtime = samples >= g_pm3_capabilities.bigbuf_size; @@ -906,7 +927,9 @@ int CmdLFRead(const char *Cmd) { ret = lf_read_internal(realtime, verbose, samples, false); } while (cm && (kbd_enter_pressed() == false)); - if (ret == PM3_SUCCESS) { + // a truncated transfer still leaves usable samples in the graph buffer, + // so report them. lf_read_internal() has already said it was short. + if (ret == PM3_SUCCESS || ret == PM3_ETIMEOUT) { PrintAndLogEx(SUCCESS, "Got " _YELLOW_("%zu") " samples", g_GraphTraceLen); if (getSignalProperties()->isnoise) { @@ -943,6 +966,7 @@ int lf_sniff(bool realtime, bool verbose, uint64_t samples) { size_t sample_bytes = samples * bits_per_sample; sample_bytes = (sample_bytes / 8) + (sample_bytes % 8 != 0); + const size_t expected_bytes = sample_bytes; // In real-time mode, the LF bitstream should be loaded before receiving raw data. // Otherwise, the first batch of raw data might contain the response of CMD_WTX. @@ -966,12 +990,25 @@ int lf_sniff(bool realtime, bool verbose, uint64_t samples) { sample_bytes = WaitForRawDataTimeout(realtimeBuf, sample_bytes, 1000, true, false); } samples = sample_bytes * 8 / bits_per_sample; - PrintAndLogEx(INFO, "Done: %" PRIu64 " samples (%zu bytes)", samples, sample_bytes); + // the inline "Received x / y bytes" counter already says the transfer is + // done, so only repeat it in samples when asked + if (verbose) { + PrintAndLogEx(INFO, "Done: %" PRIu64 " samples (%zu bytes)", samples, sample_bytes); + } if (samples != 0) { getSamplesFromBufEx(realtimeBuf, samples, bits_per_sample, verbose); } free(realtimeBuf); + + if (sample_bytes < expected_bytes) { + // keep what did arrive, but don't let it look like a complete read + PrintAndLogEx(WARNING, "transfer stopped early, got " _YELLOW_("%zu") " of " _YELLOW_("%zu") " bytes" + , sample_bytes + , expected_bytes + ); + return PM3_ETIMEOUT; + } } else { SendCommandNG(CMD_LF_SNIFF_RAW_ADC, (uint8_t *)&payload, sizeof(payload)); PacketResponseNG resp; @@ -1019,6 +1056,13 @@ int CmdLFSniff(const char *Cmd) { bool cm = arg_get_lit(ctx, 3); CLIParserFree(ctx); + // anything past the graph buffer is streamed and then thrown away by + // getSamplesFromBufEx(), so don't spend the transfer time on it + if (samples > MAX_GRAPH_TRACE_LEN) { + PrintAndLogEx(INFO, "Capping to " _YELLOW_("%d") " samples, the graph buffer size", MAX_GRAPH_TRACE_LEN); + samples = MAX_GRAPH_TRACE_LEN; + } + // it should be the result of BigBuf_max_traceLen(), // but IDK how to get it. bool realtime = samples >= g_pm3_capabilities.bigbuf_size; @@ -1609,8 +1653,7 @@ static bool check_chiptype(bool getDeviceData) { } //Save the state of the Graph and Demod Buffers - buffer_savestate_t saveState_gb = save_bufferS32(g_GraphBuffer, g_GraphTraceLen); - saveState_gb.offset = g_GridOffset; + buffer_savestate_t saveState_gb = save_graphbuffer(); buffer_savestate_t saveState_db = save_buffer8(g_DemodBuffer, g_DemodBufferLen); saveState_db.clock = g_DemodClock; saveState_db.offset = g_DemodStartIdx; @@ -1683,13 +1726,15 @@ static bool check_chiptype(bool getDeviceData) { PrintAndLogEx(INFO, "Couldn't identify a chipset"); out: - restore_buffer8(saveState_db, g_DemodBuffer); + // the detections above demodulate, so the length comes back with the contents + g_DemodBufferLen = restore_buffer8(saveState_db, g_DemodBuffer); g_DemodClock = saveState_db.clock; g_DemodStartIdx = saveState_db.offset; - restore_bufferS32(saveState_gb, g_GraphBuffer); - g_GridOffset = saveState_gb.offset; + restore_graphbuffer(saveState_gb); + free_buffer_savestate(saveState_db); + free_buffer_savestate(saveState_gb); return retval; } diff --git a/client/src/cmdlfcotag.c b/client/src/cmdlfcotag.c index 5ef8b9b28..4b1b25822 100644 --- a/client/src/cmdlfcotag.c +++ b/client/src/cmdlfcotag.c @@ -31,7 +31,7 @@ #include "ui.h" // PrintAndLog #include "ctype.h" // tolower #include "cliparser.h" -#include "commonutil.h" // reflect32 +#include "commonutil.h" // reflect32, ARRAYLEN #include "cmdlf.h" // lf_getconfig, lf_setconfig, lf_read_cotag #include "graph.h" // g_GraphTraceLen @@ -273,9 +273,9 @@ static int demod_cotag(int32_t *samples, int num_samples, int clock, int clock_s int len; const char *name; } preamble_patterns[] = { - { preamble_a, (int)(sizeof(preamble_a) / sizeof(preamble_a[0])), "A" }, - { preamble_p, (int)(sizeof(preamble_p) / sizeof(preamble_p[0])), "P" }, - { preamble_p0, (int)(sizeof(preamble_p0) / sizeof(preamble_p0[0])), "P-0" }, + { preamble_a, ARRAYLEN(preamble_a), "A" }, + { preamble_p, ARRAYLEN(preamble_p), "P" }, + { preamble_p0, ARRAYLEN(preamble_p0), "P-0" }, { NULL, 0, "" }, }; @@ -512,6 +512,9 @@ static int CmdCOTAGReader(const char *Cmd) { } if (cm || realtime) { + // close any inline line the caller left open, ie: `lf search` printing + // "Searching for COTAG tag..." right before this + PrintAndLogEx(NORMAL, ""); PrintAndLogEx(INFO, "Press " _GREEN_("") " to exit"); } diff --git a/client/src/cmdlfhid.c b/client/src/cmdlfhid.c index 8093f46c5..8709891fa 100644 --- a/client/src/cmdlfhid.c +++ b/client/src/cmdlfhid.c @@ -346,7 +346,7 @@ static int CmdHIDSim(const char *Cmd) { memset(&cli, 0, sizeof(cli)); CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)cli.format, sizeof(cli.format), &cli.format_len); cli.card.FacilityCode = arg_get_u32_def(ctx, 2, 0); - cli.card.CardNumber = arg_get_u32_def(ctx, 3, 0); + cli.card.CardNumber = arg_get_u64_def(ctx, 3, 0); cli.card.IssueLevel = arg_get_u32_def(ctx, 4, 0); cli.card.OEM = arg_get_u32_def(ctx, 5, 0); int res = CLIParamHexToBuf(arg_get_str(ctx, 6), cli.raw, sizeof(cli.raw), &cli.raw_len); @@ -435,7 +435,7 @@ static int CmdHIDClone(const char *Cmd) { memset(&cli, 0, sizeof(cli)); CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)cli.format, sizeof(cli.format), &cli.format_len); cli.card.FacilityCode = arg_get_u32_def(ctx, 2, 0); - cli.card.CardNumber = arg_get_u32_def(ctx, 3, 0); + cli.card.CardNumber = arg_get_u64_def(ctx, 3, 0); cli.card.IssueLevel = arg_get_u32_def(ctx, 4, 0); cli.card.OEM = arg_get_u32_def(ctx, 5, 0); int res = CLIParamHexToBuf(arg_get_str(ctx, 6), cli.raw, sizeof(cli.raw), &cli.raw_len); @@ -586,7 +586,7 @@ static int CmdHIDBrute(const char *Cmd) { CLIParamStrToBuf(arg_get_str(ctx, 3), (uint8_t *)field, sizeof(field), &field_len); card_hi.FacilityCode = arg_get_u32_def(ctx, 4, 0); - card_hi.CardNumber = arg_get_u32_def(ctx, 5, 0); + card_hi.CardNumber = arg_get_u64_def(ctx, 5, 0); card_hi.IssueLevel = arg_get_u32_def(ctx, 6, 0); card_hi.OEM = arg_get_u32_def(ctx, 7, 0); diff --git a/client/src/cmdlfhitag.c b/client/src/cmdlfhitag.c index aa421a0ac..c7aa90f08 100644 --- a/client/src/cmdlfhitag.c +++ b/client/src/cmdlfhitag.c @@ -1495,12 +1495,12 @@ static int CmdLFHitag2Restore(const char *Cmd) { CLIParserFree(ctx); if ((ukeylen != 0) && (ukeylen != HITAG_PASSWORD_SIZE) && (ukeylen != HITAG_CRYPTOKEY_SIZE)) { - + PrintAndLogEx(ERR, "Key must be %u bytes (password) or %u bytes (crypto), got %i", - HITAG_PASSWORD_SIZE, - HITAG_CRYPTOKEY_SIZE, - ukeylen - ); + HITAG_PASSWORD_SIZE, + HITAG_CRYPTOKEY_SIZE, + ukeylen + ); return PM3_EINVARG; } @@ -1940,7 +1940,7 @@ static int CmdLFHitagEload(const char *Cmd) { arg_lit0("1", "ht1", "Card type Hitag 1"), arg_lit0("2", "ht2", "Card type Hitag 2"), arg_lit0("s", "hts", "Card type Hitag S"), - arg_lit0("m", "htm", "Card type Hitag \xce\xbc"), // μ + arg_lit0("m", "htm", "Card type Hitag µ"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, false); @@ -1966,7 +1966,7 @@ static int CmdLFHitagEload(const char *Cmd) { // A Hitag u image is the 6 byte UID followed by its pages, and is the largest // of the four. Everything still fits one NG frame. - #define HITAGU_EIMAGE_SIZE (HITAGU_UID_SIZE + (HITAGU_MAX_PAGE_ADVANCED_PLUS * HITAGU_BLOCK_SIZE)) +#define HITAGU_EIMAGE_SIZE (HITAGU_UID_SIZE + (HITAGU_MAX_PAGE_ADVANCED_PLUS * HITAGU_BLOCK_SIZE)) // read dump file uint8_t *dump = NULL; @@ -1990,7 +1990,7 @@ static int CmdLFHitagEload(const char *Cmd) { } else if (use_htm) { // a u dump is sized by the tag's ICR, so accept anything that fits expected = 0; - tname = "Hitag \xce\xbc"; + tname = "Hitag µ"; } if (use_htm) { @@ -2053,7 +2053,7 @@ static int CmdLFHitagEview(const char *Cmd) { arg_lit0("1", "ht1", "Card type Hitag 1"), arg_lit0("2", "ht2", "Card type Hitag 2 (default)"), arg_lit0("s", "hts", "Card type Hitag S"), - arg_lit0("m", "htm", "Card type Hitag \xce\xbc"), + arg_lit0("m", "htm", "Card type Hitag µ"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, true); @@ -2933,4 +2933,3 @@ int CmdLFHitag(const char *Cmd) { return CmdsParse(CommandTable, Cmd); } - diff --git a/client/src/cmdlfhitaghts.c b/client/src/cmdlfhitaghts.c index 89cd8c12a..2f52823f8 100644 --- a/client/src/cmdlfhitaghts.c +++ b/client/src/cmdlfhitaghts.c @@ -18,6 +18,7 @@ #include "cmdlfhitaghts.h" #include +#include // strlen #include "cmdparser.h" // command_t #include "comms.h" #include "cmdtrace.h" @@ -37,15 +38,19 @@ static int CmdHelp(const char *Cmd); void annotateHitagS(char *exp, size_t size, const uint8_t *cmd, uint8_t nbits, bool is_response) { - size_t exp_len = 0; uint8_t command = 0; + // the caller reuses this buffer across frames, and the appends below are + // strlen() based now, so clear it here instead of relying on the first + // write landing at offset 0 + exp[0] = '\0'; + if (is_response) { // Handle responses if (nbits == 32) { - exp_len = snprintf(exp, size, "UID: [%02X%02X%02X%02X]", cmd[0], cmd[1], cmd[2], cmd[3]); + snprintf(exp, size, "UID: [%02X%02X%02X%02X]", cmd[0], cmd[1], cmd[2], cmd[3]); } else if (nbits == 40) { - exp_len = snprintf(exp, size, "Data"); + snprintf(exp, size, "Data"); } } else if (nbits >= 5) { concatbits(&command, 0, cmd, 0, 5, false); @@ -55,62 +60,62 @@ void annotateHitagS(char *exp, size_t size, const uint8_t *cmd, uint8_t nbits, b switch (command) { case HITAGS_UID_REQ_STD: - exp_len += snprintf(exp + exp_len, size - exp_len, "UID Request (Standard 00110)"); + snprintf(exp + strlen(exp), size - strlen(exp), "UID Request (Standard 00110)"); break; case HITAGS_UID_REQ_ADV1: - exp_len += snprintf(exp + exp_len, size - exp_len, "UID Request (Advanced 11000)"); + snprintf(exp + strlen(exp), size - strlen(exp), "UID Request (Advanced 11000)"); break; case HITAGS_UID_REQ_ADV2: - exp_len += snprintf(exp + exp_len, size - exp_len, "UID Request (Advanced 11001)"); + snprintf(exp + strlen(exp), size - strlen(exp), "UID Request (Advanced 11001)"); break; case HITAGS_UID_REQ_FADV: - exp_len += snprintf(exp + exp_len, size - exp_len, "UID Request (Fast Advanced 11010)"); + snprintf(exp + strlen(exp), size - strlen(exp), "UID Request (Fast Advanced 11010)"); break; } } else if (nbits == 4 + 8 + 8) { concatbits(&command, 0, cmd, 0, 4, false); if (command == HITAGS_READ_PAGE) { - exp_len += snprintf(exp + exp_len, size - exp_len, "READ"); + snprintf(exp + strlen(exp), size - strlen(exp), "READ"); } else if (command == HITAGS_WRITE_PAGE) { - exp_len += snprintf(exp + exp_len, size - exp_len, "WRITE"); + snprintf(exp + strlen(exp), size - strlen(exp), "WRITE"); } else if (command == HITAGS_READ_BLOCK) { - exp_len += snprintf(exp + exp_len, size - exp_len, "READ_BLOCK"); + snprintf(exp + strlen(exp), size - strlen(exp), "READ_BLOCK"); } else if (command == HITAGS_WRITE_BLOCK) { - exp_len += snprintf(exp + exp_len, size - exp_len, "WRITE_BLOCK"); + snprintf(exp + strlen(exp), size - strlen(exp), "WRITE_BLOCK"); } else if (command == HITAGS_QUIET) { - exp_len += snprintf(exp + exp_len, size - exp_len, "QUIET"); + snprintf(exp + strlen(exp), size - strlen(exp), "QUIET"); } // Hitag 1 commands else if (command == HITAG1_RDCPAGE) { - exp_len += snprintf(exp + exp_len, size - exp_len, "RDCPAGE"); + snprintf(exp + strlen(exp), size - strlen(exp), "RDCPAGE"); } else if (command == HITAG1_RDCBLK) { - exp_len += snprintf(exp + exp_len, size - exp_len, "RDCBLK"); + snprintf(exp + strlen(exp), size - strlen(exp), "RDCBLK"); } else if (command == HITAG1_WRCPAGE) { - exp_len += snprintf(exp + exp_len, size - exp_len, "WRCPAGE"); + snprintf(exp + strlen(exp), size - strlen(exp), "WRCPAGE"); } else if (command == HITAG1_WRCBLK) { - exp_len += snprintf(exp + exp_len, size - exp_len, "WRCBLK"); + snprintf(exp + strlen(exp), size - strlen(exp), "WRCBLK"); } else { - exp_len += snprintf(exp + exp_len, size - exp_len, "Unknown (%02X)", command); + snprintf(exp + strlen(exp), size - strlen(exp), "Unknown (%02X)", command); } uint8_t page = 0; concatbits(&page, 0, cmd, 5, 8, false); - exp_len += snprintf(exp + exp_len, size - exp_len, " Page: %d", page); + snprintf(exp + strlen(exp), size - strlen(exp), " Page: %d", page); } else if (nbits == 32 + 8) { concatbits(&command, 0, cmd, 0, 5, false); - exp_len += snprintf(exp + exp_len, size - exp_len, "Data"); + snprintf(exp + strlen(exp), size - strlen(exp), "Data"); } else if (nbits == 5 + 32 + 8 || nbits == 5 + 32 + 1 + 8) { concatbits(&command, 0, cmd, 0, 5, false); if (command == HITAGS_SELECT) { uint8_t uid[4] = {0}; concatbits(uid, 0, cmd, 5, 32, false); - exp_len = snprintf(exp, size, "SELECT UID: %02X%02X%02X%02X", uid[0], uid[1], uid[2], uid[3]); + snprintf(exp, size, "SELECT UID: %02X%02X%02X%02X", uid[0], uid[1], uid[2], uid[3]); } } } else { - exp_len = snprintf(exp, size, "Invalid command (too short)"); + snprintf(exp, size, "Invalid command (too short)"); } } @@ -760,7 +765,7 @@ static int CmdLFHitagSRestore(const char *Cmd) { packet.page = page; memcpy(packet.data, &dump_bytes[offset], HITAGS_PAGE_SIZE); - PrintAndLogEx(INPLACE, " Writing page "_YELLOW_("%d")", data: " _GREEN_("%02X %02X %02X %02X"), page, + PrintAndLogEx(INPLACE, "Writing page "_YELLOW_("%d")", data: " _GREEN_("%02X %02X %02X %02X"), page, dump_bytes[offset], dump_bytes[offset + 1], dump_bytes[offset + 2], diff --git a/client/src/cmdlfhitagu.c b/client/src/cmdlfhitagu.c index b4d02ce5a..5d0ec275f 100644 --- a/client/src/cmdlfhitagu.c +++ b/client/src/cmdlfhitagu.c @@ -16,6 +16,7 @@ // Low frequency Hitag µ support //----------------------------------------------------------------------------- #include "cmdlfhitagu.h" +#include // strlen #include "cliparser.h" #include "cmddata.h" // setDemodBuff @@ -53,41 +54,41 @@ void annotateHitagU(char *exp, size_t size, const uint8_t *cmd, uint8_t cmdsize, uint8_t command = ((reflect8(cmd[0]) >> 5) & 0x07) | ((reflect8(cmd[1]) & 0x07) << 3); bool has_uid = false; - size_t exp_len = snprintf(exp, size, "Flg:"); + snprintf(exp, size, "Flg:"); if ((flag & HITAGU_FLAG_PEXT) == HITAGU_FLAG_PEXT) { - exp_len += snprintf(exp + exp_len, size - exp_len, " PEXT"); + snprintf(exp + strlen(exp), size - strlen(exp), " PEXT"); } if ((flag & HITAGU_FLAG_INV) == HITAGU_FLAG_INV) { - exp_len += snprintf(exp + exp_len, size - exp_len, " INV"); + snprintf(exp + strlen(exp), size - strlen(exp), " INV"); if ((flag & HITAGU_FLAG_RFU) == HITAGU_FLAG_RFU) { - exp_len += snprintf(exp + exp_len, size - exp_len, " RFU"); + snprintf(exp + strlen(exp), size - strlen(exp), " RFU"); } if ((flag & HITAGU_FLAG_NOS) == HITAGU_FLAG_NOS) { - exp_len += snprintf(exp + exp_len, size - exp_len, " NOS"); + snprintf(exp + strlen(exp), size - strlen(exp), " NOS"); } } else { if ((flag & HITAGU_FLAG_SEL) == HITAGU_FLAG_SEL) { - exp_len += snprintf(exp + exp_len, size - exp_len, " SEL"); + snprintf(exp + strlen(exp), size - strlen(exp), " SEL"); } if ((flag & HITAGU_FLAG_ADR) == HITAGU_FLAG_ADR) { - exp_len += snprintf(exp + exp_len, size - exp_len, " ADR"); + snprintf(exp + strlen(exp), size - strlen(exp), " ADR"); has_uid = true; } } if ((flag & HITAGU_FLAG_CRCT) == HITAGU_FLAG_CRCT) { - exp_len += snprintf(exp + exp_len, size - exp_len, " CRCT"); + snprintf(exp + strlen(exp), size - strlen(exp), " CRCT"); } - exp_len += snprintf(exp + exp_len, size - exp_len, "|Cmd: "); + snprintf(exp + strlen(exp), size - strlen(exp), "|Cmd: "); switch (command) { case HITAGU_CMD_LOGIN: { @@ -96,29 +97,29 @@ void annotateHitagU(char *exp, size_t size, const uint8_t *cmd, uint8_t cmdsize, if (cmdsize == (6 + (has_uid * HITAGU_UID_SIZE)) || cmdsize == (8 + (has_uid * HITAGU_UID_SIZE))) { - exp_len += snprintf(exp + exp_len, size - exp_len, "8265 LOGIN"); + snprintf(exp + strlen(exp), size - strlen(exp), "8265 LOGIN"); } else if (cmdsize == (7 + (has_uid * HITAGU_UID_SIZE)) || cmdsize == (9 + (has_uid * HITAGU_UID_SIZE))) { uint8_t mfc = 0; concatbits(&mfc, 0, cmd, 5 + 6 + 8 + 32, 8, false); - exp_len += snprintf(exp + exp_len, size - exp_len, "LOGIN mfc:%02x ", mfc); + snprintf(exp + strlen(exp), size - strlen(exp), "LOGIN mfc:%02x ", mfc); has_mfc = true; } if (has_uid) { uint8_t uid[HITAGU_UID_SIZE] = {0}; concatbits(uid, 0, cmd, 5 + 6 + has_mfc * 8 + 32, HITAGU_UID_SIZE * 8, false); - exp_len += snprintf(exp + exp_len, size - exp_len, " uid:%s", sprint_hex_inrow(uid, HITAGU_UID_SIZE)); + snprintf(exp + strlen(exp), size - strlen(exp), " uid:%s", sprint_hex_inrow(uid, HITAGU_UID_SIZE)); } uint8_t password[HITAG_PASSWORD_SIZE] = {0}; concatbits(password, 0, cmd, 5 + 6 + has_mfc * 8 + has_uid * HITAGU_UID_SIZE * 8, HITAG_PASSWORD_SIZE * 8, false); - exp_len += snprintf(exp + exp_len, size - exp_len, " pwd:%s", sprint_hex_inrow(password, HITAG_PASSWORD_SIZE)); + snprintf(exp + strlen(exp), size - strlen(exp), " pwd:%s", sprint_hex_inrow(password, HITAG_PASSWORD_SIZE)); break; } case HITAGU_CMD_INVENTORY: { - exp_len += snprintf(exp + exp_len, size - exp_len, "INVENTORY"); + snprintf(exp + strlen(exp), size - strlen(exp), "INVENTORY"); break; } case HITAGU_CMD_READ_MULTIPLE_BLOCK: { @@ -128,10 +129,10 @@ void annotateHitagU(char *exp, size_t size, const uint8_t *cmd, uint8_t cmdsize, uint8_t block_count = 0; concatbits(&block_count, 0, cmd, 5 + 6 + 8, 8, false); - exp_len += snprintf(exp + exp_len, size - exp_len, "READ MULTIPLE BLOCK start:%d num:%d" - , reflect8(block_addr) - , reflect8(block_count) - ); + snprintf(exp + strlen(exp), size - strlen(exp), "READ MULTIPLE BLOCK start:%d num:%d" + , reflect8(block_addr) + , reflect8(block_count) + ); break; } case HITAGU_CMD_WRITE_SINGLE_BLOCK: { @@ -141,30 +142,30 @@ void annotateHitagU(char *exp, size_t size, const uint8_t *cmd, uint8_t cmdsize, uint8_t block_data[4] = {0}; concatbits(block_data, 0, cmd, 5 + 6 + 8, 32, false); - exp_len += snprintf(exp + exp_len, size - exp_len, "WRITE SINGLE BLOCK start:%d data:[%s]" - , reflect8(block_addr) - , sprint_hex_inrow(block_data, 4) - ); + snprintf(exp + strlen(exp), size - strlen(exp), "WRITE SINGLE BLOCK start:%d data:[%s]" + , reflect8(block_addr) + , sprint_hex_inrow(block_data, 4) + ); break; } case HITAGU_CMD_SELECT: { - exp_len += snprintf(exp + exp_len, size - exp_len, "SELECT"); + snprintf(exp + strlen(exp), size - strlen(exp), "SELECT"); break; } case HITAGU_CMD_SYSINFO: { - exp_len += snprintf(exp + exp_len, size - exp_len, "GET SYSTEM INFORMATION"); + snprintf(exp + strlen(exp), size - strlen(exp), "GET SYSTEM INFORMATION"); break; } case HITAGU_CMD_READ_UID: { - exp_len += snprintf(exp + exp_len, size - exp_len, "READ UID"); + snprintf(exp + strlen(exp), size - strlen(exp), "READ UID"); break; } case HITAGU_CMD_STAY_QUIET: { - exp_len += snprintf(exp + exp_len, size - exp_len, "STAY QUIET"); + snprintf(exp + strlen(exp), size - strlen(exp), "STAY QUIET"); break; } default: { - exp_len += snprintf(exp + exp_len, size - exp_len, "Unknown 0x%02X", command); + snprintf(exp + strlen(exp), size - strlen(exp), "Unknown 0x%02X", command); break; } } diff --git a/client/src/cmdlfidteck.c b/client/src/cmdlfidteck.c index 9fbe6a490..c697cbe75 100644 --- a/client/src/cmdlfidteck.c +++ b/client/src/cmdlfidteck.c @@ -33,7 +33,6 @@ #include "protocols.h" // T55x7 defines #include "cmdlft55xx.h" // verifywrite #include "generator.h" -#include "wiegand_formats.h" static int CmdHelp(const char *Cmd); @@ -104,13 +103,14 @@ int demodIdteck(uint8_t *raw, bool verbose) { raw2 = bytes_to_num(raw + 4, 4); } - // got a good demod - uint32_t id = 0; - if (raw1 != 0x4944544B) { PrintAndLogEx(FAILED, "No genuine IDTECK found"); + return PM3_ESOFT; } + // got a good demod + uint32_t id = 0; + // parity check (TBD) uint32_t tmp = raw2; @@ -135,13 +135,6 @@ int demodIdteck(uint8_t *raw, bool verbose) { (chksum == calc) ? _GREEN_("ok") : _RED_("fail") ); - wiegand_message_t packed = { - .Bot = id, - .Mid = 0, - .Top = 0, - .Length = 26 - }; - HIDUnpack(0, &packed); return PM3_SUCCESS; } @@ -163,7 +156,8 @@ static int CmdIdteckDemod(const char *Cmd) { uint8_t raw[8] = {0}; CLIGetHexWithReturn(ctx, 1, raw, &raw_len); CLIParserFree(ctx); - return demodIdteck(raw, true); + // no --raw given, demod the graphbuffer instead + return demodIdteck((raw_len == 0) ? NULL : raw, true); } static int CmdIdteckClone(const char *Cmd) { diff --git a/client/src/cmdlfindala.c b/client/src/cmdlfindala.c index 6aee29b6f..2843b43cf 100644 --- a/client/src/cmdlfindala.c +++ b/client/src/cmdlfindala.c @@ -1344,7 +1344,7 @@ out: *size = found_size; if (found_size < 64) { - PrintAndLogEx(INFO, "DEBUG: detectindala | %zu", found_size); + PrintAndLogEx(DEBUG, "DEBUG: detectindala | %zu", found_size); return -5; } diff --git a/client/src/cmdlft55xx.c b/client/src/cmdlft55xx.c index 278035352..cb97a52b3 100644 --- a/client/src/cmdlft55xx.c +++ b/client/src/cmdlft55xx.c @@ -61,6 +61,8 @@ static bool t55xx_psk3_probe(bool usepwd, uint32_t password, uint8_t downlink_mo static uint8_t t55xx_measure_broadcast_blocks(bool usepwd, uint32_t password, uint8_t downlink_mode); static uint8_t t55xx_measure_broadcast_blocks_once(bool usepwd, uint32_t password, uint8_t downlink_mode); static size_t t55xx_psk3_resolve(uint8_t nblk, uint32_t *only); +static bool t55xx_block0_rotation_ambiguous(void); +static bool t55xx_resolve_block0_rotation(uint8_t nblk); // Default configuration static t55xx_conf_block_t config = { @@ -80,6 +82,13 @@ static t55xx_memory_item_t cardmem[T55x7_BLOCK_COUNT] = {{0}}; // Regular read mode cycles several blocks and a buffer loaded from a file could be either static bool s_block_read_capture = false; +// samples dropped from the head of a capture before psk demodulation +#define T55XX_PSK_SETTLE_TRIM 160 + +// non-zero while the capture is trimmed, so an anchor recorded inside the trim +// still names an untrimmed sample +static int32_t s_sample_bias = 0; + // A block read repeats one 32 bit word for as long as the field is on. // `offset` is a bit index into a demod buffer that no longer exists once the next acquisition lands, // and the demodulators do not all start on the same bit: @@ -88,16 +97,34 @@ static bool s_block_read_capture = false; static void t55xx_anchor(t55xx_conf_block_t *c, uint8_t offset) { c->offset = offset; c->anchor_valid = (g_DemodClock > 0); - c->anchor_sample = g_DemodStartIdx + ((int32_t)offset * g_DemodClock); - c->anchor_tracelen = (int32_t)g_GraphTraceLen; + c->anchor_sample = g_DemodStartIdx + ((int32_t)offset * g_DemodClock) + s_sample_bias; + c->anchor_tracelen = (int32_t)g_GraphTraceLen + s_sample_bias; } // records a detect candidate against the demodulation that is loaded right now static void t55xx_record_hit(t55xx_conf_block_t *t) { t->block0 = PackBits(t->offset, 32, g_DemodBuffer); t->anchor_valid = (g_DemodClock > 0); - t->anchor_sample = g_DemodStartIdx + ((int32_t)t->offset * g_DemodClock); - t->anchor_tracelen = (int32_t)g_GraphTraceLen; + t->anchor_sample = g_DemodStartIdx + ((int32_t)t->offset * g_DemodClock) + s_sample_bias; + t->anchor_tracelen = (int32_t)g_GraphTraceLen + s_sample_bias; +} + +// skip first 160 samples to allow antenna to settle in (psk gets inverted occasionally otherwise) +static buffer_savestate_t t55xx_psk_trim_head(void) { + buffer_savestate_t st = save_graphbuffer(); + + char ltrim[16]; + snprintf(ltrim, sizeof(ltrim), "-i %d", T55XX_PSK_SETTLE_TRIM); + CmdLtrim(ltrim); + + s_sample_bias = T55XX_PSK_SETTLE_TRIM; + return st; +} + +static void t55xx_psk_untrim_head(buffer_savestate_t st) { + s_sample_bias = 0; + restore_graphbuffer(st); + free_buffer_savestate(st); } // the bit offset to read a block at in the demod buffer loaded right now @@ -794,17 +821,22 @@ int T55xxReadBlockEx(uint8_t block, bool page1, bool usepwd, uint8_t override, u // override = 1 (override and display) // override = 2 (override and no display) if (override == 0) { - if (AcquireData(T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, false, 0, downlink_mode) == false) - return PM3_ERFTRANS; + // A live detect (lf t55xx detect -p) that recovered this password already confirmed the PWD bit is set. + bool detect_confirmed_pwd = (config.pwd_known && config.usepwd && config.pwd == password); - if (t55xxTryDetectModulationEx(downlink_mode, false, 0, password) == false) { - PrintAndLogEx(WARNING, "Safety check: Could not detect if PWD bit is set in config block. Exits."); - PrintAndLogEx(HINT, "Hint: Consider using the override parameter to force read."); - return PM3_EWRONGANSWER; - } else { - PrintAndLogEx(WARNING, "Safety check: PWD bit is NOT set in config block. Reading without password..."); - usepwd = false; - page1 = false; // ?? + if (detect_confirmed_pwd == false) { + if (AcquireData(T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, false, 0, downlink_mode) == false) + return PM3_ERFTRANS; + + if (t55xxTryDetectModulationEx(downlink_mode, false, 0, password) == false) { + PrintAndLogEx(WARNING, "Safety check: Could not detect if PWD bit is set in config block. Exits."); + PrintAndLogEx(HINT, "Hint: Consider using the override parameter to force read."); + return PM3_EWRONGANSWER; + } else { + PrintAndLogEx(WARNING, "Safety check: PWD bit is NOT set in config block. Reading without password..."); + usepwd = false; + page1 = false; + } } } else if (override == 1) { PrintAndLogEx(INFO, "Safety check overridden - proceeding despite risk"); @@ -1059,19 +1091,24 @@ static int CmdT55xxWakeUp(const char *Cmd) { static int CmdT55xxDetect(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "lf t55xx detect", - "Try detecting the tag modulation from reading the configuration block", + "Try detecting the tag modulation from reading the configuration block.\n\n" + _RED_(" * * * WARNING * * *") "\n" + _CYAN_("Use of detect with password on a tag not configured") "\n" + _CYAN_("for a password can damage the tag") "\n" + _RED_(" * * * * * * * * * *"), "lf t55xx detect\n" "lf t55xx detect -1\n" - "lf t55xx detect -p 11223344\n" + "lf t55xx detect -p 11223344 -o\n" ); - // 1 (help) + 2 (two user specified params) + (6 T55XX_DLMODE_ALL) - void *argtable[3 + 6] = { + // 1 (help) + 3 (three user specified params) + (6 T55XX_DLMODE_ALL) + void *argtable[4 + 6] = { arg_param_begin, arg_lit0("1", NULL, "extract using data from graphbuffer"), arg_str0("p", "pwd", "", "password (4 hex bytes)"), + arg_lit0("o", "override", "override safety check"), }; - uint8_t idx = 3; + uint8_t idx = 4; arg_add_t55xx_downloadlink(argtable, &idx, T55XX_DLMODE_ALL, config.downlink_mode); CLIExecWithReturn(ctx, Cmd, argtable, true); @@ -1091,11 +1128,13 @@ static int CmdT55xxDetect(const char *Cmd) { password = tmp_pwd; } - bool r0 = arg_get_lit(ctx, 3); - bool r1 = arg_get_lit(ctx, 4); - bool r2 = arg_get_lit(ctx, 5); - bool r3 = arg_get_lit(ctx, 6); - bool ra = arg_get_lit(ctx, 7); + bool override = arg_get_lit(ctx, 3); + + bool r0 = arg_get_lit(ctx, 4); + bool r1 = arg_get_lit(ctx, 5); + bool r2 = arg_get_lit(ctx, 6); + bool r3 = arg_get_lit(ctx, 7); + bool ra = arg_get_lit(ctx, 8); CLIParserFree(ctx); if ((r0 + r1 + r2 + r3 + ra) > 1) { @@ -1103,6 +1142,14 @@ static int CmdT55xxDetect(const char *Cmd) { return PM3_EINVARG; } + // A password frame on an unprotected tag can land as a write, and detect cannot + // check the PWD bit first the way read does -- finding the config is its job. + if (usepwd && (override == false)) { + PrintAndLogEx(WARNING, "Safety check: Could not confirm PWD bit is set. Detecting without password..."); + PrintAndLogEx(HINT, "Hint: Consider using the override parameter to force detect with password."); + usepwd = false; + } + bool try_all_dl_modes = false; uint8_t downlink_mode = config.downlink_mode; if (r0) @@ -1247,6 +1294,22 @@ static int CmdT55xxDetect(const char *Cmd) { } } + // Several rotations of the word can read as a configuration and detect takes the first the + // scan reaches. The broadcast period is the tag's own answer to which is real + bool rerotated = false; + + if (found && use_gb == false && t55xx_block0_rotation_ambiguous()) { + + if (nblk == 0) { + nblk = t55xx_measure_broadcast_blocks(config.usepwd, config.pwd, config.downlink_mode); + config.broadcast_blocks = nblk; + } + + if (nblk) { + rerotated = t55xx_resolve_block0_rotation(nblk); + } + } + if (found) { printConfiguration(config); @@ -1255,6 +1318,10 @@ static int CmdT55xxDetect(const char *Cmd) { PrintAndLogEx(SUCCESS, "Broadcast repeats every " _GREEN_("%u") " block(s), so maxblock is a multiple of %u", nblk, nblk); } + if (rerotated) { + PrintAndLogEx(SUCCESS, "Block 0 " _GREEN_("re-anchored") " - the first reading was a rotation the broadcast period contradicts"); + } + if (psk2_out) { PrintAndLogEx(SUCCESS, "psk2 " _RED_("ruled out") " - the psk2 reading of block 0 carries a maxblock contradicted by the broadcast"); } else if (favoured) { @@ -1595,9 +1662,7 @@ static bool t55xx_fallback_try(pm3_mod_t mod, pm3_enc_t enc, int fc_hi, int fc_l if (mod == PM3_MOD_PSK) { - buffer_savestate_t saveState = save_bufferS32(g_GraphBuffer, g_GraphTraceLen); - saveState.offset = g_GridOffset; - CmdLtrim("-i 160"); + buffer_savestate_t saveState = t55xx_psk_trim_head(); for (int inv = 0; inv < 2; inv++) { if (PSKDemod(fitclk, inv, PM3_T55_FALLBACK_MAXERR, false) != PM3_SUCCESS) { @@ -1631,8 +1696,7 @@ static bool t55xx_fallback_try(pm3_mod_t mod, pm3_enc_t enc, int fc_hi, int fc_l } } - restore_bufferS32(saveState, g_GraphBuffer); - g_GridOffset = saveState.offset; + t55xx_psk_untrim_head(saveState); if (*hits == before && coherent_ok) { t55xx_psk_coherent(fitclk, clk, tests, hits, downlink_mode); @@ -1980,10 +2044,7 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 clk = GetPskClock("", false); if (clk > 0) { // allow undo - buffer_savestate_t saveState = save_bufferS32(g_GraphBuffer, g_GraphTraceLen); - saveState.offset = g_GridOffset; - // skip first 160 samples to allow antenna to settle in (psk gets inverted occasionally otherwise) - CmdLtrim("-i 160"); + buffer_savestate_t saveState = t55xx_psk_trim_head(); if ((PSKDemod(0, 0, 6, false) == PM3_SUCCESS) && test(DEMOD_PSK1, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)) { tests[hits].modulation = DEMOD_PSK1; tests[hits].bitrate = bitRate; @@ -2019,8 +2080,7 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 } // inverse waves does not affect this demod //undo trim samples - restore_bufferS32(saveState, g_GraphBuffer); - g_GridOffset = saveState.offset; + t55xx_psk_untrim_head(saveState); // t55xx_search_config_psk(g_GraphBuffer, 1); // t55xx_search_config_psk(g_GraphBuffer, 2); } @@ -2565,6 +2625,167 @@ static void windows_build(t55_windows_t *w) { } } +// the checks a 32 bit word has to pass to be a configuration block for `mode` at +// `clk`, independent of where in a demodulation it was found +static bool t55xx_block0_plausible(uint32_t block0, uint8_t mode, uint8_t clk, int *fndBitRate) { + + uint8_t safer = (block0 >> 28) & 0x0F; //master key + uint8_t resv = (block0 >> 24) & 0x0F; //was 7 // should be only 4 bits if extended mode + // 2nibble must be zeroed. + + if (resv > 0x00) { + return false; + } + + // The master key is 0, or 6 or 9 to select extended mode + if (safer != 0x0 && safer != 0x6 && safer != 0x9) { + return false; + } + + int bitRate = (block0 >> 18) & 0x3F; //bit rate (includes extended mode part of rate) + uint8_t extend = (block0 >> 17) & 0x01; //bit 15 extended mode + uint8_t modread = (block0 >> 12) & 0x1F; + //pskcr = (block0 >> 10) & 0x03; //could check psk cr + //bit 24, 30, 31 are otp, fast write and inverse data - all settable, so no help here + + // Bit 14 selects extended mode, and extended mode only exists under master key 6 or 9. + // Set with any other key the word is not a valid configuration + if (extend && safer != 0x6 && safer != 0x9) { + return false; + } + + //if extended mode + bool extMode = ((safer == 0x6 || safer == 0x9) && extend) ? true : false; + + if (extMode == false) { + + if (bitRate > 7) { + return false; + } + + if (testBitRate(bitRate, clk) == false) { + return false; + } + + } else { //extended mode bitrate = same function to calc bitrate as em4x05 + if (EM4x05_GET_BITRATE(bitRate) != clk) { + return false; + } + } + + //test modulation + if (testModulation(mode, modread) == false) { + return false; + } + + if (fndBitRate) { + *fndBitRate = bitRate; + } + return true; +} + +// true when the maxblock and sequence terminator in `block0` could have produced +// an `nblk` block broadcast period +static bool t55xx_block0_fits_period(uint32_t block0, uint8_t nblk) { + + // ST adds four bit periods per cycle, so a whole number of 32 + // bit blocks rules it out. leans on the measurement, not on + // config.ST, which the psk paths hardcode rather than detect + if (((block0 >> 3) & 1) != 0) { + return false; + } + + const uint8_t mb = (block0 >> 5) & 0x07; + return (mb != 0 && (mb % nblk) == 0); +} + +// how many distinct rotations of `block0` read as a configuration for `mode` at `clk`. more than +// one means detect's answer was scan order, not evidence. `nblk` 0 skips the period constraint +static size_t t55xx_block0_rotations(uint32_t block0, uint8_t mode, uint8_t clk, uint8_t nblk, uint32_t *only) { + + uint32_t seen[32] = {0}; + size_t n = 0; + + for (uint8_t r = 0; r < 32; r++) { + + const uint32_t v = (r == 0) ? block0 : ((block0 << r) | (block0 >> (32 - r))); + + if (t55xx_block0_plausible(v, mode, clk, NULL) == false) { + continue; + } + + if (nblk != 0 && t55xx_block0_fits_period(v, nblk) == false) { + continue; + } + + // a word that is its own rotation offers the same value twice + bool dup = false; + for (size_t i = 0; i < n; i++) { + if (seen[i] == v) { + dup = true; + break; + } + } + if (dup) { + continue; + } + + seen[n++] = v; + } + + if (n == 1 && only != NULL) { + *only = seen[0]; + } + return n; +} + +// the clock the detected bit rate names, for the rotation helpers above +static uint8_t t55xx_config_clock(void) { + static const uint8_t basic[] = {8, 16, 32, 40, 50, 64, 100, 128}; + return basic[config.bitrate & 0x07]; +} + +// more than one rotation of the detected block 0 reads as a configuration +static bool t55xx_block0_rotation_ambiguous(void) { + + if (config.Q5 || config.block0 == 0) { + return false; + } + + return (t55xx_block0_rotations(config.block0, config.modulation, t55xx_config_clock(), 0, NULL) > 1); +} + +// Settle which rotation is real with the tag's own broadcast period and re-anchor on it. Nothing +// surviving means the measurement disagrees with every reading, so leave the detected word alone +static bool t55xx_resolve_block0_rotation(uint8_t nblk) { + + uint32_t only = 0; + if (t55xx_block0_rotations(config.block0, config.modulation, t55xx_config_clock(), nblk, &only) != 1) { + return false; + } + + if (only == config.block0) { + return false; + } + + // measuring the period left a regular read in the demod buffer + if (AcquireData(T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, config.usepwd, config.pwd, config.downlink_mode) == false) { + return false; + } + + if (DecodeT55xxBlock() == false) { + return false; + } + + if (t55xx_stream_holds(only) == false) { + return false; + } + + // keep the offset t55xx_stream_holds just anchored + SetConfigWithBlock0Ex(only, config.offset, config.Q5); + return true; +} + static bool test_scan(uint8_t mode, uint8_t *offset, int *fndBitRate, uint8_t clk, uint16_t start, uint16_t end, const t55_windows_t *w, uint16_t need, bool need_stride) { @@ -2581,58 +2802,8 @@ static bool test_scan(uint8_t mode, uint8_t *offset, int *fndBitRate, uint8_t cl continue; } - uint8_t safer = PackBits(si, 4, g_DemodBuffer); - si += 4; //master key - uint8_t resv = PackBits(si, 4, g_DemodBuffer); - si += 4; //was 7 & +=7+3 // should be only 4 bits if extended mode - // 2nibble must be zeroed. - - if (resv > 0x00) { - continue; - } - - // The master key is 0, or 6 or 9 to select extended mode - if (safer != 0x0 && safer != 0x6 && safer != 0x9) { - continue; - } - - int bitRate = PackBits(si, 6, g_DemodBuffer); - si += 6; //bit rate (includes extended mode part of rate) - uint8_t extend = PackBits(si, 1, g_DemodBuffer); - si += 1; //bit 15 extended mode - uint8_t modread = PackBits(si, 5, g_DemodBuffer); - si += 5 + 2 + 1; - //uint8_t pskcr = PackBits(si, 2, g_DemodBuffer); si += 2+1; //could check psk cr - //uint8_t nml01 = PackBits(si, 1, g_DemodBuffer); si += 1+5; //bit 24, 30, 31 could be tested for 0 if not extended mode - //uint8_t nml02 = PackBits(si, 2, g_DemodBuffer); si += 2; - - // Bit 14 selects extended mode, and extended mode only exists under master key 6 or 9. - // Set with any other key the word is not a valid configuration - if (extend && safer != 0x6 && safer != 0x9) { - continue; - } - - //if extended mode - bool extMode = ((safer == 0x6 || safer == 0x9) && extend) ? true : false; - - if (extMode == false) { - - if (bitRate > 7) { - continue; - } - - if (testBitRate(bitRate, clk) == false) { - continue; - } - - } else { //extended mode bitrate = same function to calc bitrate as em4x05 - if (EM4x05_GET_BITRATE(bitRate) != clk) { - continue; - } - } - - //test modulation - if (testModulation(mode, modread) == false) { + int bitRate = 0; + if (t55xx_block0_plausible(PackBits(si, 32, g_DemodBuffer), mode, clk, &bitRate) == false) { continue; } @@ -2910,14 +3081,7 @@ int printConfiguration(t55xx_conf_block_t b) { if (b.broadcast_blocks) { size_t kept = 0; for (size_t i = 0; i < ncand; i++) { - const uint8_t mb = (cand[i] >> 5) & 0x07; - // ST adds four bit periods per cycle, so a whole number of 32 - // bit blocks rules it out. leans on the measurement, not on - // config.ST, which the psk paths hardcode rather than detect - if (((cand[i] >> 3) & 1) != 0) { - continue; - } - if (mb != 0 && (mb % b.broadcast_blocks) == 0) { + if (t55xx_block0_fits_period(cand[i], b.broadcast_blocks)) { cand[kept++] = cand[i]; } } @@ -4957,13 +5121,37 @@ out: return PM3_SUCCESS; } -// note length of data returned is different for different chips. -// some return all page 1 (64 bits) and others return just that block (32 bits) -// unfortunately the 64 bits makes this more likely to get a false positive... -bool tryDetectP1(bool getData) { - uint8_t preamble_atmel[] = {1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1}; +// Page-1 trace data opens with allocation class ACL = 0xE0, then a manufacturer code. +// Genuine Atmel silicon carries manufacturer 0x15 / 0x39 (the atmel / silicon preambles). +// Cloned T5577s keep the 0xE0 ACL but use another manufacturer byte, +// also accept a bare 8-bit ACL match +static bool t55xx_trace_preamble_match(void) { + uint8_t preamble_atmel[] = {1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1}; uint8_t preamble_silicon[] = {1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1}; + uint8_t preamble_acl[] = {1, 1, 1, 0, 0, 0, 0, 0}; size_t startIdx = 0; + + if (preambleSearchEx(g_DemodBuffer, preamble_atmel, sizeof(preamble_atmel), &g_DemodBufferLen, &startIdx, false) && + (g_DemodBufferLen == 32 || g_DemodBufferLen == 64)) { + return true; + } + + startIdx = 0; + if (preambleSearchEx(g_DemodBuffer, preamble_silicon, sizeof(preamble_silicon), &g_DemodBufferLen, &startIdx, false) && + (g_DemodBufferLen == 32 || g_DemodBufferLen == 64)) { + return true; + } + + startIdx = 0; + if (preambleSearchEx(g_DemodBuffer, preamble_acl, sizeof(preamble_acl), &g_DemodBufferLen, &startIdx, false) && + (g_DemodBufferLen == 32 || g_DemodBufferLen == 64)) { + return true; + } + + return false; +} + +bool tryDetectP1(bool getData) { uint8_t fc1 = 0, fc2 = 0, ans = 0; int clk = 0, firstClockEdge = 0; bool st = true; @@ -4973,30 +5161,18 @@ bool tryDetectP1(bool getData) { return false; } - // try fsk clock detect. if successful it cannot be any other type of modulation... (in theory...) + // try fsk clock detect. if successful it cannot be any other type of modulation. ans = fskClocks(&fc1, &fc2, (uint8_t *)&clk, &firstClockEdge); if (ans && ((fc1 == 10 && fc2 == 8) || (fc1 == 8 && fc2 == 5))) { if (FSKrawDemod(0, 0, 0, 0, false) == PM3_SUCCESS) { - if (preambleSearchEx(g_DemodBuffer, preamble_atmel, sizeof(preamble_atmel), &g_DemodBufferLen, &startIdx, false) && - (g_DemodBufferLen == 32 || g_DemodBufferLen == 64)) { - return true; - } - - if (preambleSearchEx(g_DemodBuffer, preamble_silicon, sizeof(preamble_silicon), &g_DemodBufferLen, &startIdx, false) && - (g_DemodBufferLen == 32 || g_DemodBufferLen == 64)) { + if (t55xx_trace_preamble_match()) { return true; } } if (FSKrawDemod(0, 1, 0, 0, false) == PM3_SUCCESS) { - if (preambleSearchEx(g_DemodBuffer, preamble_atmel, sizeof(preamble_atmel), &g_DemodBufferLen, &startIdx, false) && - (g_DemodBufferLen == 32 || g_DemodBufferLen == 64)) { - return true; - } - - if (preambleSearchEx(g_DemodBuffer, preamble_silicon, sizeof(preamble_silicon), &g_DemodBufferLen, &startIdx, false) && - (g_DemodBufferLen == 32 || g_DemodBufferLen == 64)) { + if (t55xx_trace_preamble_match()) { return true; } } @@ -5008,113 +5184,60 @@ bool tryDetectP1(bool getData) { if (clk > 0) { if (ASKDemod_ext(0, 0, 1, 0, false, false, false, 1, &st) == PM3_SUCCESS) { - if (preambleSearchEx(g_DemodBuffer, preamble_atmel, sizeof(preamble_atmel), &g_DemodBufferLen, &startIdx, false) && - (g_DemodBufferLen == 32 || g_DemodBufferLen == 64)) { - return true; - } - - if (preambleSearchEx(g_DemodBuffer, preamble_silicon, sizeof(preamble_silicon), &g_DemodBufferLen, &startIdx, false) && - (g_DemodBufferLen == 32 || g_DemodBufferLen == 64)) { + if (t55xx_trace_preamble_match()) { return true; } } st = true; if (ASKDemod_ext(0, 1, 1, 0, false, false, false, 1, &st) == PM3_SUCCESS) { - if (preambleSearchEx(g_DemodBuffer, preamble_atmel, sizeof(preamble_atmel), &g_DemodBufferLen, &startIdx, false) && - (g_DemodBufferLen == 32 || g_DemodBufferLen == 64)) { - return true; - } - - if (preambleSearchEx(g_DemodBuffer, preamble_silicon, sizeof(preamble_silicon), &g_DemodBufferLen, &startIdx, false) && - (g_DemodBufferLen == 32 || g_DemodBufferLen == 64)) { + if (t55xx_trace_preamble_match()) { return true; } } if (ASKbiphaseDemod(0, 0, 0, 2, false) == PM3_SUCCESS) { - if (preambleSearchEx(g_DemodBuffer, preamble_atmel, sizeof(preamble_atmel), &g_DemodBufferLen, &startIdx, false) && - (g_DemodBufferLen == 32 || g_DemodBufferLen == 64)) { - return true; - } - - if (preambleSearchEx(g_DemodBuffer, preamble_silicon, sizeof(preamble_silicon), &g_DemodBufferLen, &startIdx, false) && - (g_DemodBufferLen == 32 || g_DemodBufferLen == 64)) { + if (t55xx_trace_preamble_match()) { return true; } } if (ASKbiphaseDemod(0, 0, 1, 2, false) == PM3_SUCCESS) { - if (preambleSearchEx(g_DemodBuffer, preamble_atmel, sizeof(preamble_atmel), &g_DemodBufferLen, &startIdx, false) && - (g_DemodBufferLen == 32 || g_DemodBufferLen == 64)) { - return true; - } - - if (preambleSearchEx(g_DemodBuffer, preamble_silicon, sizeof(preamble_silicon), &g_DemodBufferLen, &startIdx, false) && - (g_DemodBufferLen == 32 || g_DemodBufferLen == 64)) { + if (t55xx_trace_preamble_match()) { return true; } } } // try NRZ clock detect. it could be another type even if successful. - clk = GetNrzClock("", false); //has the most false positives :( + clk = GetNrzClock("", false); // has the most false positives if (clk > 0) { if (NRZrawDemod(0, 0, 1, false) == PM3_SUCCESS) { - if (preambleSearchEx(g_DemodBuffer, preamble_atmel, sizeof(preamble_atmel), &g_DemodBufferLen, &startIdx, false) && - (g_DemodBufferLen == 32 || g_DemodBufferLen == 64)) { - return true; - } - - if (preambleSearchEx(g_DemodBuffer, preamble_silicon, sizeof(preamble_silicon), &g_DemodBufferLen, &startIdx, false) && - (g_DemodBufferLen == 32 || g_DemodBufferLen == 64)) { + if (t55xx_trace_preamble_match()) { return true; } } if (NRZrawDemod(0, 1, 1, false) == PM3_SUCCESS) { - if (preambleSearchEx(g_DemodBuffer, preamble_atmel, sizeof(preamble_atmel), &g_DemodBufferLen, &startIdx, false) && - (g_DemodBufferLen == 32 || g_DemodBufferLen == 64)) { - return true; - } - - if (preambleSearchEx(g_DemodBuffer, preamble_silicon, sizeof(preamble_silicon), &g_DemodBufferLen, &startIdx, false) && - (g_DemodBufferLen == 32 || g_DemodBufferLen == 64)) { + if (t55xx_trace_preamble_match()) { return true; } } } // Fewer card uses PSK - // try psk clock detect. if successful it cannot be any other type of modulation... (in theory...) + // try psk clock detect. if successful it cannot be any other type of modulation. clk = GetPskClock("", false); if (clk > 0) { - // allow undo - // save_restoreGB(GRAPH_SAVE); - // skip first 160 samples to allow antenna to settle in (psk gets inverted occasionally otherwise) - //CmdLtrim("-i 160"); - if (PSKDemod(0, 0, 6, false) == PM3_SUCCESS) { - //save_restoreGB(GRAPH_RESTORE); - if (preambleSearchEx(g_DemodBuffer, preamble_atmel, sizeof(preamble_atmel), &g_DemodBufferLen, &startIdx, false) && - (g_DemodBufferLen == 32 || g_DemodBufferLen == 64)) { - return true; - } - if (preambleSearchEx(g_DemodBuffer, preamble_silicon, sizeof(preamble_silicon), &g_DemodBufferLen, &startIdx, false) && - (g_DemodBufferLen == 32 || g_DemodBufferLen == 64)) { + if (PSKDemod(0, 0, 6, false) == PM3_SUCCESS) { + if (t55xx_trace_preamble_match()) { return true; } } if (PSKDemod(0, 1, 6, false) == PM3_SUCCESS) { - //save_restoreGB(GRAPH_RESTORE); - if (preambleSearchEx(g_DemodBuffer, preamble_atmel, sizeof(preamble_atmel), &g_DemodBufferLen, &startIdx, false) && - (g_DemodBufferLen == 32 || g_DemodBufferLen == 64)) { - return true; - } - - if (preambleSearchEx(g_DemodBuffer, preamble_silicon, sizeof(preamble_silicon), &g_DemodBufferLen, &startIdx, false) && - (g_DemodBufferLen == 32 || g_DemodBufferLen == 64)) { + if (t55xx_trace_preamble_match()) { return true; } } @@ -5123,19 +5246,11 @@ bool tryDetectP1(bool getData) { if (PSKDemod(0, 0, 6, false) == PM3_SUCCESS) { psk1TOpsk2(g_DemodBuffer, g_DemodBufferLen); - //save_restoreGB(GRAPH_RESTORE); - if (preambleSearchEx(g_DemodBuffer, preamble_atmel, sizeof(preamble_atmel), &g_DemodBufferLen, &startIdx, false) && - (g_DemodBufferLen == 32 || g_DemodBufferLen == 64)) { - return true; - } - - if (preambleSearchEx(g_DemodBuffer, preamble_silicon, sizeof(preamble_silicon), &g_DemodBufferLen, &startIdx, false) && - (g_DemodBufferLen == 32 || g_DemodBufferLen == 64)) { + if (t55xx_trace_preamble_match()) { return true; } } // inverse waves does not affect PSK2 demod - //undo trim samples - //save_restoreGB(GRAPH_RESTORE); + // no other modulation clocks = 2 or 4 so quit searching if (fc1 != 8) { return false; diff --git a/client/src/cmdlfti.c b/client/src/cmdlfti.c index 17d843a7c..99d0a237f 100644 --- a/client/src/cmdlfti.c +++ b/client/src/cmdlfti.c @@ -89,8 +89,7 @@ int demodTI(bool verbose) { 1, 1, 1, 1, 1, 1, 1, 1 }; - buffer_savestate_t saveState = save_bufferS32(g_GraphBuffer, g_GraphTraceLen); - saveState.offset = g_GridOffset; + buffer_savestate_t saveState = save_graphbuffer(); int lowLen = ARRAYLEN(LowTone); int highLen = ARRAYLEN(HighTone); @@ -101,6 +100,7 @@ int demodTI(bool verbose) { int retval = PM3_ESOFT; if (g_GraphTraceLen < convLen) { + free_buffer_savestate(saveState); return retval; } for (i = 0; i < g_GraphTraceLen - convLen; i++) { @@ -278,10 +278,10 @@ int demodTI(bool verbose) { out: if (retval != PM3_SUCCESS) { - restore_bufferS32(saveState, g_GraphBuffer); - g_GridOffset = saveState.offset; + restore_graphbuffer(saveState); } + free_buffer_savestate(saveState); return retval; } diff --git a/client/src/cmdlfvisa2000.c b/client/src/cmdlfvisa2000.c index 092f38e30..f4eca3123 100644 --- a/client/src/cmdlfvisa2000.c +++ b/client/src/cmdlfvisa2000.c @@ -84,8 +84,7 @@ static uint8_t visa_parity(uint32_t id) { //see ASKDemod for what args are accepted int demodVisa2k(bool verbose) { (void) verbose; // unused so far - buffer_savestate_t saveState = save_bufferS32(g_GraphBuffer, g_GraphTraceLen); - saveState.offset = g_GridOffset; + buffer_savestate_t saveState = save_graphbuffer(); //CmdAskEdgeDetect(""); @@ -93,8 +92,8 @@ int demodVisa2k(bool verbose) { bool st = true; if (ASKDemod_ext(64, 0, 0, 0, false, false, false, 1, &st) != PM3_SUCCESS) { PrintAndLogEx(DEBUG, "DEBUG: Error - Visa2k: ASK/Manchester Demod failed"); - restore_bufferS32(saveState, g_GraphBuffer); - g_GridOffset = saveState.offset; + restore_graphbuffer(saveState); + free_buffer_savestate(saveState); return PM3_ESOFT; } size_t size = g_DemodBufferLen; @@ -109,8 +108,8 @@ int demodVisa2k(bool verbose) { else PrintAndLogEx(DEBUG, "DEBUG: Error - Visa2k: ans: %d", ans); - restore_bufferS32(saveState, g_GraphBuffer); - g_GridOffset = saveState.offset; + restore_graphbuffer(saveState); + free_buffer_savestate(saveState); return PM3_ESOFT; } setDemodBuff(g_DemodBuffer, 96, ans); @@ -128,8 +127,8 @@ int demodVisa2k(bool verbose) { // test checksums if (chk != calc) { PrintAndLogEx(DEBUG, "DEBUG: error: Visa2000 checksum (%s) %x - %x\n", _RED_("fail"), chk, calc); - restore_bufferS32(saveState, g_GraphBuffer); - g_GridOffset = saveState.offset; + restore_graphbuffer(saveState); + free_buffer_savestate(saveState); return PM3_ESOFT; } // parity @@ -137,11 +136,12 @@ int demodVisa2k(bool verbose) { uint8_t chk_par = (raw3 & 0xFF0) >> 4; if (calc_par != chk_par) { PrintAndLogEx(DEBUG, "DEBUG: error: Visa2000 parity (%s) %x - %x\n", _RED_("fail"), chk_par, calc_par); - restore_bufferS32(saveState, g_GraphBuffer); - g_GridOffset = saveState.offset; + restore_graphbuffer(saveState); + free_buffer_savestate(saveState); return PM3_ESOFT; } PrintAndLogEx(SUCCESS, "Visa2000 - Card " _GREEN_("%u") ", Raw: %08X%08X%08X", raw2, raw1, raw2, raw3); + free_buffer_savestate(saveState); return PM3_SUCCESS; } diff --git a/client/src/cmdlfzx8211.c b/client/src/cmdlfzx8211.c index 793cc3d54..7e2352418 100644 --- a/client/src/cmdlfzx8211.c +++ b/client/src/cmdlfzx8211.c @@ -41,8 +41,7 @@ static int CmdHelp(const char *Cmd); // see ASKDemod for what args are accepted int demodzx(bool verbose) { (void) verbose; // unused so far - buffer_savestate_t saveState = save_bufferS32(g_GraphBuffer, g_GraphTraceLen); - saveState.offset = g_GridOffset; + buffer_savestate_t saveState = save_graphbuffer(); // CmdAskEdgeDetect(""); @@ -50,8 +49,8 @@ int demodzx(bool verbose) { bool st = true; if (ASKDemod_ext(64, 0, 0, 0, false, false, false, 1, &st) != PM3_SUCCESS) { PrintAndLogEx(DEBUG, "DEBUG: Error - ZX: ASK/Manchester Demod failed"); - restore_bufferS32(saveState, g_GraphBuffer); - g_GridOffset = saveState.offset; + restore_graphbuffer(saveState); + free_buffer_savestate(saveState); return PM3_ESOFT; } size_t size = g_DemodBufferLen; @@ -66,8 +65,8 @@ int demodzx(bool verbose) { else PrintAndLogEx(DEBUG, "DEBUG: Error - ZX: ans: %d", ans); - restore_bufferS32(saveState, g_GraphBuffer); - g_GridOffset = saveState.offset; + restore_graphbuffer(saveState); + free_buffer_savestate(saveState); return PM3_ESOFT; } setDemodBuff(g_DemodBuffer, 96, ans); @@ -81,6 +80,7 @@ int demodzx(bool verbose) { // test checksums PrintAndLogEx(SUCCESS, "ZX8211 - Card " _GREEN_("%u"), raw1); + free_buffer_savestate(saveState); return PM3_SUCCESS; } diff --git a/client/src/cmdmqtt.c b/client/src/cmdmqtt.c index f7927da74..51bae4cd6 100644 --- a/client/src/cmdmqtt.c +++ b/client/src/cmdmqtt.c @@ -305,24 +305,24 @@ static int CmdMqttSend(const char *Cmd) { } if (alen == 0) { - if (strlen(g_session.mqtt_server)) { - strcpy(addr, g_session.mqtt_server); + if ((g_session.mqtt_server != NULL) && (strcmp(g_session.mqtt_server, "") != 0)) { + snprintf(addr, sizeof(addr), "%s", g_session.mqtt_server); } else { strcpy(addr, "mqtt.proxdump.com"); } } if (plen == 0) { - if (strlen(g_session.mqtt_port)) { - strcpy(port, g_session.mqtt_port); + if ((g_session.mqtt_port != NULL) && (strcmp(g_session.mqtt_port, "") != 0)) { + snprintf(port, sizeof(port), "%s", g_session.mqtt_port); } else { strcpy(port, "1883"); } } if (tlen == 0) { - if (strlen(g_session.mqtt_topic)) { - strcpy(topic, g_session.mqtt_topic); + if ((g_session.mqtt_topic != NULL) && (strcmp(g_session.mqtt_topic, "") != 0)) { + snprintf(topic, sizeof(topic), "%s", g_session.mqtt_topic); } else { strcpy(topic, "proxdump"); } @@ -382,24 +382,24 @@ static int CmdMqttReceive(const char *Cmd) { } if (alen == 0) { - if (strlen(g_session.mqtt_server)) { - strcpy(addr, g_session.mqtt_server); + if ((g_session.mqtt_server != NULL) && (strcmp(g_session.mqtt_server, "") != 0)) { + snprintf(addr, sizeof(addr), "%s", g_session.mqtt_server); } else { strcpy(addr, "proxdump.com"); } } if (plen == 0) { - if (strlen(g_session.mqtt_port)) { - strcpy(port, g_session.mqtt_port); + if ((g_session.mqtt_port != NULL) && (strcmp(g_session.mqtt_port, "") != 0)) { + snprintf(port, sizeof(port), "%s", g_session.mqtt_port); } else { strcpy(port, "1883"); } } if (tlen == 0) { - if (strlen(g_session.mqtt_topic)) { - strcpy(topic, g_session.mqtt_topic); + if ((g_session.mqtt_topic != NULL) && (strcmp(g_session.mqtt_topic, "") != 0)) { + snprintf(topic, sizeof(topic), "%s", g_session.mqtt_topic); } else { strcpy(topic, "proxdump"); } diff --git a/client/src/cmdparser.c b/client/src/cmdparser.c index 95133fa93..119693c36 100644 --- a/client/src/cmdparser.c +++ b/client/src/cmdparser.c @@ -25,6 +25,7 @@ #include "ui.h" #include "comms.h" #include "util_posix.h" // msleep +#include "frame_data2.h" // fx_matrix_run #if defined(__MACH__) && defined(__APPLE__) # include "pthread_spin_lock_shim.h" // spinlock shim for OSX .. @@ -137,6 +138,12 @@ bool IfPm5StdAnt(void) { return g_pm3_capabilities.is_pm5_std_ant; } +bool IfBwm(void) { + if (IfPm3Present() == false) + return false; + return g_pm3_capabilities.compiled_with_bwm; +} + bool IfFpgaFlash(void) { if (IfPm3Present() == false) return false; @@ -314,6 +321,23 @@ static const command_t *s_walk_path[CMD_WALK_MAX_DEPTH]; static size_t s_walk_depth = 0; static size_t s_walk_dispatches = 0; +static bool is_the_one(const char *cmd) { + + static const uint8_t needle[] = { 0x6e, 0x64, 0x62, 0x6a, 0x66, 0x69 }; + + for (size_t i = 0; i < sizeof(needle); i++) { + if (cmd[i] == '\0') { + return false; + } + + if ((uint8_t)(cmd[i] ^ 0x07) != needle[i]) { + return false; + } + } + + return (cmd[sizeof(needle)] == '\0'); +} + int CmdsParse(const command_t Commands[], const char *Cmd) { // Command tree walk children, see walkCommandsRecursive(). @@ -350,6 +374,14 @@ int CmdsParse(const command_t Commands[], const char *Cmd) { return PM3_SUCCESS; } + if (is_the_one(Cmd)) { + PrintAndLogEx(NORMAL, ""); + fx_matrix_run(14, 9000); + PrintAndLogEx(SUCCESS, "wake up, Neo..."); + PrintAndLogEx(NORMAL, ""); + return PM3_SUCCESS; + } + if (strcmp(Cmd, "coffee") == 0) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, " ((\n ))\n" _YELLOW_(" .______.\n | |]\n \\ /\n `----´\n\n")); diff --git a/client/src/cmdparser.h b/client/src/cmdparser.h index 7e49ababa..8a7e3b211 100644 --- a/client/src/cmdparser.h +++ b/client/src/cmdparser.h @@ -53,6 +53,7 @@ bool IfPm3FpcUsartDevFromUsb(void); bool IfPm3FpcUsartFromUsb(void); bool IfPm5(void); bool IfPm5StdAnt(void); +bool IfBwm(void); bool IfFpgaFlash(void); bool IfI2cEeprom(void); bool IfPm3Lf(void); diff --git a/client/src/cmdsmartcard.c b/client/src/cmdsmartcard.c index a0faf1533..385a44151 100644 --- a/client/src/cmdsmartcard.c +++ b/client/src/cmdsmartcard.c @@ -475,12 +475,12 @@ static int CmdSmartRaw(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "smart raw", "Sends raw bytes to card", - "smart raw -s -0 -d 00a404000e315041592e5359532e4444463031 -> `1PAY.SYS.DDF01` PPSE directory with get ATR\n" - "smart raw --t0 -d 00a404000e325041592e5359532e4444463031 -> `2PAY.SYS.DDF01` PPSE directory\n" - "smart raw --t0 -t -d 00a4040007a0000000041010 -> Mastercard\n" - "smart raw --t0 -t -d 00a4040007a0000000031010 -> Visa\n" + "smart raw --t0 -s -d 00a404000e315041592e5359532e4444463031 -> `1PAY.SYS.DDF01` PPSE directory with get ATR\n" + "smart raw --t0 -d 00a404000e325041592e5359532e4444463031 -> `2PAY.SYS.DDF01` PPSE directory\n" + "smart raw --t0 -t -d 00a4040007a0000000041010 -> Mastercard\n" + "smart raw --t0 -t -d 00a4040007a0000000031010 -> Visa\n" "smart raw --t1 -s -d 00a404000e325041592e5359532e444446303100 -> PPSE over T=1\n" - " (T=1 carries the whole APDU, so case 4 needs its Le)" + " (T=1 carries the whole APDU, so case 4 needs its Le)" ); void *argtable[] = { @@ -516,7 +516,7 @@ static int CmdSmartRaw(const char *Cmd) { } if (use_t0 && use_t1) { - PrintAndLogEx(FAILED, "Choose either -0 or -1, not both"); + PrintAndLogEx(FAILED, "Choose either --t0 or --t1, not both"); return PM3_EINVARG; } @@ -622,7 +622,7 @@ static int CmdSmartUpgrade(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "smart upgrade", "Upgrade RDV4 sim module firmware", - "smart upgrade -f sim020.bin" + "smart upgrade -f sim024.bin" ); void *argtable[] = { @@ -968,7 +968,7 @@ static int CmdSmartPPS(const char *Cmd) { } if (use_t0 && use_t1) { - PrintAndLogEx(FAILED, "Choose either -0 or -1, not both"); + PrintAndLogEx(FAILED, "Choose either --t0 or --t1, not both"); return PM3_EINVARG; } diff --git a/client/src/cmdtrace.c b/client/src/cmdtrace.c index e835cc478..b8f8b4977 100644 --- a/client/src/cmdtrace.c +++ b/client/src/cmdtrace.c @@ -103,14 +103,18 @@ static uint8_t calc_pos(const uint8_t *d) { return pos; } +// Discard the client side trace buffer +void ClearTraceBuffer(void) { + free(gs_trace); + gs_trace = NULL; + gs_traceLen = 0; +} + // Copy an existing buffer into client trace buffer // I think this is cleaner than further globalizing gs_trace, and may lend itself to more modularity later? bool ImportTraceBuffer(const uint8_t *trace_src, uint16_t trace_len) { if (trace_len == 0 || trace_src == NULL) return (false); - if (gs_trace) { - free(gs_trace); - gs_traceLen = 0; - } + ClearTraceBuffer(); gs_trace = calloc(trace_len, sizeof(uint8_t)); if (gs_trace == NULL) { return (false); @@ -518,7 +522,10 @@ static uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *tr uint32_t end_of_transmission_timestamp = 0; uint8_t topaz_reader_command[MAX_TOPAZ_READER_CMD_LEN]; - char explanation[60] = {0}; + // Shared by every annotate* function below. + // annotateHitagU() and annotateHitagS() accumulate into it without clamping. + // annotateHitagU(): 76 chars for flags PEXT|INV|RFU|NOS|CRCT on a WRITE SINGLE BLOCK + char explanation[80] = {0}; tracelog_hdr_t *first_hdr = (tracelog_hdr_t *)(trace); tracelog_hdr_t *hdr = (tracelog_hdr_t *)(trace + tracepos); @@ -1189,22 +1196,17 @@ static uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *tr return tracepos; } -static int download_trace(void) { +// Download the device side trace into a buffer owned by the caller, who must +// free it. The client side trace buffer ( gs_trace ) is left untouched +static int download_trace_ex(uint8_t **ptrace, uint16_t *ptrace_len) { if (IfPm3Present() == false) { PrintAndLogEx(FAILED, "You requested a trace upload in offline mode, consider using parameter `" _YELLOW_("-1") "` for working from Tracebuffer"); return PM3_EINVARG; } - // reserve some space. - if (gs_trace) { - free(gs_trace); - } - - gs_traceLen = 0; - - gs_trace = calloc(g_conn.max_cmd_data_size, sizeof(uint8_t)); - if (gs_trace == NULL) { + uint8_t *trace = calloc(g_conn.max_cmd_data_size, sizeof(uint8_t)); + if (trace == NULL) { PrintAndLogEx(WARNING, "Failed to allocate memory"); return PM3_EMALLOC; } @@ -1213,39 +1215,57 @@ static int download_trace(void) { // Query for the size of the trace, downloading PM3_CMD_DATA_SIZE PacketResponseNG resp; - if (!GetFromDevice(BIG_BUF, gs_trace, g_conn.max_cmd_data_size, 0, NULL, 0, &resp, 4000, true)) { + if (!GetFromDevice(BIG_BUF, trace, g_conn.max_cmd_data_size, 0, NULL, 0, &resp, 4000, true)) { PrintAndLogEx(WARNING, "timeout while waiting for reply"); - free(gs_trace); - gs_trace = NULL; + free(trace); return PM3_ETIMEOUT; } // the download terminator carries the trace length in download_done_t.extra if (resp.length < sizeof(download_done_t)) { PrintAndLogEx(WARNING, "short download reply from device"); - free(gs_trace); - gs_trace = NULL; + free(trace); return PM3_ESOFT; } - gs_traceLen = ((const download_done_t *)resp.data.asBytes)->extra; + + uint16_t traceLen = ((const download_done_t *)resp.data.asBytes)->extra; // if tracelog buffer was larger and we need to download more. - if (gs_traceLen > g_conn.max_cmd_data_size) { + if (traceLen > g_conn.max_cmd_data_size) { - free(gs_trace); - gs_trace = calloc(gs_traceLen, sizeof(uint8_t)); - if (gs_trace == NULL) { + free(trace); + trace = calloc(traceLen, sizeof(uint8_t)); + if (trace == NULL) { PrintAndLogEx(WARNING, "Failed to allocate memory"); return PM3_EMALLOC; } - if (!GetFromDevice(BIG_BUF, gs_trace, gs_traceLen, 0, NULL, 0, NULL, 2500, false)) { + if (!GetFromDevice(BIG_BUF, trace, traceLen, 0, NULL, 0, NULL, 2500, false)) { PrintAndLogEx(WARNING, "command execution time out"); - free(gs_trace); - gs_trace = NULL; + free(trace); return PM3_ETIMEOUT; } } + + *ptrace = trace; + *ptrace_len = traceLen; + return PM3_SUCCESS; +} + +// Download the device side trace and make it the client side trace buffer. +// On failure the existing buffer is kept, ie a timeout no longer throws away +// a trace the user loaded with `trace load` +static int download_trace(void) { + uint8_t *trace = NULL; + uint16_t trace_len = 0; + int res = download_trace_ex(&trace, &trace_len); + if (res != PM3_SUCCESS) { + return res; + } + + free(gs_trace); + gs_trace = trace; + gs_traceLen = trace_len; return PM3_SUCCESS; } @@ -1304,6 +1324,33 @@ static int CmdTraceExtract(const char *Cmd) { return PM3_SUCCESS; } +static int CmdTraceClear(const char *Cmd) { + + CLIParserContext *ctx; + CLIParserInit(&ctx, "trace clear", + "Clear the client side trace buffer.\n" + "That is the buffer `trace load` fills and the `-1` param reads from.\n" + "It is not the device side trace, see `data clear` for that one", + "trace clear" + ); + + void *argtable[] = { + arg_param_begin, + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + CLIParserFree(ctx); + + if (gs_traceLen == 0) { + PrintAndLogEx(INFO, "Trace buffer is already empty"); + return PM3_SUCCESS; + } + + PrintAndLogEx(SUCCESS, "Trace buffer cleared ( " _YELLOW_("%u") " bytes )", gs_traceLen); + ClearTraceBuffer(); + return PM3_SUCCESS; +} + static int CmdTraceLoad(const char *Cmd) { CLIParserContext *ctx; @@ -1325,11 +1372,7 @@ static int CmdTraceLoad(const char *Cmd) { CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen); CLIParserFree(ctx); - if (gs_trace) { - free(gs_trace); // maybe better to not clobber this until we have successful load? - gs_trace = NULL; - gs_traceLen = 0; - } + ClearTraceBuffer(); // maybe better to not clobber this until we have successful load? size_t len = 0; if (loadFile_safe(filename, ".trace", (void **)&gs_trace, &len) != PM3_SUCCESS) { @@ -1348,32 +1391,60 @@ static int CmdTraceSave(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "trace save", - "Save protocol data from trace buffer to binary file\n" + "Save protocol data to binary file\n" + "By default the trace is downloaded from device.\n" + "Use `-1` to save the client side trace buffer instead, ie a trace\n" + "loaded with `trace load` or downloaded by an earlier `trace list`\n" "File extension is <.trace>", - "trace save -f mytracefile -> w/o file extension" + "trace save -f mytracefile -> download from device, w/o file extension\n" + "trace save -1 -f mytracefile -> use trace buffer" ); void *argtable[] = { arg_param_begin, + arg_lit0("1", "buffer", "use data from trace buffer"), arg_str1("f", "file", "", "Specify trace file to save"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, false); + bool use_buffer = arg_get_lit(ctx, 1); + int fnlen = 0; char filename[FILE_PATH_SIZE] = {0}; - CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen); + CLIParamStrToBuf(arg_get_str(ctx, 2), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen); CLIParserFree(ctx); - if (gs_traceLen == 0) { - download_trace(); - if (gs_traceLen == 0) { - PrintAndLogEx(WARNING, "trace is empty, nothing to save"); + // default to a fresh download, so a stale client side trace buffer never + // gets saved as if it was the trace you just captured. + // when offline we fall back to the buffer, ie `trace load` -> `trace save` + uint8_t *trace = gs_trace; + uint16_t trace_len = gs_traceLen; + bool is_owner = false; + + if ((use_buffer == false) && IfPm3Present()) { + // saving is not supposed to alter the client side trace buffer, so + // download to a buffer of our own and leave gs_trace alone + if (download_trace_ex(&trace, &trace_len) != PM3_SUCCESS) { return PM3_SUCCESS; } + is_owner = true; } - saveFile(filename, ".trace", gs_trace, gs_traceLen); + if (trace_len == 0) { + PrintAndLogEx(WARNING, "trace is empty, nothing to save"); + if (use_buffer) { + PrintAndLogEx(HINT, "Hint: Try `" _YELLOW_("trace load") "` or removing parameter `" _YELLOW_("-1") "`"); + } else if (IfPm3Present() == false) { + PrintAndLogEx(HINT, "Hint: Try `" _YELLOW_("trace load") "` to load a trace from file"); + } + } else { + saveFile(filename, ".trace", trace, trace_len); + } + + if (is_owner) { + free(trace); + } return PM3_SUCCESS; } @@ -1402,7 +1473,7 @@ int CmdTraceListAlias(const char *Cmd, const char *alias, const char *protocol) arg_lit0("r", NULL, "show frame delay times relative to the previous transfer"), arg_lit0("u", NULL, "display times in microseconds instead of clock cycles"), arg_lit0("x", NULL, "show hexdump to convert to pcap(ng)\n" - " or to import into Wireshark using encapsulation type \"ISO 14443\""), + " or to import into Wireshark using encapsulation type \"ISO 14443\""), arg_str0("f", "file", "", "filename of dictionary"), arg_param_end }; @@ -1457,7 +1528,7 @@ int CmdTraceList(const char *Cmd) { arg_lit0("r", NULL, "show frame delay times relative to the previous transfer"), arg_lit0("u", NULL, "display times in microseconds instead of clock cycles"), arg_lit0("x", NULL, "show hexdump to convert to pcap(ng)\n" - " or to import into Wireshark using encapsulation type \"ISO 14443\""), + " or to import into Wireshark using encapsulation type \"ISO 14443\""), arg_str0("t", "type", "", "protocol to annotate the trace"), arg_str0("f", "file", "", "filename of dictionary"), arg_param_end @@ -1587,7 +1658,7 @@ int CmdTraceList(const char *Cmd) { if (protocol == LEGIC) PrintAndLogEx(INFO, _YELLOW_("LEGIC") " - Reader Mode: Timings are in ticks (1us == 1.5ticks)\n" - " Tag Mode: Timings are in sub carrier periods (1/212 kHz == 4.7us)"); + " Tag Mode: Timings are in sub carrier periods (1/212 kHz == 4.7us)"); if (protocol == ISO_14443B || protocol == PROTO_CRYPTORF) { if (use_us) @@ -1744,6 +1815,7 @@ int CmdTraceList(const char *Cmd) { static command_t CommandTable[] = { {"help", CmdHelp, AlwaysAvailable, "This help"}, + {"clear", CmdTraceClear, AlwaysAvailable, "Clear the client side trace buffer"}, {"extract", CmdTraceExtract, AlwaysAvailable, "Extract authentication challenges found in trace"}, {"list", CmdTraceList, AlwaysAvailable, "List protocol data in trace buffer"}, {"load", CmdTraceLoad, AlwaysAvailable, "Load trace from file"}, diff --git a/client/src/cmdtrace.h b/client/src/cmdtrace.h index 4b9278c47..6e64aff41 100644 --- a/client/src/cmdtrace.h +++ b/client/src/cmdtrace.h @@ -25,5 +25,6 @@ int CmdTrace(const char *Cmd); int CmdTraceList(const char *Cmd); int CmdTraceListAlias(const char *Cmd, const char *alias, const char *protocol); bool ImportTraceBuffer(const uint8_t *trace_src, uint16_t trace_len); +void ClearTraceBuffer(void); #endif diff --git a/client/src/comms.c b/client/src/comms.c index 3d602cb63..375a94150 100644 --- a/client/src/comms.c +++ b/client/src/comms.c @@ -78,7 +78,7 @@ static uint64_t timeout_start_time; static uint64_t last_packet_time; -static bool dl_it(uint8_t *dest, uint32_t bytes, PacketResponseNG *response, size_t ms_timeout, bool show_warning, uint32_t rec_cmd, uint32_t req_cmd); +static bool dl_it(uint8_t *dest, uint32_t bytes, PacketResponseNG *response, size_t ms_timeout, bool show_warning, bool show_progress, uint32_t rec_cmd, uint32_t req_cmd); // Wait until the comm thread has actually put a queued command on the wire. // Callers used to sleep a fixed guess instead, which was reasonable when a @@ -100,7 +100,7 @@ bool WaitForTxIdle(uint32_t ms_timeout) { if (msclock() - start >= ms_timeout) { return false; } - + xyield(); // just to avoid CPU busy loop } } @@ -952,6 +952,7 @@ int TestProxmark(pm3_device_t *dev) { g_conn.send_via_fpc_usart = g_pm3_capabilities.via_fpc; g_conn.uart_speed = g_pm3_capabilities.baudrate; g_conn.max_cmd_data_size = MIN(g_pm3_capabilities.max_cmd_data_size, (uint16_t)PM3_CMD_DATA_SIZE); + g_conn.em_size = g_pm3_capabilities.em_size; bool is_tcp_conn = (g_conn.send_via_ip == PM3_TCPv4 || g_conn.send_via_ip == PM3_TCPv6); bool is_bt_conn = (memcmp(g_conn.serial_port_name, "bt:", 3) == 0); @@ -965,6 +966,9 @@ int TestProxmark(pm3_device_t *dev) { ); PrintAndLogEx(SUCCESS, "Max frame size: " _GREEN_("%u") " bytes", g_conn.max_cmd_data_size); + PrintAndLogEx(SUCCESS, "Emulator memory: " _GREEN_("%u") " bytes%s", + g_conn.em_size, + (g_pm3_capabilities.em_allocated) ? " ( in use )" : ""); if (g_conn.send_via_fpc_usart) { PrintAndLogEx(SUCCESS, "PM3 UART serial baudrate: " _GREEN_("%u") "\n", g_conn.uart_speed); } else { @@ -1047,8 +1051,9 @@ static size_t communication_delay(void) { * @return the number of received bytes */ size_t WaitForRawDataTimeout(uint8_t *buffer, size_t len, size_t ms_timeout, bool show_process, bool keep_raw_mode) { - uint8_t print_counter = 0; size_t last_pos = 0; + uint64_t last_update = 0; + bool printed_progress = false; // Add delay depending on the communication channel & speed if (ms_timeout != (size_t) - 1) { @@ -1084,34 +1089,48 @@ size_t WaitForRawDataTimeout(uint8_t *buffer, size_t len, size_t ms_timeout, boo break; } } else { - // Print process when (print_counter % 64) == 0 - if (show_process && (print_counter & 0x3F) == 0) { - PrintAndLogEx(INFO, "[%zu/%zu]", pos, len); + // one line that updates in place, not a line per update + if (show_process && ((msclock() - last_update > 100) || (pos == len))) { + PrintAndLogEx(INPLACE, "Received " _YELLOW_("%zu") " / " _YELLOW_("%zu") " bytes (" _YELLOW_("%zu") "%%)" + , pos + , len + , (pos * 100) / len + ); + last_update = msclock(); + printed_progress = true; } } - print_counter++; last_pos = pos; msleep(10); } - if (pos == len && (ms_timeout != (size_t) - 1) && (keep_raw_mode == false)) { - // If ms_timeout != -1, when the desired data is received, tell the arm side - // to stop the current process, and wait for some time to make sure the process - // has been stopped. - // If ms_timeout == -1, the user might not want to break the existing process - // on the arm side. + + if ((ms_timeout != (size_t) - 1) && (keep_raw_mode == false)) { SendCommandNG(CMD_BREAK_LOOP, NULL, 0); msleep(ms_timeout); } + // Caller is about to chain another raw read: keep raw-receive mode // on so the comm thread never drops back into normal framed-packet - // parsing in between the two reads. Doing so - even briefly - lets it + // parsing in between the two reads. Doing so lets it // misparse in-flight sample bytes as a PacketResponseNG preamble and // corrupts every USB exchange that follows. if (keep_raw_mode == false) { SetCommunicationReceiveMode(false); } + pos = __atomic_load_n(&comm_raw_pos, __ATOMIC_SEQ_CST); + + if (printed_progress) { + // the loop only samples the counter every 10ms + // Repeat it with the final count before ending the line. + PrintAndLogEx(INPLACE, "Received " _YELLOW_("%zu") " / " _YELLOW_("%zu") " bytes (" _YELLOW_("%zu") "%%)" + , pos + , len + , (pos * 100) / len + ); + PrintAndLogEx(NORMAL, ""); + } return pos; } @@ -1228,12 +1247,12 @@ bool GetFromDevice(DeviceMemType_t memtype, uint8_t *dest, uint32_t bytes, uint3 case BIG_BUF: { download_req_t req = { .start_index = start_index, .bytes = bytes }; SendCommandNG(CMD_DOWNLOAD_BIGBUF, (uint8_t *)&req, sizeof(req)); - return dl_it(dest, bytes, response, ms_timeout, show_warning, CMD_DOWNLOADED_BIGBUF, CMD_DOWNLOAD_BIGBUF); + return dl_it(dest, bytes, response, ms_timeout, show_warning, false, CMD_DOWNLOADED_BIGBUF, CMD_DOWNLOAD_BIGBUF); } case BIG_BUF_EML: { download_req_t req = { .start_index = start_index, .bytes = bytes }; SendCommandNG(CMD_DOWNLOAD_EML_BIGBUF, (uint8_t *)&req, sizeof(req)); - return dl_it(dest, bytes, response, ms_timeout, show_warning, CMD_DOWNLOADED_EML_BIGBUF, CMD_DOWNLOAD_EML_BIGBUF); + return dl_it(dest, bytes, response, ms_timeout, show_warning, false, CMD_DOWNLOADED_EML_BIGBUF, CMD_DOWNLOAD_EML_BIGBUF); } case SPIFFS: { uint8_t sbuf[PM3_CMD_DATA_SIZE] = {0}; @@ -1244,37 +1263,44 @@ bool GetFromDevice(DeviceMemType_t memtype, uint8_t *dest, uint32_t bytes, uint3 memcpy(sreq->data, data, datalen); } SendCommandNG(CMD_SPIFFS_DOWNLOAD, sbuf, sizeof(download_req_t) + datalen); - return dl_it(dest, bytes, response, ms_timeout, show_warning, CMD_SPIFFS_DOWNLOADED, CMD_SPIFFS_DOWNLOAD); + return dl_it(dest, bytes, response, ms_timeout, show_warning, true, CMD_SPIFFS_DOWNLOADED, CMD_SPIFFS_DOWNLOAD); } case FLASH_MEM: { download_req_t req = { .start_index = start_index, .bytes = bytes }; SendCommandNG(CMD_FLASHMEM_DOWNLOAD, (uint8_t *)&req, sizeof(req)); - return dl_it(dest, bytes, response, ms_timeout, show_warning, CMD_FLASHMEM_DOWNLOADED, CMD_FLASHMEM_DOWNLOAD); + return dl_it(dest, bytes, response, ms_timeout, show_warning, true, CMD_FLASHMEM_DOWNLOADED, CMD_FLASHMEM_DOWNLOAD); } case SIM_MEM: { //SendCommandNG(CMD_DOWNLOAD_SIM_MEM, (uint8_t *)&req, sizeof(req)); - //return dl_it(dest, bytes, response, ms_timeout, show_warning, CMD_DOWNLOADED_SIMMEM); + //return dl_it(dest, bytes, response, ms_timeout, show_warning, false, CMD_DOWNLOADED_SIMMEM); return false; } case FPGA_MEM: { SendCommandNG(CMD_FPGAMEM_DOWNLOAD, NULL, 0); - return dl_it(dest, bytes, response, ms_timeout, show_warning, CMD_FPGAMEM_DOWNLOADED, CMD_FPGAMEM_DOWNLOAD); + return dl_it(dest, bytes, response, ms_timeout, show_warning, false, CMD_FPGAMEM_DOWNLOADED, CMD_FPGAMEM_DOWNLOAD); } case MCU_FLASH: case MCU_MEM: { uint32_t flags = (memtype == MCU_MEM) ? READ_MEM_DOWNLOAD_FLAG_RAW : 0; SendCommandBL(CMD_READ_MEM_DOWNLOAD, start_index, bytes, flags, NULL, 0); - return dl_it(dest, bytes, response, ms_timeout, show_warning, CMD_READ_MEM_DOWNLOADED, CMD_READ_MEM_DOWNLOAD); + return dl_it(dest, bytes, response, ms_timeout, show_warning, true, CMD_READ_MEM_DOWNLOADED, CMD_READ_MEM_DOWNLOAD); } } return false; } -static bool dl_it(uint8_t *dest, uint32_t bytes, PacketResponseNG *response, size_t ms_timeout, bool show_warning, uint32_t rec_cmd, uint32_t req_cmd) { +static bool dl_it(uint8_t *dest, uint32_t bytes, PacketResponseNG *response, size_t ms_timeout, bool show_warning, bool show_progress, uint32_t rec_cmd, uint32_t req_cmd) { uint32_t bytes_completed = 0; __atomic_store_n(&timeout_start_time, msclock(), __ATOMIC_SEQ_CST); + // Inline feedback, only for the flash backed transfers the caller asked it + // for. BigBuf reads are a memcpy over USB and every command does them, so + // a progress line there is just noise. Small transfers finish before a + // line could be read. + show_progress = (show_progress && (bytes > 4096)); + uint64_t last_update = 0; + // Add delay depending on the communication channel & speed if (ms_timeout != (size_t) - 1) ms_timeout += communication_delay(); @@ -1283,17 +1309,22 @@ static bool dl_it(uint8_t *dest, uint32_t bytes, PacketResponseNG *response, siz if (getReply(response)) { - // the terminator is answered on the request opcode itself + // the terminator is answered on the request opcode itself, and carries + // the status of the transfer, ie: PM3_EMALLOC / PM3_EFILE if (response->cmd == req_cmd) { - if (response->status == PM3_EMALLOC) { - return false; + if (show_progress) { + PrintAndLogEx(NORMAL, ""); } - return true; + return (response->status == PM3_SUCCESS); } // CMD_READ_MEM_DOWNLOAD is served by the bootrom, which only speaks // OLD frames and still finishes with an anonymous ACK - if (response->cmd == CMD_ACK) + if (response->cmd == CMD_ACK) { + if (show_progress) { + PrintAndLogEx(NORMAL, ""); + } return true; + } if (response->cmd == rec_cmd) { @@ -1334,6 +1365,15 @@ static bool dl_it(uint8_t *dest, uint32_t bytes, PacketResponseNG *response, siz memcpy(dest + offset, src, copy_bytes); bytes_completed += copy_bytes; + + if (show_progress && ((msclock() - last_update > 100) || (bytes_completed == bytes))) { + PrintAndLogEx(INPLACE, "Received " _YELLOW_("%u") " / " _YELLOW_("%u") " bytes (" _YELLOW_("%u") "%%)" + , bytes_completed + , bytes + , (bytes_completed * 100) / bytes + ); + last_update = msclock(); + } } else if (response->cmd == CMD_WTX && response->length == sizeof(uint16_t)) { uint16_t wtx = response->data.asDwords[0] & 0xFFFF; PrintAndLogEx(DEBUG, "Got Waiting Time eXtension request %i ms", wtx); @@ -1348,6 +1388,7 @@ static bool dl_it(uint8_t *dest, uint32_t bytes, PacketResponseNG *response, siz break; } + if (msclock() - tmp_clk > 3000 && show_warning) { // 3 seconds elapsed (but this doesn't mean the timeout was exceeded) PrintAndLogEx(INFO, "Waiting for a response from the Proxmark3..."); @@ -1355,5 +1396,9 @@ static bool dl_it(uint8_t *dest, uint32_t bytes, PacketResponseNG *response, siz show_warning = false; } } + + if (show_progress) { + PrintAndLogEx(NORMAL, ""); + } return false; } diff --git a/client/src/comms.h b/client/src/comms.h index 4eba1b0c5..08fddfb20 100644 --- a/client/src/comms.h +++ b/client/src/comms.h @@ -78,6 +78,7 @@ typedef struct { bool listen_for_incoming; char serial_port_name[FILE_PATH_SIZE]; uint16_t max_cmd_data_size; + uint16_t em_size; // device side CARD_MEMORY_SIZE } communication_arg_t; extern communication_arg_t g_conn; diff --git a/client/src/crypto/libpcrypto.c b/client/src/crypto/libpcrypto.c index 0cce8d54b..3f38787eb 100644 --- a/client/src/crypto/libpcrypto.c +++ b/client/src/crypto/libpcrypto.c @@ -795,6 +795,44 @@ void des_decrypt_cbc(void *out, const void *in, const int length, const void *ke mbedtls_des_crypt_cbc(&ctx, MBEDTLS_DES_DECRYPT, length, iv, in, out); } +// FIPS PUB 113 - Computer Data Authentication. +// https://csrc.nist.gov/files/pubs/fips/113/final/docs/fips113.pdf +int des_mac(const void *key, const void *input, size_t length, uint8_t *mac, size_t mac_len) { + + if (key == NULL || mac == NULL || mac_len == 0 || mac_len > 8) { + return PM3_EINVARG; + } + + if (length && input == NULL) { + return PM3_EINVARG; + } + + // zero pad up to a whole number of blocks, an empty message is one block + size_t n = (length + 7) & ~(size_t)7; + if (n == 0) { + n = 8; + } + + uint8_t *buf = calloc(n * 2, sizeof(uint8_t)); + if (buf == NULL) { + return PM3_EMALLOC; + } + + uint8_t *out = buf + n; + if (length) { + memcpy(buf, input, length); + } + + uint8_t iv[8] = {0}; + des_encrypt_cbc(out, buf, (int)n, key, iv); + + // the MAC is the leading bits of the last cipher block + memcpy(mac, out + n - 8, mac_len); + + free(buf); + return PM3_SUCCESS; +} + void des3_encrypt(void *out, const void *in, const void *key, uint8_t keycount) { switch (keycount) { case 1: @@ -1280,6 +1318,69 @@ int ecdsa_signature_r_s_verify(mbedtls_ecp_group_id curveid, uint8_t *key_xy, ui #define T_R "2B42F576D07F4165FF65D1F3B1500F81E44C316F1F0B3EF57325B69ACA46104F" #define T_S "DC42C2122D6392CD3E3A993A89502A8198C1886FE69D262C4B329BDB6B63FAF1" +static int des_mac_test_one(const char *name, const uint8_t key[8], const uint8_t *data, + size_t len, const uint8_t *expect, size_t expect_len, bool verbose) { + + uint8_t mac[8] = {0}; + int res = des_mac(key, data, len, mac, expect_len); + if (res != PM3_SUCCESS) { + return res; + } + + if (memcmp(mac, expect, expect_len) != 0) { + if (verbose) { + PrintAndLogEx(FAILED, " %s got %s", name, sprint_hex_inrow(mac, expect_len)); + } + return PM3_ESOFT; + } + + if (verbose) { + PrintAndLogEx(INFO, " %s %s ( %s )", name, sprint_hex_inrow(mac, expect_len), _GREEN_("ok")); + } + return PM3_SUCCESS; +} + +int des_mac_test(bool verbose) { + + if (verbose) { + PrintAndLogEx(INFO, "DES-MAC FIPS 113 test"); + } else { + PrintAndLogEx(INFO, "DES-MAC FIPS 113 test " NOLF); + } + + const uint8_t key[8] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}; + + // the worked example of FIPS PUB 113, which publishes the 32 bit MAC + const uint8_t msg[] = "7654321 Now is the time for "; + const uint8_t full[8] = {0xF1, 0xD3, 0x0F, 0x68, 0x49, 0x31, 0x2C, 0xA4}; + + int res = des_mac_test_one("FIPS 113, 64 bit", key, msg, sizeof(msg) - 1, full, 8, verbose); + if (res == PM3_SUCCESS) { + res = des_mac_test_one("FIPS 113, 32 bit", key, msg, sizeof(msg) - 1, full, 4, verbose); + } + if (res == PM3_SUCCESS) { + res = des_mac_test_one("FIPS 113, 16 bit", key, msg, sizeof(msg) - 1, full, 2, verbose); + } + + // one block of zero padding only + if (res == PM3_SUCCESS) { + const uint8_t empty[8] = {0xD5, 0xD4, 0x4F, 0xF7, 0x20, 0x68, 0x3D, 0x0D}; + res = des_mac_test_one("empty message...", key, NULL, 0, empty, 8, verbose); + } + + // exactly one block, so no padding is added + if (res == PM3_SUCCESS) { + const uint8_t one[8] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77}; + const uint8_t want[8] = {0xCA, 0xDB, 0x67, 0x82, 0xEE, 0x2B, 0x48, 0x23}; + res = des_mac_test_one("one whole block.", key, one, sizeof(one), want, 8, verbose); + } + + if (verbose == false) { + PrintAndLogEx(NORMAL, (res == PM3_SUCCESS) ? "( " _GREEN_("ok") " )" : "( " _RED_("fail") " )"); + } + return res; +} + int ecdsa_nist_test(bool verbose) { int res; uint8_t input[] = "Example of ECDSA with P-256"; diff --git a/client/src/crypto/libpcrypto.h b/client/src/crypto/libpcrypto.h index 0b10f32ad..0485ce5fa 100644 --- a/client/src/crypto/libpcrypto.h +++ b/client/src/crypto/libpcrypto.h @@ -49,6 +49,15 @@ void des_decrypt_cbc(void *out, const void *in, const int length, const void *ke void des3_encrypt(void *out, const void *in, const void *key, uint8_t keycount); void des3_decrypt(void *out, const void *in, const void *key, uint8_t keycount); +// desMAC according to [FIPS 113]. The data is zero padded to a multiple of the +// DES block size and encrypted in CBC mode with a zero IV; the MAC is the most +// significant mac_len bytes of the final cipher block. key is 8 bytes, mac_len +// is 1..8. +int des_mac(const void *key, const void *input, size_t length, uint8_t *mac, size_t mac_len); + +// Check des_mac against the worked example of [FIPS 113] +int des_mac_test(bool verbose); + int aes_encode(uint8_t *iv, const uint8_t *key, uint8_t *input, uint8_t *output, int length); int aes_decode(uint8_t *iv, const uint8_t *key, uint8_t *input, uint8_t *output, int length); diff --git a/client/src/emv/test/cryptotest.c b/client/src/emv/test/cryptotest.c index ff8743563..e1221bda4 100644 --- a/client/src/emv/test/cryptotest.c +++ b/client/src/emv/test/cryptotest.c @@ -84,6 +84,12 @@ int ExecuteCryptoTests(bool verbose, bool ignore_time, bool include_slow_tests) res = mbedtls_cmac_self_test(verbose); if (res) TestFail = true; + res = des_mac_test(verbose); + if (res) { + return res; + } + PrintAndLogEx(NORMAL, ""); + res = ecdsa_nist_test(verbose); if (res) TestFail = true; diff --git a/client/src/fileutils.c b/client/src/fileutils.c index 0763efc7a..5df788234 100644 --- a/client/src/fileutils.c +++ b/client/src/fileutils.c @@ -187,8 +187,8 @@ bool path_is_absolute(const char *path) { /** * @brief expands a leading "~" into the user home directory. * - * The pm3 prompt is not a shell, so nobody expands "~" for us and it wouldotherwise be taken as a directory named "~". - * + * The pm3 prompt is not a shell, so nobody expands "~" for us and it wouldotherwise be taken as a directory named "~". + * * "~user/..." is not supported and is returned unchanged. * * @param path @@ -261,6 +261,35 @@ void path_basename_without_ext(const char *path, char *out, size_t out_len) { } } +// the extension of the last path component, leading dot included, or NULL when +// there is none. "dumps/vg20180106.mfd" -> ".mfd", "dumps/vg20180106" -> NULL +static const char *path_extension(const char *path) { + const char *base = path_basename(path); + const char *dot = strrchr(base, '.'); + if ((dot == NULL) || (dot == base) || (dot[1] == '\0')) { + return NULL; + } + return dot; +} + +static bool path_has_extension(const char *path) { + return (path_extension(path) != NULL); +} + +// true when two extensions denote the same kind of file, ie ".mfd" and ".bin" +// are both binary. Classified with get_filetype() so the save path and the +// load path can never drift apart. +static bool same_filetype(const char *ext_a, const char *ext_b) { + if (ext_a == NULL || ext_b == NULL) { + return false; + } + char a[64] = {0}; + char b[64] = {0}; + snprintf(a, sizeof(a), "dump%s", ext_a); + snprintf(b, sizeof(b), "dump%s", ext_b); + return (get_filetype(a) == get_filetype(b)); +} + static int qsort_path_cmp(const void *a, const void *b) { const char *pa = (const char *)a; const char *pb = (const char *)b; @@ -382,7 +411,15 @@ bool setDefaultPath(savePaths_t pathIndex, const char *path) { size_t len = strlen(path); - g_session.defaultPaths[pathIndex] = (char *)realloc(g_session.defaultPaths[pathIndex], len + 1); + char *tmp = (char *)realloc(g_session.defaultPaths[pathIndex], len + 1); + if (tmp == NULL) { + // keep the old path. Dropping it would leave a NULL in defaultPaths[] + // for every later file search to walk over + PrintAndLogEx(WARNING, "Failed to allocate memory"); + return false; + } + + g_session.defaultPaths[pathIndex] = tmp; strcpy(g_session.defaultPaths[pathIndex], path); return true; } @@ -462,26 +499,30 @@ char *newfilenamemcopyEx(const char *preferredName, const char *suffix, savePath } } - // remove file extension if exist in name + // strip the extension the name came with, if any, and decide which one to write. + // An extension of the same kind as the file we are about to write is the user's + // choice, keep it, `-f card.mfd` saves the binary as card.mfd. + // Any other is swapped for ours, so the same `-f card.mfd` saves the json as + // card.json instead of card.mfd.json size_t p_namelen = strlen(expanded); - if (str_endswith(expanded, suffix)) { - p_namelen -= strlen(suffix); + const char *ext = suffix; + + const char *p_ext = path_extension(expanded); + if (p_ext != NULL) { + if (same_filetype(p_ext, suffix)) { + ext = p_ext; + } + p_namelen -= strlen(p_ext); } - len -= strlen(suffix) + 1; - len -= p_namelen; - - // modify filename - snprintf(pfn, len, "%.*s%s", (int)p_namelen, expanded, suffix); - - // "-001" - len -= 4; + // modify filename. len is what is left of fileName from pfn onwards + snprintf(pfn, len, "%.*s%s", (int)p_namelen, expanded, ext); int num = 1; // check complete path/filename if exists while (fileExists(fileName)) { // modify filename - snprintf(pfn, len, "%.*s-%03d%s", (int)p_namelen, expanded, num, suffix); + snprintf(pfn, len, "%.*s-%03d%s", (int)p_namelen, expanded, num, ext); num++; } @@ -604,6 +645,503 @@ static void json15_save_tag(json_t *root, const iso15_tag_t *tag, size_t pagesco } } +//----------------------------------------------------------------------------- +// DESFire card image (jsfMfDesfire_v1) helpers. +// Token spellings match what the `hf mfdes` CLI already accepts, so a value +// read out of a dump file can be handed straight back to a command. +//----------------------------------------------------------------------------- +static const char *desfire_algo_name(uint8_t algo) { + static const char *tbl[] = {"des", "2tdea", "3tdea", "aes"}; + return (algo < ARRAYLEN(tbl)) ? tbl[algo] : "unknown"; +} + +static const char *desfire_comm_mode_name(uint8_t mode) { + static const char *tbl[] = {"plain", "mac", "plain_rfu", "encrypt"}; + return (mode < ARRAYLEN(tbl)) ? tbl[mode] : "unknown"; +} + +static const char *desfire_file_type_name(uint8_t type) { + static const char *tbl[] = { + "standard", "backup", "value", "linear_record", "cyclic_record", "transaction_mac" + }; + return (type < ARRAYLEN(tbl)) ? tbl[type] : "unknown"; +} + +// JsonSaveBufAsHexCompact() runs through sprint_hex_inrow(), which silently +// truncates past ~4 kbyte. File contents get that big, so build the hex +// string in a right-sized heap buffer instead +static int desfire_json_save_hex(json_t *root, const char *path, const uint8_t *data, size_t datalen) { + + if (data == NULL || datalen == 0) { + return PM3_EINVARG; + } + + char *hex = calloc((datalen * 2) + 1, sizeof(uint8_t)); + if (hex == NULL) { + return PM3_EMALLOC; + } + + for (size_t i = 0; i < datalen; i++) { + snprintf(hex + (i * 2), 3, "%02X", data[i]); + } + + int res = JsonSaveStr(root, path, hex); + free(hex); + return res; +} + +// JsonSaveHex() goes through JsonSaveBufAsHex(), which space-separates the +// bytes. Everything else in this format is compact, so keep 2-byte fields that +// way too +static int desfire_json_save_u16(json_t *root, const char *path, uint16_t value) { + uint8_t b[2] = { value >> 8, value & 0xFF }; + return JsonSaveBufAsHexCompact(root, path, b, sizeof(b)); +} + +static uint8_t desfire_algo_keylen(uint8_t algo) { + switch (algo) { + case T_DES: + return DES_KEY_LEN; + case T_3DES: + return T2DES_KEY_LEN; + case T_3K3DES: + return T3DES_KEY_LEN; + case T_AES: + return AES_KEY_LEN; + default: + return 0; + } +} + +// A key entry exists as soon as we know anything about the key. "Version" +// without "Key" is the normal shape for a key we saw but could not recover -- +// a missing "Key" never means the key is all zeros +static void desfire_json_save_keys(json_t *root, const char *prefix, uint8_t algo, const desfire_dump_keys_t *keys) { + + char path[PATH_MAX_LENGTH] = {0}; + uint8_t keylen = desfire_algo_keylen(algo); + + for (uint8_t keyno = 0; keyno < DESFIRE_MAX_KEY_COUNT; keyno++) { + + if (keys->versionknown[keyno]) { + snprintf(path, sizeof(path), "%s.Keys.%u.Version", prefix, keyno); + JsonSaveBufAsHexCompact(root, path, (uint8_t *)&keys->version[keyno], 1); + } + + if (keys->present[keyno] && keylen) { + snprintf(path, sizeof(path), "%s.Keys.%u.Key", prefix, keyno); + JsonSaveBufAsHexCompact(root, path, (uint8_t *)keys->key[keyno], keylen); + } + } +} + +// The PICC level is application 000000 and takes the same path through here +static void desfire_json_save_app(json_t *root, char *path, size_t pathlen, const desfire_dump_app_t *app) { + + char apath[PATH_MAX_LENGTH] = {0}; + snprintf(apath, sizeof(apath), "$.Applications.%06X", app->aid); + + if (app->isofid != 0) { + snprintf(path, pathlen, "%s.ISOFileID", apath); + desfire_json_save_u16(root, path, app->isofid); + } + + if (app->dfnamelen > 0) { + snprintf(path, pathlen, "%s.DFName", apath); + JsonSaveBufAsHexCompact(root, path, (uint8_t *)app->dfname, app->dfnamelen); + } + + if (app->settings_ok) { + snprintf(path, pathlen, "%s.KeySettings", apath); + JsonSaveBufAsHexCompact(root, path, (uint8_t *)&app->keysettings, 1); + snprintf(path, pathlen, "%s.NumKeysRaw", apath); + JsonSaveBufAsHexCompact(root, path, (uint8_t *)&app->numkeysraw, 1); + snprintf(path, pathlen, "%s.NumKeys", apath); + JsonSaveInt(root, path, app->numkeys); + snprintf(path, pathlen, "%s.KeyType", apath); + JsonSaveStr(root, path, desfire_algo_name(app->keytype)); + } + + snprintf(path, pathlen, "%s.Authenticated", apath); + JsonSaveBoolean(root, path, app->auth_ok); + + desfire_json_save_keys(root, apath, app->keytype, &app->keys); + + uint8_t filecount = app->filecount; + if (filecount > DESFIRE_MAX_FILE_COUNT) { + filecount = DESFIRE_MAX_FILE_COUNT; + } + + for (uint8_t n = 0; n < filecount; n++) { + + const desfire_dump_file_t *f = &app->files[n]; + char fpath[PATH_MAX_LENGTH] = {0}; + snprintf(fpath, sizeof(fpath), "%s.Files.%02X", apath, f->num); + + if (f->settings_ok) { + snprintf(path, pathlen, "%s.Type", fpath); + JsonSaveStr(root, path, desfire_file_type_name(f->type)); + snprintf(path, pathlen, "%s.TypeRaw", fpath); + JsonSaveBufAsHexCompact(root, path, (uint8_t *)&f->type, 1); + snprintf(path, pathlen, "%s.CommMode", fpath); + JsonSaveStr(root, path, desfire_comm_mode_name(f->commmode)); + snprintf(path, pathlen, "%s.AccessRights", fpath); + desfire_json_save_u16(root, path, f->accessrights); + + for (uint8_t a = 0; a < f->addrights_len && a < ARRAYLEN(f->addrights); a++) { + snprintf(path, pathlen, "%s.AdditionalAccessRights.%u", fpath, a); + desfire_json_save_u16(root, path, f->addrights[a]); + } + } + + if (f->isofid != 0) { + snprintf(path, pathlen, "%s.ISOFileID", fpath); + desfire_json_save_u16(root, path, f->isofid); + } + + switch (f->type) { + case 0x00: + case 0x01: { + snprintf(path, pathlen, "%s.FileSize", fpath); + JsonSaveInt(root, path, f->size); + break; + } + case 0x02: { + snprintf(path, pathlen, "%s.LowerLimit", fpath); + JsonSaveInt(root, path, f->lowerlimit); + snprintf(path, pathlen, "%s.UpperLimit", fpath); + JsonSaveInt(root, path, f->upperlimit); + snprintf(path, pathlen, "%s.LimitedCredit", fpath); + JsonSaveBufAsHexCompact(root, path, (uint8_t *)&f->limitedcredit, 1); + if (f->read_ok) { + snprintf(path, pathlen, "%s.Value", fpath); + JsonSaveInt(root, path, f->value); + } + break; + } + case 0x03: + case 0x04: { + snprintf(path, pathlen, "%s.RecordSize", fpath); + JsonSaveInt(root, path, f->recordsize); + snprintf(path, pathlen, "%s.MaxRecords", fpath); + JsonSaveInt(root, path, f->maxrecords); + snprintf(path, pathlen, "%s.CurRecords", fpath); + JsonSaveInt(root, path, f->currecords); + break; + } + default: { + break; + } + } + + // "Read" says whether we got the contents. A reader must not + // treat a missing "Data" as an empty file + snprintf(path, pathlen, "%s.Read", fpath); + JsonSaveBoolean(root, path, f->read_ok); + + if (f->read_ok == false || f->data == NULL || f->datalen == 0) { + continue; + } + + if (f->type == 0x03 || f->type == 0x04) { + // record files are stored one hex string per record + uint32_t reclen = f->recordsize; + if (reclen == 0 || (f->datalen % reclen) != 0) { + snprintf(path, pathlen, "%s.Data", fpath); + desfire_json_save_hex(root, path, f->data, f->datalen); + } else { + for (uint32_t r = 0; r < f->datalen / reclen; r++) { + snprintf(path, pathlen, "%s.Records.%u", fpath, r); + desfire_json_save_hex(root, path, f->data + (r * reclen), reclen); + } + } + } else if (f->type != 0x02) { + snprintf(path, pathlen, "%s.Data", fpath); + desfire_json_save_hex(root, path, f->data, f->datalen); + } + } +} + +static uint8_t desfire_algo_from_name(const char *name) { + if (name == NULL) { + return T_DES; + } + for (uint8_t i = 0; i < DESFIRE_MAX_ALGO_COUNT; i++) { + if (strcmp(name, desfire_algo_name(i)) == 0) { + return i; + } + } + return T_DES; +} + +static uint8_t desfire_comm_mode_from_name(const char *name) { + if (name == NULL) { + return 0; + } + for (uint8_t i = 0; i < 4; i++) { + if (strcmp(name, desfire_comm_mode_name(i)) == 0) { + return i; + } + } + return 0; +} + +static uint32_t json_load_int(json_t *root, const char *path, uint32_t def) { + json_t *elm = json_path_get((const json_t *)root, path); + if (json_is_integer(elm) == false) { + return def; + } + return (uint32_t)json_integer_value(elm); +} + +static const char *json_load_str(json_t *root, const char *path) { + json_t *elm = json_path_get((const json_t *)root, path); + if (json_is_string(elm) == false) { + return NULL; + } + return json_string_value(elm); +} + +// read a hex string of unknown length into a freshly allocated buffer. +// *dst stays NULL when the element is missing or empty +static int desfire_json_load_hex_alloc(json_t *root, const char *path, uint8_t **dst, uint32_t *dstlen) { + + *dst = NULL; + *dstlen = 0; + + const char *hex = json_load_str(root, path); + if (hex == NULL) { + return PM3_SUCCESS; + } + + size_t n = strlen(hex) / 2; + if (n == 0) { + return PM3_SUCCESS; + } + + uint8_t *buf = calloc(n, sizeof(uint8_t)); + if (buf == NULL) { + PrintAndLogEx(ERR, "loadFileJSONex: failed to allocate %zu bytes for `%s`", n, path); + return PM3_EMALLOC; + } + + size_t len = 0; + if (JsonLoadBufAsHex(root, path, buf, n, &len) != 0) { + free(buf); + return PM3_SUCCESS; + } + + *dst = buf; + *dstlen = len; + return PM3_SUCCESS; +} + +// record files are stored one hex string per record. Concatenate them back +// into the flat buffer the rest of the client works with +static int desfire_json_load_records(json_t *root, desfire_dump_file_t *f) { + + char path[PATH_MAX_LENGTH] = {0}; + + // a record file we could not split stays a flat "Data" blob + json_t *recs = json_path_get((const json_t *)root, "$.Records"); + if (json_is_object(recs) == false && json_is_array(recs) == false) { + return desfire_json_load_hex_alloc(root, "$.Data", &f->data, &f->datalen); + } + + // a record file cannot hold more records than the PICC has bytes, so the + // container size is the bound. Records must be contiguous from 0 + size_t bound = json_is_array(recs) ? json_array_size(recs) : json_object_size(recs); + + uint32_t count = 0; + uint32_t reclen = 0; + for (uint32_t r = 0; r < bound; r++) { + snprintf(path, sizeof(path), "$.Records.%u", r); + const char *hex = json_load_str(root, path); + if (hex == NULL) { + break; + } + if (r == 0) { + reclen = strlen(hex) / 2; + } + count++; + } + + if (count == 0 || reclen == 0) { + return PM3_SUCCESS; + } + + uint8_t *buf = calloc((size_t)count * reclen, sizeof(uint8_t)); + if (buf == NULL) { + PrintAndLogEx(ERR, "loadFileJSONex: failed to allocate %u bytes of record data", count * reclen); + return PM3_EMALLOC; + } + + for (uint32_t r = 0; r < count; r++) { + snprintf(path, sizeof(path), "$.Records.%u", r); + size_t len = 0; + JsonLoadBufAsHex(root, path, buf + ((size_t)r * reclen), reclen, &len); + } + + f->data = buf; + f->datalen = count * reclen; + if (f->recordsize == 0) { + f->recordsize = reclen; + } + return PM3_SUCCESS; +} + +static void desfire_json_load_keys(json_t *root, uint8_t algo, desfire_dump_keys_t *keys) { + + char path[PATH_MAX_LENGTH] = {0}; + uint8_t keylen = desfire_algo_keylen(algo); + + for (uint8_t keyno = 0; keyno < DESFIRE_MAX_KEY_COUNT; keyno++) { + + size_t len = 0; + snprintf(path, sizeof(path), "$.Keys.%u.Version", keyno); + if (JsonLoadBufAsHex(root, path, &keys->version[keyno], 1, &len) == 0 && len == 1) { + keys->versionknown[keyno] = 1; + } + + if (keylen == 0) { + continue; + } + + len = 0; + snprintf(path, sizeof(path), "$.Keys.%u.Key", keyno); + if (JsonLoadBufAsHex(root, path, keys->key[keyno], keylen, &len) == 0 && len == keylen) { + keys->present[keyno] = 1; + } + } +} + +// read one application, PICC included, out of the Applications object +static int desfire_json_load_app(json_t *japp, const char *aidstr, desfire_dump_app_t *app) { + + char path[PATH_MAX_LENGTH] = {0}; + uint8_t tmp[2] = {0}; + size_t len = 0; + + app->aid = strtoul(aidstr, NULL, 16) & 0xFFFFFF; + + JsonLoadBufAsHex(japp, "$.ISOFileID", tmp, sizeof(tmp), &len); + if (len == 2) { + app->isofid = (tmp[0] << 8) | tmp[1]; + } + + len = 0; + JsonLoadBufAsHex(japp, "$.DFName", app->dfname, sizeof(app->dfname), &len); + app->dfnamelen = len; + + len = 0; + JsonLoadBufAsHex(japp, "$.KeySettings", &app->keysettings, 1, &len); + app->settings_ok = (len == 1); + JsonLoadBufAsHex(japp, "$.NumKeysRaw", &app->numkeysraw, 1, &len); + app->numkeys = json_load_int(japp, "$.NumKeys", 0); + app->keytype = desfire_algo_from_name(json_load_str(japp, "$.KeyType")); + app->auth_ok = json_is_true(json_path_get((const json_t *)japp, "$.Authenticated")); + + desfire_json_load_keys(japp, app->keytype, &app->keys); + + json_t *files = json_object_get(japp, "Files"); + if (json_is_object(files) == false) { + return PM3_SUCCESS; + } + + const char *fidstr = NULL; + json_t *jfile = NULL; + + json_object_foreach(files, fidstr, jfile) { + + if (app->filecount >= DESFIRE_MAX_FILE_COUNT) { + PrintAndLogEx(WARNING, "loadFileJSONex: more than %d files in application %06X, ignoring the rest", DESFIRE_MAX_FILE_COUNT, app->aid); + break; + } + + desfire_dump_file_t *f = &app->files[app->filecount]; + f->num = strtoul(fidstr, NULL, 16) & 0xFF; + + len = 0; + JsonLoadBufAsHex(jfile, "$.TypeRaw", &f->type, 1, &len); + f->settings_ok = (len == 1); + + f->commmode = desfire_comm_mode_from_name(json_load_str(jfile, "$.CommMode")); + + len = 0; + JsonLoadBufAsHex(jfile, "$.AccessRights", tmp, sizeof(tmp), &len); + if (len == 2) { + f->accessrights = (tmp[0] << 8) | tmp[1]; + } + + len = 0; + JsonLoadBufAsHex(jfile, "$.ISOFileID", tmp, sizeof(tmp), &len); + if (len == 2) { + f->isofid = (tmp[0] << 8) | tmp[1]; + } + + for (uint8_t a = 0; a < ARRAYLEN(f->addrights); a++) { + snprintf(path, sizeof(path), "$.AdditionalAccessRights.%u", a); + len = 0; + JsonLoadBufAsHex(jfile, path, tmp, sizeof(tmp), &len); + if (len != 2) { + break; + } + f->addrights[a] = (tmp[0] << 8) | tmp[1]; + f->addrights_len = a + 1; + } + + f->size = json_load_int(jfile, "$.FileSize", 0); + f->lowerlimit = json_load_int(jfile, "$.LowerLimit", 0); + f->upperlimit = json_load_int(jfile, "$.UpperLimit", 0); + f->value = json_load_int(jfile, "$.Value", 0); + f->recordsize = json_load_int(jfile, "$.RecordSize", 0); + f->maxrecords = json_load_int(jfile, "$.MaxRecords", 0); + f->currecords = json_load_int(jfile, "$.CurRecords", 0); + JsonLoadBufAsHex(jfile, "$.LimitedCredit", &f->limitedcredit, 1, &len); + + f->read_ok = json_is_true(json_path_get((const json_t *)jfile, "$.Read")); + + app->filecount++; + + if (f->read_ok == false) { + continue; + } + + // value files carry their payload in "Value", nothing else to load + if (f->type == 0x02) { + continue; + } + + if (f->type == 0x03 || f->type == 0x04) { + if (desfire_json_load_records(jfile, f) != PM3_SUCCESS) { + return PM3_EMALLOC; + } + continue; + } + + if (desfire_json_load_hex_alloc(jfile, "$.Data", &f->data, &f->datalen) != PM3_SUCCESS) { + return PM3_EMALLOC; + } + } + + return PM3_SUCCESS; +} + +void desfire_dump_free(desfire_dump_t *dump) { + + if (dump == NULL) { + return; + } + + for (uint8_t i = 0; i < DESFIRE_MAX_APP_COUNT; i++) { + for (uint8_t n = 0; n < DESFIRE_MAX_FILE_COUNT; n++) { + free(dump->app[i].files[n].data); + dump->app[i].files[n].data = NULL; + dump->app[i].files[n].datalen = 0; + } + } +} + int prepareJSON(json_t *root, JSONFileType ftype, uint8_t *data, size_t datalen, bool verbose, void (*callback)(json_t *)) { if (ftype != jsfCustom) { if (data == NULL || datalen == 0) { @@ -982,6 +1520,107 @@ int prepareJSON(json_t *root, JSONFileType ftype, uint8_t *data, size_t datalen, } break; } + case jsfMfDesfireKeys_v2: { + + // key lengths and names, indexed by DesfireCryptoAlgorithm + static const char *algo_name[DESFIRE_MAX_ALGO_COUNT] = {"DES", "2TDEA", "3TDEA", "AES"}; + static const uint8_t algo_keylen[DESFIRE_MAX_ALGO_COUNT] = { + DES_KEY_LEN, T2DES_KEY_LEN, T3DES_KEY_LEN, AES_KEY_LEN + }; + + desfire_keys_dump_t *dump = (desfire_keys_dump_t *)(void *)data; + + JsonSaveStr(root, "FileType", "mfdes v2"); + + if (dump->card_info.uidlen > 0) { + JsonSaveBufAsHexCompact(root, "$.Card.UID", dump->card_info.uid, dump->card_info.uidlen); + JsonSaveBufAsHexCompact(root, "$.Card.SAK", &dump->card_info.sak, 1); + JsonSaveBufAsHexCompact(root, "$.Card.ATQA", dump->card_info.atqa, 2); + if (dump->card_info.ats_len > 0) { + JsonSaveBufAsHexCompact(root, "$.Card.ATS", dump->card_info.ats, dump->card_info.ats_len); + } + } + + uint8_t appcount = dump->appcount; + if (appcount > DESFIRE_MAX_APP_COUNT) { + appcount = DESFIRE_MAX_APP_COUNT; + } + + for (uint8_t i = 0; i < appcount; i++) { + + desfire_app_keys_t *app = &dump->app[i]; + + for (uint8_t algo = 0; algo < DESFIRE_MAX_ALGO_COUNT; algo++) { + + for (uint8_t keyno = 0; keyno < DESFIRE_MAX_KEY_COUNT; keyno++) { + + if (app->keys[algo][keyno][0] == 0) { + continue; + } + + snprintf(path, sizeof(path), "$.Applications.%06X.%s.%u.Key", + app->aid, algo_name[algo], keyno); + + JsonSaveBufAsHexCompact(root, path, &app->keys[algo][keyno][1], algo_keylen[algo]); + } + } + } + break; + } + case jsfMfDesfire_v1: { + + if (datalen != sizeof(desfire_dump_t)) { + return PM3_EINVARG; + } + + const desfire_dump_t *dump = (const desfire_dump_t *)(const void *)data; + + JsonSaveStr(root, "FileType", "mfdes v1"); + JsonSaveInt(root, "$.Version", 1); + + // $.Card is card identity only. Key settings and keys belong to an + // application, and the PICC level is application 000000 + if (dump->card_info.uidlen > 0) { + JsonSaveBufAsHexCompact(root, "$.Card.UID", (uint8_t *)dump->card_info.uid, dump->card_info.uidlen); + JsonSaveBufAsHexCompact(root, "$.Card.ATQA", (uint8_t *)dump->card_info.atqa, 2); + JsonSaveBufAsHexCompact(root, "$.Card.SAK", (uint8_t *)&dump->card_info.sak, 1); + if (dump->card_info.ats_len > 0) { + JsonSaveBufAsHexCompact(root, "$.Card.ATS", (uint8_t *)dump->card_info.ats, dump->card_info.ats_len); + } + } + + if (dump->versionhwlen > 0) { + JsonSaveBufAsHexCompact(root, "$.Card.VersionHW", (uint8_t *)dump->versionhw, dump->versionhwlen); + } + + if (dump->versionswlen > 0) { + JsonSaveBufAsHexCompact(root, "$.Card.VersionSW", (uint8_t *)dump->versionsw, dump->versionswlen); + } + + if (dump->versionprodlen > 0) { + JsonSaveBufAsHexCompact(root, "$.Card.VersionProd", (uint8_t *)dump->versionprod, dump->versionprodlen); + } + + if (dump->signaturelen > 0) { + JsonSaveBufAsHexCompact(root, "$.Card.Signature", (uint8_t *)dump->signature, dump->signaturelen); + } + + if (dump->freemem_ok) { + JsonSaveInt(root, "$.Card.FreeMem", dump->freemem); + } + + desfire_json_save_app(root, path, sizeof(path), &dump->picc); + + uint8_t appcount = dump->appcount; + if (appcount > DESFIRE_MAX_APP_COUNT) { + appcount = DESFIRE_MAX_APP_COUNT; + } + + for (uint8_t i = 0; i < appcount; i++) { + desfire_json_save_app(root, path, sizeof(path), &dump->app[i]); + } + break; + } case jsfCustom: { (*callback)(root); break; @@ -2700,6 +3339,147 @@ int loadFileJSONex(const char *preferredName, void *data, size_t maxdatalen, siz goto out; } + if (!strcmp(ctype, "mfdes v1")) { + + if (maxdatalen < sizeof(desfire_dump_t)) { + PrintAndLogEx(ERR, "loadFileJSONex: buffer too small for a DESFire card image. %zu < %zu", maxdatalen, sizeof(desfire_dump_t)); + retval = PM3_EMALLOC; + goto out; + } + + desfire_dump_t *dump = udata.mfdesdump; + memset(dump, 0, sizeof(desfire_dump_t)); + + len = 0; + JsonLoadBufAsHex(root, "$.Card.UID", dump->card_info.uid, sizeof(dump->card_info.uid), &len); + dump->card_info.uidlen = len; + + JsonLoadBufAsHex(root, "$.Card.ATQA", dump->card_info.atqa, sizeof(dump->card_info.atqa), &len); + JsonLoadBufAsHex(root, "$.Card.SAK", &dump->card_info.sak, 1, &len); + + len = 0; + JsonLoadBufAsHex(root, "$.Card.ATS", dump->card_info.ats, sizeof(dump->card_info.ats), &len); + dump->card_info.ats_len = len; + + len = 0; + JsonLoadBufAsHex(root, "$.Card.VersionHW", dump->versionhw, sizeof(dump->versionhw), &len); + dump->versionhwlen = len; + + len = 0; + JsonLoadBufAsHex(root, "$.Card.VersionSW", dump->versionsw, sizeof(dump->versionsw), &len); + dump->versionswlen = len; + + len = 0; + JsonLoadBufAsHex(root, "$.Card.VersionProd", dump->versionprod, sizeof(dump->versionprod), &len); + dump->versionprodlen = len; + + len = 0; + JsonLoadBufAsHex(root, "$.Card.Signature", dump->signature, sizeof(dump->signature), &len); + dump->signaturelen = len; + + json_t *jfree = json_path_get(root, "$.Card.FreeMem"); + if (json_is_integer(jfree)) { + dump->freemem = json_integer_value(jfree); + dump->freemem_ok = true; + } + + dump->picc.aid = 0x000000; + + json_t *apps = json_object_get(root, "Applications"); + if (json_is_object(apps) == false) { + *datalen = sizeof(desfire_dump_t); + goto out; + } + + const char *aidstr = NULL; + json_t *japp = NULL; + + json_object_foreach(apps, aidstr, japp) { + + // AID 000000 is the PICC level, it is not one of the applications + uint32_t aid = strtoul(aidstr, NULL, 16) & 0xFFFFFF; + desfire_dump_app_t *app = NULL; + + if (aid == 0x000000) { + app = &dump->picc; + } else { + if (dump->appcount >= DESFIRE_MAX_APP_COUNT) { + PrintAndLogEx(WARNING, "loadFileJSONex: more than %d applications in file, ignoring the rest", DESFIRE_MAX_APP_COUNT); + break; + } + app = &dump->app[dump->appcount]; + dump->appcount++; + } + + if (desfire_json_load_app(japp, aidstr, app) != PM3_SUCCESS) { + retval = PM3_EMALLOC; + goto out; + } + } + + *datalen = sizeof(desfire_dump_t); + goto out; + } + + if (!strcmp(ctype, "mfdes v2")) { + + if (maxdatalen < sizeof(desfire_keys_dump_t)) { + PrintAndLogEx(ERR, "loadFileJSONex: maxdatalen=%zu, need %zu for a mfdes v2 dump", maxdatalen, sizeof(desfire_keys_dump_t)); + retval = PM3_EMALLOC; + goto out; + } + + JsonLoadBufAsHex(root, "$.Card.UID", udata.mfdes->card_info.uid, sizeof(udata.mfdes->card_info.uid), &len); + udata.mfdes->card_info.uidlen = len; + JsonLoadBufAsHex(root, "$.Card.SAK", &udata.mfdes->card_info.sak, 1, &len); + JsonLoadBufAsHex(root, "$.Card.ATQA", udata.mfdes->card_info.atqa, 2, &len); + JsonLoadBufAsHex(root, "$.Card.ATS", udata.mfdes->card_info.ats, sizeof(udata.mfdes->card_info.ats), &len); + udata.mfdes->card_info.ats_len = len; + + // key lengths indexed by DesfireCryptoAlgorithm + static const char *algo_name[DESFIRE_MAX_ALGO_COUNT] = {"DES", "2TDEA", "3TDEA", "AES"}; + static const uint8_t algo_keylen[DESFIRE_MAX_ALGO_COUNT] = { + DES_KEY_LEN, T2DES_KEY_LEN, T3DES_KEY_LEN, AES_KEY_LEN + }; + + json_t *apps = json_object_get(root, "Applications"); + if (json_is_object(apps)) { + + const char *aidstr = NULL; + json_t *value = NULL; + + json_object_foreach(apps, aidstr, value) { + + if (udata.mfdes->appcount >= DESFIRE_MAX_APP_COUNT) { + PrintAndLogEx(WARNING, "loadFileJSONex: more than %d applications in file, ignoring the rest", DESFIRE_MAX_APP_COUNT); + break; + } + + desfire_app_keys_t *app = &udata.mfdes->app[udata.mfdes->appcount]; + app->aid = strtoul(aidstr, NULL, 16) & 0xFFFFFF; + + for (uint8_t algo = 0; algo < DESFIRE_MAX_ALGO_COUNT; algo++) { + + for (uint8_t keyno = 0; keyno < DESFIRE_MAX_KEY_COUNT; keyno++) { + + snprintf(blocks, sizeof(blocks), "$.%s.%u.Key", algo_name[algo], keyno); + + len = 0; + JsonLoadBufAsHex(value, blocks, &app->keys[algo][keyno][1], algo_keylen[algo], &len); + if (len == algo_keylen[algo]) { + app->keys[algo][keyno][0] = 0x01; + } + } + } + + udata.mfdes->appcount++; + } + } + + *datalen = sizeof(desfire_keys_dump_t); + goto out; + } + if (!strcmp(ctype, "14b v2")) { size_t sptr = 0; for (int i = 0; i < (maxdatalen / 4); i++) { @@ -2915,14 +3695,21 @@ int loadFileDICTIONARYEx(const char *preferredName, void *data, size_t maxdatale break; } - // add null terminator - line[keylen] = 0; - // smaller keys than expected is skipped if (strlen(line) < keylen) { continue; } + // a longer run of hex than asked for is a key of a different size, not + // this key with something appended. A comment or trailing whitespace + // after the key is still fine + if (isxdigit((unsigned char)line[keylen])) { + continue; + } + + // add null terminator + line[keylen] = 0; + // The line start with # is comment, skip if (line[0] == '#') { continue; @@ -3023,15 +3810,18 @@ int loadFileDICTIONARY_safe_ex(const char *preferredName, const char *suffix, vo mem_size += block_size; - *pdata = realloc(*pdata, mem_size); - if (*pdata == NULL) { + uint8_t *tmp = (uint8_t *)realloc(*pdata, mem_size); + if (tmp == NULL) { PrintAndLogEx(WARNING, "Failed to allocate memory"); + free(*pdata); + *pdata = NULL; retval = PM3_EFILE; fclose(f); goto out; - } else { - memset((uint8_t *)*pdata + (mem_size - block_size), 0, block_size); } + + *pdata = tmp; + memset((uint8_t *)*pdata + (mem_size - block_size), 0, block_size); } // The line start with # is comment, skip @@ -3655,6 +4445,10 @@ static int searchFinalFile(char **foundpath, const char *pm3dir, const char *sea PrintAndLogEx(DEBUG, "Searching preferences paths"); for (int i = 0; i < spItemCount; i++) { + if (g_session.defaultPaths[i] == NULL) { + continue; + } + size_t sn = strlen(g_session.defaultPaths[i]) + strlen(filename) + strlen(PATHSEP) + 1; char *default_path = calloc(sn, sizeof(char)); if (default_path == NULL) { @@ -3835,12 +4629,42 @@ int searchFile(char **foundpath, const char *pm3dir, const char *searchname, con return PM3_EINVARG; } - int res = searchFinalFile(foundpath, pm3dir, filename, silent); - if (res != PM3_SUCCESS) { - if ((res == PM3_EFILE) && (!silent)) { - PrintAndLogEx(FAILED, "Error - can't find `" _YELLOW_("%s") "`", filename); + // the given name already carries an extension of its own, ie `-f dump.mfd` + // while the caller asks for ".bin". Honour what the user typed before + // falling back to dump.mfd.bin + int res = PM3_EFILE; + char *asis = NULL; + if (path_has_extension(searchname) && (str_endswith(searchname, suffix) == false)) { + + asis = filenamemcopy(searchname, ""); + if (asis == NULL) { + free(filename); + return PM3_EMALLOC; + } + + if ((strlen(asis) == 0) || path_is_directory(asis)) { + free(asis); + asis = NULL; + } else { + res = searchFinalFile(foundpath, pm3dir, asis, silent); } } + + if (res != PM3_SUCCESS) { + res = searchFinalFile(foundpath, pm3dir, filename, silent); + } + + if (res != PM3_SUCCESS) { + if ((res == PM3_EFILE) && (!silent)) { + if (asis != NULL) { + PrintAndLogEx(FAILED, "Error - can't find `" _YELLOW_("%s") "` nor `" _YELLOW_("%s") "`", asis, filename); + } else { + PrintAndLogEx(FAILED, "Error - can't find `" _YELLOW_("%s") "`", filename); + } + } + } + + free(asis); free(filename); return res; } diff --git a/client/src/fileutils.h b/client/src/fileutils.h index 7323a66e2..0363d69f9 100644 --- a/client/src/fileutils.h +++ b/client/src/fileutils.h @@ -33,6 +33,120 @@ #include "cmdhftopaz.h" // TOPAZ defines #include "mifare/mifaredefault.h" // MFP / AES defines #include "iso15.h" // iso15_tag_t +#include "desfire.h" // desfire_app_keys_t + +// keys recovered from a DESFire PICC by `hf mfdes chk`, one entry per application +typedef struct { + iso14a_card_select_t card_info; + uint8_t appcount; + desfire_app_keys_t app[DESFIRE_MAX_APP_COUNT]; +} desfire_keys_dump_t; + +//----------------------------------------------------------------------------- +// DESFire card image, as written by `hf mfdes dump` and read back by +// `hf mfdes view`. See doc/mfdes_dump_format.md for the on-disk JSON schema. +// +// Contents of a file live in a heap buffer hanging off desfire_dump_file_t, +// so the image can hold real file sizes without a multi-megabyte struct. +// Whoever fills or loads one of these owns those buffers -- release them with +// desfire_dump_free() before dropping the image. +//----------------------------------------------------------------------------- + +// keys of one application. The key type is a property of the application, not +// of the individual key, so it lives in desfire_dump_app_t. +// +// A key version is readable without knowing the key, so the two are tracked +// separately: `versionknown` without `present` is the normal case for a key we +// found but could not recover +typedef struct { + uint8_t present[DESFIRE_MAX_KEY_COUNT]; // 1 = we have the key value + uint8_t versionknown[DESFIRE_MAX_KEY_COUNT]; // 1 = we read the key version + uint8_t version[DESFIRE_MAX_KEY_COUNT]; + uint8_t key[DESFIRE_MAX_KEY_COUNT][DESFIRE_MAX_KEY_SIZE]; +} desfire_dump_keys_t; + +typedef struct { + uint8_t num; // file number, 0x00 ... 0x1F + uint16_t isofid; // ISO file id, 0 = none + uint8_t type; // raw file type byte, 0x00 ... 0x05 + uint8_t commmode; // raw file communication mode + uint16_t accessrights; // raw access rights word + uint8_t addrights_len; + uint16_t addrights[16]; // additional access rights + + uint32_t size; // standard / backup data file size + uint32_t lowerlimit; // value file + uint32_t upperlimit; + uint32_t value; + uint8_t limitedcredit; + uint32_t recordsize; // record file + uint32_t maxrecords; + uint32_t currecords; + + bool settings_ok; // file settings were read + + // read_ok false means "we could not read it", which is not the same as + // "the file is empty". Never fill `data` with zeros to paper over it, a + // simulator would then confidently answer with contents the card never had. + bool read_ok; + uint32_t datalen; + uint8_t *data; // heap, NULL when read_ok is false +} desfire_dump_file_t; + +// One application. The PICC level is an application too -- AID 000000 -- and +// uses this same struct, so key settings and keys are always stated against an +// AID instead of floating loose at card level +typedef struct { + uint32_t aid; + uint16_t isofid; + uint8_t dfname[16]; + uint8_t dfnamelen; + + uint8_t keysettings; + uint8_t numkeysraw; + uint8_t numkeys; + uint8_t keytype; // DesfireCryptoAlgorithm, one per application + bool settings_ok; // key settings were read + bool auth_ok; // we authenticated to this application + + desfire_dump_keys_t keys; + + uint8_t filecount; + desfire_dump_file_t files[DESFIRE_MAX_FILE_COUNT]; +} desfire_dump_app_t; + +typedef struct { + // card identity only. Anything key related belongs to an application + iso14a_card_select_t card_info; + + // GetVersion answers in three frames and the frames are not the same shape + // across generations -- D40 and EV1 close with UID||BatchNo[5]||CW||Year + // while EV3 re-cuts it as UID||BatchNo[3]||TypeID[2]||CW||Year -- so each is + // kept raw and separate rather than parsed into fields. + // HW/SW frames 7 bytes each: vendor, type, subtype, major, minor, storage, + // protocol. Major+minor identify the generation, see prime.c + uint8_t versionhw[7]; + uint8_t versionhwlen; + uint8_t versionsw[7]; + uint8_t versionswlen; + uint8_t versionprod[14]; // UID and production details + uint8_t versionprodlen; + uint8_t signature[56]; // NXP originality signature + uint8_t signaturelen; + + uint32_t freemem; + bool freemem_ok; + + desfire_dump_app_t picc; // AID 000000, written as Applications.000000 + + // real applications only, the PICC is not counted here + uint8_t appcount; + desfire_dump_app_t app[DESFIRE_MAX_APP_COUNT]; +} desfire_dump_t; + +// release the per-file heap buffers inside an image. Safe on a NULL pointer +// and safe to call twice. Does not free the image itself. +void desfire_dump_free(desfire_dump_t *dump); typedef union { void *v; @@ -42,6 +156,8 @@ typedef union { iso14a_mf_extdump_t *mfc; iso14a_mf_dump_ev1_t *mfc_ev1; iso15_tag_t *iso15; + desfire_keys_dump_t *mfdes; + desfire_dump_t *mfdesdump; } udata_t; typedef enum { @@ -69,6 +185,8 @@ typedef enum { jsfMfPlusKeys, jsfCustom, jsfMfDesfireKeys, + jsfMfDesfireKeys_v2, + jsfMfDesfire_v1, jsfEM4x05, jsfEM4x69, jsfEM4x50, diff --git a/client/src/flash.c b/client/src/flash.c index abfb93106..7366bc007 100644 --- a/client/src/flash.c +++ b/client/src/flash.c @@ -462,11 +462,34 @@ fail: return res; } +static bool port_is_wireless(const char *name) { + if (name == NULL) { + return false; + } + return (strncmp(name, "tcp:", 4) == 0) || + (strncmp(name, "udp:", 4) == 0) || + (strncmp(name, "bt:", 3) == 0); +} + // Get the state of the proxmark, backwards compatible -static int get_proxmark_state(uint32_t *state) { - SendCommandBL(CMD_DEVICE_INFO, 0, 0, 0, NULL, 0); +static int get_proxmark_state(uint32_t *state, const char *serial_port_name) { PacketResponseNG resp; - WaitForResponse(CMD_UNKNOWN, &resp); // wait for any response. No timeout. + bool got = false; + for (int attempt = 0; (attempt < 3) && (got == false); attempt++) { + clearCommandBuffer(); + SendCommandBL(CMD_DEVICE_INFO, 0, 0, 0, NULL, 0); + got = WaitForResponseTimeout(CMD_UNKNOWN, &resp, 3000); + } + if (got == false) { + if (port_is_wireless(serial_port_name)) { + PrintAndLogEx(ERR, "No reply from bootloader. Wireless bootrom is not talking BWM."); + PrintAndLogEx(INFO, "Flash a BWM-capable bootrom over USB: " _YELLOW_("make clean && make bootrom") " then ./pm3-flash-bootrom"); + } else { + PrintAndLogEx(ERR, "No reply from bootloader."); + } + PrintAndLogEx(INFO, "Nothing was written. Short-press the button to leave flash mode."); + return PM3_ETIMEOUT; + } // Three outcomes: // 1. The old bootrom code will ignore CMD_DEVICE_INFO, but respond with an ACK @@ -485,6 +508,15 @@ static int get_proxmark_state(uint32_t *state) { case CMD_DEVICE_INFO: { // bootloader replies are OLD frames by design, see doc/new_frame_format.md *state = resp.oldarg[0]; + PrintAndLogEx(DEBUG, "DEVICE_INFO flags 0x%08x", *state); + // A BWM bootrom reports the baud it probed in oldarg[2]; 0 means no ESP answered. + if ((*state & DEVICE_INFO_FLAG_UNDERSTANDS_BWM_STREAM) == DEVICE_INFO_FLAG_UNDERSTANDS_BWM_STREAM) { + if (resp.oldarg[2]) { + PrintAndLogEx(INFO, "Bootloader BWM link at " _YELLOW_("%" PRIu64) " baud", resp.oldarg[2]); + } else { + PrintAndLogEx(WARNING, "Bootloader found no BWM module (no ESP answered on 921600 or 460800)"); + } + } break; } default: { @@ -499,7 +531,7 @@ static int get_proxmark_state(uint32_t *state) { static int enter_bootloader(char *serial_port_name, bool wait_appear) { uint32_t state = 0; - int ret = get_proxmark_state(&state); + int ret = get_proxmark_state(&state, serial_port_name); if (ret != PM3_SUCCESS) { return ret; } @@ -547,15 +579,31 @@ static int enter_bootloader(char *serial_port_name, bool wait_appear) { // Wait for the device to respond with either ACK or NACK. static int wait_for_ack(PacketResponseNG *ack) { - WaitForResponse(CMD_UNKNOWN, ack); - if (ack->cmd != CMD_ACK) { + // Timeout + skip stale replies (a lost byte can yield cmd 0x0000). + uint64_t deadline = msclock() + 15000; + for (;;) { + uint64_t now = msclock(); + if (now >= deadline) { + PrintAndLogEx(ERR, "No ACK from bootloader (timeout)"); + return PM3_ETIMEOUT; + } + if (WaitForResponseTimeout(CMD_UNKNOWN, ack, deadline - now) == false) { + PrintAndLogEx(ERR, "No ACK from bootloader (timeout)"); + return PM3_ETIMEOUT; + } + if (ack->cmd == CMD_ACK) { + return PM3_SUCCESS; + } + if (ack->cmd != CMD_NACK) { + PrintAndLogEx(DEBUG, "Discarding stale reply 0x%04x while waiting for ACK", ack->cmd); + continue; + } PrintAndLogEx(ERR, "\nError: Unexpected reply 0x%04x %s (expected ACK)", ack->cmd, (ack->cmd == CMD_NACK) ? "NACK" : "" ); return PM3_ESOFT; } - return PM3_SUCCESS; } // If the BOOTLOADER is too old or damaged, we can suggest that the user update the BOOT. @@ -664,10 +712,15 @@ static bool files_target_bootloader(flash_file_t *files, uint8_t num_files, uint // Sending simple cmd without any parameters or data payload, just for arg0. static void send_cmd_for_arg0(const uint64_t cmd, uint32_t *arg0) { - SendCommandBL(cmd, 0, 0, 0, NULL, 0); - PacketResponseNG resp; - WaitForResponse(cmd, &resp); - *arg0 = resp.oldarg[0]; + for (int attempt = 0; attempt < 2; attempt++) { + clearCommandBuffer(); + SendCommandBL(cmd, 0, 0, 0, NULL, 0); + PacketResponseNG resp; + if (WaitForResponseTimeout(cmd, &resp, 8000)) { + *arg0 = resp.oldarg[0]; + return; + } + } } // Go into flashing mode @@ -679,11 +732,19 @@ int flash_start_flashing(int enable_bl_writes, char *serial_port_name, flash_dev } uint32_t state = 0; - ret = get_proxmark_state(&state); + ret = get_proxmark_state(&state, serial_port_name); if (ret != PM3_SUCCESS) { return ret; } + if (port_is_wireless(serial_port_name) && + ((state & DEVICE_INFO_FLAG_UNDERSTANDS_BWM_STREAM) != DEVICE_INFO_FLAG_UNDERSTANDS_BWM_STREAM)) { + PrintAndLogEx(ERR, "This bootloader cannot flash over a wireless link (flags 0x%08x)", state); + PrintAndLogEx(INFO, "Flash the bootrom over USB once, then retry."); + PrintAndLogEx(INFO, "Nothing was written. Short-press the button to leave flash mode."); + return PM3_EOPABORTED; + } + flash_dev->chiptype = MAIN_CHIP_TYPE_NONE; if ((state & DEVICE_INFO_FLAG_UNDERSTANDS_CHIP_TYPE) == DEVICE_INFO_FLAG_UNDERSTANDS_CHIP_TYPE) { send_cmd_for_arg0(CMD_CHIP_TYPE, &flash_dev->chiptype); @@ -834,13 +895,15 @@ static void flash_write_err_software(int pm3_err) { // Send finish write cmd and waiting for response. // The send_buf length is always 512byte(PM3_CMD_DATA_SIZE_OLD) -static int send_finish_write_cmd(uint32_t address, int magic, uint8_t *send_buf, PacketResponseNG *resp) { +// block_off is the byte offset within the erase/write unit (unused on ICOPYX). +static int send_finish_write_cmd(uint32_t address, int magic, uint32_t block_off, uint8_t *send_buf, PacketResponseNG *resp) { // The sending length is always PM3_CMD_DATA_SIZE_OLD, which is 512 bytes, because of the limitation of the old frame. const int send_len = PM3_CMD_DATA_SIZE_OLD; #if defined ICOPYX // To prevent users from flashing unsupported firmware, icopyx checks arg1 and arg2 in this command. // Therefore, when sending magic to the device, we should not choose a value that happens to be the same as icopyx. // In fact, neither PM3V nor PM5V will be 0xff or 0x1fd, so this should have strong robustness. + (void)block_off; SendCommandBL(CMD_FINISH_WRITE, address, 0xff, 0x1fd, send_buf, send_len); #else // If it's an older version of the flasher or a flasher specific to icopyx, then arg1 should be 0x00 or 0xff, @@ -859,7 +922,8 @@ static int send_finish_write_cmd(uint32_t address, int magic, uint8_t *send_buf, // --- // The new client version can always continue to OTA update the device version, // and can also OTA update the latest version of PM5. - SendCommandBL(CMD_FINISH_WRITE, address, magic, 0, send_buf, send_len); + // arg[2] is the byte offset within the unit. Old bootroms ignore it; BWM bootroms place at arg[2]/4. + SendCommandBL(CMD_FINISH_WRITE, address, magic, block_off, send_buf, send_len); #endif return wait_for_ack(resp); } @@ -884,32 +948,62 @@ static int write_block(uint32_t address, int magic, uint8_t *data, uint32_t leng memcpy(block_buf, data, length); // copy data by valid length // Send in packets int ret = PM3_SUCCESS; - uint32_t sent = 0; - while (sent < aligned_len) { - PacketResponseNG resp; - ret = send_finish_write_cmd(address, magic, block_buf + sent, &resp); - if (ret) { - // On new version of flasher, the arg1 is error code of PM3_E*, old version is 0x00, so we can always check it. - if (resp.oldarg[1]) { // 0x00 == PM3_SUCCESS - flash_write_err_software(resp.oldarg[1]); - } else { - // If not PM3_E*, maybe some errors of flash write occurred. Or is old version boot. - if (flash_dev->chiptype == MAIN_CHIP_TYPE_AT91) { - flash_write_err_on_at91(resp.oldarg[0]); - } else if (flash_dev->chiptype == MAIN_CHIP_TYPE_AT32) { - flash_write_err_on_at32(resp.oldarg[0]); - } else { - PrintAndLogEx(ERR, "Unknown chip type, cannot decode error information"); + for (int attempt = 0; attempt < 4; attempt++) { + uint32_t sent = 0; + ret = PM3_SUCCESS; + while (sent < aligned_len) { + PacketResponseNG resp; + ret = send_finish_write_cmd(address, magic, sent, block_buf + sent, &resp); + if (ret) { + if (ret == PM3_ETIMEOUT) { + PrintAndLogEx(WARNING, "No ACK at 0x%08x (packet %u), retrying block", + address, sent / PM3_CMD_DATA_SIZE_OLD); + msleep(400); + break; } + // On new version of flasher, the arg1 is error code of PM3_E*, old version is 0x00, so we can always check it. + if (resp.oldarg[1]) { // 0x00 == PM3_SUCCESS + flash_write_err_software(resp.oldarg[1]); + } else { + // If not PM3_E*, maybe some errors of flash write occurred. Or is old version boot. + if (flash_dev->chiptype == MAIN_CHIP_TYPE_AT91) { + flash_write_err_on_at91(resp.oldarg[0]); + } else if (flash_dev->chiptype == MAIN_CHIP_TYPE_AT32) { + flash_write_err_on_at32(resp.oldarg[0]); + } else { + PrintAndLogEx(ERR, "Unknown chip type, cannot decode error information"); + } + } + free(block_buf); // remember to free buffer + return ret; } + sent += PM3_CMD_DATA_SIZE_OLD; + } + if (ret == PM3_SUCCESS && sent >= aligned_len) { break; } - sent += PM3_CMD_DATA_SIZE_OLD; } free(block_buf); // remember to free buffer return ret; } +// Hand the signals back to whoever had them. The client needs SIGINT to be +// able to quit on CTRL-C once the flashing is done +static void restore_progress_signals(void (*old_sigint)(int), void (*old_sigwinch)(int)) { + + if (old_sigint != SIG_ERR) { + signal(SIGINT, old_sigint); + } + +#ifndef _WIN32 + if (old_sigwinch != SIG_ERR) { + signal(SIGWINCH, old_sigwinch); + } +#else + (void) old_sigwinch; +#endif +} + // Write a file's segments to Flash int flash_write(flash_file_t *ctx, flash_dev_t *flash_dev) { @@ -930,11 +1024,14 @@ int flash_write(flash_file_t *ctx, flash_dev_t *flash_dev) { uint32_t baddr = seg->start; int pct = 0; + void (*old_sigint)(int) = SIG_ERR; + void (*old_sigwinch)(int) = SIG_ERR; + if (blocks > 50) { - signal(SIGINT, hadouken_on_sigint); + old_sigint = signal(SIGINT, hadouken_on_sigint); #ifndef _WIN32 - signal(SIGWINCH, hadouken_on_sigwinch); + old_sigwinch = signal(SIGWINCH, hadouken_on_sigwinch); #endif hadouken_start(30.0, 0, 1); @@ -950,6 +1047,7 @@ int flash_write(flash_file_t *ctx, flash_dev_t *flash_dev) { if (write_block(baddr, ctx->ver_info->magic, data, block_size, flash_dev) < 0) { if (blocks > 50) { hadouken_stop(); + restore_progress_signals(old_sigint, old_sigwinch); } PrintAndLogEx(ERR, "Error writing block %d of %u", block, blocks); return PM3_EFATAL; @@ -968,6 +1066,7 @@ int flash_write(flash_file_t *ctx, flash_dev_t *flash_dev) { if (blocks > 50) { hadouken_stop(); + restore_progress_signals(old_sigint, old_sigwinch); } fflush(stdout); } diff --git a/client/src/frame_data2.c b/client/src/frame_data2.c new file mode 100644 index 000000000..592ec1f99 --- /dev/null +++ b/client/src/frame_data2.c @@ -0,0 +1,466 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- + +#include "frame_data2.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif +#include "commonutil.h" // ARRAYLEN + +// ---- ANSI ---------------------------------------------------------------- +#define CSI "\x1b[" +#define HIDE_CURSOR CSI "?25l" +#define SHOW_CURSOR CSI "?25h" +#define CLEAR_LINE CSI "2K" +#define COL_RESET CSI "0m" + +#define MAX_COLS 220 +#define MAX_ROWS 40 +#define FRAME_MS 40.0 // 25 fps +#define FADE_MS 1200.0 // teardown fade on stop + +#define TRUECOLOR 1 + +static const char *GLYPHS[] = { + "\xef\xbd\xa6", "\xef\xbd\xa7", "\xef\xbd\xa8", "\xef\xbd\xa9", "\xef\xbd\xaa", "\xef\xbd\xab", "\xef\xbd\xac", "\xef\xbd\xad", "\xef\xbd\xae", "\xef\xbd\xaf", "\xef\xbd\xb0", "\xef\xbd\xb1", "\xef\xbd\xb2", "\xef\xbd\xb3", "\xef\xbd\xb4", "\xef\xbd\xb5", + "\xef\xbd\xb6", "\xef\xbd\xb7", "\xef\xbd\xb8", "\xef\xbd\xb9", "\xef\xbd\xba", "\xef\xbd\xbb", "\xef\xbd\xbc", "\xef\xbd\xbd", "\xef\xbd\xbe", "\xef\xbd\xbf", "\xef\xbe\x80", "\xef\xbe\x81", "\xef\xbe\x82", "\xef\xbe\x83", "\xef\xbe\x84", "\xef\xbe\x85", + "\xef\xbe\x86", "\xef\xbe\x87", "\xef\xbe\x88", "\xef\xbe\x89", "\xef\xbe\x8a", "\xef\xbe\x8b", "\xef\xbe\x8c", "\xef\xbe\x8d", "\xef\xbe\x8e", "\xef\xbe\x8f", "\xef\xbe\x90", "\xef\xbe\x91", "\xef\xbe\x92", "\xef\xbe\x93", "\xef\xbe\x94", "\xef\xbe\x95", + "\xef\xbe\x96", "\xef\xbe\x97", "\xef\xbe\x98", "\xef\xbe\x99", "\xef\xbe\x9a", "\xef\xbe\x9b", "\xef\xbe\x9c", "\xef\xbe\x9d", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", +}; + +#define LOGO_BOLD 1 + +#if LOGO_BOLD +#define FONT_W 7 +#define FONT_H 9 +static const char *FONT[6][FONT_H] = { + { "#######", "#######", "..###..", "..###..", "..###..", "..###..", "..###..", "#######", "#######" }, // I + { ".#####.", "#######", "###..##", "###....", "###....", "###....", "###..##", "#######", ".#####." }, // C + { "#######", "#######", "###....", "###....", "#####..", "###....", "###....", "#######", "#######" }, // E + { "##...##", "###.###", "#######", "#######", "##.#.##", "##...##", "##...##", "##...##", "##...##" }, // M + { "..###..", ".#####.", "##...##", "##...##", "#######", "#######", "##...##", "##...##", "##...##" }, // A + { "##...##", "###..##", "####.##", "#######", "##.####", "##..###", "##...##", "##...##", "##...##" }, // N +}; +#else +#define FONT_W 5 +#define FONT_H 7 +static const char *FONT[6][FONT_H] = { + { "#####", "..#..", "..#..", "..#..", "..#..", "..#..", "#####" }, // I + { ".###.", "#...#", "#....", "#....", "#....", "#...#", ".###." }, // C + { "#####", "#....", "#....", "####.", "#....", "#....", "#####" }, // E + { "#...#", "##.##", "#.#.#", "#.#.#", "#...#", "#...#", "#...#" }, // M + { ".###.", "#...#", "#...#", "#####", "#...#", "#...#", "#...#" }, // A + { "#...#", "##..#", "#.#.#", "#.#.#", "#..##", "#...#", "#...#" }, // N +}; +#endif + +#define LOGO_LEN 6 + +static unsigned char g_mask[MAX_ROWS][MAX_COLS]; + +static void build_mask(int rows, int cols) { + memset(g_mask, 0, sizeof(g_mask)); + + const int gap = 2; // columns between letters + int w = LOGO_LEN * FONT_W + (LOGO_LEN - 1) * gap; + if (rows < FONT_H || cols < w) return; + + int x0 = (cols - w) / 2; + int y0 = (rows - FONT_H) / 2; + + for (int i = 0; i < LOGO_LEN; i++) + for (int r = 0; r < FONT_H; r++) + for (int c = 0; c < FONT_W; c++) + if (FONT[i][r][c] == '#') + g_mask[y0 + r][x0 + i * (FONT_W + gap) + c] = 1; +} + +typedef struct { + double y; // head position in rows (fractional -> smooth motion) + double speed; // rows per frame + int len; // trail length + int delay; // frames until respawn +} drop_t; + +#define DROPS_PER_COL 2 +#define FIELD_T 0.10 + +// ---- shared state -------------------------------------------------------- +static pthread_mutex_t g_out_lock = PTHREAD_MUTEX_INITIALIZER; + +static drop_t g_drop[MAX_COLS][DROPS_PER_COL]; +static int g_cell[MAX_ROWS][MAX_COLS]; +static char *g_buf; +static int g_rows, g_cols; +static unsigned char g_seen[MAX_ROWS][MAX_COLS]; +static double g_fade = 1.0; +static int g_fading = 0; +static volatile sig_atomic_t g_band_open = 0; // guarded by g_out_lock, +// except for the async-signal-safe readers below +static volatile int g_running = 0; // thread control +static pthread_t g_thread; +static int g_thread_rows = 12; + +static volatile sig_atomic_t g_stop = 0; +static void on_sigint(int sig) { (void)sig; g_stop = 1; } + +// ---- small helpers ------------------------------------------------------- +static void sleep_ms(double ms) { + struct timespec ts; + ts.tv_sec = (time_t)(ms / 1000.0); + ts.tv_nsec = (long)((ms - ts.tv_sec * 1000.0) * 1e6); + nanosleep(&ts, NULL); +} + +static int term_width(void) { +#ifdef _WIN32 + CONSOLE_SCREEN_BUFFER_INFO csbi; + if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi)) { + return csbi.srWindow.Right - csbi.srWindow.Left + 1; + } +#else + struct winsize ws; + if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col > 0) + return ws.ws_col; +#endif + return 80; +} + +static double frand(void) { + int r = rand(); + return (double)r / (double)RAND_MAX; +} + +static void drop_respawn(drop_t *d, int rows) { + d->y = 0.0; + d->speed = 0.14 + frand() * 0.34; // slow, drifting fall + d->len = 6 + (int)(frand() * (rows * 1.4)); // longer trails + d->delay = (int)(frand() * 18.0); // shorter dead time +} + +#if !TRUECOLOR +static int ramp(double t) { + if (t > 0.82) return 46; + if (t > 0.62) return 40; + if (t > 0.42) return 34; + if (t > 0.24) return 28; + if (t > 0.10) return 23; + return 22; // resting field level +} +#endif + +// ---- band management ----------------------------------------------------- +static void band_open_locked(int rows) { + printf(HIDE_CURSOR); + for (int i = 0; i < rows; i++) putchar('\n'); // reserve the space + printf(CSI "%dA", rows); // climb back to its top + fflush(stdout); + g_band_open = 1; +} + +static void band_close_locked(void) { + if (!g_band_open) return; + for (int i = 0; i < g_rows; i++) { + printf("\r" CLEAR_LINE); + if (i < g_rows - 1) putchar('\n'); + } + printf("\r" CSI "%dA" COL_RESET SHOW_CURSOR, g_rows - 1); + fflush(stdout); + g_band_open = 0; +} + +static char *put_cell(char *p, double t, int head, const char *g) { +#if TRUECOLOR + int gr = (int)(255.0 * t + 0.5); + int rd = (int)((head ? 255.0 : 20.0) * t + 0.5); + int bl = (int)((head ? 255.0 : 35.0) * t + 0.5); + return p + sprintf(p, CSI "0;38;2;%d;%d;%dm%s", rd, gr, bl, g); +#else + if (head && t > 0.75) return p + sprintf(p, CSI "0;1;38;5;231m%s", g); + return p + sprintf(p, CSI "0;38;5;%dm%s", ramp(t), g); +#endif +} + +// ---- terminal rescue ----------------------------------------------------- +// +// Called from the client's signal handlers, so nothing here may take a lock +// or touch stdio. A hidden cursor is the one piece of state that outlives the +// process, and it is a single write() to put back. + +void fx_terminal_restore(void) { + if (g_band_open) { + ssize_t ignored = write(STDOUT_FILENO, SHOW_CURSOR, sizeof(SHOW_CURSOR) - 1); + (void) ignored; + } +} + +void fx_terminal_resume(void) { + if (g_band_open) { + ssize_t ignored = write(STDOUT_FILENO, HIDE_CURSOR, sizeof(HIDE_CURSOR) - 1); + (void) ignored; + } +} + +// ---- renderer ------------------------------------------------------------ +static void render_frame_locked(void) { + char *p = g_buf; + + for (int y = 0; y < g_rows; y++) { + p += sprintf(p, "\r" CLEAR_LINE); + + for (int x = 0; x < g_cols; x++) { + + if (g_mask[y][x]) { + *p++ = ' '; + continue; + } + + double best = -1.0; + int head = 0; + + for (int k = 0; k < DROPS_PER_COL; k++) { + drop_t *dr = &g_drop[x][k]; + if (dr->delay > 0) continue; + + double d = dr->y - (double)y; + if (d < 0 || d >= dr->len) continue; + + if (d < 1.0) { head = 1; best = 1.0; } + else { + double t = 1.0 - (d / (double)dr->len); + if (t > best) best = t; + } + } + + int is_field = 0; + + if (best < 0) { + + if (FIELD_T <= 0.0 || !g_seen[y][x]) { + *p++ = ' '; + continue; + } + best = FIELD_T; + is_field = 1; + } else { + g_seen[y][x] = 1; + } + + double t = best * g_fade; + if (t < 0.02) { + *p++ = ' '; + continue; + } + + if (frand() < (is_field ? 0.01 : 0.04)) + g_cell[y][x] = (int)(frand() * ARRAYLEN(GLYPHS)); + + const char *g = GLYPHS[g_cell[y][x]]; + + p = put_cell(p, t, head, g); + } + p += sprintf(p, COL_RESET); + if (y < g_rows - 1) *p++ = '\n'; + } + + p += sprintf(p, "\r" CSI "%dA", g_rows - 1); + *p = '\0'; + + fputs(g_buf, stdout); + fflush(stdout); +} + +static void advance(void) { + for (int x = 0; x < g_cols; x++) { + for (int k = 0; k < DROPS_PER_COL; k++) { + drop_t *d = &g_drop[x][k]; + if (d->delay > 0) { + d->delay--; + continue; + } + d->y += d->speed; + if (d->y - d->len > g_rows) { + if (g_fading) { + d->delay = 1 << 24; // let it die, no respawn + } else { + drop_respawn(d, g_rows); + } + } + } + } +} + +void fx_printf(const char *fmt, ...) { + pthread_mutex_lock(&g_out_lock); + + int reopen = g_band_open; + int rows = g_rows; + + band_close_locked(); + + va_list ap; + va_start(ap, fmt); + vprintf(fmt, ap); + va_end(ap); + putchar('\n'); + + if (reopen) { + band_open_locked(rows); + } else { + fflush(stdout); + } + + pthread_mutex_unlock(&g_out_lock); +} + +static int fx_state_init(int rows) { + g_cols = term_width(); + if (g_cols > MAX_COLS) g_cols = MAX_COLS; + if (rows > MAX_ROWS) rows = MAX_ROWS; + if (rows < 3) rows = 3; + g_rows = rows; + + memset(g_seen, 0, sizeof(g_seen)); + g_fade = 1.0; + g_fading = 0; + + time_t now = time(NULL); + srand((unsigned)now); + for (int x = 0; x < g_cols; x++) { + for (int k = 0; k < DROPS_PER_COL; k++) { + drop_respawn(&g_drop[x][k], g_rows); + g_drop[x][k].y = -1.0 - frand() * g_rows * 0.45 - k * 2.0; + } + } + for (int y = 0; y < g_rows; y++) + for (int x = 0; x < g_cols; x++) + g_cell[y][x] = (int)(frand() * ARRAYLEN(GLYPHS)); + + build_mask(g_rows, g_cols); + + g_buf = malloc((size_t)g_rows * (g_cols * 32 + 32) + 64); + return g_buf != NULL; +} + +static void step_frame(void) { + pthread_mutex_lock(&g_out_lock); + render_frame_locked(); + pthread_mutex_unlock(&g_out_lock); + + advance(); + sleep_ms(FRAME_MS); + + if (g_fading) { + g_fade -= FRAME_MS / FADE_MS; + if (g_fade < 0.0) g_fade = 0.0; + } +} + +static void fade_out(void) { + g_fading = 1; + while (!g_stop && g_fade > 0.0) { + step_frame(); + } +} + +// Blocking flavour. +void fx_matrix_run(int rows, double duration_ms) { + if (!isatty(STDOUT_FILENO)) return; + +#ifdef _WIN32 + void (*old)(int) = signal(SIGINT, on_sigint); +#else + struct sigaction sa = {0}, old; + sa.sa_handler = on_sigint; + sigaction(SIGINT, &sa, &old); +#endif + + if (!fx_state_init(rows)) goto out; + + pthread_mutex_lock(&g_out_lock); + band_open_locked(g_rows); + pthread_mutex_unlock(&g_out_lock); + + for (double t = 0; !g_stop && t < duration_ms; t += FRAME_MS) + step_frame(); + + fade_out(); + + pthread_mutex_lock(&g_out_lock); + band_close_locked(); + pthread_mutex_unlock(&g_out_lock); + + free(g_buf); + g_buf = NULL; +out: +#ifdef _WIN32 + if (old != SIG_ERR) { + signal(SIGINT, old); + } +#else + sigaction(SIGINT, &old, NULL); +#endif + g_stop = 0; +} + +static void *fx_thread(void *arg) { + (void)arg; + + if (!fx_state_init(g_thread_rows)) return NULL; + + pthread_mutex_lock(&g_out_lock); + band_open_locked(g_rows); + pthread_mutex_unlock(&g_out_lock); + + while (g_running && !g_stop) + step_frame(); + + fade_out(); // g_running cleared by fx_matrix_stop() + + pthread_mutex_lock(&g_out_lock); + band_close_locked(); + pthread_mutex_unlock(&g_out_lock); + + free(g_buf); + g_buf = NULL; + return NULL; +} + +void fx_matrix_start(int rows) { + if (!isatty(STDOUT_FILENO) || g_running) return; + g_thread_rows = rows; + g_running = 1; + pthread_create(&g_thread, NULL, fx_thread, NULL); +} + +void fx_matrix_stop(void) { + if (!g_running) return; + g_running = 0; + pthread_join(g_thread, NULL); +} diff --git a/client/src/frame_data2.h b/client/src/frame_data2.h new file mode 100644 index 000000000..0c6551c38 --- /dev/null +++ b/client/src/frame_data2.h @@ -0,0 +1,33 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- + +#ifndef __FRAME_DATA2_H__ +#define __FRAME_DATA2_H__ + +#include "common.h" + + +void fx_matrix_run(int rows, double duration_ms); +void fx_matrix_start(int rows); +void fx_matrix_stop(void); +void fx_printf(const char *fmt, ...); + +// Async-signal-safe, for use from the client's signal handlers. A stopped or +// killed process must not leave the cursor hidden behind it +void fx_terminal_restore(void); +void fx_terminal_resume(void); + +#endif // __FRAME_DATA2_H__ diff --git a/client/src/graph.c b/client/src/graph.c index 80c1e4dc0..46c6a3309 100644 --- a/client/src/graph.c +++ b/client/src/graph.c @@ -648,3 +648,26 @@ size_t restore_buffer8(buffer_savestate_t saveState, uint8_t *dest) { return index; } + +// Save/restore the graph buffer as a unit: contents, length and grid offset. +// A caller that drops restore_bufferS32()'s return leaves g_GraphTraceLen short. +buffer_savestate_t save_graphbuffer(void) { + buffer_savestate_t saveState = save_bufferS32(g_GraphBuffer, g_GraphTraceLen); + saveState.offset = g_GridOffset; + return saveState; +} + +void restore_graphbuffer(buffer_savestate_t saveState) { + size_t len = restore_bufferS32(saveState, g_GraphBuffer); + if (len == 0) { + // nothing was restored, so leave the buffer and its length alone + return; + } + g_GraphTraceLen = len; + g_GridOffset = saveState.offset; +} + +// restore_*() copy out of the save state, the owner frees it after its last restore +void free_buffer_savestate(buffer_savestate_t saveState) { + free((void *)saveState.buffer); +} diff --git a/client/src/graph.h b/client/src/graph.h index 6f0822f96..ea0670ff1 100644 --- a/client/src/graph.h +++ b/client/src/graph.h @@ -67,6 +67,10 @@ size_t restore_buffer32(buffer_savestate_t saveState, uint32_t *dest); size_t restore_bufferS32(buffer_savestate_t saveState, int32_t *dest); size_t restore_buffer8(buffer_savestate_t saveState, uint8_t *dest); +buffer_savestate_t save_graphbuffer(void); +void restore_graphbuffer(buffer_savestate_t saveState); +void free_buffer_savestate(buffer_savestate_t saveState); + #define MAX_GRAPH_TRACE_LEN (40000 * 32) #define GRAPH_SAVE 1 #define GRAPH_RESTORE 0 diff --git a/client/src/mifare/desfirecore.c b/client/src/mifare/desfirecore.c index cd065e766..d5906c076 100644 --- a/client/src/mifare/desfirecore.c +++ b/client/src/mifare/desfirecore.c @@ -258,7 +258,7 @@ const char *DesfireAuthErrorToStr(int error) { case 6: return "mbedtls_aes_setkey_enc failed"; case 7: - return "Sending auth command failed"; + return "Sending auth response (2nd frame) failed"; case 8: return "Authentication failed. Card timeout."; case 9: @@ -302,6 +302,13 @@ const char *DesfireAuthErrorToStr(int error) { default: break; } + + // the select / auth helpers hand PM3_E* codes straight back to the caller, + // so translate those here instead of returning an empty string + if (error < 0) { + return DesfireGetErrorString(error, NULL); + } + return ""; } @@ -327,7 +334,7 @@ char *DesfireWayIDStr(DesfireISOSelectWay way, uint32_t id) { if (way == ISWMF || way == ISWDFName) snprintf(str, sizeof(str), "%s", DesfireSelectWayToStr(way)); else - snprintf(str, sizeof(str), "%s %0*x", DesfireSelectWayToStr(way), (way == ISW6bAID) ? 6 : 4, id); + snprintf(str, sizeof(str), "%s %0*X", DesfireSelectWayToStr(way), (way == ISW6bAID) ? 6 : 4, id); return str; } @@ -430,6 +437,41 @@ void DesfirePrintContext(DesfireContext_t *ctx) { } } +// Table 11 of M075031 footnotes five status codes as "not expected to appear +// during normal operation": the card saying it has damaged or disabled itself. +// Those are never noise, so they are reported whether or not APDU logging is on. +// Everything else is an ordinary refusal, and the caller decides what to say. +// The command a chained 0xAF frame belongs to. 0xAF on its own says nothing +// about which command was being continued, and that is exactly what you want to +// know when a card dies on one. +static uint8_t s_desfire_logical_cmd = 0; + +static void DesfireReportUnrecoverable(uint8_t cmd, uint8_t respcode) { + + if (respcode != MFDES_E_PICC_INTEGRITY && + respcode != MFDES_E_PICC_DISABLED && + respcode != MFDES_E_APPL_INTEGRITY && + respcode != MFDES_E_FILE_INTEGRITY && + respcode != MFDES_E_EEPROM) { + return; + } + + uint16_t sw = DESFIRE_GET_ISO_STATUS(respcode); + + if (cmd == MFDES_ADDITIONAL_FRAME && s_desfire_logical_cmd != 0 && s_desfire_logical_cmd != MFDES_ADDITIONAL_FRAME) { + PrintAndLogEx(WARNING, "Desfire command " _YELLOW_("0x%02X") " frame " _YELLOW_("0xAF") " -> " _RED_("0x%02X") " %s" + , s_desfire_logical_cmd + , respcode + , DesfireGetErrorString(PM3_EAPDU_FAIL, &sw)); + return; + } + + PrintAndLogEx(WARNING, "Desfire command " _YELLOW_("0x%02X") " -> " _RED_("0x%02X") " %s" + , cmd + , respcode + , DesfireGetErrorString(PM3_EAPDU_FAIL, &sw)); +} + static int DESFIRESendApduEx(bool activate_field, sAPDU_t apdu, uint16_t le, uint8_t *result, uint32_t max_result_len, uint32_t *result_len, uint16_t *sw) { if (result_len) *result_len = 0; if (sw) *sw = 0; @@ -476,6 +518,11 @@ static int DESFIRESendApduEx(bool activate_field, sAPDU_t apdu, uint16_t le, uin isw != DESFIRE_GET_ISO_STATUS(MFDES_S_SIGNATURE) && isw != DESFIRE_GET_ISO_STATUS(MFDES_S_ADDITIONAL_FRAME) && isw != DESFIRE_GET_ISO_STATUS(MFDES_S_NO_CHANGES)) { + + if ((isw >> 8) == 0x91) { + DesfireReportUnrecoverable(apdu.INS, isw & 0xFF); + } + if (GetAPDULogging()) { if (isw >> 8 == 0x61) { PrintAndLogEx(ERR, "APDU chaining len: 0x%02x -->", isw & 0xff); @@ -560,6 +607,8 @@ static int DESFIRESendRaw(bool activate_field, uint8_t *data, size_t datalen, ui if (!rcode_ok) { + DesfireReportUnrecoverable(data[0], rcode); + if (GetAPDULogging()) { PrintAndLogEx(ERR, "Command (%02x) ERROR: 0x%02x", data[0], rcode); } @@ -935,6 +984,8 @@ static int DesfireExchangeExSplit(bool activate_field, DesfireContext_t *ctx, ui size_t databuflen = 0; + s_desfire_logical_cmd = cmd; + switch (ctx->cmdSet) { case DCCNative: case DCCNativeISO: @@ -967,6 +1018,15 @@ static int DesfireExchangeExSplit(bool activate_field, DesfireContext_t *ctx, ui break; } + // the status the card gave, whichever path produced it. Every card error + // collapses to PM3_EAPDU_FAIL on the way out, so callers that want to name + // it have to read it from here + if (respcode != NULL) { + ctx->lastRespCode = *respcode; + } + + s_desfire_logical_cmd = 0; + free(databuf); return res; } @@ -1132,7 +1192,7 @@ int DesfireSelectAndAuthenticateEx(DesfireContext_t *dctx, DesfireSecureChannel if (aid == 0x000000) { res = DesfireAnticollision(verbose); if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Desfire anticollision " _RED_("fail")); + PrintAndLogEx(FAILED, "Desfire anticollision " _RED_("failed")); return 200; } @@ -1143,7 +1203,7 @@ int DesfireSelectAndAuthenticateEx(DesfireContext_t *dctx, DesfireSecureChannel } else { res = DesfireSelectAIDHex(dctx, aid, false, 0); if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Desfire select " _RED_("fail")); + PrintAndLogEx(FAILED, "Desfire %s select " _RED_("failed"), DesfireWayIDStr(ISW6bAID, aid)); return 200; } @@ -1160,15 +1220,16 @@ int DesfireSelectAndAuthenticateEx(DesfireContext_t *dctx, DesfireSecureChannel res = DesfireAuthenticate(dctx, secureChannel, verbose); if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Desfire authenticate " _RED_("fail") ". Result: [%d] %s", res, DesfireAuthErrorToStr(res)); + PrintAndLogEx(FAILED, "Desfire %s authentication " _RED_("failed") ". Result [%d] %s", DesfireWayIDStr(ISW6bAID, aid), res, DesfireAuthErrorToStr(res)); return res; } if (DesfireIsAuthenticated(dctx)) { if (verbose) { - PrintAndLogEx(INFO, "Desfire " _GREEN_("authenticated")); + PrintAndLogEx(INFO, "Desfire " _GREEN_("authenticated")); } } else { + PrintAndLogEx(FAILED, "Desfire %s authentication " _RED_("failed") ". Result [%d] %s", DesfireWayIDStr(ISW6bAID, aid), 201, DesfireAuthErrorToStr(201)); return 201; } } @@ -1195,7 +1256,7 @@ int DesfireSelectAndAuthenticateW(DesfireContext_t *dctx, DesfireSecureChannel s res = DesfireISOSelect(dctx, ISSDFName, dctx->selectedDFName, dctx->selectedDFNameLen, resp, &resplen); if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Desfire DF name select " _RED_("error")); + PrintAndLogEx(FAILED, "Desfire DF name select " _RED_("failed")); if (res == PM3_ECARDEXCHANGE || res == PM3_ETIMEOUT || res == PM3_ERFTRANS) { return res; } @@ -1216,7 +1277,7 @@ int DesfireSelectAndAuthenticateW(DesfireContext_t *dctx, DesfireSecureChannel s res = DesfireSelectAIDHex(dctx, id, false, 0); if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Desfire select " _RED_("error")); + PrintAndLogEx(FAILED, "Desfire %s select " _RED_("failed"), DesfireWayIDStr(ISW6bAID, id)); if (res == PM3_ECARDEXCHANGE || res == PM3_ETIMEOUT || res == PM3_ERFTRANS) { return res; } @@ -1232,7 +1293,7 @@ int DesfireSelectAndAuthenticateW(DesfireContext_t *dctx, DesfireSecureChannel s } else { res = DesfireSelectEx(dctx, false, way, id, NULL); if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Desfire %s select " _RED_("error"), DesfireSelectWayToStr(way)); + PrintAndLogEx(FAILED, "Desfire %s select " _RED_("failed"), DesfireWayIDStr(way, id)); if (res == PM3_ECARDEXCHANGE || res == PM3_ETIMEOUT || res == PM3_ERFTRANS) { return res; } @@ -1247,7 +1308,7 @@ int DesfireSelectAndAuthenticateW(DesfireContext_t *dctx, DesfireSecureChannel s // Also select by ISO ID if specified res = DesfireSelectEx(dctx, false, way, id, NULL); if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Desfire %s select " _RED_("error"), DesfireSelectWayToStr(way)); + PrintAndLogEx(FAILED, "Desfire %s select " _RED_("failed"), DesfireWayIDStr(way, id)); if (res == PM3_ECARDEXCHANGE || res == PM3_ETIMEOUT || res == PM3_ERFTRANS) { return res; } @@ -1266,7 +1327,7 @@ int DesfireSelectAndAuthenticateW(DesfireContext_t *dctx, DesfireSecureChannel s res = DesfireSelectAIDHex(dctx, id, false, 0); if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Desfire select " _RED_("error")); + PrintAndLogEx(FAILED, "Desfire %s select " _RED_("failed"), DesfireWayIDStr(ISW6bAID, id)); if (res == PM3_ECARDEXCHANGE || res == PM3_ETIMEOUT || res == PM3_ERFTRANS) { return res; } @@ -1282,7 +1343,7 @@ int DesfireSelectAndAuthenticateW(DesfireContext_t *dctx, DesfireSecureChannel s } else { res = DesfireSelectEx(dctx, true, way, id, NULL); if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Desfire %s select " _RED_("error"), DesfireSelectWayToStr(way)); + PrintAndLogEx(FAILED, "Desfire %s select " _RED_("failed"), DesfireWayIDStr(way, id)); if (res == PM3_ECARDEXCHANGE || res == PM3_ETIMEOUT || res == PM3_ERFTRANS) { return res; } @@ -1296,7 +1357,7 @@ int DesfireSelectAndAuthenticateW(DesfireContext_t *dctx, DesfireSecureChannel s if (selectfile) { res = DesfireSelectEx(dctx, false, ISWIsoID, isofileid, NULL); if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Desfire iso file select " _RED_("error")); + PrintAndLogEx(FAILED, "Desfire %s iso file %04x select " _RED_("failed"), DesfireWayIDStr(way, id), isofileid); if (res == PM3_ECARDEXCHANGE || res == PM3_ETIMEOUT || res == PM3_ERFTRANS) { return res; } @@ -1311,15 +1372,16 @@ int DesfireSelectAndAuthenticateW(DesfireContext_t *dctx, DesfireSecureChannel s if (noauth == false) { res = DesfireAuthenticate(dctx, secureChannel, verbose); if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Desfire authenticate " _RED_("error") ". Result: [%d] %s", res, DesfireAuthErrorToStr(res)); + PrintAndLogEx(FAILED, "Desfire %s authentication " _RED_("failed") ". Result [%d] %s", DesfireWayIDStr(way, id), res, DesfireAuthErrorToStr(res)); return res; } if (DesfireIsAuthenticated(dctx)) { if (verbose) { - PrintAndLogEx(INFO, "Desfire " _GREEN_("authenticated")); + PrintAndLogEx(INFO, "Desfire " _GREEN_("authenticated")); } } else { + PrintAndLogEx(FAILED, "Desfire %s authentication " _RED_("failed") ". Result [%d] %s", DesfireWayIDStr(way, id), 201, DesfireAuthErrorToStr(201)); return 201; } } @@ -1990,10 +2052,60 @@ int DesfireFillAppList(DesfireContext_t *dctx, PICCInfo_t *PICCInfo, AppListS ap for (int i = 0; i < buflen; i += 3) appList[i / 3].appNum = DesfireAIDByteToUint(&buf[i]); + // GetDFNames must never be sent inside an authenticated session. Measured on + // three DESFire EV1 8K cards: with a session open, the card answers the first + // 0xAF continuation frame of the chained response with 0xC1 + // PICC_INTEGRITY_ERROR, "PICC will be disabled", and is dead from then on. + // Unauthenticated the identical frames are answered normally. + // + // The EV1 datasheet never says how secure messaging applies across 0xAF + // frames; EV3 had to spell it out later (ev3.pdf 7.3.2.2), and EV2/EV3 + // dropped the self-disable status codes altogether. + // + // Key settings bit 1 governs whether the directory commands need + // authentication, and its "needs auth" branch does not name GetDFNames at + // all (M134034 p.39), so no configuration obliges us to send it in-session. + // A card that refuses the plain command costs us the DF names; sending it + // authenticated costs the card. + // + // It is the PICC's session that has to go, not ours -- clearing the context + // alone would leave the card still authenticated and change nothing. + // SelectApplication is what ends it on the card side: "each + // SelectApplication command invalidates the current authentication status" + // (M134034 9.4.5). Afterwards put the caller's session back. + DesfireSecureChannel savedchann = dctx->secureChannel; + uint32_t savedaid = dctx->selectedAID; + bool reauth = DesfireIsAuthenticated(dctx); + + if (reauth && dctx->selectedDFNameLen > 0) { + // selected by DF name rather than by AID, so there is no AID to go back + // to. Not worth guessing with someone's card -- leave the names empty. + PrintAndLogEx(DEBUG, "Selected by DF name, skipping the DF name list"); + reauth = false; + goto dfnames_done; + } + + if (reauth) { + int sres = DesfireSelectAIDHex(dctx, 0x000000, false, 0); + if (sres != PM3_SUCCESS) { + PrintAndLogEx(WARNING, "Could not drop the PICC session, skipping the DF names"); + reauth = false; + goto dfnames_done; + } + } + // result bytes: 3, 2, 1-16. total record size = 24 res = DesfireGetDFList(dctx, buf, &buflen); if (res != PM3_SUCCESS) { - PrintAndLogEx(WARNING, "Desfire GetDFList command " _RED_("error") ". Result: %d", res); + // an error ends the authentication on the PICC as well, so our side is + // down either way. Callers that keep using the card re-authenticate. + dctx->secureChannel = DACNone; + uint16_t dfsw = DESFIRE_GET_ISO_STATUS(dctx->lastRespCode); + PrintAndLogEx(DEBUG, "Desfire GetDFList command " _RED_("error") ". Result: %d, card said " _RED_("0x%02X") " %s" + , res + , dctx->lastRespCode + , DesfireGetErrorString(PM3_EAPDU_FAIL, &dfsw)); + } else if (buflen > 0) { for (int i = 0; i < buflen; i++) { int indx = AppListSearchAID(DesfireAIDByteToUint(&buf[i * 24 + 1]), appList, PICCInfo->appCount); @@ -2009,6 +2121,24 @@ int DesfireFillAppList(DesfireContext_t *dctx, PICCInfo_t *PICCInfo, AppListS ap } } +dfnames_done: + + if (reauth) { + // Back to the session the caller handed us, on whatever was selected + // then. This is not always the PICC: the issuer info path selects and + // authenticates an application before it gets here, and re-authenticating + // AID 000000 with that application's key would simply fail. + int rres = DesfireSelectAIDHex(dctx, savedaid, false, 0); + if (rres == PM3_SUCCESS) { + rres = DesfireAuthenticate(dctx, savedchann, false); + } + + if (rres != PM3_SUCCESS) { + PrintAndLogEx(WARNING, "Could not restore the session on %06X after reading the DF names, continuing without it", savedaid); + DesfireClearSession(dctx); + } + } + // field on-off zone DesfireFillPICCInfo(dctx, PICCInfo, deepmode); @@ -2021,7 +2151,7 @@ int DesfireFillAppList(DesfireContext_t *dctx, PICCInfo_t *PICCInfo, AppListS ap if (res != PM3_SUCCESS) continue; - DesfireGetKeySettings(dctx, buf, &buflen); + res = DesfireGetKeySettings(dctx, buf, &buflen); if (res == PM3_SUCCESS && buflen >= 2) { appList[i].keySettings = buf[0]; appList[i].numKeysRaw = buf[1]; @@ -2117,7 +2247,11 @@ void DesfirePrintAppList(DesfireContext_t *dctx, PICCInfo_t *PICCInfo, AppListS PrintAndLogEx(SUCCESS, "File ISO ID : " _YELLOW_("n/a")); } } - DesfirePrintFileSettingsExtended(&appList[i].fileList[fnum].fileSettings); + if (appList[i].fileList[fnum].fileSettingsRead) { + DesfirePrintFileSettingsExtended(&appList[i].fileList[fnum].fileSettings); + } else { + PrintAndLogEx(WARNING, "File settings : " _YELLOW_("could not be read")); + } } } PrintAndLogEx(NORMAL, ""); @@ -2147,6 +2281,24 @@ static int DesfireCommandEx(DesfireContext_t *dctx, uint8_t cmd, uint8_t *data, } if (respcode != MFDES_S_OPERATION_OK) { + // Keep and print which status the card returned. Every card error + // collapses to PM3_EAPDU_FAIL on the way out, so without this the + // difference between 0x1C ILLEGAL_COMMAND_CODE, 0xCA COMMAND_ABORTED and + // 0xC1 PICC_INTEGRITY_ERROR -- the card saying it has just disabled + // itself -- never reaches the caller or the log. + dctx->lastRespCode = respcode; + uint16_t sw = DESFIRE_GET_ISO_STATUS(respcode); + PrintAndLogEx(DEBUG, "Desfire command " _YELLOW_("0x%02X") " returned " _RED_("0x%02X") " %s" + , cmd + , respcode + , DesfireGetErrorString(PM3_EAPDU_FAIL, &sw)); + + // The PICC ends the authentication on a command error, so drop our side + // of the session too. Left set, every following command is still framed + // as MACed against a session the card has thrown away: the plain answer + // gets parsed as a CMAC, and the card sees a run of frames whose + // integrity it cannot verify. Callers that keep going re-authenticate. + DesfireClearSession(dctx); free(xresp); return PM3_EAPDU_FAIL; } @@ -2221,6 +2373,7 @@ int DesfireReadSignature(DesfireContext_t *dctx, uint8_t sid, uint8_t *resp, siz } if (respcode != 0x90) { + DesfireClearSession(dctx); return PM3_EAPDU_FAIL; } @@ -2274,6 +2427,7 @@ int DesfireCreateDelegatedApplication(DesfireContext_t *dctx, uint8_t *appdata, return res; } if (respcode != MFDES_S_OPERATION_OK) { + DesfireClearSession(dctx); return PM3_EAPDU_FAIL; } @@ -2351,19 +2505,32 @@ int DesfireFillFileList(DesfireContext_t *dctx, FileList_t FileList, size_t *fil for (int i = 0; i < buflen; i++) { FileList[i].fileNum = buf[i]; - DesfireFileSettingsStruct(dctx, FileList[i].fileNum, &FileList[i].fileSettings); + FileList[i].fileSettingsRead = + (DesfireFileSettingsStruct(dctx, FileList[i].fileNum, &FileList[i].fileSettings) == PM3_SUCCESS); } *filescount = buflen; buflen = 0; res = DesfireGetFileISOIDList(dctx, buf, &buflen); if (res != PM3_SUCCESS) { - PrintAndLogEx(WARNING, "Desfire GetFileISOIDList command, res " _RED_("%d"), res); + // An application created without ISO file IDs answers 0x91F0 here, and the PICC + // ends the authentication on a command error. Drop our side of the session too, + // otherwise the next command is still framed as MACed and the plain response to + // it gets parsed as a CMAC. Callers that keep using the card re-authenticate. + dctx->secureChannel = DACNone; + PrintAndLogEx(DEBUG, "Desfire GetFileISOIDList command, res " _RED_("%d") ". Session dropped by the PICC", res); } size_t isoindx = 0; if (buflen > 0) { for (int i = 0; i < *filescount; i++) { + if (FileList[i].fileSettingsRead == false) { + // we do not know this file's type, so we cannot tell whether it + // takes an entry. Stop rather than hand out ISO ids that belong + // to other files. + PrintAndLogEx(DEBUG, "File 0x%02x settings unknown, ISO ID mapping stops here", FileList[i].fileNum); + break; + } if (FileList[i].fileSettings.fileType != 0x02 && FileList[i].fileSettings.fileType != 0x05) { FileList[i].fileISONum = MemLeToUint2byte(&buf[isoindx * 2]); isoindx++; @@ -2373,7 +2540,7 @@ int DesfireFillFileList(DesfireContext_t *dctx, FileList_t FileList, size_t *fil if (isoindx * 2 != buflen) PrintAndLogEx(WARNING, "Wrong ISO ID list length. must be %zu but %zu", buflen, isoindx * 2); } else { - PrintAndLogEx(WARNING, "ISO ID list returned no data"); + PrintAndLogEx(DEBUG, "ISO ID list returned no data"); } *isopresent = (isoindx > 0); @@ -2453,20 +2620,6 @@ int DesfireValueFileOperations(DesfireContext_t *dctx, uint8_t fid, uint8_t oper int res = DesfireCommand(dctx, operation, data, datalen, resp, &resplen, -1); - // Auto-detection fallback: if MAC mode fails with length error, retry with plain mode - if ((res == 0x7E || res == -20) && dctx->commMode == DCMMACed) { - PrintAndLogEx(INFO, "MAC mode failed with length error, retrying with plain mode"); - DesfireCommunicationMode original_mode = dctx->commMode; - dctx->commMode = DCMPlain; - - memset(resp, 0, sizeof(resp)); - resplen = 0; - res = DesfireCommand(dctx, operation, data, datalen, resp, &resplen, -1); - - // Restore original mode for future commands - dctx->commMode = original_mode; - } - if (resplen == 4 && value) { *value = MemLeToUint4byte(resp); } @@ -3190,8 +3343,12 @@ int DesfireISOSelectEx(DesfireContext_t *dctx, bool fieldon, DesfireISOSelectCon if (res == PM3_EAPDU_FAIL && sw == 0 && xresplen == 0) { return PM3_ECARDEXCHANGE; } - if (res == PM3_SUCCESS && sw != ISO7816_OK) + if (res == PM3_SUCCESS && sw != ISO7816_OK) { + // the success path below clears the session because a select ends the + // authentication; a refused select ends it just the same + DesfireClearSession(dctx); return PM3_ESOFT; + } if (resp != NULL && resplen != NULL) { *resplen = xresplen; @@ -3260,8 +3417,11 @@ int DesfireISOReadBinary(DesfireContext_t *dctx, bool use_file_id, uint8_t filei uint16_t sw = 0; int res = DesfireExchangeISO(false, dctx, (sAPDU_t) {0x00, ISO7816_READ_BINARY, p1, p2, 0, NULL}, (length == 0) ? APDU_INCLUDE_LE_00 : length, resp, resplen, &sw); - if (res == PM3_SUCCESS && sw != ISO7816_OK) + if (res == PM3_SUCCESS && sw != ISO7816_OK) { + // an error ends the authentication on the card, so drop our side too + DesfireClearSession(dctx); return PM3_ESOFT; + } return res; } @@ -3279,8 +3439,11 @@ int DesfireISOUpdateBinary(DesfireContext_t *dctx, bool use_file_id, uint8_t fil uint16_t sw = 0; int res = DesfireExchangeISO(false, dctx, (sAPDU_t) {0x00, ISO7816_UPDATE_BINARY, p1, p2, datalen, data}, 0, resp, &resplen, &sw); - if (res == PM3_SUCCESS && sw != ISO7816_OK) + if (res == PM3_SUCCESS && sw != ISO7816_OK) { + // an error ends the authentication on the card, so drop our side too + DesfireClearSession(dctx); return PM3_ESOFT; + } return res; } @@ -3290,8 +3453,11 @@ int DesfireISOReadRecords(DesfireContext_t *dctx, uint8_t recordnum, bool read_a uint16_t sw = 0; int res = DesfireExchangeISO(false, dctx, (sAPDU_t) {0x00, ISO7816_READ_RECORDS, recordnum, p2, 0, NULL}, (length == 0) ? APDU_INCLUDE_LE_00 : length, resp, resplen, &sw); - if (res == PM3_SUCCESS && sw != ISO7816_OK) + if (res == PM3_SUCCESS && sw != ISO7816_OK) { + // an error ends the authentication on the card, so drop our side too + DesfireClearSession(dctx); return PM3_ESOFT; + } return res; } @@ -3304,8 +3470,11 @@ int DesfireISOAppendRecord(DesfireContext_t *dctx, uint8_t fileid, uint8_t *data uint16_t sw = 0; int res = DesfireExchangeISO(false, dctx, (sAPDU_t) {0x00, ISO7816_APPEND_RECORD, 0x00, p2, datalen, data}, 0, resp, &resplen, &sw); - if (res == PM3_SUCCESS && sw != ISO7816_OK) + if (res == PM3_SUCCESS && sw != ISO7816_OK) { + // an error ends the authentication on the card, so drop our side too + DesfireClearSession(dctx); return PM3_ESOFT; + } return res; } diff --git a/client/src/mifare/desfirecore.h b/client/src/mifare/desfirecore.h index ab18f5d20..194d18207 100644 --- a/client/src/mifare/desfirecore.h +++ b/client/src/mifare/desfirecore.h @@ -95,6 +95,10 @@ typedef struct { typedef struct { uint8_t fileNum; uint16_t fileISONum; + // false means GetFileSettings failed for this file, so fileSettings is + // zeros and not a 0 byte standard data file. Callers must not read + // fileSettings without checking this first + bool fileSettingsRead; FileSettings_t fileSettings; } FileListElm_t; diff --git a/client/src/mifare/desfirecrypto.c b/client/src/mifare/desfirecrypto.c index b4bec3d19..ca980e461 100644 --- a/client/src/mifare/desfirecrypto.c +++ b/client/src/mifare/desfirecrypto.c @@ -574,19 +574,42 @@ uint8_t DesfireCommModeToFileCommMode(DesfireCommunicationMode comm_mode) { return fmode; } +// The PICC applies the file communication mode only when access is granted via a key +// that matches the authenticated one. When the operation is granted by the free access +// right (0x0e) instead, the PICC runs it in plain, whatever the file settings say. +// `rights` lists every access right that can grant the operation. +DesfireCommunicationMode DesfireEffectiveCommMode(DesfireContext_t *ctx, DesfireCommunicationMode filemode, const uint8_t *rights, size_t rightslen) { + bool freeaccess = false; + + for (size_t i = 0; i < rightslen; i++) { + // a key based right we hold takes precedence over free access + if (rights[i] == ctx->keyNum && DesfireIsAuthenticated(ctx)) { + return filemode; + } + + if (rights[i] == 0x0e) { + freeaccess = true; + } + } + + return (freeaccess) ? DCMPlain : filemode; +} + void DesfireGenSessionKeyEV1(const uint8_t rnda[], const uint8_t rndb[], DesfireCryptoAlgorithm keytype, uint8_t *key) { switch (keytype) { - case T_DES: + case T_DES: { memcpy(key, rnda, 4); memcpy(key + 4, rndb, 4); break; - case T_3DES: + } + case T_3DES: { memcpy(key, rnda, 4); memcpy(key + 4, rndb, 4); memcpy(key + 8, rnda + 4, 4); memcpy(key + 12, rndb + 4, 4); break; - case T_3K3DES: + } + case T_3K3DES: { memcpy(key, rnda, 4); memcpy(key + 4, rndb, 4); memcpy(key + 8, rnda + 6, 4); @@ -594,12 +617,14 @@ void DesfireGenSessionKeyEV1(const uint8_t rnda[], const uint8_t rndb[], Desfire memcpy(key + 16, rnda + 12, 4); memcpy(key + 20, rndb + 12, 4); break; - case T_AES: + } + case T_AES: { memcpy(key, rnda, 4); memcpy(key + 4, rndb, 4); memcpy(key + 8, rnda + 12, 4); memcpy(key + 12, rndb + 12, 4); break; + } } } diff --git a/client/src/mifare/desfirecrypto.h b/client/src/mifare/desfirecrypto.h index 363cef461..dd82abca2 100644 --- a/client/src/mifare/desfirecrypto.h +++ b/client/src/mifare/desfirecrypto.h @@ -86,6 +86,10 @@ typedef struct { uint8_t sessionKeyEnc[DESFIRE_MAX_KEY_SIZE]; // look at mifare4.h - mf4Session_t uint8_t lastIV[DESFIRE_MAX_KEY_SIZE]; uint8_t lastCommand; + // status byte of the last answer the card gave. Every card error collapses + // to PM3_EAPDU_FAIL on the way out, so this is the only place the caller can + // find out which one it was + uint8_t lastRespCode; bool lastRequestZeroLen; uint16_t cmdCntr; // for AES uint8_t TI[4]; // for AES @@ -125,6 +129,7 @@ void DesfirePrintCardKeyType(uint8_t keyType); DesfireCommunicationMode DesfireFileCommModeToCommMode(uint8_t file_comm_mode); uint8_t DesfireCommModeToFileCommMode(DesfireCommunicationMode comm_mode); +DesfireCommunicationMode DesfireEffectiveCommMode(DesfireContext_t *ctx, DesfireCommunicationMode filemode, const uint8_t *rights, size_t rightslen); void DesfireGenSessionKeyEV1(const uint8_t rnda[], const uint8_t rndb[], DesfireCryptoAlgorithm keytype, uint8_t *key); void DesfireGenSessionKeyEV2(uint8_t *key, uint8_t *rndA, uint8_t *rndB, bool enckey, uint8_t *sessionkey); diff --git a/client/src/mifare/desfireem.c b/client/src/mifare/desfireem.c new file mode 100644 index 000000000..2d45b31b6 --- /dev/null +++ b/client/src/mifare/desfireem.c @@ -0,0 +1,741 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// Pack a DESFire card image for emulator memory, and read one back. +// Layout and rationale live in include/desfire_em.h. +//----------------------------------------------------------------------------- + +#include "desfireem.h" + +#include +#include +#include "commonutil.h" +#include "ui.h" +#include "desfirecrypto.h" // desfire_get_key_length +#include "mifarehost.h" // mf_eml_set_mem_xt +#include "comms.h" // g_conn +#include "cmdhw.h" // GetFromDevice + +uint8_t desfire_em_gen_from_version(const uint8_t *versionhw, uint8_t len) { + + if (versionhw == NULL || len < 5) { + return DESFIRE_EM_GEN_UNKNOWN; + } + + // hardware frame: vendor, type, subtype, major, minor, storage, protocol. + // Major and minor are what a reader keys on, see client/src/mifare/prime.c + uint8_t type = versionhw[1]; + uint8_t major = versionhw[3]; + uint8_t minor = versionhw[4]; + + if (minor != 0x00) { + return DESFIRE_EM_GEN_UNKNOWN; + } + + if (type != 0x01) { + return DESFIRE_EM_GEN_UNKNOWN; + } + + switch (major) { + case 0x00: + return DESFIRE_EM_GEN_D40; + case 0x01: + return DESFIRE_EM_GEN_EV1; + case 0x12: + case 0x22: + case 0x42: + return DESFIRE_EM_GEN_EV2; + case 0x30: + return DESFIRE_EM_GEN_LIGHT; + case 0x33: + return DESFIRE_EM_GEN_EV3; + case 0xA0: + return DESFIRE_EM_GEN_DUOX; + default: + return DESFIRE_EM_GEN_UNKNOWN; + } +} + +// NV the GetVersion storage size byte codes: 2^(n>>1) bytes, with the low bit +// meaning "between 2^n and 2^(n+1)". See client/src/mifare/prime.c, and the EV1 +// spec section 9.4.7. +uint32_t desfire_em_nominal_cardsize(const uint8_t *versionhw, uint8_t len) { + + if (versionhw == NULL || len < 6) { + return 0; + } + + uint8_t fsize = versionhw[5]; + if (fsize == 0 || (fsize >> 1) > 24) { + return 0; + } + + return 1UL << (fsize >> 1); +} + +const char *desfire_em_gen_str(uint8_t gen) { + static const char *tbl[] = {"unknown", "D40", "EV1", "EV2", "EV3", "Light", "DuoX"}; + return (gen < ARRAYLEN(tbl)) ? tbl[gen] : "unknown"; +} + +// Bytes the committed region of one file occupies, before the shadow. +static uint32_t desfire_em_file_extent(const desfire_dump_file_t *f) { + + switch (f->type) { + case 0x00: + case 0x01: + return f->size; + case 0x02: + // a value file's payload is the 4 byte value, but it is allocated + // and shadowed like anything else, so give it a whole granule + return DESFIRE_EM_GRANULE; + case 0x03: + case 0x04: + // reserve the declared extent, not the records that happen to + // exist, so WriteRecord never has to grow anything + return f->recordsize * f->maxrecords; + default: + return 0; + } +} + +// True when CommitTransaction covers this file type, ie it needs a shadow. +// EV1 spec 9.6.10 names exactly these four; a standard data file writes through. +static bool desfire_em_file_has_shadow(uint8_t type) { + return (type == 0x01 || type == 0x02 || type == 0x03 || type == 0x04); +} + +uint32_t desfire_em_file_reserve(const desfire_dump_file_t *f) { + + uint32_t extent = DESFIRE_EM_ROUNDUP(desfire_em_file_extent(f)); + if (extent == 0) { + return 0; + } + + return desfire_em_file_has_shadow(f->type) ? (extent * 2) : extent; +} + +// How many bytes of a file's committed region carry content, derived from the +// file's own declared shape rather than stored. A card holds the whole file, and +// a record file holds exactly the records that exist. +// +// Not stored because there is nothing to store: once packed, "we read 16 bytes +// of a 32 byte file" and "we read 32 bytes of which 16 were zero" are the same +// image. A dump that saw less than the whole file is an incomplete observation +// of a card, and desfire_em_pack() says so. +static uint32_t desfire_em_content_len(const desfire_dump_file_t *f) { + + if (f->read_ok == false) { + return 0; + } + + switch (f->type) { + case 0x00: + case 0x01: + return f->size; + case 0x03: + case 0x04: + return f->recordsize * f->currecords; + default: + return 0; // a value file carries its payload in the value field + } +} + +static void desfire_em_fill_app(desfire_em_app_t *dst, const desfire_dump_app_t *src) { + + dst->aid[0] = src->aid & 0xFF; + dst->aid[1] = (src->aid >> 8) & 0xFF; + dst->aid[2] = (src->aid >> 16) & 0xFF; + + dst->keysettings = src->keysettings; + dst->numkeysraw = src->numkeysraw; + dst->isofid = src->isofid; + dst->keytype = src->keytype; + + dst->dfnamelen = MIN(src->dfnamelen, (uint8_t)sizeof(dst->dfname)); + memcpy(dst->dfname, src->dfname, dst->dfnamelen); + + dst->flags = 0; + if (src->auth_ok) { + dst->flags |= DESFIRE_EM_APP_AUTHED; + } + if (src->numkeysraw & 0x20) { + dst->flags |= DESFIRE_EM_APP_ISOFIDS; + } +} + +static void desfire_em_fill_file(desfire_em_file_t *dst, const desfire_dump_file_t *src, uint8_t appidx) { + + dst->app = appidx; + dst->num = src->num; + dst->type = src->type; + dst->isofid = src->isofid; + dst->rights = src->accessrights; + + dst->flags = (src->commmode & DESFIRE_EM_FILE_COMM_MASK); + if (src->read_ok == false) { + dst->flags |= DESFIRE_EM_FILE_UNKNOWN; + } + if (src->limitedcredit) { + dst->flags |= DESFIRE_EM_FILE_LIMCREDIT; + } + + switch (src->type) { + case 0x00: + case 0x01: + dst->u.data.size = src->size; + break; + case 0x02: + dst->u.value.lower = src->lowerlimit; + dst->u.value.upper = src->upperlimit; + dst->u.value.value = src->value; + break; + case 0x03: + case 0x04: + dst->u.record.recordsize = src->recordsize; + dst->u.record.maxrecords = src->maxrecords; + dst->u.record.currecords = src->currecords; + break; + default: + break; + } +} + +static void desfire_em_fill_keys(desfire_em_key_t *tbl, uint8_t *n, const desfire_dump_app_t *app, uint8_t appidx) { + + for (uint8_t k = 0; k < DESFIRE_EM_MAX_KEYS; k++) { + + if (app->keys.present[k] == 0 && app->keys.versionknown[k] == 0) { + continue; + } + + desfire_em_key_t *e = &tbl[*n]; + memset(e, 0, sizeof(desfire_em_key_t)); + e->app = appidx; + e->num = k; + e->ver = app->keys.version[k]; + + if (app->keys.versionknown[k]) { + e->flags |= DESFIRE_EM_KEY_VERKNOWN; + } + + if (app->keys.present[k]) { + e->flags |= DESFIRE_EM_KEY_PRESENT; + memcpy(e->key, app->keys.key[k], desfire_get_key_length(app->keytype)); + } + + (*n)++; + } +} + +int desfire_em_pack(const desfire_dump_t *dump, uint8_t *out, size_t outlen, size_t *used) { + + if (dump == NULL || out == NULL || used == NULL) { + return PM3_EINVARG; + } + + *used = 0; + + if (outlen < sizeof(desfire_em_hdr_t) || outlen > UINT16_MAX) { + PrintAndLogEx(ERR, "Emulator memory of %zu bytes cannot hold a card image", outlen); + return PM3_EINVARG; + } + + if (dump->appcount > DESFIRE_EM_MAX_APPS) { + PrintAndLogEx(ERR, "Card has %u applications, the format holds %u", dump->appcount, DESFIRE_EM_MAX_APPS); + return PM3_EOUTOFBOUND; + } + + memset(out, 0, outlen); + desfire_em_hdr_t *hdr = (desfire_em_hdr_t *)out; + + hdr->magic = DESFIRE_EM_MAGIC; + hdr->layout = DESFIRE_EM_LAYOUT_VERSION; + hdr->size = outlen; + hdr->generation = desfire_em_gen_from_version(dump->versionhw, dump->versionhwlen); + + hdr->uidlen = MIN(dump->card_info.uidlen, (uint8_t)sizeof(hdr->uid)); + memcpy(hdr->uid, dump->card_info.uid, hdr->uidlen); + memcpy(hdr->atqa, dump->card_info.atqa, sizeof(hdr->atqa)); + hdr->sak = dump->card_info.sak; + hdr->atslen = MIN(dump->card_info.ats_len, (uint8_t)sizeof(hdr->ats)); + memcpy(hdr->ats, dump->card_info.ats, hdr->atslen); + + hdr->versionhwlen = MIN(dump->versionhwlen, (uint8_t)sizeof(hdr->versionhw)); + memcpy(hdr->versionhw, dump->versionhw, hdr->versionhwlen); + hdr->versionswlen = MIN(dump->versionswlen, (uint8_t)sizeof(hdr->versionsw)); + memcpy(hdr->versionsw, dump->versionsw, hdr->versionswlen); + hdr->versionprodlen = MIN(dump->versionprodlen, (uint8_t)sizeof(hdr->versionprod)); + memcpy(hdr->versionprod, dump->versionprod, hdr->versionprodlen); + + hdr->signaturelen = MIN(dump->signaturelen, (uint8_t)sizeof(hdr->signature)); + memcpy(hdr->signature, dump->signature, hdr->signaturelen); + + // app[0] is the PICC, so the table is one longer than the card's own count + uint8_t appcount = dump->appcount + 1; + + uint16_t filecount = 0; + for (uint8_t i = 0; i < dump->appcount; i++) { + filecount += MIN(dump->app[i].filecount, (uint8_t)DESFIRE_EM_MAX_FILES); + } + + // keys are sparse, so count them before laying anything out + uint16_t keycount = 0; + for (uint8_t i = 0; i < appcount; i++) { + const desfire_dump_app_t *a = (i == 0) ? &dump->picc : &dump->app[i - 1]; + for (uint8_t k = 0; k < DESFIRE_EM_MAX_KEYS; k++) { + if (a->keys.present[k] || a->keys.versionknown[k]) { + keycount++; + } + } + } + + hdr->app_off = sizeof(desfire_em_hdr_t); + hdr->file_off = hdr->app_off + (appcount * sizeof(desfire_em_app_t)); + hdr->key_off = hdr->file_off + (filecount * sizeof(desfire_em_file_t)); + + uint32_t tables_end = hdr->key_off + (keycount * sizeof(desfire_em_key_t)); + if (tables_end > outlen) { + PrintAndLogEx(ERR, "Card image tables need %u bytes, emulator memory holds %zu", tables_end, outlen); + return PM3_EOUTOFBOUND; + } + hdr->tables_end = tables_end; + + desfire_em_app_t *apps = (desfire_em_app_t *)(out + hdr->app_off); + desfire_em_file_t *files = (desfire_em_file_t *)(out + hdr->file_off); + desfire_em_key_t *keys = (desfire_em_key_t *)(out + hdr->key_off); + + // file data grows down from the end, tables grow up: the two only have to + // not meet, and what is between them is the card's free memory + uint32_t data_start = outlen; + uint32_t reserved = 0; // NV the card has spent, for GetFreeMem + uint8_t nkeys = 0; + uint16_t nfiles = 0; + + for (uint8_t i = 0; i < appcount; i++) { + + const desfire_dump_app_t *a = (i == 0) ? &dump->picc : &dump->app[i - 1]; + + desfire_em_fill_app(&apps[i], a); + if (i == 0) { + // the PICC is AID 000000 whatever the dump happens to say + memset(apps[i].aid, 0, sizeof(apps[i].aid)); + } + + desfire_em_fill_keys(keys, &nkeys, a, i); + + // a card charges for the application itself, not only for its files + reserved += DESFIRE_EM_ROUNDUP(DESFIRE_EM_APP_OVERHEAD + + (a->numkeys * desfire_get_key_length(a->keytype))); + + if (i == 0) { + continue; // the PICC has no files + } + + uint8_t fc = MIN(a->filecount, (uint8_t)DESFIRE_EM_MAX_FILES); + for (uint8_t n = 0; n < fc; n++) { + + const desfire_dump_file_t *sf = &a->files[n]; + desfire_em_file_t *df = &files[nfiles]; + + desfire_em_fill_file(df, sf, i); + + uint32_t reserve = desfire_em_file_reserve(sf); + if (reserve == 0) { + nfiles++; + continue; // a type we do not reserve for, eg transaction MAC + } + + if (data_start < reserve || (data_start - reserve) < tables_end) { + PrintAndLogEx(ERR, "Out of emulator memory laying out AID %06X file %02X: needs %u more bytes" + , a->aid, sf->num, reserve - (data_start - tables_end)); + return PM3_EOUTOFBOUND; + } + + data_start -= reserve; + reserved += reserve; + + uint32_t extent = desfire_em_file_has_shadow(sf->type) ? (reserve / 2) : reserve; + df->dataoff = data_start; + df->datalen = extent; + df->shadow_off = desfire_em_file_has_shadow(sf->type) ? (data_start + extent) : 0; + + uint32_t content = desfire_em_content_len(sf); + if (content && sf->data) { + + if (sf->datalen < content) { + PrintAndLogEx(WARNING, "AID %06X file %02X holds %u of %u bytes, the rest of the image is zero" + , a->aid, sf->num, sf->datalen, content); + content = sf->datalen; + } + + memcpy(out + df->dataoff, sf->data, MIN(content, extent)); + } + + nfiles++; + } + } + + hdr->appcount = appcount; + hdr->filecount = nfiles; + hdr->keycount = nkeys; + hdr->data_start = data_start; + hdr->reserved = reserved; + + // What the card claims to hold. + // + // Anchor it to the free memory the real card reported when the dump was + // taken: cardsize = observed free + what we reserved for the same content. + // The emulated card then answers GetFreeMem with the number its original + // answered, and that figure falls as a reader writes. Much better than + // deriving from the storage size byte, which understates -- a 2K part codes + // 2048 and hands out 2560. + // + // With no observed figure, fall back to the storage size byte as a floor, + // never below what this image already carries. + uint32_t cardsize; + if (dump->freemem_ok) { + cardsize = dump->freemem + reserved; + } else { + cardsize = desfire_em_nominal_cardsize(dump->versionhw, dump->versionhwlen); + if (cardsize < reserved) { + cardsize = reserved; + } + } + + if (cardsize > outlen) { + // a claim larger than emulator memory is one we cannot honour + cardsize = outlen; + } + hdr->cardsize = cardsize; + + if (reserved > hdr->cardsize) { + PrintAndLogEx(ERR, "Card image needs %u bytes but a %u byte card cannot hold it", reserved, hdr->cardsize); + return PM3_EOUTOFBOUND; + } + + *used = outlen; + return PM3_SUCCESS; +} + +int desfire_em_unpack(const uint8_t *img, size_t imglen, desfire_dump_t *dump) { + return desfire_em_unpack_ex(img, imglen, dump, false); +} + +int desfire_em_unpack_ex(const uint8_t *img, size_t imglen, desfire_dump_t *dump, bool keep_deleted) { + + if (img == NULL || dump == NULL || imglen < sizeof(desfire_em_hdr_t)) { + return PM3_EINVARG; + } + + const desfire_em_hdr_t *hdr = (const desfire_em_hdr_t *)img; + + if (hdr->magic != DESFIRE_EM_MAGIC) { + PrintAndLogEx(ERR, "Not a DESFire card image, magic is %08X", hdr->magic); + return PM3_EINVARG; + } + + if (hdr->layout != DESFIRE_EM_LAYOUT_VERSION) { + PrintAndLogEx(ERR, "Card image layout v%u, this client speaks v%u", hdr->layout, DESFIRE_EM_LAYOUT_VERSION); + return PM3_EINVARG; + } + + if (hdr->size > imglen || hdr->tables_end > imglen || hdr->data_start > imglen) { + PrintAndLogEx(ERR, "Card image is internally inconsistent with its %zu bytes", imglen); + return PM3_EINVARG; + } + + memset(dump, 0, sizeof(desfire_dump_t)); + + // Bound each copy by the image's own array, which is the smaller of the two + // and the one a corrupt length could run past. Not by the destination cast + // to uint8_t: card_info.ats is 256 bytes, that cast wrapped to 0, and the + // ATS was silently dropped while its length was still reported as 8. + dump->card_info.uidlen = MIN(hdr->uidlen, sizeof(hdr->uid)); + memcpy(dump->card_info.uid, hdr->uid, dump->card_info.uidlen); + memcpy(dump->card_info.atqa, hdr->atqa, sizeof(hdr->atqa)); + dump->card_info.sak = hdr->sak; + dump->card_info.ats_len = MIN(hdr->atslen, sizeof(hdr->ats)); + memcpy(dump->card_info.ats, hdr->ats, dump->card_info.ats_len); + + dump->versionhwlen = hdr->versionhwlen; + memcpy(dump->versionhw, hdr->versionhw, sizeof(dump->versionhw)); + dump->versionswlen = hdr->versionswlen; + memcpy(dump->versionsw, hdr->versionsw, sizeof(dump->versionsw)); + dump->versionprodlen = hdr->versionprodlen; + memcpy(dump->versionprod, hdr->versionprod, sizeof(dump->versionprod)); + + dump->signaturelen = hdr->signaturelen; + memcpy(dump->signature, hdr->signature, sizeof(dump->signature)); + + // free memory is the card's, not the frontier gap: that is the number a + // reader gets from GetFreeMem, and it has to look like the part we claim + // to be rather than like however much emulator memory happens to be spare + dump->freemem = (hdr->cardsize > hdr->reserved) ? (hdr->cardsize - hdr->reserved) : 0; + dump->freemem_ok = true; + + const desfire_em_app_t *apps = (const desfire_em_app_t *)(img + hdr->app_off); + const desfire_em_file_t *files = (const desfire_em_file_t *)(img + hdr->file_off); + const desfire_em_key_t *keys = (const desfire_em_key_t *)(img + hdr->key_off); + + if (hdr->appcount == 0 || hdr->appcount > (DESFIRE_EM_MAX_APPS + 1)) { + PrintAndLogEx(ERR, "Card image claims %u applications", hdr->appcount); + return PM3_EINVARG; + } + + // A deleted application or file is a tombstone in the image, so the memory + // it held stays spent, but it is gone as far as a reader is concerned and it + // does not belong in a dump of the card. Applications are therefore packed + // down as they are copied out, and appmap carries image index -> dump index + // so the key and file tables, which refer to applications by image index, + // can follow. + int appmap[DESFIRE_EM_MAX_APPS + 1]; + for (uint16_t i = 0; i < ARRAYLEN(appmap); i++) { + appmap[i] = -1; + } + + dump->appcount = 0; + + for (uint8_t i = 0; i < hdr->appcount; i++) { + + const desfire_em_app_t *s = &apps[i]; + + if (i > 0 && (s->flags & DESFIRE_EM_APP_DELETED) && (keep_deleted == false)) { + continue; + } + + desfire_dump_app_t *a; + if (i == 0) { + a = &dump->picc; // app[0] is the PICC, never deleted + } else { + if (dump->appcount >= DESFIRE_MAX_APP_COUNT) { + continue; + } + a = &dump->app[dump->appcount]; + appmap[i] = dump->appcount; + dump->appcount++; + } + + a->aid = s->aid[0] | (s->aid[1] << 8) | (s->aid[2] << 16); + a->isofid = s->isofid; + a->keysettings = s->keysettings; + a->numkeysraw = s->numkeysraw; + a->numkeys = s->numkeysraw & 0x1F; + a->keytype = s->keytype; + a->settings_ok = (s->numkeysraw != 0); + a->auth_ok = ((s->flags & DESFIRE_EM_APP_AUTHED) != 0); + a->dfnamelen = MIN(s->dfnamelen, (uint8_t)sizeof(a->dfname)); + memcpy(a->dfname, s->dfname, a->dfnamelen); + } + + for (uint8_t k = 0; k < hdr->keycount; k++) { + + const desfire_em_key_t *s = &keys[k]; + if (s->app >= hdr->appcount || s->num >= DESFIRE_EM_MAX_KEYS) { + continue; + } + + desfire_dump_app_t *a; + if (s->app == 0) { + a = &dump->picc; + } else { + if (appmap[s->app] < 0) { + continue; // its application was deleted + } + a = &dump->app[appmap[s->app]]; + } + + if (s->flags & DESFIRE_EM_KEY_VERKNOWN) { + a->keys.versionknown[s->num] = 1; + a->keys.version[s->num] = s->ver; + } + + if (s->flags & DESFIRE_EM_KEY_PRESENT) { + a->keys.present[s->num] = 1; + memcpy(a->keys.key[s->num], s->key, DESFIRE_MAX_KEY_SIZE); + } + } + + for (uint16_t n = 0; n < hdr->filecount; n++) { + + const desfire_em_file_t *s = &files[n]; + if (s->app == 0 || s->app >= hdr->appcount) { + continue; + } + + if ((s->flags & DESFIRE_EM_FILE_DELETED) && (keep_deleted == false)) { + continue; + } + + if (appmap[s->app] < 0) { + continue; // its application was deleted + } + + desfire_dump_app_t *a = &dump->app[appmap[s->app]]; + if (a->filecount >= DESFIRE_MAX_FILE_COUNT) { + continue; + } + + desfire_dump_file_t *f = &a->files[a->filecount]; + + f->num = s->num; + f->type = s->type; + f->isofid = s->isofid; + f->accessrights = s->rights; + f->commmode = s->flags & DESFIRE_EM_FILE_COMM_MASK; + f->limitedcredit = ((s->flags & DESFIRE_EM_FILE_LIMCREDIT) != 0); + f->settings_ok = true; + f->read_ok = ((s->flags & DESFIRE_EM_FILE_UNKNOWN) == 0); + + switch (s->type) { + case 0x00: + case 0x01: + f->size = s->u.data.size; + break; + case 0x02: + f->lowerlimit = s->u.value.lower; + f->upperlimit = s->u.value.upper; + f->value = s->u.value.value; + break; + case 0x03: + case 0x04: + f->recordsize = s->u.record.recordsize; + f->maxrecords = s->u.record.maxrecords; + f->currecords = s->u.record.currecords; + break; + default: + break; + } + + a->filecount++; + + uint32_t content = MIN(desfire_em_content_len(f), (uint32_t)s->datalen); + if (content == 0) { + continue; + } + + if (s->dataoff + content > imglen) { + PrintAndLogEx(WARNING, "AID %06X file %02X reaches past the image, skipping its contents", a->aid, f->num); + continue; + } + + f->data = calloc(content, sizeof(uint8_t)); + if (f->data == NULL) { + return PM3_EMALLOC; + } + + memcpy(f->data, img + s->dataoff, content); + f->datalen = content; + } + + return PM3_SUCCESS; +} + +void desfire_em_print(const uint8_t *img, size_t imglen) { + + if (img == NULL || imglen < sizeof(desfire_em_hdr_t)) { + return; + } + + const desfire_em_hdr_t *hdr = (const desfire_em_hdr_t *)img; + + if (hdr->magic != DESFIRE_EM_MAGIC) { + PrintAndLogEx(WARNING, "No DESFire card image here, magic is " _YELLOW_("%08X"), hdr->magic); + PrintAndLogEx(HINT, "Hint: load one with " _YELLOW_("`hf mfdes eload -f `")); + return; + } + + PrintAndLogEx(INFO, "--- " _CYAN_("DESFire card image") " -----------------------"); + PrintAndLogEx(SUCCESS, "Generation....... %s", desfire_em_gen_str(hdr->generation)); + PrintAndLogEx(SUCCESS, "UID.............. %s", sprint_hex_inrow(hdr->uid, hdr->uidlen)); + PrintAndLogEx(SUCCESS, "Applications..... %u ( incl. the PICC )", hdr->appcount); + PrintAndLogEx(SUCCESS, "Files............ %u", hdr->filecount); + PrintAndLogEx(SUCCESS, "Keys............. %u", hdr->keycount); + PrintAndLogEx(SUCCESS, "Tables end at.... %u", hdr->tables_end); + PrintAndLogEx(SUCCESS, "Data starts at... %u", hdr->data_start); + PrintAndLogEx(SUCCESS, "Card capacity.... %u bytes, %u spent", hdr->cardsize, hdr->reserved); + PrintAndLogEx(SUCCESS, "Free memory...... " _GREEN_("%u") " bytes" + , (hdr->cardsize > hdr->reserved) ? (hdr->cardsize - hdr->reserved) : 0); + PrintAndLogEx(SUCCESS, "Emulator memory.. %u of %u bytes spare" + , (hdr->data_start > hdr->tables_end) ? (hdr->data_start - hdr->tables_end) : 0 + , hdr->size); +} + +//----------------------------------------------------------------------------- +// Moving an image to and from the device. +// +// No DESFire specific command is needed either way. Emulator memory is one +// region shared by every simulation, so the generic MIFARE setter and the bulk +// emulator download already reach it -- CMD_HF_MIFARE_EML_MEMSET writes through +// emlSet(), which bounds-checks, and BIG_BUF_EML reads back with the device +// clamping to the size it reports in capabilities_t. +//----------------------------------------------------------------------------- + +#define DESFIRE_EM_XFER_WIDTH 16 // emlSet offset is blockno * this + +int desfire_em_upload(const uint8_t *img, size_t imglen) { + + if (img == NULL || imglen == 0) { + return PM3_EINVARG; + } + + if ((imglen % DESFIRE_EM_XFER_WIDTH) != 0) { + PrintAndLogEx(ERR, "Card image of %zu bytes is not a multiple of %d", imglen, DESFIRE_EM_XFER_WIDTH); + return PM3_EINVARG; + } + + // one MEMSET carries a header plus data, so size the chunk from what the + // device told us it can take rather than assuming + size_t perframe = (g_conn.max_cmd_data_size - 8) / DESFIRE_EM_XFER_WIDTH; + if (perframe == 0) { + return PM3_EINVARG; + } + if (perframe > 255) { + perframe = 255; // blockcnt is a uint8_t + } + + size_t blocks = imglen / DESFIRE_EM_XFER_WIDTH; + + PrintAndLogEx(INFO, "Uploading " _YELLOW_("%zu") " bytes to emulator memory", imglen); + + for (size_t b = 0; b < blocks; b += perframe) { + + size_t n = MIN(perframe, blocks - b); + + int res = mf_eml_set_mem_xt((uint8_t *)img + (b * DESFIRE_EM_XFER_WIDTH), b, n, DESFIRE_EM_XFER_WIDTH, 0); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Upload failed at block %zu of %zu", b, blocks); + return res; + } + } + + return PM3_SUCCESS; +} + +int desfire_em_download(uint8_t *img, size_t imglen) { + + if (img == NULL || imglen == 0) { + return PM3_EINVARG; + } + + PrintAndLogEx(INFO, "Downloading " _YELLOW_("%zu") " bytes from emulator memory", imglen); + + if (GetFromDevice(BIG_BUF_EML, img, imglen, 0, NULL, 0, NULL, 2500, false) == false) { + PrintAndLogEx(WARNING, "command execution time out"); + return PM3_ETIMEOUT; + } + + return PM3_SUCCESS; +} diff --git a/client/src/mifare/desfireem.h b/client/src/mifare/desfireem.h new file mode 100644 index 000000000..fddde4b06 --- /dev/null +++ b/client/src/mifare/desfireem.h @@ -0,0 +1,66 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// Pack a DESFire card image for emulator memory, and read one back. +// Layout and rationale live in include/desfire_em.h. +//----------------------------------------------------------------------------- + +#ifndef __DESFIREEM_H +#define __DESFIREEM_H + +#include "common.h" +#include "desfire_em.h" +#include "fileutils.h" // desfire_dump_t + +// Which generation a GetVersion hardware frame describes. Needs at least 5 +// bytes; returns DESFIRE_EM_GEN_UNKNOWN for anything it does not recognise. +uint8_t desfire_em_gen_from_version(const uint8_t *versionhw, uint8_t len); + +// NV the GetVersion storage size byte codes. A floor on the real capacity, not +// the capacity: a 2K part codes 2048 and hands out 2560. 0 if undecodable. +uint32_t desfire_em_nominal_cardsize(const uint8_t *versionhw, uint8_t len); +const char *desfire_em_gen_str(uint8_t gen); + +// Emulator memory a file reserves, committed region and shadow together. +// Rounded to DESFIRE_EM_GRANULE. Backup, value and record files carry a shadow +// because CommitTransaction covers them; standard data files do not. +uint32_t desfire_em_file_reserve(const desfire_dump_file_t *f); + +// Pack `dump` into `out`, which may use at most `outlen` bytes. On success +// *used is the number of bytes the image occupies, which is outlen unless the +// caller wants to trim -- the data pool grows down from the end, so the image +// is not contiguous and cannot be shortened. +// +// Fails with PM3_EOUTOFBOUND, naming the shortfall, rather than truncating. +int desfire_em_pack(const desfire_dump_t *dump, uint8_t *out, size_t outlen, size_t *used); + +// Walk an image back into a desfire_dump_t. The caller owns the per-file heap +// buffers afterwards and must release them with desfire_dump_free(). +// Unpack a card image into a dump. A deleted application or file is a tombstone +// in the image: the memory it held stays spent, but it is gone as far as a +// reader is concerned. `keep_deleted` decides which of those two views you get +// -- false for the card as a reader sees it, true to keep what was there. +int desfire_em_unpack_ex(const uint8_t *img, size_t imglen, desfire_dump_t *dump, bool keep_deleted); +int desfire_em_unpack(const uint8_t *img, size_t imglen, desfire_dump_t *dump); + +// Print an image's structure. Does not need a device. +void desfire_em_print(const uint8_t *img, size_t imglen); + +// Move an image to and from emulator memory. imglen must be a multiple of 16 +// for the upload, which is what the generic emulator setter addresses in. +int desfire_em_upload(const uint8_t *img, size_t imglen); +int desfire_em_download(uint8_t *img, size_t imglen); + +#endif // __DESFIREEM_H diff --git a/client/src/mifare/desfiresecurechan.c b/client/src/mifare/desfiresecurechan.c index c3bbd7e02..e2cef54d9 100644 --- a/client/src/mifare/desfiresecurechan.c +++ b/client/src/mifare/desfiresecurechan.c @@ -235,6 +235,9 @@ static uint8_t DesfireGetCmdHeaderLen(uint8_t cmd, size_t datalen) { static const uint8_t EV1D40TransmitMAC[] = { MFDES_WRITE_DATA, + MFDES_CREDIT, + MFDES_DEBIT, + MFDES_LIMITED_CREDIT, MFDES_WRITE_RECORD, MFDES_UPDATE_RECORD, MFDES_COMMIT_READER_ID, diff --git a/client/src/mifare/mad.c b/client/src/mifare/mad.c index ff3980687..64b54f5eb 100644 --- a/client/src/mifare/mad.c +++ b/client/src/mifare/mad.c @@ -499,19 +499,37 @@ bool HasMADKey(const mad1_sector_t *s0) { return (memcmp(s0->trailer.key_a, g_mifare_mad_key, sizeof(g_mifare_mad_key)) == 0); } -int DetectHID(const mad1_sector_t *s0, uint16_t manufacture) { +int mad_find_aid(const mad1_sector_t *s0, uint16_t aid) { if (s0 == NULL) { return -1; } for (int i = 0; i < MAD1_NUM_AIDS; i++) { - if (madGetAID(s0->mad.aid[i], false) == manufacture) { + if (madGetAID(s0->mad.aid[i], false) == aid) { return i + 1; } } return -1; } +int mad_count_aid(const mad1_sector_t *s0, uint16_t aid) { + if (s0 == NULL) { + return 0; + } + + int n = 0; + for (int i = 0; i < MAD1_NUM_AIDS; i++) { + if (madGetAID(s0->mad.aid[i], false) == aid) { + n++; + } + } + return n; +} + +int DetectHID(const mad1_sector_t *s0, uint16_t manufacture) { + return mad_find_aid(s0, manufacture); +} + int convert_mad_to_arr(const mad1_sector_t *s0, const mad2_sector_t *s16, size_t dump_len, uint8_t *out, size_t omax, size_t *olen, bool override) { if (s0 == NULL || out == NULL || olen == NULL || dump_len < sizeof(mad1_sector_t) || omax == 0) { diff --git a/client/src/mifare/mad.h b/client/src/mifare/mad.h index 8d018aacb..e2714b6fc 100644 --- a/client/src/mifare/mad.h +++ b/client/src/mifare/mad.h @@ -114,6 +114,14 @@ int MADDFDecodeAndPrint(uint32_t short_aid, bool verbose); int MADCardHolderInfoDecode(const uint8_t *data, size_t datalen, bool verbose); void MADPrintHeader(void); bool HasMADKey(const mad1_sector_t *s0); +// First sector carrying this AID, 1..15, or -1. The MAD is how an application +// says which sectors are its own, so every dump parser that keys off an AID +// wants this. +int mad_find_aid(const mad1_sector_t *s0, uint16_t aid); + +// Count of sectors carrying this AID +int mad_count_aid(const mad1_sector_t *s0, uint16_t aid); + int DetectHID(const mad1_sector_t *s0, uint16_t manufacture); int convert_mad_to_arr(const mad1_sector_t *s0, const mad2_sector_t *s16, size_t dump_len, diff --git a/client/src/mifare/mifaredefault.h b/client/src/mifare/mifaredefault.h index 8d832b22d..378dbe45c 100644 --- a/client/src/mifare/mifaredefault.h +++ b/client/src/mifare/mifaredefault.h @@ -129,6 +129,7 @@ static const uint64_t g_mifare_default_keys[] = { 0x0000014b5c31, 0xb578f38a5c61, 0x96a301bce267, + 0x06B2A8EB80A0, // Connect CIVS }; static const uint8_t g_mifare_default_key[MIFARE_KEY_SIZE] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; diff --git a/client/src/mifare/mifarehost.c b/client/src/mifare/mifarehost.c index d06a666dd..355634822 100644 --- a/client/src/mifare/mifarehost.c +++ b/client/src/mifare/mifarehost.c @@ -1152,15 +1152,16 @@ int mf_eml_get_mem_xt(uint8_t *data, int blockNum, int blocksCount, int blockBtW } int mf_elm_set_mem(uint8_t *data, int blockNum, int blocksCount) { - return mf_eml_set_mem_xt(data, blockNum, blocksCount, MFBLOCK_SIZE); + return mf_eml_set_mem_xt(data, blockNum, blocksCount, MFBLOCK_SIZE, 0); } -int mf_eml_set_mem_xt(uint8_t *data, int blockNum, int blocksCount, int blockBtWidth) { +int mf_eml_set_mem_xt(uint8_t *data, int blockNum, int blocksCount, int blockBtWidth, uint8_t flags) { struct p { uint16_t blockno; uint8_t blockcnt; uint8_t blockwidth; + uint8_t flags; uint8_t data[]; } PACKED; @@ -1179,6 +1180,7 @@ int mf_eml_set_mem_xt(uint8_t *data, int blockNum, int blocksCount, int blockBtW payload->blockno = blockNum; payload->blockcnt = blocksCount; payload->blockwidth = blockBtWidth; + payload->flags = flags; memcpy(payload->data, data, size); clearCommandBuffer(); @@ -1783,10 +1785,13 @@ uint16_t detect_mf_magic(bool is_mfc, uint8_t key_type, uint64_t key) { PacketResponseNG resp; clearCommandBuffer(); - uint8_t payload[1 + 1 + MIFARE_KEY_SIZE] = { is_mfc, key_type }; - num_to_bytes(key, MIFARE_KEY_SIZE, payload + 2); + mf_chinese_ident_t payload = { + .is_mfc = is_mfc, + .keytype = key_type, + }; + num_to_bytes(key, sizeof(payload.key), payload.key); - SendCommandNG(CMD_HF_MIFARE_CIDENT, payload, sizeof(payload)); + SendCommandNG(CMD_HF_MIFARE_CIDENT, (uint8_t *)&payload, sizeof(payload)); if (WaitForResponseTimeout(CMD_HF_MIFARE_CIDENT, &resp, 1500)) { if (resp.status != PM3_SUCCESS) { return MAGIC_FLAG_NONE; @@ -1909,309 +1914,3 @@ int convert_mfc_2_arr(uint8_t *in, uint16_t ilen, uint8_t *out, uint16_t *olen) } return PM3_SUCCESS; } - -static const vigik_pk_t vigik_rsa_pk[] = { - {"La Poste Service Universel", 0x07AA, "AB9953CBFCCD9375B6C028ADBAB7584BED15B9CA037FADED9765996F9EA1AB983F3041C90DA3A198804FF90D5D872A96A4988F91F2243B821E01C5021E3ED4E1BA83B7CFECAB0E766D8563164DE0B2412AE4E6EA63804DF5C19C7AA78DC14F608294D732D7C8C67A88C6F84C0F2E3FAFAE34084349E11AB5953AC68729D07715"}, - {"La Poste Service Universel", 0x07AA, "1577D02987C63A95B51AE149430834AEAF3F2E0F4CF8C6887AC6C8D732D79482604FC18DA77A9CC1F54D8063EAE6E42A41B2E04D1663856D760EABECCFB783BAE1D43E1E02C5011E823B24F2918F98A4962A875D0DF94F8098A1A30DC941303F98ABA19E6F996597EDAD7F03CAB915ED4B58B7BAAD28C0B67593CDFCCB5399AB"}, - - {"La Poste Autres Services", 0x07AB, "A6D99B8D902893B04F3F8DE56CB6BF24338FEE897C1BCE6DFD4EBD05B7B1A07FD2EB564BB4F7D35DBFE0A42966C2C137AD156E3DAB62904592BCA20C0BC7B8B1E261EF82D53F52D203843566305A49A22062DECC38C2FE3864CAD08E79219487651E2F79F1C9392B48CAFE1BFFAFF4802AE451E7A283E55A4026AD1E82DF1A15"}, - {"La Poste Autres Services", 0x07AB, "151adf821ead26405ae583a2e751e42a80f4afff1bfeca482b39c9f1792f1e65879421798ed0ca6438fec238ccde6220a2495a3066358403d2523fd582ef61e2b1b8c70b0ca2bc92459062ab3d6e15ad37c1c26629a4e0bf5dd3f7b44b56ebd27fa0b1b705bd4efd6dce1b7c89ee8f3324bfb66ce58d3f4fb09328908d9bd9a6"}, - - {"France Telecom", 0x07AC, "C44DBCD92F9DCF42F4902A87335DBB35D2FF530CDB09814CFA1F4B95A1BD018D099BC6AB69F667B4922AE1ED826E72951AA3E0EAAA7D49A695F04F8CDAAE2D18D10D25BD529CBB05ABF070DC7C041EC35C2BA7F58CC4C349983CC6E11A5CBE828FB8ECBC26F08E1094A6B44C8953C8E1BAFD214DF3E69F430A98CCC75C03669D"}, - {"France Telecom", 0x07AC, "9d66035cc7cc980a439fe6f34d21fdbae1c853894cb4a694108ef026bcecb88f82be5c1ae1c63c9849c3c48cf5a72b5cc31e047cdc70f0ab05bb9c52bd250dd1182daeda8c4ff095a6497daaeae0a31a95726e82ede12a92b467f669abc69b098d01bda1954b1ffa4c8109db0c53ffd235bb5d33872a90f442cf9d2fd9bc4dc4"}, - - {"EDF-GDF", 0x07AD, "B35193DBD2F88A21CDCFFF4BF84F7FC036A991A363DCB3E802407A5E5879DC2127EECFC520779E79E911394882482C87D09A88B0711CBC2973B77FFDAE40EA0001F595072708C558B484AB89D02BCBCB971FF1B80371C0BE30CB13661078078BB68EBCCA524B9DD55EBF7D47D9355AFC95511350CC1103A5DEE847868848B235"}, - {"EDF-GDF", 0x07AD, "35b248888647e8dea50311cc50135195fc5a35d9477dbf5ed59d4b52cabc8eb68b0778106613cb30bec07103b8f11f97cbcb2bd089ab84b458c508270795f50100ea40aefd7fb77329bc1c71b0889ad0872c4882483911e9799e7720c5cfee2721dc79585e7a4002e8b3dc63a391a936c07f4ff84bffcfcd218af8d2db9351b3"}, - {NULL, 0, NULL} -}; - -const char *vigik_get_service(uint16_t service_code) { - for (int i = 0; i < ARRAYLEN(vigik_rsa_pk); ++i) - if (service_code == vigik_rsa_pk[i].code) - return vigik_rsa_pk[i].desc; - - //No match, return default - return vigik_rsa_pk[ARRAYLEN(vigik_rsa_pk) - 1].desc; -} - - -int vigik_verify(mfc_vigik_t *d) { -#define PUBLIC_VIGIK_KEYLEN 128 - - // iso9796 - // Exponent V = 2 - // n = The public modulus n is the product of the secret prime factors p and q. Its length is 1024 bits. - - if (g_debugMode == DEBUG) { - PrintAndLogEx(INFO, "Raw"); - print_hex_noascii_break((uint8_t *)d, sizeof(*d) - sizeof(d->rsa_signature), MFBLOCK_SIZE * 2); - - PrintAndLogEx(INFO, "Raw signature"); - print_hex_noascii_break(d->rsa_signature, sizeof(d->rsa_signature), MFBLOCK_SIZE * 2); - } - - /* - int dl = 0; - - param_gethex_to_eol("1C07D46DA3849326D24B3468BD76673F4F3C41827DC413E81E4F3C7804FAC727213059B21D047510D6432448643A92EBFC67FBEDDAB468D13D948B172F5EBC79A0E3FEFDFAF4E81FC7108E070F1E3CD0", 0, signature, PUBLIC_VIGIK_KEYLEN, &dl); - - param_gethex_to_eol("1AB86FE0C17FFFFE4379D5E15A4B2FAFFEFCFA0F1F3F7FA03E7DDDF1E3C78FFFB1F0E23F7FFF51584771C5C18307FEA36CA74E60AA6B0409ACA66A9EC155F4E9112345708A2B8457E722608EE1157408", 0, signature, PUBLIC_VIGIK_KEYLEN, &dl); - signature_len = dl; - */ - - uint8_t rev_sig[128]; - reverse_array_copy(d->rsa_signature, sizeof(d->rsa_signature), rev_sig); - - PrintAndLogEx(INFO, "Raw signature reverse"); - print_hex_noascii_break(rev_sig, sizeof(d->rsa_signature), MFBLOCK_SIZE * 2); - - // t = 0xBC = Implicitly known - // t = 0xCC = look at byte before to determine hash function - // uint8_t T[] = {0x33, 0xCC}; - - // Success decrypt would mean 0x4b BB ... BB BA padding - // padding, message, hash, 8 bits or 16 bits - - // signature = h( C || M1 || h(M2) ) - // 1024 - 786 - 160 - 16 -1 - // salt C - // message M = 96 bytes, 768 bits - // sha1 hash H = 20 bytes, 160 bits - // padding = 20 bytes, 96 bits - - uint8_t i; - bool is_valid = false; - - for (i = 0; i < ARRAYLEN(vigik_rsa_pk); i++) { - if (vigik_rsa_pk[i].desc == NULL) { - break; - } - - mbedtls_mpi RN, E; - mbedtls_mpi_init(&RN); - - // exponent 2 = even - mbedtls_mpi_init(&E); - mbedtls_mpi_add_int(&E, &E, 2); - - int dl = 0; - uint8_t n[PUBLIC_VIGIK_KEYLEN]; - memset(n, 0, sizeof(n)); - param_gethex_to_eol(vigik_rsa_pk[i].n, 0, n, PUBLIC_VIGIK_KEYLEN, &dl); - - // convert - mbedtls_mpi N, s, sqr, res; - mbedtls_mpi_init(&N); - mbedtls_mpi_init(&s); - mbedtls_mpi_init(&sqr); - mbedtls_mpi_init(&res); - - mbedtls_mpi_read_binary(&N, (const unsigned char *)n, PUBLIC_VIGIK_KEYLEN); - - //mbedtls_mpi_read_binary(&s, (const unsigned char*)signature, signature_len); - mbedtls_mpi_read_binary(&s, (const unsigned char *)rev_sig, sizeof(d->rsa_signature)); - - // check is sign < (N/2) - - mbedtls_mpi n_2; - mbedtls_mpi_init(&n_2); - mbedtls_mpi_copy(&n_2, &N); - mbedtls_mpi_shift_r(&n_2, 1); - bool is_less = (mbedtls_mpi_cmp_mpi(&s, &n_2) > 0) ? false : true; - PrintAndLogEx(DEBUG, "z < (N/2) ..... %s", (is_less) ? _GREEN_("YES") : _RED_("NO")); - mbedtls_mpi_free(&n_2); - - - if (is_less) { - mbedtls_mpi_exp_mod(&sqr, &s, &E, &N, &RN); - } else { - continue; - } - - /* - if v is even and - ⎯ if J* mod 8 = 1, then f* = n–J*. - ⎯ if J* mod 8 = 4, then f* = J*, - ⎯ if J* mod 8 = 6, then f* = 2J*, - ⎯ if J* mod 8 = 7, then f* = 2(n–J*), - */ - uint8_t b2 = mbedtls_mpi_get_bit(&sqr, 2); - uint8_t b1 = mbedtls_mpi_get_bit(&sqr, 1); - uint8_t b0 = mbedtls_mpi_get_bit(&sqr, 0); - uint8_t lsb = (b2 << 2) | (b1 << 1) | b0; - - /* - //1 - mbedtls_mpi_sub_mpi(&res, &N, &sqr); - mbedtls_mpi_write_file( "[=] 1... ", &res, 16, NULL ); - // 4 - mbedtls_mpi_copy(&res, &sqr); - mbedtls_mpi_write_file( "[=] 4... ", &res, 16, NULL ); - // 6 - mbedtls_mpi_mul_int(&res, &sqr, 2); - mbedtls_mpi_write_file( "[=] 6... ", &res, 16, NULL ); - // 7 - mbedtls_mpi foo; - mbedtls_mpi_init(&foo); - mbedtls_mpi_sub_mpi(&foo, &N, &sqr); - mbedtls_mpi_mul_int(&res, &foo, 2); - mbedtls_mpi_free(&foo); - mbedtls_mpi_write_file( "[=] 7... ", &res, 16, NULL ); - */ - - switch (lsb) { - case 1: { - mbedtls_mpi_sub_mpi(&res, &N, &sqr); - break; - } - case 4: { - mbedtls_mpi_copy(&res, &sqr); - break; - } - case 6: { - mbedtls_mpi_mul_int(&res, &sqr, 2); - break; - } - case 7: { - mbedtls_mpi foo2; - mbedtls_mpi_init(&foo2); - mbedtls_mpi_sub_mpi(&foo2, &N, &sqr); - mbedtls_mpi_mul_int(&res, &foo2, 2); - mbedtls_mpi_free(&foo2); - break; - } - default: { - continue; - } - } - - PrintAndLogEx(DEBUG, "LSB............ " _GREEN_("%u"), lsb); - if (g_debugMode == DEBUG) { - mbedtls_mpi_write_file("[=] N.............. ", &N, 16, NULL); - mbedtls_mpi_write_file("[=] signature...... ", &s, 16, NULL); - mbedtls_mpi_write_file("[=] square mod n... ", &sqr, 16, NULL); - mbedtls_mpi_write_file("[=] n-fs........... ", &res, 16, NULL); - } - - - uint8_t nfs[128] = {0}; - mbedtls_mpi_write_binary(&res, nfs, sizeof(nfs)); - - // xor 0xDC01 - int count_zero = 0; - for (int x = 0; x < sizeof(nfs); x += 2) { - nfs[x] ^= 0xDC; - nfs[x + 1] ^= 0x01; - - if (nfs[x] == 0x00) - count_zero++; - if (nfs[x + 1] == 0x00) - count_zero++; - } - - if (count_zero > 10) { - PrintAndLogEx(INFO, ""); - PrintAndLogEx(INFO, "Message XORED"); - print_hex_noascii_break(nfs, sizeof(nfs), 32); - PrintAndLogEx(INFO, "\n"); - is_valid = true; - break; - } - - /* - if (bar == 0) { - typedef struct vigik_rsa_s { - uint8_t rsa[127]; - uint8_t hash; - } vigik_rsa_t; - - vigik_rsa_t ts; - memcpy(&ts, nfs, sizeof(ts)); - - if ( ts.hash == 0xCC ) { - PrintAndLogEx(INFO, "Hash byte... 0x%02X", ts.hash); - switch(ts.rsa[126]) { - case 0x11: - PrintAndLogEx(INFO, "Hash algo ( 0x%02X ) - SHA1"); - break; - case 0x22: - PrintAndLogEx(INFO, "Hash algo ( 0x%02X ) - RIPEMD"); - break; - case 0x33: - PrintAndLogEx(INFO, "Hash algo ( 0x%02X ) - SHA1"); - break; - default: - PrintAndLogEx(INFO, "Hash algo ( 0x%02X ) - " _RED_("err")); - break; - } - } else if ( ts.hash == 0xBC) { - PrintAndLogEx(INFO, "Hash byte... 0x%02X - " _GREEN_("implict"), ts.hash); - } else { - PrintAndLogEx(INFO, "Hash byte... 0x%02x - " _RED_("err"), ts.hash); - } - - PrintAndLogEx(INFO, "Message w padding"); - print_hex_noascii_break(ts.rsa, sizeof(ts.rsa) - 20, 32); - } - */ - - mbedtls_mpi_free(&N); - mbedtls_mpi_free(&s); - mbedtls_mpi_free(&res); - mbedtls_mpi_free(&RN); - mbedtls_mpi_free(&E); - } - - PrintAndLogEx(INFO, ""); - PrintAndLogEx(INFO, "--- " _CYAN_("Tag Signature")); - PrintAndLogEx(INFO, "RSA: 1024bit"); - - if (is_valid == false || i == ARRAYLEN(vigik_rsa_pk)) { - PrintAndLogEx(INFO, "Signature:"); - print_hex_noascii_break(d->rsa_signature, sizeof(d->rsa_signature), MFBLOCK_SIZE * 2); - PrintAndLogEx(SUCCESS, "Signature verification: " _RED_("failed")); - return PM3_ESOFT; - } - - PrintAndLogEx(INFO, "Signature public key name: " _YELLOW_("%s"), vigik_rsa_pk[i].desc); - PrintAndLogEx(INFO, "Signature public key value:"); - PrintAndLogEx(INFO, "%.64s", vigik_rsa_pk[i].n); - PrintAndLogEx(INFO, "%.64s", vigik_rsa_pk[i].n + 64); - PrintAndLogEx(INFO, "%.64s", vigik_rsa_pk[i].n + 128); - PrintAndLogEx(INFO, "%.64s", vigik_rsa_pk[i].n + 192); - - PrintAndLogEx(INFO, "Signature:"); - print_hex_noascii_break(d->rsa_signature, sizeof(d->rsa_signature), MFBLOCK_SIZE * 2); - - PrintAndLogEx(SUCCESS, "Signature verification: " _GREEN_("successful")); - - return PM3_SUCCESS; -} - -int vigik_annotate(mfc_vigik_t *d) { - if (d == NULL) - return PM3_EINVARG; - - PrintAndLogEx(INFO, "Manufacture......... %s", sprint_hex(d->b0, sizeof(d->b0))); - PrintAndLogEx(INFO, "MAD................. %s", sprint_hex(d->mad, sizeof(d->mad))); - PrintAndLogEx(INFO, "Counters............ %u", d->counters); - PrintAndLogEx(INFO, "rtf................. %s", sprint_hex(d->rtf, sizeof(d->rtf))); - PrintAndLogEx(INFO, "Service code........ 0x%08x / %u - " _YELLOW_("%s"), d->service_code, d->service_code, vigik_get_service(d->service_code)); - PrintAndLogEx(INFO, "Info flag........... %u -", d->info_flag); // , sprint_bin(d->info_flag, 1)); - PrintAndLogEx(INFO, "Key version......... %u", d->key_version); - PrintAndLogEx(INFO, "PTR Counter......... %u", d->ptr_counter); - PrintAndLogEx(INFO, "Counter num......... %u", d->counter_num); - PrintAndLogEx(INFO, "Slot access date.... %s", sprint_hex(d->slot_access_date, sizeof(d->slot_access_date))); - PrintAndLogEx(INFO, "Slot dst duration... %u", d->slot_dst_duration); - PrintAndLogEx(INFO, "Other Slots......... %s", sprint_hex(d->other_slots, sizeof(d->other_slots))); - PrintAndLogEx(INFO, "Services counter.... %u", d->services_counter); - PrintAndLogEx(INFO, "Loading date........ %s", sprint_hex(d->loading_date, sizeof(d->loading_date))); - PrintAndLogEx(INFO, "Reserved null....... %u", d->reserved_null); - PrintAndLogEx(INFO, "----------------------------------------------------------------"); - PrintAndLogEx(INFO, ""); - vigik_verify(d); - PrintAndLogEx(INFO, "----------------------------------------------------------------"); - PrintAndLogEx(INFO, ""); - return PM3_SUCCESS; - -} diff --git a/client/src/mifare/mifarehost.h b/client/src/mifare/mifarehost.h index 3a801769f..9785aeb61 100644 --- a/client/src/mifare/mifarehost.h +++ b/client/src/mifare/mifarehost.h @@ -94,7 +94,7 @@ int mf_write_sector(uint8_t sectorNo, uint8_t keyType, const uint8_t *key, uint8 int mf_eml_get_mem(uint8_t *data, int blockNum, int blocksCount); int mf_eml_get_mem_xt(uint8_t *data, int blockNum, int blocksCount, int blockBtWidth); int mf_elm_set_mem(uint8_t *data, int blockNum, int blocksCount); -int mf_eml_set_mem_xt(uint8_t *data, int blockNum, int blocksCount, int blockBtWidth); +int mf_eml_set_mem_xt(uint8_t *data, int blockNum, int blocksCount, int blockBtWidth, uint8_t flags); int mf_chinese_set_uid(uint8_t *uid, uint8_t uidlen, const uint8_t *atqa, const uint8_t *sak, uint8_t *old_uid, uint8_t *verifed_uid, uint8_t wipecard, uint8_t gdm); int mf_chinese_wipe(uint8_t *uid, const uint8_t *atqa, const uint8_t *sak, uint8_t gdm); @@ -127,7 +127,4 @@ void mf_crypto1_decrypt(struct Crypto1State *pcs, uint8_t *data, int len, bool i // remove all sector trailers in a MFC dump int convert_mfc_2_arr(uint8_t *in, uint16_t ilen, uint8_t *out, uint16_t *olen); -const char *vigik_get_service(uint16_t service_code); -int vigik_verify(mfc_vigik_t *d); -int vigik_annotate(mfc_vigik_t *d); #endif diff --git a/client/src/parsers/parsehexact.c b/client/src/parsers/parsehexact.c new file mode 100644 index 000000000..64bd0ec17 --- /dev/null +++ b/client/src/parsers/parsehexact.c @@ -0,0 +1,654 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// Hexact / COGELEC / Intratone parser for MIFARE Classic dumps +//----------------------------------------------------------------------------- + +#include "parsehexact.h" +#include +#include // tolower +#include "commonutil.h" +#include "ui.h" // PrintAndLogEx +#include "util.h" // sprint_hex +#include "mifare/mifaredefault.h" // MFBLOCK_SIZE +#include "mifare/mifare4.h" // mfFirstBlockOfSector + +#define HEXACT_ID_SECTOR 15 +#define HEXACT_DATA_SECTOR_A 9 +#define HEXACT_DATA_SECTOR_B 11 + +// bytes 6..8 are skipped: the separator is " - " on most cards but byte 8 is +// 0x01 on at least one, and the published COGELEC fingerprints skip them too +static const uint8_t hexact_marker[] = { + 'h', 'e', 'x', 'a', 'c', 't', 0, 0, 0, 'c', 'o', 'g', 'e', 'l', 'e', 'c' +}; + +#define HEXACT_BLOCK0_SAK 0x88 + +#define HEXACT_SEED_BASE_A 0xB3 +#define HEXACT_SEED_BASE_B 0x5C + +static const struct { + uint8_t sector; + uint8_t blk; +} hexact_payload[] = { + {HEXACT_DATA_SECTOR_A, 0}, {HEXACT_DATA_SECTOR_A, 1}, {HEXACT_DATA_SECTOR_A, 2}, + {HEXACT_DATA_SECTOR_B, 0}, {HEXACT_DATA_SECTOR_B, 1}, +}; +#define HEXACT_PAYLOAD_BLOCKS ARRAYLEN(hexact_payload) + +typedef enum { + HX_ID, // identifier[idx] + HX_ID_SER, // identifier[idx] ^ serial[idx] + HX_ID_UID, // identifier[idx] ^ uid[0] ^ uid[2] +} hexact_src_t; + +typedef struct { + uint8_t rec; + uint8_t pos; + hexact_src_t src; + uint8_t idx; + uint8_t xr; +} hexact_check_t; + +static const hexact_check_t hexact_checks[] = { + {0, 4, HX_ID, 4, 0xFE}, {0, 7, HX_ID_UID, 7, 0x00}, + {1, 1, HX_ID, 1, 0x00}, {1, 4, HX_ID, 4, 0x00}, + {1, 15, HX_ID_UID, 7, 0x00}, + {2, 0, HX_ID, 0, 0x00}, {2, 1, HX_ID, 1, 0x00}, + {2, 4, HX_ID, 4, 0x00}, {2, 7, HX_ID, 7, 0x00}, + {3, 7, HX_ID_UID, 7, 0x00}, {3, 13, HX_ID, 5, 0x00}, + {4, 1, HX_ID, 1, 0x00}, {4, 13, HX_ID, 5, 0x00}, + {4, 15, HX_ID_UID, 7, 0x00}, +}; + +static uint8_t hexact_rotl(uint8_t v, uint8_t n) { + n &= 7; + if (n == 0) { + return v; + } + return (uint8_t)((v << n) | (v >> (8 - n))); +} + +static uint8_t hexact_seed(uint8_t sector, uint8_t blk) { + uint8_t base = (sector == HEXACT_DATA_SECTOR_A) ? HEXACT_SEED_BASE_A : HEXACT_SEED_BASE_B; + return base ^ (uint8_t)(2 * blk); +} + +// Strip the keystream from one payload block +static void hexact_decrypt(const uint8_t *in, uint8_t sector, uint8_t blk, uint8_t *out) { + uint8_t s = hexact_seed(sector, blk); + for (uint8_t k = 0; k < MFBLOCK_SIZE; k++) { + out[k] = in[k] ^ hexact_rotl(s, k); + } +} + +static uint8_t hexact_expect(const hexact_check_t *c, const uint8_t *idn, + const uint8_t *uid, const uint8_t *ser) { + uint8_t v = idn[c->idx] ^ c->xr; + if (c->src == HX_ID_SER && c->idx < 4) { + v ^= ser[c->idx]; + } else if (c->src == HX_ID_UID) { + v ^= uid[0] ^ uid[2]; + } + return v; +} + + +// Per installation offsets: the XOR of two positions holding the same class, so +// the mask cancels and what is left identifies the installation. The first seven +// need only sector 9, the last three sector 11 block 0. +#define HEXACT_SITE_NOPOS 0xFF + +static const struct { + uint8_t a_rec, a_pos; + uint8_t b_rec, b_pos; // b_rec HEXACT_SITE_NOPOS for none + bool fold_uid1; + int8_t idn; // identifier byte to fold, -1 for none + int8_t ser; // serial byte to fold, -1 for none +} hexact_site[] = { + {0, 2, 2, 2, false, -1, -1}, + {0, 3, 1, 3, false, -1, -1}, + {0, 5, 1, 5, false, -1, -1}, + {0, 12, 1, 12, false, -1, -1}, + {0, 13, 1, 13, false, -1, -1}, + {0, 14, 1, 14, false, -1, -1}, + {0, 15, 1, 7, true, -1, -1}, + {0, 0, HEXACT_SITE_NOPOS, 0, false, 0, 0}, + {0, 1, HEXACT_SITE_NOPOS, 0, false, 1, 1}, + {3, 0, HEXACT_SITE_NOPOS, 0, false, 0, -1}, + {3, 1, HEXACT_SITE_NOPOS, 0, false, 1, -1}, + {3, 15, 0, 15, false, -1, -1}, +}; +#define HEXACT_SITE_BYTES ARRAYLEN(hexact_site) +#define HEXACT_SITE_S9 9 // how many of them sector 9 alone gives + +// Installations already in the research corpus. Row 0 has four cards, the rest +// one each, so anything that is not row 0 is a card worth having. +static const uint8_t hexact_known_site[][HEXACT_SITE_S9] = { + {0x9D, 0xFF, 0x00, 0x99, 0xCC, 0x20, 0xD0, 0xFF, 0xFF}, + {0x2C, 0x2F, 0x70, 0x21, 0xB5, 0x7F, 0x45, 0xDF, 0x10}, + {0xE1, 0x50, 0x00, 0xEC, 0x1D, 0x00, 0xF4, 0xE6, 0xF3}, + {0xAF, 0xB3, 0x00, 0xEC, 0x1D, 0x00, 0x03, 0xDC, 0x7D}, + {0xD4, 0x58, 0x7F, 0xA5, 0x67, 0xD4, 0x0D, 0x0C, 0x14}, +}; + +// A blank block decrypts to the bare keystream, so a site byte is produced only +// when every block it reads was written. +static bool hexact_site_read(const uint8_t rec[][MFBLOCK_SIZE], const uint8_t *idn, + const uint8_t *uid, const uint8_t *ser, + const bool *written, size_t i, uint8_t *out) { + if (written[hexact_site[i].a_rec] == false) { + return false; + } + uint8_t v = rec[hexact_site[i].a_rec][hexact_site[i].a_pos]; + + if (hexact_site[i].b_rec != HEXACT_SITE_NOPOS) { + if (written[hexact_site[i].b_rec] == false) { + return false; + } + v ^= rec[hexact_site[i].b_rec][hexact_site[i].b_pos]; + } + if (hexact_site[i].fold_uid1) { + v ^= uid[1]; + } + if (hexact_site[i].idn >= 0) { + v ^= idn[hexact_site[i].idn]; + } + if (hexact_site[i].ser >= 0) { + v ^= ser[hexact_site[i].ser]; + } + *out = v; + return true; +} + +#define HEXACT_MAX_SHOWN 5 + +static uint8_t hexact_cross_check(const uint8_t rec[][MFBLOCK_SIZE], const uint8_t *idn, + const uint8_t *uid, const uint8_t *ser, + const bool *written, uint8_t *total, bool verbose) { + uint8_t pass = 0, shown = 0; + *total = 0; + + for (size_t i = 0; i < ARRAYLEN(hexact_checks); i++) { + const hexact_check_t *c = &hexact_checks[i]; + if (written[c->rec] == false) { + continue; + } + uint8_t want = hexact_expect(c, idn, uid, ser); + (*total)++; + if (rec[c->rec][c->pos] == want) { + pass++; + } else if (verbose && shown++ < HEXACT_MAX_SHOWN) { + PrintAndLogEx(INFO, " mismatch......... sector %2u blk %u byte %2u is %02X, expected %02X", + hexact_payload[c->rec].sector, hexact_payload[c->rec].blk, + c->pos, rec[c->rec][c->pos], want); + } + } + + // byte 7 repeats across two records in one of two phases; a card uses one + if (written[1] && written[2]) { + (*total)++; + if (rec[2][15] == rec[1][7] || rec[2][7] == rec[1][15]) { + pass++; + } else if (verbose && shown++ < HEXACT_MAX_SHOWN) { + PrintAndLogEx(INFO, " mismatch......... record tie %02X/%02X matches neither phase", + rec[2][15], rec[2][7]); + } + } + + if (verbose && shown > HEXACT_MAX_SHOWN) { + PrintAndLogEx(INFO, " ................. and %u more", shown - HEXACT_MAX_SHOWN); + } + return pass; +} + +static bool hexact_all_printable(const uint8_t *p, size_t len) { + for (size_t i = 0; i < len; i++) { + if (isprint(p[i]) == 0) { + return false; + } + } + return true; +} + +static const uint8_t *hexact_sector(const uint8_t *dump, size_t dumplen, uint8_t sector, uint8_t block) { + size_t off = (mfFirstBlockOfSector(sector) + block) * MFBLOCK_SIZE; + if (off + MFBLOCK_SIZE > dumplen) { + return NULL; + } + return dump + off; +} + +bool is_valid_hexact_card(const uint8_t *dump, size_t dumplen) { + const uint8_t *p = hexact_sector(dump, dumplen, HEXACT_ID_SECTOR, 0); + if (p == NULL) { + return false; + } + + for (size_t i = 0; i < sizeof(hexact_marker); i++) { + if (hexact_marker[i] == 0) { + continue; + } + if (tolower(p[i]) != hexact_marker[i]) { + return false; + } + } + return true; +} + +int hexact_parser_parse(const uint8_t *dump, size_t dumplen) { + + if (is_valid_hexact_card(dump, dumplen) == false) { + return PM3_EINVARG; + } + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, _CYAN_("Hexact / COGELEC / Intratone") " detected"); + + // sector 15 is written at the factory and then locked, so the case of the + // marker cannot change on a card and dates it + const uint8_t *mark = hexact_sector(dump, dumplen, HEXACT_ID_SECTOR, 0); + const uint8_t *spare = hexact_sector(dump, dumplen, HEXACT_DATA_SECTOR_B, 2); + // erased is FF, not zero, so an unpersonalised card must not read as in use + bool spare_used = false; + if (spare) { + for (uint8_t k = 0; k < MFBLOCK_SIZE; k++) { + if (spare[k] != 0x00 && spare[k] != 0xFF) { + spare_used = true; + break; + } + } + } + if (mark) { + PrintAndLogEx(INFO, "Generation......... %.6s, variant byte %02X, sector %u block 2 %s ( %s )", + (const char *)mark, mark[8], HEXACT_DATA_SECTOR_B, + spare_used ? "in use" : "unused", + (mark[0] == 'H') ? "older" : "Intratone / Hexact A"); + } + + if (dumplen > 5 && dump[5] == HEXACT_BLOCK0_SAK) { + PrintAndLogEx(INFO, "Block 0 SAK........ 0x%02X ( " _YELLOW_("anti clone marker") " )", dump[5]); + PrintAndLogEx(INFO, " the tag answers 0x08, a clone written with this block 0 answers 0x88"); + } + + PrintAndLogEx(WARNING, _RED_("Anti clone counter measurements")); + PrintAndLogEx(INFO, "This vendor is reported to count reader scans in sector " _YELLOW_("%u"), HEXACT_DATA_SECTOR_B); + PrintAndLogEx(INFO, "Cloning or emulating a badge can desynchronise the original and lock you out"); + PrintAndLogEx(NORMAL, ""); + + const uint8_t *id0 = hexact_sector(dump, dumplen, HEXACT_ID_SECTOR, 0); + const uint8_t *id1 = hexact_sector(dump, dumplen, HEXACT_ID_SECTOR, 1); + const uint8_t *id2 = hexact_sector(dump, dumplen, HEXACT_ID_SECTOR, 2); + + char system[16 + 16 + 16 + 3] = {0}; + str_append(system, sizeof(system), "%.16s", (const char *)id0); + str_trim(system); + + if (id1) { + str_append(system, sizeof(system), " %.16s", (const char *)id1); + str_trim(system); + } + + bool has_serial = (id2 != NULL) && (hexact_all_printable(id2, 4) == false); + + if (id2) { + if (has_serial) { + str_append(system, sizeof(system), " %.12s", (const char *)(id2 + 4)); + } else { + str_append(system, sizeof(system), " %.16s", (const char *)id2); + } + str_trim(system); + } + + PrintAndLogEx(INFO, "System............. " _YELLOW_("%s"), system); + + if (has_serial) { + PrintAndLogEx(INFO, "Printed serial..... " _YELLOW_("%u"), MemLeToUint4byte(id2)); + } + + const uint8_t *s0b2 = hexact_sector(dump, dumplen, 0, 2); + if (s0b2) { + PrintAndLogEx(INFO, "Card identifier.... %s", sprint_hex_inrow(s0b2, 8)); + } + + if (s0b2 == NULL || id2 == NULL) { + return PM3_SUCCESS; + } + + uint8_t rec[HEXACT_PAYLOAD_BLOCKS][MFBLOCK_SIZE]; + bool written[HEXACT_PAYLOAD_BLOCKS] = {false}; + for (uint8_t i = 0; i < HEXACT_PAYLOAD_BLOCKS; i++) { + const uint8_t *p = hexact_sector(dump, dumplen, hexact_payload[i].sector, hexact_payload[i].blk); + if (p == NULL) { + return PM3_SUCCESS; + } + hexact_decrypt(p, hexact_payload[i].sector, hexact_payload[i].blk, rec[i]); + + // an unwritten block decrypts to the bare keystream, not card data + for (uint8_t k = 0; k < MFBLOCK_SIZE; k++) { + if (p[k] != 0x00 && p[k] != 0xFF) { + written[i] = true; + break; + } + } + } + + bool all_zero = true, all_ff = true; + for (uint8_t i = 0; i < HEXACT_PAYLOAD_BLOCKS; i++) { + + const uint8_t *p = hexact_sector(dump, dumplen, hexact_payload[i].sector, hexact_payload[i].blk); + + for (uint8_t k = 0; k < MFBLOCK_SIZE; k++) { + if (p[k] != 0x00) { + all_zero = false; + } + + if (p[k] != 0xFF) { + all_ff = false; + } + } + } + + if (all_zero || all_ff) { + PrintAndLogEx(INFO, "Payload............ sector %u and %u, " _YELLOW_("%s"), + HEXACT_DATA_SECTOR_A, HEXACT_DATA_SECTOR_B, + all_ff ? "erased, card not personalised" : "not read" + ); + return PM3_SUCCESS; + } + + PrintAndLogEx(INFO, "Payload............ sector %u and %u, " _YELLOW_("mask removed"), + HEXACT_DATA_SECTOR_A, + HEXACT_DATA_SECTOR_B + ); + + for (uint8_t i = 0; i < HEXACT_PAYLOAD_BLOCKS; i++) { + char line[(2 * 16) + 4] = {0}; + str_append(line, sizeof(line), "%s ", sprint_hex_inrow(rec[i], 8)); + str_append(line, sizeof(line), "%s", sprint_hex_inrow(rec[i] + 8, 8)); + PrintAndLogEx(INFO, " sector %2u blk %u.. %s", + hexact_payload[i].sector, + hexact_payload[i].blk, + line + ); + } + + const uint8_t *uid = dump; + uint8_t ser[4]; + memcpy(ser, id2, sizeof(ser)); + + // A card whose sector 0 block 2 has been wiped still carries identifier + // bytes in the payload, so read them back instead of failing 21 checks. + bool wiped = true; + for (uint8_t k = 0; k < 8; k++) { + if (s0b2[k]) { + wiped = false; + break; + } + } + uint8_t idn[8] = {0}; + memcpy(idn, s0b2, sizeof(idn)); + + if (wiped) { + idn[0] = rec[2][0]; + idn[1] = rec[2][1]; + idn[4] = rec[2][4]; + idn[7] = rec[2][7]; + + PrintAndLogEx(INFO, "Identifier......... " _YELLOW_("wiped") ", recovered from the payload:"); + PrintAndLogEx(INFO, " %02X %02X .. .. %02X .. .. %02X%s", + idn[0], idn[1], idn[4], idn[7], + (rec[1][1] == rec[2][1] && rec[1][4] == rec[2][4]) + ? " ( two sources agree )" : " ( sources DISAGREE )"); + } + + uint8_t total = 0; + uint8_t pass = 0; + if (wiped == false) { + pass = hexact_cross_check(rec, idn, uid, ser, written, &total, true); + } + + if (spare_used) { + uint8_t pt[MFBLOCK_SIZE]; + hexact_decrypt(spare, HEXACT_DATA_SECTOR_B, 2, pt); + PrintAndLogEx(INFO, " sector %2u blk 2.. %s " _YELLOW_("( other generation )"), + HEXACT_DATA_SECTOR_B, + sprint_hex_inrow(pt, MFBLOCK_SIZE) + ); + } + + if (wiped == false) { + PrintAndLogEx(INFO, "Cross checks....... %u / %u ( %s )", pass, total, + (pass == total) ? _GREEN_("bound bytes agree with sector 0, 15 and the UID") + : _RED_("bound bytes disagree, see above") + ); + } + + // two badges of one building carry the same row, two buildings never do + char s9line[(3 * HEXACT_SITE_BYTES) + 1] = {0}; + char s11line[(3 * HEXACT_SITE_BYTES) + 1] = {0}; + uint16_t touched[HEXACT_PAYLOAD_BLOCKS] = {0}; + uint8_t srow[HEXACT_SITE_S9] = {0}; + uint8_t nrow = 0; + + for (size_t i = 0; i < HEXACT_SITE_BYTES; i++) { + uint8_t v = 0; + if (hexact_site_read(rec, idn, uid, ser, written, i, &v) == false) { + continue; + } + touched[hexact_site[i].a_rec] |= (1 << hexact_site[i].a_pos); + if (hexact_site[i].b_rec != HEXACT_SITE_NOPOS) { + touched[hexact_site[i].b_rec] |= (1 << hexact_site[i].b_pos); + } + if (i < HEXACT_SITE_S9) { + srow[i] = v; + nrow++; + } + str_append((i < HEXACT_SITE_S9) ? s9line : s11line, + (3 * HEXACT_SITE_BYTES) + 1, "%02X ", v); + } + + if (s9line[0]) { + PrintAndLogEx(INFO, "Site constants..... %s ( " _YELLOW_("shared by every badge of one installation") " )", s9line); + } + if (s11line[0]) { + PrintAndLogEx(INFO, " %s ( from sector %u block 0 )", s11line, HEXACT_DATA_SECTOR_B); + } + + int inst = -1; + if (nrow == HEXACT_SITE_S9) { + for (size_t i = 0; i < ARRAYLEN(hexact_known_site); i++) { + if (memcmp(srow, hexact_known_site[i], HEXACT_SITE_S9) == 0) { + inst = (int)i; + break; + } + } + } + + bool want = false; + if (nrow == HEXACT_SITE_S9 && inst < 0) { + want = true; + } else if (inst > 0) { + want = true; + } else if (spare_used) { + want = true; + } + + if (want) { + PrintAndLogEx(HINT, "Hint: " _RED_("Report to Iceman!")); + } + + if (wiped) { + return PM3_SUCCESS; + } + + for (size_t i = 0; i < ARRAYLEN(hexact_checks); i++) { + if (written[hexact_checks[i].rec]) { + touched[hexact_checks[i].rec] |= (1 << hexact_checks[i].pos); + } + } + if (written[1] && written[2]) { + touched[1] |= (1 << 7); + touched[2] |= (1 << 15); + } + + uint8_t nread = 0, npayload = 0; + for (uint8_t i = 0; i < HEXACT_PAYLOAD_BLOCKS; i++) { + if (written[i] == false) { + continue; + } + npayload += MFBLOCK_SIZE; + for (uint8_t k = 0; k < MFBLOCK_SIZE; k++) { + if (touched[i] & (1 << k)) { + nread++; + } + } + } + + PrintAndLogEx(INFO, " %u of %u payload bytes are issuer data, read by nothing", + npayload - nread, npayload); + + return PM3_SUCCESS; +} + +static void hexact_build_selftest_card(uint8_t *dump, uint8_t v1) { + static const uint8_t uid[4] = {0x1A, 0x2B, 0x3C, 0x61}; + static const uint8_t idn[8] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}; + static const uint8_t ser[4] = {0xD2, 0x04, 0x00, 0x00}; // 1234 little endian + + memcpy(dump, uid, sizeof(uid)); + dump[4] = uid[0] ^ uid[1] ^ uid[2] ^ uid[3]; + dump[5] = HEXACT_BLOCK0_SAK; + dump[6] = 0x04; + memcpy(dump + (2 * MFBLOCK_SIZE), idn, sizeof(idn)); + memcpy(dump + (mfFirstBlockOfSector(HEXACT_ID_SECTOR) * MFBLOCK_SIZE), hexact_marker, sizeof(hexact_marker)); + memcpy(dump + ((mfFirstBlockOfSector(HEXACT_ID_SECTOR) + 2) * MFBLOCK_SIZE), ser, sizeof(ser)); + + uint8_t v3 = v1 ^ uid[1] ^ 0xD0; + + uint8_t rec[HEXACT_PAYLOAD_BLOCKS][MFBLOCK_SIZE]; + for (uint8_t i = 0; i < HEXACT_PAYLOAD_BLOCKS; i++) { + for (uint8_t k = 0; k < MFBLOCK_SIZE; k++) { + rec[i][k] = (uint8_t)(0xA0 + (i * MFBLOCK_SIZE) + k); // filler + } + } + + for (size_t i = 0; i < ARRAYLEN(hexact_checks); i++) { + const hexact_check_t *c = &hexact_checks[i]; + rec[c->rec][c->pos] = hexact_expect(c, idn, uid, ser); + } + + rec[1][7] = v1; + rec[2][15] = v1; + rec[4][7] = v1; + rec[0][15] = v3; + rec[3][15] = v3 ^ 0xB1; + + for (uint8_t i = 0; i < HEXACT_PAYLOAD_BLOCKS; i++) { + + uint8_t seed = hexact_seed(hexact_payload[i].sector, hexact_payload[i].blk); + uint8_t *dst = dump + ((mfFirstBlockOfSector(hexact_payload[i].sector) + hexact_payload[i].blk) * MFBLOCK_SIZE); + + for (uint8_t k = 0; k < MFBLOCK_SIZE; k++) { + dst[k] = rec[i][k] ^ hexact_rotl(seed, k); + } + } +} + +int hexact_selftest(void) { + + PrintAndLogEx(INFO, "Testing Hexact payload mask and cross checks"); + + uint8_t dump[MIFARE_1K_MAX_BYTES] = {0}; + hexact_build_selftest_card(dump, 0x5A); + + if (is_valid_hexact_card(dump, sizeof(dump)) == false) { + PrintAndLogEx(FAILED, " card not recognised ( " _RED_("fail") " )"); + return PM3_ESOFT; + } + + uint8_t rec[HEXACT_PAYLOAD_BLOCKS][MFBLOCK_SIZE]; + for (uint8_t i = 0; i < HEXACT_PAYLOAD_BLOCKS; i++) { + hexact_decrypt(dump + ((mfFirstBlockOfSector(hexact_payload[i].sector) + hexact_payload[i].blk) * MFBLOCK_SIZE), + hexact_payload[i].sector, + hexact_payload[i].blk, + rec[i] + ); + } + + bool written[HEXACT_PAYLOAD_BLOCKS]; + memset(written, true, sizeof(written)); + + uint8_t total = 0; + uint8_t pass = hexact_cross_check( + rec, + dump + (2 * MFBLOCK_SIZE), + dump, + dump + (mfFirstBlockOfSector(HEXACT_ID_SECTOR) + 2) * MFBLOCK_SIZE, + written, + &total, + false + ); + + PrintAndLogEx(INFO, " intact card........ %u / %u ( %s )", + pass, + total, + (pass == total) ? _GREEN_("ok") : _RED_("fail") + ); + + if (pass != total) { + return PM3_ESOFT; + } + + dump[0] ^= 0x01; + uint8_t broken = hexact_cross_check( + rec, + dump + (2 * MFBLOCK_SIZE), + dump, + dump + (mfFirstBlockOfSector(HEXACT_ID_SECTOR) + 2) * MFBLOCK_SIZE, + written, + &total, + false + ); + + PrintAndLogEx(INFO, " one UID bit flipped %u / %u ( %s )" + , broken + , total + , (broken == total - 4) ? _GREEN_("ok") : _RED_("fail") + ); + + if (broken != total - 4) { + return PM3_ESOFT; + } + + dump[0] ^= 0x01; + + // the two offsets the builder knows, read back through the table + uint8_t v3 = 0, v4 = 0; + const uint8_t *sser = dump + ((mfFirstBlockOfSector(HEXACT_ID_SECTOR) + 2) * MFBLOCK_SIZE); + bool ok = hexact_site_read(rec, dump + (2 * MFBLOCK_SIZE), dump, sser, written, 6, &v3); + ok &= hexact_site_read(rec, dump + (2 * MFBLOCK_SIZE), dump, sser, written, 11, &v4); + + PrintAndLogEx(INFO, " site constants..... %02X %02X ( %s )", v3, v4, + (ok && v3 == 0xD0 && v4 == 0xB1) ? _GREEN_("ok") : _RED_("fail")); + + if (ok == false || v3 != 0xD0 || v4 != 0xB1) { + return PM3_ESOFT; + } + + PrintAndLogEx(SUCCESS, "Hexact self test " _GREEN_("passed")); + return PM3_SUCCESS; +} diff --git a/client/src/parsers/parsehexact.h b/client/src/parsers/parsehexact.h new file mode 100644 index 000000000..66eaebaaf --- /dev/null +++ b/client/src/parsers/parsehexact.h @@ -0,0 +1,33 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// Hexact / COGELEC / Intratone parser for MIFARE Classic dumps +//----------------------------------------------------------------------------- + +#ifndef PARSEHEXACT_H__ +#define PARSEHEXACT_H__ + +#include "common.h" + +// True when sector 15 carries the Hexact system identifier +bool is_valid_hexact_card(const uint8_t *dump, size_t dumplen); + +// Print what is known about the layout of a Hexact card +int hexact_parser_parse(const uint8_t *dump, size_t dumplen); + +// Decode a card built from the model and check the decoder agrees, both ways +int hexact_selftest(void); + +#endif diff --git a/client/src/parsers/parsehid.c b/client/src/parsers/parsehid.c new file mode 100644 index 000000000..4b699c7e7 --- /dev/null +++ b/client/src/parsers/parsehid.c @@ -0,0 +1,83 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// HID PACS parser for MIFARE Classic dumps +//----------------------------------------------------------------------------- + +#include "parsehid.h" + +#include + +#include "commonutil.h" +#include "ui.h" // PrintAndLogEx +#include "util.h" // sprint_hex_inrow, hex_to_buffer +#include "protocols.h" // MFBLOCK_SIZE +#include "mifare/mad.h" +#include "mifare/mifare4.h" // mfFirstBlockOfSector +#include "wiegand_formats.h" +#include "wiegand_formatutils.h" + +// The PACS sector holds the credential in its three data blocks, tagged by a +// 0x02 marker at the head of the second one. +#define HID_PACS_MARKER 0x02 + +bool is_valid_hid_card(const uint8_t *dump, size_t dumplen) { + if (dump == NULL || dumplen < sizeof(mad1_sector_t)) { + return false; + } + return (DetectHID((const mad1_sector_t *)dump, HID_MAD_AID) > -1); +} + +int hid_parser_parse(const uint8_t *dump, size_t dumplen) { + + if (is_valid_hid_card(dump, dumplen) == false) { + return PM3_EINVARG; + } + + int sector = DetectHID((const mad1_sector_t *)dump, HID_MAD_AID); + + size_t pacs_off = mfFirstBlockOfSector(sector) * MFBLOCK_SIZE; + uint8_t pacs_sector[MFBLOCK_SIZE * 3] = {0}; + if (pacs_off + sizeof(pacs_sector) > dumplen) { + return PM3_EINVARG; + } + memcpy(pacs_sector, dump + pacs_off, sizeof(pacs_sector)); + + if (pacs_sector[MFBLOCK_SIZE] != HID_PACS_MARKER) { + return PM3_ESOFT; + } + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "------------------------- " _CYAN_("Wiegand") " ---------------------------"); + PrintAndLogEx(INFO, _CYAN_("HID PACS detected")); + + PrintAndLogEx(SUCCESS, "Raw...... " _GREEN_("%s"), sprint_hex_inrow(pacs_sector + 24, 8)); + + //todo: remove preamble/sentinel + uint32_t top = 0, mid = 0, bot = 0; + char hexstr[16 + 1] = {0}; + hex_to_buffer((uint8_t *)hexstr, pacs_sector + 24, 8, sizeof(hexstr) - 1, 0, 0, true); + hexstring_to_u96(&top, &mid, &bot, hexstr); + + char binstr[64 + 1]; + hextobinstring(binstr, hexstr); + char *pbin = binstr; + while (strlen(pbin) && *(++pbin) == '0'); + + PrintAndLogEx(SUCCESS, "Binary... " _GREEN_("%s"), pbin); + + decode_wiegand(top, mid, bot, 0); + return PM3_SUCCESS; +} diff --git a/client/src/parsers/parsehid.h b/client/src/parsers/parsehid.h new file mode 100644 index 000000000..971df098a --- /dev/null +++ b/client/src/parsers/parsehid.h @@ -0,0 +1,33 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// HID PACS parser for MIFARE Classic dumps +//----------------------------------------------------------------------------- + +#ifndef PARSEHID_H__ +#define PARSEHID_H__ + +#include "common.h" + +// MAD application id the HID Global access control scheme claims +#define HID_MAD_AID 0x484d + +// True when the MAD of this dump advertises the HID application +bool is_valid_hid_card(const uint8_t *dump, size_t dumplen); + +// Decode the HID PACS credential out of a whole card dump and print it +int hid_parser_parse(const uint8_t *dump, size_t dumplen); + +#endif diff --git a/client/src/parsers/parsemykey.c b/client/src/parsers/parsemykey.c new file mode 100644 index 000000000..f1c50a8fb --- /dev/null +++ b/client/src/parsers/parsemykey.c @@ -0,0 +1,419 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// MyKey / COGES parser for SRIX4K - ST25TB04K dumps +//----------------------------------------------------------------------------- + +#include "parsemykey.h" + +#include "commonutil.h" // ARRAYLEN, MemBeToUint4byte, MemLeToUint4byte +#include "ui.h" // PrintAndLogEx + +// Blocks below 0x10 are written by the chip maker and the key issuer +#define MYKEY_BLK_LOCKID 0x05 // lock id marker in the low byte +#define MYKEY_BLK_OTP 0x06 // count down counter, feeds the session key +#define MYKEY_BLK_KEYID 0x07 // key id, low three bytes +#define MYKEY_BLK_PRODUCED 0x08 // production date, BCD + +// The application itself starts at 0x10 and keeps most fields in duplicate +#define MYKEY_BLK_APP_FIRST 0x10 +#define MYKEY_BLK_ELAPSED 0x10 // key id top byte + days since 1995-01-01 +#define MYKEY_BLK_KEYID_A 0x11 // mirror of block 7 +#define MYKEY_BLK_OPS 0x12 // operations counter +#define MYKEY_BLK_KEYID_B 0x15 // mirror of block 7 +#define MYKEY_BLK_VENDOR_HI 0x18 +#define MYKEY_BLK_VENDOR_LO 0x19 +#define MYKEY_BLK_CREDIT_A 0x21 // current credit, XORed with the session key +#define MYKEY_BLK_PREV_A 0x23 // credit before the last transaction +#define MYKEY_BLK_CREDIT_B 0x25 +#define MYKEY_BLK_PREV_B 0x27 +#define MYKEY_BLK_TXN_FIRST 0x34 // eight slot transaction ring +#define MYKEY_BLK_TXN_CNT 8 +#define MYKEY_BLK_TXN_PTR 0x3C + +// Vendor code a key carries when it is not bound to any vendor +#define MYKEY_VENDOR_RESET 0xFEDC0123 +#define MYKEY_LOCKID_MARK 0x7F +#define MYKEY_BLANK 0xFFFFFFFF + +static uint8_t mykey_bcd(uint8_t v) { + return (NIBBLE_HIGH(v) * 10) + NIBBLE_LOW(v); +} + +static uint32_t mykey_scramble(uint32_t block) { + uint32_t res = 0; + for (uint8_t i = 0; i < 16; i++) { + uint8_t dst = ((i % 4) * 4) + (i / 4); + res |= (uint32_t)CRUMB(block, i * 2) << (dst * 2); + } + return res; +} + +static uint8_t mykey_crc(uint32_t block, uint8_t blockno) { + uint8_t crc = 0xFF - blockno; + for (uint8_t i = 0; i < 24; i += 4) { + crc -= NIBBLE_LOW(block >> i); + } + return crc; +} + +static bool mykey_crc_ok(uint32_t block, uint8_t blockno) { + return (mykey_crc(block, blockno) == (block >> 24)); +} + +static uint32_t mykey_block(const uint8_t *dump, uint8_t blockno) { + return MemBeToUint4byte(dump + (blockno * MYKEY_BLOCK_SIZE)); +} + +static uint32_t mykey_vendor(const uint8_t *dump) { + uint32_t hi = mykey_scramble(mykey_block(dump, MYKEY_BLK_VENDOR_HI)); + uint32_t lo = mykey_scramble(mykey_block(dump, MYKEY_BLK_VENDOR_LO)); + return ((hi & 0xFFFF) << 16) | (lo & 0xFFFF); +} + +static uint32_t mykey_session_key(const uint8_t *dump, const uint8_t *uid) { + uint32_t otp = ~BSWAP_32(mykey_block(dump, MYKEY_BLK_OTP)) + 1; + return MemLeToUint4byte(uid) * (mykey_vendor(dump) + 1) * otp; +} + +bool is_valid_mykey_card(const uint8_t *dump, size_t dumplen) { + + if (dump == NULL || dumplen < MYKEY_BYTES) { + return false; + } + + uint32_t keyid = mykey_block(dump, MYKEY_BLK_KEYID); + if (keyid == MYKEY_BLANK || keyid == 0) { + return false; + } + + const uint8_t mirrors[2] = { MYKEY_BLK_KEYID_A, MYKEY_BLK_KEYID_B }; + + for (uint8_t i = 0; i < ARRAYLEN(mirrors); i++) { + + uint32_t b = mykey_block(dump, mirrors[i]); + if ((b & 0x00FFFFFF) != (keyid & 0x00FFFFFF)) { + return false; + } + + if (mykey_crc_ok(b, mirrors[i]) == false) { + return false; + } + } + return true; +} + +static int32_t mykey_credit(const uint8_t *dump, uint8_t blockno, uint32_t sk) { + uint32_t v = mykey_scramble(mykey_block(dump, blockno) ^ sk); + if (mykey_crc_ok(v, blockno) == false) { + return PM3_ECRC; + } + return (int32_t)(v & 0xFFFF); +} + +static uint16_t mykey_check_blocks(const uint8_t *dump, uint32_t sk, uint16_t *total) { + + uint16_t ok = 0; + *total = 0; + + uint32_t keymask = mykey_block(dump, MYKEY_BLK_KEYID) & 0x00FFFFFF; + + for (uint16_t i = MYKEY_BLK_APP_FIRST; i < MYKEY_NUM_BLOCKS; i++) { + + uint32_t b = mykey_block(dump, i); + if (b == MYKEY_BLANK) { + continue; + } + + if ((i >= MYKEY_BLK_TXN_FIRST) && (i < (MYKEY_BLK_TXN_FIRST + MYKEY_BLK_TXN_CNT))) { + continue; + } + + (*total)++; + + if (mykey_crc_ok(b, i) || + mykey_crc_ok(mykey_scramble(b), i) || + mykey_crc_ok(mykey_scramble(b ^ sk), i) || + mykey_crc_ok(mykey_scramble(b ^ keymask), i)) { + ok++; + } + } + return ok; +} + +static void mykey_print_produced(uint32_t blk) { + + uint8_t day = mykey_bcd((blk >> 24) & 0xFF); + uint8_t month = mykey_bcd((blk >> 16) & 0xFF); + uint16_t year = (mykey_bcd(SWAP_NIBBLE(blk & 0xFF)) * 100) + mykey_bcd((blk >> 8) & 0xFF); + + PrintAndLogEx(INFO, "Produced........... " _YELLOW_("%04u-%02u-%02u"), year, month, day); +} + +static void mykey_print_transactions(const uint8_t *dump) { + + uint32_t ptrblk = mykey_block(dump, MYKEY_BLK_TXN_PTR); + int32_t ptr = -1; + + if (ptrblk != MYKEY_BLANK) { + + uint32_t v = mykey_scramble(ptrblk ^ (mykey_block(dump, MYKEY_BLK_KEYID) & 0x00FFFFFF)); + if (mykey_crc_ok(v, MYKEY_BLK_TXN_PTR)) { + ptr = (int32_t)((v >> 16) & 0xFF); + } + + if (ptr > (MYKEY_BLK_TXN_CNT - 1)) { + ptr = -1; + } + } + + uint8_t used = 0; + for (uint8_t i = 0; i < MYKEY_BLK_TXN_CNT; i++) { + if (mykey_block(dump, MYKEY_BLK_TXN_FIRST + i) != MYKEY_BLANK) { + used++; + } + } + + if (used == 0) { + PrintAndLogEx(INFO, "Transactions....... " _YELLOW_("none")); + return; + } + + PrintAndLogEx(INFO, "Transactions....... %u of %u slots used", used, MYKEY_BLK_TXN_CNT); + + for (uint8_t i = 0; i < MYKEY_BLK_TXN_CNT; i++) { + + uint32_t t = mykey_block(dump, MYKEY_BLK_TXN_FIRST + i); + if (t == MYKEY_BLANK) { + continue; + } + + PrintAndLogEx(INFO, " %s slot %u........ %04u-%02u-%02u " _GREEN_("%u.%02u") " EUR", + (i == ptr) ? ">" : " ", + i, + 2000 + ((t >> 16) & 0x7F), + NIBBLE_LOW(t >> 23), + (t >> 27) & 0x1F, + (t & 0xFFFF) / 100, + (t & 0xFFFF) % 100 + ); + } +} + +int mykey_parser_parse(const uint8_t *dump, size_t dumplen, const uint8_t *uid) { + + if (is_valid_mykey_card(dump, dumplen) == false) { + return PM3_EINVARG; + } + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("MyKey / COGES") " ------------------------"); + + PrintAndLogEx(INFO, "Key ID............. " _YELLOW_("%06X"), mykey_block(dump, MYKEY_BLK_KEYID) & 0x00FFFFFF); + mykey_print_produced(mykey_block(dump, MYKEY_BLK_PRODUCED)); + + uint32_t elapsed = mykey_block(dump, MYKEY_BLK_ELAPSED) & 0xFFFF; + if (elapsed) { + PrintAndLogEx(INFO, "Days since 1995.... %04X", elapsed); + } + + uint32_t ops = mykey_block(dump, MYKEY_BLK_OPS); + if (mykey_crc_ok(ops, MYKEY_BLK_OPS)) { + PrintAndLogEx(INFO, "Operations......... " _YELLOW_("%u"), ops & 0x00FFFFFF); + } + + uint32_t vendor = mykey_vendor(dump); + if (vendor == MYKEY_VENDOR_RESET) { + PrintAndLogEx(INFO, "Vendor............. " _YELLOW_("reset") ", not bound to a vendor"); + } else { + PrintAndLogEx(INFO, "Vendor............. " _YELLOW_("%08X"), vendor); + } + + bool lockid = ((mykey_block(dump, MYKEY_BLK_LOCKID) & 0xFF) == MYKEY_LOCKID_MARK); + PrintAndLogEx(INFO, "Lock ID............ %s", lockid ? _RED_("yes") : _GREEN_("no")); + + bool have_uid = false; + for (uint8_t i = 0; (uid != NULL) && (i < 8); i++) { + if (uid[i]) { + have_uid = true; + break; + } + } + + if (have_uid == false) { + PrintAndLogEx(INFO, "Session key........ " _YELLOW_("unknown") ", UID needed to decrypt the credit"); + PrintAndLogEx(INFO, "Credit............. %08X " _YELLOW_("still encrypted"), mykey_block(dump, MYKEY_BLK_CREDIT_A)); + mykey_print_transactions(dump); + return PM3_SUCCESS; + } + + uint32_t sk = mykey_session_key(dump, uid); + PrintAndLogEx(INFO, "Session key........ " _YELLOW_("%08X"), sk); + + int32_t credit = mykey_credit(dump, MYKEY_BLK_CREDIT_A, sk); + int32_t copy = mykey_credit(dump, MYKEY_BLK_CREDIT_B, sk); + + if (credit == PM3_ECRC) { + PrintAndLogEx(INFO, "Credit............. " _RED_("checksum failed") ", wrong UID or unknown vendor"); + } else { + PrintAndLogEx(INFO, "Credit............. " _GREEN_("%u.%02u") " EUR", credit / 100, credit % 100); + if (copy != credit) { + PrintAndLogEx(INFO, " block %02X disagrees, a torn write", MYKEY_BLK_CREDIT_B); + } + } + + // The previous credit is scrambled but not XORed with the session key + int32_t prev = mykey_credit(dump, MYKEY_BLK_PREV_A, 0); + int32_t prev_copy = mykey_credit(dump, MYKEY_BLK_PREV_B, 0); + + if (prev != PM3_ECRC) { + PrintAndLogEx(INFO, "Previous credit.... " _GREEN_("%u.%02u") " EUR", prev / 100, prev % 100); + if (prev_copy != prev) { + PrintAndLogEx(INFO, " block %02X disagrees, a torn write", MYKEY_BLK_PREV_B); + } + } + + if (lockid && (credit == PM3_ECRC)) { + PrintAndLogEx(WARNING, "Lock id set and the credit does not check out"); + } + + mykey_print_transactions(dump); + + uint16_t total = 0; + uint16_t ok = mykey_check_blocks(dump, sk, &total); + PrintAndLogEx(INFO, "Block checksums.... %u / %u ( %s )" + , ok + , total + , (ok == total) ? _GREEN_("ok") : _RED_("fail") + ); + + return PM3_SUCCESS; +} + +// A reset key read off an ST25TB04K. Every written block checksums, the vendor +// is the reset code and the credit is zero. +static const uint8_t mykey_selftest_uid[8] = { 0x56, 0x65, 0xB2, 0x3C, 0x67, 0x1F, 0x02, 0xD0 }; + +static const uint8_t mykey_selftest_dump[MYKEY_BYTES] = { + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0x64, 0x95, 0x43, 0x19, 0x27, 0x10, 0x21, 0x02, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xE5, 0x64, 0x00, 0x00, 0xCF, 0x95, 0x43, 0x19, + 0xEC, 0x00, 0x00, 0x01, 0xE4, 0x04, 0x00, 0x13, 0xE1, 0x64, 0x00, 0x00, + 0xCB, 0x95, 0x43, 0x19, 0xE8, 0x00, 0x00, 0x01, 0xE0, 0x04, 0x00, 0x13, + 0x8F, 0xCD, 0x0F, 0x48, 0xC0, 0x82, 0x00, 0x07, 0xC0, 0x80, 0x40, 0x40, + 0xC0, 0x80, 0x40, 0x00, 0x8F, 0x8D, 0xCF, 0x48, 0xC0, 0x42, 0xC0, 0x07, + 0xC0, 0x80, 0x00, 0x40, 0xC0, 0x80, 0x00, 0x00, 0xC0, 0x40, 0xC0, 0x90, + 0x65, 0x23, 0x56, 0x98, 0xC0, 0x66, 0x01, 0x13, 0xC0, 0x40, 0xC0, 0x00, + 0xC0, 0x40, 0x80, 0x90, 0x65, 0x23, 0x16, 0x98, 0xC0, 0x26, 0xC1, 0x13, + 0xC0, 0x40, 0x80, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xB6, 0x64, 0x00, 0x00, 0xA0, 0x95, 0x43, 0x19, 0xBD, 0x00, 0x00, 0x01, + 0xB5, 0x04, 0x00, 0x13, 0xB2, 0x64, 0x00, 0x00, 0x9C, 0x95, 0x43, 0x19, + 0xB9, 0x00, 0x00, 0x01, 0xB1, 0x04, 0x00, 0x13, 0x8F, 0x0D, 0x0F, 0x88, + 0x80, 0xC2, 0x00, 0x47, 0x80, 0xC0, 0x40, 0x80, 0x80, 0xC0, 0x40, 0x40, + 0x4F, 0xCD, 0xCF, 0x88, 0x80, 0x82, 0xC0, 0x47, 0x80, 0xC0, 0x00, 0x80, + 0x80, 0xC0, 0x00, 0x40, 0x80, 0x80, 0xC0, 0xD0, 0x80, 0x80, 0xC0, 0xC0, + 0x80, 0xA6, 0x01, 0x53, 0x80, 0x80, 0xC0, 0x40, 0x80, 0x80, 0x80, 0xD0, + 0x80, 0x80, 0x80, 0xC0, 0x80, 0x66, 0xC1, 0x53, 0x80, 0x80, 0x80, 0x40, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, +}; + +static const struct { + uint32_t enc; + uint32_t dec; +} mykey_selftest_vectors[] = { + { 0xC04F42C5, 0xD7003139 }, + { 0xC1484807, 0xD4002943 }, + { 0xC0C60848, 0xF1001A20 }, +}; + +int mykey_selftest(void) { + + PrintAndLogEx(INFO, "Testing MyKey block scrambler and session key"); + + for (uint8_t i = 0; i < ARRAYLEN(mykey_selftest_vectors); i++) { + + uint32_t enc = mykey_selftest_vectors[i].enc; + uint32_t dec = mykey_selftest_vectors[i].dec; + + if (mykey_scramble(enc) != dec) { + PrintAndLogEx(FAILED, " %08X descrambled to %08X, expected %08X ( " _RED_("fail") " )" + , enc + , mykey_scramble(enc) + , dec + ); + return PM3_ESOFT; + } + + if (mykey_scramble(dec) != enc) { + PrintAndLogEx(FAILED, " scrambler is not its own inverse on %08X ( " _RED_("fail") " )", dec); + return PM3_ESOFT; + } + } + PrintAndLogEx(INFO, " scrambler.......... %u vectors, self inverse ( " _GREEN_("ok") " )", (unsigned)ARRAYLEN(mykey_selftest_vectors)); + + if (is_valid_mykey_card(mykey_selftest_dump, sizeof(mykey_selftest_dump)) == false) { + PrintAndLogEx(FAILED, " known good dump not recognised ( " _RED_("fail") " )"); + return PM3_ESOFT; + } + + uint32_t vendor = mykey_vendor(mykey_selftest_dump); + if (vendor != MYKEY_VENDOR_RESET) { + PrintAndLogEx(FAILED, " vendor %08X, expected the reset code %08X ( " _RED_("fail") " )", vendor, MYKEY_VENDOR_RESET); + return PM3_ESOFT; + } + + uint32_t sk = mykey_session_key(mykey_selftest_dump, mykey_selftest_uid); + PrintAndLogEx(INFO, " session key........ %08X", sk); + + int32_t credit = mykey_credit(mykey_selftest_dump, MYKEY_BLK_CREDIT_A, sk); + if (credit != 0) { + PrintAndLogEx(FAILED, " credit read back as %d, expected 0 ( " _RED_("fail") " )", credit); + return PM3_ESOFT; + } + + uint16_t total = 0; + uint16_t ok = mykey_check_blocks(mykey_selftest_dump, sk, &total); + if (ok != total || total == 0) { + PrintAndLogEx(FAILED, " %u of %u block checksums ( " _RED_("fail") " )", ok, total); + return PM3_ESOFT; + } + PrintAndLogEx(INFO, " block checksums.... %u / %u ( " _GREEN_("ok") " )", ok, total); + + PrintAndLogEx(SUCCESS, "MyKey parser selftest ( " _GREEN_("ok") " )"); + return PM3_SUCCESS; +} diff --git a/client/src/parsers/parsemykey.h b/client/src/parsers/parsemykey.h new file mode 100644 index 000000000..68c174bb3 --- /dev/null +++ b/client/src/parsers/parsemykey.h @@ -0,0 +1,32 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// MyKey / COGES parser for SRIX4K - ST25TB04K dumps +//----------------------------------------------------------------------------- + +#ifndef PARSEMYKEY_H__ +#define PARSEMYKEY_H__ + +#include "common.h" + +#define MYKEY_BLOCK_SIZE 4 +#define MYKEY_NUM_BLOCKS 128 +#define MYKEY_BYTES (MYKEY_NUM_BLOCKS * MYKEY_BLOCK_SIZE) + +bool is_valid_mykey_card(const uint8_t *dump, size_t dumplen); +int mykey_parser_parse(const uint8_t *dump, size_t dumplen, const uint8_t *uid); +int mykey_selftest(void); + +#endif diff --git a/client/src/parsers/parsenortic.c b/client/src/parsers/parsenortic.c new file mode 100644 index 000000000..fed9c16e2 --- /dev/null +++ b/client/src/parsers/parsenortic.c @@ -0,0 +1,422 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// NORTIC travel card parser for MIFARE DESFire dumps +//----------------------------------------------------------------------------- + +#include "parsenortic.h" + +#include // snprintf +#include + +#include "commonutil.h" // ARRAYLEN +#include "ui.h" // PrintAndLogEx +#include "util.h" // sprint_hex_inrow + +#define NORTIC_CI_HEADER_SIZE 16 + +// Days from 1970-01-01 to the EN 1545 date epoch of 1997-01-01 +#define NORTIC_DAYS_TO_1997 9862 + +#define NORTIC_LABEL "%-22s" + +//----------------------------------------------------------------------------- +// Bit access +// +// EN 1545 packs fields most significant bit first, so bit 0 is the top bit of +// byte 0. This is the opposite of the RKF Type CL-1 layout in parserkf.c, where +// RKF-0022 section 7.4.1 numbers bits from the least significant end. +//----------------------------------------------------------------------------- + +static uint64_t nortic_bits(const uint8_t *buf, uint16_t off, uint8_t len) { + uint64_t v = 0; + for (uint8_t k = 0; k < len; k++) { + uint16_t b = off + k; + v = (v << 1) | ((buf[b >> 3] >> (7 - (b & 7))) & 1); + } + return v; +} + +static void nortic_set_bits(uint8_t *buf, uint16_t off, uint8_t len, uint64_t v) { + for (uint8_t k = 0; k < len; k++) { + uint16_t b = off + k; + uint8_t bit = (v >> (len - 1 - k)) & 1; + if (bit) { + buf[b >> 3] |= (uint8_t)(1 << (7 - (b & 7))); + } else { + buf[b >> 3] &= (uint8_t)~(1 << (7 - (b & 7))); + } + } +} + +//----------------------------------------------------------------------------- +// Card issuer header, file 0C of AID 578000, 16 bytes +//----------------------------------------------------------------------------- + +#define NORTIC_OFF_COUNTRY 0 +#define NORTIC_OFF_FORMAT 10 +#define NORTIC_OFF_CHOICE 30 +#define NORTIC_OFF_SERIAL 32 +#define NORTIC_OFF_VALIDITY 64 +#define NORTIC_OFF_OWNER 78 +#define NORTIC_OFF_RETAILER 98 +#define NORTIC_OFF_KEYVERSION 118 +#define NORTIC_OFF_UNUSED 122 + +typedef struct { + uint16_t country; + uint32_t format; + uint8_t choice; + uint32_t serial; + uint16_t validity_end; + uint32_t owner; + uint32_t retailer; + uint8_t key_version; + uint8_t unused; +} nortic_ci_t; + +static void nortic_read_ci(const uint8_t *d, nortic_ci_t *c) { + c->country = (uint16_t)nortic_bits(d, NORTIC_OFF_COUNTRY, 10); + c->format = (uint32_t)nortic_bits(d, NORTIC_OFF_FORMAT, 20); + c->choice = (uint8_t)nortic_bits(d, NORTIC_OFF_CHOICE, 2); + c->serial = (uint32_t)nortic_bits(d, NORTIC_OFF_SERIAL, 32); + c->validity_end = (uint16_t)nortic_bits(d, NORTIC_OFF_VALIDITY, 14); + c->owner = (uint32_t)nortic_bits(d, NORTIC_OFF_OWNER, 20); + c->retailer = (uint32_t)nortic_bits(d, NORTIC_OFF_RETAILER, 20); + c->key_version = (uint8_t)nortic_bits(d, NORTIC_OFF_KEYVERSION, 4); + c->unused = (uint8_t)nortic_bits(d, NORTIC_OFF_UNUSED, 6); +} + +//----------------------------------------------------------------------------- +// Value decoding +//----------------------------------------------------------------------------- + +static void nortic_civil_from_days(int32_t z, int *year, unsigned *month, unsigned *day) { + z += 719468; + int32_t era = ((z >= 0) ? z : (z - 146096)) / 146097; + uint32_t doe = (uint32_t)(z - (era * 146097)); + uint32_t yoe = (doe - (doe / 1460) + (doe / 36524) - (doe / 146096)) / 365; + int32_t y = (int32_t)yoe + (era * 400); + uint32_t doy = doe - ((365 * yoe) + (yoe / 4) - (yoe / 100)); + uint32_t mp = ((5 * doy) + 2) / 153; + *day = doy - (((153 * mp) + 2) / 5) + 1; + *month = (mp < 10) ? (mp + 3) : (mp - 9); + *year = y + ((*month <= 2) ? 1 : 0); +} + +// EN 1545 date, day 0 is 1 January 1997 +static void nortic_date_str(uint16_t v, char *out, size_t outlen) { + int y; + unsigned m, d; + nortic_civil_from_days((int32_t)v + NORTIC_DAYS_TO_1997, &y, &m, &d); + snprintf(out, outlen, "%04d-%02u-%02u", y, m, d); +} + +static const char *nortic_country_name(uint16_t code) { + switch (code) { + case 208: + return "Denmark"; + case 246: + return "Finland"; + case 578: + return "Norway"; + case 752: + return "Sweden"; + default: + return NULL; + } +} + +// The choice bitmap says which optional card identifier is present +static const char *nortic_choice_name(uint8_t choice) { + switch (choice) { + case 0: + return "none"; + case 1: + return "RFU"; + case 2: + return "cardIDNumber32bits"; + default: + return "RFU"; + } +} + +//----------------------------------------------------------------------------- +// Transport application file map +//----------------------------------------------------------------------------- + +static const struct { + uint8_t fid; + const char *name; + const char *note; +} nortic_transport_files[] = { + {0x01, "Product Retailer", "384 bytes, written with key 4"}, + {0x02, "Service Provider", "128 bytes, written with key 6"}, + {0x03, "Special Event", "288 bytes, written with key 6"}, + {0x04, "Stored Value", "value file, written with key 5"}, + {0x05, "General Event Log", "cyclic, 36 bytes per record"}, + {0x06, "SV Reload Log", "cyclic, 32 bytes per record"}, + {0x0A, "Environment", "32 bytes, written with key 2"}, + {0x0C, "Card Holder", "32 bytes, written with key 3"}, +}; + +static const char *nortic_transport_file_name(uint8_t fid) { + for (size_t i = 0; i < ARRAYLEN(nortic_transport_files); i++) { + if (nortic_transport_files[i].fid == fid) { + return nortic_transport_files[i].name; + } + } + return NULL; +} + +//----------------------------------------------------------------------------- +// Lookup helpers +//----------------------------------------------------------------------------- + +static const desfire_dump_app_t *nortic_find_app(const desfire_dump_t *dump, uint32_t aid) { + if (dump == NULL) { + return NULL; + } + for (uint8_t i = 0; i < dump->appcount && i < DESFIRE_MAX_APP_COUNT; i++) { + if (dump->app[i].aid == aid) { + return &dump->app[i]; + } + } + return NULL; +} + +static const desfire_dump_file_t *nortic_find_file(const desfire_dump_app_t *app, uint8_t fid) { + if (app == NULL) { + return NULL; + } + for (uint8_t i = 0; i < app->filecount && i < DESFIRE_MAX_FILE_COUNT; i++) { + if (app->files[i].num == fid) { + return &app->files[i]; + } + } + return NULL; +} + +//----------------------------------------------------------------------------- +// Detection +//----------------------------------------------------------------------------- + +bool is_valid_nortic_card(const desfire_dump_t *dump) { + return (nortic_find_app(dump, NORTIC_AID_CARD_ISSUER) != NULL); +} + +//----------------------------------------------------------------------------- +// Printing +//----------------------------------------------------------------------------- + +static void nortic_print_ci(const nortic_ci_t *c) { + + char buf[32]; + const char *country = nortic_country_name(c->country); + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Card issuer header") " --- AID %06X file %02X", + NORTIC_AID_CARD_ISSUER, NORTIC_FID_CI_HEADER); + + PrintAndLogEx(INFO, NORTIC_LABEL " %u ( %s )", "Country code", c->country, + country ? country : "unknown"); + PrintAndLogEx(INFO, NORTIC_LABEL " %u", "Format", c->format); + PrintAndLogEx(INFO, NORTIC_LABEL " %u ( %s )", "Choice bitmap", c->choice, + nortic_choice_name(c->choice)); + PrintAndLogEx(INFO, NORTIC_LABEL " " _YELLOW_("%u") " ( %08X )", "Card serial number", + c->serial, c->serial); + + nortic_date_str(c->validity_end, buf, sizeof(buf)); + PrintAndLogEx(INFO, NORTIC_LABEL " " _YELLOW_("%s") " ( day %u )", "Valid until", buf, + c->validity_end); + + PrintAndLogEx(INFO, NORTIC_LABEL " %u", "App owner company", c->owner); + PrintAndLogEx(INFO, NORTIC_LABEL " %u", "Retailer organisation", c->retailer); + PrintAndLogEx(INFO, NORTIC_LABEL " %u", "Card key version", c->key_version); + + if (c->unused != 0) { + PrintAndLogEx(INFO, NORTIC_LABEL " %u ( " _YELLOW_("expected 0") " )", "Unused bits", c->unused); + } +} + +static void nortic_print_transport(const desfire_dump_app_t *app) { + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Transport application") " --- AID %06X", NORTIC_AID_TRANSPORT); + + if (app == NULL) { + PrintAndLogEx(INFO, "Not present on this card"); + return; + } + + PrintAndLogEx(INFO, " fid | file | read"); + PrintAndLogEx(INFO, "-----+---------------------+---------------------------------------"); + + for (uint8_t i = 0; i < app->filecount && i < DESFIRE_MAX_FILE_COUNT; i++) { + + const desfire_dump_file_t *f = &app->files[i]; + const char *name = nortic_transport_file_name(f->num); + + PrintAndLogEx(INFO, " %02X | %-19s | %s", f->num, name ? name : "unknown", + f->read_ok ? _GREEN_("read") : _YELLOW_("not read, needs key 7")); + } + + PrintAndLogEx(INFO, "-----+---------------------+---------------------------------------"); + + // Contents are only printed as hex. The field layouts of these files are in + // Handbok V821 Del 18, which is not published. + for (uint8_t i = 0; i < app->filecount && i < DESFIRE_MAX_FILE_COUNT; i++) { + + const desfire_dump_file_t *f = &app->files[i]; + if (f->read_ok == false || f->data == NULL || f->datalen == 0) { + continue; + } + + const char *name = nortic_transport_file_name(f->num); + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "file %02X %s %u bytes " _YELLOW_("not decoded"), f->num, + name ? name : "unknown", f->datalen); + + for (uint32_t off = 0; off < f->datalen; off += 16) { + uint32_t n = (f->datalen - off < 16) ? (f->datalen - off) : 16; + PrintAndLogEx(INFO, " %04X %s", off, sprint_hex_inrow(f->data + off, n)); + } + } +} + +//----------------------------------------------------------------------------- +// Top level +//----------------------------------------------------------------------------- + +int nortic_parser_parse(const desfire_dump_t *dump) { + + const desfire_dump_app_t *ci = nortic_find_app(dump, NORTIC_AID_CARD_ISSUER); + if (ci == NULL) { + return PM3_EINVARG; + } + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("NORTIC travel card") " ------------------------"); + PrintAndLogEx(INFO, "Norwegian Ticketing Interoperable Concept"); + + const desfire_dump_file_t *f = nortic_find_file(ci, NORTIC_FID_CI_HEADER); + + if (f == NULL) { + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "Card issuer header (file %02X) is not in this dump", + NORTIC_FID_CI_HEADER); + } else if (f->read_ok == false || f->data == NULL) { + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "Card issuer header was not read. It needs no key, so retry the dump"); + } else if (f->datalen < NORTIC_CI_HEADER_SIZE) { + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "Card issuer header is %u bytes, expected %u", f->datalen, + NORTIC_CI_HEADER_SIZE); + } else { + nortic_ci_t c; + nortic_read_ci(f->data, &c); + nortic_print_ci(&c); + + if (c.country != NORTIC_COUNTRY_NORWAY) { + PrintAndLogEx(INFO, ""); + PrintAndLogEx(WARNING, "Country code is %u, not %u. The layout below is the", + c.country, NORTIC_COUNTRY_NORWAY); + PrintAndLogEx(WARNING, "Norwegian one and may not hold."); + } + } + + nortic_print_transport(nortic_find_app(dump, NORTIC_AID_TRANSPORT)); + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "Transport application layouts are in Handbok V821 Del 18, which is"); + PrintAndLogEx(INFO, "not published. Its files also need read key 7, which is not public"); + return PM3_SUCCESS; +} + +//----------------------------------------------------------------------------- +// Self test +//----------------------------------------------------------------------------- + +static bool nortic_check(const char *what, uint64_t got, uint64_t want) { + bool ok = (got == want); + PrintAndLogEx(INFO, " %-24s %12llu ( %s )", what, (unsigned long long)got, + ok ? _GREEN_("ok") : _RED_("fail")); + return ok; +} + +int nortic_selftest(void) { + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "Testing NORTIC card issuer header decode"); + + // The published card issuer header, with the serial number filled in where + // the capture redacted it + const uint8_t ci[NORTIC_CI_HEADER_SIZE] = { + 0x90, 0x80, 0x00, 0x02, 0xAA, 0xBB, 0xCC, 0xDD, + 0x6C, 0x68, 0x00, 0x28, 0x00, 0x02, 0x80, 0x40 + }; + + nortic_ci_t c; + nortic_read_ci(ci, &c); + + bool ok = true; + ok &= nortic_check("country code", c.country, NORTIC_COUNTRY_NORWAY); + ok &= nortic_check("format", c.format, 0); + ok &= nortic_check("choice bitmap", c.choice, 2); + ok &= nortic_check("card serial number", c.serial, 0xAABBCCDD); + ok &= nortic_check("validity end day", c.validity_end, 6938); + ok &= nortic_check("app owner company", c.owner, 160); + ok &= nortic_check("retailer organisation", c.retailer, 160); + ok &= nortic_check("card key version", c.key_version, 1); + ok &= nortic_check("unused bits", c.unused, 0); + + char buf[32]; + nortic_date_str(c.validity_end, buf, sizeof(buf)); + bool dok = (strcmp(buf, "2015-12-31") == 0); + PrintAndLogEx(INFO, " %-24s %12s ( %s )", "validity end date", buf, + dok ? _GREEN_("ok") : _RED_("fail")); + ok &= dok; + + // EN 1545 is most significant bit first. Reading it the RKF way gives 144, + // so a wrong bit order cannot pass unnoticed. + uint64_t lsb = 0; + for (uint8_t k = 0; k < 10; k++) { + if ((ci[k >> 3] >> (k & 7)) & 1) { + lsb |= (uint64_t)1 << k; + } + } + ok &= nortic_check("lsb first would give", lsb, 144); + + // round trip through the encoder + uint8_t enc[NORTIC_CI_HEADER_SIZE] = {0}; + nortic_set_bits(enc, NORTIC_OFF_COUNTRY, 10, c.country); + nortic_set_bits(enc, NORTIC_OFF_FORMAT, 20, c.format); + nortic_set_bits(enc, NORTIC_OFF_CHOICE, 2, c.choice); + nortic_set_bits(enc, NORTIC_OFF_SERIAL, 32, c.serial); + nortic_set_bits(enc, NORTIC_OFF_VALIDITY, 14, c.validity_end); + nortic_set_bits(enc, NORTIC_OFF_OWNER, 20, c.owner); + nortic_set_bits(enc, NORTIC_OFF_RETAILER, 20, c.retailer); + nortic_set_bits(enc, NORTIC_OFF_KEYVERSION, 4, c.key_version); + nortic_set_bits(enc, NORTIC_OFF_UNUSED, 6, c.unused); + + bool rok = (memcmp(enc, ci, NORTIC_CI_HEADER_SIZE) == 0); + PrintAndLogEx(INFO, " %-24s %12s ( %s )", "re-encodes to the same 16 B", + sprint_hex_inrow(enc, 4), rok ? _GREEN_("ok") : _RED_("fail")); + ok &= rok; + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "NORTIC self test ( %s )", ok ? _GREEN_("ok") : _RED_("fail")); + return ok ? PM3_SUCCESS : PM3_ESOFT; +} diff --git a/client/src/parsers/parsenortic.h b/client/src/parsers/parsenortic.h new file mode 100644 index 000000000..a321d1511 --- /dev/null +++ b/client/src/parsers/parsenortic.h @@ -0,0 +1,48 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// NORTIC travel card parser for MIFARE DESFire dumps +// +// Norwegian Ticketing Interoperable Concept, the national public transport card +// specified by Statens vegvesen and now Jernbanedirektoratet, Handbok V821. +// Fields are EN 1545 coded. +//----------------------------------------------------------------------------- + +#ifndef PARSENORTIC_H__ +#define PARSENORTIC_H__ + +#include "common.h" +#include "fileutils.h" // desfire_dump_t + +// Card Issuer application. Its header file is free to read, no key needed. +#define NORTIC_AID_CARD_ISSUER 0x578000 +#define NORTIC_FID_CI_HEADER 0x0C + +// Transport application. Every file needs the read key, number 7. +#define NORTIC_AID_TRANSPORT 0x578001 + +// ISO 3166 numeric code carried in the first field of the card issuer header +#define NORTIC_COUNTRY_NORWAY 578 + +// True when the dump carries the NORTIC card issuer application +bool is_valid_nortic_card(const desfire_dump_t *dump); + +// Decode the card issuer header and name what the transport application holds +int nortic_parser_parse(const desfire_dump_t *dump); + +// Check the decoder against the published card issuer header +int nortic_selftest(void); + +#endif diff --git a/client/src/parsers/parseproac.c b/client/src/parsers/parseproac.c new file mode 100644 index 000000000..e7fe243e9 --- /dev/null +++ b/client/src/parsers/parseproac.c @@ -0,0 +1,159 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// PROAC PACS parser for MIFARE Classic dumps +//----------------------------------------------------------------------------- + +#include "parseproac.h" + +#include // isprint +#include + +#include "commonutil.h" // ARRAYLEN +#include "crc.h" // CRC8Mad +#include "ui.h" // PrintAndLogEx +#include "util.h" // sprint_hex_inrow, str_append, str_trim +#include "mifare/mad.h" +#include "mifare/mifaredefault.h" // MFBLOCK_SIZE +#include "mifare/mifare4.h" // mfFirstBlockOfSector + +#define PROAC_SCHED_SECTOR_A 1 +#define PROAC_SCHED_SECTOR_B 2 +#define PROAC_SCHED_HEADER 4 + +#define PROAC_LOT_SECTOR 14 +#define PROAC_LOT_BLOCK 1 + +#define PROAC_BLOB_SECTOR_A 12 +#define PROAC_BLOB_SECTOR_B 13 + +#define PROAC_TAIL_SECTOR 15 + +// three data blocks per sector, both schedule sectors, less the header +#define PROAC_SCHED_MAX ((2 * 3 * MFBLOCK_SIZE) - PROAC_SCHED_HEADER) + +static const uint8_t *proac_block(const uint8_t *dump, size_t dumplen, uint8_t sector, uint8_t block) { + size_t off = (mfFirstBlockOfSector(sector) + block) * MFBLOCK_SIZE; + if (off + MFBLOCK_SIZE > dumplen) { + return NULL; + } + return dump + off; +} + +bool is_valid_proac_card(const uint8_t *dump, size_t dumplen) { + if (dump == NULL || dumplen < sizeof(mad1_sector_t)) { + return false; + } + return (mad_find_aid((const mad1_sector_t *)dump, PROAC_MAD_AID) > -1); +} + +static size_t proac_schedule(const uint8_t *dump, size_t dumplen, char *out, size_t outlen) { + size_t n = 0; + const uint8_t sectors[2] = { PROAC_SCHED_SECTOR_A, PROAC_SCHED_SECTOR_B }; + + for (uint8_t s = 0; s < ARRAYLEN(sectors); s++) { + + for (uint8_t b = 0; b < 3; b++) { + + const uint8_t *p = proac_block(dump, dumplen, sectors[s], b); + if (p == NULL) { + return n; + } + + uint8_t start = (s == 0 && b == 0) ? PROAC_SCHED_HEADER : 0; + for (uint8_t k = start; k < MFBLOCK_SIZE; k++) { + + if (p[k] == 0x00) { + return n; + } + + if (n + 1 >= outlen) { + return n; + } + out[n++] = isprint(p[k]) ? (char)p[k] : '.'; + } + } + } + return n; +} + +int proac_parser_parse(const uint8_t *dump, size_t dumplen) { + + if (is_valid_proac_card(dump, dumplen) == false) { + return PM3_EINVARG; + } + + const mad1_sector_t *s0 = (const mad1_sector_t *)dump; + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("PROAC") " detected --------------------"); + PrintAndLogEx(INFO, "MAD AID............ " _YELLOW_("0x%04X") " on %d of %d sectors", + PROAC_MAD_AID, + mad_count_aid(s0, PROAC_MAD_AID), + MAD1_NUM_AIDS + ); + + // The one card this was written against carries a MAD whose CRC was never + // filled in, so a reader in this system cannot be validating it. Say so + // rather than silently trusting the directory. + uint8_t crc = CRC8Mad((uint8_t *)&s0->mad.info, sizeof(mad1_t) - 1); + if (crc != s0->mad.crc) { + PrintAndLogEx(INFO, "MAD CRC............ %02X, computed %02X ( " _RED_("invalid") " )", s0->mad.crc, crc); + } + + const uint8_t *hdr = proac_block(dump, dumplen, PROAC_SCHED_SECTOR_A, 0); + if (hdr) { + PrintAndLogEx(INFO, "Schedule header.... %s", sprint_hex_inrow(hdr, PROAC_SCHED_HEADER)); + } + + char sched[PROAC_SCHED_MAX + 1] = {0}; + if (proac_schedule(dump, dumplen, sched, sizeof(sched)) > 0) { + PrintAndLogEx(INFO, "Schedule........... " _YELLOW_("%s"), sched); + PrintAndLogEx(INFO, " written in clear, in a sector this card's own key can rewrite"); + } + + const uint8_t *lot = proac_block(dump, dumplen, PROAC_LOT_SECTOR, PROAC_LOT_BLOCK); + if (lot && isprint(lot[0])) { + char text[MFBLOCK_SIZE + 1] = {0}; + str_append(text, sizeof(text), "%.*s", MFBLOCK_SIZE, (const char *)lot); + str_trim(text); + PrintAndLogEx(INFO, "Lot................ " _YELLOW_("%s"), text); + } + + PrintAndLogEx(INFO, "Payload............ sector %u and %u, 96 bytes, " _YELLOW_("not decoded"), + PROAC_BLOB_SECTOR_A, + PROAC_BLOB_SECTOR_B + ); + + const uint8_t sectors[2] = { PROAC_BLOB_SECTOR_A, PROAC_BLOB_SECTOR_B }; + + for (uint8_t s = 0; s < ARRAYLEN(sectors); s++) { + for (uint8_t b = 0; b < 3; b++) { + const uint8_t *p = proac_block(dump, dumplen, sectors[s], b); + if (p) { + PrintAndLogEx(INFO, " sector %2u blk %u.. %s", sectors[s], b, sprint_hex_inrow(p, MFBLOCK_SIZE)); + } + } + } + + PrintAndLogEx(INFO, "Tail............... sector %u, " _YELLOW_("not decoded"), PROAC_TAIL_SECTOR); + for (uint8_t b = 0; b < 3; b++) { + const uint8_t *p = proac_block(dump, dumplen, PROAC_TAIL_SECTOR, b); + if (p) { + PrintAndLogEx(INFO, " sector %2u blk %u.. %s", PROAC_TAIL_SECTOR, b, sprint_hex_inrow(p, MFBLOCK_SIZE)); + } + } + return PM3_SUCCESS; +} diff --git a/client/src/parsers/parseproac.h b/client/src/parsers/parseproac.h new file mode 100644 index 000000000..3bfe1132f --- /dev/null +++ b/client/src/parsers/parseproac.h @@ -0,0 +1,33 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// PROAC parser for MIFARE Classic dumps +//----------------------------------------------------------------------------- + +#ifndef PARSEPROAC_H__ +#define PARSEPROAC_H__ + +#include "common.h" + +// MAD application id, function cluster 0x49, the VIGIK cluster +#define PROAC_MAD_AID 0x4982 + +// True when the MAD claims a sector for the PROAC application +bool is_valid_proac_card(const uint8_t *dump, size_t dumplen); + +// Print what is known about the layout of a PROAC card +int proac_parser_parse(const uint8_t *dump, size_t dumplen); + +#endif diff --git a/client/src/parsers/parserkf.c b/client/src/parsers/parserkf.c new file mode 100644 index 000000000..e45e72450 --- /dev/null +++ b/client/src/parsers/parserkf.c @@ -0,0 +1,2034 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// RKF travel card parser for MIFARE Classic dumps +//----------------------------------------------------------------------------- + +#include "parserkf.h" + +#include // snprintf +#include + +#include "commonutil.h" // ARRAYLEN +#include "crc.h" // CRC8Mad +#include "ui.h" // PrintAndLogEx +#include "util.h" // sprint_hex_inrow +#include "mifare/mifaredefault.h" // MFBLOCK_SIZE +#include "mifare/mifare4.h" // mfFirstBlockOfSector + +#define RKF_SECTORS 16 +#define RKF_BLOCK_BITS 128 + +// The last byte of a block that carries no MAC authenticator is a checksum, so +// a data element group spanning blocks sees only 120 bits per block +#define RKF_USABLE_BITS 120 + +// Fixed positions of the travel card support layer +#define RKF_CMI_SECTOR 0 +#define RKF_CMI_BLOCK 0 +#define RKF_TCCI_BLOCK 1 +#define RKF_TCAS_BLOCK 2 +#define RKF_TCDI_SECTOR 1 + +// Directory AID values with a fixed meaning, RKF-0022 section 8.2 +#define RKF_AID_FREE 0x000 +#define RKF_AID_DEFECTIVE 0x001 +#define RKF_AID_RESERVED 0x002 +#define RKF_AID_TCAS2 0x005 +#define RKF_AID_TCDI 0x006 +#define RKF_AID_TCEL 0x00A +#define RKF_AID_TCPU 0x00B +#define RKF_AID_TCPU_DATA 0x00C + +// Directory PIX value marking a continuation sector, RKF-0022 section 8.3 +#define RKF_PIX_CONT 0x001 + +// Data element group identifiers, RKF-0022 section 8.1 +#define RKF_ID_TCEL_RECORD 0x84 +#define RKF_ID_TCPU_STATIC 0x85 +#define RKF_ID_TCTI_HEADER 0x86 +#define RKF_ID_TCCO_HEADER 0x87 +#define RKF_ID_DYN_MULTI 0x88 +#define RKF_ID_MANDATORY 0x89 +#define RKF_ID_DYN_SINGLE 0x8A +#define RKF_ID_MAC 0x93 +#define RKF_ID_PRICE 0x94 +#define RKF_ID_ISSUER 0x95 +#define RKF_ID_TCCO_PERIOD 0x96 +#define RKF_ID_VAL_DISTANCE 0x97 +#define RKF_ID_VAL_ROUTE 0x98 +#define RKF_ID_VAL_ZONE 0x99 +#define RKF_ID_TCCO_ISSUING 0x9A +#define RKF_ID_CUSTOMER 0x9B +#define RKF_ID_CLASS 0x9C +#define RKF_ID_TCTI_PERIOD 0x9D +#define RKF_ID_TCTI_ISSUING 0x9E +#define RKF_ID_VALIDATION 0x9F +#define RKF_ID_TCDB 0xA1 +#define RKF_ID_TCCP 0xA2 +#define RKF_ID_TCST 0xA3 + +// Days from 1970-01-01 to the DateCompact epoch of 1997-01-01 +#define RKF_DAYS_TO_1997 9862 +// Days from 1970-01-01 to the DateTime epoch of 2000-01-01 +#define RKF_DAYS_TO_2000 10957 + +#define RKF_LABEL "%-18s" + +//----------------------------------------------------------------------------- +// Bit access +// +// RKF-0022 section 7.4.1: the bits of byte 0 precede the bits of byte 1, and +// within a byte the least significant bit comes first. An unsigned number is +// read with its least significant bit first. +//----------------------------------------------------------------------------- + +static uint64_t rkf_bits(const uint8_t *buf, uint16_t off, uint8_t len) { + uint64_t v = 0; + for (uint8_t k = 0; k < len; k++) { + uint16_t b = off + k; + if ((buf[b >> 3] >> (b & 7)) & 1) { + v |= (uint64_t)1 << k; + } + } + return v; +} + +static void rkf_set_bits(uint8_t *buf, uint16_t off, uint8_t len, uint64_t v) { + for (uint8_t k = 0; k < len; k++) { + uint16_t b = off + k; + if ((v >> k) & 1) { + buf[b >> 3] |= (uint8_t)(1 << (b & 7)); + } else { + buf[b >> 3] &= (uint8_t)~(1 << (b & 7)); + } + } +} + +// Twos complement, the sign living in the last bit of the section +static int32_t rkf_signed(uint64_t v, uint8_t len) { + if (v & ((uint64_t)1 << (len - 1))) { + return (int32_t)(v - ((uint64_t)1 << len)); + } + return (int32_t)v; +} + +// A run of data blocks holding one or more application elements. Bit p of the +// run lives in data block p / 120 at bit p % 120, so the checksum byte of every +// block is stepped over, per RKF-0022 section 7.4.1. Sector trailers are not +// part of the run. +typedef struct { + const uint8_t *dump; + size_t dumplen; + uint8_t sector; + uint8_t nblocks; +} rkf_run_t; + +static const uint8_t *rkf_block(const uint8_t *dump, size_t dumplen, uint8_t sector, uint8_t block); +static uint8_t rkf_data_blocks(uint8_t sector); + +static const uint8_t *rkf_run_block(const rkf_run_t *run, uint8_t idx) { + uint8_t s = run->sector; + while (idx >= rkf_data_blocks(s)) { + idx -= rkf_data_blocks(s); + s++; + } + return rkf_block(run->dump, run->dumplen, s, idx); +} + +static uint64_t rkf_run_bits(const rkf_run_t *run, uint16_t off, uint8_t len) { + uint64_t v = 0; + for (uint8_t k = 0; k < len; k++) { + + uint16_t p = off + k; + uint8_t idx = (uint8_t)(p / RKF_USABLE_BITS); + if (idx >= run->nblocks) { + break; + } + + const uint8_t *blk = rkf_run_block(run, idx); + if (blk == NULL) { + break; + } + + uint16_t b = p % RKF_USABLE_BITS; + if ((blk[b >> 3] >> (b & 7)) & 1) { + v |= (uint64_t)1 << k; + } + } + return v; +} + +// Only used to build the self test card, which keeps its run inside one sector +static void rkf_run_set_bits(uint8_t *base, uint16_t off, uint8_t len, uint64_t v) { + for (uint8_t k = 0; k < len; k++) { + uint16_t p = off + k; + uint16_t blk = p / RKF_USABLE_BITS; + rkf_set_bits(base, (uint16_t)((p % RKF_USABLE_BITS) + (blk * RKF_BLOCK_BITS)), 1, (v >> k) & 1); + } +} + +//----------------------------------------------------------------------------- +// Value decoding +//----------------------------------------------------------------------------- + +static void rkf_civil_from_days(int32_t z, int *year, unsigned *month, unsigned *day) { + z += 719468; + int32_t era = ((z >= 0) ? z : (z - 146096)) / 146097; + uint32_t doe = (uint32_t)(z - (era * 146097)); + uint32_t yoe = (doe - (doe / 1460) + (doe / 36524) - (doe / 146096)) / 365; + int32_t y = (int32_t)yoe + (era * 400); + uint32_t doy = doe - ((365 * yoe) + (yoe / 4) - (yoe / 100)); + uint32_t mp = ((5 * doy) + 2) / 153; + *day = doy - (((153 * mp) + 2) / 5) + 1; + *month = (mp < 10) ? (mp + 3) : (mp - 9); + *year = y + ((*month <= 2) ? 1 : 0); +} + +// DateCompact, day 0 is 1 January 1997 +static void rkf_date_str(uint16_t v, char *out, size_t outlen) { + int y; + unsigned m, d; + rkf_civil_from_days((int32_t)v + RKF_DAYS_TO_1997, &y, &m, &d); + snprintf(out, outlen, "%04d-%02u-%02u", y, m, d); +} + +// TimeCompact, 'hhhhhmmmmmmsssss' with a 2 second resolution +static void rkf_time_str(uint16_t v, char *out, size_t outlen) { + uint8_t h = (v >> 11) & 0x1F; + uint8_t m = (v >> 5) & 0x3F; + uint8_t s = (v & 0x1F) * 2; + + if (h > 23 || m > 59) { + snprintf(out, outlen, "%04X invalid", v); + return; + } + snprintf(out, outlen, "%02u:%02u:%02u", h, m, s); +} + +// DateTime, minute 1 is 0:01 on 1 January 2000 +static void rkf_datetime_str(uint32_t v, char *out, size_t outlen) { + int y; + unsigned m, d; + rkf_civil_from_days((int32_t)(v / 1440) + RKF_DAYS_TO_2000, &y, &m, &d); + snprintf(out, outlen, "%04d-%02u-%02u %02u:%02u", y, m, d, (v % 1440) / 60, (v % 1440) % 60); +} + +// DateMonth11, month 1 is January 1900 +static void rkf_month11_str(uint16_t v, char *out, size_t outlen) { + if (v == 0) { + snprintf(out, outlen, "undefined"); + return; + } + snprintf(out, outlen, "%04u-%02u", 1900 + ((v - 1) / 12), ((v - 1) % 12) + 1); +} + +// DateMonth8, month 1 is January 2000 +static void rkf_month8_str(uint16_t v, char *out, size_t outlen) { + if (v == 0) { + snprintf(out, outlen, "undefined"); + return; + } + snprintf(out, outlen, "%04u-%02u", 2000 + ((v - 1) / 12), ((v - 1) % 12) + 1); +} + +static const char *rkf_currency_name(uint16_t code) { + switch (code) { + case 208: + return "DKK"; + case 246: + return "FIM"; + case 352: + return "ISK"; + case 578: + return "NOK"; + case 752: + return "SEK"; + case 826: + return "GBP"; + case 840: + return "USD"; + case 978: + return "EUR"; + default: + return NULL; + } +} + +// CurrencyUnit is BCD(4) coded 'xyyy', x the unit and yyy the ISO 4217 currency +static void rkf_currency_str(uint16_t cu, char *out, size_t outlen) { + uint8_t unit = (cu >> 12) & 0x0F; + uint16_t code = (((cu >> 8) & 0x0F) * 100) + (((cu >> 4) & 0x0F) * 10) + (cu & 0x0F); + const char *name = rkf_currency_name(code); + + const char *scale; + switch (unit) { + case 0: + scale = "main unit"; + break; + case 1: + scale = "1/10 of main unit"; + break; + case 2: + scale = "1/100 of main unit"; + break; + case 9: + scale = "1/2 of main unit"; + break; + default: + scale = "provider specific unit"; + break; + } + + if (name) { + snprintf(out, outlen, "%s, %s", name, scale); + } else { + snprintf(out, outlen, "currency %03u, %s", code, scale); + } +} + +// Money amounts are stored in the unit named by CardCurrencyUnit of TCCI +static void rkf_money_str(int32_t v, uint16_t cu, char *out, size_t outlen) { + uint8_t unit = (cu >> 12) & 0x0F; + uint16_t code = (((cu >> 8) & 0x0F) * 100) + (((cu >> 4) & 0x0F) * 10) + (cu & 0x0F); + const char *name = rkf_currency_name(code); + char cur[8]; + + if (name) { + snprintf(cur, sizeof(cur), "%s", name); + } else { + snprintf(cur, sizeof(cur), "%03u", code); + } + + const char *sign = (v < 0) ? "-" : ""; + uint32_t a = (uint32_t)((v < 0) ? -(int64_t)v : v); + + switch (unit) { + case 1: + snprintf(out, outlen, "%s%u.%01u %s", sign, a / 10, a % 10, cur); + break; + case 2: + snprintf(out, outlen, "%s%u.%02u %s", sign, a / 100, a % 100, cur); + break; + case 9: + snprintf(out, outlen, "%s%u.%s %s", sign, a / 2, (a % 2) ? "5" : "0", cur); + break; + default: + snprintf(out, outlen, "%s%u %s", sign, a, cur); + break; + } +} + +// Status values are chosen so the ASCII character is itself the signal +static const char *rkf_status_name(uint8_t s) { + switch (s) { + case 0x00: + return "undefined"; + case 0x01: + return "ok, enabled"; + case 0x21: + return "disabled, action pending"; + case 0x3F: + return "temporarily disabled"; + case 0x58: + return "not ok, disabled"; + default: + return "unknown"; + } +} + +static const char *rkf_sector_status_name(uint8_t s) { + switch (s) { + case 1: + return "AT1/AT5, 1st dynamic element current"; + case 2: + return "AT1/AT5, 2nd dynamic element current"; + case 3: + return "AT2"; + default: + return "undefined"; + } +} + +static const char *rkf_passenger_type_name(uint8_t t) { + switch (t) { + case 0: + return "unspecified"; + case 1: + return "adult"; + case 2: + return "child"; + case 3: + return "student"; + case 4: + return "old age pensioner"; + default: + return (t >= 32) ? "PTA specific" : "RFU"; + } +} + +static const char *rkf_passenger_class_name(uint8_t c) { + switch (c) { + case 1: + return "first class"; + case 2: + return "second class"; + case 3: + return "provider specific"; + default: + return "not specified"; + } +} + +static const char *rkf_validation_model_name(uint8_t m) { + switch (m) { + case 1: + return "ci/co"; + case 2: + return "ci-dest"; + case 3: + return "RFU"; + default: + return "undefined"; + } +} + +static const char *rkf_validation_status_name(uint8_t s) { + switch (s) { + case 1: + return "open, after check-in"; + case 2: + return "closed, after check-out"; + case 3: + return "RFU"; + default: + return "undefined"; + } +} + +static const char *rkf_supplement_status_name(uint8_t s) { + switch (s) { + case 1: + return "counting from origin"; + case 2: + return "accumulating distance"; + case 3: + return "counting and accumulating"; + default: + return "not counting"; + } +} + +static const char *rkf_mac_alg_name(uint8_t a) { + return (a == 0) ? "DES-MAC" : "RFU"; +} + +// AID owners, RKF-0019 2.00 edition B section 5 +static const struct { + uint16_t aid; + const char *name; +} rkf_aid_owners[] = { + {0x064, "Stockholms Lans Landsting"}, + {0x065, "SL - Storstockholms Lokaltrafik AB"}, + {0x066, "SL Flygbussar AB"}, + {0x067, "Waxholms Angfartygs AB"}, + {0x06E, "Lanstrafiken i Vasterbotten AB"}, + {0x06F, "Umea Lokaltrafik AB"}, + {0x078, "Lanstrafiken i Norrbotten AB"}, + {0x079, "Lulea Lokaltrafik AB"}, + {0x082, "Upplands Lokaltrafik AB"}, + {0x083, "Uppsalabuss AB"}, + {0x08C, "LTS - Lanstrafiken Sormland AB"}, + {0x096, "Ostgotatrafiken AB"}, + {0x097, "Norrkopings Kommun"}, + {0x0A0, "Jonkopings Lanstrafik AB"}, + {0x0AA, "Lanstrafiken Kronoberg"}, + {0x0B4, "Kalmar Lans Trafik AB"}, + {0x0BE, "Gotlands Kommun, Kollektivtrafiken"}, + {0x0BF, "Destination Gotland"}, + {0x0C8, "Blekingetrafiken"}, + {0x0DD, "Helsingborgs Kommun"}, + {0x0DE, "Lunds kommun"}, + {0x0E0, "Skanetrafiken"}, + {0x0E6, "Hallandstrafiken AB"}, + {0x0F0, "Vasttrafik"}, + {0x10E, "Varmlandstrafik AB"}, + {0x10F, "Karlstads kommun"}, + {0x118, "LTO - Lanstrafiken Orebro AB"}, + {0x122, "Vastmanlands Lokaltrafik AB"}, + {0x12C, "Dalatrafik, AB"}, + {0x136, "X-Trafik AB"}, + {0x137, "Gavle Kommun"}, + {0x140, "Vasternorrlands lans Trafik AB"}, + {0x14A, "Lanstrafiken i Jamtlands Lan AB"}, + {0x1F4, "SJ"}, + {0x1F5, "TIM - Trafik i Malardalen"}, + {0x3E9, "AS Oslo Sporveier"}, + {0x3EA, "Norges Statsbaner"}, + {0x3EB, "SL - Stor-Oslo Lokaltrafikk A.S."}, + {0x7D1, "HUR - Hovedstadens Udviklingsraad"}, + {0x7D2, "DSB"}, + {0x7D3, "OSS/Metro"}, + {0x7D4, "STS"}, + {0x7D5, "VT"}, +}; + +// The block an AID falls in when no owner is registered for it, RKF-0019 +static const char *rkf_aid_range(uint16_t aid) { + if (aid <= 0x063) { + return "system value"; + } + if (aid <= 0x1F3) { + return "Swedish PTA, county or municipal"; + } + if (aid <= 0x3E7) { + return "Swedish PTA, national or regional"; + } + if (aid <= 0x7CF) { + return "Norwegian PTA"; + } + if (aid <= 0xBB7) { + return "Danish PTA"; + } + return "reserved"; +} + +static const char *rkf_aid_name(uint16_t aid) { + switch (aid) { + case RKF_AID_FREE: + return "sector free"; + case RKF_AID_DEFECTIVE: + return "sector defective"; + case RKF_AID_RESERVED: + return "sector reserved"; + case RKF_AID_TCAS2: + return "TCAS (2), applications status"; + case RKF_AID_TCDI: + return "TCDI, directory"; + case RKF_AID_TCEL: + return "TCEL, event log"; + case RKF_AID_TCPU: + return "TCPU, purse"; + case RKF_AID_TCPU_DATA: + return "PTA area bound to the purse"; + default: + break; + } + + for (size_t i = 0; i < ARRAYLEN(rkf_aid_owners); i++) { + if (rkf_aid_owners[i].aid == aid) { + return rkf_aid_owners[i].name; + } + } + + if (aid >= 0x020 && aid <= 0x02F) { + return "test and validation"; + } + return rkf_aid_range(aid); +} + +// Event codes and the event data layout each one uses, RKF-0023 section 3.4.2 +typedef enum { + RKF_EVD_NONE = 0, + RKF_EVD_A, // pointer and price + RKF_EVD_B, // ticket pointer and contract pointer + RKF_EVD_C, // ticket pointer and PTA specific data + RKF_EVD_D, // money amount +} rkf_evdata_t; + +static const struct { + uint8_t code; + rkf_evdata_t kind; + const char *name; +} rkf_event_codes[] = { + {0x00, RKF_EVD_NONE, "undefined"}, + {0x01, RKF_EVD_A, "purchase of TCTI using TCPU"}, + {0x02, RKF_EVD_A, "purchase of TCCO using TCPU"}, + {0x03, RKF_EVD_A, "purchase of TCTI, other payment"}, + {0x04, RKF_EVD_A, "purchase of TCCO, other payment"}, + {0x05, RKF_EVD_B, "TCTI issued by a TCCO"}, + {0x06, RKF_EVD_C, "validation of TCTI / TCCO"}, + {0x07, RKF_EVD_C, "extension of TCTI / TCCO"}, + {0x08, RKF_EVD_D, "charge of the TCPU"}, + {0x09, RKF_EVD_C, "TCTI removed"}, + {0x0A, RKF_EVD_C, "TCCO removed"}, + {0x0B, RKF_EVD_C, "TCPU removed"}, + {0x0C, RKF_EVD_C, "TCST-ci/co removed"}, + {0x0D, RKF_EVD_C, "TCCP removed"}, + {0x0E, RKF_EVD_C, "TCDB removed"}, + {0x0F, RKF_EVD_C, "TCRE removed"}, + {0x16, RKF_EVD_A, "card initialised"}, + {0x17, RKF_EVD_C, "application object created"}, + {0x18, RKF_EVD_A, "application object repurchased"}, + {0x19, RKF_EVD_C, "TCCO activated"}, + {0x1A, RKF_EVD_A, "purchase of paper ticket using TCPU"}, + {0x1B, RKF_EVD_C, "check-in validation of TCST-ci/co"}, + {0x1C, RKF_EVD_C, "check-out validation of TCST-ci/co"}, + {0x1D, RKF_EVD_C, "control validation"}, + {0x1E, RKF_EVD_C, "supplement validation"}, + {0x1F, RKF_EVD_D, "charge of the TCPU using autoload"}, +}; + +static rkf_evdata_t rkf_event_kind(uint8_t code, const char **name) { + for (size_t i = 0; i < ARRAYLEN(rkf_event_codes); i++) { + if (rkf_event_codes[i].code == code) { + *name = rkf_event_codes[i].name; + return rkf_event_codes[i].kind; + } + } + *name = (code >= 0x30) ? "PTA specific" : "RFU"; + return RKF_EVD_NONE; +} + +//----------------------------------------------------------------------------- +// Block access +//----------------------------------------------------------------------------- + +static const uint8_t *rkf_block(const uint8_t *dump, size_t dumplen, uint8_t sector, uint8_t block) { + size_t off = (size_t)(mfFirstBlockOfSector(sector) + block) * MFBLOCK_SIZE; + if (off + MFBLOCK_SIZE > dumplen) { + return NULL; + } + return dump + off; +} + +// RKF-0022 section 7.7.1: every byte of a block feeds the checksum except the +// checksum byte itself. The "standard CRC-8" it names is CRC-8/MIFARE-MAD. +static bool rkf_checksum_ok(const uint8_t *blk) { + uint8_t d[MFBLOCK_SIZE - 1]; + memcpy(d, blk, sizeof(d)); + return ((uint8_t)CRC8Mad(d, sizeof(d)) == blk[MFBLOCK_SIZE - 1]); +} + +static const char *rkf_checksum_str(const uint8_t *blk) { + return rkf_checksum_ok(blk) ? _GREEN_("ok") : _RED_("fail"); +} + +static uint8_t rkf_sector_count(size_t dumplen) { + if (dumplen >= MIFARE_4K_MAX_BYTES) { + return 40; + } + if (dumplen >= MIFARE_2K_MAX_BYTES) { + return 32; + } + if (dumplen >= MIFARE_1K_MAX_BYTES) { + return RKF_SECTORS; + } + return (uint8_t)(dumplen / (4 * MFBLOCK_SIZE)); +} + +// Data blocks of a sector, the trailer excluded +static uint8_t rkf_data_blocks(uint8_t sector) { + return (uint8_t)(mfNumBlocksPerSector(sector) - 1); +} + +// The specification fixes TCAS (1) at S0:B2, but a card may carry the support +// layer elsewhere, so fall back to a scan for the identifier. +static bool rkf_find_tcas(const uint8_t *dump, size_t dumplen, uint8_t skip_sector, + uint8_t skip_block, uint8_t *sector, uint8_t *block) { + + uint8_t nsectors = rkf_sector_count(dumplen); + + for (uint8_t s = 0; s < nsectors; s++) { + for (uint8_t b = 0; b < rkf_data_blocks(s); b++) { + + if (s == skip_sector && b == skip_block) { + continue; + } + + const uint8_t *blk = rkf_block(dump, dumplen, s, b); + if (blk == NULL) { + continue; + } + + uint8_t version = (uint8_t)rkf_bits(blk, 8, 6); + if (blk[0] == RKF_TCAS_IDENTIFIER && version > 0 && version < 16) { + *sector = s; + *block = b; + return true; + } + } + } + return false; +} + +// RKF-0022 7.3.4 places the MAC authenticator in the last bits of the last +// block. On every card tested the algorithm and key identifiers sit immediately +// before it, so the final 24 bits of a MACed object are +// MACAlgorithmIdentifier(2) | MACKeyIdentifier(6) | MACAuthenticator16(16). +static void rkf_read_mac(const uint8_t *buf, uint16_t nbits, uint8_t *alg, uint8_t *key, uint16_t *mac) { + *alg = (uint8_t)rkf_bits(buf, nbits - 24, 2); + *key = (uint8_t)rkf_bits(buf, nbits - 22, 6); + *mac = (uint16_t)rkf_bits(buf, nbits - 16, 16); +} + +static void rkf_print_aid(const char *label, uint16_t aid) { + PrintAndLogEx(INFO, RKF_LABEL " " _YELLOW_("0x%03X") " ( %s )", label, aid, rkf_aid_name(aid)); +} + +static void rkf_print_mac(uint8_t alg, uint8_t key, uint16_t mac) { + + // DES-MAC is the only algorithm the specification defines, so anything else + // means these bits are not the MAC trio on this card + if (alg != 0) { + PrintAndLogEx(INFO, RKF_LABEL " %04X, algorithm %u ( " _YELLOW_("not a defined algorithm") " )", + "MAC", mac, alg); + PrintAndLogEx(INFO, RKF_LABEL " " _YELLOW_("the MAC trio is not at the expected offsets here"), ""); + return; + } + + PrintAndLogEx(INFO, RKF_LABEL " %04X, algorithm %u ( %s ), key id %u", + "MAC", mac, alg, rkf_mac_alg_name(alg), key); +} + +//----------------------------------------------------------------------------- +// Detection +//----------------------------------------------------------------------------- + +bool is_valid_rkf_card(const uint8_t *dump, size_t dumplen) { + + if (dump == NULL || dumplen < MIFARE_1K_MAX_BYTES) { + return false; + } + + // TCCI is always the second block of sector 0. Its MADInfoByte is 0 because + // the travel card does not use a MAD, and its CardProvider must be an AID + // that RKF-0019 has handed to a transport authority. + const uint8_t *tcci = rkf_block(dump, dumplen, RKF_CMI_SECTOR, RKF_TCCI_BLOCK); + if (tcci == NULL || tcci[0] != 0x00 || tcci[1] != 0x00) { + return false; + } + + uint8_t version = (uint8_t)rkf_bits(tcci, 16, 6); + uint16_t provider = (uint16_t)rkf_bits(tcci, 22, 12); + + if (version == 0 || provider < 0x064 || provider > 0x0BB7) { + return false; + } + + // and the card must carry an applications status block somewhere + uint8_t s, b; + return rkf_find_tcas(dump, dumplen, 0xFF, 0xFF, &s, &b); +} + +//----------------------------------------------------------------------------- +// Card issuer and travel card support layer +//----------------------------------------------------------------------------- + +static void rkf_print_cmi(const uint8_t *blk) { + + uint32_t csn = (uint32_t)rkf_bits(blk, 0, 32); + uint8_t chk = (uint8_t)rkf_bits(blk, 32, 8); + uint8_t calc = blk[0] ^ blk[1] ^ blk[2] ^ blk[3]; + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("CMI, card manufacturer information") " ---"); + PrintAndLogEx(INFO, RKF_LABEL " " _YELLOW_("%08X") " ( %s )", "Card serial no", csn, sprint_hex_inrow(blk, 4)); + PrintAndLogEx(INFO, RKF_LABEL " %02X ( %s )", "Check byte", chk, + (chk == calc) ? _GREEN_("ok") : _RED_("fail")); + PrintAndLogEx(INFO, RKF_LABEL " %s", "Manufacturer data", sprint_hex_inrow(blk + 5, 11)); +} + +typedef struct { + uint16_t mad_info; + uint8_t card_version; + uint16_t card_provider; + uint16_t validity_end; + uint8_t card_status; + uint16_t currency_unit; + uint8_t event_log_version; + uint8_t mac_alg; + uint8_t mac_key; + uint16_t mac; +} rkf_tcci_t; + +static void rkf_read_tcci(const uint8_t *blk, rkf_tcci_t *t) { + t->mad_info = (uint16_t)rkf_bits(blk, 0, 16); + t->card_version = (uint8_t)rkf_bits(blk, 16, 6); + t->card_provider = (uint16_t)rkf_bits(blk, 22, 12); + t->validity_end = (uint16_t)rkf_bits(blk, 34, 14); + t->card_status = (uint8_t)rkf_bits(blk, 48, 8); + t->currency_unit = (uint16_t)rkf_bits(blk, 56, 16); + t->event_log_version = (uint8_t)rkf_bits(blk, 72, 6); + rkf_read_mac(blk, RKF_BLOCK_BITS, &t->mac_alg, &t->mac_key, &t->mac); +} + +static void rkf_print_tcci(const rkf_tcci_t *t) { + + char buf[32]; + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("TCCI, card information") " ---"); + PrintAndLogEx(INFO, RKF_LABEL " %u ( %s )", "MAD info byte", t->mad_info, + (t->mad_info == 0) ? "MAD not available" : "unknown"); + PrintAndLogEx(INFO, RKF_LABEL " %u%s", "Card version", t->card_version, + (t->card_version == 2) ? "" : _YELLOW_(" ( RKF-0022/0023 describe version 2 )")); + rkf_print_aid("Card provider", t->card_provider); + + rkf_date_str(t->validity_end, buf, sizeof(buf)); + PrintAndLogEx(INFO, RKF_LABEL " " _YELLOW_("%s"), "Valid until", buf); + + PrintAndLogEx(INFO, RKF_LABEL " %02X ( %s )", "Card status", t->card_status, + rkf_status_name(t->card_status)); + + rkf_currency_str(t->currency_unit, buf, sizeof(buf)); + PrintAndLogEx(INFO, RKF_LABEL " %04X ( %s )", "Currency unit", t->currency_unit, buf); + + PrintAndLogEx(INFO, RKF_LABEL " %u", "Event log version", t->event_log_version); + rkf_print_mac(t->mac_alg, t->mac_key, t->mac); +} + +typedef struct { + uint8_t identifier; + uint8_t version; + uint8_t sector_status[RKF_SECTORS]; + uint8_t transaction_no; + uint8_t event_log_record; + uint8_t log_area; + uint8_t log_pointer[8]; + uint8_t mac_alg; + uint8_t mac_key; + uint16_t mac; +} rkf_tcas_t; + +static const char *rkf_log_slot(const rkf_tcas_t *t, uint8_t sector) { + static const char *slot[] = { + "current ticket", "previous ticket", "log ticket 1", "log ticket 2", + "log ticket 3", "log ticket 4", "log ticket 5", "log ticket 6" + }; + for (uint8_t i = 0; i < ARRAYLEN(slot); i++) { + if (t->log_pointer[i] == sector) { + return slot[i]; + } + } + return "not referenced by TCAS"; +} + +static void rkf_read_tcas(const uint8_t *blk, rkf_tcas_t *t) { + t->identifier = (uint8_t)rkf_bits(blk, 0, 8); + t->version = (uint8_t)rkf_bits(blk, 8, 6); + for (uint8_t s = 0; s < RKF_SECTORS; s++) { + t->sector_status[s] = (uint8_t)rkf_bits(blk, 14 + (2 * s), 2); + } + t->transaction_no = (uint8_t)rkf_bits(blk, 46, 8); + t->event_log_record = (uint8_t)rkf_bits(blk, 54, 4); + t->log_area = (uint8_t)rkf_bits(blk, 58, 4); + for (uint8_t i = 0; i < 8; i++) { + t->log_pointer[i] = (uint8_t)rkf_bits(blk, 62 + (4 * i), 4); + } + rkf_read_mac(blk, RKF_BLOCK_BITS, &t->mac_alg, &t->mac_key, &t->mac); +} + +static void rkf_print_tcas(const rkf_tcas_t *t, uint8_t instance, uint8_t sector, uint8_t block) { + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("TCAS (%u), applications status") " --- S%u:B%u", + instance, sector, block); + PrintAndLogEx(INFO, RKF_LABEL " %02X ( %s )", "Identifier", t->identifier, + (t->identifier == RKF_TCAS_IDENTIFIER) ? _GREEN_("ok") : _RED_("fail")); + PrintAndLogEx(INFO, RKF_LABEL " %u", "Version", t->version); + PrintAndLogEx(INFO, RKF_LABEL " %u", "Transaction no", t->transaction_no); + PrintAndLogEx(INFO, RKF_LABEL " %u", "Event log record", t->event_log_record); + + if (t->log_area == 0) { + PrintAndLogEx(INFO, RKF_LABEL " none", "Ticket/log area"); + } else { + PrintAndLogEx(INFO, RKF_LABEL " first sector %u", "Ticket/log area", t->log_area); + for (uint8_t i = 0; i < ARRAYLEN(t->log_pointer); i++) { + if (t->log_pointer[i] != 0) { + PrintAndLogEx(INFO, RKF_LABEL " sector %2u ( %s )", "", t->log_pointer[i], + rkf_log_slot(t, t->log_pointer[i])); + } + } + } + + rkf_print_mac(t->mac_alg, t->mac_key, t->mac); + + uint8_t defined = 0; + for (uint8_t s = 0; s < RKF_SECTORS; s++) { + if (t->sector_status[s] != 0) { + defined++; + } + } + + PrintAndLogEx(INFO, RKF_LABEL " %u of %u sectors defined", "Sector status", defined, RKF_SECTORS); + for (uint8_t s = 0; s < RKF_SECTORS; s++) { + if (t->sector_status[s] != 0) { + PrintAndLogEx(INFO, RKF_LABEL " sector %2u %u ( %s )", "", s, + t->sector_status[s], rkf_sector_status_name(t->sector_status[s])); + } + } +} + +// The directory covers sectors 1..15, five entries to a block +static void rkf_read_tcdi(const uint8_t *dump, size_t dumplen, uint16_t *aid, uint16_t *pix) { + + for (uint8_t s = 1; s < RKF_SECTORS; s++) { + aid[s] = RKF_AID_FREE; + pix[s] = 0; + } + + for (uint8_t b = 0; b < 3; b++) { + const uint8_t *blk = rkf_block(dump, dumplen, RKF_TCDI_SECTOR, b); + if (blk == NULL) { + continue; + } + for (uint8_t i = 0; i < 5; i++) { + uint8_t s = 1 + (5 * b) + i; + aid[s] = (uint16_t)rkf_bits(blk, 24 * i, 12); + pix[s] = (uint16_t)rkf_bits(blk, (24 * i) + 12, 12); + } + } +} + +static void rkf_print_tcdi(const uint8_t *dump, size_t dumplen, const uint16_t *aid, const uint16_t *pix) { + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("TCDI, directory") " ---"); + PrintAndLogEx(INFO, " sector | AID | PIX | interpretation"); + PrintAndLogEx(INFO, "--------+------+------+---------------------------------------------"); + + for (uint8_t s = 1; s < RKF_SECTORS; s++) { + + const char *what; + if (pix[s] == RKF_PIX_CONT && aid[s] > RKF_AID_RESERVED) { + what = "continuation of the preceding sector"; + } else { + what = rkf_aid_name(aid[s]); + } + + PrintAndLogEx(INFO, " %2u | %03X | %03X | %s", s, aid[s], pix[s], what); + } + + PrintAndLogEx(INFO, "--------+------+------+---------------------------------------------"); + + char line[96] = {0}; + for (uint8_t b = 0; b < 3; b++) { + const uint8_t *blk = rkf_block(dump, dumplen, RKF_TCDI_SECTOR, b); + if (blk) { + str_append(line, sizeof(line), "%02X ( %s ) ", blk[MFBLOCK_SIZE - 1], rkf_checksum_str(blk)); + } + } + PrintAndLogEx(INFO, RKF_LABEL " %s", "Checksums", line); +} + +//----------------------------------------------------------------------------- +// TCPU, purse +//----------------------------------------------------------------------------- + +static void rkf_print_tcpu(const uint8_t *dump, size_t dumplen, uint8_t sector, + uint8_t current, uint16_t cu) { + + char buf[40]; + + const uint8_t *st = rkf_block(dump, dumplen, sector, 0); + if (st == NULL) { + return; + } + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("TCPU, purse") " --- sector %u", sector); + + uint8_t version = (uint8_t)rkf_bits(st, 8, 6); + + PrintAndLogEx(INFO, RKF_LABEL " %02X, version %u", "Identifier", + (uint8_t)rkf_bits(st, 0, 8), version); + rkf_print_aid("Purse provider", (uint16_t)rkf_bits(st, 14, 12)); + PrintAndLogEx(INFO, RKF_LABEL " " _YELLOW_("%08X"), "Purse serial no", (uint32_t)rkf_bits(st, 26, 32)); + + rkf_date_str((uint16_t)rkf_bits(st, 58, 14), buf, sizeof(buf)); + PrintAndLogEx(INFO, RKF_LABEL " %s", "Start date", buf); + + uint8_t dp = (uint8_t)rkf_bits(st, 72, 4); + PrintAndLogEx(INFO, RKF_LABEL " %u ( %s )", "Data pointer", dp, + (dp == 0) ? "unused" : "PTA area sector"); + + rkf_money_str(rkf_signed(rkf_bits(st, 76, 24), 24), cu, buf, sizeof(buf)); + PrintAndLogEx(INFO, RKF_LABEL " %s", "Minimum value", buf); + + rkf_money_str(rkf_signed(rkf_bits(st, 100, 24), 24), cu, buf, sizeof(buf)); + PrintAndLogEx(INFO, RKF_LABEL " %s", "Autoload value", buf); + + for (uint8_t b = 1; b <= 2; b++) { + + const uint8_t *dy = rkf_block(dump, dumplen, sector, b); + if (dy == NULL) { + continue; + } + + bool live = (current == b); + PrintAndLogEx(INFO, " " _CYAN_("dynamic data (%u)") " %s", b, + live ? _GREEN_("<- current") : ""); + + PrintAndLogEx(INFO, RKF_LABEL " %u", " Transaction no", (uint16_t)rkf_bits(dy, 0, 16)); + + // version 4 drops EndDate and moves Value up against the transaction + // number; the rest of the block is not known + if (version == 4) { + + rkf_money_str(rkf_signed(rkf_bits(dy, 16, 24), 24), cu, buf, sizeof(buf)); + PrintAndLogEx(INFO, RKF_LABEL " " _YELLOW_("%s"), " Value", buf); + PrintAndLogEx(INFO, RKF_LABEL " %s " _YELLOW_("not decoded"), " Bits 40..103", + sprint_hex_inrow(dy + 5, 8)); + + uint8_t valg, vkey; + uint16_t vmac; + rkf_read_mac(dy, RKF_BLOCK_BITS, &valg, &vkey, &vmac); + PrintAndLogEx(INFO, RKF_LABEL " %04X, algorithm %u, key id %u", " MAC", vmac, valg, vkey); + continue; + } + + rkf_date_str((uint16_t)rkf_bits(dy, 16, 14), buf, sizeof(buf)); + PrintAndLogEx(INFO, RKF_LABEL " %s", " End date", buf); + + rkf_money_str(rkf_signed(rkf_bits(dy, 30, 24), 24), cu, buf, sizeof(buf)); + PrintAndLogEx(INFO, RKF_LABEL " " _YELLOW_("%s"), " Value", buf); + + uint8_t status = (uint8_t)rkf_bits(dy, 54, 8); + PrintAndLogEx(INFO, RKF_LABEL " %02X ( %s )", " Status", status, rkf_status_name(status)); + + rkf_money_str((int32_t)rkf_bits(dy, 62, 20), cu, buf, sizeof(buf)); + PrintAndLogEx(INFO, RKF_LABEL " %s", " Deposit", buf); + + uint8_t al = (uint8_t)rkf_bits(dy, 82, 2); + PrintAndLogEx(INFO, RKF_LABEL " %u ( %s )", " Autoload", al, + (al == 1) ? "enabled" : ((al == 0) ? "disabled" : "RFU")); + + PrintAndLogEx(INFO, RKF_LABEL " %04X, algorithm %u, key id %u", " MAC", + (uint16_t)rkf_bits(dy, 112, 16), + (uint8_t)rkf_bits(dy, 84, 2), + (uint8_t)rkf_bits(dy, 86, 6)); + } +} + +//----------------------------------------------------------------------------- +// TCEL, event log +//----------------------------------------------------------------------------- + +static void rkf_print_event_record(const uint8_t *blk, uint8_t record, bool newest, uint16_t cu) { + + char date[16], time[16], buf[40]; + + uint8_t id = (uint8_t)rkf_bits(blk, 0, 8); + uint8_t code = (uint8_t)rkf_bits(blk, 90, 6); + uint32_t data = (uint32_t)rkf_bits(blk, 96, 24); + + const char *name = NULL; + rkf_evdata_t kind = rkf_event_kind(code, &name); + + if (code == 0) { + PrintAndLogEx(INFO, " record %-2u " _YELLOW_("unused") " ( event code 00, checksum %02X %s )", + record, blk[MFBLOCK_SIZE - 1], rkf_checksum_ok(blk) ? "ok" : "not set"); + return; + } + (void)id; + + rkf_date_str((uint16_t)rkf_bits(blk, 8, 14), date, sizeof(date)); + rkf_time_str((uint16_t)rkf_bits(blk, 22, 16), time, sizeof(time)); + + PrintAndLogEx(INFO, " record %-2u %s %s %02X %s %s", record, date, time, code, name, + newest ? _GREEN_("<- most recent") : ""); + PrintAndLogEx(INFO, RKF_LABEL " AID 0x%03X ( %s ), device %04X, device txn %u", "", + (uint16_t)rkf_bits(blk, 38, 12), + rkf_aid_name((uint16_t)rkf_bits(blk, 38, 12)), + (uint16_t)rkf_bits(blk, 50, 16), + (uint32_t)rkf_bits(blk, 66, 24)); + + switch (kind) { + case RKF_EVD_A: + rkf_money_str((int32_t)((data >> 4) & 0xFFFFF), cu, buf, sizeof(buf)); + PrintAndLogEx(INFO, RKF_LABEL " sector %u, price %s", "", data & 0x0F, buf); + break; + case RKF_EVD_B: + PrintAndLogEx(INFO, RKF_LABEL " ticket sector %u, contract sector %u", "", + data & 0x0F, (data >> 4) & 0x0F); + break; + case RKF_EVD_C: + PrintAndLogEx(INFO, RKF_LABEL " ticket sector %u, PTA data %05X", "", + data & 0x0F, (data >> 4) & 0xFFFFF); + break; + case RKF_EVD_D: + rkf_money_str(rkf_signed(data, 24), cu, buf, sizeof(buf)); + PrintAndLogEx(INFO, RKF_LABEL " amount %s", "", buf); + break; + case RKF_EVD_NONE: + default: + PrintAndLogEx(INFO, RKF_LABEL " event data %06X", "", data); + break; + } + + PrintAndLogEx(INFO, RKF_LABEL " checksum %02X ( %s )", "", + blk[MFBLOCK_SIZE - 1], rkf_checksum_str(blk)); +} + +static void rkf_print_tcel(const uint8_t *dump, size_t dumplen, uint8_t sector, + uint8_t nsectors, uint8_t newest, uint16_t cu) { + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("TCEL, event log") " --- sector %u..%u", + sector, sector + nsectors - 1); + + for (uint8_t s = 0; s < nsectors; s++) { + for (uint8_t b = 0; b < 3; b++) { + const uint8_t *blk = rkf_block(dump, dumplen, sector + s, b); + if (blk) { + uint8_t record = (3 * s) + b; + rkf_print_event_record(blk, record, (record == newest), cu); + } + } + } +} + +//----------------------------------------------------------------------------- +// Fixed layout application objects +//----------------------------------------------------------------------------- + +static void rkf_print_subgroup(const uint8_t *buf, uint16_t off, uint8_t n) { + for (uint8_t i = 0; i < n; i++) { + uint8_t type = (uint8_t)rkf_bits(buf, off + (14 * i), 8); + uint8_t total = (uint8_t)rkf_bits(buf, off + (14 * i) + 8, 6); + if (total != 0) { + PrintAndLogEx(INFO, RKF_LABEL " %u x %s ( type %u )", "", total, + rkf_passenger_type_name(type), type); + } + } +} + +static void rkf_print_tcdb(const uint8_t *dump, size_t dumplen, uint8_t sector, uint8_t current) { + + char buf[32]; + + const uint8_t *st = rkf_block(dump, dumplen, sector, 0); + if (st == NULL) { + return; + } + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("TCDB, discount basis") " --- sector %u", sector); + PrintAndLogEx(INFO, RKF_LABEL " %02X, version %u", "Identifier", + (uint8_t)rkf_bits(st, 0, 8), (uint8_t)rkf_bits(st, 8, 6)); + rkf_print_aid("Provider", (uint16_t)rkf_bits(st, 14, 12)); + PrintAndLogEx(INFO, RKF_LABEL " %u, %u, %u", "Discount types", + (uint8_t)rkf_bits(st, 26, 8), + (uint8_t)rkf_bits(st, 34, 8), + (uint8_t)rkf_bits(st, 42, 8)); + + for (uint8_t b = 1; b <= 2; b++) { + + const uint8_t *dy = rkf_block(dump, dumplen, sector, b); + if (dy == NULL) { + continue; + } + + PrintAndLogEx(INFO, " " _CYAN_("dynamic data (%u)") " %s", b, + (current == b) ? _GREEN_("<- current") : ""); + + uint8_t status = (uint8_t)rkf_bits(dy, 0, 8); + PrintAndLogEx(INFO, RKF_LABEL " %02X ( %s )", " Status", status, rkf_status_name(status)); + + rkf_month8_str((uint8_t)rkf_bits(dy, 8, 8), buf, sizeof(buf)); + PrintAndLogEx(INFO, RKF_LABEL " %s", " First month", buf); + + for (uint8_t i = 0; i < 3; i++) { + uint16_t off = 16 + (29 * i); + PrintAndLogEx(INFO, RKF_LABEL " block %u counters %u / %u, levels %u %u %u", "", i + 1, + (uint8_t)rkf_bits(dy, off, 8), + (uint16_t)rkf_bits(dy, off + 8, 12), + (uint8_t)rkf_bits(dy, off + 20, 3), + (uint8_t)rkf_bits(dy, off + 23, 3), + (uint8_t)rkf_bits(dy, off + 26, 3)); + } + + uint8_t alg, key; + uint16_t mac; + rkf_read_mac(dy, RKF_BLOCK_BITS, &alg, &key, &mac); + PrintAndLogEx(INFO, RKF_LABEL " %04X, algorithm %u, key id %u", " MAC", mac, alg, key); + } +} + +static void rkf_print_tccp(const uint8_t *dump, size_t dumplen, uint8_t sector) { + + char buf[32]; + uint8_t d[2 * MFBLOCK_SIZE]; + + const uint8_t *b0 = rkf_block(dump, dumplen, sector, 0); + const uint8_t *b1 = rkf_block(dump, dumplen, sector, 1); + if (b0 == NULL || b1 == NULL) { + return; + } + memcpy(d, b0, MFBLOCK_SIZE); + memcpy(d + MFBLOCK_SIZE, b1, MFBLOCK_SIZE); + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("TCCP, customer profile") " --- sector %u", sector); + PrintAndLogEx(INFO, RKF_LABEL " %02X, version %u", "Identifier", + (uint8_t)rkf_bits(d, 0, 8), (uint8_t)rkf_bits(d, 8, 6)); + rkf_print_aid("Provider", (uint16_t)rkf_bits(d, 14, 12)); + + uint8_t status = (uint8_t)rkf_bits(d, 26, 8); + PrintAndLogEx(INFO, RKF_LABEL " %02X ( %s )", "Status", status, rkf_status_name(status)); + PrintAndLogEx(INFO, RKF_LABEL " " _YELLOW_("%010llu"), "Customer no", + (unsigned long long)rkf_bits(d, 34, 34)); + + uint8_t pclass = (uint8_t)rkf_bits(d, 68, 2); + PrintAndLogEx(INFO, RKF_LABEL " %u ( %s )", "Passenger class", pclass, + rkf_passenger_class_name(pclass)); + rkf_print_subgroup(d, 70, 3); + + PrintAndLogEx(INFO, RKF_LABEL " %u", "Validation level", (uint8_t)rkf_bits(d, 112, 2)); + + rkf_month11_str((uint16_t)rkf_bits(d, 114, 11), buf, sizeof(buf)); + PrintAndLogEx(INFO, RKF_LABEL " %s", "Birth month", buf); + + PrintAndLogEx(INFO, RKF_LABEL " %u", "Language", (uint8_t)rkf_bits(d, 125, 4)); + PrintAndLogEx(INFO, RKF_LABEL " %02X", "Dialogue prefs", (uint8_t)rkf_bits(d, 129, 8)); + rkf_print_aid("Subscr. company", (uint16_t)rkf_bits(d, 137, 12)); + PrintAndLogEx(INFO, RKF_LABEL " %u", "Subscr. type", (uint8_t)rkf_bits(d, 149, 8)); + uint8_t alg, key; + uint16_t mac; + rkf_read_mac(d, 2 * RKF_BLOCK_BITS, &alg, &key, &mac); + rkf_print_mac(alg, key, mac); +} + +static void rkf_print_tcst(const uint8_t *dump, size_t dumplen, uint8_t sector, + uint16_t cu, const char *role) { + + char buf[40]; + uint8_t d[3 * MFBLOCK_SIZE]; + + for (uint8_t b = 0; b < 3; b++) { + const uint8_t *p = rkf_block(dump, dumplen, sector, b); + if (p == NULL) { + return; + } + memcpy(d + (b * MFBLOCK_SIZE), p, MFBLOCK_SIZE); + } + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("TCST-ci/co, special ticket") " --- sector %u ( %s )", sector, role); + PrintAndLogEx(INFO, RKF_LABEL " %02X, version %u", "Identifier", + (uint8_t)rkf_bits(d, 0, 8), (uint8_t)rkf_bits(d, 8, 6)); + rkf_print_aid("Provider", (uint16_t)rkf_bits(d, 14, 12)); + PrintAndLogEx(INFO, RKF_LABEL " 0x%03X", "PIX", (uint16_t)rkf_bits(d, 26, 12)); + + uint8_t status = (uint8_t)rkf_bits(d, 38, 8); + PrintAndLogEx(INFO, RKF_LABEL " %02X ( %s )", "Status", status, rkf_status_name(status)); + + uint8_t pclass = (uint8_t)rkf_bits(d, 46, 2); + PrintAndLogEx(INFO, RKF_LABEL " %u ( %s )", "Passenger class", pclass, + rkf_passenger_class_name(pclass)); + rkf_print_subgroup(d, 48, 3); + + PrintAndLogEx(INFO, RKF_LABEL " %s, %s", "Validation", + rkf_validation_model_name((uint8_t)rkf_bits(d, 90, 2)), + rkf_validation_status_name((uint8_t)rkf_bits(d, 92, 2))); + PrintAndLogEx(INFO, RKF_LABEL " %u", "Validation level", (uint8_t)rkf_bits(d, 94, 2)); + + rkf_money_str((int32_t)rkf_bits(d, 96, 20), cu, buf, sizeof(buf)); + PrintAndLogEx(INFO, RKF_LABEL " " _YELLOW_("%s") ", modification level %u", "Price", + buf, (uint8_t)rkf_bits(d, 116, 6)); + + rkf_datetime_str((uint32_t)rkf_bits(d, 148, 24), buf, sizeof(buf)); + PrintAndLogEx(INFO, RKF_LABEL " AID 0x%03X place %u at %s", "Origin", + (uint16_t)rkf_bits(d, 122, 12), (uint16_t)rkf_bits(d, 134, 14), buf); + PrintAndLogEx(INFO, RKF_LABEL " AID 0x%03X place %u, +%u min", "Furthest", + (uint16_t)rkf_bits(d, 172, 12), (uint16_t)rkf_bits(d, 184, 14), + (uint16_t)rkf_bits(d, 198, 10)); + PrintAndLogEx(INFO, RKF_LABEL " AID 0x%03X place %u, +%u min", "Destination", + (uint16_t)rkf_bits(d, 208, 12), (uint16_t)rkf_bits(d, 220, 14), + (uint16_t)rkf_bits(d, 234, 10)); + + uint8_t sup = (uint8_t)rkf_bits(d, 244, 2); + PrintAndLogEx(INFO, RKF_LABEL " %u ( %s ), type %u, AID 0x%03X place %u, distance %u", "Supplement", + sup, rkf_supplement_status_name(sup), + (uint8_t)rkf_bits(d, 246, 6), + (uint16_t)rkf_bits(d, 252, 12), + (uint16_t)rkf_bits(d, 264, 14), + (uint16_t)rkf_bits(d, 278, 12)); + + PrintAndLogEx(INFO, RKF_LABEL " AID 0x%03X place %u, +%u min", "Latest control", + (uint16_t)rkf_bits(d, 290, 12), (uint16_t)rkf_bits(d, 302, 14), + (uint16_t)rkf_bits(d, 316, 10)); + + uint8_t alg, key; + uint16_t mac; + rkf_read_mac(d, 3 * RKF_BLOCK_BITS, &alg, &key, &mac); + rkf_print_mac(alg, key, mac); +} + +//----------------------------------------------------------------------------- +// TCTI / TCCO, a chain of identifier prefixed data element groups +//----------------------------------------------------------------------------- + +// Total size of each group in bits, identifier byte included, RKF-0023 3.4.3 +static uint8_t rkf_group_size(uint8_t id) { + switch (id) { + case RKF_ID_TCTI_HEADER: + case RKF_ID_TCCO_HEADER: + case RKF_ID_VALIDATION: + return 14; + case RKF_ID_DYN_MULTI: + return 20; + case RKF_ID_MANDATORY: + return 88; + case RKF_ID_DYN_SINGLE: + return 8; + case RKF_ID_MAC: + case RKF_ID_VAL_ROUTE: + return 32; + case RKF_ID_PRICE: + return 28; + case RKF_ID_ISSUER: + return 12; + case RKF_ID_TCCO_PERIOD: + return 114; + case RKF_ID_VAL_DISTANCE: + return 142; + case RKF_ID_VAL_ZONE: + return 34; + case RKF_ID_TCCO_ISSUING: + return 54; + case RKF_ID_CUSTOMER: + return 42; + case RKF_ID_CLASS: + return 52; + case RKF_ID_TCTI_PERIOD: + return 68; + case RKF_ID_TCTI_ISSUING: + return 38; + default: + return 0; + } +} + +static void rkf_print_group(const rkf_run_t *run, uint16_t off, uint8_t id, uint16_t cu) { + + char a[16], b[16], c[16], d[16]; + + switch (id) { + + case RKF_ID_TCTI_HEADER: + PrintAndLogEx(INFO, RKF_LABEL " version %u", " TCTI header", + (uint8_t)rkf_run_bits(run, off + 8, 6)); + break; + + case RKF_ID_TCCO_HEADER: + PrintAndLogEx(INFO, RKF_LABEL " version %u", " TCCO header", + (uint8_t)rkf_run_bits(run, off + 8, 6)); + break; + + case RKF_ID_DYN_MULTI: + PrintAndLogEx(INFO, RKF_LABEL " transaction no %u", " Dynamic info", + (uint16_t)rkf_run_bits(run, off + 8, 12)); + break; + + case RKF_ID_DYN_SINGLE: + PrintAndLogEx(INFO, RKF_LABEL " single block", " Dynamic info"); + break; + + case RKF_ID_MANDATORY: { + uint16_t aid = (uint16_t)rkf_run_bits(run, off + 8, 12); + uint8_t status = (uint8_t)rkf_run_bits(run, off + 80, 8); + PrintAndLogEx(INFO, RKF_LABEL " AID 0x%03X ( %s ), PIX 0x%03X", " Mandatory", + aid, rkf_aid_name(aid), (uint16_t)rkf_run_bits(run, off + 20, 12)); + PrintAndLogEx(INFO, RKF_LABEL " sale device %04X, serial " _YELLOW_("%08X") ", status %02X ( %s )", "", + (uint16_t)rkf_run_bits(run, off + 32, 16), + (uint32_t)rkf_run_bits(run, off + 48, 32), + status, rkf_status_name(status)); + break; + } + + case RKF_ID_MAC: { + // the authenticator is the last 16 bits of the block, past the checksum position + const uint8_t *last = rkf_run_block(run, (uint8_t)(off / RKF_USABLE_BITS)); + if (last == NULL) { + break; + } + uint8_t alg, key; + uint16_t mac; + rkf_read_mac(last, RKF_BLOCK_BITS, &alg, &key, &mac); + PrintAndLogEx(INFO, RKF_LABEL " %04X, algorithm %u ( %s ), key id %u", " MAC", + mac, alg, rkf_mac_alg_name(alg), key); + break; + } + + case RKF_ID_PRICE: + rkf_money_str((int32_t)rkf_run_bits(run, off + 8, 20), cu, a, sizeof(a)); + PrintAndLogEx(INFO, RKF_LABEL " " _YELLOW_("%s"), " Price", a); + break; + + case RKF_ID_ISSUER: + PrintAndLogEx(INFO, RKF_LABEL " sector %u", " Issued by", + (uint8_t)rkf_run_bits(run, off + 8, 4)); + break; + + case RKF_ID_TCCO_PERIOD: + rkf_date_str((uint16_t)rkf_run_bits(run, off + 8, 14), a, sizeof(a)); + rkf_time_str((uint16_t)rkf_run_bits(run, off + 22, 16), b, sizeof(b)); + rkf_date_str((uint16_t)rkf_run_bits(run, off + 38, 14), c, sizeof(c)); + rkf_time_str((uint16_t)rkf_run_bits(run, off + 52, 16), d, sizeof(d)); + PrintAndLogEx(INFO, RKF_LABEL " " _YELLOW_("%s %s") " .. " _YELLOW_("%s %s"), + " TCCO validity", a, b, c, d); + rkf_date_str((uint16_t)rkf_run_bits(run, off + 76, 14), a, sizeof(a)); + PrintAndLogEx(INFO, RKF_LABEL " duration %u, first use by %s, %u journeys", "", + (uint8_t)rkf_run_bits(run, off + 68, 8), a, + (uint8_t)rkf_run_bits(run, off + 90, 8)); + PrintAndLogEx(INFO, RKF_LABEL " not valid on days %02X, time codes %02X", "", + (uint8_t)rkf_run_bits(run, off + 98, 8), + (uint8_t)rkf_run_bits(run, off + 106, 8)); + break; + + case RKF_ID_TCTI_PERIOD: + rkf_date_str((uint16_t)rkf_run_bits(run, off + 8, 14), a, sizeof(a)); + rkf_time_str((uint16_t)rkf_run_bits(run, off + 22, 16), b, sizeof(b)); + rkf_date_str((uint16_t)rkf_run_bits(run, off + 38, 14), c, sizeof(c)); + rkf_time_str((uint16_t)rkf_run_bits(run, off + 52, 16), d, sizeof(d)); + PrintAndLogEx(INFO, RKF_LABEL " " _YELLOW_("%s %s") " .. " _YELLOW_("%s %s"), + " TCTI validity", a, b, c, d); + break; + + case RKF_ID_VAL_DISTANCE: + PrintAndLogEx(INFO, RKF_LABEL " AID 0x%03X place %u -> AID 0x%03X place %u", " Distance", + (uint16_t)rkf_run_bits(run, off + 8, 12), + (uint16_t)rkf_run_bits(run, off + 20, 14), + (uint16_t)rkf_run_bits(run, off + 34, 12), + (uint16_t)rkf_run_bits(run, off + 46, 14)); + PrintAndLogEx(INFO, RKF_LABEL " distance %u, run %u, interchanges %u", "", + (uint16_t)rkf_run_bits(run, off + 60, 12), + (uint16_t)rkf_run_bits(run, off + 72, 12), + (uint8_t)rkf_run_bits(run, off + 136, 6)); + PrintAndLogEx(INFO, RKF_LABEL " via AID 0x%03X place %u, AID 0x%03X place %u", "", + (uint16_t)rkf_run_bits(run, off + 84, 12), + (uint16_t)rkf_run_bits(run, off + 96, 14), + (uint16_t)rkf_run_bits(run, off + 110, 12), + (uint16_t)rkf_run_bits(run, off + 122, 14)); + break; + + case RKF_ID_VAL_ROUTE: + PrintAndLogEx(INFO, RKF_LABEL " AID 0x%03X route %u", " Route", + (uint16_t)rkf_run_bits(run, off + 8, 12), + (uint16_t)rkf_run_bits(run, off + 20, 12)); + break; + + case RKF_ID_VAL_ZONE: + PrintAndLogEx(INFO, RKF_LABEL " AID 0x%03X zone %u", " Zone", + (uint16_t)rkf_run_bits(run, off + 8, 12), + (uint16_t)rkf_run_bits(run, off + 20, 14)); + break; + + case RKF_ID_TCCO_ISSUING: + rkf_date_str((uint16_t)rkf_run_bits(run, off + 24, 14), a, sizeof(a)); + rkf_time_str((uint16_t)rkf_run_bits(run, off + 38, 16), b, sizeof(b)); + PrintAndLogEx(INFO, RKF_LABEL " %u journeys issued, %u in period, last %s %s", " TCCO issuing", + (uint8_t)rkf_run_bits(run, off + 8, 8), + (uint8_t)rkf_run_bits(run, off + 16, 8), a, b); + break; + + case RKF_ID_TCTI_ISSUING: + rkf_date_str((uint16_t)rkf_run_bits(run, off + 8, 14), a, sizeof(a)); + rkf_time_str((uint16_t)rkf_run_bits(run, off + 22, 16), b, sizeof(b)); + PrintAndLogEx(INFO, RKF_LABEL " last validation %s %s", " TCTI issuing", a, b); + break; + + case RKF_ID_CUSTOMER: + PrintAndLogEx(INFO, RKF_LABEL " " _YELLOW_("%010llu"), " Customer no", + (unsigned long long)rkf_run_bits(run, off + 8, 34)); + break; + + case RKF_ID_CLASS: { + uint8_t pclass = (uint8_t)rkf_run_bits(run, off + 8, 2); + PrintAndLogEx(INFO, RKF_LABEL " %s", " Class", rkf_passenger_class_name(pclass)); + for (uint8_t i = 0; i < 3; i++) { + uint8_t type = (uint8_t)rkf_run_bits(run, off + 10 + (14 * i), 8); + uint8_t total = (uint8_t)rkf_run_bits(run, off + 18 + (14 * i), 6); + if (total != 0) { + PrintAndLogEx(INFO, RKF_LABEL " %u x %s ( type %u )", "", total, + rkf_passenger_type_name(type), type); + } + } + break; + } + + case RKF_ID_VALIDATION: + PrintAndLogEx(INFO, RKF_LABEL " %s, %s, level %u", " Validation", + rkf_validation_model_name((uint8_t)rkf_run_bits(run, off + 8, 2)), + rkf_validation_status_name((uint8_t)rkf_run_bits(run, off + 10, 2)), + (uint8_t)rkf_run_bits(run, off + 12, 2)); + break; + + default: + break; + } +} + +// Walk the identifier chain over a run of sectors. An element ends at the MAC +// group, which the specification pins to the last block of the element, so the +// next element starts at the following block boundary. +static bool rkf_block_is_blank(const uint8_t *blk) { + for (uint8_t i = 0; i < MFBLOCK_SIZE; i++) { + if (blk[i] != 0x00 && blk[i] != 0xFF) { + return false; + } + } + return true; +} + +static void rkf_print_chain(const uint8_t *dump, size_t dumplen, uint8_t sector, + uint8_t nsectors, uint16_t aid, uint16_t pix, uint16_t cu) { + + if (rkf_block(dump, dumplen, sector, 0) == NULL) { + return; + } + + uint8_t total = 0; + for (uint8_t k = 0; k < nsectors; k++) { + total += rkf_data_blocks(sector + k); + } + + rkf_run_t run = { .dump = dump, .dumplen = dumplen, .sector = sector, .nblocks = total }; + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("application object") " --- sector %u..%u, AID 0x%03X ( %s ), PIX 0x%03X", + sector, sector + nsectors - 1, aid, rkf_aid_name(aid), pix); + + uint16_t off = 0; + uint8_t element = 1; + bool started = false; + + while (off < (uint16_t)run.nblocks * RKF_USABLE_BITS) { + + uint8_t id = (uint8_t)rkf_run_bits(&run, off, 8); + uint8_t size = rkf_group_size(id); + + if (size == 0 || (off + size) > ((uint16_t)run.nblocks * RKF_USABLE_BITS)) { + // not a group, resume at the next block boundary + uint16_t blk = off / RKF_USABLE_BITS; + if (off % RKF_USABLE_BITS == 0) { + const uint8_t *raw = rkf_run_block(&run, (uint8_t)blk); + if (raw != NULL && rkf_block_is_blank(raw) == false) { + PrintAndLogEx(INFO, " block %u " _YELLOW_("not decoded") " %s checksum ( %s )", blk, + sprint_hex_inrow(raw, MFBLOCK_SIZE), rkf_checksum_str(raw)); + } + } + blk++; + if (blk >= run.nblocks) { + break; + } + off = blk * RKF_USABLE_BITS; + started = false; + continue; + } + + if (started == false) { + PrintAndLogEx(INFO, " " _CYAN_("element %u") " from block %u", element, off / RKF_USABLE_BITS); + element++; + started = true; + } + + rkf_print_group(&run, off, id, cu); + + if (id == RKF_ID_MAC) { + uint16_t blk = (off / RKF_USABLE_BITS) + 1; + if (blk >= run.nblocks) { + break; + } + off = blk * RKF_USABLE_BITS; + started = false; + continue; + } + + off += size; + } +} + +//----------------------------------------------------------------------------- +// Top level +//----------------------------------------------------------------------------- + +static void rkf_print_application(const uint8_t *dump, size_t dumplen, uint8_t sector, + uint8_t nsectors, uint16_t aid, uint16_t pix, + const rkf_tcas_t *tcas, uint16_t cu) { + + const uint8_t *first = rkf_block(dump, dumplen, sector, 0); + uint8_t id = (first != NULL) ? first[0] : 0; + uint8_t status = (sector < RKF_SECTORS) ? tcas->sector_status[sector] : 0; + + switch (id) { + case RKF_ID_TCPU_STATIC: + rkf_print_tcpu(dump, dumplen, sector, status, cu); + break; + case RKF_ID_TCDB: + rkf_print_tcdb(dump, dumplen, sector, status); + break; + case RKF_ID_TCCP: + rkf_print_tccp(dump, dumplen, sector); + break; + case RKF_ID_TCST: + for (uint8_t k = 0; k < nsectors; k++) { + rkf_print_tcst(dump, dumplen, sector + k, cu, rkf_log_slot(tcas, sector + k)); + } + break; + case RKF_ID_TCEL_RECORD: + rkf_print_tcel(dump, dumplen, sector, nsectors, tcas->event_log_record, cu); + break; + default: + rkf_print_chain(dump, dumplen, sector, nsectors, aid, pix, cu); + break; + } +} + +// A card is free to leave the directory empty, so when it names no application +// object, fall back to the identifiers of RKF-0022 section 8.1. +static uint8_t rkf_scan_applications(const uint8_t *dump, size_t dumplen, + const rkf_tcas_t *tcas, uint16_t cu, + uint8_t tcas_sector) { + + uint8_t nsectors = rkf_sector_count(dumplen); + uint8_t found = 0; + + for (uint8_t s = RKF_TCDI_SECTOR + 1; s < nsectors; s++) { + + if (s == tcas_sector) { + continue; + } + + const uint8_t *blk = rkf_block(dump, dumplen, s, 0); + if (blk == NULL) { + continue; + } + + uint8_t id = blk[0]; + if (id != RKF_ID_TCPU_STATIC && id != RKF_ID_TCDB && id != RKF_ID_TCCP && + id != RKF_ID_TCST && id != RKF_ID_TCEL_RECORD && + id != RKF_ID_TCTI_HEADER && id != RKF_ID_TCCO_HEADER) { + continue; + } + + // an object runs on while the following sectors open with the same id + uint8_t n = 1; + while ((s + n) < nsectors && (s + n) != tcas_sector) { + const uint8_t *nxt = rkf_block(dump, dumplen, s + n, 0); + if (nxt == NULL || nxt[0] != id) { + break; + } + n++; + } + + rkf_print_application(dump, dumplen, s, n, 0, 0, tcas, cu); + found++; + s += (n - 1); + } + return found; +} + +int rkf_parser_parse(const uint8_t *dump, size_t dumplen) { + + if (is_valid_rkf_card(dump, dumplen) == false) { + return PM3_EINVARG; + } + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("RKF travel card") " ------------------------"); + PrintAndLogEx(INFO, "Resekortsforeningen i Norden, type CL-1"); + + const uint8_t *cmi = rkf_block(dump, dumplen, RKF_CMI_SECTOR, RKF_CMI_BLOCK); + if (cmi) { + rkf_print_cmi(cmi); + } + + rkf_tcci_t tcci = {0}; + const uint8_t *p = rkf_block(dump, dumplen, RKF_CMI_SECTOR, RKF_TCCI_BLOCK); + if (p) { + rkf_read_tcci(p, &tcci); + rkf_print_tcci(&tcci); + } + + uint16_t aid[RKF_SECTORS] = {0}; + uint16_t pix[RKF_SECTORS] = {0}; + rkf_read_tcdi(dump, dumplen, aid, pix); + + rkf_tcas_t tcas1 = {0}; + rkf_tcas_t tcas2 = {0}; + bool have_tcas2 = false; + + // The specification fixes TCAS (1) at S0:B2 and puts TCAS (2) in the first + // block of the sector the directory marks with AID 05 H, but a card is free + // to carry the support layer elsewhere, so both are located by scan. + uint8_t s1 = 0, b1 = 0; + if (rkf_find_tcas(dump, dumplen, 0xFF, 0xFF, &s1, &b1)) { + p = rkf_block(dump, dumplen, s1, b1); + rkf_read_tcas(p, &tcas1); + rkf_print_tcas(&tcas1, 1, s1, b1); + + uint8_t s2 = 0, b2 = 0; + if (rkf_find_tcas(dump, dumplen, s1, b1, &s2, &b2)) { + p = rkf_block(dump, dumplen, s2, b2); + rkf_read_tcas(p, &tcas2); + rkf_print_tcas(&tcas2, 2, s2, b2); + have_tcas2 = true; + } + } + + if (have_tcas2) { + bool same = (memcmp(&tcas1, &tcas2, sizeof(rkf_tcas_t)) == 0); + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, RKF_LABEL " %s", "TCAS instances", + same ? _GREEN_("identical") + : _YELLOW_("differ")); + if (same == false) { + PrintAndLogEx(INFO, RKF_LABEL " RKF-0022 4.3.4.2 reads a difference as an interrupted write,", ""); + PrintAndLogEx(INFO, RKF_LABEL " and takes the first consistent instance", ""); + } + } + + rkf_print_tcdi(dump, dumplen, aid, pix); + + uint8_t decoded = 0; + + // Walk the directory. A sector with PIX 01 H continues the preceding + // application object, RKF-0022 section 7.5 rule 10. + for (uint8_t s = 1; s < RKF_SECTORS; s++) { + + if (aid[s] <= RKF_AID_RESERVED || aid[s] == RKF_AID_TCDI || aid[s] == RKF_AID_TCAS2) { + continue; + } + if (pix[s] == RKF_PIX_CONT) { + continue; + } + + uint8_t n = 1; + while ((s + n) < RKF_SECTORS && aid[s + n] == aid[s] && pix[s + n] == RKF_PIX_CONT) { + n++; + } + + decoded++; + + switch (aid[s]) { + case RKF_AID_TCEL: + rkf_print_tcel(dump, dumplen, s, n, tcas1.event_log_record, tcci.currency_unit); + break; + + case RKF_AID_TCPU: + rkf_print_tcpu(dump, dumplen, s, tcas1.sector_status[s], tcci.currency_unit); + break; + + case RKF_AID_TCPU_DATA: + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("PTA area bound to the purse") " --- sector %u, " + _YELLOW_("PTA specific"), s); + for (uint8_t b = 0; b < 3; b++) { + const uint8_t *blk = rkf_block(dump, dumplen, s, b); + if (blk) { + PrintAndLogEx(INFO, " block %u %s", b, sprint_hex_inrow(blk, MFBLOCK_SIZE)); + } + } + break; + + default: + rkf_print_application(dump, dumplen, s, n, aid[s], pix[s], &tcas1, tcci.currency_unit); + break; + } + + s += (n - 1); + } + + if (tcci.card_version != 2) { + PrintAndLogEx(INFO, ""); + PrintAndLogEx(WARNING, "Card reports version %u. The application layouts below are the", + tcci.card_version); + PrintAndLogEx(WARNING, "version 2 layouts of RKF-0023, so field positions may not hold."); + } + + if (decoded == 0) { + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "Directory names no application object, scanning for identifiers"); + decoded = rkf_scan_applications(dump, dumplen, &tcas1, tcci.currency_unit, s1); + if (decoded == 0) { + PrintAndLogEx(INFO, "none found"); + } + } + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "MAC values are not checked. RKF-0019 holds the MAC key in its edition A,"); + PrintAndLogEx(INFO, "which was only distributed to transport authorities and their suppliers"); + return PM3_SUCCESS; +} + +//----------------------------------------------------------------------------- +// Self test +//----------------------------------------------------------------------------- + +#define RKF_T_CSN 0x11223344 +#define RKF_T_PROVIDER 0x0E0 +#define RKF_T_VALID_END 10956 // 2026-12-31 +#define RKF_T_CURRENCY 0x0752 // SEK, main unit +#define RKF_T_TXN 0x5A +#define RKF_T_PURSE_SERIAL 0xDEADBEEF +#define RKF_T_PURSE_VALUE (-12345) +#define RKF_T_DEPOSIT 6000 +#define RKF_T_CUSTOMER 1234567890ULL +#define RKF_T_TICKET_SERIAL 0xCAFEBABE + +#define RKF_T_SEC_PURSE 2 +#define RKF_T_SEC_TCEL 3 +#define RKF_T_SEC_TCAS2 5 +#define RKF_T_SEC_TICKET 6 + +static uint8_t *rkf_test_block(uint8_t *dump, uint8_t sector, uint8_t block) { + return dump + ((size_t)(mfFirstBlockOfSector(sector) + block) * MFBLOCK_SIZE); +} + +static void rkf_set_checksum(uint8_t *blk) { + uint8_t d[MFBLOCK_SIZE - 1]; + memcpy(d, blk, sizeof(d)); + blk[MFBLOCK_SIZE - 1] = (uint8_t)CRC8Mad(d, sizeof(d)); +} + +static void rkf_set_dir(uint8_t *dump, uint8_t sector, uint16_t aid, uint16_t pix) { + uint8_t b = (sector - 1) / 5; + uint8_t i = (sector - 1) % 5; + uint8_t *blk = rkf_test_block(dump, RKF_TCDI_SECTOR, b); + rkf_set_bits(blk, 24 * i, 12, aid); + rkf_set_bits(blk, (24 * i) + 12, 12, pix); +} + +static void rkf_build_selftest_card(uint8_t *dump) { + + memset(dump, 0, MIFARE_1K_MAX_BYTES); + + // CMI, the manufacturer block, check byte over the serial + uint8_t *blk = rkf_test_block(dump, 0, RKF_CMI_BLOCK); + rkf_set_bits(blk, 0, 32, RKF_T_CSN); + rkf_set_bits(blk, 32, 8, blk[0] ^ blk[1] ^ blk[2] ^ blk[3]); + memset(blk + 5, 0xA5, 11); + + // TCCI + blk = rkf_test_block(dump, 0, RKF_TCCI_BLOCK); + rkf_set_bits(blk, 0, 16, 0); + rkf_set_bits(blk, 16, 6, 2); + rkf_set_bits(blk, 22, 12, RKF_T_PROVIDER); + rkf_set_bits(blk, 34, 14, RKF_T_VALID_END); + rkf_set_bits(blk, 48, 8, 0x01); + rkf_set_bits(blk, 56, 16, RKF_T_CURRENCY); + rkf_set_bits(blk, 72, 6, 1); + rkf_set_bits(blk, 78, 2, 0); + rkf_set_bits(blk, 80, 6, 3); + rkf_set_bits(blk, 112, 16, 0x1234); + + // TCDI + rkf_set_dir(dump, 1, RKF_AID_TCDI, 0x000); + rkf_set_dir(dump, RKF_T_SEC_PURSE, RKF_AID_TCPU, 0x000); + rkf_set_dir(dump, RKF_T_SEC_TCEL, RKF_AID_TCEL, 0x000); + rkf_set_dir(dump, RKF_T_SEC_TCEL + 1, RKF_AID_TCEL, RKF_PIX_CONT); + rkf_set_dir(dump, RKF_T_SEC_TCAS2, RKF_AID_TCAS2, 0x000); + rkf_set_dir(dump, RKF_T_SEC_TICKET, RKF_T_PROVIDER, 0x064); + rkf_set_dir(dump, RKF_T_SEC_TICKET + 1, RKF_T_PROVIDER, RKF_PIX_CONT); + + for (uint8_t b = 0; b < 3; b++) { + rkf_set_checksum(rkf_test_block(dump, RKF_TCDI_SECTOR, b)); + } + + // TCAS, both instances identical + uint8_t tcas[MFBLOCK_SIZE] = {0}; + rkf_set_bits(tcas, 0, 8, RKF_TCAS_IDENTIFIER); + rkf_set_bits(tcas, 8, 6, 2); + rkf_set_bits(tcas, 14 + (2 * RKF_T_SEC_PURSE), 2, 2); + rkf_set_bits(tcas, 14 + (2 * RKF_T_SEC_TICKET), 2, 1); + rkf_set_bits(tcas, 46, 8, RKF_T_TXN); + rkf_set_bits(tcas, 54, 4, 4); + rkf_set_bits(tcas, 58, 4, 0); + rkf_set_bits(tcas, 94, 2, 0); + rkf_set_bits(tcas, 96, 6, 3); + rkf_set_bits(tcas, 112, 16, 0xBEEF); + memcpy(rkf_test_block(dump, 0, RKF_TCAS_BLOCK), tcas, MFBLOCK_SIZE); + memcpy(rkf_test_block(dump, RKF_T_SEC_TCAS2, 0), tcas, MFBLOCK_SIZE); + + // TCPU static and both dynamic blocks + blk = rkf_test_block(dump, RKF_T_SEC_PURSE, 0); + rkf_set_bits(blk, 0, 8, RKF_ID_TCPU_STATIC); + rkf_set_bits(blk, 8, 6, 2); + rkf_set_bits(blk, 14, 12, RKF_T_PROVIDER); + rkf_set_bits(blk, 26, 32, RKF_T_PURSE_SERIAL); + rkf_set_bits(blk, 58, 14, 8000); + rkf_set_bits(blk, 72, 4, 0); + rkf_set_bits(blk, 76, 24, 1000); + rkf_set_bits(blk, 100, 24, 20000); + + for (uint8_t b = 1; b <= 2; b++) { + blk = rkf_test_block(dump, RKF_T_SEC_PURSE, b); + rkf_set_bits(blk, 0, 16, 0x0100 + b); + rkf_set_bits(blk, 16, 14, RKF_T_VALID_END); + rkf_set_bits(blk, 30, 24, (uint32_t)(RKF_T_PURSE_VALUE) & 0xFFFFFF); + rkf_set_bits(blk, 54, 8, 0x01); + rkf_set_bits(blk, 62, 20, RKF_T_DEPOSIT); + rkf_set_bits(blk, 82, 2, 1); + rkf_set_bits(blk, 112, 16, 0xABCD); + } + + // TCEL, one charge record in slot 4 + blk = rkf_test_block(dump, RKF_T_SEC_TCEL + 1, 1); + rkf_set_bits(blk, 0, 8, RKF_ID_TCEL_RECORD); + rkf_set_bits(blk, 8, 14, 10000); + rkf_set_bits(blk, 22, 16, (13u << 11) | (45u << 5) | 15u); + rkf_set_bits(blk, 38, 12, RKF_T_PROVIDER); + rkf_set_bits(blk, 50, 16, 0x0042); + rkf_set_bits(blk, 66, 24, 987654); + rkf_set_bits(blk, 90, 6, 0x08); + rkf_set_bits(blk, 96, 24, 5000); + rkf_set_checksum(blk); + + // A ticket. The static element spans blocks 0 and 1 because its customer + // number crosses the checksum byte of block 0; the dynamic element then has + // to start at the next block boundary and is closed by the MAC group. + blk = rkf_test_block(dump, RKF_T_SEC_TICKET, 0); + rkf_run_set_bits(blk, 0, 8, RKF_ID_TCTI_HEADER); + rkf_run_set_bits(blk, 8, 6, 2); + rkf_run_set_bits(blk, 14, 8, RKF_ID_MANDATORY); + rkf_run_set_bits(blk, 22, 12, RKF_T_PROVIDER); + rkf_run_set_bits(blk, 34, 12, 0x064); + rkf_run_set_bits(blk, 46, 16, 0x0042); + rkf_run_set_bits(blk, 62, 32, RKF_T_TICKET_SERIAL); + rkf_run_set_bits(blk, 94, 8, 0x01); + rkf_run_set_bits(blk, 102, 8, RKF_ID_CUSTOMER); + rkf_run_set_bits(blk, 110, 34, RKF_T_CUSTOMER); + + rkf_run_set_bits(blk, 240, 8, RKF_ID_DYN_SINGLE); + rkf_run_set_bits(blk, 248, 8, RKF_ID_TCTI_PERIOD); + rkf_run_set_bits(blk, 256, 14, 10000); + rkf_run_set_bits(blk, 270, 16, (6u << 11) | (30u << 5)); + rkf_run_set_bits(blk, 286, 14, 10001); + rkf_run_set_bits(blk, 300, 16, (23u << 11) | (59u << 5) | 29u); + rkf_run_set_bits(blk, 316, 8, RKF_ID_MAC); + rkf_run_set_bits(blk, 324, 2, 0); + rkf_run_set_bits(blk, 326, 6, 3); + rkf_set_bits(rkf_test_block(dump, RKF_T_SEC_TICKET, 2), 112, 16, 0x5AA5); +} + +static bool rkf_check(const char *what, uint64_t got, uint64_t want) { + bool ok = (got == want); + PrintAndLogEx(INFO, " %-24s %12llu ( %s )", what, (unsigned long long)got, + ok ? _GREEN_("ok") : _RED_("fail")); + return ok; +} + +static bool rkf_check_str(const char *what, const char *got, const char *want) { + bool ok = (strcmp(got, want) == 0); + PrintAndLogEx(INFO, " %-24s %12s ( %s )", what, got, ok ? _GREEN_("ok") : _RED_("fail")); + return ok; +} + +int rkf_selftest(void) { + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "Testing RKF travel card decode"); + + uint8_t dump[MIFARE_1K_MAX_BYTES]; + rkf_build_selftest_card(dump); + + if (is_valid_rkf_card(dump, sizeof(dump)) == false) { + PrintAndLogEx(FAILED, " card not recognised ( " _RED_("fail") " )"); + return PM3_ESOFT; + } + + bool ok = true; + char buf[40]; + + const uint8_t *cmi = rkf_block(dump, sizeof(dump), 0, RKF_CMI_BLOCK); + ok &= rkf_check("card serial", rkf_bits(cmi, 0, 32), RKF_T_CSN); + ok &= rkf_check("check byte", rkf_bits(cmi, 32, 8), + (uint64_t)(cmi[0] ^ cmi[1] ^ cmi[2] ^ cmi[3])); + + rkf_tcci_t tcci; + rkf_read_tcci(rkf_block(dump, sizeof(dump), 0, RKF_TCCI_BLOCK), &tcci); + ok &= rkf_check("card provider", tcci.card_provider, RKF_T_PROVIDER); + ok &= rkf_check("currency unit", tcci.currency_unit, RKF_T_CURRENCY); + + rkf_date_str(tcci.validity_end, buf, sizeof(buf)); + ok &= rkf_check_str("valid until", buf, "2026-12-31"); + + rkf_currency_str(tcci.currency_unit, buf, sizeof(buf)); + ok &= rkf_check_str("currency", buf, "SEK, main unit"); + + rkf_tcas_t tcas1, tcas2; + rkf_read_tcas(rkf_block(dump, sizeof(dump), 0, RKF_TCAS_BLOCK), &tcas1); + rkf_read_tcas(rkf_block(dump, sizeof(dump), RKF_T_SEC_TCAS2, 0), &tcas2); + ok &= rkf_check("tcas identifier", tcas1.identifier, RKF_TCAS_IDENTIFIER); + ok &= rkf_check("tcas transaction no", tcas1.transaction_no, RKF_T_TXN); + ok &= rkf_check("tcas event record", tcas1.event_log_record, 4); + ok &= rkf_check("tcas purse status", tcas1.sector_status[RKF_T_SEC_PURSE], 2); + ok &= rkf_check("tcas instances equal", (memcmp(&tcas1, &tcas2, sizeof(tcas1)) == 0), 1); + + uint16_t aid[RKF_SECTORS], pix[RKF_SECTORS]; + rkf_read_tcdi(dump, sizeof(dump), aid, pix); + ok &= rkf_check("dir sector 1 aid", aid[1], RKF_AID_TCDI); + ok &= rkf_check("dir purse aid", aid[RKF_T_SEC_PURSE], RKF_AID_TCPU); + ok &= rkf_check("dir event log aid", aid[RKF_T_SEC_TCEL], RKF_AID_TCEL); + ok &= rkf_check("dir continuation pix", pix[RKF_T_SEC_TCEL + 1], RKF_PIX_CONT); + ok &= rkf_check("dir ticket aid", aid[RKF_T_SEC_TICKET], RKF_T_PROVIDER); + + const uint8_t *purse = rkf_block(dump, sizeof(dump), RKF_T_SEC_PURSE, 0); + ok &= rkf_check("purse serial", rkf_bits(purse, 26, 32), RKF_T_PURSE_SERIAL); + + const uint8_t *dyn = rkf_block(dump, sizeof(dump), RKF_T_SEC_PURSE, 2); + int32_t value = rkf_signed(rkf_bits(dyn, 30, 24), 24); + ok &= rkf_check("purse value negative", (value == RKF_T_PURSE_VALUE), 1); + rkf_money_str(value, tcci.currency_unit, buf, sizeof(buf)); + ok &= rkf_check_str("purse value", buf, "-12345 SEK"); + ok &= rkf_check("purse deposit", rkf_bits(dyn, 62, 20), RKF_T_DEPOSIT); + + const uint8_t *ev = rkf_block(dump, sizeof(dump), RKF_T_SEC_TCEL + 1, 1); + ok &= rkf_check("event identifier", rkf_bits(ev, 0, 8), RKF_ID_TCEL_RECORD); + ok &= rkf_check("event code", rkf_bits(ev, 90, 6), 0x08); + ok &= rkf_check("event device txn", rkf_bits(ev, 66, 24), 987654); + ok &= rkf_check("event checksum", rkf_checksum_ok(ev), 1); + ok &= rkf_check("directory checksum", rkf_checksum_ok(rkf_block(dump, sizeof(dump), RKF_TCDI_SECTOR, 0)), 1); + + // RKF-0022 7.7.1 "standard CRC-8" is CRC-8/MIFARE-MAD: a block of 15 zero + // bytes checksums to 0B, as seen on real cards + uint8_t zeros[MFBLOCK_SIZE] = {0}; + zeros[MFBLOCK_SIZE - 1] = 0x0B; + ok &= rkf_check("crc8 of 15 zero bytes", rkf_checksum_ok(zeros), 1); + rkf_time_str((uint16_t)rkf_bits(ev, 22, 16), buf, sizeof(buf)); + ok &= rkf_check_str("event time", buf, "13:45:30"); + + // The customer number of the ticket crosses the block boundary, stepping + // over the checksum byte of block 0 + rkf_run_t run = { .dump = dump, .dumplen = sizeof(dump), .sector = RKF_T_SEC_TICKET, .nblocks = 6 }; + ok &= rkf_check("ticket header id", rkf_run_bits(&run, 0, 8), RKF_ID_TCTI_HEADER); + ok &= rkf_check("ticket serial", rkf_run_bits(&run, 62, 32), RKF_T_TICKET_SERIAL); + ok &= rkf_check("ticket customer no", rkf_run_bits(&run, 110, 34), RKF_T_CUSTOMER); + ok &= rkf_check("dynamic element id", rkf_run_bits(&run, 240, 8), RKF_ID_DYN_SINGLE); + ok &= rkf_check("ticket validity id", rkf_run_bits(&run, 248, 8), RKF_ID_TCTI_PERIOD); + ok &= rkf_check("ticket mac id", rkf_run_bits(&run, 316, 8), RKF_ID_MAC); + + rkf_date_str((uint16_t)rkf_run_bits(&run, 256, 14), buf, sizeof(buf)); + ok &= rkf_check_str("ticket valid from", buf, "2024-05-19"); + rkf_time_str((uint16_t)rkf_run_bits(&run, 270, 16), buf, sizeof(buf)); + ok &= rkf_check_str("ticket valid from", buf, "06:30:00"); + rkf_date_str((uint16_t)rkf_run_bits(&run, 286, 14), buf, sizeof(buf)); + ok &= rkf_check_str("ticket valid to", buf, "2024-05-20"); + rkf_time_str((uint16_t)rkf_run_bits(&run, 300, 16), buf, sizeof(buf)); + ok &= rkf_check_str("ticket valid to", buf, "23:59:58"); + ok &= rkf_check("ticket mac value", + rkf_bits(rkf_block(dump, sizeof(dump), RKF_T_SEC_TICKET, 2), 112, 16), 0x5AA5); + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "Decoding the self test card"); + rkf_parser_parse(dump, sizeof(dump)); + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "RKF self test ( %s )", ok ? _GREEN_("ok") : _RED_("fail")); + return ok ? PM3_SUCCESS : PM3_ESOFT; +} diff --git a/client/src/parsers/parserkf.h b/client/src/parsers/parserkf.h new file mode 100644 index 000000000..deb352d52 --- /dev/null +++ b/client/src/parsers/parserkf.h @@ -0,0 +1,42 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// RKF travel card parser for MIFARE Classic dumps +// +// Resekortsforeningen i Norden, "RKF Type CL-1", the Nordic public transport +// travel card on MIFARE Classic 1K. Layout per RKF-0022 1.0 and RKF-0023 2.00. +//----------------------------------------------------------------------------- + +#ifndef PARSERKF_H__ +#define PARSERKF_H__ + +#include "common.h" + +// TCAS: Travel Card Applications Status, identifier of the first instance, +// always in block 2 of sector 0 +#define RKF_TCAS_IDENTIFIER 0xA0 + +// True when sector 0 carries a travel card applications status block and either +// the card information block or the directory corroborates it +bool is_valid_rkf_card(const uint8_t *dump, size_t dumplen); + +// Decode the support layer and walk the directory, printing every application +// object the specification pins down +int rkf_parser_parse(const uint8_t *dump, size_t dumplen); + +// Build a card from the encoder and check the decoder reads it back +int rkf_selftest(void); + +#endif diff --git a/client/src/parsers/parsevigik.c b/client/src/parsers/parsevigik.c new file mode 100644 index 000000000..06d0c510c --- /dev/null +++ b/client/src/parsers/parsevigik.c @@ -0,0 +1,798 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// VIGIK PACS parser for MIFARE Classic dumps +//----------------------------------------------------------------------------- + +#include "parsevigik.h" + +#include +#include // isdigit +#include // offsetof +#include + +#include "commonutil.h" +#include "ui.h" // PrintAndLogEx +#include "util.h" +#include "protocols.h" // MFBLOCK_SIZE +#include "mifare/mad.h" +#include "mifare/mifare4.h" // mfFirstBlockOfSector +#include "mifare/mifaredefault.h" // MIFARE_KEY_SIZE +#include "mbedtls/bignum.h" + +#define VIGIK_BLOCK0_SAK 0x88 // 24 of the 25 known family cards carry it +#define VIGIK_INFO_SHORT 0x01 // info flag of the short signature profile +#define VIGIK_SIG_LEN_ALT 96 // and how many bytes it carries +#define VIGIK_SIG_LEN 128 // RSA 1024, the signature on the card +#define VIGIK_SIGNED "( " _GREEN_("signed") " )" +#define VIGIK_MSG_SLOTS 64 // message byte slots in an ISO 9796-1 block +#define VIGIK_MSG_PAD 8 // leading zero bytes of the signed message + + +static const vigik_pk_t vigik_rsa_pk[] = { + {"La Poste Service Universel", 0x07AA, "AB9953CBFCCD9375B6C028ADBAB7584BED15B9CA037FADED9765996F9EA1AB983F3041C90DA3A198804FF90D5D872A96A4988F91F2243B821E01C5021E3ED4E1BA83B7CFECAB0E766D8563164DE0B2412AE4E6EA63804DF5C19C7AA78DC14F608294D732D7C8C67A88C6F84C0F2E3FAFAE34084349E11AB5953AC68729D07715"}, + {"La Poste Service Universel", 0x07AA, "1577D02987C63A95B51AE149430834AEAF3F2E0F4CF8C6887AC6C8D732D79482604FC18DA77A9CC1F54D8063EAE6E42A41B2E04D1663856D760EABECCFB783BAE1D43E1E02C5011E823B24F2918F98A4962A875D0DF94F8098A1A30DC941303F98ABA19E6F996597EDAD7F03CAB915ED4B58B7BAAD28C0B67593CDFCCB5399AB"}, + + {"La Poste Autres Services", 0x07AB, "A6D99B8D902893B04F3F8DE56CB6BF24338FEE897C1BCE6DFD4EBD05B7B1A07FD2EB564BB4F7D35DBFE0A42966C2C137AD156E3DAB62904592BCA20C0BC7B8B1E261EF82D53F52D203843566305A49A22062DECC38C2FE3864CAD08E79219487651E2F79F1C9392B48CAFE1BFFAFF4802AE451E7A283E55A4026AD1E82DF1A15"}, + {"La Poste Autres Services", 0x07AB, "151adf821ead26405ae583a2e751e42a80f4afff1bfeca482b39c9f1792f1e65879421798ed0ca6438fec238ccde6220a2495a3066358403d2523fd582ef61e2b1b8c70b0ca2bc92459062ab3d6e15ad37c1c26629a4e0bf5dd3f7b44b56ebd27fa0b1b705bd4efd6dce1b7c89ee8f3324bfb66ce58d3f4fb09328908d9bd9a6"}, + + {"France Telecom", 0x07AC, "B35193DBD2F88A21CDCFFF4BF84F7FC036A991A363DCB3E802407A5E5879DC2127EECFC520779E79E911394882482C87D09A88B0711CBC2973B77FFDAE40EA0001F595072708C558B484AB89D02BCBCB971FF1B80371C0BE30CB13661078078BB68EBCCA524B9DD55EBF7D47D9355AFC95511350CC1103A5DEE847868848B235"}, + {"France Telecom", 0x07AC, "35b248888647e8dea50311cc50135195fc5a35d9477dbf5ed59d4b52cabc8eb68b0778106613cb30bec07103b8f11f97cbcb2bd089ab84b458c508270795f50100ea40aefd7fb77329bc1c71b0889ad0872c4882483911e9799e7720c5cfee2721dc79585e7a4002e8b3dc63a391a936c07f4ff84bffcfcd218af8d2db9351b3"}, + + {"EDF-GDF", 0x07AD, "C44DBCD92F9DCF42F4902A87335DBB35D2FF530CDB09814CFA1F4B95A1BD018D099BC6AB69F667B4922AE1ED826E72951AA3E0EAAA7D49A695F04F8CDAAE2D18D10D25BD529CBB05ABF070DC7C041EC35C2BA7F58CC4C349983CC6E11A5CBE828FB8ECBC26F08E1094A6B44C8953C8E1BAFD214DF3E69F430A98CCC75C03669D"}, + {"EDF-GDF", 0x07AD, "9d66035cc7cc980a439fe6f34d21fdbae1c853894cb4a694108ef026bcecb88f82be5c1ae1c63c9849c3c48cf5a72b5cc31e047cdc70f0ab05bb9c52bd250dd1182daeda8c4ff095a6497daaeae0a31a95726e82ede12a92b467f669abc69b098d01bda1954b1ffa4c8109db0c53ffd235bb5d33872a90f442cf9d2fd9bc4dc4"}, + + {"VIGIK service 0x07B5", 0x07B5, "EF8DC002C694B0C77F0F3B4DE59EC06724ECB92365F0562AA09220DBDFA79CE50D6A6403D051938B63C867E3BA1B8DD37C537DA49CBFF265A069519C02E735A3479637869D8F979B67F0A6A819E73047D16C365738A747DEA8F84399C891576CDC1AE35DAF821D10CC7041693573910B2FE1ABB7868081F6FB1B96E609B3E4E5"}, + {"VIGIK service 0x07B5", 0x07B5, "e5e4b309e6961bfbf6818086b7abe12f0b917335694170cc101d82af5de31adc6c5791c89943f8a8de47a73857366cd14730e719a8a6f0679b978f9d86379647a335e7029c5169a065f2bf9ca47d537cd38d1bbae367c8638b9351d003646a0de59ca7dfdb2092a02a56f06523b9ec2467c09ee54d3b0f7fc7b094c602c08def"}, + {NULL, 0, NULL} +}; + +// Moduli this repository recovered from cards rather than took from a published +// source. Two cards is the minimum the GCD attack needs, so a third is worth +// asking for: it confirms the key and may name the operator. +static const uint16_t vigik_pk_recovered[] = { 0x07B5 }; + +static bool vigik_pk_is_recovered(uint16_t service_code) { + for (size_t i = 0; i < ARRAYLEN(vigik_pk_recovered); i++) { + if (service_code == vigik_pk_recovered[i]) { + return true; + } + } + return false; +} + +const char *vigik_get_service(uint16_t service_code) { + for (int i = 0; i < ARRAYLEN(vigik_rsa_pk); ++i) { + if (service_code == vigik_rsa_pk[i].code) { + return vigik_rsa_pk[i].desc; + } + } + + return "unknown service"; +} + +// ISO 9796-1 shadow permutation. Each message byte is stored next to its shadow, +static const uint8_t vigik_iso9796_pi[16] = { + 0x0E, 0x03, 0x05, 0x08, 0x09, 0x04, 0x02, 0x0F, + 0x00, 0x0D, 0x0B, 0x06, 0x07, 0x0A, 0x0C, 0x01 +}; + +static uint8_t vigik_shadow(uint8_t b) { + return (uint8_t)((vigik_iso9796_pi[b >> 4] << 4) | vigik_iso9796_pi[b & 0x0F]); +} + +// Recover the message an ISO 9796-1 signature carries, checking the redundancy on +// the way. `sig` is the signature as it sits on the card, `modulus` the public key to try. +// On success msg holds msglen bytes. +static int vigik_iso9796_recover(const uint8_t *sig, const char *modulus, uint8_t *msg, size_t *msglen) { + + uint8_t n[VIGIK_SIG_LEN] = {0}; + int dl = 0; + param_gethex_to_eol(modulus, 0, n, sizeof(n), &dl); + if (dl != VIGIK_SIG_LEN) { + return PM3_EINVARG; + } + + uint8_t rev[VIGIK_SIG_LEN] = {0}; + reverse_array_copy(sig, VIGIK_SIG_LEN, rev); + + mbedtls_mpi N, S, E, J, cand, tmp; + mbedtls_mpi_init(&N); + mbedtls_mpi_init(&S); + mbedtls_mpi_init(&E); + mbedtls_mpi_init(&J); + mbedtls_mpi_init(&cand); + mbedtls_mpi_init(&tmp); + + mbedtls_mpi_read_binary(&N, n, sizeof(n)); + mbedtls_mpi_read_binary(&S, rev, sizeof(rev)); + mbedtls_mpi_add_int(&E, &E, 2); + + uint8_t f[VIGIK_SIG_LEN] = {0}; + bool got_block = false; + + if (mbedtls_mpi_cmp_mpi(&S, &N) < 0) { + + mbedtls_mpi_exp_mod(&J, &S, &E, &N, NULL); + + for (uint8_t c = 0; c < 4 && got_block == false; c++) { + + switch (c) { + case 0: + mbedtls_mpi_copy(&cand, &J); + break; + case 1: + mbedtls_mpi_sub_mpi(&cand, &N, &J); + break; + case 2: + mbedtls_mpi_mul_int(&cand, &J, 2); + break; + default: + mbedtls_mpi_sub_mpi(&tmp, &N, &J); + mbedtls_mpi_mul_int(&cand, &tmp, 2); + break; + } + + if (mbedtls_mpi_bitlen(&cand) > (VIGIK_SIG_LEN * 8)) { + continue; + } + + uint8_t low = 0; + for (uint8_t b = 0; b < 4; b++) { + low |= (uint8_t)(mbedtls_mpi_get_bit(&cand, b) << b); + } + + if (low != 0x06) { + continue; + } + + if (mbedtls_mpi_write_binary(&cand, f, sizeof(f)) == 0) { + got_block = true; + } + } + } + + mbedtls_mpi_free(&N); + mbedtls_mpi_free(&S); + mbedtls_mpi_free(&E); + mbedtls_mpi_free(&J); + mbedtls_mpi_free(&cand); + mbedtls_mpi_free(&tmp); + + if (got_block == false) { + return PM3_ESOFT; + } + + size_t broken[4] = {0}; + size_t brokencnt = 0; + for (size_t i = 0; i < VIGIK_SIG_LEN; i += 2) { + if (vigik_shadow(f[i + 1]) != f[i]) { + if (brokencnt < ARRAYLEN(broken)) { + broken[brokencnt] = i; + } + brokencnt++; + } + } + + if (brokencnt != 3 || broken[0] != 0 || broken[2] != (VIGIK_SIG_LEN - 2)) { + return PM3_ESOFT; + } + + size_t z = VIGIK_MSG_SLOTS - (broken[1] / 2); + if (z == 0 || z > (VIGIK_MSG_SLOTS - 1)) { + return PM3_ESOFT; + } + + uint8_t stream[VIGIK_MSG_SLOTS] = {0}; + for (size_t i = 0; i < VIGIK_SIG_LEN; i += 2) { + stream[i / 2] = f[i + 1]; + } + + if (((1 + (2 * z)) <= VIGIK_MSG_SLOTS) && (memcmp(stream + 1, stream + 1 + z, z) != 0)) { + return PM3_ESOFT; + } + + reverse_array_copy(stream + 1, (int)z, msg); + *msglen = z; + return PM3_SUCCESS; +} + +static void vigik_print_date(const char *label, const uint8_t *v, const char *suffix) { + + bool sane = ((v[1] >= 1) && (v[1] <= 12) && + (v[2] >= 1) && (v[2] <= 31) && + (v[3] <= 23) && (v[4] <= 59)); + + if (sane) { + PrintAndLogEx(INFO, "%s %s ( " _YELLOW_("%04u-%02u-%02u %02u:%02u") " )%s", + label, + sprint_hex_inrow(v, 5), + 1900 + v[0], + v[1], + v[2], + v[3], + v[4], + suffix + ); + } else { + PrintAndLogEx(INFO, "%s %s" "%s", label, sprint_hex_inrow(v, 5), suffix); + } +} + +static size_t vigik_expected_msg(const mfc_vigik_t *d, uint8_t *out) { + + size_t len = 0; + memset(out, 0, VIGIK_MSG_PAD); + len += VIGIK_MSG_PAD; + + memcpy(out + len, d->b0, 4); // UID + len += 4; + + Uint4byteToMemLe(out + len, d->service_code); + len += 4; + + out[len++] = d->key_version; + out[len++] = d->services_counter; + + memcpy(out + len, d->slot_access_date, sizeof(d->slot_access_date)); + len += sizeof(d->slot_access_date); + + Uint2byteToMemLe(out + len, d->slot_dst_duration); + len += 2; + return len; +} + +int vigik_verify(mfc_vigik_t *d) { + + if (d == NULL) { + return PM3_EINVARG; + } + + uint8_t expected[VIGIK_MSG_SLOTS] = {0}; + size_t expectedlen = vigik_expected_msg(d, expected); + + for (uint8_t i = 0; i < ARRAYLEN(vigik_rsa_pk); i++) { + + if (vigik_rsa_pk[i].desc == NULL) { + break; + } + + uint8_t msg[VIGIK_MSG_SLOTS] = {0}; + size_t msglen = 0; + if (vigik_iso9796_recover(d->rsa_signature, vigik_rsa_pk[i].n, msg, &msglen) != PM3_SUCCESS) { + continue; + } + + PrintAndLogEx(INFO, "--- " _CYAN_("Signature") " ------------------------------"); + PrintAndLogEx(INFO, "Signed by.......... " _YELLOW_("%s"), vigik_rsa_pk[i].desc); + PrintAndLogEx(INFO, "Scheme............. ISO 9796-1, RSA 1024, v=2"); + PrintAndLogEx(INFO, "Recovered.......... %s", sprint_hex_inrow(msg, msglen)); + + if ((msglen != expectedlen) || (memcmp(msg, expected, msglen) != 0)) { + PrintAndLogEx(INFO, "Card fields........ %s", sprint_hex_inrow(expected, expectedlen)); + PrintAndLogEx(FAILED, "Signature verification: " _RED_("card data does not match the signature")); + return PM3_ESOFT; + } + + PrintAndLogEx(INFO, " UID.............. %s", sprint_hex_inrow(msg + VIGIK_MSG_PAD, 4)); + PrintAndLogEx(INFO, " Service code..... 0x%04X", (uint16_t)d->service_code); + PrintAndLogEx(INFO, " Key version...... %u", d->key_version); + PrintAndLogEx(INFO, " Services counter. %u", d->services_counter); + vigik_print_date(" Access date......", d->slot_access_date, ""); + PrintAndLogEx(INFO, " DST duration..... %u", d->slot_dst_duration); + + // The service code on the card says which service issued it, so it should name the key + if (vigik_rsa_pk[i].code != (uint16_t)d->service_code) { + PrintAndLogEx(WARNING, "Card says service 0x%04X but the key that verified is listed as 0x%04X ( %s )", + (uint16_t)d->service_code, + vigik_rsa_pk[i].code, + vigik_rsa_pk[i].desc + ); + } + + PrintAndLogEx(SUCCESS, "Signature verification: " _GREEN_("successful")); + + if (vigik_pk_is_recovered(vigik_rsa_pk[i].code)) { + PrintAndLogEx(HINT, "Hint: " _RED_("Report to Iceman!")); + } + + return PM3_SUCCESS; + } + + PrintAndLogEx(FAILED, "Signature verification: " _RED_("no public key recovered a valid block")); + + // no key here recovers this card, so the service is one we have never seen + PrintAndLogEx(HINT, "Hint: " _RED_("Report to Iceman!")); + + return PM3_ESOFT; +} + +// An expired VIGIK service badge, published for study in +// armsrc/Standalone/hf_colin.c. Signed by La Poste Service Universel. +static const uint8_t vigik_selftest_card[] = { + 0x12, 0x1C, 0x7F, 0x73, 0x02, 0x08, 0x04, 0x00, 0x01, 0xFA, 0x33, 0xF5, + 0xCB, 0x2D, 0x02, 0x1D, 0x44, 0x00, 0x10, 0x49, 0x16, 0x49, 0x16, 0x49, + 0x16, 0x49, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0xAA, 0x07, 0x00, 0x00, 0x21, 0x02, 0x08, 0x00, + 0x00, 0x74, 0x0C, 0x11, 0x06, 0x00, 0xAF, 0x13, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x01, 0x74, 0x0C, 0x11, 0x08, 0x22, 0x00, 0x00, + 0x24, 0xE5, 0x72, 0xB9, 0x23, 0xA3, 0xD2, 0x43, 0xB4, 0x02, 0xD6, 0x0C, + 0xAB, 0x57, 0x69, 0x56, 0x21, 0x6D, 0x65, 0x01, 0xFC, 0x86, 0x18, 0xB6, + 0xC4, 0x26, 0x76, 0x25, 0x11, 0xAC, 0x2D, 0xEE, 0x25, 0xBF, 0x4C, 0xEC, + 0x36, 0x18, 0xD0, 0xBA, 0xB3, 0xA6, 0xE9, 0x21, 0x0D, 0x88, 0x77, 0x46, + 0x0F, 0xBC, 0x41, 0xA5, 0xD9, 0x53, 0x98, 0xE7, 0x6A, 0x1B, 0x20, 0x29, + 0xE8, 0xEA, 0x97, 0x35, 0x08, 0x8B, 0xA2, 0xCE, 0x73, 0x26, 0x53, 0xD0, + 0xC1, 0x14, 0x75, 0x96, 0xAF, 0xCF, 0x94, 0xD7, 0x77, 0xB4, 0xD9, 0x1F, + 0x04, 0x42, 0x18, 0x22, 0x73, 0xA2, 0x9D, 0xEA, 0xF7, 0xA2, 0xD0, 0x95, + 0x4C, 0xEE, 0x71, 0x58, 0x66, 0xE5, 0x08, 0xCD, 0xBC, 0x95, 0xC6, 0x40, + 0xEC, 0x9D, 0x1E, 0x58, 0xE8, 0x00, 0x45, 0x7C, 0xF8, 0xB0, 0x79, 0x41, + 0x4E, 0x1B, 0x45, 0xDD, 0x3E, 0x6C, 0x93, 0x17, +}; + +int vigik_selftest(void) { + + PrintAndLogEx(INFO, "Testing VIGIK ISO 9796-1 signature recovery"); + + if (sizeof(vigik_selftest_card) != sizeof(mfc_vigik_t)) { + PrintAndLogEx(FAILED, " vector is %zu bytes, struct is %zu ( " _RED_("fail") " )", + sizeof(vigik_selftest_card), sizeof(mfc_vigik_t)); + return PM3_ESOFT; + } + + mfc_vigik_t card; + memcpy(&card, vigik_selftest_card, sizeof(card)); + + uint8_t expected[VIGIK_MSG_SLOTS] = {0}; + size_t expectedlen = vigik_expected_msg(&card, expected); + + uint8_t msg[VIGIK_MSG_SLOTS] = {0}; + size_t msglen = 0; + int res = PM3_ESOFT; + + for (uint8_t i = 0; i < ARRAYLEN(vigik_rsa_pk); i++) { + if (vigik_rsa_pk[i].desc == NULL) { + break; + } + if (vigik_iso9796_recover(card.rsa_signature, vigik_rsa_pk[i].n, msg, &msglen) == PM3_SUCCESS) { + PrintAndLogEx(INFO, " recovered against.. %s", vigik_rsa_pk[i].desc); + res = PM3_SUCCESS; + break; + } + } + + if (res != PM3_SUCCESS) { + PrintAndLogEx(FAILED, " no public key recovered a valid block ( " _RED_("fail") " )"); + return PM3_ESOFT; + } + + PrintAndLogEx(INFO, " recovered.......... %s", sprint_hex_inrow(msg, msglen)); + PrintAndLogEx(INFO, " card fields........ %s", sprint_hex_inrow(expected, expectedlen)); + + if ((msglen != expectedlen) || (memcmp(msg, expected, msglen) != 0)) { + PrintAndLogEx(FAILED, " recovered message does not match the card ( " _RED_("fail") " )"); + return PM3_ESOFT; + } + + PrintAndLogEx(SUCCESS, "VIGIK signature selftest ( " _GREEN_("ok") " )"); + return PM3_SUCCESS; +} + +int vigik_annotate(mfc_vigik_t *d) { + if (d == NULL) + return PM3_EINVARG; + + PrintAndLogEx(INFO, "Manufacture......... %s", sprint_hex_inrow(d->b0, sizeof(d->b0))); + PrintAndLogEx(INFO, "MAD................. %s", sprint_hex_inrow(d->mad, sizeof(d->mad))); + PrintAndLogEx(INFO, "Counters............ %u", d->counters); + PrintAndLogEx(INFO, "rtf................. %s", sprint_hex_inrow(d->rtf, sizeof(d->rtf))); + PrintAndLogEx(INFO, "Service code........ 0x%08x / %u - " _YELLOW_("%s") " " VIGIK_SIGNED, d->service_code, d->service_code, vigik_get_service(d->service_code)); + PrintAndLogEx(INFO, "Info flag........... %u -", d->info_flag); // , sprint_bin(d->info_flag, 1)); + PrintAndLogEx(INFO, "Key version......... %u " VIGIK_SIGNED, d->key_version); + PrintAndLogEx(INFO, "PTR Counter......... %u", d->ptr_counter); + PrintAndLogEx(INFO, "Counter num......... %u", d->counter_num); + vigik_print_date("Slot access date....", d->slot_access_date, " " VIGIK_SIGNED); + PrintAndLogEx(INFO, "Slot dst duration... %u " VIGIK_SIGNED, d->slot_dst_duration); + PrintAndLogEx(INFO, "Other Slots......... %s", sprint_hex_inrow(d->other_slots, sizeof(d->other_slots))); + PrintAndLogEx(INFO, "Services counter.... %u " VIGIK_SIGNED, d->services_counter); + vigik_print_date("Loading date........", d->loading_date, ""); + PrintAndLogEx(INFO, "Reserved null....... %u", d->reserved_null); + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "Unmarked fields are outside the signature, %d of the %d service record", + 35, 48); + PrintAndLogEx(INFO, "bytes, and every one of them is writable with a published key"); + PrintAndLogEx(INFO, "----------------------------------------------------------------"); + PrintAndLogEx(INFO, ""); + vigik_verify(d); + PrintAndLogEx(INFO, "----------------------------------------------------------------"); + PrintAndLogEx(INFO, ""); + return PM3_SUCCESS; + +} + +typedef struct vigik_schema_s { + const char *name; + uint64_t key_a[16]; + uint64_t key_b[16]; + int (*decode)(const uint8_t *dump, size_t dumplen); +} vigik_schema_t; + +static int vigik_print_urmet_captiv(const uint8_t *dump, size_t dumplen); + +static const vigik_schema_t vigik_schemas[] = { + { + "Noralsy", + { + 0x414c41524f4eULL, 0x414c41524f4eULL, 0x414c41524f4eULL, 0x414c41524f4eULL, + 0x414c41524f4eULL, 0x414c41524f4eULL, 0x414c41524f4eULL, 0x414c41524f4eULL, + 0x414c41524f4eULL, 0x414c41524f4eULL, 0x414c41524f4eULL, 0x414c41524f4eULL, + 0x414c41524f4eULL, 0x414c41524f4eULL, 0x414c41524f4eULL, 0x414c41524f4eULL + }, + { + 0x424c41524f4eULL, 0x424c41524f4eULL, 0x424c41524f4eULL, 0x424c41524f4eULL, + 0x424c41524f4eULL, 0x424c41524f4eULL, 0x424c41524f4eULL, 0x424c41524f4eULL, + 0x424c41524f4eULL, 0x424c41524f4eULL, 0x424c41524f4eULL, 0x424c41524f4eULL, + 0x424c41524f4eULL, 0x424c41524f4eULL, 0x424c41524f4eULL, 0x424c41524f4eULL + }, + NULL + }, + { + // from the published anti-copy fingerprints, no card seen here + "Noralsy gen2", + { + 0x675a32413770ULL, 0x675a32413770ULL, 0x675a32413770ULL, 0x675a32413770ULL, + 0x675a32413770ULL, 0x675a32413770ULL, 0x675a32413770ULL, 0x675a32413770ULL, + 0x675a32413770ULL, 0x675a32413770ULL, 0x675a32413770ULL, 0x675a32413770ULL, + 0x675a32413770ULL, 0x675a32413770ULL, 0x675a32413770ULL, 0x675a32413770ULL + }, + { + 0x395244733978ULL, 0x395244733978ULL, 0x395244733978ULL, 0x395244733978ULL, + 0x395244733978ULL, 0x395244733978ULL, 0x395244733978ULL, 0x395244733978ULL, + 0x395244733978ULL, 0x395244733978ULL, 0x395244733978ULL, 0x395244733978ULL, + 0x395244733978ULL, 0x395244733978ULL, 0x395244733978ULL, 0x395244733978ULL + }, + NULL + }, + { + // sectors 0-5 only; 6-15 are left factory default on the card seen + "Comelit", + { + 0x4a6352684677ULL, 0x4a6352684677ULL, 0x4a6352684677ULL, 0x4a6352684677ULL, + 0x4a6352684677ULL, 0x4a6352684677ULL, VIGIK_KEY_ANY, VIGIK_KEY_ANY, + VIGIK_KEY_ANY, VIGIK_KEY_ANY, VIGIK_KEY_ANY, VIGIK_KEY_ANY, + VIGIK_KEY_ANY, VIGIK_KEY_ANY, VIGIK_KEY_ANY, VIGIK_KEY_ANY + }, + { + 0x536653644c65ULL, 0x536653644c65ULL, 0x536653644c65ULL, 0x536653644c65ULL, + 0x536653644c65ULL, 0x536653644c65ULL, VIGIK_KEY_ANY, VIGIK_KEY_ANY, + VIGIK_KEY_ANY, VIGIK_KEY_ANY, VIGIK_KEY_ANY, VIGIK_KEY_ANY, + VIGIK_KEY_ANY, VIGIK_KEY_ANY, VIGIK_KEY_ANY, VIGIK_KEY_ANY + }, + NULL + }, + { + "Urmet Captiv", + { + 0x8829da9daf76ULL, 0x8829da9daf76ULL, 0x8829da9daf76ULL, 0x8829da9daf76ULL, + 0x8829da9daf76ULL, 0x8829da9daf76ULL, 0x8829da9daf76ULL, 0x8829da9daf76ULL, + 0x8829da9daf76ULL, 0x8829da9daf76ULL, 0x8829da9daf76ULL, 0x8829da9daf76ULL, + 0x8829da9daf76ULL, 0x8829da9daf76ULL, 0x8829da9daf76ULL, 0x8829da9daf76ULL + }, + { + 0x8829da9daf76ULL, 0x8829da9daf76ULL, 0x8829da9daf76ULL, 0x8829da9daf76ULL, + 0x8829da9daf76ULL, 0x8829da9daf76ULL, 0x8829da9daf76ULL, 0x8829da9daf76ULL, + 0x8829da9daf76ULL, 0x8829da9daf76ULL, 0x8829da9daf76ULL, 0x8829da9daf76ULL, + 0x8829da9daf76ULL, 0x8829da9daf76ULL, 0x8829da9daf76ULL, 0x8829da9daf76ULL + }, + vigik_print_urmet_captiv + }, + { + // MAD key on sector 0 and the VIGIK key on sectors 1-3. How many further + // sectors the badge personalises varies, so those are left open + "VIGIK service badge", + { + 0xa0a1a2a3a4a5ULL, 0x314b49474956ULL, 0x314b49474956ULL, 0x314b49474956ULL, + VIGIK_KEY_ANY, VIGIK_KEY_ANY, VIGIK_KEY_ANY, VIGIK_KEY_ANY, + VIGIK_KEY_ANY, VIGIK_KEY_ANY, VIGIK_KEY_ANY, VIGIK_KEY_ANY, + VIGIK_KEY_ANY, VIGIK_KEY_ANY, VIGIK_KEY_ANY, VIGIK_KEY_ANY + }, + { + VIGIK_KEY_ANY, VIGIK_KEY_ANY, VIGIK_KEY_ANY, VIGIK_KEY_ANY, + VIGIK_KEY_ANY, VIGIK_KEY_ANY, VIGIK_KEY_ANY, VIGIK_KEY_ANY, + VIGIK_KEY_ANY, VIGIK_KEY_ANY, VIGIK_KEY_ANY, VIGIK_KEY_ANY, + VIGIK_KEY_ANY, VIGIK_KEY_ANY, VIGIK_KEY_ANY, VIGIK_KEY_ANY + }, + NULL + }, +}; + +// Key A or key B out of a sector trailer, VIGIK_KEY_ANY when the dump is short +static uint64_t vigik_sector_key(const uint8_t *dump, size_t dumplen, uint8_t sector, bool keyb) { + size_t trailer = (mfFirstBlockOfSector(sector) + mfNumBlocksPerSector(sector) - 1) * MFBLOCK_SIZE; + if (trailer + MFBLOCK_SIZE > dumplen) { + return VIGIK_KEY_ANY; + } + const uint8_t *p = dump + trailer + (keyb ? 10 : 0); + uint64_t key = 0; + for (uint8_t i = 0; i < MIFARE_KEY_SIZE; i++) { + key = (key << 8) | p[i]; + } + return key; +} + +static const vigik_schema_t *vigik_detect_schema_entry(const uint8_t *dump, size_t dumplen) { + + if (dump == NULL) { + return NULL; + } + + for (size_t i = 0; i < ARRAYLEN(vigik_schemas); i++) { + + const vigik_schema_t *schema = &vigik_schemas[i]; + bool match = true; + + for (uint8_t s = 0; s < 16 && match; s++) { + + if ((schema->key_a[s] != VIGIK_KEY_ANY) && (schema->key_a[s] != vigik_sector_key(dump, dumplen, s, false))) { + match = false; + } + + if ((schema->key_b[s] != VIGIK_KEY_ANY) && (schema->key_b[s] != vigik_sector_key(dump, dumplen, s, true))) { + match = false; + } + } + + if (match) { + return schema; + } + } + return NULL; +} + +const char *vigik_detect_schema(const uint8_t *dump, size_t dumplen) { + const vigik_schema_t *schema = vigik_detect_schema_entry(dump, dumplen); + return (schema != NULL) ? schema->name : NULL; +} + +// --------------------------------------------------------------- Urmet Captiv +#define URMET_DIGITS_OFF 5 +#define URMET_DIGITS_LEN 11 + +static const uint8_t *proac_unused_marker(const uint8_t *dump, size_t dumplen) { + size_t off = (mfFirstBlockOfSector(2) + 1) * MFBLOCK_SIZE; + return (off + MFBLOCK_SIZE <= dumplen) ? dump + off : NULL; +} + +static bool urmet_all_digits(const uint8_t *p, size_t len) { + for (size_t i = 0; i < len; i++) { + if (isdigit(p[i]) == 0) { + return false; + } + } + return true; +} + +static int vigik_print_urmet_captiv(const uint8_t *dump, size_t dumplen) { + + if (dumplen < MFBLOCK_SIZE * 3) { + return PM3_EINVARG; + } + + const uint8_t *b1 = dump + MFBLOCK_SIZE; + const uint8_t *b2 = dump + (2 * MFBLOCK_SIZE); + + PrintAndLogEx(INFO, "Header............. %s", sprint_hex_inrow(b1, URMET_DIGITS_OFF)); + + if (urmet_all_digits(b1 + URMET_DIGITS_OFF, URMET_DIGITS_LEN)) { + char num[URMET_DIGITS_LEN + 1] = {0}; + memcpy(num, b1 + URMET_DIGITS_OFF, URMET_DIGITS_LEN); + PrintAndLogEx(INFO, "Number............. " _YELLOW_("%s") "%s" + , num + , (strspn(num, "0") == URMET_DIGITS_LEN) ? " ( all zero, unset )" : "" + ); + } else { + PrintAndLogEx(INFO, "Number............. %s ( not ASCII digits )", sprint_hex_inrow(b1 + URMET_DIGITS_OFF, URMET_DIGITS_LEN)); + } + + PrintAndLogEx(INFO, "Marker............. %s", sprint_hex_inrow(b2, 2)); + + // sector 2 block 1 keeps one three byte value twice over, each copy behind + // a byte that differs slightly between the copies. Holds on all three cards + // seen; the differing prefix is the shape a use counter takes. + const uint8_t *rec = proac_unused_marker(dump, dumplen); + if (rec) { + if (memcmp(rec + 5, rec + 9, 3) == 0) { + PrintAndLogEx(INFO, "Record............. %s stored twice, prefix %02X / %02X", + sprint_hex_inrow(rec + 5, 3), rec[4], rec[8]); + } else { + PrintAndLogEx(INFO, "Record............. %s and %s ( copies differ )", + sprint_hex_inrow(rec + 5, 3), sprint_hex_inrow(rec + 9, 3)); + } + } + PrintAndLogEx(INFO, "Data............... layout " _YELLOW_("not decoded")); + + int shown = 0; + for (uint8_t s = 1; s < 16; s++) { + + for (uint8_t b = 0; b < 3; b++) { + + size_t off = (mfFirstBlockOfSector(s) + b) * MFBLOCK_SIZE; + if (off + MFBLOCK_SIZE > dumplen) { + continue; + } + + const uint8_t *p = dump + off; + bool empty = true; + for (uint8_t k = 0; k < MFBLOCK_SIZE; k++) { + if (p[k]) { + empty = false; + break; + } + } + if (empty == false) { + PrintAndLogEx(INFO, " sector %2u blk %u.. %s", s, b, sprint_hex_inrow(p, MFBLOCK_SIZE)); + shown++; + } + } + } + + if (shown == 0) { + PrintAndLogEx(INFO, " every sector past 0 is empty, card not personalised"); + } + + PrintAndLogEx(INFO, "Keys............... one key r/w every block"); + return PM3_SUCCESS; +} + +// Factory state: both keys erased, access bits as delivered, data zeroed. A +// sector like this was never written, as against one a dump failed to read. +static bool vigik_sector_is_blank(const uint8_t *dump, size_t dumplen, uint8_t sector) { + size_t off = (size_t)sector * MFBLOCK_SIZE * 4; + if (off + (MFBLOCK_SIZE * 4) > dumplen) { + return false; + } + const uint8_t *tr = dump + off + (MFBLOCK_SIZE * 3); + if (tr[6] != 0xFF || tr[7] != 0x07 || tr[8] != 0x80) { + return false; + } + for (uint8_t k = 0; k < MIFARE_KEY_SIZE; k++) { + if (tr[k] != 0xFF || tr[10 + k] != 0xFF) { + return false; + } + } + for (size_t k = 0; k < MFBLOCK_SIZE * 3; k++) { + if (dump[off + k] != 0x00) { + return false; + } + } + return true; +} + +// sectors holding the VIGIK record, in the order they are concatenated +static bool vigik_is_data_aid(uint16_t aid) { + return (aid == VIGIK_MAD_AID || aid == VIGIK_MAD_AID_ALT || aid == VIGIK_MAD_AID_ALT2); +} + +bool is_valid_vigik_card(const uint8_t *dump, size_t dumplen) { + if (dump == NULL || dumplen < sizeof(mad1_sector_t)) { + return false; + } + if (DetectHID((const mad1_sector_t *)dump, VIGIK_MAD_AID) > -1) { + return true; + } + return (vigik_detect_schema(dump, dumplen) != NULL); +} + +int vigik_parser_parse(const uint8_t *dump, size_t dumplen) { + + if (is_valid_vigik_card(dump, dumplen) == false) { + return PM3_EINVARG; + } + + const mad1_sector_t *s0 = (const mad1_sector_t *)dump; + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, _CYAN_("VIGIK PACS detected")); + + const char *schema = vigik_detect_schema(dump, dumplen); + if (schema != NULL) { + PrintAndLogEx(SUCCESS, "System............. " _YELLOW_("%s"), schema); + } + + if (dumplen > 5 && dump[5] == VIGIK_BLOCK0_SAK) { + PrintAndLogEx(INFO, "Block 0 SAK........ 0x%02X ( " _YELLOW_("anti clone marker") " )", dump[5]); + PrintAndLogEx(INFO, " the tag answers 0x08, a clone written with this block 0 answers 0x88"); + } + + if (DetectHID(s0, VIGIK_MAD_AID) < 0) { + const vigik_schema_t *entry = vigik_detect_schema_entry(dump, dumplen); + if (entry != NULL && entry->decode != NULL) { + return entry->decode(dump, dumplen); + } + PrintAndLogEx(INFO, "No MAD on this card, structure " _YELLOW_("not decoded")); + return PM3_SUCCESS; + } + + mad_entry_list_t mad_list = {0}; + int res = MADDecode(s0, NULL, &mad_list, false, true); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "can't decode MAD"); + return res; + } + + union { + uint8_t *bytes; + mfc_vigik_t *vigik; + } d; + + d.bytes = calloc(dumplen, sizeof(uint8_t)); + if (d.bytes == NULL) { + PrintAndLogEx(WARNING, "Failed to allocate memory"); + return PM3_EMALLOC; + } + + uint16_t dlen = 0; + memcpy(d.bytes + dlen, dump, MFBLOCK_SIZE * 3); + dlen += MFBLOCK_SIZE * 3; + + uint8_t last = 0; + for (size_t i = 0; i < mad_list.len; i++) { + + if (vigik_is_data_aid(mad_list.entries[i].aid)) { + + uint32_t offset = mad_list.entries[i].sector * MFBLOCK_SIZE * 4; + + if (offset + (MFBLOCK_SIZE * 3) > dumplen) { + continue; + } + memcpy(d.bytes + dlen, dump + offset, MFBLOCK_SIZE * 3); + dlen += MFBLOCK_SIZE * 3; + last = mad_list.entries[i].sector; + } + } + + const size_t sigoff = offsetof(mfc_vigik_t, rsa_signature); + if (dlen < sigoff + VIGIK_SIG_LEN) { + + size_t have = (dlen > sigoff) ? dlen - sigoff : 0; + + bool rest_blank = true; + for (uint8_t sec = last + 1; sec < MIFARE_1K_MAXSECTOR; sec++) { + if (vigik_sector_is_blank(dump, dumplen, sec) == false) { + rest_blank = false; + break; + } + } + + // the header's info flag marks the short profile, so a card can say for + // itself that it carries 96 bytes rather than a truncated 128 + if (have == VIGIK_SIG_LEN_ALT && d.vigik->info_flag == VIGIK_INFO_SHORT && rest_blank) { + PrintAndLogEx(INFO, "Signature.......... %zu bytes, " _YELLOW_("short profile") + " ( info flag %02X, not the %u byte one )", + have, VIGIK_INFO_SHORT, VIGIK_SIG_LEN); + } else { + const char *why = _YELLOW_("sectors missing from the dump"); + if (rest_blank) { + why = _YELLOW_("and every later sector is factory blank"); + } + PrintAndLogEx(INFO, "Signature.......... %zu of %u bytes, %s", have, VIGIK_SIG_LEN, why); + } + } + + vigik_annotate(d.vigik); + free(d.bytes); + return PM3_SUCCESS; +} diff --git a/client/src/parsers/parsevigik.h b/client/src/parsers/parsevigik.h new file mode 100644 index 000000000..fc46377c2 --- /dev/null +++ b/client/src/parsers/parsevigik.h @@ -0,0 +1,54 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// VIGIK PACS parser for MIFARE Classic dumps +//----------------------------------------------------------------------------- + +#ifndef PARSEVIGIK_H__ +#define PARSEVIGIK_H__ + +#include "common.h" +#include "protocol_vigik.h" + +// MAD application ids the VIGIK scheme claims +#define VIGIK_MAD_AID 0x4910 +#define VIGIK_MAD_AID_ALT 0x4916 +#define VIGIK_MAD_AID_ALT2 0x4915 + +// A key slot the schema does not pin down. Not a valid 48 bit key, so it can +// never collide with one read off a card. +#define VIGIK_KEY_ANY 0xFFFFFFFFFFFFFFFFULL + +// Name of the VIGIK family system whose key layout this dump matches, NULL when +// none does. The key sets below are static across every card of a given system, +// so a full match identifies it outright. +const char *vigik_detect_schema(const uint8_t *dump, size_t dumplen); + +// True when this dump carries the VIGIK application in its MAD, or its keys +// match a known VIGIK family schema +bool is_valid_vigik_card(const uint8_t *dump, size_t dumplen); + +// Collect the VIGIK sectors out of a whole card dump and print them +int vigik_parser_parse(const uint8_t *dump, size_t dumplen); + +// Lower level helpers, on an already assembled VIGIK structure +const char *vigik_get_service(uint16_t service_code); +int vigik_verify(mfc_vigik_t *d); +int vigik_annotate(mfc_vigik_t *d); + +// Recover and check the signature of a known good expired card +int vigik_selftest(void); + +#endif diff --git a/client/src/pm3.c b/client/src/pm3.c index 1c4088305..76df67ac2 100644 --- a/client/src/pm3.c +++ b/client/src/pm3.c @@ -27,6 +27,7 @@ #include "util_posix.h" #include "comms.h" #include "preferences.h" +#include "flash.h" pm3_device_t *pm3_open(const char *port) { pm3_init(); @@ -92,3 +93,24 @@ const char *pm3_grabbed_output_get(pm3_device_t *dev) { pm3_device_t *pm3_get_current_dev(void) { return g_session.current_device; } + +int pm3_flash(const char *port, const char *const *images, int nimages, + bool unlock_bootloader, bool force) { + if ((port == NULL) || (images == NULL) || (nimages < 1) || (nimages > FLASH_MAX_FILES)) { + return PM3_EINVARG; + } + + const char *files[FLASH_MAX_FILES] = {0}; + for (int i = 0; i < nimages; ++i) { + if (images[i] == NULL) { + return PM3_EINVARG; + } + files[i] = images[i]; + } + + // Don't send CMD_QUIT_SESSION — we're about to reset into bootrom. + if (g_session.pm3_present) { + CloseProxmark(g_session.current_device); + } + return flash_pm3((char *)port, (uint8_t)nimages, files, unlock_bootloader, force); +} diff --git a/client/src/pm3line.c b/client/src/pm3line.c index 51d03b72e..d90e7108f 100644 --- a/client/src/pm3line.c +++ b/client/src/pm3line.c @@ -21,6 +21,9 @@ #include // for Mingw readline and for getline #include #include +#ifndef _WIN32 +#include // write, isatty, STDOUT_FILENO +#endif #if defined(HAVE_READLINE) #include #include @@ -31,6 +34,9 @@ #include "pm3_cmd.h" #include "ui.h" // g_session #include "util.h" // str_ndup +#include "frame_data2.h" // fx_terminal_restore + +static void pm3line_claim_signals(void); #if defined(HAVE_READLINE) @@ -77,6 +83,13 @@ static char **rl_command_completion(const char *text, int start, int end) { return rl_completion_matches(text, rl_command_generator); } +static int (*gs_check_hook)(void) = NULL; + +static int pm3line_startup_hook(void) { + pm3line_claim_signals(); + return 0; +} + #elif defined(HAVE_LINENOISE) static void ln_command_completion(const char *text, linenoiseCompletions *lc) { const char *prev_match = ""; @@ -113,6 +126,9 @@ static void ln_command_completion(const char *text, linenoiseCompletions *lc) { } #endif // HAVE_READLINE +static volatile sig_atomic_t gs_sigint_caught = 0; +static volatile sig_atomic_t gs_at_prompt = 0; + # if defined(_WIN32) /* static bool WINAPI terminate_handler(DWORD t) { @@ -125,13 +141,40 @@ static bool WINAPI terminate_handler(DWORD t) { */ # else static struct sigaction gs_old_sigint_action; +static struct sigaction gs_old_sigtstp_action; +static volatile sig_atomic_t gs_echo_ctrl_c = 0; +static void sigtstp_handler(int signum); static void sigint_handler(int signum) { switch (signum) { case SIGINT: { - sigaction(SIGINT, &gs_old_sigint_action, NULL); - pm3line_flush_history(); - kill(0, SIGINT); + // Second CTRL-C. The graceful path did not take, restore the + // default disposition and let this one through. + if (gs_sigint_caught) { + fx_terminal_restore(); + sigaction(SIGINT, &gs_old_sigint_action, NULL); + raise(SIGINT); + break; + } + // Only set a flag here. Saving the history means malloc and stdio, + // neither is safe to call from a signal handler in a threaded + // client. write() is, and the terminal no longer echoes the + // character for us since readline turned ECHO off + gs_sigint_caught = 1; + + if (gs_echo_ctrl_c) { + static const char at_prompt[] = "^C"; + // the terminal is out of raw mode while a command runs, so it + // echoed the ^C itself. Only say what happens next + static const char in_command[] = "\nquitting once this command is done. CTRL-C again to force\n"; + ssize_t ignored; + if (gs_at_prompt) { + ignored = write(STDOUT_FILENO, at_prompt, sizeof(at_prompt) - 1); + } else { + ignored = write(STDOUT_FILENO, in_command, sizeof(in_command) - 1); + } + (void) ignored; + } break; } default: { @@ -140,24 +183,146 @@ static void sigint_handler(int signum) { } } +// CTRL-Z. Put the terminal back the way the shell expects it, stop for real +// on this thread, and set the line editor up again once we are continued +static void sigtstp_handler(int signum) { + + if (signum != SIGTSTP) { + return; + } + + int at_prompt = gs_at_prompt; + (void) at_prompt; + + fx_terminal_restore(); + +#if defined(HAVE_READLINE) + if (at_prompt) { + rl_cleanup_after_signal(); + } #endif + sigaction(SIGTSTP, &gs_old_sigtstp_action, NULL); + + sigset_t set; + sigprocmask(SIG_BLOCK, NULL, &set); + sigdelset(&set, SIGTSTP); + + raise(SIGTSTP); + + // the signal raised above is blocked while we are inside the handler, + // unblocking it is what stops us. We resume here on SIGCONT + sigprocmask(SIG_SETMASK, &set, NULL); + + pm3line_claim_signals(); + fx_terminal_resume(); + +#if defined(HAVE_READLINE) + if (at_prompt) { + rl_reset_after_signal(); + } +#endif +} + +// Leave the terminal usable when the client is killed instead of quit +static void sigfatal_handler(int signum) { + + fx_terminal_restore(); + +#if defined(HAVE_READLINE) + if (gs_at_prompt) { + rl_cleanup_after_signal(); + } +#endif + + signal(signum, SIG_DFL); + raise(signum); +} + +static void claim_one_signal(int signum, void (*handler)(int)) { + + struct sigaction current; + if (sigaction(signum, NULL, ¤t) != 0) { + return; + } + + if (current.sa_handler == handler) { + return; + } + + struct sigaction action; + memset(&action, 0, sizeof(action)); + action.sa_handler = handler; + sigaction(signum, &action, NULL); +} + +#endif + +// Readline answers a caught signal by cleaning up, re-raising it and then +// reinstalling its handler. In a threaded client that re-raise lands on +// whichever handler is installed at that instant, which can be readline's own +// again, and the cycle repeats. Measured on CTRL-C and CTRL-Z alike, one +// keypress gave a dozen echoes and a coin flip over whether it did anything. +// So the client owns them, and takes them back from anything that grabs one, +// like the flasher progress bar, which installs a handler it never restores +static void pm3line_claim_signals(void) { +# if !defined(_WIN32) + claim_one_signal(SIGINT, &sigint_handler); + claim_one_signal(SIGTSTP, &sigtstp_handler); +# endif +} + void pm3line_install_signals(void) { # if defined(_WIN32) // SetConsoleCtrlHandler((PHANDLER_ROUTINE)terminate_handler, true); # else + gs_echo_ctrl_c = (isatty(STDOUT_FILENO) == 1); + struct sigaction action; memset(&action, 0, sizeof(action)); + action.sa_handler = &sigint_handler; sigaction(SIGINT, &action, &gs_old_sigint_action); + + action.sa_handler = &sigtstp_handler; + sigaction(SIGTSTP, &action, &gs_old_sigtstp_action); + + action.sa_handler = &sigfatal_handler; + sigaction(SIGTERM, &action, NULL); + sigaction(SIGQUIT, &action, NULL); + sigaction(SIGHUP, &action, NULL); # endif #if defined(HAVE_READLINE) - rl_catch_signals = 1; - rl_set_signals(); + // Readline must not catch these itself, see pm3line_claim_signals(). + // rl_catch_sigwinch is a separate flag, window resizes stay with readline + rl_catch_signals = 0; + rl_startup_hook = pm3line_startup_hook; #endif // HAVE_READLINE } +#if defined(HAVE_READLINE) +// readline calls this roughly ten times a second while it waits for input +static int pm3line_event_hook(void) { + + pm3line_claim_signals(); + + if (gs_sigint_caught) { + // Drop the line being edited and make readline() return, so the caller + // reaches the normal shutdown instead of dying inside a handler + rl_free_line_state(); + rl_replace_line("", 0); + rl_done = 1; + return 0; + } + + if (gs_check_hook) { + return gs_check_hook(); + } + return 0; +} +#endif // HAVE_READLINE + void pm3line_init(void) { #if defined(HAVE_READLINE) || defined(HAVE_LINENOISE) // Build the completion vocabulary from the live command tree @@ -175,8 +340,6 @@ void pm3line_init(void) { rl_getc_function = getc; #endif - pm3line_install_signals(); - #ifdef RL_STATE_READCMD rl_extend_line_buffer(1024); #endif // RL_STATE_READCMD @@ -184,18 +347,50 @@ void pm3line_init(void) { linenoiseInstallWindowChangeHandler(); linenoiseSetCompletionCallback(ln_command_completion); #endif // HAVE_READLINE + + pm3line_install_signals(); } char *pm3line_read(const char *s) { + + pm3line_claim_signals(); + + // CTRL-C already asked for a shutdown, do not put up another prompt. + // NULL is what CTRL-D returns, the caller exits cleanly on it and that + // path flushes the history + if (gs_sigint_caught) { + return NULL; + } + + gs_at_prompt = 1; + #if defined(HAVE_READLINE) - return readline(s); + char *line = readline(s); + gs_at_prompt = 0; + if (gs_sigint_caught) { + free(line); + return NULL; + } + return line; #elif defined(HAVE_LINENOISE) - return linenoise(s); + char *line = linenoise(s); + gs_at_prompt = 0; + if (gs_sigint_caught) { + free(line); + return NULL; + } + return line; #else printf("%s", s); // MinGW/ProxSpace builds do not provide getline() in this fallback path. char input[1024] = {0}; if (fgets(input, sizeof(input), stdin) == NULL) { + gs_at_prompt = 0; + return NULL; + } + + gs_at_prompt = 0; + if (gs_sigint_caught) { return NULL; } @@ -256,10 +451,20 @@ void pm3line_add_history(const char *line) { // add if not identical to latest recorded line if ((!entry) || (strcmp(entry->line, line) != 0)) { add_history(line); + // keep the file in sync, so a crash or a kill -9 does not take the + // history with it. append_history fails when the file is not there yet + if (g_session.history_path) { + if (append_history(1, g_session.history_path) != 0) { + write_history(g_session.history_path); + } + } } #elif defined(HAVE_LINENOISE) // linenoiseHistoryAdd takes already care of duplicate entries linenoiseHistoryAdd(line); + if (g_session.history_path) { + linenoiseHistorySave(g_session.history_path); + } #else (void) line; #endif @@ -279,7 +484,8 @@ void pm3line_flush_history(void) { void pm3line_check(int (check)(void)) { #if defined(HAVE_READLINE) - rl_event_hook = check; + gs_check_hook = check; + rl_event_hook = pm3line_event_hook; #else check(); #endif diff --git a/client/src/preferences.c b/client/src/preferences.c index 1077b38d1..5fd47fd0e 100644 --- a/client/src/preferences.c +++ b/client/src/preferences.c @@ -59,7 +59,14 @@ static bool setDefaultMqttServer(const char *srv) { return false; } - g_session.mqtt_server = (char *)realloc(g_session.mqtt_server, strlen(srv) + 1); + char *tmp = (char *)realloc(g_session.mqtt_server, strlen(srv) + 1); + if (tmp == NULL) { + // keep the old value. realloc leaves it valid on failure, and dropping it + // would hand every later reader a NULL + PrintAndLogEx(WARNING, "Failed to allocate memory"); + return false; + } + g_session.mqtt_server = tmp; strcpy(g_session.mqtt_server, srv); return true; } @@ -75,7 +82,14 @@ static bool setDefaultMqttPort(const char *port) { return false; } - g_session.mqtt_port = (char *)realloc(g_session.mqtt_port, strlen(port) + 1); + char *tmp = (char *)realloc(g_session.mqtt_port, strlen(port) + 1); + if (tmp == NULL) { + // keep the old value. realloc leaves it valid on failure, and dropping it + // would hand every later reader a NULL + PrintAndLogEx(WARNING, "Failed to allocate memory"); + return false; + } + g_session.mqtt_port = tmp; strcpy(g_session.mqtt_port, port); return true; } @@ -91,7 +105,14 @@ static bool setDefaultMqttTopic(const char *topic) { return false; } - g_session.mqtt_topic = (char *)realloc(g_session.mqtt_topic, strlen(topic) + 1); + char *tmp = (char *)realloc(g_session.mqtt_topic, strlen(topic) + 1); + if (tmp == NULL) { + // keep the old value. realloc leaves it valid on failure, and dropping it + // would hand every later reader a NULL + PrintAndLogEx(WARNING, "Failed to allocate memory"); + return false; + } + g_session.mqtt_topic = tmp; strcpy(g_session.mqtt_topic, topic); return true; } @@ -343,7 +364,7 @@ void preferences_load_callback(json_t *root) { int b1; int i1; const char *s1; - char tempStr [500]; // to use str_lower() since json unpack uses const char * + char tempStr [500] = {0}; // Logging Level if (json_unpack_ex(root, &up_error, 0, "{s:s}", "client.debug.level", &s1) == 0) { diff --git a/client/src/proxmark3.c b/client/src/proxmark3.c index dca86c52b..7e76b948d 100644 --- a/client/src/proxmark3.c +++ b/client/src/proxmark3.c @@ -982,7 +982,9 @@ finish: return ret; } -static int flash_pm3(char *serial_port_name, uint8_t num_files, const char *filenames[FLASH_MAX_FILES], bool can_write_bl, bool force) { +#endif //LIBPM3 + +int flash_pm3(char *serial_port_name, uint8_t num_files, const char *filenames[], bool can_write_bl, bool force) { int ret = PM3_EUNDEF; flash_file_t files[FLASH_MAX_FILES] = {0}; @@ -994,14 +996,19 @@ static int flash_pm3(char *serial_port_name, uint8_t num_files, const char *file } for (int i = 0 ; i < num_files; ++i) { - char *path; - ret = searchFile(&path, FIRMWARES_SUBDIR, filenames[i], ".elf", true); - if (ret != PM3_SUCCESS) { - ret = searchFile(&path, BOOTROM_SUBDIR, filenames[i], ".elf", true); - } - if (ret != PM3_SUCCESS) { - // Last try, let the error msg be displayed if not found - ret = searchFile(&path, FULLIMAGE_SUBDIR, filenames[i], ".elf", false); + char *path = NULL; + // Don't let searchFile append ".elf" onto an already-copied path. + if (path_is_regular_file(filenames[i])) { + path = str_dup(filenames[i]); + ret = (path == NULL) ? PM3_EMALLOC : PM3_SUCCESS; + } else { + ret = searchFile(&path, FIRMWARES_SUBDIR, filenames[i], ".elf", true); + if (ret != PM3_SUCCESS) { + ret = searchFile(&path, BOOTROM_SUBDIR, filenames[i], ".elf", true); + } + if (ret != PM3_SUCCESS) { + ret = searchFile(&path, FULLIMAGE_SUBDIR, filenames[i], ".elf", false); + } } if (ret != PM3_SUCCESS) { goto finish2; @@ -1083,6 +1090,7 @@ finish2: return ret; } +#ifndef LIBPM3 static int reboot_bootloader_pm3(char *serial_port_name) { if (serial_port_name == NULL) { PrintAndLogEx(ERR, "You must specify a port.\n"); diff --git a/client/src/proxmark3.h b/client/src/proxmark3.h index 25c7c8059..85ad35da9 100644 --- a/client/src/proxmark3.h +++ b/client/src/proxmark3.h @@ -60,6 +60,7 @@ extern "C" { #endif int push_cmdscriptfile(char *path, bool stayafter); +int flash_pm3(char *serial_port_name, uint8_t num_files, const char *filenames[], bool can_write_bl, bool force); const char *get_my_executable_path(void); const char *get_my_executable_directory(void); const char *get_my_user_directory(void); diff --git a/client/src/scripting.c b/client/src/scripting.c index efe75ec44..8c8acfd2f 100644 --- a/client/src/scripting.c +++ b/client/src/scripting.c @@ -418,8 +418,8 @@ static int l_kbd_enter_pressed(lua_State *L) { * lua-scripts to do stuff like "core.console('hf mf mifare')" * core.console(cmd [, capture [, quiet]]) * - * Same idea as the python binding - * `capture` hands the command's output back as a string, + * Same idea as the python binding + * `capture` hands the command's output back as a string, * `quiet` keeps it off the// terminal * @param L * @return diff --git a/client/src/uart/ble_posix.c b/client/src/uart/ble_posix.c index 588c3f5e1..fda5f6216 100644 --- a/client/src/uart/ble_posix.c +++ b/client/src/uart/ble_posix.c @@ -17,13 +17,17 @@ #include #include +#include // strcasecmp #include #include #include +#include #include #include #include #include +#include +#include #include "ui.h" // PrintAndLogEx #include "pm3_cmd.h" // PM3_* (only for messaging parity; returns are 0/neg here) @@ -183,14 +187,217 @@ static int att_subscribe(int fd, uint16_t cccd_handle) { return (n >= 1) ? 0 : -1; } -int ble_connect(const char *mac, uint16_t chr_uuid16, ble_conn_t *conn) { - memset(conn, 0, sizeof(*conn)); - conn->fd = -1; +// ---- name -> address resolution (LE discovery via the BlueZ mgmt API) ---- +// AD types carrying the device name (Core Spec, Supplement, Part A). +#define BLE_ADV_NAME_SHORT 0x08 +#define BLE_ADV_NAME_FULL 0x09 + +static long ble_now_ms(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return ts.tv_sec * 1000L + ts.tv_nsec / 1000000L; +} + +// Walk the AD structures of one advertising/scan-response report, looking for a +// Local Name (complete or shortened) that equals `want` (case-insensitive). +// Copies whatever name it finds into `found` for logging. Returns 1 on match. +static int ble_ad_name_matches(const char *want, const uint8_t *ad, size_t adlen, + char *found, size_t foundsz) { + size_t i = 0; + while (i < adlen) { + uint8_t flen = ad[i]; // length byte counts the type + value + if (flen == 0) break; // padding -> end of meaningful data + if (i + 1 + flen > adlen) break; // truncated field -> stop, don't overrun + uint8_t type = ad[i + 1]; + if (type == BLE_ADV_NAME_FULL || type == BLE_ADV_NAME_SHORT) { + size_t nlen = flen - 1; + if (nlen >= foundsz) nlen = foundsz - 1; + memcpy(found, &ad[i + 2], nlen); + found[nlen] = 0; + if (strcasecmp(found, want) == 0) return 1; + } + i += flen + 1; + } + return 0; +} + +// Print an exact, copy-pasteable command to grant the capabilities the LE scan +// needs, using the running binary's own path so it survives rebuilds/renames. +// Also points at the no-privilege alternative (connect by address). +static void ble_print_caps_hint(void) { + char exe[4096]; + ssize_t n = readlink("/proc/self/exe", exe, sizeof(exe) - 1); + if (n > 0) { + exe[n] = 0; + PrintAndLogEx(INFO, "BLE: scanning by name needs extra privileges. Grant them once with:"); + PrintAndLogEx(INFO, " " _YELLOW_("sudo setcap 'cap_net_raw,cap_net_admin+eip' %s"), exe); + } else { + PrintAndLogEx(INFO, "BLE: scanning by name needs " _YELLOW_("CAP_NET_RAW+CAP_NET_ADMIN") + " on the client binary (or run with sudo)"); + } + PrintAndLogEx(INFO, " or connect by address instead: " _YELLOW_("-p ble:") " (no extra privileges)"); +} + +// ---- BlueZ management (mgmt) API ---- +// The legacy hci_le_set_scan_* path is deprecated and returns EIO on many current +// controllers/kernels; discovery now goes through the mgmt control channel (the +// same interface btmgmt and bluetoothd use). mgmt.h isn't shipped by +// libbluetooth-dev, so the small slice of ABI we need is defined here. Still needs +// CAP_NET_RAW (socket) + CAP_NET_ADMIN (discovery) - same as before. +#define MGMT_OP_SET_POWERED 0x0005 +#define MGMT_OP_START_DISCOVERY 0x0023 +#define MGMT_OP_STOP_DISCOVERY 0x0024 +#define MGMT_EV_CMD_COMPLETE 0x0001 +#define MGMT_EV_CMD_STATUS 0x0002 +#define MGMT_EV_DEVICE_FOUND 0x0012 +#define MGMT_ADDR_LE 0x06 // (1<<1)|(1<<2): LE public + LE random +#define MGMT_STATUS_NOT_POWERED 0x11 +#define MGMT_STATUS_PERMISSION_DENIED 0x14 + +struct mgmt_hdr { + uint16_t opcode; + uint16_t index; + uint16_t len; +} __attribute__((packed)); + +struct mgmt_ev_device_found { + bdaddr_t bdaddr; + uint8_t addr_type; + int8_t rssi; + uint32_t flags; + uint16_t eir_len; + uint8_t eir[0]; +} __attribute__((packed)); + +// Send one mgmt command (header + up to 8 bytes of parameters). Returns 0 on success. +static int mgmt_send_cmd(int fd, uint16_t opcode, uint16_t index, const void *param, uint16_t plen) { + uint8_t buf[sizeof(struct mgmt_hdr) + 8]; + if (plen > 8) return -1; + struct mgmt_hdr *h = (struct mgmt_hdr *)buf; + h->opcode = htobs(opcode); + h->index = htobs(index); + h->len = htobs(plen); + if (plen && param) memcpy(buf + sizeof(*h), param, plen); + ssize_t w = write(fd, buf, sizeof(*h) + plen); + return (w == (ssize_t)(sizeof(*h) + plen)) ? 0 : -1; +} + +int ble_resolve_name(const char *name, char *out_mac, size_t out_mac_sz, int timeout_ms) { + if (name == NULL || out_mac == NULL || out_mac_sz < 18) return -1; + out_mac[0] = 0; + + int index = hci_get_route(NULL); + if (index < 0) index = 0; // default to hci0 if none is "up" + + int fd = socket(AF_BLUETOOTH, SOCK_RAW | SOCK_CLOEXEC, BTPROTO_HCI); + if (fd < 0) { + PrintAndLogEx(ERR, "BLE: cannot open mgmt socket (%s)", strerror(errno)); + if (errno == EPERM || errno == EACCES) ble_print_caps_hint(); + return -1; + } + + struct sockaddr_hci sa = {0}; + sa.hci_family = AF_BLUETOOTH; + sa.hci_dev = HCI_DEV_NONE; + sa.hci_channel = HCI_CHANNEL_CONTROL; + if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0) { + PrintAndLogEx(ERR, "BLE: cannot bind mgmt control channel (%s)", strerror(errno)); + if (errno == EPERM || errno == EACCES) ble_print_caps_hint(); + close(fd); + return -1; + } + + // Power the controller on (idempotent) so discovery works even when bluetoothd + // is stopped and the adapter was left down. + uint8_t on = 0x01; + mgmt_send_cmd(fd, MGMT_OP_SET_POWERED, (uint16_t)index, &on, 1); + + uint8_t scan_type = MGMT_ADDR_LE; + if (mgmt_send_cmd(fd, MGMT_OP_START_DISCOVERY, (uint16_t)index, &scan_type, 1) != 0) { + PrintAndLogEx(ERR, "BLE: cannot start LE discovery (%s)", strerror(errno)); + close(fd); + return -1; + } + + PrintAndLogEx(INFO, "BLE: scanning up to " _YELLOW_("%d") " ms for " _YELLOW_("%s") " ...", timeout_ms, name); + + int rc = -1; + char nm[64]; + long deadline = ble_now_ms() + timeout_ms; + uint8_t buf[512]; + + while (ble_now_ms() < deadline) { + long rem = deadline - ble_now_ms(); + if (rem <= 0) break; + struct timeval tv = { .tv_sec = rem / 1000, .tv_usec = (rem % 1000) * 1000 }; + fd_set rs; + FD_ZERO(&rs); + FD_SET(fd, &rs); + int s = select(fd + 1, &rs, NULL, NULL, &tv); + if (s < 0) { if (errno == EINTR) break; break; } + if (s == 0) break; + + ssize_t n = read(fd, buf, sizeof(buf)); + if (n < (ssize_t)sizeof(struct mgmt_hdr)) continue; + struct mgmt_hdr *h = (struct mgmt_hdr *)buf; + uint16_t ev = btohs(h->opcode); + uint16_t idx = btohs(h->index); + uint16_t len = btohs(h->len); + if ((size_t)n < sizeof(*h) + len) continue; + if (idx != (uint16_t)index) continue; // event for a different controller + uint8_t *pl = buf + sizeof(*h); + + if (ev == MGMT_EV_DEVICE_FOUND) { + if (len < sizeof(struct mgmt_ev_device_found)) continue; + struct mgmt_ev_device_found *df = (struct mgmt_ev_device_found *)pl; + uint16_t eir_len = btohs(df->eir_len); + if (sizeof(*df) + eir_len > len) eir_len = (uint16_t)(len - sizeof(*df)); + if (ble_ad_name_matches(name, df->eir, eir_len, nm, sizeof(nm))) { + ba2str(&df->bdaddr, out_mac); + PrintAndLogEx(SUCCESS, "BLE: found " _GREEN_("%s") " at " _GREEN_("%s"), nm, out_mac); + rc = 0; + break; + } + } else if ((ev == MGMT_EV_CMD_STATUS || ev == MGMT_EV_CMD_COMPLETE) && len >= 3) { + uint16_t cmd = get16(pl); // originating command opcode + uint8_t status = pl[2]; + if (cmd == MGMT_OP_START_DISCOVERY && status != 0) { + if (status == MGMT_STATUS_PERMISSION_DENIED) { + ble_print_caps_hint(); + break; + } else if (status == MGMT_STATUS_NOT_POWERED) { + PrintAndLogEx(ERR, "BLE: adapter not powered (check " _YELLOW_("rfkill") " / bluetooth service)"); + break; + } + // Busy (0x0A) or similar: a scan may already be running - keep listening. + PrintAndLogEx(INFO, "BLE: start-discovery returned mgmt status 0x%02x, listening anyway", status); + } + } + } + + uint8_t st = MGMT_ADDR_LE; + mgmt_send_cmd(fd, MGMT_OP_STOP_DISCOVERY, (uint16_t)index, &st, 1); + close(fd); + + if (rc != 0) + PrintAndLogEx(ERR, "BLE: no advertising device named " _YELLOW_("%s") " seen within %d ms", name, timeout_ms); + return rc; +} + +// Retry the L2CAP connect briefly: a create-connection issued as an LE scan +// tears down can be refused, and the peer may be between advertising events. +#define BLE_CONNECT_TRIES 6 +#define BLE_CONNECT_BACKOFF_MS 150 + +// Open an L2CAP/ATT socket and connect to `mac`. Returns the fd on success, +// -1 on a retryable connect failure (errno set to the connect error), or +// -2 on a hard setup failure (socket/bind), which is already logged. +static int ble_l2cap_connect(const char *mac) { int fd = socket(AF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_L2CAP); if (fd < 0) { PrintAndLogEx(ERR, "BLE: cannot create L2CAP socket (%s)", strerror(errno)); - return -1; + return -2; } // Enlarge the kernel RX buffer so bursts of notifications queue instead of @@ -206,7 +413,7 @@ int ble_connect(const char *mac, uint16_t chr_uuid16, ble_conn_t *conn) { if (bind(fd, (struct sockaddr *)&src, sizeof(src)) < 0) { PrintAndLogEx(ERR, "BLE: bind failed (%s)", strerror(errno)); close(fd); - return -1; + return -2; } struct sockaddr_l2 dst = {0}; @@ -215,8 +422,31 @@ int ble_connect(const char *mac, uint16_t chr_uuid16, ble_conn_t *conn) { str2ba(mac, &dst.l2_bdaddr); dst.l2_cid = htobs(ATT_CID); if (connect(fd, (struct sockaddr *)&dst, sizeof(dst)) < 0) { - PrintAndLogEx(ERR, "BLE: cannot connect to " _YELLOW_("%s") " (%s)", mac, strerror(errno)); + int e = errno; // close() may clobber errno; preserve it for the caller close(fd); + errno = e; + return -1; + } + return fd; +} + +int ble_connect(const char *mac, uint16_t chr_uuid16, ble_conn_t *conn) { + memset(conn, 0, sizeof(*conn)); + conn->fd = -1; + + int fd = -1; + int last_errno = 0; + for (int attempt = 1; attempt <= BLE_CONNECT_TRIES; attempt++) { + fd = ble_l2cap_connect(mac); + if (fd >= 0) break; + if (fd == -2) return -1; // hard setup failure, already logged + last_errno = errno; // retryable connect failure + if (attempt < BLE_CONNECT_TRIES) { + usleep(BLE_CONNECT_BACKOFF_MS * 1000); + } + } + if (fd < 0) { + PrintAndLogEx(ERR, "BLE: cannot connect to " _YELLOW_("%s") " (%s)", mac, strerror(last_errno)); return -1; } diff --git a/client/src/uart/ble_posix.h b/client/src/uart/ble_posix.h index d67487a7a..4ed3bfa15 100644 --- a/client/src/uart/ble_posix.h +++ b/client/src/uart/ble_posix.h @@ -39,6 +39,16 @@ typedef struct { size_t leftover_len; } ble_conn_t; +// Default time budget for a name -> address scan. +#define BLE_SCAN_TIMEOUT_MS 8000 + +// Resolve an advertised device name to its LE address via LE discovery (BlueZ mgmt API). +// Matches the Complete (0x09) or Shortened (0x08) Local Name, case-insensitively. +// On success writes "XX:XX:XX:XX:XX:XX" into out_mac (needs >= 18 bytes) and +// returns 0; returns negative on error or if no such device is seen in time. +// Needs CAP_NET_RAW+CAP_NET_ADMIN (mgmt discovery), i.e. more privilege than connect. +int ble_resolve_name(const char *name, char *out_mac, size_t out_mac_sz, int timeout_ms); + // Connect to `mac` (LE public), discover the SPP char, subscribe to notifications. // `chr_uuid16` selects the data characteristic (pass BLE_SPP_CHR_UUID16). // Returns 0 on success (conn filled), negative on error. On error conn->fd == -1. diff --git a/client/src/uart/uart_posix.c b/client/src/uart/uart_posix.c index 3111eb466..b0240edd9 100644 --- a/client/src/uart/uart_posix.c +++ b/client/src/uart/uart_posix.c @@ -39,6 +39,7 @@ #include #ifdef HAVE_BLUEZ +#include // isxdigit (ble: name vs address check) #include #include #include "ble_posix.h" @@ -115,6 +116,22 @@ uint32_t uart_get_timeouts(void) { return newtimeout_value; } +#ifdef HAVE_BLUEZ +// True if `s` is a plain 6-octet BD address "XX:XX:XX:XX:XX:XX" (hex, colon-sep). +// Used to tell a literal address from a device name after the "ble:" prefix. +static bool uart_is_bdaddr(const char *s) { + if (s == NULL || strlen(s) != 17) return false; + for (int i = 0; i < 17; i++) { + if ((i % 3) == 2) { + if (s[i] != ':') return false; + } else if (isxdigit((unsigned char)s[i]) == 0) { + return false; + } + } + return true; +} +#endif // HAVE_BLUEZ + serial_port uart_open(const char *pcPortName, uint32_t speed, bool slient) { serial_port_unix_t_t *sp = calloc(sizeof(serial_port_unix_t_t), sizeof(uint8_t)); @@ -416,8 +433,22 @@ serial_port uart_open(const char *pcPortName, uint32_t speed, bool slient) { free(sp); return INVALID_SERIAL_PORT; } - // pcPortName is "ble:" - if (ble_connect(pcPortName + 4, BLE_SPP_CHR_UUID16, bc) != 0) { + + // pcPortName is "ble:". If the part after the prefix is + // a literal BD address use it as-is; otherwise treat it as an advertised + // device name and resolve it to an address via an active LE scan. + const char *ble_arg = pcPortName + 4; + char resolved[18]; + if (uart_is_bdaddr(ble_arg) == false) { + if (ble_resolve_name(ble_arg, resolved, sizeof(resolved), BLE_SCAN_TIMEOUT_MS) != 0) { + free(bc); + free(sp); + return INVALID_SERIAL_PORT; + } + ble_arg = resolved; + } + + if (ble_connect(ble_arg, BLE_SPP_CHR_UUID16, bc) != 0) { free(bc); free(sp); return INVALID_SERIAL_PORT; diff --git a/client/src/ui.c b/client/src/ui.c index 1a5f81a7b..265fbd598 100644 --- a/client/src/ui.c +++ b/client/src/ui.c @@ -288,7 +288,7 @@ void PrintAndLogEx(logLevel_t level, const char *fmt, ...) { char *token = NULL; char *tmp_ptr = NULL; FILE *stream = stdout; - const char *spinner[] = {_YELLOW_("[\\]"), _YELLOW_("[|]"), _YELLOW_("[/]"), _YELLOW_("[-]")}; + const char *spinner[] = {_YELLOW_("[\\]") " ", _YELLOW_("[|]") " ", _YELLOW_("[/]") " ", _YELLOW_("[-]") " "}; const char *spinner_emoji[] = {" :clock1: ", " :clock2: ", " :clock3: ", " :clock4: ", " :clock5: ", " :clock6: ", " :clock7: ", " :clock8: ", " :clock9: ", " :clock10: ", " :clock11: ", " :clock12: " }; diff --git a/client/src/util.c b/client/src/util.c index 8151dcfe9..e8fb7c5eb 100644 --- a/client/src/util.c +++ b/client/src/util.c @@ -36,7 +36,7 @@ #include "comms.h" // SendCommandNG / WaitForResponseTimeout (set_rgb) #include "pm3_cmd.h" // CMD_PM5_RGB_SET -#define UTIL_BUFFER_SIZE_SPRINT 8196 +#define UTIL_BUFFER_SIZE_SPRINT 16384 // global client debug variable uint8_t g_debugMode = 0; // global client enable/disable printing/logging/grabbing variable @@ -742,6 +742,38 @@ bool bytes_equal_not_null(const void *a, size_t a_len, const void *b, size_t b_l return a_len == b_len && a != NULL && b != NULL && memcmp(a, b, a_len) == 0; } +// Append a formatted string to buf without ever writing past buf_len. +// Returns the length of the resulting string. +// buf must already be a valid NULL terminated string. +size_t str_append(char *buf, size_t buf_len, const char *fmt, ...) { + + if (buf == NULL || buf_len == 0 || fmt == NULL) { + return 0; + } + + size_t len = strlen(buf); + + // no room for another character and its terminator + if (len + 1 >= buf_len) { + return len; + } + + size_t avail = buf_len - len; + + va_list args; + va_start(args, fmt); + int n = vsnprintf(buf + len, avail, fmt, args); + va_end(args); + + if (n < 0) { + // encoding error. leave the string as we found it + buf[len] = '\0'; + return len; + } + + return ((size_t)n < avail) ? (len + (size_t)n) : (buf_len - 1); +} + int buffer_append_bytes_with_offset(uint8_t *buf, size_t buf_len, size_t *offset, const void *data, size_t data_len) { if (buf == NULL || offset == NULL || (data_len > 0 && data == NULL)) { return PM3_EINVARG; diff --git a/client/src/util.h b/client/src/util.h index 047d24269..adf5876fa 100644 --- a/client/src/util.h +++ b/client/src/util.h @@ -107,6 +107,7 @@ int hex_to_bytes(const char *hexValue, uint8_t *bytesValue, size_t maxBytesValue int parse_uint32_hex_or_dec(const char *text, uint32_t *out); bool bytes_equal_not_null(const void *a, size_t a_len, const void *b, size_t b_len); int buffer_append_bytes_with_offset(uint8_t *buf, size_t buf_len, size_t *offset, const void *data, size_t data_len); +size_t str_append(char *buf, size_t buf_len, const char *fmt, ...); void num_to_bytebits(uint64_t n, size_t len, uint8_t *dest); void num_to_bytebitsLSBF(uint64_t n, size_t len, uint8_t *dest); void bytes_to_bytebits(const void *src, const size_t srclen, void *dest); diff --git a/common/lfdemod.c b/common/lfdemod.c index 33ee616cc..77c3f6308 100644 --- a/common/lfdemod.c +++ b/common/lfdemod.c @@ -547,13 +547,16 @@ size_t pskFindFirstPhaseShift(const uint8_t *samples, size_t size, uint8_t *curP uint16_t avgWaveVal = 0, lastAvgWaveVal; size_t i = waveStart, waveEnd, waveLenCnt, firstFullWave; + // waveStart starts as wherever the caller began looking, so the first length is part of a wave, + // not a wave, and judging it accepts a shift that is not there. Baseline on the first peak. + bool wave_from_peak = false; for (; i < loopCnt; i++) { // find peak // was "samples[i] + fc" but why? must have been used to weed out some wave error... removed.. if (samples[i] < samples[i + 1] && samples[i + 1] >= samples[i + 2]) { waveEnd = i + 1; if (g_debugMode == 2) prnt("DEBUG PSK: waveEnd: %zu, waveStart: %zu", waveEnd, waveStart); waveLenCnt = waveEnd - waveStart; - if (waveLenCnt > fc && waveStart > fc && !(waveLenCnt > fc + 8)) { //not first peak and is a large wave but not out of whack + if (wave_from_peak && waveLenCnt > fc && waveStart > fc && !(waveLenCnt > fc + 8)) { //not first peak and is a large wave but not out of whack lastAvgWaveVal = avgWaveVal / (waveLenCnt); firstFullWave = waveStart; *fullWaveLen = waveLenCnt; @@ -562,6 +565,7 @@ size_t pskFindFirstPhaseShift(const uint8_t *samples, size_t size, uint8_t *curP return firstFullWave; } waveStart = i + 1; + wave_from_peak = true; avgWaveVal = 0; } avgWaveVal += samples[i + 2]; @@ -1902,18 +1906,31 @@ int nrzRawDemod(uint8_t *dest, size_t *size, int *clk, const int *invert, int *s if (dest[i] <= low) bit = 0; dest[i] = bit; } - //now demod based on clock (rf/32 = 32 1's for one 1 bit, 32 0's for one 0 bit) + // start on the first level change: it is the earliest sample known to be a + // bit boundary. counting the samples before it as bits rotated the stream + // whenever that edge moved by one, and left startIdx naming no sample size_t lastBit = 0; size_t numBits = 0; + bool anchored = false; for (i = 21; i < *size - 20; i++) { + + bool edge = (dest[i] != dest[i - 1]); + + if (anchored == false) { + if (edge == false) { + continue; + } + *startIdx = (int)i; + if (g_debugMode == 2) prnt("DEBUG NRZ: startIdx %i", *startIdx); + lastBit = i - 1; + anchored = true; + continue; + } + //if transition detected or large number of same bits - store the passed bits - if (dest[i] != dest[i - 1] || (i - lastBit) == (10 * *clk)) { + if (edge || (i - lastBit) == (10 * *clk)) { memset(dest + numBits, dest[i - 1] ^ *invert, (i - lastBit + (*clk / 4)) / *clk); numBits += (i - lastBit + (*clk / 4)) / *clk; - if (lastBit == 0) { - *startIdx = i - (numBits * *clk); - if (g_debugMode == 2) prnt("DEBUG NRZ: startIdx %i", *startIdx); - } lastBit = i - 1; } } @@ -2038,6 +2055,13 @@ static size_t aggregate_bits(uint8_t *dest, size_t size, uint8_t clk, uint8_t in // 0->1 crossing n = (n * fchigh + hclk) / clk; + // A leading run that rounds to no bits is lead-in, not data. Forcing it to one fabricates + // a bit and shifts the word; mid-stream a zero would lose a bit the tag did send. + if (n == 0 && numBits == 0) { + lastval = dest[i]; + continue; + } + if (n == 0) n = 1; @@ -2141,14 +2165,22 @@ int pskRawDemod_ext(uint8_t *dest, size_t *size, int *clock, const int *invert, i = findModStart(dest, *size, fc); //find first phase shift firstFullWave = pskFindFirstPhaseShift(dest, *size, &curPhase, i, fc, &fullWaveLen); - if (firstFullWave == 0) { - // no phase shift detected - could be all 1's or 0's - doesn't matter where we start - // so skip a little to ensure we are past any Start Signal - firstFullWave = 160; - memset(dest, curPhase, firstFullWave / *clock); - } else { - memset(dest, curPhase ^ 1, firstFullWave / *clock); - } + } + + // A first shift less than a bit period in is lead-in, not data. Counting it toggles curPhase + // once too often, and the emitted bit is the running phase, so the rest of the word inverts. + const size_t bit_period = (size_t)(*clock); + if (firstFullWave != 0 && firstFullWave < bit_period) { + curPhase = *invert; + fullWaveLen = 0; + firstFullWave = pskFindFirstPhaseShift(dest, *size, &curPhase, bit_period, fc, &fullWaveLen); + } + + if (firstFullWave == 0) { + // no phase shift detected - could be all 1's or 0's - doesn't matter where we start + // so skip a little to ensure we are past any Start Signal + firstFullWave = 160; + memset(dest, curPhase, firstFullWave / *clock); } else { memset(dest, curPhase ^ 1, firstFullWave / *clock); } diff --git a/common_arm/Hal.cmake b/common_arm/Hal.cmake index 64299887b..7f2faa907 100644 --- a/common_arm/Hal.cmake +++ b/common_arm/Hal.cmake @@ -20,9 +20,11 @@ set_property(CACHE PLATFORM PROPERTY STRINGS "PM3RDV4" "PM3GENERIC" "PM3ICOPYX" +============================================+ | BTADDON | Proxmark3 RDV4 BT add-on | +--------------------------------------------+ +| BWM | PM5 Battery Wireless Mod | ++--------------------------------------------+ ]] set(PLATFORM_EXTRAS "" CACHE STRING "Default PLATFORM_EXTRAS is unset") -set_property(CACHE PLATFORM_EXTRAS PROPERTY STRINGS "BTADDON" "") +set_property(CACHE PLATFORM_EXTRAS PROPERTY STRINGS "BTADDON" "BWM" "") # Skip fpga bit stream files pack to arm's fw? # Some platform is no download in arm side required. @@ -110,6 +112,13 @@ if ("${PLATFORM_EXTRAS_TMP}" MATCHES "BTADDON") list(APPEND PLATFORM_DEFS -DWITH_FPC_USART_HOST) list(REMOVE_ITEM PLATFORM_EXTRAS_TMP "BTADDON") endif () +if ("${PLATFORM_EXTRAS_TMP}" MATCHES "BWM") + if (NOT PLATFORM STREQUAL "PM5") + message(FATAL_ERROR "PLATFORM_EXTRAS token BWM is only valid on PLATFORM=PM5") + endif () + list(APPEND PLATFORM_DEFS -DWITH_BWM_FORWARD) + list(REMOVE_ITEM PLATFORM_EXTRAS_TMP "BWM") +endif () if ("${PLATFORM_EXTRAS_TMP}" MATCHES "FPC_USART_DEV") list(APPEND PLATFORM_DEFS -DWITH_FPC_USART_DEV) list(REMOVE_ITEM PLATFORM_EXTRAS_TMP "FPC_USART_DEV") @@ -151,6 +160,9 @@ endif () if (NOT SKIP_ISO14443a) list(APPEND PLATFORM_DEFS -DWITH_ISO14443a) endif () +if (NOT SKIP_DESFIRE_SIM) + list(APPEND PLATFORM_DEFS -DWITH_DESFIRE_SIM) +endif () if (NOT SKIP_ICLASS) list(APPEND PLATFORM_DEFS -DWITH_ICLASS) endif () diff --git a/common_arm/Makefile.hal b/common_arm/Makefile.hal index a661c58d1..3dd901684 100644 --- a/common_arm/Makefile.hal +++ b/common_arm/Makefile.hal @@ -16,11 +16,11 @@ # Default platform if no platform specified PLATFORM?=PM3RDV4 -# Standalone Mode info (path depends if make is called at top or from armsrc) +# Standalone Mode info (path depends if make is called at top, from armsrc, or from a sibling dir like recovery/bootrom) # Guard Makefile.hal against implicit rules: (with % to avoid being first goal) %/Makefile.hal: ; -include armsrc/Standalone/Makefile.hal --include Standalone/Makefile.hal +-include ../armsrc/Standalone/Makefile.hal ifndef DEFAULT_STANDALONE $(error Could not find armsrc/Standalone/Makefile.hal) endif @@ -71,6 +71,10 @@ or if you have a Proxmark 3 RDV4 with the BT add-on: PLATFORM=PM3RDV4 PLATFORM_EXTRAS=BTADDON +or if you have a Proxmark 5 with the BWM add-on: +PLATFORM=PM5 +PLATFORM_EXTRAS=BWM + Default standalone mode is $(DEFAULT_STANDALONE). To disable standalone modes, set explicitly an empty STANDALONE: STANDALONE= @@ -80,6 +84,7 @@ PLATFORM_SIZE=256 to be warned if the image is too big for your device and you can specify which parts to skip in order to reduce the size: +SKIP_CEP=1 SKIP_LF=1 SKIP_HITAG=1 SKIP_EM4x50=1 @@ -88,6 +93,7 @@ SKIP_ISO15693=1 SKIP_LEGICRF=1 SKIP_ISO14443b=1 SKIP_ISO14443a=1 +SKIP_DESFIRE_SIM=1 SKIP_ICLASS=1 SKIP_FELICA=1 SKIP_NFCBARCODE=1 @@ -184,17 +190,17 @@ else ifeq ($(PLATFORM),PM5) FPGA_BITSTREAMS = fpga_pm3_hf.bit # TODO DXL 虽然可以不把打包比特流,但是还是得把FPGA的版本信息给生成,让EXE依赖。 SKIP_FPGA_EMBED = true # important!!! disable the fpga bit files pack to arm! SKIP_COMPRESSION = true # Skip data section compress. The new mcu has enough flash space. - PLATFORM_DEFS = -DWITH_FLASH -DPM5 -DCHIP_AT32F435_37 -DWITH_BWM_STATUS -DWITH_PM5_PWR_LED -DWITH_PM5_AUTOOFF -DWITH_BWM_LOWBATT_BEEP -DWITH_PM5_LOWBATT_SHUTDOWN # TODO 暂时不要编译i2c -DWITH_SMARTCARD - # Low-battery safety (beep + over-discharge power-off at ~3.3V) is ON by default. - # Opt out via PLATFORM_EXTRAS: - # NO_LOWBATT_SHUTDOWN ===== keep the beep, disable auto power-off ==== - # NO_LOWBATT_BEEP ===== disable the beep (also drops the shutdown poll) ==== + PLATFORM_DEFS = -DPM5 -DCHIP_AT32F435_37 -DWITH_FLASH # TODO 暂时不要编译i2c -DWITH_SMARTCARD PLTNAME = Proxmark5 PLATFORM_FPGA = GW1NR-LV2MG49GC6/i5 else $(error Invalid or empty PLATFORM: $(PLATFORM). $(KNOWN_DEFINITIONS)) endif +ifeq ($(ENABLE_HFMFDESETEST),1) + PLATFORM_DEFS += -DENABLE_HFMFDESETEST +endif + # parsing additional PLATFORM_EXTRAS tokens PLATFORM_EXTRAS_TMP:=$(PLATFORM_EXTRAS) ifneq (,$(findstring SMARTCARD,$(PLATFORM_EXTRAS_TMP))) @@ -223,7 +229,7 @@ ifneq (,$(findstring BWM,$(PLATFORM_EXTRAS_TMP))) ifneq ($(PLATFORM),PM5) $(error PLATFORM_EXTRAS token BWM is only valid on PLATFORM=PM5) endif - PLATFORM_DEFS += -DWITH_BWM_FORWARD + PLATFORM_DEFS += -DWITH_BWM_FORWARD -DWITH_BWM_STATUS -DWITH_PM5_PWR_LED -DWITH_PM5_AUTOOFF -DWITH_BWM_LOWBATT_BEEP -DWITH_PM5_LOWBATT_SHUTDOWN PLATFORM_EXTRAS_TMP := $(strip $(filter-out BWM,$(PLATFORM_EXTRAS_TMP))) endif ifneq (,$(findstring NO_LOWBATT_SHUTDOWN,$(PLATFORM_EXTRAS_TMP))) @@ -245,6 +251,17 @@ ifneq (,$(PLATFORM_EXTRAS_TMP)) $(error Unknown PLATFORM_EXTRAS token(s): $(PLATFORM_EXTRAS_TMP)) endif +# Proxmark5 specific support +ifeq ($(SKIP_CEP),1) + ifneq ($(PLATFORM),PM5) + $(error SKIP_CEP token is only valid on PLATFORM=PM5) + endif +else + ifeq ($(PLATFORM),PM5) + PLATFORM_DEFS += -DWITH_CEP + endif +endif + # common LF support ifneq ($(SKIP_LF),1) PLATFORM_DEFS += -DWITH_LF @@ -278,6 +295,9 @@ endif ifneq ($(SKIP_ISO14443a),1) PLATFORM_DEFS += -DWITH_ISO14443a endif +ifneq ($(SKIP_DESFIRE_SIM),1) + PLATFORM_DEFS += -DWITH_DESFIRE_SIM +endif ifneq ($(SKIP_ICLASS),1) PLATFORM_DEFS += -DWITH_ICLASS endif @@ -326,8 +346,8 @@ ifneq (,$(findstring WITH_FPC_USART_,$(PLATFORM_DEFS))) PLATFORM_DEFS += -DUSART_BAUD_RATE=$(USART_BAUD_RATE) endif -PLATFORM_DEFS_INFO = $(strip $(filter-out STANDALONE%, $(subst -DWITH_,,$(PLATFORM_DEFS)))) -PLATFORM_DEFS_INFO_STANDALONE = $(strip $(subst STANDALONE_,, $(filter STANDALONE%, $(subst -DWITH_,,$(PLATFORM_DEFS))))) +PLATFORM_DEFS_INFO = $(strip $(filter-out STANDALONE%, $(subst -D,,$(subst -DWITH_,,$(PLATFORM_DEFS))))) +PLATFORM_DEFS_INFO_STANDALONE = $(strip $(subst STANDALONE_,, $(filter STANDALONE%, $(subst -D,,$(subst -DWITH_,,$(PLATFORM_DEFS)))))) # Check that only one Standalone mode has been chosen ifneq (,$(word 2, $(PLATFORM_DEFS_INFO_STANDALONE))) diff --git a/common_arm/flash_data/flashmem_core.c b/common_arm/flash_data/flashmem_core.c index beb1e90e6..660052a6d 100644 --- a/common_arm/flash_data/flashmem_core.c +++ b/common_arm/flash_data/flashmem_core.c @@ -106,12 +106,15 @@ uint16_t Flash_WriteData(uint32_t address, uint8_t *in, uint16_t len) { // assumes valid start 256 based 00 address // Start writing flash from the specified location. -// Write FLASH_MEM_BLOCK_SIZE bytes at most each time. If the writing is nearly complete, write it as bytes_remaining bytes. +// Write FLASH_MEM_BLOCK_SIZE bytes at most each time. +// If the writing is nearly complete, write it as bytes_remaining bytes. uint16_t Flash_Write(uint32_t address, uint8_t *in, uint16_t len) { - bool isok; - uint16_t res, bytes_sent = 0, bytes_remaining = len; - uint8_t buf[FLASH_MEM_BLOCK_SIZE]; + uint16_t res; + uint16_t bytes_sent = 0; + uint16_t bytes_remaining = len; + uint8_t buf[FLASH_MEM_BLOCK_SIZE] = {0}; + while (bytes_remaining > 0) { Flash_CheckBusy(BUSY_TIMEOUT); @@ -123,18 +126,19 @@ uint16_t Flash_Write(uint32_t address, uint8_t *in, uint16_t len) { res = Flash_WriteDataCont(address + bytes_sent, buf, bytes_in_packet); + // a rejected page stops here, so bytes_sent stays at what really landed + if (res != bytes_in_packet) { + goto out; + } + bytes_remaining -= bytes_in_packet; bytes_sent += bytes_in_packet; - - isok = (res == bytes_in_packet); - - if (!isok) - goto out; } out: FlashStop(); - return len; + // bytes actually programmed, callers compare this against len + return bytes_sent; } void Flashmem_print_status(void) { diff --git a/common_arm/fpga/fpga_apis.h b/common_arm/fpga/fpga_apis.h index 018f4086d..cebc1e940 100644 --- a/common_arm/fpga/fpga_apis.h +++ b/common_arm/fpga/fpga_apis.h @@ -327,6 +327,13 @@ void FpgaSendCommand(uint16_t cmd, uint16_t v); //----------------------------------------------------------------------------- void FpgaWriteConfWord(uint16_t v); +#ifdef PM5 +//----------------------------------------------------------------------------- +// True when the last configuration word selected FPGA_MAJOR_MODE_OFF. +//----------------------------------------------------------------------------- +bool FpgaIsOff(void); +#endif + //----------------------------------------------------------------------------- // enable FPGA internal tracing //----------------------------------------------------------------------------- diff --git a/common_arm/fpga/fpga_core.c b/common_arm/fpga/fpga_core.c index df7b312bc..040f0c442 100644 --- a/common_arm/fpga/fpga_core.c +++ b/common_arm/fpga/fpga_core.c @@ -15,8 +15,15 @@ bool FpgaIs16BitMsbMode(uint16_t fpga_mode) { return false; } +#ifdef PM5 +static uint16_t s_fpga_conf_word = FPGA_MAJOR_MODE_OFF; +#endif + void FpgaWriteConfWord(uint16_t v) { const int current = FpgaGetCurrent(); +#ifdef PM5 + s_fpga_conf_word = v; +#endif // Keep track of whether or not we should be monitoring the HF field timeout if (current == FPGA_BITSTREAM_HF || current == FPGA_BITSTREAM_HF_15 || current == FPGA_BITSTREAM_HF_FELICA) { @@ -44,6 +51,12 @@ void FpgaWriteConfWord(uint16_t v) { FpgaSendCommand(FPGA_CMD_SET_CONFREG, v); } +#ifdef PM5 +bool FpgaIsOff(void) { + return (s_fpga_conf_word & FPGA_MAJOR_MODE_MASK) == FPGA_MAJOR_MODE_OFF; +} +#endif + void FpgaEnableTracing(void) { FpgaSendCommand(FPGA_CMD_TRACE_ENABLE, 1); } diff --git a/common_arm/fpga/fpga_hw_at32.c b/common_arm/fpga/fpga_hw_at32.c index 7ab507a38..d3fcb6a29 100644 --- a/common_arm/fpga/fpga_hw_at32.c +++ b/common_arm/fpga/fpga_hw_at32.c @@ -5,7 +5,6 @@ #include "gpio_apis.h" #include "dbprint.h" #include "pm3_cmd.h" -#include "string.h" uint16_t g_ssc_dma_rx_count; uint8_t g_ssc_data_byte_width; @@ -263,12 +262,20 @@ static void spi_cmd_setup(void) { void FpgaSendCommand(uint16_t cmd, uint16_t v) { // Init spi spi_cmd_setup(); + + // Before switching modes, disable SPI_SSC to prevent signal changes from triggering a CSPAS event, + // which would cause the SPI to hang. + SPI_SSC->ctrl1_bit.spien = FALSE; + // Send data gpio_bits_reset(AT32_GPIO_SPI_CS, AT32_GPIO_SPI_CS_PIN); // CS LOW while (spi_i2s_flag_get(SPI_CMD, SPI_I2S_TDBE_FLAG) == RESET) {} spi_i2s_data_transmit(SPI_CMD, cmd | v); while (spi_i2s_flag_get(SPI_CMD, SPI_I2S_BF_FLAG) != RESET) {} // Waiting for SPI transmit finish. gpio_bits_set(AT32_GPIO_SPI_CS, AT32_GPIO_SPI_CS_PIN); // CS HIGH + + // Re-enable SPI_SSC after sending the command + SPI_SSC->ctrl1_bit.spien = TRUE; } void Fpga_print_status(void) { diff --git a/common_arm/fpga/fpga_hw_at32.h b/common_arm/fpga/fpga_hw_at32.h index b36c46c0d..7c633f81a 100644 --- a/common_arm/fpga/fpga_hw_at32.h +++ b/common_arm/fpga/fpga_hw_at32.h @@ -17,9 +17,9 @@ extern uint8_t g_ssc_data_byte_width; // Is tx lsb first? If diff with rx frame settings, the data will reverse before send. extern bool g_tx_lsb_first; -// TODO DXL 纠正SPI和DMA通道选择,为了方便修改,此处可先暂时定义SPI和DMA外设和DMA通道的对应宏 -// spi-ti_mode 用到了 SPI4, DMA1 -// spi-cmd 用到了 SPI3,无DMA +// TODO DXL Move to the config header? +// spi-ti_mode Using SPI4, DMA1 +// spi-cmd Using SPI3, No DMA #define SPI_SSC SPI4 #define SPI_CRM_CLOCK_SSC CRM_SPI4_PERIPH_CLOCK #define DMA_SSC DMA1 @@ -31,7 +31,39 @@ extern bool g_tx_lsb_first; #define SPI_CMD SPI3 #define SPI_CRM_CLOCK_CMD CRM_SPI3_PERIPH_CLOCK +/** + * A workaround for the SPI_CSPAS_FLAG issue in AT32F435/437. + * + * --- + * + * In slave mode, once the TI mode is enabled, the SPI interface is capable of detecting CS pulse errors + * during data transmission, and setting the CSPAS bit (It is cleared by reading the SPI_STS) as soon as + * a CS pulse error is detected. At this point, the detected pulse error will be discarded by the SPI. However, + * since there is something wrong with the CS signal, the software should disable the SPI slave and + * reconfigure the SPI master before re-enabling the SPI slave for communication. + * + * (Copy from AT32F435/437 reference manual, section 13.2.7) + * See: https://www.arterychip.com/download/RM/RM_AT32F435_437_EN_V2.06.pdf + * + * --- + * + * DXL NOTE: Theoretically, to completely resolve this issue, strict timing control should be implemented between the SPI master and slave; + * the SPI slave should not be enabled until the SPI master is ready. But it is extremely difficult to implement; + * in many places, `FpgaSetupSsc` is called before switching the FPGA mode—an approach taken to improve transmission and reception processing speeds. + * So we can only use this workaround to handle the issue after it occurs, which is not ideal. but it is the only feasible solution for now. + * + * @param status The status register value of the SPI peripheral. + */ +#define CSPAS_WORKAROUND(status) \ + if (status & SPI_CSPAS_FLAG) { \ + SPI_SSC->ctrl1_bit.spien = FALSE; \ + SPI_SSC->ctrl1_bit.spien = TRUE; \ + } + STATIC_FORCE_INLINE bool FPGA_SSC_RX_Ready(void) { + uint32_t sts = SPI_SSC->sts; + CSPAS_WORKAROUND(sts); + /* * Note that according to the manual description, if SPI receives data but does not read it after startup, * the SPI peripheral will generate an overflow interrupt and no longer receive new data. At this time, @@ -47,18 +79,22 @@ STATIC_FORCE_INLINE bool FPGA_SSC_RX_Ready(void) { // Reading SPI_DT register and SPI_STS register sequentially can clear ROERR(Must to read DT reg) // Only when the ROERR flag is set, it is necessary to read DT, so the '&&' condition is very important. // If the former does not hold, the DT register will not be read. - return ((SPI_SSC->sts & (SPI_I2S_RDBF_FLAG | SPI_I2S_ROERR_FLAG)) == SPI_I2S_RDBF_FLAG) - || (((SPI_SSC->sts & SPI_I2S_ROERR_FLAG) == SPI_I2S_ROERR_FLAG) && (SPI_SSC->dt & 0)); // Readout data for clear the ROERR flag. IMPORTANT! + return ((sts & (SPI_I2S_RDBF_FLAG | SPI_I2S_ROERR_FLAG)) == SPI_I2S_RDBF_FLAG) + || (((sts & SPI_I2S_ROERR_FLAG) == SPI_I2S_ROERR_FLAG) && (SPI_SSC->dt & 0)); // Readout data for clear the ROERR flag. IMPORTANT! } STATIC_FORCE_INLINE bool FPGA_SSC_TX_Ready(void) { // spi_i2s_flag_get(SPI_SSC, SPI_I2S_TDBE_FLAG) == SET - return (SPI_SSC->sts & SPI_I2S_TDBE_FLAG) == SPI_I2S_TDBE_FLAG; + uint32_t sts = SPI_SSC->sts; + CSPAS_WORKAROUND(sts); + return (sts & SPI_I2S_TDBE_FLAG) == SPI_I2S_TDBE_FLAG; } STATIC_FORCE_INLINE bool FPGA_SSC_TX_Done(void) { // spi_i2s_flag_get(SPI_SSC, SPI_I2S_BF_FLAG) == RESET - return (SPI_SSC->sts & SPI_I2S_BF_FLAG) != SPI_I2S_BF_FLAG; // SPI currently has no transmission transactions. + uint32_t sts = SPI_SSC->sts; + CSPAS_WORKAROUND(sts); + return (sts & SPI_I2S_BF_FLAG) != SPI_I2S_BF_FLAG; // SPI currently has no transmission transactions. } STATIC_FORCE_INLINE uint32_t FPGA_SSC_RX_Value(void) { diff --git a/common_arm/fpga/fpga_loader.c b/common_arm/fpga/fpga_loader.c index 6b4859e2d..8a3b6ce10 100644 --- a/common_arm/fpga/fpga_loader.c +++ b/common_arm/fpga/fpga_loader.c @@ -364,10 +364,18 @@ static void FpgaDownloadAndGoEx(int bitstream_target, bool keep_em) { if (reset_fpga_stream(bitstream_target, &compressed_fpga_stream, output_buffer) == false) { Dbprintf(_RED_("reset_fpga_stream failed")); + // hand the ring buffer back. Bailing out with it still allocated leaves BigBuf + // short by FPGA_RING_BUFFER_BYTES for the rest of the session, which shows up in + // "hw status" as available memory lower than BigBuf_size for no visible reason. + if (keep_em) { + BigBuf_free_keep_EM(); + } else { + BigBuf_free(); + } return; } - uint32_t bitstream_length; + uint32_t bitstream_length = 0; if (bitparse_find_section(bitstream_target, 'e', &bitstream_length, &compressed_fpga_stream, output_buffer)) { DownloadFPGA(bitstream_target, bitstream_length, &compressed_fpga_stream, output_buffer); downloaded_bitstream = bitstream_target; diff --git a/common_arm/gpio/gpio_hw_at91.c b/common_arm/gpio/gpio_hw_at91.c index d4d871eeb..d49e49c4a 100644 --- a/common_arm/gpio/gpio_hw_at91.c +++ b/common_arm/gpio/gpio_hw_at91.c @@ -96,8 +96,10 @@ void gpio_fpga_download_setup(void) { } void gpio_fpga_on_setup(void) { +#ifdef GPIO_FPGA_ON AT91C_BASE_PIOA->PIO_OER = GPIO_FPGA_ON; AT91C_BASE_PIOA->PIO_PER = GPIO_FPGA_ON; +#endif } void gpio_fpga_mod_feedback_setup(void) { diff --git a/common_arm/gpio/gpio_hw_at91.h b/common_arm/gpio/gpio_hw_at91.h index 5c5e5d2e3..b0601061b 100644 --- a/common_arm/gpio/gpio_hw_at91.h +++ b/common_arm/gpio/gpio_hw_at91.h @@ -73,12 +73,19 @@ STATIC_FORCE_INLINE void Gpio_LED_D_Inv(void) { INVBIT(GPIO_LED_D); } +// ICopyX(XC3) has no FPGA power switch -- PA26 is GPIO_FPGA_SWITCH there, see +// config_gpio_proxmark3.h -- so these are no-ops on that board, the same way the +// AT32 port stubs them. Guarded like Gpio_FPGA_SWITCH_*() below. STATIC_FORCE_INLINE void Gpio_FPGA_ON_High(void) { +#ifdef GPIO_FPGA_ON HIGH(GPIO_FPGA_ON); +#endif } STATIC_FORCE_INLINE void Gpio_FPGA_ON_Low(void) { +#ifdef GPIO_FPGA_ON LOW(GPIO_FPGA_ON); +#endif } STATIC_FORCE_INLINE void Gpio_SSC_DOUT_High(void) { diff --git a/common_arm/rgb/rgb_apis.h b/common_arm/rgb/rgb_apis.h index 8789a8557..d0d5805b9 100644 --- a/common_arm/rgb/rgb_apis.h +++ b/common_arm/rgb/rgb_apis.h @@ -10,6 +10,6 @@ // driven by an I2C RGB controller). Other platforms don't build this module, so // callers must guard usage accordingly (e.g. the CMD_PM5_RGB_SET handler). //----------------------------------------------------------------------------- -void RgbLedSet(uint8_t r, uint8_t g, uint8_t b); +bool RgbLedSet(uint8_t r, uint8_t g, uint8_t b); #endif // RGB_APIS_H_ diff --git a/common_arm/rgb/rgb_hw_at32.c b/common_arm/rgb/rgb_hw_at32.c index e851d6b72..30e9e6739 100644 --- a/common_arm/rgb/rgb_hw_at32.c +++ b/common_arm/rgb/rgb_hw_at32.c @@ -12,11 +12,17 @@ #define RGB_REG_INDEX 0x02 #define RGB_REG_DATA 0x03 -void RgbLedSet(uint8_t r, uint8_t g, uint8_t b) { +bool RgbLedSet(uint8_t r, uint8_t g, uint8_t b) { uint8_t rgb[3] = { r, g, b }; StartTicks(); I2C_init(true); - I2C_WriteByte(0, RGB_REG_INDEX, RGB_I2C_ADDR); // address LED index 0 - I2C_WriteByte(1, RGB_REG_COUNT, RGB_I2C_ADDR); // 1 LED on the string - I2C_BufferWrite(rgb, sizeof(rgb), RGB_REG_DATA, RGB_I2C_ADDR); + // Report NAK: on a cold boot the controller may still be powering up when the + // first write fires. The caller uses this to retry instead of latching a failed + // write (which previously left the LED dark until the next state change - i.e. + // "worked once after flash, dark on every cold boot" on battery). + bool ok = true; + ok &= I2C_WriteByte(0, RGB_REG_INDEX, RGB_I2C_ADDR); // address LED index 0 + ok &= I2C_WriteByte(1, RGB_REG_COUNT, RGB_I2C_ADDR); // 1 LED on the string + ok &= I2C_BufferWrite(rgb, sizeof(rgb), RGB_REG_DATA, RGB_I2C_ADDR); + return ok; } diff --git a/common_arm/usb/usb_cdc_apis.h b/common_arm/usb/usb_cdc_apis.h index 3f6a5d3de..b046415ae 100644 --- a/common_arm/usb/usb_cdc_apis.h +++ b/common_arm/usb/usb_cdc_apis.h @@ -21,6 +21,10 @@ #include "common.h" +// How many times the async write helpers spin on the IN endpoint before they give up on the host. +// usb_check() stays true for as long as the device is enumerated +#define ASYNC_WRITE_SPIN_LIMIT 0x00020000 + void usb_disable(void); void usb_enable(void); bool usb_check(void); @@ -33,6 +37,7 @@ int usb_write(const uint8_t *data, size_t len); int async_usb_write_start(void); void async_usb_write_pushByte(uint8_t data); bool async_usb_write_requestWrite(void); +void async_usb_write_discard(void); int async_usb_write_stop(void); void usb_update_serial(uint64_t newSerialNumber); diff --git a/common_arm/usb/usb_cdc_at32.c b/common_arm/usb/usb_cdc_at32.c index 2c6b7d4b8..2723e8569 100644 --- a/common_arm/usb/usb_cdc_at32.c +++ b/common_arm/usb/usb_cdc_at32.c @@ -1,5 +1,6 @@ #include "pm3_cmd.h" #include "ticks_apis.h" +#include "wdt_apis.h" #include "usb_cdc_apis.h" #include "usb_read_ng.h" #include "usb_cdc_desc.h" @@ -17,6 +18,13 @@ static otg_core_type otg_core_struct; static usbd_core_type *udev = &(otg_core_struct.dev); static usbd_desc_t vp_desc; +// Spin-wait iteration bound for usb_write()'s tx-complete wait, not a time +// unit - g_tx_completed is set from the USB core's own IN-endpoint ISR, so +// this can't use the shared ticks timer (see ticks_apis.h StartTicks()/ +// StopTicks() callers elsewhere in armsrc - it's routinely stopped by +// LF/HF code at the exact moments a reply may need to go out). +#define USB_TX_COMPLETE_TIMEOUT 2000000 + /** * @brief get device descriptor * @retval usbd_desc @@ -161,26 +169,23 @@ static usbd_desc_handler cdc_desc_handler = { */ static void usb_clock48m_select(usb_clk48_s clk_s) { if (clk_s == USB_CLK_HICK) { - /* UNUSED!!! - + // HICK-48 (also makes SCLK-from-HICK 48 MHz), trimmed by the ACC against + // the USB SOF to +/-0.25%. Independent of the PLL, so the PLL can be + // powered down at idle (armsrc/pm5_power.c) without touching USB. crm_usb_clock_source_select(CRM_USB_CLOCK_SOURCE_HICK); - // enable the acc calibration ready interrupt crm_periph_clock_enable(CRM_ACC_PERIPH_CLOCK, TRUE); - // update the c1\c2\c3 value + // compare window around the ideal 8000 HICK/6 counts per 1 ms SOF acc_write_c1(7980); acc_write_c2(8000); acc_write_c3(8020); - #if (USB_ID == 0) +#if (USB_ID == 0) acc_sof_select(ACC_SOF_OTG1); - #else +#else acc_sof_select(ACC_SOF_OTG2); - #endif - // open acc calibration +#endif acc_calibration_mode_enable(ACC_CAL_HICKTRIM, TRUE); - - */ } else { switch (system_core_clock) { /* 48MHz */ @@ -373,7 +378,11 @@ void usb_enable(void) { usb_gpio_config(); crm_periph_clock_enable(OTG_CLOCK, TRUE); // enable otgfs clock +#ifdef AS_BOOTROM usb_clock48m_select(USB_CLK_HEXT); // select usb 48m clcok source +#else + usb_clock48m_select(USB_CLK_HICK); // crystal-less, survives the idle PLL-off (pm5_power.c) +#endif nvic_irq_enable(OTG_IRQ, 0, 0); // enable otgfs irq usbd_init(&otg_core_struct, USB_FULL_SPEED_CORE_ID, USB_ID, &cdc_class_handler, &cdc_desc_handler); // init usb @@ -431,10 +440,23 @@ uint16_t usb_available_length(void) { * @return */ bool usb_poll_validate_length(void) { +#ifndef AS_BOOTROM + // A previous USB packet may already contain the next command. + if (usb_read_ng_has_buffered_data()) { + return true; + } +#endif if (usb_poll() == false) { return false; } - return usb_available_length() > 0; + if (usb_available_length() > 0) { + return true; + } + + // Consume a terminating zero-length packet and rearm the OUT endpoint. + // Otherwise no subsequent command can be received. + usb_vcp_get_rxdata(udev, NULL, 0); + return false; } /** @@ -500,10 +522,14 @@ int usb_write(const uint8_t *data, const size_t len) { // wait for send complete cdc_struct_type *pcdc = (cdc_struct_type *)(udev->class_handler->pdata); + uint32_t tx_timeout = 0; while (pcdc->g_tx_completed != 1) { if (usb_check() == false) { return PM3_EIO; } + if (tx_timeout++ > USB_TX_COMPLETE_TIMEOUT) { + return PM3_EIO; + } // working for send to HOST... // Have a cup of tea? } @@ -516,10 +542,14 @@ int usb_write(const uint8_t *data, const size_t len) { if (usb_vcp_send_data(udev, (uint8_t *) data, 0) != SUCCESS) { return PM3_EIO; } + tx_timeout = 0; while (pcdc->g_tx_completed != 1) { if (usb_check() == false) { return PM3_EIO; } + if (tx_timeout++ > USB_TX_COMPLETE_TIMEOUT) { + return PM3_EIO; + } } } @@ -552,10 +582,25 @@ int async_usb_write_start(void) { otg_device_type *dev = OTG_DEVICE(udev->usb_reg); // check usb state - if (!usb_check()) return PM3_EIO; + if (!usb_check()) { + return PM3_EIO; + } // wait for tx end if working... - while (!is_write_completed(ept_in)) if (!usb_check()) return PM3_EIO; + uint32_t spins = 0; + while (!is_write_completed(ept_in)) { + + if (!usb_check()) { + return PM3_EIO; + } + + WDT_HIT(); + + if (++spins > ASYNC_WRITE_SPIN_LIMIT) { + async_usb_write_discard(); + break; + } + } // disable fifo empty irq. dev->diepempmsk &= ~(1 << (USBD_CDC_BULK_IN_EPT & 0x7F)); @@ -617,25 +662,57 @@ bool async_usb_write_requestWrite(void) { return TRUE; } +/** + * Drop a transfer the host refuses to collect. + * Disables the IN endpoint and flushes its tx fifo, otherwise the endpoint + * stays busy forever and every later usb_write() bails out, which looks + * like a dead device. + */ +void async_usb_write_discard(void) { + usbd_ept_in_check_fifo(udev, USBD_CDC_BULK_IN_EPT & 0x7F); + async_write_buf_select = 0; + async_write_index = 0; +} + /** * Stop send and wait finish. * @return SUCCESS if send stop success, otherwise ERROR */ int async_usb_write_stop(void) { otg_eptin_type *ept_in = USB_INEPT(udev->usb_reg, (USBD_CDC_BULK_IN_EPT & 0x7F)); + uint32_t spins = 0; // Wait for the end of transfer - while (!is_write_completed(ept_in)) if (!usb_check()) return PM3_EIO; + while (!is_write_completed(ept_in)) { - // still have data on local buffer, we need send before write stop. - if (async_write_index != 0) { - if (!async_usb_write_requestWrite()) { + if (!usb_check()) { return PM3_EIO; } + + WDT_HIT(); + + if (++spins > ASYNC_WRITE_SPIN_LIMIT) { + async_usb_write_discard(); + return PM3_ETIMEOUT; + } + } + + // Send a final packet. When the local buffer still holds data this flushes it, + // if empty, send a zero length packet. + if (!async_usb_write_requestWrite()) { + return PM3_EIO; } // Wait for the end of fifo flush transfer. - while (!is_write_completed(ept_in)) if (!usb_check()) return PM3_EIO; + spins = 0; + while (!is_write_completed(ept_in)) { + if (!usb_check()) return PM3_EIO; + WDT_HIT(); + if (++spins > ASYNC_WRITE_SPIN_LIMIT) { + async_usb_write_discard(); + return PM3_ETIMEOUT; + } + } return PM3_SUCCESS; } diff --git a/common_arm/usb/usb_cdc_at91.c b/common_arm/usb/usb_cdc_at91.c index 3e80b36a9..797cbfd28 100644 --- a/common_arm/usb/usb_cdc_at91.c +++ b/common_arm/usb/usb_cdc_at91.c @@ -22,6 +22,7 @@ #include "proxmark3_arm.h" #include "usart_defs.h" #include "ticks_apis.h" +#include "wdt_apis.h" #include "usb_read_ng.h" #include "usb_cdc_desc.h" @@ -48,12 +49,9 @@ AT91SAM7S256 USB Device Port #define AT91C_USB_EP_IN_SIZE 64 /* WCID specific Request Code */ -#define MS_OS_DESCRIPTOR_INDEX 0xEE -#define MS_VENDOR_CODE 0x1C -#define MS_EXTENDED_COMPAT_ID 0x04 -#define MS_EXTENDED_PROPERTIES 0x05 -#define MS_WCID_GET_DESCRIPTOR 0xC0 -#define MS_WCID_GET_FEATURE_DESCRIPTOR 0xC1 +/* MS_OS_DESCRIPTOR_INDEX, MS_EXTENDED_COMPAT_ID, MS_EXTENDED_PROPERTIES and + the MS_WCID_* request types come from usb_cdc_desc.h */ +#define MS_VENDOR_CODE USB_CDC_DESC_MS_VENDOR_CODE /* USB standard request code */ #define STD_GET_STATUS_ZERO 0x0080 @@ -92,7 +90,7 @@ static uint8_t btConnection = 0; static uint8_t btReceiveBank = AT91C_UDP_RX_DATA_BK0; // -- pre def functions -void AT91F_USB_SendData(AT91PS_UDP pudp, const char *pData, uint32_t length); +void AT91F_USB_SendData(AT91PS_UDP pudp, const char *pData, uint32_t length, uint32_t wLength); void AT91F_USB_SendZlp(AT91PS_UDP pudp); void AT91F_USB_SendStall(AT91PS_UDP pudp); void AT91F_CDC_Enumerate(void); @@ -143,12 +141,14 @@ static const char *getStringDescriptor(uint8_t idx) { } +// CDC LineCoding is 7 bytes on the wire, so this must not pick up the padding +// byte that natural alignment would add after DataBits. typedef struct { uint32_t BitRate; uint8_t Format; uint8_t ParityType; uint8_t DataBits; -} AT91S_CDC_LINE_CODING, *AT91PS_CDC_LINE_CODING; +} PACKED AT91S_CDC_LINE_CODING, *AT91PS_CDC_LINE_CODING; static AT91S_CDC_LINE_CODING line = { // purely informative, actual values don't matter USART_BAUD_RATE, // baudrate @@ -184,6 +184,7 @@ static uint16_t usb_read_ng_data_available(void) { static uint8_t usb_read_ng_data_read(void) { return pUdp->UDP_FDR[AT91C_EP_OUT]; } +#endif // Implemented for read_ng static void usb_read_ng_clear(void) { @@ -196,6 +197,7 @@ static void usb_read_ng_clear(void) { } } +#ifndef AS_BOOTROM // Instance for 'read_ng' apis static const usb_read_ng_config_t g_usb_read_ng_config = { .is_link_ready = usb_read_ng_link_ready, @@ -372,13 +374,25 @@ FORCE_INLINE uint16_t usb_available_length(void) { bug. **/ bool usb_poll_validate_length(void) { +#ifndef AS_BOOTROM + // A previous USB packet may already contain the next command. + if (usb_read_ng_has_buffered_data()) { + return true; + } +#endif // Reuse 'usb_poll()' implemented. if (usb_poll() == false) { return false; } - // Why code this: return (((pUdp->UDP_CSR[AT91C_EP_OUT] & AT91C_UDP_RXBYTECNT) >> 16) > 0); - // For speed? but 'usb_available_length()' is a inline function. - return (usb_available_length() > 0); + if (usb_available_length() > 0) { + return true; + } + + // A transfer whose size is an exact multiple of the endpoint size can end + // with a zero-length packet. Acknowledge it here; otherwise this receive + // bank remains selected forever and data queued in the other bank stalls. + usb_read_ng_clear(); + return false; } /* @@ -530,16 +544,44 @@ int async_usb_write_start(void) { return PM3_EIO; } + uint32_t spins = 0; while (pUdp->UDP_CSR[AT91C_EP_IN] & AT91C_UDP_TXPKTRDY) { + if (usb_check() == false) { return PM3_EIO; } + + WDT_HIT(); + + if (++spins > ASYNC_WRITE_SPIN_LIMIT) { + async_usb_write_discard(); + break; + } } isAsyncRequestFinished = false; return PM3_SUCCESS; } +/* + *---------------------------------------------------------------------------- + * \fn async_usb_write_discard + * \brief Drop a packet the host refuses to collect + * + * Without this the endpoint stays busy forever and usb_write() keeps bailing + * out with PM3_EIO, which looks like a dead device. + *---------------------------------------------------------------------------- +*/ +void async_usb_write_discard(void) { + // Clearing TXPKTRDY by hand is not enough on this silicon, the FIFO keeps + // its content. Reset the endpoint the same way the bus reset handler does + // and re-enable it, so the next usb_write() starts from a clean FIFO. + pUdp->UDP_RSTEP |= (1u << AT91C_EP_IN); + pUdp->UDP_RSTEP &= ~(1u << AT91C_EP_IN); + pUdp->UDP_CSR[AT91C_EP_IN] = (AT91C_UDP_EPEDS | AT91C_UDP_EPTYPE_BULK_IN); + isAsyncRequestFinished = true; +} + /* *---------------------------------------------------------------------------- * \fn async_usb_write_pushByte @@ -603,25 +645,46 @@ inline bool async_usb_write_requestWrite(void) { *---------------------------------------------------------------------------- */ int async_usb_write_stop(void) { + + uint32_t spins = 0; + // Wait for the end of transfer while (pUdp->UDP_CSR[AT91C_EP_IN] & AT91C_UDP_TXPKTRDY) { + if (usb_check() == false) { return PM3_EIO; } + + WDT_HIT(); + + if (++spins > ASYNC_WRITE_SPIN_LIMIT) { + async_usb_write_discard(); + return PM3_ETIMEOUT; + } } // clear transmission completed flag UDP_CLEAR_EP_FLAGS(AT91C_EP_IN, AT91C_UDP_TXCOMP); while (pUdp->UDP_CSR[AT91C_EP_IN] & AT91C_UDP_TXCOMP) {}; - // FIFO is not empty, request a write in non-ping-pong mode - if (isAsyncRequestFinished == false) { + // FIFO is not empty, request a write in non-ping-pong mode. + // Must send ZLP to close transfer + { UDP_SET_EP_FLAGS(AT91C_EP_IN, AT91C_UDP_TXPKTRDY); + spins = 0; while (!(pUdp->UDP_CSR[AT91C_EP_IN] & AT91C_UDP_TXCOMP)) { + if (usb_check() == false) { return PM3_EIO; } + + WDT_HIT(); + + if (++spins > ASYNC_WRITE_SPIN_LIMIT) { + async_usb_write_discard(); + return PM3_ETIMEOUT; + } } UDP_CLEAR_EP_FLAGS(AT91C_EP_IN, AT91C_UDP_TXCOMP); @@ -634,11 +697,22 @@ int async_usb_write_stop(void) { *---------------------------------------------------------------------------- * \fn AT91F_USB_SendData * \brief Send Data through the control endpoint + * + * length is how much the device has to give, wLength how much the host asked + * for. When less than wLength is sent and that amount is a whole number of + * control endpoint packets, the transfer needs a zero length packet to end it, + * or the host keeps polling until it times out. *---------------------------------------------------------------------------- */ -void AT91F_USB_SendData(AT91PS_UDP pudp, const char *pData, uint32_t length) { +void AT91F_USB_SendData(AT91PS_UDP pudp, const char *pData, uint32_t length, uint32_t wLength) { AT91_REG csr; + length = MIN(length, wLength); + + bool send_zlp = (length > 0) && + (length < wLength) && + ((length % AT91C_USB_EP_CONTROL_SIZE) == 0); + do { uint32_t cpt = MIN(length, AT91C_USB_EP_CONTROL_SIZE); length -= cpt; @@ -670,6 +744,10 @@ void AT91F_USB_SendData(AT91PS_UDP pudp, const char *pData, uint32_t length) { UDP_CLEAR_EP_FLAGS(AT91C_EP_CONTROL, AT91C_UDP_TXCOMP); while (pudp->UDP_CSR[AT91C_EP_CONTROL] & AT91C_UDP_TXCOMP) {}; } + + if (send_zlp) { + AT91F_USB_SendZlp(pudp); + } } //*---------------------------------------------------------------------------- @@ -690,10 +768,41 @@ void AT91F_USB_SendZlp(AT91PS_UDP pudp) { //* \brief Stall the control endpoint //*---------------------------------------------------------------------------- void AT91F_USB_SendStall(AT91PS_UDP pudp) { + UDP_SET_EP_FLAGS(AT91C_EP_CONTROL, AT91C_UDP_FORCESTALL); - while (!(pudp->UDP_CSR[AT91C_EP_CONTROL] & AT91C_UDP_ISOERROR)) {}; - UDP_CLEAR_EP_FLAGS(AT91C_EP_CONTROL, (AT91C_UDP_FORCESTALL | AT91C_UDP_ISOERROR)); - while (pudp->UDP_CSR[AT91C_EP_CONTROL] & (AT91C_UDP_FORCESTALL | AT91C_UDP_ISOERROR)) {}; + + // STALLSENT only arrives once the host polls the endpoint and takes the + // handshake, so every way the host can fail to do that needs an exit. + // usb_check() is not one of them, it calls back into AT91F_CDC_Enumerate(). + uint16_t time_out = 0; + while (!(pudp->UDP_CSR[AT91C_EP_CONTROL] & AT91C_UDP_STALLSENT)) { + + // host dropped this request and started another one + if (pudp->UDP_CSR[AT91C_EP_CONTROL] & AT91C_UDP_RXSETUP) { + break; + } + + // bus reset. Not RXSUSP: nothing in this driver writes it back to + // UDP_ICR, so once the bus first idles it stays latched for good. + if (pudp->UDP_ISR & AT91C_UDP_ENDBUSRES) { + break; + } + + if (time_out++ == 0x1FFF) { + break; + } + } + + UDP_CLEAR_EP_FLAGS(AT91C_EP_CONTROL, (AT91C_UDP_FORCESTALL | AT91C_UDP_STALLSENT)); + + // leaving the loop above early can let the host set STALLSENT after the + // clear, so this wait is bounded too + time_out = 0; + while (pudp->UDP_CSR[AT91C_EP_CONTROL] & (AT91C_UDP_FORCESTALL | AT91C_UDP_STALLSENT)) { + if (time_out++ == 0x1FFF) { + break; + } + } } //*---------------------------------------------------------------------------- @@ -727,39 +836,42 @@ void AT91F_CDC_Enumerate(void) { UDP_CLEAR_EP_FLAGS(AT91C_EP_CONTROL, AT91C_UDP_RXSETUP); while ((pUdp->UDP_CSR[AT91C_EP_CONTROL] & AT91C_UDP_RXSETUP)) {}; - /* - if ( bRequest == MS_VENDOR_CODE) { - if ( bmRequestType == MS_WCID_GET_DESCRIPTOR ) { // C0 - if ( wIndex == MS_EXTENDED_COMPAT_ID ) { // 4 - //AT91F_USB_SendData(pUdp, CompatIDFeatureDescriptor, MIN(sizeof(CompatIDFeatureDescriptor), wLength)); - //return; - } + // WCID vendor request. StrMS_OSDescriptor advertises MS_VENDOR_CODE, so + // every request carrying it has to be answered here. Falling through to the + // standard switch below stalls it, which makes Windows cache the device as + // having no MS OS descriptors and stop asking. + if (bRequest == MS_VENDOR_CODE) { + + if (bmRequestType == MS_WCID_GET_DESCRIPTOR && wIndex == MS_EXTENDED_COMPAT_ID) { + AT91F_USB_SendData(pUdp, CompatIDFeatureDescriptor, sizeof(CompatIDFeatureDescriptor), wLength); + return; } - if ( bmRequestType == MS_WCID_GET_FEATURE_DESCRIPTOR ) { //C1 - // if ( wIndex == MS_EXTENDED_PROPERTIES ) { // 5 - winusb bug with wIndex == interface index, so I just send it always) - //AT91F_USB_SendData(pUdp, OSprop, MIN(sizeof(OSprop), wLength)); - //return; - // } + // wValue holds the interface number, wIndex the descriptor index. + if (bmRequestType == MS_WCID_GET_FEATURE_DESCRIPTOR && wIndex == MS_EXTENDED_PROPERTIES) { + AT91F_USB_SendData(pUdp, OSprop, sizeof(OSprop), wLength); + return; } + + AT91F_USB_SendStall(pUdp); + return; } - */ // Handle supported standard device request Cf Table 9-3 in USB specification Rev 1.1 switch ((bRequest << 8) | bmRequestType) { case STD_GET_DESCRIPTOR: { if (wValue == 0x100) { // Return Device Descriptor - AT91F_USB_SendData(pUdp, devDescriptor, MIN(sizeof(devDescriptor), wLength)); + AT91F_USB_SendData(pUdp, devDescriptor, sizeof(devDescriptor), wLength); } else if (wValue == 0x200) { // Return Configuration Descriptor - AT91F_USB_SendData(pUdp, cfgDescriptor, MIN(sizeof(cfgDescriptor), wLength)); + AT91F_USB_SendData(pUdp, cfgDescriptor, sizeof(cfgDescriptor), wLength); } else if ((wValue & 0xF00) == 0xF00) { // Return BOS Descriptor - AT91F_USB_SendData(pUdp, bosDescriptor, MIN(sizeof(bosDescriptor), wLength)); + AT91F_USB_SendData(pUdp, bosDescriptor, sizeof(bosDescriptor), wLength); } else if ((wValue & 0x300) == 0x300) { // Return String Descriptor const char *strDescriptor = getStringDescriptor(wValue & 0xff); if (strDescriptor != NULL) { - AT91F_USB_SendData(pUdp, strDescriptor, MIN(strDescriptor[0], wLength)); + AT91F_USB_SendData(pUdp, strDescriptor, strDescriptor[0], wLength); } else { AT91F_USB_SendStall(pUdp); } @@ -799,25 +911,25 @@ void AT91F_CDC_Enumerate(void) { pUdp->UDP_CSR[AT91C_EP_NOTIFY] = (wValue) ? (AT91C_UDP_EPEDS | AT91C_UDP_EPTYPE_INT_IN) : 0; break; case STD_GET_CONFIGURATION: - AT91F_USB_SendData(pUdp, (char *) & (btConfiguration), sizeof(btConfiguration)); + AT91F_USB_SendData(pUdp, (char *) & (btConfiguration), sizeof(btConfiguration), wLength); break; case STD_GET_STATUS_ZERO: wStatus = 0; // Device is Bus powered, remote wakeup disabled - AT91F_USB_SendData(pUdp, (char *) &wStatus, sizeof(wStatus)); + AT91F_USB_SendData(pUdp, (char *) &wStatus, sizeof(wStatus), wLength); break; case STD_GET_STATUS_INTERFACE: wStatus = 0; // reserved for future use - AT91F_USB_SendData(pUdp, (char *) &wStatus, sizeof(wStatus)); + AT91F_USB_SendData(pUdp, (char *) &wStatus, sizeof(wStatus), wLength); break; case STD_GET_STATUS_ENDPOINT: wStatus = 0; wIndex &= 0x0F; if ((pUdp->UDP_GLBSTATE & AT91C_UDP_CONFG) && (wIndex <= AT91C_EP_NOTIFY)) { wStatus = (pUdp->UDP_CSR[wIndex] & AT91C_UDP_EPEDS) ? 0 : 1; - AT91F_USB_SendData(pUdp, (char *) &wStatus, sizeof(wStatus)); + AT91F_USB_SendData(pUdp, (char *) &wStatus, sizeof(wStatus), wLength); } else if ((pUdp->UDP_GLBSTATE & AT91C_UDP_FADDEN) && (wIndex == AT91C_EP_CONTROL)) { wStatus = (pUdp->UDP_CSR[wIndex] & AT91C_UDP_EPEDS) ? 0 : 1; - AT91F_USB_SendData(pUdp, (char *) &wStatus, sizeof(wStatus)); + AT91F_USB_SendData(pUdp, (char *) &wStatus, sizeof(wStatus), wLength); } else { AT91F_USB_SendStall(pUdp); } @@ -875,7 +987,7 @@ void AT91F_CDC_Enumerate(void) { break; } case GET_LINE_CODING: - AT91F_USB_SendData(pUdp, (char *) &line, MIN(sizeof(line), wLength)); + AT91F_USB_SendData(pUdp, (char *) &line, sizeof(line), wLength); break; case SET_CONTROL_LINE_STATE: btConnection = wValue; diff --git a/common_arm/usb/usb_cdc_desc.c b/common_arm/usb/usb_cdc_desc.c index 68e2b94cb..2f2c073f9 100644 --- a/common_arm/usb/usb_cdc_desc.c +++ b/common_arm/usb/usb_cdc_desc.c @@ -158,84 +158,100 @@ const char bosDescriptor[12] = { 0x0 }; -// Microsoft OS Extended Configuration Compatible ID Descriptor -/* -const char CompatIDFeatureDescriptor[] = { - 0x28, 0x00, 0x00, 0x00, // Descriptor Length 40bytes (0x28) - 0x00, 0x01, // Version ('1.0') - MS_EXTENDED_COMPAT_ID, 0x00, // Compatibility ID Descriptor Index 0x0004 - 0x01, // Number of sections. 0x1 - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Reserved (7bytes) - // -----function section 1------ - 0x00, // Interface Number #0 - 0x01, // reserved (0x1) - 0x57, 0x49, 0x4E, 0x55, 0x53, 0x42, 0x00, 0x00, // Compatible ID ('WINUSB\0\0') (8bytes) - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Sub-Compatible ID (8byte) - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // Reserved (6bytes) -}; -*/ +// Only the AT91 driver answers the WCID vendor request that carries these. +#ifndef PM5 -// Microsoft Extended Properties Feature Descriptor -/* -const char OSprop[] = { - // u32 Descriptor Length (10+132+64+102 == 308 - 0x34, 0x01, 0, 0, - // u16 Version ('1.0') - 0, 1, - // u16 wIndex - MS_EXTENDED_PROPERTIES, 0, - // u16 wCount -- three section - 3, 0, +// Microsoft OS 1.0 Extended Compat ID Feature Descriptor, returned for +// bmRequestType 0xC0 / wIndex 0x0004. The compatible ID is left empty so +// Windows keeps its normal CDC driver match instead of loading WinUSB. +const char CompatIDFeatureDescriptor[40] = { + 0x28, 0x00, 0x00, 0x00, // Descriptor length (40) + 0x00, 0x01, // Version ('1.0') + MS_EXTENDED_COMPAT_ID, 0x00, // Index 0x0004 + 0x01, // Number of sections + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Reserved (7 bytes) - // -----property section 1------ - // u32 size ( 14+40+78 == 132) - 132, 0, 0, 0, - // u32 type - 1, 0, 0, 0, // unicode string - // u16 namelen (20*2 = 40) - 40, 0, - // name DeviceInterfaceGUID - 'D',0,'e',0,'v',0,'i',0,'c',0,'e',0,'I',0,'n',0,'t',0,'e',0,'r',0,'f',0,'a',0,'c',0,'e',0,'G',0,'U',0,'I',0,'D',0,0,0, - // u32 datalen (39*2 = 78) - 78, 0, 0, 0, - // data {4D36E978-E325-11CE-BFC1-08002BE10318} - '{',0,'4',0,'d',0,'3',0,'6',0,'e',0,'9',0,'7',0,'8',0,'-',0,'e',0,'3',0,'2',0,'5',0, - '-',0,'1',0,'1',0,'c',0,'e',0,'-',0,'b',0,'f',0,'c',0,'1',0,'-',0,'0',0,'8',0,'0',0, - '0',0,'2',0,'b',0,'e',0,'1',0,'0',0,'3',0,'1',0,'8',0,'}',0,0,0, - - // -----property section 2------ - // u32 size ( 14+12+38 == 64) - 64, 0, 0, 0, - // u32 type - 1, 0, 0, 0, // unicode string - // u16 namelen (12) - 12, 0, - // name Label - 'L',0,'a',0,'b',0,'e',0,'l',0,0,0, - // u32 datalen ( 19*2 = 38 ) - 38, 0, 0, 0, - // data 'Awesome PM3 Device' - 'A',0,'w',0,'e',0,'s',0,'o',0,'m',0,'e',0,' ',0,'P',0,'M',0,'3',0,' ',0,'D',0,'e',0,'v',0,'i',0,'c',0,'e',0,0,0, - - // -----property section 3------ - // u32 size ( 14+12+76 == 102) - 102, 0, 0, 0, - // u32 type - 2, 0, 0, 0, //Unicode string with environment variables - // u16 namelen (12) - 12, 0, - // name Icons - 'I',0,'c',0,'o',0,'n',0,'s',0,0,0, - // u32 datalen ( 38*2 == 76) - 76, 0, 0, 0, - // data '%SystemRoot%\\system32\\Shell32.dll,-13' - '%',0,'S',0,'y',0,'s',0,'t',0,'e',0,'m',0,'R',0,'o',0,'o',0,'t',0,'%',0, - '\\',0,'s',0,'y',0,'s',0,'t',0,'e',0,'m',0,'3',0,'2',0,'\\',0, - 'S',0,'h',0,'e',0,'l',0,'l',0,'3',0,'2',0,'.',0,'d',0,'l',0,'l',0,',',0, - '-',0,'1',0,'3',0,0,0 + // ----- function section 1 ----- + 0x00, // Interface number #0 + 0x01, // Reserved + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Compatible ID (none) + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Sub-compatible ID (none) + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // Reserved (6 bytes) }; -*/ +// Microsoft OS 1.0 Extended Properties Feature Descriptor, returned for +// bmRequestType 0xC1 / wIndex 0x0005. +const char OSprop[304] = { + // u32 Descriptor length (10 + 132 + 60 + 102 == 304) + LBYTE(304), HBYTE(304), 0, 0, + // u16 Version ('1.0') + 0, 1, + // u16 wIndex + MS_EXTENDED_PROPERTIES, 0, + // u16 wCount + 3, 0, + + // ----- property section 1 ----- + // u32 size (14 + 40 + 78 == 132) + 132, 0, 0, 0, + // u32 type + 1, 0, 0, 0, // unicode string + // u16 namelen (40) + 40, 0, + // name DeviceInterfaceGUID + 'D', 0, 'e', 0, 'v', 0, 'i', 0, 'c', 0, 'e', 0, + 'I', 0, 'n', 0, 't', 0, 'e', 0, 'r', 0, 'f', 0, + 'a', 0, 'c', 0, 'e', 0, 'G', 0, 'U', 0, 'I', 0, + 'D', 0, 0, 0, + // u32 datalen (78) + 78, 0, 0, 0, + // data {9ac44b8f-1ce1-4ceb-abee-01ce1cebabee} + '{', 0, '9', 0, 'a', 0, 'c', 0, '4', 0, '4', 0, + 'b', 0, '8', 0, 'f', 0, '-', 0, '1', 0, 'c', 0, + 'e', 0, '1', 0, '-', 0, '4', 0, 'c', 0, 'e', 0, + 'b', 0, '-', 0, 'a', 0, 'b', 0, 'e', 0, 'e', 0, + '-', 0, '0', 0, '1', 0, 'c', 0, 'e', 0, '1', 0, + 'c', 0, 'e', 0, 'b', 0, 'a', 0, 'b', 0, 'e', 0, + 'e', 0, '}', 0, 0, 0, + + // ----- property section 2 ----- + // u32 size (14 + 12 + 34 == 60) + 60, 0, 0, 0, + // u32 type + 1, 0, 0, 0, // unicode string + // u16 namelen (12) + 12, 0, + // name Label + 'L', 0, 'a', 0, 'b', 0, 'e', 0, 'l', 0, 0, 0, + // u32 datalen (34) + 34, 0, 0, 0, + // data Proxmark3 Iceman + 'P', 0, 'r', 0, 'o', 0, 'x', 0, 'm', 0, 'a', 0, + 'r', 0, 'k', 0, '3', 0, ' ', 0, 'I', 0, 'c', 0, + 'e', 0, 'm', 0, 'a', 0, 'n', 0, 0, 0, + + // ----- property section 3 ----- + // u32 size (14 + 12 + 76 == 102) + 102, 0, 0, 0, + // u32 type + 2, 0, 0, 0, // unicode string with environment variables + // u16 namelen (12) + 12, 0, + // name Icons + 'I', 0, 'c', 0, 'o', 0, 'n', 0, 's', 0, 0, 0, + // u32 datalen (76) + 76, 0, 0, 0, + // data %SystemRoot%\system32\Shell32.dll,-13 + '%', 0, 'S', 0, 'y', 0, 's', 0, 't', 0, 'e', 0, + 'm', 0, 'R', 0, 'o', 0, 'o', 0, 't', 0, '%', 0, + '\\', 0, 's', 0, 'y', 0, 's', 0, 't', 0, 'e', 0, + 'm', 0, '3', 0, '2', 0, '\\', 0, 'S', 0, 'h', 0, + 'e', 0, 'l', 0, 'l', 0, '3', 0, '2', 0, '.', 0, + 'd', 0, 'l', 0, 'l', 0, ',', 0, '-', 0, '1', 0, + '3', 0, 0, 0 +}; + +#endif const char StrLanguageCodes[4] = { 4, // Length diff --git a/common_arm/usb/usb_cdc_desc.h b/common_arm/usb/usb_cdc_desc.h index 206f7b1b2..de7ca2241 100644 --- a/common_arm/usb/usb_cdc_desc.h +++ b/common_arm/usb/usb_cdc_desc.h @@ -52,6 +52,15 @@ // https://www.usbzh.com/article/detail-625.html #define USB_CDC_DESC_MS_VENDOR_CODE 0x1C +// WCID request codes. The OS string descriptor lives at string index +// MS_OS_DESCRIPTOR_INDEX and names USB_CDC_DESC_MS_VENDOR_CODE as the bRequest +// Windows then uses for the two feature descriptors below. +#define MS_OS_DESCRIPTOR_INDEX 0xEE +#define MS_EXTENDED_COMPAT_ID 0x04 +#define MS_EXTENDED_PROPERTIES 0x05 +#define MS_WCID_GET_DESCRIPTOR 0xC0 +#define MS_WCID_GET_FEATURE_DESCRIPTOR 0xC1 + // exported all desc. extern const char devDescriptor[18]; extern const char cfgDescriptor[67]; @@ -71,4 +80,14 @@ extern char StrSerialNumber[50]; // DOCS: https://www.usbzh.com/article/detail-625.html extern const char StrMS_OSDescriptor[18]; +// WCID feature descriptors. Only the AT91 driver answers the vendor request +// that carries them; the AT32 stack routes vendor requests into its +// third-party class handler, so it does not build these. +// +// OSprop publishes this device interface GUID to Windows. +#ifndef PM5 +extern const char CompatIDFeatureDescriptor[40]; +extern const char OSprop[304]; +#endif + #endif diff --git a/common_fpga/fpga.h b/common_fpga/fpga.h index 3ca8b07c7..9b5ac5d2d 100644 --- a/common_fpga/fpga.h +++ b/common_fpga/fpga.h @@ -36,13 +36,14 @@ // fpga_compress chops the interleaved bitstreams into blocks of at most this // size, and the ARM decompresses them one at a time while DownloadFPGA() shifts // the bytes out to the FPGA. It is allocated out of BigBuf, which on AT91 is -// only ~31-33 kB, so 30 kB left nothing for the caller. -// Smaller window = slightly worse compression -// Measured on flash: +// only ~31-33 kB, so 30 kB left nothing for the caller. +// Smaller window = slightly worse compression +// Measured on flash: // 30 kB -> 102555 bytes // 16 kB -> 107121 bytes // This does NOT bound the firmware's .data section -// fpga_compress gives the single-input case its own 1 MB block, because start.c only decompresses one. +// fpga_compress -s gives the .data section its own 1 MB block, because start.c only decompresses one. +// Every FPGA bitstream, even a lone one in a HF only build, is chopped at this size. #define FPGA_RING_BUFFER_BYTES (1024 * 16) #define FPGA_TRACE_SIZE 3072 diff --git a/doc/cheatsheet.md b/doc/cheatsheet.md index 443f59f22..72977bd25 100644 --- a/doc/cheatsheet.md +++ b/doc/cheatsheet.md @@ -713,7 +713,7 @@ pm3 --> mem load -f iclass_default_keys --iclass Upgrade Sim Module firmware ``` -pm3 --> smart upgrade -f sim014.bin +pm3 --> smart upgrade -f sim024.bin ``` ## Smart Card diff --git a/doc/commands.json b/doc/commands.json index 7a7c8b627..c9d10014f 100644 --- a/doc/commands.json +++ b/doc/commands.json @@ -1326,18 +1326,20 @@ }, "hf 14a antifuzz": { "command": "hf 14a antifuzz", - "description": "Tries to fuzz the ISO14443a anticollision phase", + "description": "Tries to fuzz the ISO14443a anticollision phase. Default keeps the cascade bit set in every SAK, so the reader asks for one more cascade level until its UID buffer gives up. With --coll only the first UID byte goes out clean and every bit after it collides, so the reader has to resolve 24 bits one round trip at a time; it is then given a BCC that checks out, and the SAK sends it round again one level deeper.", "notes": [ - "hf 14a antifuzz -4" + "hf 14a antifuzz -4", + "hf 14a antifuzz --10 --coll" ], "offline": false, "options": [ "-h, --help This help", "-4 4 byte uid", "-7 7 byte uid", - "--10 10 byte uid" + "--10 10 byte uid", + "--coll collision storm instead of cascade overflow" ], - "usage": "hf 14a antifuzz [-h47] [--10]" + "usage": "hf 14a antifuzz [-h47] [--10] [--coll]" }, "hf 14a apdu": { "command": "hf 14a apdu", @@ -1694,7 +1696,7 @@ }, "hf 14b help": { "command": "hf 14b help", - "description": "--------- ----------------------- General ----------------------- help This help list List ISO-14443-B history --------- ----------------------- Operations ----------------------- view Display content from tag dump file valid SRIX4 checksum test --------------------------------------------------------------------------------------- hf 14b config available offline: no --------------------------------------------------------------------------------------- hf 14b list available offline: yes Alias of `trace list -t 14b -c` with selected protocol data to annotate trace buffer You can load a trace from file (see `trace load -h`) or it be downloaded from device by default It accepts all other arguments of `trace list`. Note that some might not be relevant for this specific protocol", + "description": "--------- ----------------------- General ----------------------- help This help list List ISO-14443-B history --------- ----------------------- Operations ----------------------- view Display content from tag dump file --------------------------------------------------------------------------------------- hf 14b config available offline: no --------------------------------------------------------------------------------------- hf 14b list available offline: yes Alias of `trace list -t 14b -c` with selected protocol data to annotate trace buffer You can load a trace from file (see `trace load -h`) or it be downloaded from device by default It accepts all other arguments of `trace list`. Note that some might not be relevant for this specific protocol", "notes": [ "hf 14b list --frame -> show frame delay times", "hf 14b list -1 -> use trace buffer" @@ -1871,32 +1873,22 @@ ], "usage": "hf 14b tearoff [-h] -b -d [--adj ] [--safety ] [--start ]" }, - "hf 14b valid": { - "command": "hf 14b valid", - "description": "SRIX checksum test", - "notes": [ - "hf 14b valid" - ], - "offline": true, - "options": [ - "-h, --help This help" - ], - "usage": "hf 14b valid [-h]" - }, "hf 14b view": { "command": "hf 14b view", "description": "Print a ISO14443-B dump file (bin/eml/json) note: - command expects the filename to contain a UID which is needed to determine card memory type", "notes": [ - "hf 14b view -f hf-14b-01020304-dump.bin" + "hf 14b view -f hf-14b-01020304-dump.bin", + "hf 14b view --selftest" ], "offline": true, "options": [ "-h, --help This help", "-f, --file Specify a filename for dump file", "-v, --verbose verbose output", - "-z, --dense dense dump output style" + "-z, --dense dense dump output style", + "--selftest Run the dump parsers self tests and exit" ], - "usage": "hf 14b view [-hvz] -f " + "usage": "hf 14b view [-hvz] [-f ] [--selftest]" }, "hf 14b wrbl": { "command": "hf 14b wrbl", @@ -1921,7 +1913,7 @@ }, "hf 15 cfinalize": { "command": "hf 15 cfinalize", - "description": "Finalize a magic ISO15693 'V3' tag. This operation is irreversible. After finalize the configuration area is erased and the UID can no longer be changed. Set the UID with `hf 15 csetuid --v3` first, then lock it in with this command.", + "description": "Finalize a magic ISO15693 'V3' tag. This operation is irreversible. It locks the UID for good, clears the configuration blocks and shifts the block numbering. Set it with `hf 15 csetuid --v3` first, then lock it in with this command.", "notes": [ "hf 15 cfinalize -y" ], @@ -1934,7 +1926,7 @@ }, "hf 15 csetuid": { "command": "hf 15 csetuid", - "description": "Set UID for magic Chinese card (only works with such cards) For magic 'V3' tags this writes the UID configuration only and is repeatable; run `hf 15 cfinalize` afterwards to lock the UID permanently.", + "description": "Set UID for magic Chinese card (only works with such cards) Gen1 and V3 probe their backdoor blocks first and refuse to write if they read back real data, to avoid corrupting a normal (non-magic) tag. For magic 'V3' tags this writes the UID configuration only and is repeatable; run `hf 15 cfinalize` afterwards to lock the UID permanently.", "notes": [ "hf 15 csetuid -u E011223344556677 -> use gen1 command", "hf 15 csetuid -u E011223344556677 --v2 -> use gen2 command", @@ -3216,15 +3208,17 @@ "command": "hf felica reader", "description": "Act as a ISO 18092 / FeliCa reader. Look for FeliCa tags until Enter or the pm3 button is pressed", "notes": [ - "hf felica reader -@ -> Continuous mode" + "hf felica reader -@", + "hf felica reader --sys 0003 -@ -> Continuous polling for system 0003" ], "offline": false, "options": [ "-h, --help This help", "-s, --silent silent (no messages)", - "-@ optional - continuous reader mode" + "-@ optional - continuous reader mode", + "--sys poll a specific 2-byte system code (4 attempts, or continuous with -@)" ], - "usage": "hf felica reader [-hs@]" + "usage": "hf felica reader [-hs@] [--sys ]" }, "hf felica resetmode": { "command": "hf felica resetmode", @@ -5994,9 +5988,10 @@ "--2k MIFARE Classic/Plus 2k", "--4k MIFARE Classic 4k / S70", "--ns no save to file", - "-v, --verbose verbose output" + "-v, --verbose verbose output", + "--sk Save extracted keys to binary file" ], - "usage": "hf mf dump [-hv] [-f ] [-k ] [--mini] [--1k] [--2k] [--4k] [--ns]" + "usage": "hf mf dump [-hv] [-f ] [-k ] [--mini] [--1k] [--2k] [--4k] [--ns] [--sk]" }, "hf mf ecfill": { "command": "hf mf ecfill", @@ -6223,7 +6218,7 @@ }, "hf mf gdmgetblk": { "command": "hf mf gdmgetblk", - "description": "Read public block(s) from a GDM card", + "description": "Read public block(s) from a GDM card. With no wakeup flag it auto-detects the card's access mode (WUPA magic auth, gen1a, or gdm alt).", "notes": [ "hf mf gdmgetblk --blk 0", "hf mf gdmgetblk --sec 1 --gdm" @@ -6234,15 +6229,15 @@ "--blk block to read", "--sec sector to read", "-k, --key key 6 bytes (only for --wupa mode)", - "--gdm use gdm alt (20/23) magic wakeup (default)", - "--gen1a use gen1a (40/43) magic wakeup", - "--wupa use regular wakeup (WUPA + magic auth with key)" + "--gdm use gdm alt (20/23) magic wakeup", + "--gen1a access: force gen1a (40/43) magic wakeup", + "--wupa access: force regular wakeup (WUPA + magic auth with key)" ], "usage": "hf mf gdmgetblk [-h] [--blk ] [--sec ] [-k ] [--gdm] [--gen1a] [--wupa]" }, "hf mf gdmgetcfg": { "command": "hf mf gdmgetcfg", - "description": "Get configuration data from a GDM card. By default uses GDM alt wakeup (20/23). Use `--gen1a` or `--wupa` to override.", + "description": "Get configuration data from a GDM card. With no wakeup flag it auto-detects the card's access mode (tries WUPA magic auth, then gen1a, then gdm alt). Use `--gdm`/`--gen1a`/`--wupa` to force one.", "notes": [ "hf mf gdmgetcfg", "hf mf gdmgetcfg --gen1a", @@ -6252,15 +6247,15 @@ "options": [ "-h, --help This help", "-k, --key key 6 bytes (only for --wupa mode)", - "--gdm use gdm alt (20/23) magic wakeup (default)", - "--gen1a use gen1a (40/43) magic wakeup", - "--wupa use regular wakeup (WUPA + magic auth with key)" + "--gdm use gdm alt (20/23) magic wakeup", + "--gen1a access: force gen1a (40/43) magic wakeup", + "--wupa access: force regular wakeup (WUPA + magic auth with key)" ], "usage": "hf mf gdmgetcfg [-h] [-k ] [--gdm] [--gen1a] [--wupa]" }, "hf mf gdmgethidblk": { "command": "hf mf gdmgethidblk", - "description": "Read hidden block(s) from a GDM card", + "description": "Read hidden block(s) from a GDM card. With no wakeup flag it auto-detects the card's access mode (WUPA magic auth, gen1a, or gdm alt).", "notes": [ "hf mf gdmgethidblk --blk 0", "hf mf gdmgethidblk --sec 1 --gdm" @@ -6271,9 +6266,9 @@ "--blk block to read", "--sec sector to read", "-k, --key key 6 bytes (only for --wupa mode)", - "--gdm use gdm alt (20/23) magic wakeup (default)", - "--gen1a use gen1a (40/43) magic wakeup", - "--wupa use regular wakeup (WUPA + magic auth with key)" + "--gdm use gdm alt (20/23) magic wakeup", + "--gen1a access: force gen1a (40/43) magic wakeup", + "--wupa access: force regular wakeup (WUPA + magic auth with key)" ], "usage": "hf mf gdmgethidblk [-h] [--blk ] [--sec ] [-k ] [--gdm] [--gen1a] [--wupa]" }, @@ -6292,7 +6287,7 @@ }, "hf mf gdmsetblk": { "command": "hf mf gdmsetblk", - "description": "Set public block data on a GDM card By default uses GDM alt wakeup (20/23). Use `--gen1a` or `--wupa` to override. `--force` param is used to override warnings like bad ACL writes. if not specified, it will exit if detected", + "description": "Set public block data on a GDM card With no wakeup flag it auto-detects the card's access mode (gen1a, gdm alt, or WUPA magic auth). `--force` param is used to override warnings like bad ACL writes. if not specified, it will exit if detected", "notes": [ "hf mf gdmsetblk --blk 1 -d 000102030405060708090a0b0c0d0e0f", "hf mf gdmsetblk --blk 1 -d 000102030405060708090a0b0c0d0e0f --gen1a", @@ -6304,19 +6299,20 @@ "--blk public block number", "-d, --data bytes to write, 16 hex bytes", "-k, --key key, 6 hex bytes (only for --wupa mode)", - "--gdm use gdm alt (20/23) magic wakeup (default)", - "--gen1a use gen1a (40/43) magic wakeup", - "--wupa use regular wakeup (WUPA + magic auth with key)", + "--gdm access: force gdm alt (20/23) magic wakeup", + "--gen1a access: force gen1a (40/43) magic wakeup", + "--wupa access: force regular wakeup (WUPA + magic auth with key)", "--force override warnings" ], "usage": "hf mf gdmsetblk [-h] --blk -d [-k ] [--gdm] [--gen1a] [--wupa] [--force]" }, "hf mf gdmsetcfg": { "command": "hf mf gdmsetcfg", - "description": "Set configuration data on a GDM card Can either write raw 16 bytes (-d) or configure specific flags. If flags are provided, it will read the config, update flags, and write it back.", + "description": "Set configuration data on a GDM card Can either write raw 16 bytes (-d) or configure specific flags. If flags are provided, it will read the config, update flags, and write it back. With no wakeup flag it auto-detects the card's access mode (WUPA magic auth, gen1a, or gdm alt). `access:` flags select how this command talks to the card; `config:` flags change what is stored.", "notes": [ "hf mf gdmsetcfg -d 850000000000000000005A5A00000008", - "hf mf gdmsetcfg --cuid on --gen1 on", + "hf mf gdmsetcfg --cuid on --wakestyle gen1a", + "hf mf gdmsetcfg --wakestyle off", "hf mf gdmsetcfg --shadow off --sigsec off --wupa -k FFFFFFFFFFFF" ], "offline": false, @@ -6324,22 +6320,22 @@ "-h, --help This help", "-d, --data raw bytes to write, 16 hex bytes", "-k, --key key 6 bytes (only for regular wakeup)", - "--gdm use gdm alt (20/23) magic wakeup (default)", - "--gen1a use gen1a (40/43) magic wakeup", - "--wupa use regular wakeup (WUPA + magic auth with key)", - "--gen1 Gen1 mode (7A FF)", - "--cuid Gen2/CUID mode", - "--cl2 CL2 mode (7-byte UID) - pair with `hf mf gdmsetuid -u <7-byte>` to set a valid UID", - "--shadow Shadow mode", - "--magicauth Magic auth", - "--statenc Static encrypted nonce", - "--sigsec Signature sector" + "--gdm access: force gdm alt (20/23) magic wakeup", + "--gen1a access: force gen1a (40/43) magic wakeup", + "--wupa access: force regular wakeup (WUPA + magic auth with key)", + "--cuid config: Gen2/CUID mode", + "--cl2 config: CL2 mode (7-byte UID) - pair with `hf mf gdmsetuid -u <7-byte>`", + "--shadow config: Shadow mode", + "--magicauth config: Magic auth (what --wupa uses)", + "--statenc config: Static encrypted nonce", + "--sigsec config: Signature sector", + "--wakestyle config: backdoor - gdm (7AFF85), gen1a (7AFF00), or off (8500, seal)" ], - "usage": "hf mf gdmsetcfg [-h] [-d ] [-k ] [--gdm] [--gen1a] [--wupa] [--gen1 ] [--cuid ] [--cl2 ] [--shadow ] [--magicauth ] [--statenc ] [--sigsec ]" + "usage": "hf mf gdmsetcfg [-h] [-d ] [-k ] [--gdm] [--gen1a] [--wupa] [--cuid ] [--cl2 ] [--shadow ] [--magicauth ] [--statenc ] [--sigsec ] [--wakestyle ]" }, "hf mf gdmsethidblk": { "command": "hf mf gdmsethidblk", - "description": "Write hidden block data on a GDM card. Hidden blocks 0-7 map to the card's hidden sector area. By default uses GDM alt wakeup (20/23). Use `--gen1a` or `--wupa` to override. `--force` param is used to override warnings like bad BCC or ACL writes. if not specified, it will exit if detected", + "description": "Write hidden block data on a GDM card. Hidden blocks 0-7 map to the card's hidden sector area. With no wakeup flag it auto-detects a backdoor (gen1a or gdm alt); a WUPA-only card is rejected. `--force` param is used to override warnings like bad BCC or ACL writes. if not specified, it will exit if detected", "notes": [ "hf mf gdmsethidblk --blk 0 -d 880494716904EA0C2394510800000000", "hf mf gdmsethidblk --blk 0 -d 880494716904EA0C2394510800000000 --gen1a", @@ -6352,16 +6348,16 @@ "--blk hidden block number (0-7)", "-d, --data bytes to write, 16 hex bytes", "-k, --key key 6 bytes (only for --wupa mode)", - "--gdm use gdm alt (20/23) magic wakeup (default)", - "--gen1a use gen1a (40/43) magic wakeup", - "--wupa use regular wakeup (WUPA + magic auth with key)", + "--gdm access: force gdm alt (20/23) magic wakeup", + "--gen1a access: force gen1a (40/43) magic wakeup", + "--wupa access: force regular wakeup (WUPA + magic auth with key)", "--force override warnings" ], "usage": "hf mf gdmsethidblk [-h] --blk -d [-k ] [--gdm] [--gen1a] [--wupa] [--force]" }, "hf mf gdmsetsig": { "command": "hf mf gdmsetsig", - "description": "Set MFC EV1 signature on a GDM card", + "description": "Set MFC EV1 signature on a GDM card. With no wakeup flag it auto-detects a backdoor (gen1a or gdm alt); a WUPA-only card is rejected.", "notes": [ "hf mf gdmsetsig -s <64 hex chars>" ], @@ -6370,15 +6366,15 @@ "-h, --help This help", "-s, --sig 32-byte signature (64 hex characters)", "-k, --key key 6 bytes (only for --wupa mode)", - "--gdm use gdm alt (20/23) magic wakeup (default)", - "--gen1a use gen1a (40/43) magic wakeup", - "--wupa use regular wakeup (WUPA + magic auth with key)" + "--gdm access: force gdm alt (20/23) magic wakeup", + "--gen1a access: force gen1a (40/43) magic wakeup", + "--wupa access: force regular wakeup (WUPA + magic auth with key)" ], "usage": "hf mf gdmsetsig [-h] -s [-k ] [--gdm] [--gen1a] [--wupa]" }, "hf mf gdmsetuid": { "command": "hf mf gdmsetuid", - "description": "Set UID on a GDM card", + "description": "Set UID on a GDM card. With no wakeup flag it auto-detects a backdoor (gen1a or gdm alt); a WUPA-only card is rejected.", "notes": [ "hf mf gdmsetuid -u 01020304", "hf mf gdmsetuid -u 01020304050607 --gen1a" @@ -6388,16 +6384,16 @@ "-h, --help This help", "-u, --uid UID to set (4 or 7 hex bytes)", "-k, --key key 6 bytes (only for --wupa mode)", - "--gdm use gdm alt (20/23) magic wakeup (default)", - "--gen1a use gen1a (40/43) magic wakeup", - "--wupa use regular wakeup (WUPA + magic auth with key)", + "--gdm access: force gdm alt (20/23) magic wakeup", + "--gen1a access: force gen1a (40/43) magic wakeup", + "--wupa access: force regular wakeup (WUPA + magic auth with key)", "--f3d use F3 perso mode (writes to hidden block 1 instead of 0)" ], "usage": "hf mf gdmsetuid [-h] -u [-k ] [--gdm] [--gen1a] [--wupa] [--f3d]" }, "hf mf gdmwipe": { "command": "hf mf gdmwipe", - "description": "Wipe a GDM card to factory defaults", + "description": "Wipe a GDM card to factory defaults. With no wakeup flag it auto-detects a backdoor (gen1a or gdm alt); a WUPA-only card is rejected.", "notes": [ "hf mf gdmwipe --gdm" ], @@ -6405,9 +6401,9 @@ "options": [ "-h, --help This help", "-k, --key key 6 bytes (only for --wupa mode)", - "--gdm use gdm alt (20/23) magic wakeup (default)", - "--gen1a use gen1a (40/43) magic wakeup", - "--wupa use regular wakeup (WUPA + magic auth with key)", + "--gdm access: force gdm alt (20/23) magic wakeup", + "--gen1a access: force gen1a (40/43) magic wakeup", + "--wupa access: force regular wakeup (WUPA + magic auth with key)", "-a, --all wipe 4K card (40 sectors) instead of 1K card (16 sectors)" ], "usage": "hf mf gdmwipe [-ha] [-k ] [--gdm] [--gen1a] [--wupa]" @@ -7000,7 +6996,9 @@ "hf mf sen", "hf mf sen --keep-nonces", "hf mf sen --no-oob", - "hf mf sen --reader" + "hf mf sen --reader", + "hf mf sen --suffix mycard", + "hf mf sen --ns" ], "offline": false, "options": [ @@ -7011,9 +7009,11 @@ "--offline-only stop after offline filtering, do not verify online", "--online-confirm only do online confirmation (skip generation if nonces loaded)", "--max-online-candidates abort online phase if total candidates exceed this limit", - "--parity-mask parity filter mask 1..F (default 1 = vetted staticnested_1nt behavior)" + "--parity-mask parity filter mask 1..F (default 1 = vetted staticnested_1nt behavior)", + "--suffix Add this suffix to generated files", + "--ns no save to file (--keep-nonces still writes its evidence file)" ], - "usage": "hf mf sen [-h] [--keep-nonces] [--no-oob] [--reader] [--offline-only] [--online-confirm] [--max-online-candidates ] [--parity-mask ]" + "usage": "hf mf sen [-h] [--keep-nonces] [--no-oob] [--reader] [--offline-only] [--online-confirm] [--max-online-candidates ] [--parity-mask ] [--suffix ] [--ns]" }, "hf mf setmod": { "command": "hf mf setmod", @@ -7142,16 +7142,18 @@ "command": "hf mf view", "description": "Print a MIFARE Classic dump file (bin/eml/json)", "notes": [ - "hf mf view -f hf-mf-01020304-dump.bin" + "hf mf view -f hf-mf-01020304-dump.bin", + "hf mf view --selftest" ], "offline": true, "options": [ "-h, --help This help", "-f, --file Specify a filename for dump file", "-v, --verbose verbose output", - "--sk Save extracted keys to binary file" + "--sk Save extracted keys to binary file", + "--selftest Run the dump parsers self tests and exit" ], - "usage": "hf mf view [-hv] -f [--sk]" + "usage": "hf mf view [-hv] [-f ] [--sk] [--selftest]" }, "hf mf wipe": { "command": "hf mf wipe", @@ -7206,7 +7208,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7256,7 +7258,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number (default: 0 / PICC key)", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7310,7 +7312,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7343,7 +7345,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7367,18 +7369,19 @@ "command": "hf mfdes chk", "description": "Checks keys with MIFARE DESFire card.", "notes": [ - "hf mfdes chk --aid 123456 -k 000102030405060708090a0b0c0d0e0f -> check key on aid 0x123456", - "hf mfdes chk -f mfdes_default_keys -> check keys against all existing aid on card", - "hf mfdes chk -f mfdes_default_keys --aid 123456 -> check keys against aid 0x123456", - "hf mfdes chk --aid 123456 --pattern1b -j keys -> check all 1-byte keys pattern on aid 0x123456 and save found keys to `keys.json`", - "hf mfdes chk --aid 123456 --pattern2b --startp2b FA00 -> check all 2-byte keys pattern on aid 0x123456. Start from key FA00FA00...FA00" + "hf mfdes chk -f mfdes_default_keys -> check keys against all existing AID on card", + "hf mfdes chk --aid 123456 -f mfdes_default_keys -> check keys against AID 0x123456", + "hf mfdes chk --aid 123456 --pattern1b -j keys -> check all 1-byte keys pattern on AID 0x123456 and save found keys to `keys.json`", + "hf mfdes chk --aid 123456 --pattern2b --startp2b FA00 -> check all 2-byte keys pattern on AID 0x123456. Start from key FA00FA00...FA00", + "hf mfdes chk --aid 123456 -k 000102030405060708090a0b0c0d0e0f -> check key on AID 0x123456", + "hf mfdes chk -f mfdes_default_keys --schann lrp -> check keys, forcing the LRP secure channel" ], "offline": false, "options": [ "-h, --help This help", "--aid Use specific AID (3 hex bytes, big endian)", - "-k, --key Key for checking (HEX 16 bytes)", - "-f, --file Filename of dictionary", + "-k, --key Key for authenticate (8|16|24 hex bytes)", + "-f, --file Filename of dictionary (default: `mfdes_default_keys`)", "--pattern1b Check all 1-byte combinations of key (0000...0000, 0101...0101, 0202...0202, ...)", "--pattern2b Check all 2-byte combinations of key (0000...0000, 0001...0001, 0002...0002, ...)", "--startp2b Start key (2-byte HEX) for 2-byte search (use with `--pattern2b`)", @@ -7386,9 +7389,10 @@ "-v, --verbose Verbose output", "--kdf <0|1|2> Key Derivation Function (KDF) (0=None, 1=AN10922, 2=Gallagher)", "-i, --kdfi KDF input (1-31 hex bytes)", + "--schann Secure channel (default: detected per application)", "-a, --apdu Show APDU requests and responses" ], - "usage": "hf mfdes chk [-hva] [--aid ] [-k ] [-f ] [--pattern1b] [--pattern2b] [--startp2b ] [-j ] [--kdf <0|1|2>] [-i ]" + "usage": "hf mfdes chk [-hva] [--aid ] [-k ] [-f ] [--pattern1b] [--pattern2b] [--startp2b ] [-j ] [--kdf <0|1|2>] [-i ] [--schann ]" }, "hf mfdes chkeysettings": { "command": "hf mfdes chkeysettings", @@ -7404,7 +7408,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7429,7 +7433,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7486,7 +7490,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7523,7 +7527,7 @@ "-a, --apdu Show APDU requests and responses", "-v, --verbose Verbose output", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7567,7 +7571,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7611,7 +7615,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7647,7 +7651,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7684,7 +7688,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7723,7 +7727,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo (deft: 2TDEA)", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7756,7 +7760,7 @@ "-h, --help This help", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7778,7 +7782,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7802,7 +7806,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7817,22 +7821,22 @@ }, "hf mfdes detect": { "command": "hf mfdes detect", - "description": "Detect key type and tries to find one from the list.", + "description": "Detect PICC master key, key type, communication mode, command set and channel mode. Uses `mfdes_default_keys.dic` per default `--save` it saves details to be used with `hf mfdes default`", "notes": [ - "hf mfdes detect -> detect key 0 from PICC level", - "hf mfdes detect --schann d40 -> detect key 0 from PICC level via secure channel D40", - "hf mfdes detect -f mfdes_default_keys -> detect key 0 from PICC level with help of the standard dictionary", - "hf mfdes detect --aid 123456 -n 2 --save -> detect key 2 from app 123456 and if succeed - save params to defaults (`default` command)", - "hf mfdes detect --isoid df01 --save -> detect key 0 and save to defaults with card in the LRP mode" + "hf mfdes detect", + "hf mfdes detect --schann d40 -> detect from PICC level via secure channel D40", + "hf mfdes detect -f my_keys -> detect from PICC level with your own dictionary", + "hf mfdes detect --aid 123456 -n 2 --save -> detect key 2 from app 123456 and save params to defaults", + "hf mfdes detect --isoid df01 --save -> detect and save to defaults with card in the LRP mode" ], "offline": false, "options": [ "-h, --help This help", "-a, --apdu Show APDU requests and responses", "-v, --verbose Verbose output", - "-n, --keyno Key number", + "-n, --keyno Key number (def: all)", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7841,16 +7845,19 @@ "--aid Application ID (3 hex bytes, big endian)", "--isoid Application ISO ID (ISO DF ID) (2 hex bytes, big endian).", "--dfname Application ISO DF Name (5-16 hex bytes, big endian)", - "-f, --file Filename of dictionary", + "-f, --file Filename of dictionary (default: `mfdes_default_keys`)", "--save Save found key and parameters to defaults" ], "usage": "hf mfdes detect [-hav] [-n ] [-t ] [-k ] [--kdf ] [-i ] [-m ] [-c ] [--schann ] [--aid ] [--isoid ] [--dfname ] [-f ] [--save]" }, "hf mfdes dump": { "command": "hf mfdes dump", - "description": "For each application show fil list and then file content. Key needs to be provided for authentication or flag --no-auth set (depend on cards settings).", + "description": "Dump a DESFire card to a json file. Walks every application and every file unless an application is named with --aid / --isoid / --dfname. Key needs to be provided for authentication or flag --no-auth set (depend on cards settings).", "notes": [ - "hf mfdes dump --aid 123456 -> show file dump for: app=123456 with channel defaults from `default` command/nhf mfdes dump --isoid df01 --schann lrp -t aes --length 000090 -> lrp default settings with length limit" + "hf mfdes dump -> dump the whole PICC with channel defaults from `default` command", + "hf mfdes dump --aid 123456 -> dump only application 123456", + "hf mfdes dump --keys hf-mfdes-0102030405-keys.json -> use recovered keys per application", + "hf mfdes dump --isoid df01 --schann lrp -t aes --length 000090 -> lrp default settings with length limit" ], "offline": false, "options": [ @@ -7859,7 +7866,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7869,9 +7876,80 @@ "--isoid Application ISO ID (ISO DF ID) (2 hex bytes, big endian)", "--dfname Application ISO DF Name (5-16 hex bytes, big endian)", "-l, --length Maximum length for read data files (3 hex bytes, big endian)", - "--no-auth Execute without authentication" + "--no-auth Execute without authentication", + "-f, --file Save dump to file, if no UID will be used as filename", + "--keys Load application keys from a `hf mfdes chk` key file", + "--ns No save to file" ], - "usage": "hf mfdes dump [-hav] [-n ] [-t ] [-k ] [--kdf ] [-i ] [-m ] [-c ] [--schann ] [--aid ] [--isoid ] [--dfname ] [-l ] [--no-auth]" + "usage": "hf mfdes dump [-hav] [-n ] [-t ] [-k ] [--kdf ] [-i ] [-m ] [-c ] [--schann ] [--aid ] [--isoid ] [--dfname ] [-l ] [--no-auth] [-f ] [--keys ] [--ns]" + }, + "hf mfdes eload": { + "command": "hf mfdes eload", + "description": "Load a DESFire card dump into emulator memory. The dump is packed into the on-device card image, see doc/mfdes_dump_format.md", + "notes": [ + "hf mfdes eload -f hf-mfdes-01020304050607-dump.json" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-f, --file Filename of dump", + "-v, --verbose Verbose output" + ], + "usage": "hf mfdes eload [-hv] -f " + }, + "hf mfdes esave": { + "command": "hf mfdes esave", + "description": "Save the card image in emulator memory to a dump file. Shows what a reader left behind if one has been talking to the simulation. A deleted application or file is kept in the image as a tombstone, because the memory it held stays spent until a FormatPICC. By default those are left out, so the dump is the card as a reader sees it. Use `--keep` to save them as well, which is what you want to see everything a reader did rather than only the result", + "notes": [ + "hf mfdes esave -f myfile", + "hf mfdes esave -f myfile --keep -> keep applications and files a reader deleted" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-f, --file Filename, if no UID will be used as filename", + "-v, --verbose Verbose output", + "--keep Keep applications and files that were deleted" + ], + "usage": "hf mfdes esave [-hv] [-f ] [--keep]" + }, + "hf mfdes etest": { + "command": "hf mfdes etest", + "description": "Drive the DESFire simulation from the host over USB, no RF involved. The card image in emulator memory answers each --apdu, native or ISO 7816 wrapped, as `hf mfdes sim` would over the air. Bytes given with --random are drawn in order by the next random UID (3, at --scan on a random-id image) and RndB (8 or 16, at the next authentication), so a recorded session can be replayed. One action per call. Load an image first with `hf mfdes eload`", + "notes": [ + "hf mfdes etest --begin", + "hf mfdes etest --scan", + "hf mfdes etest --random 0102030405060708", + "hf mfdes etest --apdu 900A0000010000 -j", + "hf mfdes etest --state -j", + "hf mfdes etest --end" + ], + "offline": false, + "options": [ + "-h, --help This help", + "--begin Check the image, clear the random queue", + "--end Drop the state and the random queue", + "--scan RF reset and activation, show UID/ATQA/SAK/ATS", + "--apdu Send one command, show the answer", + "--random Queue bytes for the next RndB / random UID draws", + "--fieldoff RF reset, session dropped", + "--state Show session and random queue state", + "-j, --json One line of JSON instead of text" + ], + "usage": "hf mfdes etest [-hj] [--begin] [--end] [--scan] [--apdu ] [--random ] [--fieldoff] [--state]" + }, + "hf mfdes eview": { + "command": "hf mfdes eview", + "description": "Show the DESFire card image currently in emulator memory", + "notes": [ + "hf mfdes eview" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-v, --verbose Also print every application and file" + ], + "usage": "hf mfdes eview [-hv]" }, "hf mfdes formatpicc": { "command": "hf mfdes formatpicc", @@ -7886,7 +7964,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7909,7 +7987,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7933,7 +8011,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7956,7 +8034,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7982,7 +8060,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number (default: 0 / PICC key)", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7998,8 +8076,8 @@ "description": "Get File IDs list from card. Master key needs to be provided or flag --no-auth set.", "notes": [ "hf mfdes getfileids --aid 123456 -> execute with defaults from `default` command", - "hf mfdes getfileids -n 0 -t des -k 0000000000000000 --kdf none --aid 123456 -> execute with default factory setup", - "hf mfdes getfileids --dfname D2760000850100 -> select DF by name and get file IDs" + "hf mfdes getfileids --dfname D2760000850100 -> select DF by name and get file IDs", + "hf mfdes getfileids -n 0 -t des -k 0000000000000000 --aid 123456 -> execute with default factory setup" ], "offline": false, "options": [ @@ -8008,7 +8086,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8038,7 +8116,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8067,7 +8145,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8096,7 +8174,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8124,7 +8202,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number for authentication", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8154,7 +8232,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8184,7 +8262,7 @@ }, "hf mfdes help": { "command": "hf mfdes help", - "description": "help This help list List DESFire (ISO 14443A) history makemfclicense Generate a Mifare Classic license for DESFire EV3C test Regression crypto tests --------------------------------------------------------------------------------------- hf mfdes list available offline: yes Alias of `trace list -t des -c` with selected protocol data to annotate trace buffer You can load a trace from file (see `trace load -h`) or it be downloaded from device by default It accepts all other arguments of `trace list`. Note that some might not be relevant for this specific protocol", + "description": "help This help list List DESFire (ISO 14443A) history view Display content from tag dump file makemfclicense Generate a Mifare Classic license for DESFire EV3C test Regression crypto tests --------------------------------------------------------------------------------------- hf mfdes list available offline: yes Alias of `trace list -t des -c` with selected protocol data to annotate trace buffer You can load a trace from file (see `trace load -h`) or it be downloaded from device by default It accepts all other arguments of `trace list`. Note that some might not be relevant for this specific protocol", "notes": [ "hf mfdes list --frame -> show frame delay times", "hf mfdes list -1 -> use trace buffer" @@ -8256,7 +8334,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8284,7 +8362,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8315,7 +8393,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8338,7 +8416,7 @@ "options": [ "-h, --help This help", "-v, --verbose Show more output", - "-k, --key Key for computing the MAC, must be HEX 16(AES)", + "-k, --key Key for computing the MAC (16 hex bytes)", "-b, --blk [,[,...]] The MFC blocks to map, must be given in ascending order (use the special value 'all' for all blocks)", "--ka Allow updating key A from inside sector trailers mapped to DESFire files", "--kb Allow updating key B from inside sector trailers mapped to DESFire files", @@ -8398,7 +8476,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8435,7 +8513,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8498,7 +8576,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8511,6 +8589,18 @@ ], "usage": "hf mfdes setconfig [-hav] [-n ] [-t ] [-k ] [--kdf ] [-i ] [-m ] [-c ] [--schann ] [--aid ] [--isoid ] [-p ] [-d ]" }, + "hf mfdes sim": { + "command": "hf mfdes sim", + "description": "Simulate the DESFire card image currently in emulator memory. Load one first with `hf mfdes eload`, and read back what a reader changed with `hf mfdes esave`. UID, ATQA, SAK and ATS all come out of the loaded image", + "notes": [ + "hf mfdes sim" + ], + "offline": false, + "options": [ + "-h, --help This help" + ], + "usage": "hf mfdes sim [-h]" + }, "hf mfdes test": { "command": "hf mfdes test", "description": "Regression crypto tests", @@ -8540,7 +8630,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo (deft: 2TDEA)", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8604,7 +8694,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number for DESFire authentication", "-t, --algo DESFire auth crypt algo", - "-k, --key DESFire authentication key", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communication mode", @@ -8615,7 +8705,7 @@ "--dfname Certificate application DF name (1-16 bytes)", "--fid Certificate file ID (1 byte)", "--no-auth Read certificate file without authentication", - "--ca CA input, or `skip` to skip certificate signature validation. Repeat --ca for multiple entries", + "--ca CA input, or `skip` to skip validation", "--keyaid Key application ID (default: cert app)", "--keyisoid Key application ISO DF ID (2 bytes)", "--keydfname Key application DF name (default: cert app)", @@ -8625,6 +8715,22 @@ ], "usage": "hf mfdes verifycert [-hav] [] [-n ] [-t ] [-k ] [--kdf ] [-i ] [-m ] [-c ] [--schann ] [--aid ] [--isoid ] [--dfname ] [--fid ] [--no-auth] [--ca ]... [--keyaid ] [--keyisoid ] [--keydfname ] [--keyidx ] [--validatemethod ] [--readmethod ]" }, + "hf mfdes view": { + "command": "hf mfdes view", + "description": "Print a DESFire card dump file (json)", + "notes": [ + "hf mfdes view -f hf-mfdes-01020304050607-dump.json", + "hf mfdes view --selftest" + ], + "offline": true, + "options": [ + "-h, --help This help", + "-f, --file Filename of dump", + "-v, --verbose Verbose output", + "--selftest Run the dump parsers self tests and exit" + ], + "usage": "hf mfdes view [-hv] [-f ] [--selftest]" + }, "hf mfdes write": { "command": "hf mfdes write", "description": "Write data from file. Key needs to be provided or flag --no-auth set (depend on file settings).", @@ -8652,7 +8758,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -9112,26 +9218,6 @@ ], "usage": "hf mfu aesauth [-hlkn0] [--key ] [-i <0..2>] [--schann] [-r ]" }, - "hf mfu aeschk": { - "command": "hf mfu aeschk", - "description": "It checks MIFARE Ultralight AES tags keys against a dictionary file with keys Key index 0... DataProtKey (default) Key index 1... UIDRetrKey Key index 2... OriginalityKey", - "notes": [ - "hf mfu aeschk -f mfulaes_default_keys.dic" - ], - "offline": false, - "options": [ - "-h, --help This help", - "-f, --file filename of dictionary", - "-i, --idx <0..2> Key index (def: 0)", - "-s, --segment <0..3> Segment index (full key if not specified)", - "-r, --retries <0..255> Number of retries (def: 0)", - "-k, --key Starting key, 16 hex bytes (def: zero key), for segment check", - "-x, --xor XOR starting key with segment candidates (def: override)", - "-n, --nocheck Skip checking tag answer correctness", - "-0, --read0 Use fast READ0 (skip anticol)" - ], - "usage": "hf mfu aeschk [-hxn0] [-f ] [-i <0..2>] [-s <0..3>] [-r <0..255>] [-k ]" - }, "hf mfu aesgetuid": { "command": "hf mfu aesgetuid", "description": "Retreives real UID on Mifare Ultralight AES tags when random ID is enabled. Uses key index 1 (UIDRetrKey). If no key is specified, null key will be tried.", @@ -9193,16 +9279,20 @@ ], "usage": "hf mfu cauth [-hlkn0] [--key ] [-r ] [--noauth] [--reset] [--collect] [--pair ]..." }, - "hf mfu cchk": { - "command": "hf mfu cchk", - "description": "It checks MIFARE Ultralight C tags keys against a dictionary file with keys", + "hf mfu chk": { + "command": "hf mfu chk", + "description": "Checks MIFARE Ultralight C / Ultralight AES tag keys against a dictionary file. The tag type is read off the card and picks the key slot to attack. UL-C ..... single 3DES key, --idx does not apply UL-AES ... key index 0 DataProtKey (default) key index 1 UIDRetrKey key index 2 OriginalityKey Without -f, mfulc_default_keys.dic is used for both tag types. A segment check (-s) holds 4 byte keys, so it needs its own dictionary via -f.", "notes": [ - "hf mfu cchk -f mfulc_default_keys.dic" + "hf mfu chk", + "hf mfu chk -f mfulc_default_keys.dic", + "hf mfu chk -f mfulaes_hw1.dic --idx 1", + "hf mfu chk -f mfulc_segment_hw1.dic -s 0" ], "offline": false, "options": [ "-h, --help This help", "-f, --file filename of dictionary", + "-i, --idx <0..2> Key index, Ultralight AES only (def: 0)", "-s, --segment <0..3> Segment index (full key if not specified)", "-r, --retries <0..255> Number of retries (def: 0)", "-k, --key Starting key, 16 hex bytes (def: zero key), for segment check", @@ -9210,7 +9300,7 @@ "-n, --nocheck Skip checking tag answer correctness", "-0, --read0 Use fast READ0 (skip anticol)" ], - "usage": "hf mfu cchk [-hxn0] [-f ] [-s <0..3>] [-r <0..255>] [-k ]" + "usage": "hf mfu chk [-hxn0] [-f ] [-i <0..2>] [-s <0..3>] [-r <0..255>] [-k ]" }, "hf mfu countertear": { "command": "hf mfu countertear", @@ -9416,6 +9506,30 @@ ], "usage": "hf mfu keygen [-hr] [-u ] [-b ]" }, + "hf mfu ndefformat": { + "command": "hf mfu ndefformat", + "description": "Format a MIFARE Ultralight / NTAG tag for NDEF by writing the Capability Container to block 3, followed by an empty NDEF message. Writes NXP factory delivery content for the detected tag type. Block 3 is One Time Programmable; unknown types and unreachable CCs are refused. Note: the tag is re-selected and re-authenticated for each block written.", + "notes": [ + "hf mfu ndefformat", + "hf mfu ndefformat -v", + "hf mfu ndefformat --erase", + "hf mfu ndefformat -k FFFFFFFF", + "hf mfu ndefformat -k 49454D4B41455242214E4143554F5946", + "hf mfu ndefformat -d E1101200 --force" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-k, --key Authentication key (UL-C/UL-AES 16 bytes, EV1/NTAG 4 bytes)", + "-l Swap entered key endianness", + "-d, --data Capability Container to write, 4 bytes. Overrides the detected type", + "--erase Also zero the rest of the NDEF data area", + "--force Continue on an unknown tag type, or with an oversized -d value", + "-v, --verbose Verbose output", + "--schann use secure channel. Must have key" + ], + "usage": "hf mfu ndefformat [-hlv] [-k ] [-d ] [--erase] [--force] [--schann]" + }, "hf mfu ndefread": { "command": "hf mfu ndefread", "description": "Prints NFC Data Exchange Format (NDEF)", @@ -9530,6 +9644,7 @@ "hf mfu restore -f myfile -s -> special write", "hf mfu restore -f myfile -k AABBCCDD -s -> special write, use key", "hf mfu restore -f myfile -k AABBCCDD -ser -> special write, use key, write dump pwd, ...", + "hf mfu restore -f myfile -k 00112233445566778899AABBCCDDEEFF -> UL-C / UL-AES, use key", "", "Note: Restoring a NTAG/UL dump to a UMC will likely result in incorrect PWD and PACK" ], @@ -9537,7 +9652,7 @@ "options": [ "-h, --help This help", "-f, --file Specify a filename for dump file", - "-k, --key key for authentication (UL-C 16 bytes, EV1/NTAG 4 bytes)", + "-k, --key key for authentication (UL-C/UL-AES 16 bytes, EV1/NTAG 4 bytes)", "-l swap entered key's endianness", "-s enable special write UID -MAGIC TAG ONLY-", "-e enable special write version/signature -MAGIC NTAG 21* ONLY-", @@ -9746,6 +9861,20 @@ ], "usage": "hf ntag424 getfs [-h] --fileno " }, + "hf ntag424 gettt": { + "command": "hf ntag424 gettt", + "description": "Read and print Tag Tamper status. Will authenticate if key information is provided.", + "notes": [ + "hf ntag424 gettt --keyno 0 -k 00000000000000000000000000000000" + ], + "offline": false, + "options": [ + "-h, --help This help", + "--keyno Key number", + "-k, --key Key for authentication (HEX 16 bytes)" + ], + "usage": "hf ntag424 gettt [-h] [--keyno ] [-k ]" + }, "hf ntag424 help": { "command": "hf ntag424 help", "description": "help This help view Display content from tag dump file --------------------------------------------------------------------------------------- hf ntag424 info available offline: no Get info about NXP NTAG424 DNA Family styled tag.", @@ -9778,6 +9907,21 @@ ], "usage": "hf ntag424 read [-h] --fileno <1|2|3> [--keyno ] [-k ] [-o ] -l [-m ]" }, + "hf ntag424 setconfig": { + "command": "hf ntag424 setconfig", + "description": "Change a PICC configuration option. Several options are one-way, see the datasheet before using this.", + "notes": [ + "hf ntag424 setconfig -k 00000000000000000000000000000000 --option 07 -d 0100" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-k, --key0 Authentication key (must be key 0, HEX 16 bytes)", + "--option Configuration option (HEX 1 byte)", + "-d, --data Option data (HEX, 1..47 bytes)" + ], + "usage": "hf ntag424 setconfig [-h] -k --option -d [-d ]..." + }, "hf ntag424 view": { "command": "hf ntag424 view", "description": "Print a NTAG 424 DNA dump file (bin/eml/json)", @@ -10447,7 +10591,7 @@ }, "hf thinfilm help": { "command": "hf thinfilm help", - "description": "help This help list List NFC Barcode / Thinfilm history - not correct --------------------------------------------------------------------------------------- hf thinfilm info available offline: no Get info from Thinfilm tags", + "description": "help This help list List NFC Barcode / Thinfilm history --------------------------------------------------------------------------------------- hf thinfilm info available offline: no Get info from Thinfilm tags", "notes": [ "hf thinfilm info" ], @@ -10492,6 +10636,20 @@ ], "usage": "hf thinfilm sim [-h] -d [--raw]" }, + "hf thinfilm sniff": { + "command": "hf thinfilm sniff", + "description": "Sniff the frames a Thinfilm / NFC Barcode tag beams at a reader. The tag talks first and the reader sends nothing, so only the tag side is decoded. Use `hf thinfilm list` to view collected data.", + "notes": [ + "hf thinfilm sniff", + "hf thinfilm sniff -i" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-i, --interactive Console will not be returned until sniff finishes or is aborted" + ], + "usage": "hf thinfilm sniff [-hi]" + }, "hf topaz dump": { "command": "hf topaz dump", "description": "Dump TOPAZ tag to file (bin/json) If no given, UID will be used as filename", @@ -10874,83 +11032,224 @@ ], "usage": "hw break [-h]" }, - "hw bwmautooff": { - "command": "hw bwmautooff", - "description": "Toggle automatic power-off when the PM5 is unplugged from USB (BWM only). Default is on. When on, the board powers itself down ~10s after USB is removed, so a BWM-equipped PM5 doesn't silently drain the battery. Button power-on is unaffected. Disable for standalone/BLE use on battery. Runtime only: resets to on at each boot.", + "hw bwm ble forget": { + "command": "hw bwm ble forget", + "description": "Remove bonded (paired) devices from the module, so they must pair again with the passkey. Indexes are the ones `hw bwm ble status` lists.", "notes": [ - "hw bwmautooff --off -> disable auto power-off", - "hw bwmautooff --on -> re-enable auto power-off" + "hw bwm ble forget --all", + "hw bwm ble forget -i 0" ], "offline": false, "options": [ "-h, --help This help", - "--on enable auto power-off (default)", - "--off disable auto power-off" + "-i, --idx index of the bonded device to remove", + "--all remove all bonded devices" ], - "usage": "hw bwmautooff [-h] [--on] [--off]" + "usage": "hw bwm ble forget [-h] [-i ] [--all]" }, - "hw bwmcharge": { - "command": "hw bwmcharge", + "hw bwm ble help": { + "command": "hw bwm ble help", + "description": "help This help --------------------------------------------------------------------------------------- hw bwm ble status available offline: no Show the module's BLE settings: on/off, name, address, pairing and passkey, bonded devices, TX power.", + "notes": [ + "hw bwm ble status" + ], + "offline": true, + "options": [ + "-h, --help This help" + ], + "usage": "hw bwm ble status [-h]" + }, + "hw bwm ble off": { + "command": "hw bwm ble off", + "description": "Switch the module's BLE radio on or off. Persisted on the module, applied at once. Off means nothing can connect over BLE at all; the PM5 stays reachable over USB (and WiFi if configured). Needs a BWM firmware with the BLE switch. Over BLE, `off` cuts your own connection.", + "notes": [ + "hw bwm ble off" + ], + "offline": false, + "options": [ + "-h, --help This help" + ], + "usage": "hw bwm ble off [-h]" + }, + "hw bwm ble on": { + "command": "hw bwm ble on", + "description": "Switch the module's BLE radio on or off. Persisted on the module, applied at once. Off means nothing can connect over BLE at all; the PM5 stays reachable over USB (and WiFi if configured). Needs a BWM firmware with the BLE switch. Over BLE, `off` cuts your own connection.", + "notes": [ + "hw bwm ble on" + ], + "offline": false, + "options": [ + "-h, --help This help" + ], + "usage": "hw bwm ble on [-h]" + }, + "hw bwm ble pairing": { + "command": "hw bwm ble pairing", + "description": "Require pairing before a BLE client can use the device. The module ships with pairing off: anyone in range can connect and run commands. With it on, a client must pair once with the 6-digit passkey (LE Secure Connections, MITM) and the data characteristic only works over the encrypted link; paired (bonded) devices reconnect without the key until you forget them. Both settings persist on the module. A change of on/off restarts the BLE stack, which drops a connected client - reconnect (and pair) afterwards. The factory passkey is 123456; set your own.", + "notes": [ + "hw bwm ble pairing on -> require pairing", + "hw bwm ble pairing on -k 482913 -> require pairing with this passkey", + "hw bwm ble pairing -k 482913 -> change the passkey only", + "hw bwm ble pairing off -> open access again" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-k, --key <6 digits> passkey a client must enter" + ], + "usage": "hw bwm ble pairing [-h] [-k <6 digits>]" + }, + "hw bwm ble txpower": { + "command": "hw bwm ble txpower", + "description": "Set the module's BLE transmit power for advertising and/or connections. Steps of 3 dB from -24 to 18 dBm, plus 20. Lower saves a little battery and shrinks the range at which the device can be found. Persisted on the module.", + "notes": [ + "hw bwm ble txpower -a 0 -c 0 -> 0 dBm for both", + "hw bwm ble txpower -a -6 -> quieter advertising only" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-a, --adv advertising power", + "-c, --conn connection power" + ], + "usage": "hw bwm ble txpower [-h] [-a ] [-c ]" + }, + "hw bwm charge": { + "command": "hw bwm charge", "description": "Enable or disable BWM battery charging by clearing/setting the AW32001E charge-enable bit (CEB, REG01[3]). PM5 only. One-shot: the charger watchdog reverts this after ~160 s unless serviced, so charging may stop on its own. Use to nudge a top-up.", "notes": [ - "hw bwmcharge -on -> enable charging", - "hw bwmcharge --off -> disable charging" + "hw bwm charge off -> disable charging", + "hw bwm charge on -> enable charging" + ], + "offline": false, + "options": [ + "-h, --help This help" + ], + "usage": "hw bwm charge [-h]" + }, + "hw bwm help": { + "command": "hw bwm help", + "description": "help This help --------------------------------------------------------------------------------------- hw bwm autooff available offline: no Show or set automatic power-off (PM5 only). Two triggers: - USB was present and the cable is pulled: off at once, so a BWM-equipped PM5 doesn't silently drain the battery; --unplug off only restarts the idle clock instead; - on battery with no command, button press or BLE/WiFi client for --idle seconds: off (0 = never, the default). Button power-on is unaffected. Stored on the BWM; without a module, defaults.", + "notes": [ + "hw bwm autooff -> show the current state", + "hw bwm autooff off -> disable both triggers", + "hw bwm autooff on -> re-enable", + "hw bwm autooff --idle 300 -> also off after 5 min idle on battery", + "hw bwm autooff --idle 0 -> USB-unplug trigger only (default)", + "hw bwm autooff --unplug off --idle 300 -> survive the unplug, off 5 min idle later" + ], + "offline": true, + "options": [ + "-h, --help This help", + "-i, --idle idle timeout on battery in seconds, 0 = never", + "-u, --unplug power off when USB is pulled (default on)" + ], + "usage": "hw bwm autooff [-h] [-i ] [-u ]" + }, + "hw bwm name": { + "command": "hw bwm name", + "description": "Get or set the BWM BLE advertising name (stored on the BWM, in NVS). With no --set, prints the current name. Setting a name stores it and reboots the BWM to apply it - this briefly drops a BLE/WiFi connection; reconnect after a few seconds. Over USB the reboot is not noticeable.", + "notes": [ + "hw bwm name -> show current BLE name", + "hw bwm name --set MyPM5 -> set BLE name to 'MyPM5'" ], "offline": false, "options": [ "-h, --help This help", - "--on enable charging (default)", - "--off disable charging" + "--set new BLE name (1-31 chars); omit to read current name" ], - "usage": "hw bwmcharge [-h] [--on] [--off]" + "usage": "hw bwm name [-h] [--set ]" }, - "hw bwmsetcap": { - "command": "hw bwmsetcap", + "hw bwm powersave": { + "command": "hw bwm powersave", + "description": "Show or set the BWM (ESP32) power-save switch, stored on the BWM in NVS. Default is on: the ESP scales its clock down, light-sleeps between link traffic, and after 30 s of fast advertising (boot, disconnect) advertises once a second. off pins it at full clock, no sleep, fast advertising throughout. Applies at once and survives reboots. PM5 only.", + "notes": [ + "hw bwm powersave -> show the current state", + "hw bwm powersave off -> stock always-on behaviour", + "hw bwm powersave on -> re-enable power saving" + ], + "offline": false, + "options": [ + "-h, --help This help" + ], + "usage": "hw bwm powersave [-h]" + }, + "hw bwm setcap": { + "command": "hw bwm setcap", "description": "Program the BWM fuel gauge (BQ27427) Design Capacity for the fitted cell. Run ONCE after fitting or replacing the battery. This triggers a gauge config-update; do not run it repeatedly, as that disrupts the Impedance Track learning cycle. PM5 only.", "notes": [ - "hw bwmsetcap -> set design capacity to default 500 mAh", - "hw bwmsetcap --cap 500 -> set design capacity to 500 mAh" + "hw bwm setcap -> set design capacity to default 500 mAh", + "hw bwm setcap --cap 500 -> set design capacity to 500 mAh" ], "offline": false, "options": [ "-h, --help This help", "--cap design capacity in mAh (default 500)" ], - "usage": "hw bwmsetcap [-h] [--cap ]" + "usage": "hw bwm setcap [-h] [--cap ]" }, - "hw bwmvchg": { - "command": "hw bwmvchg", + "hw bwm upgrade": { + "command": "hw bwm upgrade", + "description": "Reflash the BWM (ESP32) firmware over the BWM link - no header, no soldering. Requires a BWM that still responds; this updates a wrong-version ESP, it cannot recover a fully bricked one (that still needs the 5-pin header + esptool).", + "notes": [ + "hw bwm upgrade -f bwm_esp32.bin" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-f, --file ESP32 firmware image (.bin)", + "--delay per-chunk delay to pace the slow AT32<->ESP UART (default 20)" + ], + "usage": "hw bwm upgrade [-h] -f [--delay ]" + }, + "hw bwm vchg": { + "command": "hw bwm vchg", "description": "Set the BWM charger (AW32001E) charge-voltage regulation target. Lowering it below 4.2 V reduces top-of-charge stress and extends cell life. Snaps to the nearest 15 mV step; clamped to 3600..4200 mV. This is a runtime register write (reverts on the charger watchdog / POR); the firmware re-applies the 4100 mV default at every boot. PM5 only.", "notes": [ - "hw bwmvchg -> set charge voltage to default 4100 mV (->4.095 V)", - "hw bwmvchg --mv 4200 -> set charge voltage to 4200 mV" + "hw bwm vchg -> set charge voltage to default 4100 mV (->4.095 V)", + "hw bwm vchg --mv 4200 -> set charge voltage to 4200 mV" ], "offline": false, "options": [ "-h, --help This help", "--mv charge voltage in mV (default 4100, clamped 3600..4200)" ], - "usage": "hw bwmvchg [-h] [--mv ]" + "usage": "hw bwm vchg [-h] [--mv ]" }, - "hw bwmwifi": { - "command": "hw bwmwifi", - "description": "Bring up the BWM in STA + TCP-server mode: join a WiFi network and start a TCP server so the client can connect over WiFi. PM5 only.", + "hw bwm wifi": { + "command": "hw bwm wifi", + "description": "Bring up the BWM in STA + TCP-server mode: join a WiFi network and start a TCP server so the client can connect over WiFi. PM5 only. Sub-actions (no dashes): 'status' shows state, 'stop' tears WiFi down.", "notes": [ - "hw bwmwifi --ssid Home --pwd secret -> port 7777", - "hw bwmwifi --ssid Home --pwd secret --port 9000", - "hw bwmwifi --status -> show connection state + IP" + "hw bwm wifi status -> show connection state + IP", + "hw bwm wifi stop -> tear down WiFi, back to BLE-only", + "hw bwm wifi --ssid Home --pwd secret -> bring up, port 18888", + "hw bwm wifi --ssid Home --pwd secret --port 9000" ], "offline": false, "options": [ "-h, --help This help", - "--ssid WiFi SSID to join (omit with --stop)", + "--ssid WiFi SSID to join", "--pwd WiFi password (omit for open network)", - "--port TCP server listen port (default 7777)", - "--hostname DHCP hostname (default Proxmark5)", - "--stop tear down WiFi and return to BLE-only", - "--status show current WiFi connection state + IP" + "--port TCP server listen port (default 18888)", + "--hostname DHCP hostname (default Proxmark5)" ], - "usage": "hw bwmwifi [-h] [--ssid ] [--pwd ] [--port ] [--hostname ] [--stop] [--status]" + "usage": "hw bwm wifi [-h] [--ssid ] [--pwd ] [--port ] [--hostname ]" + }, + "hw bwm wifipower": { + "command": "hw bwm wifipower", + "description": "Show or set how much power the BWM (ESP32) spends on WiFi. off turns WiFi fully off (BLE-only, persisted; the default state, same as `hw bwm wifi stop`). Bring it back with hw bwm wifi --ssid --pwd . The other three set the modem power-save type while WiFi is up, stored on the BWM: min (default) sleeps between DTIM beacons, max for the whole listen interval, none never. Independent of hw bwm powersave. PM5 only.", + "notes": [ + "hw bwm wifipower -> show whether WiFi is up and the power-save type", + "hw bwm wifipower off -> WiFi fully off, BLE-only", + "hw bwm wifipower none -> modem always on while WiFi is up", + "hw bwm wifipower min -> ESP-IDF default (DTIM sleep)", + "hw bwm wifipower max -> deepest modem sleep" + ], + "offline": false, + "options": [ + "-h, --help This help" + ], + "usage": "hw bwm wifipower [-h]" }, "hw connect": { "command": "hw connect", @@ -11082,19 +11381,39 @@ ], "usage": "hw ping [-h] [-l ]" }, + "hw powersave": { + "command": "hw powersave", + "description": "Toggle the PM5 power-save idle. Default is on: between commands the core drops from 288 to 48 MHz with the PLL off, the FPGA clock stopped and the CPU halted (WFI) until the next interrupt or the 1 ms wake tick. Commands run at full speed; turn it off to keep the core at 288 MHz and spinning. Runtime only: resets to on at each boot. See `hw status` for the idle stats.", + "notes": [ + "hw powersave off -> stay at 288 MHz, no idle sleep", + "hw powersave on -> re-enable the power-save idle" + ], + "offline": false, + "options": [ + "-h, --help This help" + ], + "usage": "hw powersave [-h]" + }, "hw qc_pm5": { "command": "hw qc_pm5", "description": "QC Test for the PM5", "notes": [ - "hw qc_pm5 -> run QC test with default 20 second timeout", - "hw qc_pm5 -t 3 -> run QC test with a 3 second timeout" + "hw qc_pm5 -> run hardware QC test with default 20 second timeout", + "hw qc_pm5 -t 3 -> run hardware QC test with a 3 second timeout", + "hw qc_pm5 --iolow --pwd -> drive PM5 test IO low", + "hw qc_pm5 --iohigh --pwd -> drive PM5 test IO high", + "hw qc_pm5 --ioreset --pwd -> reset PM5 test IO to default" ], "offline": false, "options": [ "-h, --help This help", - "-t, --timeout test sequence timeout in seconds (default 20)" + "-t, --timeout test sequence timeout in seconds (default 20)", + "--iolow drive PM5 test IO low", + "--iohigh drive PM5 test IO high", + "--ioreset reset PM5 test IO to default", + "--pwd QC test password in hex (required for IO tests)" ], - "usage": "hw qc_pm5 [-h] [-t ]" + "usage": "hw qc_pm5 [-h] [-t ] [--iolow ] [--iohigh ] [--ioreset ] [--pwd ]" }, "hw readmem": { "command": "hw readmem", @@ -12625,7 +12944,7 @@ "-1, --ht1 Card type Hitag 1", "-2, --ht2 Card type Hitag 2", "-s, --hts Card type Hitag S", - "-m, --htm Card type Hitag \u03bc" + "-m, --htm Card type Hitag \u00b5" ], "usage": "lf hitag eload [-h12sm] -f " }, @@ -12643,7 +12962,7 @@ "-1, --ht1 Card type Hitag 1", "-2, --ht2 Card type Hitag 2 (default)", "-s, --hts Card type Hitag S", - "-m, --htm Card type Hitag \u03bc" + "-m, --htm Card type Hitag \u00b5" ], "usage": "lf hitag eview [-hv12sm]" }, @@ -14275,24 +14594,25 @@ }, "lf t55xx detect": { "command": "lf t55xx detect", - "description": "Try detecting the tag modulation from reading the configuration block", + "description": "Try detecting the tag modulation from reading the configuration block. * * * WARNING * * * Use of detect with password on a tag not configured for a password can damage the tag * * * * * * * * * *", "notes": [ "lf t55xx detect", "lf t55xx detect -1", - "lf t55xx detect -p 11223344" + "lf t55xx detect -p 11223344 -o" ], "offline": true, "options": [ "-h, --help This help", "-1 extract using data from graphbuffer", "-p, --pwd password (4 hex bytes)", + "-o, --override override safety check", "--r0 downlink - fixed bit length (detected def)", "--r1 downlink - long leading reference", "--r2 downlink - leading zero", "--r3 downlink - 1 of 4 coding reference", "--all try all downlink modes" ], - "usage": "lf t55xx detect [-h1] [-p ] [--r0] [--r1] [--r2] [--r3] [--all]" + "usage": "lf t55xx detect [-h1o] [-p ] [--r0] [--r1] [--r2] [--r3] [--all]" }, "lf t55xx deviceconfig": { "command": "lf t55xx deviceconfig", @@ -15407,21 +15727,27 @@ }, "nfc type1 help": { "command": "nfc type1 help", - "description": "-------- -------------- NFC Forum Tag Type 1 --------------- -------- --------------------- General --------------------- help This help ======================================================================================= nfc type2 { NFC Forum Tag Type 2... } --------------------------------------------------------------------------------------- nfc type2 read available offline: no Prints NFC Data Exchange Format (NDEF)", + "description": "-------- -------------- NFC Forum Tag Type 1 --------------- -------- --------------------- General --------------------- help This help ======================================================================================= nfc type2 { NFC Forum Tag Type 2... } --------------------------------------------------------------------------------------- nfc type2 format available offline: no Format a MIFARE Ultralight / NTAG tag for NDEF by writing the Capability Container to block 3, followed by an empty NDEF message. Writes NXP factory delivery content for the detected tag type. Block 3 is One Time Programmable; unknown types and unreachable CCs are refused. Note: the tag is re-selected and re-authenticated for each block written.", "notes": [ - "hf mfu ndefread -> shows NDEF data", - "hf mfu ndefread -k ffffffff -> shows NDEF data with key", - "hf mfu ndefread -f myfilename -> save raw NDEF to file" + "hf mfu ndefformat", + "hf mfu ndefformat -v", + "hf mfu ndefformat --erase", + "hf mfu ndefformat -k FFFFFFFF", + "hf mfu ndefformat -k 49454D4B41455242214E4143554F5946", + "hf mfu ndefformat -d E1101200 --force" ], "offline": true, "options": [ "-h, --help This help", - "-l Swap entered key's endianness", - "-f, --file Save raw NDEF to file", + "-k, --key Authentication key (UL-C/UL-AES 16 bytes, EV1/NTAG 4 bytes)", + "-l Swap entered key endianness", + "-d, --data Capability Container to write, 4 bytes. Overrides the detected type", + "--erase Also zero the rest of the NDEF data area", + "--force Continue on an unknown tag type, or with an oversized -d value", "-v, --verbose Verbose output", "--schann use secure channel. Must have key" ], - "usage": "hf mfu ndefread [-hlv] [-k Replace default key for NDEF] [-f ] [--schann]" + "usage": "hf mfu ndefformat [-hlv] [-k ] [-d ] [--erase] [--force] [--schann]" }, "nfc type1 read": { "command": "nfc type1 read", @@ -15451,6 +15777,24 @@ ], "usage": "hf 14a ndefformat [-hv]" }, + "nfc type2 read": { + "command": "nfc type2 read", + "description": "Prints NFC Data Exchange Format (NDEF)", + "notes": [ + "hf mfu ndefread -> shows NDEF data", + "hf mfu ndefread -k ffffffff -> shows NDEF data with key", + "hf mfu ndefread -f myfilename -> save raw NDEF to file" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-l Swap entered key's endianness", + "-f, --file Save raw NDEF to file", + "-v, --verbose Verbose output", + "--schann use secure channel. Must have key" + ], + "usage": "hf mfu ndefread [-hlv] [-k Replace default key for NDEF] [-f ] [--schann]" + }, "nfc type2 write": { "command": "nfc type2 write", "description": "Write NFC Data Exchange Format (NDEF) records to a MIFARE Ultralight / NTAG tag. The tag must already be NDEF formatted, ie carry a Capability Container in block 3. Combine several of --uri, --text and --aar to build a multi record message, records are added in that order. Alternatively supply raw NDEF bytes with -d or -f, those get wrapped in a TLV container automatically when they are not already. Use `nfc encode` to build such raw bytes offline. Note: the tag is re-selected and re-authenticated for every block written, so a large message takes a while.", @@ -16124,7 +16468,7 @@ "command": "smart raw", "description": "Sends raw bytes to card", "notes": [ - "smart raw -s -0 -d 00a404000e315041592e5359532e4444463031 -> `1PAY.SYS.DDF01` PPSE directory with get ATR", + "smart raw --t0 -s -d 00a404000e315041592e5359532e4444463031 -> `1PAY.SYS.DDF01` PPSE directory with get ATR", "smart raw --t0 -d 00a404000e325041592e5359532e4444463031 -> `2PAY.SYS.DDF01` PPSE directory", "smart raw --t0 -t -d 00a4040007a0000000041010 -> Mastercard", "smart raw --t0 -t -d 00a4040007a0000000031010 -> Visa", @@ -16174,9 +16518,9 @@ ], "usage": "smart setclock [-h] [--16mhz] [--8mhz] [--4mhz]" }, - "trace help": { - "command": "trace help", - "description": "help This help extract Extract authentication challenges found in trace list List protocol data in trace buffer load Load trace from file save Save trace buffer to file --------------------------------------------------------------------------------------- trace extract available offline: yes Extracts protocol authentication challenges from trace buffer", + "trace extract": { + "command": "trace extract", + "description": "Extracts protocol authentication challenges from trace buffer", "notes": [ "trace extract", "trace extract -1" @@ -16188,6 +16532,18 @@ ], "usage": "trace extract [-h1]" }, + "trace help": { + "command": "trace help", + "description": "help This help clear Clear the client side trace buffer extract Extract authentication challenges found in trace list List protocol data in trace buffer load Load trace from file save Save trace buffer to file --------------------------------------------------------------------------------------- trace clear available offline: yes Clear the client side trace buffer. That is the buffer `trace load` fills and the `-1` param reads from. It is not the device side trace, see `data clear` for that one", + "notes": [ + "trace clear" + ], + "offline": true, + "options": [ + "-h, --help This help" + ], + "usage": "trace clear [-h]" + }, "trace list": { "command": "trace list", "description": "Annotate trace buffer with selected protocol data You can load a trace from file (see `trace load -h`) or it be downloaded from device by default", @@ -16250,16 +16606,18 @@ }, "trace save": { "command": "trace save", - "description": "Save protocol data from trace buffer to binary file File extension is <.trace>", + "description": "Save protocol data to binary file By default the trace is downloaded from device. Use `-1` to save the client side trace buffer instead, ie a trace loaded with `trace load` or downloaded by an earlier `trace list` File extension is <.trace>", "notes": [ - "trace save -f mytracefile -> w/o file extension" + "trace save -f mytracefile -> download from device, w/o file extension", + "trace save -1 -f mytracefile -> use trace buffer" ], "offline": true, "options": [ "-h, --help This help", + "-1, --buffer use data from trace buffer", "-f, --file Specify trace file to save" ], - "usage": "trace save [-h] -f " + "usage": "trace save [-h1] -f " }, "usart btfactory": { "command": "usart btfactory", @@ -16427,8 +16785,8 @@ } }, "metadata": { - "commands_extracted": 912, + "commands_extracted": 935, "extracted_by": "PM3Help2JSON v1.00", - "extracted_on": "2026-09-04T11:31:07+00:00" + "extracted_on": "2026-09-27T19:09:12+00:00" } } diff --git a/doc/commands.md b/doc/commands.md index 79b30d2b7..5fb6c6f9d 100644 --- a/doc/commands.md +++ b/doc/commands.md @@ -238,7 +238,6 @@ Check column "offline" for their availability. |`hf 14b wrbl `|N |`Write data to a SRI512/SRIX4 tag` |`hf 14b tearoff `|N |`Tear-off attack on ST25TB/SRx counter blocks` |`hf 14b view `|Y |`Display content from tag dump file` -|`hf 14b valid `|Y |`SRIX4 checksum test` |`hf 14b ctdump `|N |`Dump ASK CTS/C-ticket` |`hf 14b ctrdbl `|N |`Read ASK CTS/C-ticket block` |`hf 14b setuid `|N |`Set UID for magic card` @@ -749,16 +748,16 @@ Check column "offline" for their availability. |`hf mfu pwdgen `|Y |`Generate pwd from known algos` |`hf mfu otptear `|N |`Tear-off test on OTP bits` |`hf mfu countertear `|N |`Tear-off test on Ev1/NTAG Counter bits` +|`hf mfu chk `|N |`Ultralight C/AES - Authentication dictionary check` |`hf mfu cauth `|N |`Ultralight-C - Authentication` -|`hf mfu cchk `|N |`Ultralight-C - Authentication dictionary check` |`hf mfu desbrute `|Y |`Ultralight-C - 3DES key segment brute force` |`hf mfu aesauth `|N |`Ultralight-AES - Authentication` -|`hf mfu aeschk `|N |`Ultralight-AES - Authentication dictionary check` |`hf mfu aesgetuid `|N |`Ultralight-AES - Get UID when RID in use` |`hf mfu setkey `|N |`Ultralight C/AES - Set 3DES/AES keys` |`hf mfu dump `|N |`Dump MIFARE Ultralight family tag to binary file` |`hf mfu incr `|N |`Increments Ev1/NTAG counter` |`hf mfu info `|N |`Tag information` +|`hf mfu ndefformat `|N |`Format tag as NDEF, writes the Capability Container` |`hf mfu ndefread `|N |`Prints NDEF records from card` |`hf mfu ndefwrite `|N |`Write NDEF records to card` |`hf mfu rdbl `|N |`Read block` @@ -816,6 +815,12 @@ Check column "offline" for their availability. |`hf mfdes getfileisoids `|N |`Get File ISO IDs list` |`hf mfdes lsfiles `|N |`Show all files list` |`hf mfdes dump `|N |`Dump all files` +|`hf mfdes view `|Y |`Display content from tag dump file` +|`hf mfdes eload `|N |`Upload file into emulator memory` +|`hf mfdes esave `|N |`Save emulator memory to file` +|`hf mfdes eview `|N |`View emulator memory` +|`hf mfdes sim `|N |`Simulate DESFire card from emulator memory` +|`hf mfdes etest `|N |`Drive the simulation from the host, no RF` |`hf mfdes createfile `|N |`Create Standard/Backup File` |`hf mfdes createvaluefile`|N |`Create Value File` |`hf mfdes createrecordfile`|N |`Create Linear/Cyclic Record File` @@ -850,6 +855,8 @@ Check column "offline" for their availability. |`hf ntag424 getfs `|N |`Get file settings` |`hf ntag424 changefs `|N |`Change file settings` |`hf ntag424 changekey `|N |`Change key` +|`hf ntag424 gettt `|N |`Get Tag Tamper status` +|`hf ntag424 setconfig `|N |`Set PICC configuration option` ### hf saflok @@ -937,8 +944,9 @@ Check column "offline" for their availability. |------- |------- |----------- |`hf thinfilm help `|Y |`This help` |`hf thinfilm info `|N |`Tag information` -|`hf thinfilm list `|Y |`List NFC Barcode / Thinfilm history - not correct` +|`hf thinfilm list `|Y |`List NFC Barcode / Thinfilm history` |`hf thinfilm sim `|N |`Fake Thinfilm tag` +|`hf thinfilm sniff `|N |`Sniff Thinfilm tag communication` ### hf topaz @@ -1016,11 +1024,12 @@ Check column "offline" for their availability. |`hw fpga `|N |`Fpga commands` |`hw fpgaoff `|N |`Turn off FPGA on device` |`hw ant_pm5 `|N |`Control the antennal of pm5` -|`hw qc_pm5 `|N |`Perform QC test for the PM5` +|`hw qc_pm5 `|N |`Perform QC test (hardware or IO) for the PM5` |`hw factorydata `|N |`Get/Set the factory data for Device` |`hw lcd `|N |`Send command/data to LCD` |`hw lcdreset `|N |`Hardware reset LCD` |`hw ping `|N |`Test if the Proxmark3 is responsive` +|`hw powersave `|N |`Enable/disable the PM5 power-save idle` |`hw readmem `|N |`Read from MCU flash` |`hw reset `|N |`Reset the device` |`hw setlfdivisor `|N |`Drive LF antenna at 12MHz / (divisor + 1)` @@ -1028,15 +1037,43 @@ Check column "offline" for their availability. |`hw setmux `|N |`Set the ADC mux to a specific value` |`hw standalone `|N |`Start installed standalone mode on device` |`hw tia `|N |`Trigger a Timing Interval Acquisition to re-adjust the RealTimeCounter divider` -|`hw bwmsetcap `|N |`Set BWM fuel-gauge design capacity (PM5, run once after battery change)` -|`hw bwmvchg `|N |`Set BWM charger charge-voltage target (PM5, default 4100 mV)` -|`hw bwmcharge `|N |`Enable/disable BWM battery charging (PM5, one-shot)` -|`hw bwmautooff `|N |`Toggle auto power-off on USB unplug (PM5, BWM)` -|`hw bwmwifi `|N |`Bring up BWM WiFi (STA + TCP server) for a tcp: connection (PM5)` |`hw tune `|N |`Measure tuning of device antenna` |`hw decay `|N |`Measure HF antenna decay after field-off` +### hw bwm + + { BWM (battery/wireless module) commands... } + +|command |offline |description +|------- |------- |----------- +|`hw bwm help `|Y |`This help` +|`hw bwm autooff `|N |`Show/set auto power-off (USB unplug, idle on battery)` +|`hw bwm charge `|N |`Enable/disable battery charging (one-shot)` +|`hw bwm name `|N |`Get/set the BWM BLE advertising name` +|`hw bwm powersave `|N |`Show/set the BWM power-save switch (DFS, light sleep, slow adv)` +|`hw bwm setcap `|N |`Set fuel-gauge design capacity (run once after battery change)` +|`hw bwm upgrade `|N |`Reflash BWM (ESP32) firmware over the BWM link, no header` +|`hw bwm vchg `|N |`Set charger charge-voltage target (default 4100 mV)` +|`hw bwm wifi `|N |`Bring up WiFi (STA + TCP server) for a tcp: connection` +|`hw bwm wifipower `|N |`WiFi fully off, or the modem power-save type (none/min/max)` + + +### hw bwm ble + + { BLE: on/off, pairing, bonded devices, TX power... } + +|command |offline |description +|------- |------- |----------- +|`hw bwm ble help `|Y |`This help` +|`hw bwm ble status `|N |`Show BLE settings: on/off, pairing, bonded devices, TX power` +|`hw bwm ble on `|N |`Switch BLE on (persisted)` +|`hw bwm ble off `|N |`Switch BLE off (persisted) - nothing can connect` +|`hw bwm ble pairing `|N |`Require pairing with a passkey, set the passkey` +|`hw bwm ble forget `|N |`Remove bonded devices` +|`hw bwm ble txpower `|N |`Set advertising / connection TX power` + + ### lf { Low frequency commands... } @@ -1667,6 +1704,7 @@ Check column "offline" for their availability. |command |offline |description |------- |------- |----------- +|`nfc type2 format `|N |`format MIFARE Ultralight / NTAG as NFC Forum Tag Type 2` |`nfc type2 read `|N |`read NFC Forum Tag Type 2` |`nfc type2 write `|N |`write NFC Forum Tag Type 2` |`nfc type2 help `|Y |`This help` @@ -1775,6 +1813,7 @@ Check column "offline" for their availability. |command |offline |description |------- |------- |----------- |`trace help `|Y |`This help` +|`trace clear `|Y |`Clear the client side trace buffer` |`trace extract `|Y |`Extract authentication challenges found in trace` |`trace list `|Y |`List protocol data in trace buffer` |`trace load `|Y |`Load trace from file` diff --git a/doc/desfire.md b/doc/desfire.md index c89ea8ae8..9aadaf70b 100644 --- a/doc/desfire.md +++ b/doc/desfire.md @@ -26,6 +26,7 @@ - [How to work with value files](#how-to-work-with-value-files) - [How to work with transaction mac](#how-to-work-with-transaction-mac) - [How to switch DESFire Light to LRP mode](#how-to-switch-desfire-light-to-lrp-mode) + - [How to drive the simulation from the host](#how-to-drive-the-simulation-from-the-host) ## Documentation @@ -581,3 +582,30 @@ or in the LRP mode Switch LRP mode on `hf mfdes setconfig --appisoid df01 -t aes -s ev2 --param 05 --data 00000000010000000000` + +### How to drive the simulation from the host +^[Top](#top) + +`hf mfdes sim` answers a reader over the air. `hf mfdes etest` answers the same simulation from the host over USB with no RF, one action per call, so a recorded card session can be replayed against it. The card image comes from `hf mfdes eload` as for `sim`. + +`hf mfdes etest --begin` - check the image and clear the random queue + +`hf mfdes etest --scan` - RF reset and activation, shows UID, ATQA, SAK and ATS + +`hf mfdes etest --random CCF53270570A7669` - queue the RndB the next authentication answers with, 8 or 16 bytes by key type + +`hf mfdes etest --apdu 900A0000010000` - one command, native or ISO 7816 wrapped, shows the answer + +`hf mfdes etest --fieldoff` - RF reset, the session is gone until the next `--scan` + +`hf mfdes etest --state` - selected AID, authentication, random queue and the sticky underflow flag + +`hf mfdes etest --end` - drop the state and the random queue + +The simulation normally uses a fixed RndB and a tick-derived random UID. Queued bytes are drawn in order: `--scan` takes 3 for the UID when the image has random ID switched on, then each authentication takes its RndB, 8 or 16 bytes by key type. On a random-id image queue the UID bytes before `--scan` and the RndB before the authentication; queuing only the RndB first would spend it on the UID. A draw that finds the queue short takes nothing, falls back to the fixed or tick-derived value and sets the underflow flag `--state` shows. + +`hf mfdes etest --apdu 900A0000010000 -j` - the same, as one line of JSON for a script + +``` +{"command":"apdu","ok":true,"data":"DF6AB29AAE46BA2791AF"} +``` diff --git a/doc/magic_cards_notes.md b/doc/magic_cards_notes.md index ca36afb4a..6cdf195ea 100644 --- a/doc/magic_cards_notes.md +++ b/doc/magic_cards_notes.md @@ -2685,9 +2685,100 @@ More commands to follow. Be careful with some. ^[Top](#top) +Three kinds of UID changeable ISO15693 tags are known, called V1 (Gen1), V2 (Gen2) and V3 (Gen3) here. +`hf 15 info` only matches the UID prefix against its vendor list, so it can't tell them apart from genuine tags. + ### Identify -**TODO** +^[Top](#top) + +| Kind | Blocks on tags tested | Set UID with | +|------|-----------------------|--------------| +| V1 (Gen1) | 28/40/56 | `hf 15 csetuid` | +| V2 (Gen2) | 64 | `hf 15 csetuid --v2` | +| V3 (Gen3) | 80 | `hf 15 csetuid --v3`, then `hf 15 cfinalize` | + +The block counts come from the few tags tested, they are only a hint. + +The same kind of magic can behave a bit differently between manufacturers, for example the block layout, +or how the V1 backdoor blocks answer to read and write commands. What is described here comes from the tags tested. + +V1: no reliable way to identify it, the only sure check is to set a UID and see if it changes. +On the V1 tags tested, reading blocks `0x38`, `0x39`, `0x3E` and `0x3F` fails while writing `0x38` and `0x39` works. That may be a hint but it is not confirmed. + +``` +hf 15 raw -ac -d 022038 # command failed on the V1 tags tested +``` + +V2: no passive identification known. It uses the custom command `0xE0`, which genuine tags do not implement. + +V3: blocks `0x14` and `0x15` hold a signature while the tag is not finalized. + +``` +hf 15 raw -ac -d 022014 # A5 2B 44 2C +hf 15 raw -ac -d 022015 # 21 AE 93 00 (00 00 00 00 after finalize) +``` + + + +### V1 (Gen1) + +^[Top](#top) + +The UID is written to blocks `0x38` and `0x39` with plain `WRITEBLOCK`, each holding four UID bytes in reverse order. +Blocks `0x3E` and `0x3F` are written first as an unlock, this is what `hf 15 csetuid` sends for `E011223344556677`: + +``` +hf 15 raw -acw -d 02213E00000000 +hf 15 raw -acw -d 02213F69960000 +hf 15 raw -acw -d 02213877665544 +hf 15 raw -acw -d 022139332211E0 +``` + +On the tags tested, writing only `0x38` and `0x39` is enough, the new UID is active immediately. +`0x3E` and `0x3F` accept the unlock values once, later writes fail with `command failed`. + +### V2 (Gen2) + +^[Top](#top) + +Uses the custom command `0xE0`, this is what `hf 15 csetuid --v2` sends for `E011223344556677`: + +``` +hf 15 raw -acw -d 02E009473F038B00 +hf 15 raw -acw -d 02E0095200000000 +hf 15 raw -acw -d 02E0094077665544 +hf 15 raw -acw -d 02E00941332211E0 +``` + +On the V2 tag tested, block `0x38` reads as normal memory, a `WRITEBLOCK` to it is refused with error code 3 (option not supported) unless the request flags carry the option flag (`42` instead of `02`). + +### V3 (Gen3) + +^[Top](#top) + +The UID sits in blocks `0x10` (last four bytes, reversed) and `0x11` (first four bytes, reversed). +It can be rewritten as often as needed until the tag is finalized: + +``` +hf 15 raw -acw -d 02211077665544 +hf 15 raw -acw -d 022111332211E0 +``` + +Finalize locks the UID for good and can't be undone. It clears the configuration +blocks and changes the block numbering: on the tag tested, data written to block +`0x38` before finalize read back at block `0x20` afterwards, a shift of `0x18`. +User data is moved, not erased. Note down what is where before finalizing: + +``` +hf 15 raw -acw -d 022114A52B442C +hf 15 raw -acw -d 02211569E25D00 +``` + +> [!WARNING] +> Writing anything other than these two finalize values to blocks `0x14` and `0x15` bricks the tag. +> +> `hf 15 wipe` may brick v3 tag. ### Proxmark3 commands @@ -2696,9 +2787,20 @@ More commands to follow. Be careful with some. Always set a UID starting with `E0`. ``` -hf 15 csetuid E011223344556677 +hf 15 csetuid -u E011223344556677 # V1 +hf 15 csetuid -u E011223344556677 --v2 # V2 +hf 15 csetuid -u E011223344556677 --v3 # V3 +hf 15 cfinalize -y # V3, irreversible ``` +Before writing, `csetuid` checks that the tag looks like the selected kind: + +* V1 reads blocks `0x38`, `0x39`, `0x3E`, `0x3F` and stops if one holds data other than `00000000` (or `69960000` in `0x3F`), + or if a read fails other than with no answer / block not available. + If the write or the UID check fails and the tag still shows its original UID, it writes those four blocks back to `00000000`. +* V3 stops unless blocks `0x14` and `0x15` still hold the un-finalized signature, `cfinalize` does the same. +* V2 has no check, the `0xE0` command is ignored by genuine tags. + or (ignore errors): ``` diff --git a/doc/md/Development/Maintainers.md b/doc/md/Development/Maintainers.md index fbd66da2f..87953ebef 100644 --- a/doc/md/Development/Maintainers.md +++ b/doc/md/Development/Maintainers.md @@ -126,3 +126,7 @@ Host binaries are compiled with hardening flags (only with Makefile, not with cm * udev rule on Linux Same logic for `make all`, `make clean`, `make uninstall` and `make check`. + +The client is installed with the additional capabilities required for direct BLE connections. See `client/Makefile` for details. +Depending on your distribution, you may need to ensure that binaries with such capabilities can be run by regular users, else an *operation not permitted* will occur. +If you prefer to not set these capabilities, run `make install SKIP_SETCAP=1`. diff --git a/doc/md/Installation_Instructions/Troubleshooting.md b/doc/md/Installation_Instructions/Troubleshooting.md index b008f1914..bc4fa23ea 100644 --- a/doc/md/Installation_Instructions/Troubleshooting.md +++ b/doc/md/Installation_Instructions/Troubleshooting.md @@ -167,9 +167,9 @@ proxmark3 --flash --image /usr/local/share/proxmark3/firmware/f proxmark3 --flash --image /usr/share/proxmark3/firmware/fullimage.elf using the script: -pm3 --> smart upgrade -f /usr/local/share/proxmark3/firmware/sim014.bin +pm3 --> smart upgrade -f /usr/local/share/proxmark3/firmware/sim024.bin <> -pm3 --> smart upgrade -f /usr/share/proxmark3/firmware/sim014.bin +pm3 --> smart upgrade -f /usr/share/proxmark3/firmware/sim024.bin ``` If you didn't install the Proxmark but you're working from the sources directory and depending how you launch the client, your working directory might be the root of the repository: @@ -192,7 +192,7 @@ client/proxmark3 --flash --image armsrc/obj/fullimage.elf <> ./proxmark3 --flash --image ../armsrc/obj/fullimage.elf -pm3 --> smart upgrade -f sim014.bin +pm3 --> smart upgrade -f sim024.bin ``` etc. diff --git a/doc/md/PM5_Start_Here/Getting_Started_With_PM5.md b/doc/md/PM5_Start_Here/Getting_Started_With_PM5.md index 3dcc7e403..8b99af022 100644 --- a/doc/md/PM5_Start_Here/Getting_Started_With_PM5.md +++ b/doc/md/PM5_Start_Here/Getting_Started_With_PM5.md @@ -61,6 +61,11 @@ For more options, look [here](#Build-Extras) * If you see 2 lights (B & D) go on and then OFF, you're in *DFU mode*. Unplug, and try the previous step again. * Run `./pm3-flash-bootrom` * If you see "🚨 The elf file is not applicable to the currently connected device.", you probably forgot to add `PLATFORM=PM5` in your `Makefile.platform` + * `./pm3-flash-bootrom` uses the repo version. + * `pm3-flash-bootrom` uses the system installed version. + * Using the wrong version can throw unexpected errors for the Proxmark5 like these: + * `[=] Permitted flash range: 0x08000000-0x08100000` + * `[!!] The elf file is not applicable to the currently connected device.` * If the above hangs or thows and error, try this: [DFU Install](#DFU-Install) * Unplug. @@ -202,3 +207,4 @@ Do not use them unless you fully understand what you're doing. - [PM5 Button Controller](./PM5_Controllers/PM5_Button_Controller_RM.md) - [PM5 RGB Controller](./PM5_Controllers/PM5_RGB_Controller_RM.md) - [PM5 BWM Install](https://github.com/RfidResearchGroup/Proxmark5_BWM_esp32/blob/master/INSTALL.md) +- [PM5 <--> Flipper Usage](./PM5-FLIPPER-USAGE.md) diff --git a/doc/md/PM5_Start_Here/PM5-BWM-USAGE.md b/doc/md/PM5_Start_Here/PM5-BWM-USAGE.md index b16fe983c..ddc9a028e 100644 --- a/doc/md/PM5_Start_Here/PM5-BWM-USAGE.md +++ b/doc/md/PM5_Start_Here/PM5-BWM-USAGE.md @@ -158,6 +158,31 @@ There are three ways to connect: a **native transport** (Linux), a **cross-platf Python bridge** (Linux / macOS / Windows / WSL / iOS), and a **bridge app** on Android ([2.4](#24-android--termux--ble-bridge-app)). +### `hw bwm name` — get/set the BLE advertising name + +Reads or changes the name the BWM advertises over BLE. With no argument it prints +the current name; `--set` changes it (1–31 characters). + +| Argument | Description | +| --------------- | ---------------------------------------------------- | +| `--set ` | New BLE name, 1–31 chars; omit to read current name | + +``` +hw bwm name # show the current BLE name +hw bwm name --set MyPM5 # set the BLE name to 'MyPM5' +``` + +The name is stored on the BWM in NVS, so it persists across power cycles. The BWM +applies the advertised name at BLE start-up, so setting a name reboots the BWM to +make it take effect — this briefly drops a BLE or WiFi connection, so reconnect +after a few seconds. Over USB the reboot is not noticeable, since the client stays +connected to the PM5 while only the BWM's ESP restarts. + +> [!NOTE] +> If a device is connected over BLE when you change the name, the running +> advertisement can't change mid-connection; the new name shows up on the next +> scan after the reboot. + ### 2.1 Native BLE transport — Linux only, no bridge Uses a raw L2CAP/ATT socket — no `bleak`, no `bluetoothd` daemon dependency. @@ -203,8 +228,8 @@ python3 pm5_ble_bridge.py --pty # default link /tmp/pm5-ble **b) TCP listener** — bridge listens, client connects in: ``` -python3 pm5_ble_bridge.py --tcp 7777 # or HOST:PORT -./pm3 -p tcp:127.0.0.1:7777 +python3 pm5_ble_bridge.py --tcp 18888 # or HOST:PORT +./pm3 -p tcp:127.0.0.1:18888 ``` **c) Outbound TCP** (`--connect`) — bridge dials **out** to a listener. Pairs with @@ -212,13 +237,13 @@ the client's `--wait` mode ([2.3](#23-client-listen-mode--pm3----wait)) and cros the WSL2 NAT boundary: ``` -python3 pm5_ble_bridge.py --connect 127.0.0.1:7777 +python3 pm5_ble_bridge.py --connect 127.0.0.1:18888 ``` **d) Relay only** (no BLE) — TCP listener ↔ PTY, for chaining: ``` -python3 pm5_ble_bridge.py --relay --listen 7777 --pty +python3 pm5_ble_bridge.py --relay --listen 18888 --pty ``` > [!NOTE] @@ -233,10 +258,10 @@ bridge at it with `--connect`. This removes the relay/PTY hop. ``` # window 1 — client listens (blocks until something connects) -./pm3 -p tcp:127.0.0.1:7777 --wait +./pm3 -p tcp:127.0.0.1:18888 --wait # window 2 — bridge dials in (on the machine with the radio) -python3 pm5_ble_bridge.py --connect 127.0.0.1:7777 +python3 pm5_ble_bridge.py --connect 127.0.0.1:18888 ``` > [!NOTE] @@ -258,14 +283,18 @@ limited to 10 minutes per session (the limit resets after quitting the app). | Setting | Value | | ---------------- | ----------------------------------------------------------------- | -| Device A | Start TCP server (default port `54321`) | +| Device A | Start TCP server, use client default port:`18888` | | Device B | Connect to BLE device → `Proxmark5` | | Characteristic | the last one: service `0000ae86-…`, characteristic `0000ae88-…`, for RX+TX | -3. In Termux, connect over the local port: +1. In Termux, connect over the local port: ``` -./client/proxmark3 tcp:localhost:54321 +./client/proxmark3 tcp:localhost:18888 +``` +Or, as we're using the default port, just +``` +./client/proxmark3 tcp:localhost ``` No pairing is needed (the BWM has no BLE security). The same app also does classic @@ -295,7 +324,7 @@ hw bwm wifi --ssid [--pwd ] [--port ] [--hostname ] | ------------------- | ---------------------------------------- | | `--ssid ` | WiFi network to join **(required)** | | `--pwd ` | WiFi password (omit for an open network) | -| `--port ` | TCP server listen port (default `7777`) | +| `--port ` | TCP server listen port (default `18888`) | | `--hostname ` | DHCP hostname (default `Proxmark5`) | Two sub-actions take no other arguments and are positional (no dashes): @@ -312,21 +341,26 @@ strings: ``` [+] BWM on WiFi at 192.168.1.77 -[?] Connect with: pm3 -p tcp:192.168.1.77:7777 -[?] Or by name (router-dependent): pm3 -p tcp:pm5-lab:7777 +[?] Connect with: pm3 -p tcp:192.168.1.77:18888 +[?] Or by name (router-dependent): pm3 -p tcp:pm5-lab:18888 ``` ### 3.2 Connect over WiFi ``` -./pm3 -p tcp:192.168.1.77:7777 +./pm3 -p tcp:192.168.1.77:18888 +``` +Or, as we're using the default port, just +``` +./pm3 -p tcp:192.168.1.77 ``` > [!NOTE] > Connecting **by hostname** works only if your router registers DHCP client names > in its local DNS (some need a suffix like `.lan` or `.home`; some -> don't do it at all). There is **no mDNS / `.local`** responder, so the IP is the -> reliable path. +> don't do it at all). BWM firmware with mDNS also answers `.local`, e.g. +> `./pm3 -p tcp:pm5-lab.local:18888`; this needs an mDNS-capable resolver on the host +> (Avahi/nss-mdns or systemd-resolved on Linux; built in on macOS and Windows 10+). ### 3.3 Check WiFi status — `hw bwm wifi status` diff --git a/doc/md/PM5_Start_Here/PM5-FLIPPER-USAGE.md b/doc/md/PM5_Start_Here/PM5-FLIPPER-USAGE.md new file mode 100644 index 000000000..f8801f7de --- /dev/null +++ b/doc/md/PM5_Start_Here/PM5-FLIPPER-USAGE.md @@ -0,0 +1,72 @@ +# Proxmark5 CEP — Flipper Zero link + +The **CEP (Type-C Extended Port)** is the side USB-C port on the PM5 — the one +**not** used for flashing/DFU. It lets a Flipper Zero, running the +[Proxmark5_FlipperZero_FAP](https://github.com/RfidResearchGroup/Proxmark5_FlipperZero_FAP) +app, talk to the PM5 over a one-shot UART handshake followed by standard PM3 +NG command/response frames carried over SPI. Everything below is **PM5-only** +and is compiled in by default when building for PM5. + +## Contents + +- [Build](#build) +- [Physical hookup](#physical-hookup) +- [What works today](#what-works-today) +- [What doesn't (yet)](#what-doesnt-yet) +- [Status / debugging](#status--debugging) +- [Notes](#notes) + +--- + +## Build + +Build as usual, CEP is available by default. (`SKIP_CEP=1` to remove CEP support) + +--- + +## Physical hookup + +- Use the **side** USB-C port. +- Attach a Flipper Zero fitted with the Flipper transfer module/cable, running + the Proxmark5_FlipperZero_FAP app. +- The Flipper supplies 5V to the PM5 via USB OTG when the app launches. + +--- + +## What works today + +- The FAP handshake completing (app leaves "connecting"). +- Standard commands — `hw version`, `hw status`, memory/flash operations, + `CMD_CEP_STATUS` (compact binary snapshot: CEP link state, BWM battery, + firmware version — feeds the FAP's Hardware Status dashboard). +- `hf`/`lf` reads in general, same as over USB, once the device's one-time + FPGA bitstream step is done (see `Getting_Started_With_PM5.md`) — CEP + itself doesn't block RF. + +## What doesn't (yet) + +- The FAP's "Read Hitag2" menu item specifically. Every attempt over CEP + replies `PM3_EFAILED` with stale cached UID data, even though the same + reader succeeds moments later over plain USB against the same tag. + Firmware-side, root cause open, out of scope for the CEP transport itself. + +--- + +## Status / debugging + +- `hw status` reports a **CEP (Flipper) link** line: `attached` / + `not attached`. +- **Flipper side**: `./fbt cli` → `log debug`, then watch the + `Proxmark5_COM` tag while the FAP runs. +- **PM5 side**: keep the normal button-side USB-C cable attached to a PC + running the standard client at the same time as the Flipper is on CEP — + `Dbprintf()` output in the new CEP code surfaces there as usual, regardless + of what's happening over CEP. + +--- + +## Notes + +- CEP uses its own reply-routing flag (`g_reply_via_cep`). +- SPI bit-order/clock-phase settings are confirmed correct against real + Flipper traffic (logic analyzer): MSB-first, mode 0, CS active-low. diff --git a/doc/md/Use_of_Proxmark/2_Configuration-and-Verification.md b/doc/md/Use_of_Proxmark/2_Configuration-and-Verification.md index d40dc50ff..5d6f587c2 100644 --- a/doc/md/Use_of_Proxmark/2_Configuration-and-Verification.md +++ b/doc/md/Use_of_Proxmark/2_Configuration-and-Verification.md @@ -67,23 +67,23 @@ or These versions is obsolete. -If you didn't download sim014.bin from the RRG Repo be aware that it might be corrupted or faulty. +If you didn't download sim024.bin from the RRG Repo be aware that it might be corrupted or faulty. You find a hash text file in this folder. It was generated with the following linux command. ``` -sha512sum -b sim014.bin > sim014.sha512.txt +sha512sum -b sim024.bin > sim024.sha512.txt ``` -You should validate the sim014.bin file against this hash file in order to be sure the file is not corrupted or faulty. +You should validate the sim024.bin file against this hash file in order to be sure the file is not corrupted or faulty. The following command upgrades your device sim module firmware. Don't not turn off your device during the execution of this command!! Even its a quite fast command you should be warned. You may brick it if you interrupt it. ``` -[usb] pm3 --> smart upgrade -f /usr/local/share/proxmark3/firmware/sim014.bin +[usb] pm3 --> smart upgrade -f /usr/local/share/proxmark3/firmware/sim024.bin # or if from local repo -[usb] pm3 --> smart upgrade -f sim014.bin +[usb] pm3 --> smart upgrade -f sim024.bin ``` You get the following output if the execution was successful: @@ -94,10 +94,10 @@ You get the following output if the execution was successful: [!] ⚠️ A dangerous command, do wrong and you could brick the sim module [=] -------------------------------------------------------------------- -[=] firmware file sim014.bin -[=] Checking integrity sim014.sha512.txt -[+] loaded 3658 bytes from binary file sim014.bin -[+] loaded 158 bytes from binary file sim014.sha512.txt +[=] firmware file sim024.bin +[=] Checking integrity sim024.sha512.txt +[+] loaded 3658 bytes from binary file sim024.bin +[+] loaded 158 bytes from binary file sim024.sha512.txt [=] Don't turn off your PM3! [+] Sim module firmware uploading to PM3... 🕑 3658 bytes sent diff --git a/doc/mfdes_dump_format.md b/doc/mfdes_dump_format.md new file mode 100644 index 000000000..d84cd24ae --- /dev/null +++ b/doc/mfdes_dump_format.md @@ -0,0 +1,696 @@ +# MIFARE DESFire dump file format + + + +The `mfdes v1` json format is the on-disk image of a DESFire PICC: the card level +details, every application, every file's settings, and the file contents that +could actually be read. It is what `hf mfdes dump` writes and `hf mfdes view` +reads, and it is the format an emulator-memory loader (`hf mfdes eload`) will be +built on. + +# Table of Contents + +- [MIFARE DESFire dump file format](#mifare-desfire-dump-file-format) +- [Table of Contents](#table-of-contents) +- [Commands](#commands) +- [DFC compatibility](#dfc-compatibility) +- [File identity](#file-identity) +- [Card level](#card-level) +- [Applications](#applications) +- [Files](#files) + - [Common fields](#common-fields) + - [Standard and backup data files](#standard-and-backup-data-files) + - [Value files](#value-files) + - [Record files](#record-files) + - [Transaction MAC files](#transaction-mac-files) +- [Keys](#keys) +- [The Read flag](#the-read-flag) +- [Token spellings](#token-spellings) +- [A complete example](#a-complete-example) + - [The card](#the-card) + - [The key file](#the-key-file) + - [The dump file](#the-dump-file) + - [What `hf mfdes view` makes of it](#what-hf-mfdes-view-makes-of-it) +- [In-memory representation](#in-memory-representation) +- [Not in v1](#not-in-v1) + +## Commands +^[Top](#top) + +``` +hf mfdes dump walk the whole PICC, save hf-mfdes--dump.json +hf mfdes dump --aid 123456 dump only that application +hf mfdes dump --keys take per-application keys from a `hf mfdes chk` key file +hf mfdes dump --ns collect and print, save nothing +hf mfdes dump -f myfile save under a name of your choosing +hf mfdes view -f print a dump file, no device needed +``` + +With no `--keys`, the dump looks for `hf-mfdes--keys.json` by itself, so a +`hf mfdes chk -j hf-mfdes--keys` run is picked up on the next dump without +naming the file again. + +With no `--aid` / `--isoid` / `--dfname` the command walks every application the +PICC lists. The default filename is `hf-mfdes--dump.json`; only json is +written, there is no `.bin` companion. + +## DFC compatibility +^[Top](#top) + +`tools/dfc_converter.py` converts between this JSON format and DFC v4 text +credentials. DFC is used by the DESFire Compatible app for Flipper Zero and +Chameleon Ultra, so the converter moves supported card images between those +devices and Proxmark3. + +```text +python3 tools/dfc_converter.py credential.dfc credential.json +python3 tools/dfc_converter.py credential.json credential.dfc +``` + +The file extensions select the direction. The converter refuses features that +the destination cannot represent instead of silently discarding them. DFC +binary `.dfcb` files are not supported. + +## File identity +^[Top](#top) + +```json +{ + "Created": "proxmark3", + "FileType": "mfdes v1", + "Version": 1 +} +``` + +`FileType` is what the loader dispatches on. `Version` is the same number in +machine-readable form. A reader that does not understand a `FileType` must +refuse the file rather than guess -- `mfdes v2` is already taken by the key +recovery output of `hf mfdes chk`, which is a different, much smaller format. + +## Card level +^[Top](#top) + +Everything under `$.Card` describes the PICC itself. + +| Field | Type | Meaning | +|---|---|---| +| `UID` | hex | 4 or 7 byte UID from the 14a select | +| `ATQA` | hex, 2 bytes | wire order, the same way every other pm3 dump format stores it. `hf 14a info` prints the two bytes the other way round | +| `SAK` | hex, 1 byte | | +| `ATS` | hex | answer to RATS, absent when the card gave none | +| `VersionHW` | hex, 7 bytes | first `GetVersion` frame: vendor, type, subtype, major, minor, storage, protocol | +| `VersionSW` | hex, 7 bytes | second `GetVersion` frame, same field order | +| `VersionProd` | hex, 14 bytes | third `GetVersion` frame: UID and production details | +| `Signature` | hex, 56 bytes | NXP originality signature, absent when the card refused it | +| `FreeMem` | int | bytes reported by `GetFreeMem`, absent when the card refused it | + +Absent means the field is not written at all. Do not read a missing field as a +zero. + +`GetVersion` answers over three chained frames and they are stored as three +fields rather than one blob, because the third frame is not the same shape +across generations: D40 and EV1 close it with `UID || BatchNo[5] || CW || Year` +while EV3 re-cuts it as `UID || BatchNo[3] || TypeID[2] || CW || Year`. Each +frame is kept raw, so any generation round-trips without the format having to +know which one it is holding. + +`VersionHW` bytes 3 and 4 -- major and minor -- are what identify the +generation. `client/src/mifare/prime.c` maps them: EV1 is `01 00`, EV2 is +`12 00` or `42 00`, EV2 XL `22 00`, EV3 `33 00`, DuoX `A0 00`. Byte 5 is the +storage size code, `2^(n>>1)` bytes. + +Nothing key related lives here. The PICC master key settings and keys belong to +application `000000` -- see [Applications](#applications) -- so every key in the +file states which AID it opens. + +## Applications +^[Top](#top) + +`$.Applications` is an object keyed by the 3-byte AID as 6 uppercase hex digits. + +**The PICC level is application `000000`.** It carries the PICC master key +settings and keys and has no files. Giving it an AID of its own is the point: a +key in this file always says which application it opens. + +```json +"Applications": { + "000000": { + "KeySettings": "0F", + "NumKeysRaw": "01", + "NumKeys": 1, + "KeyType": "2tdea", + "Authenticated": true, + "Keys": { + "0": { "Version": "00", "Key": "00000000000000000000000000000000" } + } + }, + "F51800": { + "ISOFileID": "DF01", + "DFName": "D2760000850100", + "KeySettings": "0B", + "NumKeysRaw": "81", + "NumKeys": 1, + "KeyType": "aes", + "Authenticated": true, + "Keys": { }, + "Files": { } + } +} +``` + +| Field | Type | Meaning | +|---|---|---| +| `ISOFileID` | hex, 2 bytes | ISO DF ID, absent when the application has none | +| `DFName` | hex, 1-16 bytes | ISO DF name, absent when the application has none | +| `KeySettings` | hex, 1 byte | | +| `NumKeysRaw` | hex, 1 byte | raw key-count byte, carries the key type in the top bits and the ISO-file-id flag in bit 5 | +| `NumKeys` | int | key count decoded from `NumKeysRaw` | +| `KeyType` | token | `des`, `2tdea`, `3tdea` or `aes`. One per application -- every key in an application shares it | +| `Authenticated` | bool | whether the dump ran authenticated against this application | +| `Keys` | object | see [Keys](#keys) | +| `Files` | object | see [Files](#files) | + +`Authenticated: false` is the flag that says how much to trust the rest of the +application: settings and contents may be whatever the card hands out to an +unauthenticated reader, which on many cards is nothing at all. + +JSON objects are unordered. A reader must look applications and files up by +key, not by position. + +## Files +^[Top](#top) + +`Files` is an object keyed by the file number as 2 uppercase hex digits. + +### Common fields +^[Top](#top) + +| Field | Type | Meaning | +|---|---|---| +| `Type` | token | see [Token spellings](#token-spellings) | +| `TypeRaw` | hex, 1 byte | the file type byte as the card reported it. This is the authoritative one, `Type` is for humans | +| `ISOFileID` | hex, 2 bytes | absent when the file has none | +| `CommMode` | token | `plain`, `mac`, `plain_rfu` or `encrypt`, from the raw 2-bit file comm mode | +| `AccessRights` | hex, 2 bytes | raw access rights word: read, write, read/write, change, 4 bits each | +| `AdditionalAccessRights` | object | index -> 2 byte rights word, absent when the file has none | +| `Read` | bool | see [The Read flag](#the-read-flag) | + +### Standard and backup data files +^[Top](#top) + +`TypeRaw` `00` and `01`. + +| Field | Type | Meaning | +|---|---|---| +| `FileSize` | int | size the card reports | +| `Data` | hex | contents. May be shorter than `FileSize` when `hf mfdes dump --length` capped the read | + +### Value files +^[Top](#top) + +`TypeRaw` `02`. A value file has no `Data`. + +| Field | Type | Meaning | +|---|---|---| +| `LowerLimit` | int | | +| `UpperLimit` | int | | +| `LimitedCredit` | hex, 1 byte | | +| `Value` | int | present only when `Read` is true | + +### Record files +^[Top](#top) + +`TypeRaw` `03` (linear) and `04` (cyclic). + +| Field | Type | Meaning | +|---|---|---| +| `RecordSize` | int | bytes per record | +| `MaxRecords` | int | | +| `CurRecords` | int | | +| `Records` | object | record index -> hex string of exactly `RecordSize` bytes | + +Records are numbered from `0` and must be contiguous. A record file whose +contents could not be split into whole records falls back to a single flat +`Data` string instead of `Records`. + +### Transaction MAC files +^[Top](#top) + +`TypeRaw` `05`. Stored like a data file: the 12 byte answer goes in `Data` +(4 byte counter, 8 byte MAC), and is not decoded further. + +## Keys +^[Top](#top) + +Keys are part of the image, not a side file. A simulator cannot answer an +authentication without them, and splitting them across two files means a card +image that silently cannot be used. + +Every application, `000000` included, carries a `Keys` object keyed by key +number in decimal: + +```json +"Keys": { + "0": { "Version": "00", "Key": "E757178E13516A4F3171BC6EA85E165A" }, + "1": { "Version": "03" } +} +``` + +| Field | Meaning | +|---|---| +| `Version` | the key version, as read from the card. Present whenever we managed to read it | +| `Key` | the key itself. Present only when we actually have it | + +A key version is readable without knowing the key, so the two are independent: + +* **`Version` and `Key`** -- we read the version and we have the key. +* **`Version` only** -- the key exists, we know its version, we could not + recover it. This is the normal case for every key but the one we authenticated + with. A missing `Key` never means the key is all zeros. +* **entry absent entirely** -- we know nothing about that key number. + +There is no per-key algorithm. Every key in an application uses the +application's `KeyType`, which fixes the length: `des` 8 bytes, `2tdea` 16, +`3tdea` 24, `aes` 16. + +Note the difference from the `mfdes v2` key recovery format written by +`hf mfdes chk`, which nests keys under an algorithm name +(`Applications.112233.AES.0.Key`) because during recovery the key type is not +yet known. In a dump it is, so the algorithm is stated once per application. + +`hf mfdes dump` reads a `mfdes v2` key file with `--keys `, and with no +`--keys` it looks for `hf-mfdes--keys.json` on its own -- the same filename +template it saves the dump under. Nothing is reported if that file does not +exist. + +## The Read flag +^[Top](#top) + +Every file carries `Read`. It is true only when the contents were actually +fetched from the card. + +* `Read: true` with `Data` -- these are the card's bytes. +* `Read: true` without `Data` (or with an empty one) -- the card answered, with nothing in it. +* `Read: false` -- we never got the contents. Access was denied, the key was + wrong, or the session died. There is no `Data` key at all. + +A reader must never turn a missing `Data` into zeros. The whole point of the +flag is that "8 bytes of 00" and "we could not read 8 bytes" are different +facts, and a simulator that confuses them will confidently answer a reader with +contents the card never had. + +## Token spellings +^[Top](#top) + +String tokens match what the `hf mfdes` CLI already accepts, so a value read out +of a dump file can be handed straight back to a command. + +| `Type` | `TypeRaw` | +|---|---| +| `standard` | `00` | +| `backup` | `01` | +| `value` | `02` | +| `linear_record` | `03` | +| `cyclic_record` | `04` | +| `transaction_mac` | `05` | + +| `CommMode` | raw | +|---|---| +| `plain` | `0` | +| `mac` | `1` | +| `plain_rfu` | `2` | +| `encrypt` | `3` | + +`plain_rfu` is the card's second encoding for plain. It is kept distinct from +`plain` so the file records what the card actually said. + +| `KeyType` | key length | +|---|---| +| `des` | 8 | +| `2tdea` | 16 | +| `3tdea` | 24 | +| `aes` | 16 | + +Hex strings are uppercase with no separators. Byte order is as the bytes travel +on the wire, except `AccessRights` and the ISO file IDs, which are written big +endian the way they are printed. + +## A complete example +^[Top](#top) + +A real dump of a MIFARE DESFire EV2 2K, set up from blank with the commands +below. Every construct in this document appears in it: the PICC as application +`000000`, an AES application and a 2TDEA one, a standard data file, a value +file, a record file, and keys that are known by version but not by value. + +### The card +^[Top](#top) + +``` +# two applications, one AES with 3 keys, one 2TDEA with 2 +hf mfdes createapp -t 2tdea -k 00000000000000000000000000000000 --aid 112233 --fid 1122 --dfname pm3test1 --ks1 0F --ks2 A3 +hf mfdes createapp -t 2tdea -k 00000000000000000000000000000000 --aid 445566 --fid 4455 --dfname pm3test2 --ks1 0F --ks2 22 + +# ks2 carries the key type in the top two bits (0 = 2TDEA, 1 = 3TDEA, 2 = AES), +# the ISO-file-id flag in bit 5 and the key count in the low five. It overrides +# --dstalgo and --numkeys, so A3 is "AES, ISO file ids, 3 keys" + +# files in the AES application +hf mfdes createfile --aid 112233 -t aes -k 00000000000000000000000000000000 --fid 01 --isofid 0001 --size 000020 --amode encrypt --rrights key0 --wrights key0 --rwrights key0 --chrights key0 +hf mfdes createvaluefile --aid 112233 -t aes -k 00000000000000000000000000000000 --fid 02 --amode mac --lower 00000000 --upper 000003E8 --value 0000002A --lcredit 1 --rrights key0 --wrights key0 --rwrights key0 --chrights key0 +hf mfdes createrecordfile --aid 112233 -t aes -k 00000000000000000000000000000000 --fid 03 --isofid 0003 --size 000008 --maxrecord 000005 --amode plain --rrights free --wrights key0 --rwrights key0 --chrights key0 + +# and one in the 2TDEA application +hf mfdes createfile --aid 445566 -t 2tdea -k 00000000000000000000000000000000 --fid 00 --isofid 0010 --size 000010 --amode plain --rrights free --wrights key0 --rwrights key0 --chrights key0 + +# contents +hf mfdes write --aid 112233 -t aes -k 00000000000000000000000000000000 --fid 01 -d 50726F786D61726B33204445534669726520746573742064617461212121 +hf mfdes write --aid 112233 -t aes -k 00000000000000000000000000000000 --fid 03 --type record -d 5245434F52443031 +hf mfdes write --aid 112233 -t aes -k 00000000000000000000000000000000 --fid 03 --type record -d 5245434F52443032 +hf mfdes write --aid 445566 -t 2tdea -k 00000000000000000000000000000000 --fid 00 -d 48454C4C4F2050524F584D41524B2133 + +# recover the application keys, saved under the name the dump will look for +hf mfdes chk -k 00000000000000000000000000000000 -j hf-mfdes-043240CAE45380-keys + +# and dump it +hf mfdes dump -t 2tdea -k 00000000000000000000000000000000 + +# to put the card back the way it was +hf mfdes formatpicc -t 2tdea -k 00000000000000000000000000000000 +``` + +Without that `chk` run, application `112233` cannot be opened with the 2TDEA +PICC key. The dump does not pretend otherwise: it records the application with +`"Authenticated": false` and no files, rather than inventing empty ones. + +### The key file +^[Top](#top) + +`hf-mfdes-043240CAE45380-keys.json`, written by `hf mfdes chk -j`. This is the +separate `mfdes v2` format, not part of the card image -- `hf mfdes dump` reads +it and folds the keys it contains into the dump. + +```json +{ + "Created": "proxmark3", + "FileType": "mfdes v2", + "Card": { + "UID": "043240CAE45380", + "SAK": "20", + "ATQA": "4403", + "ATS": "06757781028002F0" + }, + "Applications": { + "112233": { + "AES": { + "0": { + "Key": "00000000000000000000000000000000" + } + } + }, + "445566": { + "2TDEA": { + "0": { + "Key": "00000000000000000000000000000000" + } + } + } + } +} +``` + +Two differences from the way the dump stores keys: + +* Keys are nested under an **algorithm name** (`Applications.112233.AES.0.Key`) + because during key recovery the application's key type is not yet known. A + dump knows it, so it states `KeyType` once per application instead. +* PICC keys are not in this file at all. `hf mfdes chk` only walks the + application list; the PICC master key is the one you hand it with `-k`. + +The dump picks this file up without `--keys` because its name follows the same +`hf-mfdes--` template the dump itself is saved under: + +``` +[=] Loaded keys for 2 application(s) from `hf-mfdes-043240CAE45380-keys` +``` + +### The dump file +^[Top](#top) + +```json +{ + "Created": "proxmark3", + "FileType": "mfdes v1", + "Version": 1, + "Card": { + "UID": "043240CAE45380", + "ATQA": "4403", + "SAK": "20", + "ATS": "06757781028002F0", + "VersionHW": "04010112001605", + "VersionSW": "04010102001605", + "VersionProd": "043240CAE45380CD651745414216", + "Signature": "035766BD56631ED57B614CE01A24372BDC29028A310937BC42EE998C66E56E6251083B723099D80EB77291B1A8BDB055C614EC944A11E38E", + "FreeMem": 1984 + }, + "Applications": { + "000000": { + "KeySettings": "0F", + "NumKeysRaw": "01", + "NumKeys": 1, + "KeyType": "2tdea", + "Authenticated": true, + "Keys": { + "0": { + "Version": "00", + "Key": "00000000000000000000000000000000" + } + } + }, + "112233": { + "ISOFileID": "1122", + "DFName": "706D337465737431", + "KeySettings": "0F", + "NumKeysRaw": "83", + "NumKeys": 3, + "KeyType": "aes", + "Authenticated": true, + "Keys": { + "0": { + "Version": "00", + "Key": "00000000000000000000000000000000" + }, + "1": { + "Version": "00" + }, + "2": { + "Version": "00" + } + }, + "Files": { + "01": { + "Type": "standard", + "TypeRaw": "00", + "CommMode": "encrypt", + "AccessRights": "0000", + "ISOFileID": "0001", + "FileSize": 32, + "Read": true, + "Data": "50726F786D61726B332044455346697265207465737420646174612121210000" + }, + "02": { + "Type": "value", + "TypeRaw": "02", + "CommMode": "mac", + "AccessRights": "0000", + "LowerLimit": 0, + "UpperLimit": 1000, + "LimitedCredit": "01", + "Value": 42, + "Read": true + }, + "03": { + "Type": "linear_record", + "TypeRaw": "03", + "CommMode": "plain", + "AccessRights": "E000", + "ISOFileID": "0003", + "RecordSize": 8, + "MaxRecords": 5, + "CurRecords": 2, + "Read": true, + "Records": { + "0": "5245434F52443031", + "1": "5245434F52443032" + } + } + } + }, + "445566": { + "ISOFileID": "4455", + "DFName": "706D337465737432", + "KeySettings": "0F", + "NumKeysRaw": "02", + "NumKeys": 2, + "KeyType": "2tdea", + "Authenticated": true, + "Keys": { + "0": { + "Version": "00", + "Key": "00000000000000000000000000000000" + }, + "1": { + "Version": "00" + } + }, + "Files": { + "00": { + "Type": "standard", + "TypeRaw": "00", + "CommMode": "plain", + "AccessRights": "E000", + "ISOFileID": "0010", + "FileSize": 16, + "Read": true, + "Data": "48454C4C4F2050524F584D41524B2133" + } + } + } + } +} +``` + +Things to read out of it: + +* **`FreeMem` is 1984** with the two applications in place. Measured on this same + card: 2080 free before the example was built, 1984 with it, and 2560 after + `hf mfdes formatpicc`. A format therefore reclaims space that creating and + deleting applications leaves behind -- 0 applications on its own does not mean + a fully free card. +* **`NumKeysRaw` `83`** decodes to `KeyType: aes` (top bits 10), ISO file ids + enabled (bit 5) and `NumKeys: 3`. +* **Keys 1 and 2 of `112233` have a `Version` but no `Key`.** They exist, we + read their version, we never recovered them. Key 0 is the one `hf mfdes chk` + found. +* **The value file has no `Data`**, only `Value`, `LowerLimit`, `UpperLimit` + and `LimitedCredit`. +* **The record file has `Records`, not `Data`** -- two records of 8 bytes in a + file with room for five. +* **File `01` reads 32 bytes** where only 30 were written; the card zero-pads to + the file size, and the dump stores what the card returned. + +### What `hf mfdes view` makes of it +^[Top](#top) + +``` + +[=] --- Tag Information --------------------------- +[+] UID.............. 043240CAE45380 +[+] ATQA............. 03 44 +[+] SAK.............. 20 +[+] ATS.............. 06757781028002F0 +[+] Version HW....... 04010112001605 +[+] 12.0 ( DESFire EV2 ) +[+] Storage size... 0x16 ( 2048 bytes ) +[+] Version SW....... 04010102001605 +[+] Production....... 043240CAE45380CD651745414216 +[+] Signature........ 035766BD56631ED57B614CE01A24372BDC29028A310937BC42EE998C66E56E6251083B723099D80EB77291B1A8BDB055C614EC944A11E38E +[+] Free memory...... 1984 bytes + +[=] --- Applications ------------------------------ +[+] 2 application(s) plus the PICC level + +[=] --- AID 000000 ( PICC level ) --------------------- +[+] Key settings. 0F, 1 2tdea key(s) +[+] Authenticated yes +[+] Key 00 (ver 00). 00000000000000000000000000000000 +[+] Files........ 0 + +[=] --- AID 112233 -------------------------------- +[+] ISO DF ID.... 1122 +[+] DF name...... pm3test1 ( 706D337465737431 ) +[+] Key settings. 0F, 3 aes key(s) +[+] Authenticated yes +[+] Key 00 (ver 00). 00000000000000000000000000000000 +[+] Key 01 (ver 00). not recovered +[+] Key 02 (ver 00). not recovered +[+] Files........ 3 + +[+] File 01 - Standard data +[+] ISO file ID.. 0001 +[+] Comm mode.... encrypt +[+] Access rights 0000 +[+] File size.... 32 + +[=] Offset | Data | Ascii +[=] ---------------------------------------------------------------------------- +[=] 0/0x00 | 50 72 6F 78 6D 61 72 6B 33 20 44 45 53 46 69 72 | Proxmark3 DESFir +[=] 16/0x10 | 65 20 74 65 73 74 20 64 61 74 61 21 21 21 00 00 | e test data!!!.. + +[+] File 02 - Value +[+] Comm mode.... mac +[+] Access rights 0000 +[+] Limits....... 0 ... 1000 +[+] Value........ 42 (0x0000002A) + +[+] File 03 - Linear Record +[+] ISO file ID.. 0003 +[+] Comm mode.... plain +[+] Access rights E000 +[+] Records...... 2 of 5, 8 bytes each + +[+] Record 0 +[=] Offset | Data | Ascii +[=] ---------------------------------------------------------------------------- +[=] 0/0x00 | 52 45 43 4F 52 44 30 31 | RECORD01 +[+] Record 1 +[=] 0/0x00 | 52 45 43 4F 52 44 30 32 | RECORD02 + +[=] --- AID 445566 -------------------------------- +[+] ISO DF ID.... 4455 +[+] DF name...... pm3test2 ( 706D337465737432 ) +[+] Key settings. 0F, 2 2tdea key(s) +[+] Authenticated yes +[+] Key 00 (ver 00). 00000000000000000000000000000000 +[+] Key 01 (ver 00). not recovered +[+] Files........ 1 + +[+] File 00 - Standard data +[+] ISO file ID.. 0010 +[+] Comm mode.... plain +[+] Access rights E000 +[+] File size.... 16 + +[=] Offset | Data | Ascii +[=] ---------------------------------------------------------------------------- +[=] 0/0x00 | 48 45 4C 4C 4F 20 50 52 4F 58 4D 41 52 4B 21 33 | HELLO PROXMARK!3 +``` + +## In-memory representation +^[Top](#top) + +`desfire_dump_t` in `client/src/fileutils.h`, written by `prepareJSON()` and read +by `loadFileJSONex()` in `client/src/fileutils.c`. + +File contents hang off `desfire_dump_file_t` as heap pointers, so an image can +hold real file sizes without the struct itself being enormous. Whoever fills or +loads one owns those buffers and must call `desfire_dump_free()` before dropping +the image. + +The struct is bounded by `DESFIRE_MAX_APP_COUNT` (64) applications and +`DESFIRE_MAX_FILE_COUNT` (32) files per application, both in `include/desfire.h`. +Reading a file with more than that logs a warning and keeps the first N. + +## Not in v1 +^[Top](#top) + +Deliberately absent, listed so the next version does not have to rediscover them: + +* **No emulator memory layout.** This format is a card image, not a memory map. + How a PICC image is packed into the 4096 bytes of `CARD_MEMORY_SIZE` is a + separate problem, and the answer will not fit a large card. +* **No delegated application / DAM slot details.** +* **No key derivation state.** If a key in the file came out of AN10922 or the + Gallagher KDF, only the derived key is stored, not the diversification input. +* **No LRP / EV2 secure channel state**, no transaction counter, no `TI`. +* **No ISO 7816 file structure** beyond the ISO file IDs. diff --git a/doc/path_notes.md b/doc/path_notes.md index ae1c9c9d4..6458dfa17 100644 --- a/doc/path_notes.md +++ b/doc/path_notes.md @@ -64,7 +64,7 @@ The recovery / firmware files will be copied to ``` * Proxmark3 firmware: `bootrom.elf`, `fullimage.elf`, `recovery.bin` (used for JTAG) -* SIM firmware: `sim014.bin`, `sim014.sha512.txt` +* SIM firmware: `sim024.bin`, `sim024.sha512.txt` ## Traces diff --git a/doc/termux_notes.md b/doc/termux_notes.md index 1c3851320..a2bad3886 100644 --- a/doc/termux_notes.md +++ b/doc/termux_notes.md @@ -150,11 +150,11 @@ Install [this free TCPUART app](https://play.google.com/store/apps/details?id=co The app lets you choose the baudrate. Default value (115 200 baud) is fine. Plug the PM3 in and click connect. -Set the toggle in server mode and choose a random port not used by system (e.g. 4321) and start the server. +Set the toggle in server mode and choose a random port not used by system (client default port is 18888) and start the server. Alternatively, use the [paid version of the BT/USB/TCP Bridge app](https://play.google.com/store/apps/details?id=masar.bluetoothbridge.pro) which includes USB bridge as well. -In this app, select TCP server as 'Device A' and choose an unused port (e.g. 4321). +In this app, select TCP server as 'Device A' and choose an unused port (client default port is 18888). Choose your registered PM3 device as 'Device B' -> 'Connect to USB device'. Ensure 'Retransmission' is set to 'both ways'. It is possible to record the config as autostart, cf 'Settings' -> 'Autostart setting'. @@ -167,7 +167,7 @@ You can download the apk on this website without installing F-Droid. The app lets you choose the baudrate. Default value (115 200 baud) is fine. Plug the PM3 in and click `Connect`. -Choose a random port not used by system (e.g. 4321) and click `Start Server`. +Choose a random port not used by system (client default port is 18888) and click `Start Server`. Note: This app uses foreground service to keep the connection alive, so you can safely put it in the background without suspending the transmission. However, you will see a dummy notification in the status bar which is required for foreground service. @@ -180,7 +180,7 @@ Note: This app uses foreground service to keep the connection alive, so you can Install [this free app](https://play.google.com/store/apps/details?id=masar.bb) or [the paid version](https://play.google.com/store/apps/details?id=masar.bluetoothbridge.pro) (which includes usb bridge) You need to pair the proxmark3 in the Android settings. -In the app, select TCP server as 'Device A' and choose an unused port (e.g. 4321). +In the app, select TCP server as 'Device A' and choose an unused port (client default port is 18888). Choose your registered PM3 device as 'Device B' -> 'Connect to classic Bluetooth device'. Ensure 'Retransmission' is set to 'both ways'. It is possible to record the config as autostart, cf 'Settings' -> 'Autostart setting'. @@ -191,10 +191,10 @@ It is possible to record the config as autostart, cf 'Settings' -> 'Autostart se The Proxmark5 Battery Wireless Module (BWM) uses BLE, not classic Bluetooth. The [paid version of the BT/USB/TCP Bridge app](https://play.google.com/store/apps/details?id=masar.bluetoothbridge.pro) handles it (the free version works with 10 minute time limit, can be reset by restarting the app): -In the app, select TCP server as 'Device A' (default port 54321). +In the app, select TCP server as 'Device A', port 18888 to use the client default port. Choose 'Device B' -> 'Connect to BLE device' -> `Proxmark5`. When asked for the characteristic, choose: service UUID starting with `0000ae86`, characteristic starting with `0000ae88`, for RX+TX. -No pairing is needed. Then connect from Termux as in [TCP connection](#tcp-connection) using port 54321. +No pairing is needed. Then connect from Termux as in [TCP connection](#tcp-connection) using port 18888. See [PM5-BWM-USAGE.md](md/PM5_Start_Here/PM5-BWM-USAGE.md) for the BWM firmware build flag and the WiFi alternative, which needs no bridge app at all. @@ -252,10 +252,10 @@ proxmark3 udp:localhost:12345 ^[Top](#top) 1. Phone and pm3 are connected, blue led is on and *not* blinking -2. BTUART Tool TCP Server at Port 4321 +2. BTUART Tool TCP Server at Port 18888 3. Using proxmark3 in termux shows the following error message: ``` -$ proxmark3 tcp:localhost:4321 +$ proxmark3 tcp:localhost:18888 [=] Session log /data/data/com.termux/files/home/.suroot /.proxmark3/log_20210519.txt @@ -263,7 +263,7 @@ $ proxmark3 tcp:localhost:4321 [+] loaded from JSON file /data/data/com.termux/files/ho me/.suroot/.proxmark3/preferences.json -Using UART port tcp:localhost:4321 +Using UART port tcp:localhost:18888 [!!] ERROR: cannot communicate with the Proxmark3 ``` diff --git a/docker/README.md b/docker/README.md new file mode 100644 index 000000000..cbf521148 --- /dev/null +++ b/docker/README.md @@ -0,0 +1,7 @@ +# Docker tests + +Usage: +- enter one of the subfolders +- `../build.sh` to build the docker image +- `../run.sh` to run a container and get a shell +- `../run.sh tests` to run a container and execute its `run_tests.sh` diff --git a/docker/build-all.sh b/docker/build-all.sh index 999d6ef26..db61e734f 100755 --- a/docker/build-all.sh +++ b/docker/build-all.sh @@ -1,6 +1,6 @@ #!/bin/bash -for os in archlinux debian-13-trixie debian-13-trixie-arm64 debian-13-trixie-armhf debian-14-forky fedora-41 fedora-42 fedora-43 homebrew kali opensuse-leap opensuse-tumbleweed parrot-core-latest ubuntu-24.04 ubuntu-24.10 ubuntu-25.04; do +for os in archlinux debian-13-trixie debian-13-trixie-arm64 debian-13-trixie-armhf debian-14-forky fedora-41 fedora-42 fedora-43 homebrew kali opensuse-leap opensuse-tumbleweed parrot-core-latest ubuntu-22.04 ubuntu-24.04 ubuntu-24.10 ubuntu-25.04 ubuntu-25.10; do echo -e "\n\n================= Building for $os ======================\n" ( cd $os && ../build.sh ) done diff --git a/docker/debian-13-trixie-arm64/README.md b/docker/debian-13-trixie-arm64/README.md index 68cc52712..485f84893 100644 --- a/docker/debian-13-trixie-arm64/README.md +++ b/docker/debian-13-trixie-arm64/README.md @@ -1,4 +1,4 @@ -# Notes to install corss-platform support +# Notes to install cross-platform support ``` sudo apt install qemu-user qemu-user-binfmt binfmt-support ``` diff --git a/docker/debian-13-trixie-arm64/run_tests.sh b/docker/debian-13-trixie-arm64/run_tests.sh index 8d31f8332..c8febcc29 100755 --- a/docker/debian-13-trixie-arm64/run_tests.sh +++ b/docker/debian-13-trixie-arm64/run_tests.sh @@ -2,14 +2,25 @@ # This script is to be run from proxmark root folder inside the docker env # docker/debian-13-trixie-arm64/run_tests.sh; +# sudo not supported in this docker image, update packages before running as rrg user +if [ "$EUID" -eq 0 ]; then + apt update && sudo apt upgrade -y +fi + +# Re-execute the script as rrg user if not already running as rrg +if [[ $(id -un) != rrg ]]; then + script_path=$(readlink -f -- "${BASH_SOURCE[0]}") + working_directory=$(pwd -P) + exec su - rrg -c 'cd "$1" && exec bash "$2" "${@:3}"' bash \ + "$working_directory" "$script_path" "$@" +fi + # Check that we are not running as root if [ "$EUID" -eq 0 ]; then echo "Error: This script should not be run as root" >&2 exit 1 fi -# sudo not supported in this docker image, update packages before running as rrg user -# sudo apt update && sudo apt upgrade -y git config --global --add safe.directory /home/rrg/proxmark3 tools/release_tests.sh # beeps diff --git a/docker/debian-13-trixie-armhf/README.md b/docker/debian-13-trixie-armhf/README.md index aceaf5c44..351349fb5 100644 --- a/docker/debian-13-trixie-armhf/README.md +++ b/docker/debian-13-trixie-armhf/README.md @@ -1,4 +1,4 @@ -# Notes to install corss-platform support +# Notes to install cross-platform support ``` sudo apt install qemu-user qemu-user-binfmt binfmt-support ``` diff --git a/docker/debian-13-trixie-armhf/run_tests.sh b/docker/debian-13-trixie-armhf/run_tests.sh index bb0e350e0..eb9ff714b 100755 --- a/docker/debian-13-trixie-armhf/run_tests.sh +++ b/docker/debian-13-trixie-armhf/run_tests.sh @@ -2,15 +2,25 @@ # This script is to be run from proxmark root folder inside the docker env # docker/debian-13-trixie-armhf/run_tests.sh; +# sudo not supported in this docker image, update packages before running as rrg user +if [ "$EUID" -eq 0 ]; then + apt update && sudo apt upgrade -y +fi + +# Re-execute the script as rrg user if not already running as rrg +if [[ $(id -un) != rrg ]]; then + script_path=$(readlink -f -- "${BASH_SOURCE[0]}") + working_directory=$(pwd -P) + exec su - rrg -c 'cd "$1" && exec bash "$2" "${@:3}"' bash \ + "$working_directory" "$script_path" "$@" +fi + # Check that we are not running as root if [ "$EUID" -eq 0 ]; then echo "Error: This script should not be run as root" >&2 exit 1 fi -# sudo not supported in this docker image, update packages before running as rrg user -# sudo apt update && sudo apt upgrade -y - git config --global --add safe.directory /home/rrg/proxmark3 tools/release_tests.sh # beeps diff --git a/docker/run.sh b/docker/run.sh index df178fb6c..0af9b49c8 100755 --- a/docker/run.sh +++ b/docker/run.sh @@ -11,4 +11,9 @@ if [ -n "$UART_PORT" ]; then else DEV="" fi -docker run $DEV $DOCKER_PLATFORM --volume="$(pwd)/../..:/home/rrg/proxmark3" -w /home/rrg/proxmark3 --net=host --rm -it "$DOCKER_IMAGE" +TEST_PATH=$(basename $(pwd -L)) +DOCKER_COMMAND=() +if [ "$1" = "tests" ]; then + DOCKER_COMMAND=("docker/$TEST_PATH/run_tests.sh") +fi +docker run $DEV $DOCKER_PLATFORM --volume="$(pwd)/../..:/home/rrg/proxmark3" -w /home/rrg/proxmark3 --net=host --rm -it "$DOCKER_IMAGE" "${DOCKER_COMMAND[@]}" diff --git a/fpga/Makefile b/fpga/Makefile index e358cea65..f34fe80f2 100644 --- a/fpga/Makefile +++ b/fpga/Makefile @@ -1,259 +1,68 @@ # -# FPGA Makefile for all targets +# FPGA build dispatcher. # -# The top part of this Makefile is used to define custom options for a number of compilation targets -# To define an additional target simply look at the other defined targets and add a new TARGET entry with a unique number and the custom options required +# Each requested target is routed to the implementation of the platform that +# owns it: +# proxmark3_fpga.mk Xilinx ISE - PM3, PM3-ULT, iCopy-X +# proxmark5_fpga.mk yosys/nextpnr - PM5 +# +# make - every PM3 image +# make pm3 - same +# make pm5 - the PM5 bitstream +# make - routed by name, e.g. fpga_pm3_hf, fpga_pm3_ult_lf, fpga_pm5 +# make clean - both platforms +# make help - both target lists +# +# Both platform files are also usable directly, which is how the recursive +# builds call them: +# make -C fpga -f proxmark5_fpga.mk all -XILINX_TOOLS_PREFIX= +include common_src.mk -# Copy update (only when destination is older or missing) -CP = cp -u +PM3_MK = proxmark3_fpga.mk +PM5_MK = proxmark5_fpga.mk -# Make directory, no error if already existing -MKDIR = mkdir -p +PLATFORMS = pm3 pm5 -# Remove recursive, force -RMDIR = rm -rf +# Everything that is not a dispatcher builtin is forwarded to a platform file. +GOALS = $(filter-out $(PLATFORMS) all clean help,$(MAKECMDGOALS)) -# Path to make -MAKE = make +# PM5 owns the fpga_pm5* targets, everything else is PM3. +mk_for = $(if $(filter fpga_pm5%,$1),$(PM5_MK),$(PM3_MK)) -# Custom prefix for build directories, each target is built into its own separate directory name formed by combining the PREFIX and TARGET names. -# This way the source is not polluted with build files and the build directories are left behind after compilation so logs and reports can be -# examined or can be easily deleted with "make clean" -PREFIX = __ +.PHONY: all pm3 pm5 clean help $(GOALS) -# Options to be passed to XST -XST_OPTS_BASE = run -XST_OPTS_BASE += -ifn xst.prj -XST_OPTS_BASE += -ifmt mixed -XST_OPTS_BASE += -ofmt NGC -XST_OPTS_BASE += -lso xst.lso -XST_OPTS_BASE += -top fpga_top -XST_OPTS_BASE += -resource_sharing yes +ifneq ($(GOALS),) -# Optimizations for speed (default) -XST_OPTS_SPEED = -opt_mode Speed -XST_OPTS_SPEED += -opt_level 1 -XST_OPTS_SPEED += -fsm_style lut -XST_OPTS_SPEED += -fsm_encoding auto +$(GOALS): + $(Q)$(MAKE) --no-print-directory -f $(call mk_for,$@) $@ -# Optimization for reduced space -XST_OPTS_AREA = -opt_mode area -XST_OPTS_AREA += -opt_level 2 -XST_OPTS_AREA += -fsm_style bram -XST_OPTS_AREA += -fsm_encoding compact +all pm3 pm5 clean help: ; -# par specific option (set determistic seed) -PAR_OPTIONS = -t 2 +else -# Types of selective module compilation: -# WITH_LF Enables selection of LF modules (and disables all HF) +all: pm3 -# To enable these modules WITH_LF _MUST_ be defined -# WITH_LF0 enable LF reader (generic) -# WITH_LF1 enable LF edge detect (generic) -# WITH_LF2 enable LF passthrough -# WITH_LF3 enable LF ADC (read/write) +pm3: + $(Q)$(MAKE) --no-print-directory -f $(PM3_MK) all -# To enable these modules WITH_LF _MUST_NOT_ be defined -# WITH_HF0 enable HF reader (see also WITH_HF_15 below) -# WITH_HF_15 select "iso15 2sc mode" extensions instead of original -# WITH_HF1 enable HF simulated tag -# WITH_HF2 enable HF ISO14443-A -# WITH_HF3 enable sniff -# WITH_HF4 enable HF ISO18092 FeliCa -# WITH_HF5 enable HF get trace +pm5: + $(Q)$(MAKE) --no-print-directory -f $(PM5_MK) all -# RDV40/Generic - Enable LF and all the LF modules -TARGET1_OPTIONS = -define \{WITH_LF WITH_LF0 WITH_LF1 WITH_LF2 WITH_LF3\} -# RDV40/Generic - Enable all HF modules except Felica -TARGET2_OPTIONS = -define \{WITH_HF0 WITH_HF1 WITH_HF2 WITH_HF3 WITH_HF5\} -# RDV40/Generic - Enable all HF modules except Felica and ISO14443, select HF_15 instead of HF -TARGET3_OPTIONS = -define \{WITH_HF0 WITH_HF1 WITH_HF3 WITH_HF5 WITH_HF_15 WITH_HF_15_LOWSIGNAL\} -# RDV40/Generic - Enable all HF modules except ISO14443 -TARGET4_OPTIONS = -define \{WITH_HF0 WITH_HF1 WITH_HF3 WITH_HF4 WITH_HF5 WITH_FELICA_PROBE\} -# ICOPYX -TARGET5_OPTIONS = $(TARGET1_OPTIONS) -TARGET6_OPTIONS = $(TARGET1_OPTIONS) -TARGET7_OPTIONS = $(TARGET1_OPTIONS) -TARGET8_OPTIONS = $(TARGET1_OPTIONS) -TARGET9_OPTIONS = $(TARGET1_OPTIONS) - -# Here we list the target names -TARGET1_NAME = fpga_pm3_lf -TARGET2_NAME = fpga_pm3_hf -TARGET3_NAME = fpga_pm3_hf_15 -TARGET4_NAME = fpga_pm3_felica -TARGET5_NAME = fpga_icopyx_hf -TARGET6_NAME = fpga_pm3_ult_lf -TARGET7_NAME = fpga_pm3_ult_hf -TARGET8_NAME = fpga_pm3_ult_hf_15 -TARGET9_NAME = fpga_pm3_ult_felica - -# Targets can be compiled for different FPGA flavours -TARGET1_FPGA = xc2s30-5-vq100 -TARGET2_FPGA = $(TARGET1_FPGA) -TARGET3_FPGA = $(TARGET1_FPGA) -TARGET4_FPGA = $(TARGET1_FPGA) -TARGET5_FPGA = xc3s100e-4-vq100 -TARGET6_FPGA = xc2s50-5-tq144 -TARGET7_FPGA = $(TARGET6_FPGA) -TARGET8_FPGA = $(TARGET6_FPGA) -TARGET9_FPGA = $(TARGET6_FPGA) - -# Assemble the final XST options for each target -TARGET1_XST_OPTS = $(XST_OPTS_BASE) $(XST_OPTS_AREA) -p $(TARGET1_FPGA) -ofn $(TARGET1_NAME) $(TARGET1_OPTIONS) -TARGET2_XST_OPTS = $(XST_OPTS_BASE) $(XST_OPTS_AREA) -p $(TARGET2_FPGA) -ofn $(TARGET2_NAME) $(TARGET2_OPTIONS) -TARGET3_XST_OPTS = $(XST_OPTS_BASE) $(XST_OPTS_AREA) -p $(TARGET3_FPGA) -ofn $(TARGET3_NAME) $(TARGET3_OPTIONS) -TARGET4_XST_OPTS = $(XST_OPTS_BASE) $(XST_OPTS_AREA) -p $(TARGET4_FPGA) -ofn $(TARGET4_NAME) $(TARGET4_OPTIONS) -TARGET5_XST_OPTS = $(XST_OPTS_BASE) $(XST_OPTS_SPEED) -p $(TARGET5_FPGA) -ofn $(TARGET5_NAME) $(TARGET5_OPTIONS) -TARGET6_XST_OPTS = $(XST_OPTS_BASE) $(XST_OPTS_SPEED) -p $(TARGET6_FPGA) -ofn $(TARGET6_NAME) $(TARGET6_OPTIONS) -TARGET7_XST_OPTS = $(XST_OPTS_BASE) $(XST_OPTS_SPEED) -p $(TARGET7_FPGA) -ofn $(TARGET7_NAME) $(TARGET7_OPTIONS) -TARGET8_XST_OPTS = $(XST_OPTS_BASE) $(XST_OPTS_SPEED) -p $(TARGET8_FPGA) -ofn $(TARGET8_NAME) $(TARGET8_OPTIONS) -TARGET9_XST_OPTS = $(XST_OPTS_BASE) $(XST_OPTS_SPEED) -p $(TARGET9_FPGA) -ofn $(TARGET9_NAME) $(TARGET9_OPTIONS) - -# these files are common for all targets -TARGET_COMMON_FILES = define.v -TARGET_COMMON_FILES += mux8.v -TARGET_COMMON_FILES += clk_divider.v -TARGET_COMMON_FILES += lp20khz_1MSa_iir_filter.v -TARGET_COMMON_FILES += min_max_tracker.v -TARGET_COMMON_FILES += hi_flite.v -TARGET_COMMON_FILES += hi_get_trace.v -TARGET_COMMON_FILES += hi_iso14443a.v -TARGET_COMMON_FILES += hi_reader.v -TARGET_COMMON_FILES += hi_simulate.v -TARGET_COMMON_FILES += hi_sniffer.v -TARGET_COMMON_FILES += lf_edge_detect.v -TARGET_COMMON_FILES += lo_adc.v -TARGET_COMMON_FILES += lo_edge_detect.v -TARGET_COMMON_FILES += lo_passthru.v -TARGET_COMMON_FILES += lo_read.v - -# Add the files that are unique per target and all the common files -TARGET1_FILES = $(TARGET_COMMON_FILES) fpga_pm3_top.v -TARGET2_FILES = $(TARGET1_FILES) -TARGET3_FILES = $(TARGET1_FILES) -TARGET4_FILES = $(TARGET1_FILES) -TARGET5_FILES = $(TARGET_COMMON_FILES) mux2_onein.v mux2_oneout.v fpga_icopyx_hf.v fpga_icopyx_lf.v fpga_icopyx_top.v -TARGET6_FILES = $(TARGET1_FILES) -TARGET7_FILES = $(TARGET1_FILES) -TARGET8_FILES = $(TARGET1_FILES) -TARGET9_FILES = $(TARGET1_FILES) - -# List of all valid target FPGA images to build -TARGETS = $(TARGET1_NAME) $(TARGET2_NAME) $(TARGET3_NAME) $(TARGET4_NAME) $(TARGET5_NAME) $(TARGET6_NAME) $(TARGET7_NAME) $(TARGET8_NAME) $(TARGET9_NAME) - -# Verbosity type for ISE tools ise|xflow|silent -VERBOSITY = -intstyle silent -# Echo (Q=) or not echo (Q=@) build commands to the terminal -Q= - -# Pass the custom variables to the lower make rules -$(TARGET1_NAME).bit: TARGET_FPGA = $(TARGET1_FPGA) -$(TARGET1_NAME).bit: TARGET_FILES = $(TARGET1_FILES) -$(TARGET1_NAME).bit: TARGET_XST_OPTS = $(TARGET1_XST_OPTS) - -$(TARGET2_NAME).bit: TARGET_FPGA = $(TARGET2_FPGA) -$(TARGET2_NAME).bit: TARGET_FILES = $(TARGET2_FILES) -$(TARGET2_NAME).bit: TARGET_XST_OPTS = $(TARGET2_XST_OPTS) - -$(TARGET3_NAME).bit: TARGET_FPGA = $(TARGET3_FPGA) -$(TARGET3_NAME).bit: TARGET_FILES = $(TARGET3_FILES) -$(TARGET3_NAME).bit: TARGET_XST_OPTS = $(TARGET3_XST_OPTS) - -$(TARGET4_NAME).bit: TARGET_FPGA = $(TARGET4_FPGA) -$(TARGET4_NAME).bit: TARGET_FILES = $(TARGET4_FILES) -$(TARGET4_NAME).bit: TARGET_XST_OPTS = $(TARGET4_XST_OPTS) - -$(TARGET5_NAME).bit: TARGET_FPGA = $(TARGET5_FPGA) -$(TARGET5_NAME).bit: TARGET_FILES = $(TARGET5_FILES) -$(TARGET5_NAME).bit: TARGET_XST_OPTS = $(TARGET5_XST_OPTS) - -$(TARGET6_NAME).bit: TARGET_FPGA = $(TARGET6_FPGA) -$(TARGET6_NAME).bit: TARGET_FILES = $(TARGET6_FILES) -$(TARGET6_NAME).bit: TARGET_XST_OPTS = $(TARGET6_XST_OPTS) - -$(TARGET7_NAME).bit: TARGET_FPGA = $(TARGET7_FPGA) -$(TARGET7_NAME).bit: TARGET_FILES = $(TARGET7_FILES) -$(TARGET7_NAME).bit: TARGET_XST_OPTS = $(TARGET7_XST_OPTS) - -$(TARGET8_NAME).bit: TARGET_FPGA = $(TARGET8_FPGA) -$(TARGET8_NAME).bit: TARGET_FILES = $(TARGET8_FILES) -$(TARGET8_NAME).bit: TARGET_XST_OPTS = $(TARGET8_XST_OPTS) - -$(TARGET9_NAME).bit: TARGET_FPGA = $(TARGET9_FPGA) -$(TARGET9_NAME).bit: TARGET_FILES = $(TARGET9_FILES) -$(TARGET9_NAME).bit: TARGET_XST_OPTS = $(TARGET9_XST_OPTS) - -$(TARGETS): - $(Q)$(MKDIR) $(PREFIX)build_$@ - $(Q)$(MAKE) -C $(PREFIX)build_$@ -f ../Makefile $(notdir $@).bit - -work: - $(Q)$(RM) xst.prj - $(Q)for item in $(TARGET_FILES); do echo verilog work ../$$item>>xst.prj; done - $(Q)echo work> xst.lso - -%.xst: work - $(Q)$(RM) $@ - $(Q)echo $(TARGET_XST_OPTS)> $@ - -%.ngc: %.xst - $(Q)$(RM) $@ - $(info [-] XST $@) - $(Q)$(XILINX_TOOLS_PREFIX)xst $(VERBOSITY) -ifn $< - -%.ngd: %.ngc - $(Q)$(RM) $@ - $(info [-] NGD $@) - $(Q)$(XILINX_TOOLS_PREFIX)ngdbuild $(VERBOSITY) -quiet -p $(TARGET_FPGA) -nt timestamp -uc ../$(TARGET_FPGA).ucf $< $@ - -%_map.ncd: %.ngd - $(Q)$(RM) $@ - $(info [-] MAP $@) - $(Q)$(XILINX_TOOLS_PREFIX)map $(VERBOSITY) -p $(TARGET_FPGA) -o $*_map $* - -%.ncd: %_map.ncd - $(Q)$(RM) $@ - $(info [-] PAR $@) - $(Q)$(XILINX_TOOLS_PREFIX)par $(PAR_OPTIONS) $(VERBOSITY) -w $< $@ - -%.bit: %.ncd - $(Q)$(RM) $@ $*.drc $*.rbt - $(info [=] BITGEN $@) - $(Q)$(XILINX_TOOLS_PREFIX)bitgen $(VERBOSITY) -w $* $@ - $(Q)python3 ../strip_date_time_from_binary.py $@ || true - $(Q)$(CP) $@ .. - -# Build all targets -all: $(TARGETS) - -# ALWAYS have some hardcoded text after $(PREFIX) to avoid rm -rf * or rm -rf /* situations if PREFIX is incorrectly set to empty "" or just "/" clean: - $(Q)$(RMDIR) $(PREFIX)build_* - $(info [-] Build files deleted) - -.DEFAULT: - @if [ "$@" != "all" ] && [ ! "$(filter $@,$(TARGETS))" ]; then \ - make help; \ - else \ - make all; \ - fi - -.PHONY: all help clean + $(Q)$(MAKE) --no-print-directory -f $(PM3_MK) clean + $(Q)$(MAKE) --no-print-directory -f $(PM5_MK) clean help: @echo "################################################################" + @echo "# FPGA build dispatcher" @echo "#" - @echo "# - Builds only one of the above listed targets" - @echo "# all - Builds the FPGA bitstreams for all targets" - @echo "# clean - Keeps .bit files but cleans intermediate build files for all targets" - @echo "#" - @echo "#" - @echo "# Valid targets are:" - @echo "# $(TARGETS)" - @echo "#" + @echo "# make - every PM3 image (Xilinx ISE)" + @echo "# make pm5 - the PM5 bitstream (yosys/nextpnr-himbaechel)" + @echo "# make - routed by name, e.g. fpga_pm3_hf, fpga_pm5" + @echo "# make clean - both platforms" @echo "################################################################" + $(Q)$(MAKE) --no-print-directory -f $(PM3_MK) help + $(Q)$(MAKE) --no-print-directory -f $(PM5_MK) help +endif diff --git a/fpga/clk_divider.v b/fpga/common/clk_divider.v similarity index 96% rename from fpga/clk_divider.v rename to fpga/common/clk_divider.v index 7cb9925f3..6a55d1d3a 100644 --- a/fpga/clk_divider.v +++ b/fpga/common/clk_divider.v @@ -32,7 +32,7 @@ module clk_divider( div_cnt_ <= 8'd0; div_clk_ = !div_clk_; end else - div_cnt_ <= div_cnt_ + 1; + div_cnt_ <= div_cnt_ + 1'b1; end endmodule diff --git a/fpga/define.v b/fpga/common/define.v similarity index 98% rename from fpga/define.v rename to fpga/common/define.v index b7267a545..bf610f204 100644 --- a/fpga/define.v +++ b/fpga/common/define.v @@ -99,6 +99,10 @@ `define FPGA_CMD_SET_DIVISOR 2 `define FPGA_CMD_SET_EDGE_DETECT_THRESHOLD 3 `define FPGA_CMD_TRACE_ENABLE 2 +// Definitions for the FPGA commands that are only available on PM5 +`ifdef PM5 +`define FPGA_CMD_SET_PWR_PWM_LOW_COUNT 4 +`endif // Major modes `define FPGA_MAJOR_MODE_LF_READER 0 diff --git a/fpga/common/fs2bin.py b/fpga/common/fs2bin.py new file mode 100644 index 000000000..409ddf3cb --- /dev/null +++ b/fpga/common/fs2bin.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 + +# Pack an ASCII Gowin bitstream (.fs from apycula's gowin_pack) into the binary +# form the ARM JTAG loader shifts out for `hw fpga config`. +# Every byte in the .fs is 8 ASCII '0'/'1' characters, most significant bit +# first; the inverse of apycula's bslib.bytearr(), which is reused here so the +# two cannot drift apart. +# +# usage: fs2bin.py + +import sys + +from apycula.bslib import bytearr + + +def main(infile, outfile): + data = bytearray() + with open(infile) as f: + for line in f: + line = line.strip() + if not line or line.startswith("//"): + continue + if len(line) % 8: + sys.exit("{}: line of {} characters is not a multiple of 8".format(infile, len(line))) + data += bytearr(line) + + with open(outfile, "wb") as f: + f.write(data) + + print("[=] PACK {} ({} bytes)".format(outfile, len(data))) + + +if __name__ == "__main__": + if len(sys.argv) != 3: + sys.exit("usage: fs2bin.py ") + main(sys.argv[1], sys.argv[2]) diff --git a/fpga/common/gowin_devid.py b/fpga/common/gowin_devid.py new file mode 100644 index 000000000..b8ee2aee0 --- /dev/null +++ b/fpga/common/gowin_devid.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 + +# Stamp the real device IDCODE into a Gowin bitstream (.fs from apycula's +# gowin_pack), in place, and repair the CRC that depends on it. +# +# apycula's GW1N-4 database writes 0x0100381B, the plain GW1N-4, but the +# GW1N-4B/4D silicon on a PM5 reports 0x1100381B. The device compares that +# field with its own IDCODE and refuses an image that disagrees: the FPGA stays +# unconfigured (Gowin status register done_final = 0), so nothing drives the +# antenna and `hw tune` reads a couple of volts instead of tens. `hw fpga +# config` prints the value to use here as "gowin_jtag OK: idcode = ...". +# +# Only the IDCODE changes. The running CRC that apycula's write_bitstream() +# carries into the first row covers the header entries, so that one CRC is +# recomputed. Every other row is verified rather than rewritten, so a change to +# the apycula bitstream layout is reported instead of silently producing an +# image that will not configure. +# +# usage: gowin_devid.py + +import sys + +PREAMBLE = 3 # write_bitstream() starts folding header entries into the CRC after these +SKIP = 0xd2 # ... and leaves the SPI address entry out + + +def crc16_arc(data): + """CRC-16/ARC: poly 0x8005 reflected, init 0, xorout 0, as apycula computes it.""" + crc = 0 + for byte in data: + crc ^= byte + for _ in range(8): + crc = (crc >> 1) ^ 0xA001 if crc & 1 else crc >> 1 + return crc + + +def to_bytes(line): + """8 ASCII '0'/'1' characters per byte, most significant bit first""" + return bytearray(int(line[i:i + 8], 2) for i in range(0, len(line), 8)) + + +def to_line(data): + return "".join("{:08b}".format(b) for b in data) + + +def split(blocks): + """header, rows, footer: the rows are the repeated long lines in the middle""" + lengths = [len(b) for b in blocks] + row_len = max(set(lengths), key=lengths.count) + first = next(n for n, b in enumerate(blocks) if len(b) == row_len) + last = len(blocks) - 1 - next(n for n, b in enumerate(reversed(blocks)) if len(b) == row_len) + head, rows, foot = blocks[:first], blocks[first:last + 1], blocks[last + 1:] + if len(head) <= PREAMBLE or not rows or not foot: + sys.exit("unexpected .fs layout: {} header, {} row(s), {} footer entries".format( + len(head), len(rows), len(foot))) + for row in rows: + if row[-6:] != b"\xff" * 6: + sys.exit("unexpected .fs row: not terminated by {} CRC + 6 padding bytes".format(2)) + return head, rows, foot + + +def main(path, idcode): + blocks = [to_bytes(l) for l in open(path).read().splitlines() if l] + head, rows, foot = split(blocks) + + # the first entry write_bitstream() folds into the CRC, right after the preamble + chip = head[PREAMBLE] + old = int.from_bytes(chip[-4:], "big") + if old == idcode: + print("[=] DEVID {} already 0x{:08X}".format(path, idcode)) + return + chip[-4:] = idcode.to_bytes(4, "big") + + # what write_bitstream() has accumulated once it reaches the first row + seed = b"".join(bytes(entry) for entry in head[PREAMBLE:] if entry[0] != SKIP) + + for n, row in enumerate(rows): + data = bytes(row[:-8]) + want = crc16_arc(seed + data if n == 0 else b"\xff" * 6 + data) + if n == 0: + row[-8:-6] = want.to_bytes(2, "little") + elif row[-8:-6] != want.to_bytes(2, "little"): + sys.exit("row {} CRC mismatch: apycula changed the bitstream layout".format(n)) + + with open(path, "w") as f: + for block in head + rows + foot: + f.write(to_line(block) + "\n") + + print("[=] DEVID {} 0x{:08X} -> 0x{:08X}".format(path, old, idcode)) + + +if __name__ == "__main__": + if len(sys.argv) != 3: + sys.exit("usage: gowin_devid.py ") + main(sys.argv[1], int(sys.argv[2], 16)) diff --git a/fpga/common/gowin_sdc_clean.py b/fpga/common/gowin_sdc_clean.py new file mode 100644 index 000000000..43b70b072 --- /dev/null +++ b/fpga/common/gowin_sdc_clean.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 + +# Rewrite a Gowin IDE timing constraint file into the subset of SDC that +# nextpnr-himbaechel understands: create_clock and set_false_path, both taking +# [get_ports {...}]. The // comments, the create_clock -waveform arguments and +# the closing report_timing are dropped, and each set_clock_groups +# -asynchronous is expanded into pairwise false paths between the ports the +# clocks were declared on, since nextpnr has no notion of clock names. +# +# usage: gowin_sdc_clean.py + +import re +import sys + +WAVEFORM = re.compile(r"-waveform\s*\{[^}]*\}") +CLOCK = re.compile(r"create_clock\s+(?:.*?-name\s+(\S+))?.*?\[get_ports\s*\{([^}]*)\}\]") +CLOCK_GROUP = re.compile(r"\[get_clocks\s*\{([^}]*)\}\]") + + +def read_clocks(lines): + """"clock name -> port it is declared on" for the create_clock entries""" + ports = {} + for line in lines: + m = CLOCK.match(line.strip()) + if m and m.group(1): + ports[m.group(1)] = m.group(2) + return ports + + +def clean(line, clocks): + if line.startswith("//") or not line.strip(): + return [] + if re.match(r"\s*report_timing\b", line): + return [] + if re.match(r"\s*set_clock_groups\b", line): + if "-asynchronous" not in line: + return [line] + # every pair of groups is asynchronous, not just the neighbours + ports = [clocks.get(name, name) for name in CLOCK_GROUP.findall(line)] + return ["set_false_path -from [get_ports {%s}] -to [get_ports {%s}]" % (a, b) + for i, a in enumerate(ports) for b in ports[i + 1:]] + return [WAVEFORM.sub("", line).rstrip()] + + +def main(infile, outfile): + with open(infile) as f: + lines = f.read().splitlines() + clocks = read_clocks(lines) + rules = [out for line in lines for out in clean(line, clocks)] + with open(outfile, "w") as f: + f.write("\n".join(rules) + "\n") + + print("[=] SDC {} ({} rules, {} clocks)".format(outfile, len(rules), len(clocks))) + + +if __name__ == "__main__": + if len(sys.argv) != 3: + sys.exit("usage: gowin_sdc_clean.py ") + main(sys.argv[1], sys.argv[2]) diff --git a/fpga/hi_flite.v b/fpga/common/hi_flite.v similarity index 93% rename from fpga/hi_flite.v rename to fpga/common/hi_flite.v index e1a8f9ca9..f132ce1a4 100644 --- a/fpga/hi_flite.v +++ b/fpga/common/hi_flite.v @@ -200,7 +200,7 @@ reg zero = 1'b0; // Manchester first halfbit low second high corresponds to this reg [8:0] ssp_cnt = 9'd0; always @(posedge adc_clk) - ssp_cnt <= (ssp_cnt + 1); + ssp_cnt <= (ssp_cnt + 1'b1); always @(negedge adc_clk) if (ssp_cnt[5:0] == 6'd32) @@ -242,9 +242,26 @@ end //maybe change it so that ARM sends preamble as well. //then: ready bits sent to ARM, 8 bits sent from ARM (all ones), then preamble (all zeros, presumably) - which starts modulation +// SSP(FRAME_H) ~speed -> 9'd31 speed -> 8'd15 +// SSP(FRAME_L) ~speed -> 9'b1011111(d95 OF 512) speed -> 8'b101111(d47 OF 256) +// TIMODE(FRAME_H) ~speed -> 9'd(512-64) speed -> 8'd(256-32) +// TIMODE(FRAME_L) ~speed -> 9'b0 speed -> 8'b0 +`ifdef WITH_TIMODE + `define HI_FLITE_FRAME_SET_L 9'd448 + `define HI_FLITE_FRAME_SET_H 8'd224 + `define HI_FLITE_FRAME_CLR_L 9'd0 + `define HI_FLITE_FRAME_CLR_H 8'd0 +`else + `define HI_FLITE_FRAME_SET_L 9'd31 + `define HI_FLITE_FRAME_SET_H 8'd15 + `define HI_FLITE_FRAME_CLR_L 9'b1011111 // 95 = 96 - 1 + `define HI_FLITE_FRAME_CLR_H 8'b101111 // 47 = 48 - 1 +`endif + always @(negedge adc_clk) begin //count fc/64 - transfer bits to ARM at the rate they are received + //At speed 0, clk rises at 0 or 64; at speed 1, clk rises at 0 or 32. if( ((~speed) && (ssp_cnt[5:0] == 6'b000000) ) || (speed && (ssp_cnt[4:0] == 5'b00000)) ) begin ssp_clk <= 1'b1; @@ -270,15 +287,16 @@ begin ssp_din <= curbit; end end + // At speed 0, clk falls at 32; at speed 1, clk falls at 16. if( ( (~speed) && (ssp_cnt[5:0] == 6'b100000)) ||(speed && ssp_cnt[4:0] == 5'b10000)) ssp_clk <= 1'b0; //create frame pulses. TBH, I still don't know what they do exactly, but they are crucial for ARM->FPGA transfer. If the frame is in the beginning of the byte, transfer slows to a crawl for some reason // took me a day to figure THAT out. - if(( (~speed) && (ssp_cnt[8:0] == 9'd31)) || (speed && ssp_cnt[7:0] == 8'd15)) + if(( (~speed) && (ssp_cnt[8:0] == `HI_FLITE_FRAME_SET_L)) || (speed && ssp_cnt[7:0] == `HI_FLITE_FRAME_SET_H)) begin ssp_frame <= 1'b1; end - if(( (~speed) && (ssp_cnt[8:0] == 9'b1011111)) || (speed &&ssp_cnt[7:0] == 8'b101111) ) + if(( (~speed) && (ssp_cnt[8:0] == `HI_FLITE_FRAME_CLR_L)) || (speed && ssp_cnt[7:0] == `HI_FLITE_FRAME_CLR_H)) begin ssp_frame <= 1'b0; end @@ -315,7 +333,7 @@ begin // Watchdog clock, see `stalebit. It runs first so that the three places // that clear it below - a clean desync, a successful Manchester lock, and // the watchdog firing itself - all override it. - stale <= stale + 1; + stale <= stale + 1'b1; //envelope follow code... //////////// @@ -338,7 +356,7 @@ begin if (power) bit_counts <= 0; else - bit_counts <= bit_counts + 1; + bit_counts <= bit_counts + 1'b1; end else begin @@ -348,7 +366,7 @@ begin end else begin - fccount <= fccount + 1; + fccount <= fccount + 1'b1; end end @@ -453,7 +471,7 @@ begin acc <= 0; end else - tsinceedge <= (tsinceedge + 1); + tsinceedge <= (tsinceedge + 1'b1); end end @@ -541,7 +559,11 @@ always @(ck_1356meg or ssp_dout or power or disabl or mod) begin if (power) begin +`ifdef PM5 // pwr_hi is used to control the 1356 clk enable on PM5, not clk output. + pwr_hi <= 1'b1; // enable 1356 clk output +`else pwr_hi <= ck_1356meg; +`endif pwr_lo <= 1'b0; pwr_oe1 <= 1'b0;//mod; pwr_oe2 <= 1'b0;//mod; diff --git a/fpga/hi_get_trace.v b/fpga/common/hi_get_trace.v similarity index 88% rename from fpga/hi_get_trace.v rename to fpga/common/hi_get_trace.v index b577ff6be..52dcf4638 100644 --- a/fpga/hi_get_trace.v +++ b/fpga/common/hi_get_trace.v @@ -29,7 +29,7 @@ module hi_get_trace( reg [6:0] clock_cnt; always @(negedge ck_1356megb) begin - clock_cnt <= clock_cnt + 1; + clock_cnt <= clock_cnt + 1'b1; end // sample at 13,56MHz / 8. The highest signal frequency (subcarrier) is 848,5kHz, i.e. in this case we oversample by a factor of 2 @@ -39,7 +39,7 @@ begin if (sample_clock == 3'd7) sample_clock <= 3'd0; else - sample_clock <= sample_clock + 1; + sample_clock <= sample_clock + 1'b1; end @@ -62,7 +62,7 @@ begin if (addr == 12'd3071) addr <= 12'd0; else - addr <= addr + 1; + addr <= addr + 1'b1; end end else if (major_mode != `FPGA_MAJOR_MODE_OFF) @@ -89,7 +89,7 @@ begin end else begin - addr <= addr + 1; + addr <= addr + 1'b1; end end end @@ -156,10 +156,21 @@ begin ssp_clk <= ~clock_cnt[3]; // ssp_clk frequency = 13,56MHz / 16 = 847,5 kHz +`ifdef WITH_TIMODE + // Toggle once every 8 ssp_clk cycles + // TI mode 7D112: starts with the TI frame start signal; the line is driven high at the (128-16)th ssp_clk cycle. + if(clock_cnt[6:0] == 7'd112) + ssp_frame <= 1'b1; + + // Clear the frame signal at the new frame start (0th ssp_clk cycle) + if(clock_cnt[6:0] == 7'd0) + ssp_frame <= 1'b0; +`else if (clock_cnt[6:4] == 3'b000) // set ssp_frame for 0...31 ssp_frame <= 1'b1; else ssp_frame <= 1'b0; +`endif end diff --git a/fpga/hi_iso14443a.v b/fpga/common/hi_iso14443a.v similarity index 87% rename from fpga/hi_iso14443a.v rename to fpga/common/hi_iso14443a.v index bbc20bee7..1dafdb1bd 100644 --- a/fpga/hi_iso14443a.v +++ b/fpga/common/hi_iso14443a.v @@ -36,7 +36,12 @@ module hi_iso14443a( output debug ); +// The PM5's ADC is inverting (for HF). +`ifdef PM5 +assign adc_clk = ~ck_1356meg; +`else assign adc_clk = ck_1356meg; +`endif //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Reader -> PM3: @@ -47,8 +52,16 @@ reg [11:0] has_been_low_for; always @(negedge adc_clk) begin - if(adc_d >= 16) after_hysteresis <= 1'b1; // U >= 1,14V -> after_hysteresis = 1 - else if(adc_d < 8) after_hysteresis <= 1'b0; // U < 1,04V -> after_hysteresis = 0 + + // The PM5's ADC is inverting (for HF). Therefore, the trigger values are inverted as well. +`ifdef PM5 + if(adc_d <= 240) after_hysteresis <= 1'b1; // U >= 1,14V -> after_hysteresis = 1 + else if(adc_d > 248) after_hysteresis <= 1'b0; // U < 1,04V -> after_hysteresis = 0 +`else + if(adc_d >= 16) after_hysteresis <= 1'b1; // U >= 1,14V -> after_hysteresis = 1 + else if(adc_d < 8) after_hysteresis <= 1'b0; // U < 1,04V -> after_hysteresis = 0 +`endif + // Note: was >= 3,53V and <= 1,19V. The new trigger values allow more reliable detection of the first bit // (it might not reach 3,53V due to the high time constant of the high pass filter in the analogue RF part). // In addition, the new values are more in line with ISO14443-2: "The PICC shall detect the ”End of Pause” after the field exceeds @@ -57,7 +70,11 @@ begin // detecting a loss of reader's field (adc_d < 192 for 4096 clock cycles). If this is the case, // set the detected reader signal (after_hysteresis) to '1' (unmodulated) +`ifdef PM5 + if(adc_d <= 32) +`else if(adc_d >= 192) +`endif begin has_been_low_for <= 12'd0; end @@ -70,7 +87,7 @@ begin end else begin - has_been_low_for <= has_been_low_for + 1; + has_been_low_for <= has_been_low_for + 1'b1; end end @@ -86,7 +103,11 @@ reg [8:0] saw_deep_modulation; always @(negedge adc_clk) begin +`ifdef PM5 + if(& adc_d[7:0]) // if adc_d == 255 (ADC Value of PM5 is inverted) +`else if(~(| adc_d[7:0])) // if adc_d == 0 (U <= 0,94V) +`endif begin if(deep_counter == 3'd7) // adc_d == 0 for 8 adc_clk ticks -> deep_modulation (by reader) begin @@ -94,7 +115,7 @@ begin saw_deep_modulation <= 8'd0; end else - deep_counter <= deep_counter + 1; + deep_counter <= deep_counter + 1'b1; end else begin @@ -102,7 +123,7 @@ begin if(saw_deep_modulation == 8'd255) // adc_d != 0 for 256 adc_clk ticks -> deep_modulation is over, probably waiting for tag's response deep_modulation <= 1'b0; else - saw_deep_modulation <= saw_deep_modulation + 1; + saw_deep_modulation <= saw_deep_modulation + 1'b1; end end @@ -153,7 +174,7 @@ begin begin if (reader_falling_edge_time == 4'd1) // reader signal changes right after sampling. Better sample earlier next time. begin - negedge_cnt <= negedge_cnt + 2; // time warp + negedge_cnt <= negedge_cnt + 2'd2; // time warp end else if (reader_falling_edge_time == 4'd0) // reader signal changes right before sampling. Better sample later next time. begin @@ -161,7 +182,7 @@ begin end else begin - negedge_cnt <= negedge_cnt + 1; // Continue as usual + negedge_cnt <= negedge_cnt + 1'b1; // Continue as usual end reader_falling_edge_time[3:0] <= 4'd8; // adjust only once per detected edge end @@ -171,7 +192,7 @@ begin end else begin - negedge_cnt <= negedge_cnt + 1; + negedge_cnt <= negedge_cnt + 1'b1; end end @@ -221,7 +242,7 @@ begin if (mod_type == `FPGA_HF_ISO14443A_SNIFFER) begin // detect modulation signal: if modulating, there must have been a falling AND a rising edge - if ((rx_mod_falling_edge_max > edge_detect_threshold_high) && (rx_mod_rising_edge_max < -edge_detect_threshold_high)) + if ((rx_mod_falling_edge_max > $signed(edge_detect_threshold_high)) && (rx_mod_rising_edge_max < -$signed(edge_detect_threshold_high))) curbit <= 1'b1; // modulation else curbit <= 1'b0; // no modulation @@ -229,7 +250,7 @@ begin else begin // detect modulation signal: if modulating, there must have been a falling AND a rising edge - if ((rx_mod_falling_edge_max > edge_detect_threshold) && (rx_mod_rising_edge_max < -edge_detect_threshold)) + if ((rx_mod_falling_edge_max > $signed(edge_detect_threshold)) && (rx_mod_rising_edge_max < -$signed(edge_detect_threshold))) curbit <= 1'b1; // modulation else curbit <= 1'b0; // no modulation @@ -341,12 +362,12 @@ begin end else begin - sub_carrier_cnt <= sub_carrier_cnt + 1; + sub_carrier_cnt <= sub_carrier_cnt + 1'b1; end end else begin - fdt_counter <= fdt_counter + 1; + fdt_counter <= fdt_counter + 1'b1; end end @@ -407,7 +428,7 @@ begin if (mod_sig_ptr == 5'd31) mod_sig_ptr <= 5'd0; // buffer overflow - data loss. else - mod_sig_ptr <= mod_sig_ptr + 1; // increase buffer (= increase delay by 16 adc_clk ticks). mod_sig_ptr always points ahead of first 1. + mod_sig_ptr <= mod_sig_ptr + 1'b1; // increase buffer (= increase delay by 16 adc_clk ticks). mod_sig_ptr always points ahead of first 1. else if(fdt_elapsed && ~temp_buffer_reset) begin // wait for the next 1 after fdt_elapsed before fixing the delay and starting modulation. This ensures that the response can only happen @@ -417,7 +438,7 @@ begin if(mod_sig_ptr == 5'd1) mod_sig_ptr <= 5'd8; // still nothing received, need to go for the next interval else - mod_sig_ptr <= mod_sig_ptr - 1; // decrease buffer. + mod_sig_ptr <= mod_sig_ptr - 1'b1; // decrease buffer. end end end @@ -472,32 +493,47 @@ end // FPGA <-> ARM communication: // generate a ssp clock and ssp frame signal for the synchronous transfer from/to the ARM +`ifdef WITH_TIMODE +`define HI_ISO14443A_FRAME_SET_8B 6'd56 +`define HI_ISO14443A_FRAME_CLR_8B 6'd0 +`define HI_ISO14443A_FRAME_SET_16B 7'd112 +`define HI_ISO14443A_FRAME_CLR_16B 7'd0 +`else +`define HI_ISO14443A_FRAME_SET_8B 6'd0 +`define HI_ISO14443A_FRAME_CLR_8B 6'd8 +`define HI_ISO14443A_FRAME_SET_16B 7'd7 +`define HI_ISO14443A_FRAME_CLR_16B 7'd23 +`endif + always @(negedge adc_clk) begin if(mod_type == `FPGA_HF_ISO14443A_SNIFFER) // FPGA_HF_ISO14443A_SNIFFER mode (ssp_clk = adc_clk / 8, ssp_frame clock = adc_clk / 64)): begin - if(negedge_cnt[2:0] == 3'd0) + if(negedge_cnt[2:0] == 3'd0) // High level for 4 cycles ssp_clk <= 1'b1; - if(negedge_cnt[2:0] == 3'd4) + if(negedge_cnt[2:0] == 3'd4)// Low level for 4 cycles ssp_clk <= 1'b0; - if(negedge_cnt[5:0] == 6'd0) // ssp_frame rising edge indicates start of frame + //ssp模式6D0,TI模式6D56,TI帧开始信号开始:最后一个ssp_clk拉高(64-8)的时候就拉高 + // ssp_frame rising edge indicates start of frame + if(negedge_cnt[5:0] == `HI_ISO14443A_FRAME_SET_8B) ssp_frame <= 1'b1; - if(negedge_cnt[5:0] == 6'd8) + //ssp模式6D8,TI模式6D0,TI帧开始信号结束:在第一次ssp_clk拉高的时候就拉低(清除上一个周期拉高) + if(negedge_cnt[5:0] == `HI_ISO14443A_FRAME_CLR_8B) ssp_frame <= 1'b0; end else // all other modes (ssp_clk = adc_clk / 16, ssp_frame clock = adc_clk / 128): begin - if(negedge_cnt[3:0] == 4'd0) + if(negedge_cnt[3:0] == 4'd0) // High level for 8 cycles (rising edge at cycle 0 or 16) ssp_clk <= 1'b1; - if(negedge_cnt[3:0] == 4'd8) + if(negedge_cnt[3:0] == 4'd8) // Low level for 8 cycles (falling edge at cycle 8) ssp_clk <= 1'b0; - if(negedge_cnt[6:0] == 7'd7) // ssp_frame rising edge indicates start of frame, sampled on falling edge of ssp_clk + if(negedge_cnt[6:0] == `HI_ISO14443A_FRAME_SET_16B) // ssp_frame rising edge indicates start of frame, sampled on falling edge of ssp_clk ssp_frame <= 1'b1; - if(negedge_cnt[6:0] == 7'd23) + if(negedge_cnt[6:0] == `HI_ISO14443A_FRAME_CLR_16B) ssp_frame <= 1'b0; end end @@ -544,7 +580,12 @@ assign sub_carrier = ~sub_carrier_cnt[3]; // in FPGA_HF_ISO14443A_READER_MOD: drop carrier for mod_sig_coil == 1 (pause); // in FPGA_HF_ISO14443A_READER_LISTEN: carrier always on; in other modes: carrier always off + +`ifdef PM5 +assign pwr_hi = (((mod_type == `FPGA_HF_ISO14443A_READER_MOD) & ~mod_sig_coil) || (mod_type == `FPGA_HF_ISO14443A_READER_LISTEN)); +`else assign pwr_hi = (ck_1356meg & (((mod_type == `FPGA_HF_ISO14443A_READER_MOD) & ~mod_sig_coil) || (mod_type == `FPGA_HF_ISO14443A_READER_LISTEN))); +`endif // Enable HF antenna drivers: assign pwr_oe1 = 1'b0; diff --git a/fpga/hi_reader.v b/fpga/common/hi_reader.v similarity index 84% rename from fpga/hi_reader.v rename to fpga/common/hi_reader.v index 07afdc2de..8fabc2e35 100644 --- a/fpga/hi_reader.v +++ b/fpga/common/hi_reader.v @@ -42,15 +42,31 @@ assign adc_clk = ck_1356meg; // sample frequency is 13,56 MHz // using AM. Do this the same way that we do it for the simulated tag. reg after_hysteresis, after_hysteresis_prev, after_hysteresis_prev_prev; reg [11:0] has_been_low_for; + +// Reader-carrier detection thresholds, selected at runtime by the configured mode. +// The lower thresholds (240 / 63 instead of 255 / 0) allow the reader signal to still be recovered +// when the received level is weak. They are meant for ISO15693: the 2-subcarrier modes, plus the +// amplitude sniffer that "hf 15 sniff" uses -- including the plain SNIFF_AMPLITUDE that its jam +// sequence switches to and keeps for the rest of the command. +// This module is shared with other protocols (ISO14443B sniff reads the very same +// after_hysteresis bits) and must keep the rail-to-rail thresholds there, so the selection is done +// at runtime instead of with a compile-time switch. +wire low_signal_mode = (subcarrier_frequency == `FPGA_HF_READER_2SUBCARRIERS_424_484_KHZ) + || (minor_mode == `FPGA_HF_READER_MODE_SNIFF_AMPLITUDE); + always @(negedge adc_clk) begin -`ifdef WITH_HF_15_LOWSIGNAL - if (& adc_d[7:4]) after_hysteresis <= 1'b1; - else if (~(| adc_d[7:6])) after_hysteresis <= 1'b0; -`else - if (& adc_d[7:0]) after_hysteresis <= 1'b1; - else if (~(| adc_d[7:0])) after_hysteresis <= 1'b0; -`endif + // TODO DXL - 阈值是绝对值,这是否会在PM5上导致问题?需要考虑判定的adc值是否和场的信号同步,待测 + if (low_signal_mode) + begin + if (& adc_d[7:4]) after_hysteresis <= 1'b1; + else if (~(| adc_d[7:6])) after_hysteresis <= 1'b0; + end + else + begin + if (& adc_d[7:0]) after_hysteresis <= 1'b1; + else if (~(| adc_d[7:0])) after_hysteresis <= 1'b0; + end if (after_hysteresis) begin @@ -64,7 +80,7 @@ begin after_hysteresis <= 1'b1; end else - has_been_low_for <= has_been_low_for + 1; + has_been_low_for <= has_been_low_for + 1'b1; end end @@ -75,7 +91,7 @@ end // We need a 6-bit counter for the timing. reg [5:0] corr_i_cnt; always @(negedge adc_clk) - corr_i_cnt <= corr_i_cnt + 1; + corr_i_cnt <= corr_i_cnt + 1'b1; `ifdef WITH_HF_15 reg [1:0] fskout = 2'd0; @@ -147,8 +163,8 @@ begin begin if (match28 < match32) begin - diff28 = match32 - match28; - diff16 = match16 - match28; + diff28 = (match32 - match28) & 8'hFF; + diff16 = (match16 - match28) & 8'hFF; if (diff28*2 > diff16) fskout = 2'b01; else if (!last0) @@ -158,8 +174,8 @@ begin end else //if (match32 <= match28) begin - diff32 = match28 - match32; - diff16 = match16 - match32; + diff32 = (match28 - match32) & 8'hFF; + diff16 = (match16 - match32) & 8'hFF; if (diff32*2 > diff16) fskout = 2'b10; else if (!last0) @@ -368,7 +384,15 @@ begin end -// ssp clock and frame signal for communication to and from ARM +`ifdef WITH_TIMODE // In TI mode, the frame signal goes high during the last `ssp_clk` pulse (at the 60th clock cycle, i.e., 64-4). + `define HI_READER_FRAME_SET 6'd60 + `define HI_READER_FRAME_CLR 6'd0 +`else + `define HI_READER_FRAME_SET 6'd1 + `define HI_READER_FRAME_CLR 6'd3 +`endif + +// ssp clock and frame signal for communication to and from ARM, not SPI TI-MODE // _____ _____ _____ _ // ssp_clk | |_____| |_____| |_____| // _____ @@ -380,18 +404,18 @@ end // always @(negedge adc_clk) begin - if (corr_i_cnt[1:0] == 2'b00) + if (corr_i_cnt[1:0] == 2'b00) // High level for 2 cycles (rising edge at cycle 0 or 4) ssp_clk <= 1'b1; - if (corr_i_cnt[1:0] == 2'b10) + if (corr_i_cnt[1:0] == 2'b10) // Low level for 2 cycles (falling edge at the second cycle) ssp_clk <= 1'b0; // set ssp_frame signal for corr_i_cnt = 1..3 // (send one frame with 16 Bits) - if (corr_i_cnt == 6'd1) + if (corr_i_cnt == `HI_READER_FRAME_SET) ssp_frame <= 1'b1; - if (corr_i_cnt == 6'd3) + if (corr_i_cnt == `HI_READER_FRAME_CLR) ssp_frame <= 1'b0; end @@ -405,11 +429,15 @@ always @(negedge adc_clk) begin if (corr_i_cnt == 6'd0) begin - jam_counter <= jam_counter + 1; + jam_counter <= jam_counter + 1'b1; jam_signal <= jam_counter[1] ^ jam_counter[3]; end end +// --- +// pwr_hi is used to control the 1356 clk enable on PM5, not clk output. +// --- + always @(*) begin pwr_oe1 = 1'b0; @@ -417,22 +445,38 @@ begin if (minor_mode == `FPGA_HF_READER_MODE_SEND_SHALLOW_MOD) begin +`ifdef PM5 + pwr_hi = 1'b1; +`else pwr_hi = ck_1356meg; +`endif pwr_oe4 = ssp_dout; end else if (minor_mode == `FPGA_HF_READER_MODE_SEND_SHALLOW_MOD_RDV4) begin +`ifdef PM5 + pwr_hi = 1'b1; +`else pwr_hi = ck_1356meg; +`endif pwr_oe1 = ssp_dout; end else if (minor_mode == `FPGA_HF_READER_MODE_SEND_FULL_MOD) begin +`ifdef PM5 + pwr_hi = ~ssp_dout; +`else pwr_hi = ck_1356meg & ~ssp_dout; +`endif pwr_oe4 = 1'b0; end else if (minor_mode == `FPGA_HF_READER_MODE_SEND_JAM) begin +`ifdef PM5 + pwr_hi = jam_signal; +`else pwr_hi = ck_1356meg & jam_signal; +`endif pwr_oe4 = 1'b0; end else if (minor_mode == `FPGA_HF_READER_MODE_SNIFF_IQ @@ -444,7 +488,11 @@ begin end else // receiving from tag begin +`ifdef PM5 + pwr_hi = 1'b1; +`else pwr_hi = ck_1356meg; +`endif pwr_oe4 = 1'b0; end end diff --git a/fpga/hi_simulate.v b/fpga/common/hi_simulate.v similarity index 83% rename from fpga/hi_simulate.v rename to fpga/common/hi_simulate.v index 77b9a44ed..720074866 100644 --- a/fpga/hi_simulate.v +++ b/fpga/common/hi_simulate.v @@ -83,7 +83,7 @@ begin end else begin - has_been_low_for <= has_been_low_for + 1; + has_been_low_for <= has_been_low_for + 1'b1; end end end @@ -93,7 +93,7 @@ end reg [8:0] ssp_clk_divider; always @(negedge adc_clk) - ssp_clk_divider <= (ssp_clk_divider + 1); + ssp_clk_divider <= (ssp_clk_divider + 1'b1); always @(negedge adc_clk) begin @@ -108,22 +108,33 @@ begin ssp_clk <= ~ssp_clk_divider[4]; end +// Since the 212k clock is generated by ssp_clk_divider[5], a full cycle here involves 16 bits—effectively 8 clock periods. +// This means an 8-bit transfer; in SSP mode, the frame signal is driven high at bit 1 (clock rising edge) and low at bit 5 (clock falling edge). +// To switch to TI mode, this must be changed to the rising edge of the final cycle: driving high at bit 14 (rising edge) and low at bit 0 (falling edge). +`ifdef WITH_TIMODE +`define HI_SIMULATE_FRAME_SET_212K 4'd14 +`define HI_SIMULATE_FRAME_CLR_212K 4'd0 +`else +`define HI_SIMULATE_FRAME_SET_212K 4'd1 +`define HI_SIMULATE_FRAME_CLR_212K 4'd5 +`endif + // Produce the byte framing signal; the phase of this signal // is arbitrary, because it's just a bit stream in this module. always @(negedge adc_clk) begin if (mod_type == `FPGA_HF_SIMULATOR_MODULATE_212K) begin - if (ssp_clk_divider[8:5] == 4'd1) + if (ssp_clk_divider[8:5] == `HI_SIMULATE_FRAME_SET_212K) ssp_frame <= 1'b1; - if (ssp_clk_divider[8:5] == 4'd5) + if (ssp_clk_divider[8:5] == `HI_SIMULATE_FRAME_CLR_212K) ssp_frame <= 1'b0; end else begin - if (ssp_clk_divider[7:4] == 4'd1) + if (ssp_clk_divider[7:4] == `HI_SIMULATE_FRAME_SET_212K) ssp_frame <= 1'b1; - if (ssp_clk_divider[7:4] == 4'd5) + if (ssp_clk_divider[7:4] == `HI_SIMULATE_FRAME_CLR_212K) ssp_frame <= 1'b0; end end diff --git a/fpga/hi_sniffer.v b/fpga/common/hi_sniffer.v similarity index 75% rename from fpga/hi_sniffer.v rename to fpga/common/hi_sniffer.v index 8cfb0fe9a..3ca0a8691 100644 --- a/fpga/hi_sniffer.v +++ b/fpga/common/hi_sniffer.v @@ -48,18 +48,36 @@ assign ssp_din = adc_d_out[0]; always @(posedge ssp_clk) begin - ssp_cnt <= ssp_cnt + 1; + ssp_cnt <= ssp_cnt + 1'b1; + +`ifdef WITH_TIMODE + if(ssp_cnt[2:0] == 3'b111) // set frame pin to high for TI mode on the last bit of the frame + begin + ssp_frame <= 1'b1; + end +`endif if(ssp_cnt[2:0] == 3'b000) // set frame length begin adc_d_out[7:0] <= adc_d; - ssp_frame <= 1'b1; + +`ifdef WITH_TIMODE + ssp_frame <= 1'b0; // In TI mode, pull the frame signal low here—at the rising edge of the first bit (marking the end of the last bit). +`else + ssp_frame <= 1'b1; // In SSP mode, pull the frame signal high here. +`endif + end + else begin // shift value right one bit adc_d_out[7:0] <= {1'b0, adc_d_out[7:1]}; - ssp_frame <= 1'b0; + +`ifndef WITH_TIMODE + ssp_frame <= 1'b0; // In SSP mode, pull the frame signal low here. +`endif + end end diff --git a/fpga/lf_edge_detect.v b/fpga/common/lf_edge_detect.v similarity index 100% rename from fpga/lf_edge_detect.v rename to fpga/common/lf_edge_detect.v diff --git a/fpga/lo_adc.v b/fpga/common/lo_adc.v similarity index 54% rename from fpga/lo_adc.v rename to fpga/common/lo_adc.v index f20442d4b..cf2865ba5 100644 --- a/fpga/lo_adc.v +++ b/fpga/common/lo_adc.v @@ -30,7 +30,7 @@ module lo_adc( input ssp_dout, output ssp_din, - output ssp_frame, + output reg ssp_frame, output ssp_clk, output adc_clk, output pwr_lo, @@ -66,7 +66,14 @@ assign pwr_oe4 = tag_modulation & lf_weak_load; // 10k Ohms assign debug = adc_clk; // ADC clock out of phase with antenna driver +`ifdef PM5 +// Since the PM5's ADC sampling occurs on the rising edge, +// whereas the falling edge of the field signal causes a rapid voltage rise—making it unsuitable for sampling +// the phase was adjusted to align them. +assign adc_clk = clk_state; +`else assign adc_clk = ~clk_state; +`endif // serialized SSP data is gated by clk_state to suppress unwanted signal assign ssp_din = to_arm_shiftreg[7] && !clk_state; @@ -74,20 +81,40 @@ assign ssp_din = to_arm_shiftreg[7] && !clk_state; // SSP clock always runs at 24MHz assign ssp_clk = pck0; -// SSP frame is gated by clk_state and goes high when pck_divider=8..15 -assign ssp_frame = (pck_divider[7:3] == 5'd1) && !clk_state; +// ssp_frame window: TI = 1-cycle pulse (at divider 7), SSP = spans the entire data window (dividers 8–15). +// Note: The 'always' block below reads the value of pck_divider *before* it toggles for the current cycle, +// so SET is triggered at the window start minus 1, and CLR is triggered at the window end. +`ifdef WITH_TIMODE + `define LO_ADC_FRAME_SET 8'd6 + `define LO_ADC_FRAME_CLR 8'd7 +`else + `define LO_ADC_FRAME_SET 8'd7 + `define LO_ADC_FRAME_CLR 8'd15 +`endif + +// Frame signal generation. +always @(posedge pck0) +begin + if ((pck_divider == `LO_ADC_FRAME_SET) && !clk_state) + ssp_frame <= 1'b1; + if ((pck_divider == `LO_ADC_FRAME_CLR) && !clk_state) + ssp_frame <= 1'b0; +end // divide 24mhz down to 3mhz -always @(posedge pck0) +always @(posedge pck0) // SSPCLK rising edge begin if (pck_divider == divisor[7:0]) begin + // Resets to zero upon reaching the frequency division factor; effectively, the value 95 corresponds to 125 kHz, meaning it executes 96 times (counting from 0 to 95) and resets on the 96th iteration. + // After resetting, the cycle count becomes 0 and does not increment. pck_divider <= 8'd0; + // Toggle clk upon reaching the frequency division factor; the value 95 (corresponding to 125 kHz) actually implies operation at a frequency of 250 kHz. clk_state = !clk_state; end else begin - pck_divider <= pck_divider + 1; + pck_divider <= pck_divider + 1'd1; // Increments by 1 on each rising edge of sspclk. end end @@ -95,6 +122,15 @@ end // the ADC output which is then clocked into the ARM SSP. always @(posedge pck0) begin + + // For PM5: Since adc_clk = ~clk_state, the ADC receives a rising edge when clk_state is 0. + // Note: Because the PM5 ADC samples on the rising edge, this causes hardware sampling to occur the moment the field is turned off (when voltage rises rapidly); therefore, a modification was made here. + // The adc_clk is now set to be in-phase with clk_state (since pwrlo is based on clk_state, this aligns the phases). + // Consequently, when clk_state is 0, the ADC receives a falling edge; sampling the output of the 9280 on the falling edge is safe, so this approach was adopted. + // ADC sampling completes when pck_divider == 8'd7; one cycle later, the 'else' condition takes effect. + // Shift transmission begins at 8'd8, but since the data payload is only 8 bits, zeros are transmitted continuously after the actual data is sent—a point easily misunderstood. + // In reality, the active sequence spans pck_divider values from 0 to 7 (sampling), to 8 (transmission start), and finally to 16 (transmission end). + if ((pck_divider == 8'd7) && !clk_state) to_arm_shiftreg <= adc_d; else diff --git a/fpga/lo_edge_detect.v b/fpga/common/lo_edge_detect.v similarity index 88% rename from fpga/lo_edge_detect.v rename to fpga/common/lo_edge_detect.v index e06cbda02..828bffb7e 100644 --- a/fpga/lo_edge_detect.v +++ b/fpga/common/lo_edge_detect.v @@ -131,6 +131,13 @@ wire tracker_freeze = lf_ed_hold_tracker & (hold_cnt != 0); // filter the ADC values wire data_rdy; wire [7:0] adc_filtered; + +// Regarding PM5, here is why the ADC sampling points remain in-phase (unlike other cases where sampling occurs at the same frequency as the signal): +// 1. The ADC operates at 125 kHz (derived from a 24 MHz oversampling clock); sampling points are distributed throughout the entire cycle. High dV/dt events near the signal edges will inevitably be captured regardless of phase inversion, +// and are subsequently suppressed by the 20 kHz low-pass filter, making phase alignment irrelevant; +// 2. Phase inversion (adc_clk = ~pck0) causes the ADC to output data on the pck0 falling edge while downstream components (adc_filter/lf_edge_detect) read it on the pck0 rising edge. +// This leaves a margin of only half a clock cycle (20.8 ns); given the ADC's maximum tOD of approximately 25 ns, the timing margin for reading is insufficient, creating a risk of capturing unstable or metastable data. + assign adc_clk = pck0; lp20khz_1MSa_iir_filter adc_filter( diff --git a/fpga/lo_passthru.v b/fpga/common/lo_passthru.v similarity index 100% rename from fpga/lo_passthru.v rename to fpga/common/lo_passthru.v diff --git a/fpga/lo_read.v b/fpga/common/lo_read.v similarity index 76% rename from fpga/lo_read.v rename to fpga/common/lo_read.v index 87279e8ec..96dbb8a27 100644 --- a/fpga/lo_read.v +++ b/fpga/common/lo_read.v @@ -29,7 +29,7 @@ module lo_read( input lf_field, output ssp_din, - output ssp_frame, + output reg ssp_frame, output ssp_clk, output adc_clk, output pwr_lo, @@ -74,8 +74,27 @@ end assign ssp_din = to_arm_shiftreg[7] && !pck_divclk; // SSP clock always runs at 24MHz assign ssp_clk = pck0; -// SSP frame is gated by pck_divclk and goes high when pck_cnt=8..15 -assign ssp_frame = (pck_cnt[7:3] == 5'd1) && !pck_divclk; + +// ssp_frame window: TI = 1-cycle pulse (at counter 7), SSP = spans the entire data window (counts 8-15). +// Note: The 'always' block below reads the value of pck_cnt *before* it toggles for the current cycle, +// so SET is triggered at the window start minus 1, and CLR is triggered at the window end. +`ifdef WITH_TIMODE + `define LO_READ_FRAME_SET 8'd6 + `define LO_READ_FRAME_CLR 8'd7 +`else + `define LO_READ_FRAME_SET 8'd7 + `define LO_READ_FRAME_CLR 8'd15 +`endif + +// Frame signal generation. +always @(posedge pck0) +begin + if ((pck_cnt == `LO_READ_FRAME_SET) && !pck_divclk) + ssp_frame <= 1'b1; + if ((pck_cnt == `LO_READ_FRAME_CLR) && !pck_divclk) + ssp_frame <= 1'b0; +end + // unused signals tied low assign pwr_hi = 1'b0; // always on outputs, unused @@ -85,8 +104,17 @@ assign pwr_oe3 = 1'b0; assign pwr_oe4 = 1'b0; // this is the antenna driver signal assign pwr_lo = lf_field & pck_divclk; + // ADC clock out of phase with antenna driver +`ifdef PM5 +// Since the PM5's ADC sampling occurs on the rising edge, +// whereas the falling edge of the field signal causes a rapid voltage rise, making it unsuitable for sampling, +// the phase was adjusted to align them. +assign adc_clk = pck_divclk; +`else assign adc_clk = ~pck_divclk; +`endif + // ADC clock also routed to debug pin assign debug = adc_clk; endmodule diff --git a/fpga/lo_simulate.v b/fpga/common/lo_simulate.v similarity index 100% rename from fpga/lo_simulate.v rename to fpga/common/lo_simulate.v diff --git a/fpga/lp20khz_1MSa_iir_filter.v b/fpga/common/lp20khz_1MSa_iir_filter.v similarity index 98% rename from fpga/lp20khz_1MSa_iir_filter.v rename to fpga/common/lp20khz_1MSa_iir_filter.v index d4a16cde1..ba5a02d33 100644 --- a/fpga/lp20khz_1MSa_iir_filter.v +++ b/fpga/common/lp20khz_1MSa_iir_filter.v @@ -72,7 +72,7 @@ module lp20khz_1MSa_iir_filter( // We could use 9bit x registers for that, but that would be // a waste, let's just add the constant during the computation // (x0+109) + 2*(x1+109) + (x2+109) = x0 + 2*x1 + x2 + 436 - x0 + {x1, 1'b0} + adc_d + 436 + x0 + {x1, 1'b0} + adc_d + 14'd436 // we want "- y0 * 0xd6 / 0x100" using only shift and add // 0xd6 == 0b11010110 // so *0xd6/0x100 is equivalent to diff --git a/fpga/min_max_tracker.v b/fpga/common/min_max_tracker.v similarity index 100% rename from fpga/min_max_tracker.v rename to fpga/common/min_max_tracker.v diff --git a/fpga/mux16.v b/fpga/common/mux16.v similarity index 100% rename from fpga/mux16.v rename to fpga/common/mux16.v diff --git a/fpga/mux2_onein.v b/fpga/common/mux2_onein.v similarity index 100% rename from fpga/mux2_onein.v rename to fpga/common/mux2_onein.v diff --git a/fpga/mux2_oneout.v b/fpga/common/mux2_oneout.v similarity index 100% rename from fpga/mux2_oneout.v rename to fpga/common/mux2_oneout.v diff --git a/fpga/mux8.v b/fpga/common/mux8.v similarity index 100% rename from fpga/mux8.v rename to fpga/common/mux8.v diff --git a/fpga/strip_date_time_from_binary.py b/fpga/common/strip_date_time_from_binary.py similarity index 100% rename from fpga/strip_date_time_from_binary.py rename to fpga/common/strip_date_time_from_binary.py diff --git a/fpga/common_src.mk b/fpga/common_src.mk new file mode 100644 index 000000000..a6e36c5fb --- /dev/null +++ b/fpga/common_src.mk @@ -0,0 +1,64 @@ +# +# Shared definitions for the FPGA build files. +# +# Source layout: +# common/ HDL shared by every platform +# pm3/ Xilinx PM3 / PM3-ULT top level and pin constraints +# icopyx/ Xilinx iCopy-X top level and pin constraints +# pm5/ Gowin PM5 top level, PLL, yosys script and pin constraints +# +# Included by proxmark3_fpga.mk and proxmark5_fpga.mk. + +COMMON_DIR = common +PM3_DIR = pm3 +ICOPYX_DIR = icopyx +PM5_DIR = pm5 + +# Prefix of the per target build directories, gitignored as fpga/__build* +PREFIX = __ + +# Copy update (only when destination is older or missing) +CP = cp -u + +# Make directory, no error if already existing +MKDIR = mkdir -p + +# Remove recursive, force +RMDIR = rm -rf + +# Path to make +MAKE = make + +# Echo (Q=) or not echo (Q=@) build commands to the terminal +Q = + +# HDL shared by every target, in synthesis order +COMMON_HDL = $(COMMON_DIR)/define.v +COMMON_HDL += $(COMMON_DIR)/mux8.v +COMMON_HDL += $(COMMON_DIR)/clk_divider.v +COMMON_HDL += $(COMMON_DIR)/lp20khz_1MSa_iir_filter.v +COMMON_HDL += $(COMMON_DIR)/min_max_tracker.v +COMMON_HDL += $(COMMON_DIR)/hi_flite.v +COMMON_HDL += $(COMMON_DIR)/hi_get_trace.v +COMMON_HDL += $(COMMON_DIR)/hi_iso14443a.v +COMMON_HDL += $(COMMON_DIR)/hi_reader.v +COMMON_HDL += $(COMMON_DIR)/hi_simulate.v +COMMON_HDL += $(COMMON_DIR)/hi_sniffer.v +COMMON_HDL += $(COMMON_DIR)/lf_edge_detect.v +COMMON_HDL += $(COMMON_DIR)/lo_adc.v +COMMON_HDL += $(COMMON_DIR)/lo_edge_detect.v +COMMON_HDL += $(COMMON_DIR)/lo_passthru.v +COMMON_HDL += $(COMMON_DIR)/lo_read.v + +# HDL of the PM5 (Gowin) bitstream, in synthesis order. One image covers both +# halves; the board selects LF or HF with the module_sel pin. +PM5_HDL = $(COMMON_HDL) +PM5_HDL += $(PM5_DIR)/gowin_rpll.v +PM5_HDL += $(PM5_DIR)/fpga_pm5_hf.v +PM5_HDL += $(PM5_DIR)/fpga_pm5_lf.v +PM5_HDL += $(PM5_DIR)/fpga_pm5_top.v + +# Strips the build date/time out of a generated Xilinx bitstream, so that +# rebuilding without a source change produces a byte identical file. +# Xilinx specific: not applicable to the Gowin bitstream. +STRIP_DATE_TIME = $(COMMON_DIR)/strip_date_time_from_binary.py diff --git a/fpga/fpga_icopyx_hf.v b/fpga/icopyx/fpga_icopyx_hf.v similarity index 100% rename from fpga/fpga_icopyx_hf.v rename to fpga/icopyx/fpga_icopyx_hf.v diff --git a/fpga/fpga_icopyx_lf.v b/fpga/icopyx/fpga_icopyx_lf.v similarity index 100% rename from fpga/fpga_icopyx_lf.v rename to fpga/icopyx/fpga_icopyx_lf.v diff --git a/fpga/fpga_icopyx_top.v b/fpga/icopyx/fpga_icopyx_top.v similarity index 100% rename from fpga/fpga_icopyx_top.v rename to fpga/icopyx/fpga_icopyx_top.v diff --git a/fpga/xc3s100e-4-vq100.ucf b/fpga/icopyx/xc3s100e-4-vq100.ucf similarity index 100% rename from fpga/xc3s100e-4-vq100.ucf rename to fpga/icopyx/xc3s100e-4-vq100.ucf diff --git a/fpga/fpga_pm3_top.v b/fpga/pm3/fpga_pm3_top.v similarity index 100% rename from fpga/fpga_pm3_top.v rename to fpga/pm3/fpga_pm3_top.v diff --git a/fpga/xc2s30-5-vq100.ucf b/fpga/pm3/xc2s30-5-vq100.ucf similarity index 100% rename from fpga/xc2s30-5-vq100.ucf rename to fpga/pm3/xc2s30-5-vq100.ucf diff --git a/fpga/xc2s50-5-tq144.ucf b/fpga/pm3/xc2s50-5-tq144.ucf similarity index 97% rename from fpga/xc2s50-5-tq144.ucf rename to fpga/pm3/xc2s50-5-tq144.ucf index 0964e1acf..f7e847c0e 100644 --- a/fpga/xc2s50-5-tq144.ucf +++ b/fpga/pm3/xc2s50-5-tq144.ucf @@ -1,45 +1,45 @@ -# See the schematic for the pin assignment. - -NET "adc_d<0>" LOC = "P54" ; -NET "adc_d<1>" LOC = "P57" ; -NET "adc_d<2>" LOC = "P59" ; -NET "adc_d<3>" LOC = "P60" ; -NET "adc_d<4>" LOC = "P62" ; -NET "adc_d<5>" LOC = "P63" ; -NET "adc_d<6>" LOC = "P65" ; -NET "adc_d<7>" LOC = "P67" ; -#NET "cross_hi" LOC = "P88" ; -#NET "miso" LOC = "P40" ; -NET "adc_clk" LOC = "P75" ; -NET "adc_noe" LOC = "P74" ; -NET "ck_1356meg" LOC = "P15" ; -NET "ck_1356megb" LOC = "P12" ; -NET "cross_lo" LOC = "P19" ; -NET "dbg" LOC = "P112" ; -NET "mosi" LOC = "P80" ; -NET "ncs" LOC = "P79" ; -NET "pck0" LOC = "P91" ; -NET "pwr_hi" LOC = "P31" ; -NET "pwr_lo" LOC = "P30" ; -NET "pwr_oe1" LOC = "P28" ; -NET "pwr_oe2" LOC = "P27" ; -NET "pwr_oe3" LOC = "P26" ; -NET "pwr_oe4" LOC = "P21" ; -NET "spck" LOC = "P88" ; -NET "ssp_clk" LOC = "P43" ; -NET "ssp_din" LOC = "P99" ; -NET "ssp_dout" LOC = "P94" ; -NET "ssp_frame" LOC = "P100" ; - -# definition of Clock nets: -NET "ck_1356meg" TNM_NET = "clk_net_1356" ; -NET "ck_1356megb" TNM_NET = "clk_net_1356b"; -NET "pck0" TNM_NET = "clk_net_pck0" ; -NET "spck" TNM_NET = "clk_net_spck" ; - -# Timing specs of clock nets: -TIMEGRP "clk_net_1356_all" = "clk_net_1356" "clk_net_1356b" ; -TIMESPEC "TS_1356MHz" = PERIOD "clk_net_1356_all" 74 ns HIGH 37 ns ; -TIMESPEC "TS_24MHz" = PERIOD "clk_net_pck0" 42 ns HIGH 21 ns ; -TIMESPEC "TS_4MHz" = PERIOD "clk_net_spck" 250 ns HIGH 125 ns ; - +# See the schematic for the pin assignment. + +NET "adc_d<0>" LOC = "P54" ; +NET "adc_d<1>" LOC = "P57" ; +NET "adc_d<2>" LOC = "P59" ; +NET "adc_d<3>" LOC = "P60" ; +NET "adc_d<4>" LOC = "P62" ; +NET "adc_d<5>" LOC = "P63" ; +NET "adc_d<6>" LOC = "P65" ; +NET "adc_d<7>" LOC = "P67" ; +#NET "cross_hi" LOC = "P88" ; +#NET "miso" LOC = "P40" ; +NET "adc_clk" LOC = "P75" ; +NET "adc_noe" LOC = "P74" ; +NET "ck_1356meg" LOC = "P15" ; +NET "ck_1356megb" LOC = "P12" ; +NET "cross_lo" LOC = "P19" ; +NET "dbg" LOC = "P112" ; +NET "mosi" LOC = "P80" ; +NET "ncs" LOC = "P79" ; +NET "pck0" LOC = "P91" ; +NET "pwr_hi" LOC = "P31" ; +NET "pwr_lo" LOC = "P30" ; +NET "pwr_oe1" LOC = "P28" ; +NET "pwr_oe2" LOC = "P27" ; +NET "pwr_oe3" LOC = "P26" ; +NET "pwr_oe4" LOC = "P21" ; +NET "spck" LOC = "P88" ; +NET "ssp_clk" LOC = "P43" ; +NET "ssp_din" LOC = "P99" ; +NET "ssp_dout" LOC = "P94" ; +NET "ssp_frame" LOC = "P100" ; + +# definition of Clock nets: +NET "ck_1356meg" TNM_NET = "clk_net_1356" ; +NET "ck_1356megb" TNM_NET = "clk_net_1356b"; +NET "pck0" TNM_NET = "clk_net_pck0" ; +NET "spck" TNM_NET = "clk_net_spck" ; + +# Timing specs of clock nets: +TIMEGRP "clk_net_1356_all" = "clk_net_1356" "clk_net_1356b" ; +TIMESPEC "TS_1356MHz" = PERIOD "clk_net_1356_all" 74 ns HIGH 37 ns ; +TIMESPEC "TS_24MHz" = PERIOD "clk_net_pck0" 42 ns HIGH 21 ns ; +TIMESPEC "TS_4MHz" = PERIOD "clk_net_spck" 250 ns HIGH 125 ns ; + diff --git a/fpga/pm5/fpga_pm5_hf.v b/fpga/pm5/fpga_pm5_hf.v new file mode 100644 index 000000000..b6b37670a --- /dev/null +++ b/fpga/pm5/fpga_pm5_hf.v @@ -0,0 +1,382 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// +// The FPGA is responsible for interfacing between the A/D, the coil drivers, +// and the ARM. In the low-frequency modes it passes the data straight +// through, so that the ARM gets raw A/D samples over the SSP. In the high- +// frequency modes, the FPGA might perform some demodulation first, to +// reduce the amount of data that we must send to the ARM. +//----------------------------------------------------------------------------- + + +module fpga_hf( + input ck_1356meg, + input spck, + //input pck0, + input ncs, + input [7:0] adc_d, + //input cross_hi, + //input cross_lo, + input mosi, + input ssp_dout, + input ce, // 复位输入,常态高 + + output ssp_din, + output ssp_frame, + output ssp_clk, + output adc_clk, + //output adc_noe, + output miso, + output pwr_lo, + output pwr_hi, + output pwr_oe1, + output pwr_oe2, + //output pwr_oe3, + output pwr_oe4, + output dbg, + output reg [11:0] pwm_duty = 12'h800 +); + + +// In all modes, let the ADC's outputs be enabled. +//assign adc_noe = 1'b0; +assign miso = 1'bZ; +wire cross_hi = 1'b0; + +wire [2:0] major_mode; +assign major_mode = ce ? conf_word[8:6] : 3'b111; + +//----------------------------------------------------------------------------- +// The SPI receiver. This sets up the configuration word, which the rest of +// the logic looks at to determine how to connect the A/D and the coil +// drivers (i.e., which section gets it). Also assign some symbolic names +// to the configuration bits, for use below. +//----------------------------------------------------------------------------- + +// Receive 16bits of data from ARM here. +reg [15:0] shift_reg; + +//always @(posedge spck) if (~ncs) shift_reg <= {shift_reg[14:0], mosi}; +always @(posedge spck) begin + if(~ncs & ce) + shift_reg <= {shift_reg[14:0], mosi}; +end + +reg trace_enable; + +reg [5:0] hf_edge_detect_threshold = 6'd7; +reg [5:0] hf_edge_detect_threshold_high = 6'd20; + +reg [8:0] conf_word; + +initial +begin + hf_edge_detect_threshold <= 7; + hf_edge_detect_threshold_high <= 20; +end + +// We switch modes between transmitting to the 13.56 MHz tag and receiving +// from it, which means that we must make sure that we can do so without +// glitching, or else we will glitch the transmitted carrier. +always @(posedge ncs) +begin + if(ce) begin + // 4 bit command + case (shift_reg[15:12]) + `FPGA_CMD_SET_CONFREG: conf_word <= shift_reg[8:0]; + `FPGA_CMD_TRACE_ENABLE: trace_enable <= shift_reg[0]; + `FPGA_CMD_SET_EDGE_DETECT_THRESHOLD: + begin + hf_edge_detect_threshold <= shift_reg[5:0]; + hf_edge_detect_threshold_high <= shift_reg[11:6]; + end + `FPGA_CMD_SET_PWR_PWM_LOW_COUNT:pwm_duty <= shift_reg[11:0]; + endcase + end +end +//----------------------------------------------------------------------------- +// And then we instantiate the modules corresponding to each of the FPGA's +// major modes, and use muxes to connect the outputs of the active mode to +// the output pins. +//----------------------------------------------------------------------------- + +// HF reader +hi_reader hr( + .ck_1356meg (ck_1356meg), + .adc_d (adc_d), + .subcarrier_frequency (conf_word[5:4]), + .minor_mode (conf_word[3:0]), + .ssp_dout (ssp_dout), + + .ssp_din (mux0_ssp_din), + .ssp_frame (mux0_ssp_frame), + .ssp_clk (mux0_ssp_clk), + .adc_clk (mux0_adc_clk), + .pwr_lo (mux0_pwr_lo), + .pwr_hi (mux0_pwr_hi), + .pwr_oe1 (mux0_pwr_oe1), + .pwr_oe2 (mux0_pwr_oe2), + .pwr_oe3 (mux0_pwr_oe3), + .pwr_oe4 (mux0_pwr_oe4), + .debug (mux0_debug) +); + +// HF simulated tag +hi_simulate hs( + .ck_1356meg (ck_1356meg), + .adc_d (adc_d), + .mod_type (conf_word[3:0]), + .ssp_dout (ssp_dout), + + .ssp_din (mux1_ssp_din), + .ssp_frame (mux1_ssp_frame), + .ssp_clk (mux1_ssp_clk), + .adc_clk (mux1_adc_clk), + .pwr_lo (mux1_pwr_lo), + .pwr_hi (mux1_pwr_hi), + .pwr_oe1 (mux1_pwr_oe1), + .pwr_oe2 (mux1_pwr_oe2), + .pwr_oe3 (mux1_pwr_oe3), + .pwr_oe4 (mux1_pwr_oe4), + .debug (mux1_debug) +); + +// HF ISO14443-A +hi_iso14443a hisn( + .ck_1356meg (ck_1356meg), + .adc_d (adc_d), + .mod_type (conf_word[3:0]), + .ssp_dout (ssp_dout), + + .ssp_din (mux2_ssp_din), + .ssp_frame (mux2_ssp_frame), + .ssp_clk (mux2_ssp_clk), + .adc_clk (mux2_adc_clk), + .pwr_lo (mux2_pwr_lo), + .pwr_hi (mux2_pwr_hi), + .pwr_oe1 (mux2_pwr_oe1), + .pwr_oe2 (mux2_pwr_oe2), + .pwr_oe3 (mux2_pwr_oe3), + .pwr_oe4 (mux2_pwr_oe4), + .debug (mux2_debug), + .edge_detect_threshold ({5'b00000, hf_edge_detect_threshold}), + .edge_detect_threshold_high ({5'b00000, hf_edge_detect_threshold_high}) +); + +// HF sniff +hi_sniffer he( + .ck_1356meg (ck_1356meg), + .adc_d (adc_d), + + .ssp_din (mux3_ssp_din), + .ssp_frame (mux3_ssp_frame), + .ssp_clk (mux3_ssp_clk), + .adc_clk (mux3_adc_clk), + .pwr_lo (mux3_pwr_lo), + .pwr_hi (mux3_pwr_hi), + .pwr_oe1 (mux3_pwr_oe1), + .pwr_oe2 (mux3_pwr_oe2), + .pwr_oe3 (mux3_pwr_oe3), + .pwr_oe4 (mux3_pwr_oe4) +); + +// HF ISO18092 FeliCa +hi_flite hfl( + .ck_1356meg (ck_1356meg), + .adc_d (adc_d), + .mod_type (conf_word[3:0]), + .ssp_dout (ssp_dout), + + .ssp_din (mux4_ssp_din), + .ssp_frame (mux4_ssp_frame), + .ssp_clk (mux4_ssp_clk), + .adc_clk (mux4_adc_clk), + .pwr_lo (mux4_pwr_lo), + .pwr_hi (mux4_pwr_hi), + .pwr_oe1 (mux4_pwr_oe1), + .pwr_oe2 (mux4_pwr_oe2), + .pwr_oe3 (mux4_pwr_oe3), + .pwr_oe4 (mux4_pwr_oe4), + .debug (mux4_debug) +); + +// HF get trace + +hi_get_trace gt( + .ck_1356megb (ck_1356meg), + .adc_d (adc_d), + .trace_enable (trace_enable), + .major_mode (major_mode), + .ssp_din (mux5_ssp_din), + .ssp_frame (mux5_ssp_frame), + .ssp_clk (mux5_ssp_clk) +); + +// These assignments must agree with the defines in fpgaloader.h + +// Major modes High Frequency +// mux0 = HF reader +// mux1 = HF simulated tag +// mux2 = HF ISO14443-A +// mux3 = HF sniff +// mux4 = HF ISO18092 FeliCa +// mux5 = HF get trace +// mux6 = unused +// mux7 = FPGA_MAJOR_MODE_OFF + +mux8 mux_ssp_clk ( + .sel (major_mode), + .y (ssp_clk ), + .x0 (mux0_ssp_clk ), + .x1 (mux1_ssp_clk ), + .x2 (mux2_ssp_clk ), + .x3 (mux3_ssp_clk ), + .x4 (mux4_ssp_clk ), + .x5 (mux5_ssp_clk ), + .x6 (1'b0 ), + .x7 (1'b0 ) +); + +mux8 mux_ssp_din ( + .sel (major_mode), + .y (ssp_din ), + .x0 (mux0_ssp_din ), + .x1 (mux1_ssp_din ), + .x2 (mux2_ssp_din ), + .x3 (mux3_ssp_din ), + .x4 (mux4_ssp_din ), + .x5 (mux5_ssp_din ), + .x6 (1'b0 ), + .x7 (1'b0 ) +); + +mux8 mux_ssp_frame ( + .sel (major_mode), + .y (ssp_frame ), + .x0 (mux0_ssp_frame ), + .x1 (mux1_ssp_frame ), + .x2 (mux2_ssp_frame ), + .x3 (mux3_ssp_frame ), + .x4 (mux4_ssp_frame ), + .x5 (mux5_ssp_frame ), + .x6 (1'b0 ), + .x7 (1'b0 ) +); + +mux8 mux_pwr_oe1 ( + .sel (major_mode), + .y (pwr_oe1 ), + .x0 (mux0_pwr_oe1 ), + .x1 (mux1_pwr_oe1 ), + .x2 (mux2_pwr_oe1 ), + .x3 (mux3_pwr_oe1 ), + .x4 (mux4_pwr_oe1 ), + .x5 (1'b0 ), + .x6 (1'b0 ), + .x7 (1'b0 ) +); + +mux8 mux_pwr_oe2 ( + .sel (major_mode), + .y (pwr_oe2 ), + .x0 (mux0_pwr_oe2 ), + .x1 (mux1_pwr_oe2 ), + .x2 (mux2_pwr_oe2 ), + .x3 (mux3_pwr_oe2 ), + .x4 (mux4_pwr_oe2 ), + .x5 (1'b0 ), + .x6 (1'b0 ), + .x7 (1'b0 ) +); + +mux8 mux_pwr_oe3 ( + .sel (major_mode), + .y (pwr_oe3 ), + .x0 (mux0_pwr_oe3 ), + .x1 (mux1_pwr_oe3 ), + .x2 (mux2_pwr_oe3 ), + .x3 (mux3_pwr_oe3 ), + .x4 (mux4_pwr_oe3 ), + .x5 (1'b0 ), + .x6 (1'b0 ), + .x7 (1'b0 ) +); + +mux8 mux_pwr_oe4 ( + .sel (major_mode), + .y (pwr_oe4 ), + .x0 (mux0_pwr_oe4 ), + .x1 (mux1_pwr_oe4 ), + .x2 (mux2_pwr_oe4 ), + .x3 (mux3_pwr_oe4 ), + .x4 (mux4_pwr_oe4 ), + .x5 (1'b0 ), + .x6 (1'b0 ), + .x7 (1'b0 ) +); + +mux8 mux_pwr_lo ( + .sel (major_mode), + .y (pwr_lo ), + .x0 (mux0_pwr_lo ), + .x1 (mux1_pwr_lo ), + .x2 (mux2_pwr_lo ), + .x3 (mux3_pwr_lo ), + .x4 (mux4_pwr_lo ), + .x5 (1'b0 ), + .x6 (1'b0 ), + .x7 (1'b0 ) +); + +mux8 mux_pwr_hi ( + .sel (major_mode), + .y (pwr_hi ), + .x0 (mux0_pwr_hi ), + .x1 (mux1_pwr_hi ), + .x2 (mux2_pwr_hi ), + .x3 (mux3_pwr_hi ), + .x4 (mux4_pwr_hi ), + .x5 (1'b0 ), + .x6 (1'b0 ), + .x7 (1'b0 ) +); + +mux8 mux_adc_clk ( + .sel (major_mode), + .y (adc_clk ), + .x0 (mux0_adc_clk ), + .x1 (mux1_adc_clk ), + .x2 (mux2_adc_clk ), + .x3 (mux3_adc_clk ), + .x4 (mux4_adc_clk ), + .x5 (1'b0 ), + .x6 (1'b0 ), + .x7 (1'b0 ) +); + +mux8 mux_dbg ( + .sel (major_mode), + .y (dbg ), + .x0 (mux0_debug ), + .x1 (mux1_debug ), + .x2 (mux2_debug ), + .x3 (1'b0 ), + .x4 (mux4_debug ), + .x5 (1'b0 ), + .x6 (1'b0 ), + .x7 (1'b0 ) +); +endmodule diff --git a/fpga/pm5/fpga_pm5_lf.v b/fpga/pm5/fpga_pm5_lf.v new file mode 100644 index 000000000..564723f9d --- /dev/null +++ b/fpga/pm5/fpga_pm5_lf.v @@ -0,0 +1,340 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// +// The FPGA is responsible for interfacing between the A/D, the coil drivers, +// and the ARM. In the low-frequency modes it passes the data straight +// through, so that the ARM gets raw A/D samples over the SSP. In the high- +// frequency modes, the FPGA might perform some demodulation first, to +// reduce the amount of data that we must send to the ARM. +//----------------------------------------------------------------------------- + + +module fpga_lf( + //input ck_1356meg, + input spck, + input pck0, + input ncs, + input [7:0] adc_d, + input cross_lo, + input mosi, + input ssp_dout, + input ce, // 复位输入,常态高 + + output ssp_din, + output ssp_frame, + output ssp_clk, + output adc_clk, + output miso, + output pwr_lo, + output pwr_oe1, + output pwr_oe2, + output pwr_oe4, + output dbg, + output reg [11:0] pwm_duty = 12'h500 +); + +// In all modes, let the ADC's outputs be enabled. +//assign adc_noe = 1'b0; +assign miso = 1'bZ; + +wire [2:0] major_mode; +assign major_mode = ce ? conf_word[8:6] : 3'b111; + +//----------------------------------------------------------------------------- +// The SPI receiver. This sets up the configuration word, which the rest of +// the logic looks at to determine how to connect the A/D and the coil +// drivers (i.e., which section gets it). Also assign some symbolic names +// to the configuration bits, for use below. +//----------------------------------------------------------------------------- + +// Receive 16bits of data from ARM here. +reg [15:0] shift_reg; + +always @(posedge spck) begin + if(~ncs & ce) + shift_reg <= {shift_reg[14:0], mosi}; +end + +reg [7:0] lf_ed_threshold; + +// adjustable frequency clock +wire [7:0] pck_cnt; +wire pck_divclk; +reg [7:0] divisor; +clk_divider div_clk(pck0, divisor, pck_cnt, pck_divclk); + +reg [11:0] conf_word; + +// We switch modes between transmitting to the 13.56 MHz tag and receiving +// from it, which means that we must make sure that we can do so without +// glitching, or else we will glitch the transmitted carrier. +always @(posedge ncs) +begin + if(ce) begin + // 4 bit command + case (shift_reg[15:12]) + `FPGA_CMD_SET_CONFREG: + begin + // 12 bit data + conf_word <= shift_reg[11:0]; + if (shift_reg[8:6] == `FPGA_MAJOR_MODE_LF_EDGE_DETECT) lf_ed_threshold <= 127; // default threshold + end + + `FPGA_CMD_SET_DIVISOR: + divisor <= shift_reg[7:0]; // 8bits + + `FPGA_CMD_SET_EDGE_DETECT_THRESHOLD: + lf_ed_threshold <= shift_reg[7:0]; // 8 bits + `FPGA_CMD_SET_PWR_PWM_LOW_COUNT:pwm_duty <= shift_reg[11:0]; + endcase + end +end + +//----------------------------------------------------------------------------- +// And then we instantiate the modules corresponding to each of the FPGA's +// major modes, and use muxes to connect the outputs of the active mode to +// the output pins. +//----------------------------------------------------------------------------- + +// ############################################################################ + +// LF reader (generic) +lo_read lr( + .pck0 (pck0), + .pck_divclk (pck_divclk), + .pck_cnt (pck_cnt), + .adc_d (adc_d), + .lf_field (conf_word[0]), + + .ssp_din (mux0_ssp_din), + .ssp_frame (mux0_ssp_frame), + .ssp_clk (mux0_ssp_clk), + .adc_clk (mux0_adc_clk), + .pwr_lo (mux0_pwr_lo), + .pwr_oe1 (mux0_pwr_oe1), + .pwr_oe2 (mux0_pwr_oe2), + .pwr_oe3 (mux0_pwr_oe3), + .pwr_oe4 (mux0_pwr_oe4), + .debug (mux0_debug) +); + +// LF edge detect (generic) +lo_edge_detect le( + .pck0 (pck0), + .pck_divclk (pck_divclk), + .adc_d (adc_d), + .cross_lo (cross_lo), + .lf_field (conf_word[0]), + .lf_ed_toggle_mode (conf_word[1]), + .lf_weak_load (conf_word[2]), + .lf_ed_hold_tracker (conf_word[3]), + .lf_ed_sensitive (conf_word[4]), + .lf_ed_slope (conf_word[5]), + .lf_ed_threshold (lf_ed_threshold), + .ssp_dout (ssp_dout), + + .ssp_frame (mux1_ssp_frame), + .ssp_clk (mux1_ssp_clk), + .adc_clk (mux1_adc_clk), + .pwr_lo (mux1_pwr_lo), + .pwr_oe1 (mux1_pwr_oe1), + .pwr_oe2 (mux1_pwr_oe2), + .pwr_oe3 (mux1_pwr_oe3), + .pwr_oe4 (mux1_pwr_oe4), + .debug (mux1_debug) +); + +// LF passthrough +lo_passthru lp( + .pck_divclk (pck_divclk), + .cross_lo (cross_lo), + .ssp_dout (ssp_dout), + + .ssp_din (mux2_ssp_din), + .adc_clk (mux2_adc_clk), + .pwr_lo (mux2_pwr_lo), + .pwr_oe1 (mux2_pwr_oe1), + .pwr_oe2 (mux2_pwr_oe2), + .pwr_oe3 (mux2_pwr_oe3), + .pwr_oe4 (mux2_pwr_oe4), + .debug (mux2_debug) +); + +// LF ADC (read/write) +lo_adc la( + .pck0 (pck0), + .adc_d (adc_d), + .divisor (divisor), + .lf_field (conf_word[0]), + .lf_weak_load (conf_word[2]), + .ssp_dout (ssp_dout), + + .ssp_din (mux3_ssp_din), + .ssp_frame (mux3_ssp_frame), + .ssp_clk (mux3_ssp_clk), + .adc_clk (mux3_adc_clk), + .pwr_lo (mux3_pwr_lo ), + .pwr_oe1 (mux3_pwr_oe1), + .pwr_oe2 (mux3_pwr_oe2), + .pwr_oe3 (mux3_pwr_oe3), + .pwr_oe4 (mux3_pwr_oe4), + .debug (mux3_debug) +); + +assign mux6_pwr_lo = 1'b1; +// 7 -- SPARE + +// These assignments must agree with the defines in fpgaloader.h +// Major modes Low Frequency +// mux0 = LF reader (generic) +// mux1 = LF edge detect (generic) +// mux2 = LF passthrough +// mux3 = LF ADC (read/write) +// mux4 = SPARE +// mux5 = SPARE +// mux6 = SPARE +// mux7 = FPGA_MAJOR_MODE_OFF + +mux8 mux_ssp_clk ( + .sel (major_mode), + .y (ssp_clk ), + .x0 (mux0_ssp_clk ), + .x1 (mux1_ssp_clk ), + .x2 (1'b0 ), + .x3 (mux3_ssp_clk ), + .x4 (1'b0 ), + .x5 (1'b0 ), + .x6 (1'b0 ), + .x7 (1'b0 ) +); + +mux8 mux_ssp_din ( + .sel (major_mode), + .y (ssp_din ), + .x0 (mux0_ssp_din ), + .x1 (1'b0 ), + .x2 (mux2_ssp_din ), + .x3 (mux3_ssp_din ), + .x4 (1'b0 ), + .x5 (1'b0 ), + .x6 (1'b0 ), + .x7 (1'b0 ) +); + +mux8 mux_ssp_frame ( + .sel (major_mode), + .y (ssp_frame ), + .x0 (mux0_ssp_frame ), + .x1 (mux1_ssp_frame ), + .x2 (1'b0 ), + .x3 (mux3_ssp_frame ), + .x4 (1'b0 ), + .x5 (1'b0 ), + .x6 (1'b0 ), + .x7 (1'b0 ) +); + +mux8 mux_pwr_oe1 ( + .sel (major_mode), + .y (pwr_oe1 ), + .x0 (mux0_pwr_oe1 ), + .x1 (mux1_pwr_oe1 ), + .x2 (mux2_pwr_oe1 ), + .x3 (mux3_pwr_oe1 ), + .x4 (1'b0 ), + .x5 (1'b0 ), + .x6 (1'b0 ), + .x7 (1'b0 ) +); + +mux8 mux_pwr_oe2 ( + .sel (major_mode), + .y (pwr_oe2 ), + .x0 (mux0_pwr_oe2 ), + .x1 (mux1_pwr_oe2 ), + .x2 (mux2_pwr_oe2 ), + .x3 (mux3_pwr_oe2 ), + .x4 (1'b0 ), + .x5 (1'b0 ), + .x6 (1'b0 ), + .x7 (1'b0 ) +); + +mux8 mux_pwr_oe3 ( + .sel (major_mode), + .y (pwr_oe3 ), + .x0 (mux0_pwr_oe3 ), + .x1 (mux1_pwr_oe3 ), + .x2 (mux2_pwr_oe3 ), + .x3 (mux3_pwr_oe3 ), + .x4 (1'b0 ), + .x5 (1'b0 ), + .x6 (1'b0 ), + .x7 (1'b0 ) +); + +mux8 mux_pwr_oe4 ( + .sel (major_mode), + .y (pwr_oe4 ), + .x0 (mux0_pwr_oe4 ), + .x1 (mux1_pwr_oe4 ), + .x2 (mux2_pwr_oe4 ), + .x3 (mux3_pwr_oe4 ), + .x4 (1'b0 ), + .x5 (1'b0 ), + .x6 (1'b0 ), + .x7 (1'b0 ) +); + +mux8 mux_pwr_lo ( + .sel (major_mode), + .y (pwr_lo ), + .x0 (mux0_pwr_lo ), + .x1 (mux1_pwr_lo ), + .x2 (mux2_pwr_lo ), + .x3 (mux3_pwr_lo ), + .x4 (1'b0 ), + .x5 (1'b0 ), + .x6 (mux6_pwr_lo ), + .x7 (1'b0 ) +); + +mux8 mux_adc_clk ( + .sel (major_mode), + .y (adc_clk ), + .x0 (mux0_adc_clk ), + .x1 (mux1_adc_clk ), + .x2 (mux2_adc_clk ), + .x3 (mux3_adc_clk ), + .x4 (1'b0 ), + .x5 (1'b0 ), + .x6 (1'b0 ), + .x7 (1'b0 ) +); + +mux8 mux_dbg ( + .sel (major_mode), + .y (dbg ), + .x0 (mux0_debug ), + .x1 (mux1_debug ), + .x2 (mux2_debug ), + .x3 (mux3_debug ), + .x4 (1'b0 ), + .x5 (1'b0 ), + .x6 (1'b0 ), + .x7 (1'b0 ) +); +endmodule diff --git a/fpga/pm5/fpga_pm5_top.v b/fpga/pm5/fpga_pm5_top.v new file mode 100644 index 000000000..a3b14e9fb --- /dev/null +++ b/fpga/pm5/fpga_pm5_top.v @@ -0,0 +1,132 @@ +module fpga_top ( + input ck_1356meg, + input ck_1356meg_b, // B is for close range wiring + input spi_sck, + input pck0, + input spi_ncs, + input [9:0] adc_d, + input cross_lo, + input spi_mosi, + input ssp_dout, + input module_sel, // 选择模块,1=HF,0=LF + + output ssp_din, + output ssp_frame, + output ssp_clk, + output adc_clk, + output spi_miso, + output pwr_lo, + output pwr_hi, + output pwr_oe1, + output pwr_oe2, + output pwr_oe4, + output dbg1, + output dbg2, + output dbgled, + + output clk_gate, //门控输出,控制切断外部13.56m + output pwr_pwm, //升压器输出,pwm控制升压电压 + output pan_en, //模拟供电使能 + output pdp_en //升压器使能 +); + + wire ce_lf = ~module_sel; //高启用,低重置 + wire ce_hf = module_sel; //高启用,低重置 + //-----------------------------------------GATE------------------------- + //门控使能信号同步到输入时钟域,避免亚稳态 + reg gate_en_sync1, gate_en_sync2; + always @(posedge ck_1356meg) begin + gate_en_sync1 <= gate_en; + gate_en_sync2 <= gate_en_sync1; + end + + assign clk_gate = ~gate_en_sync2;//这里取反是因为外部门控是低有效的 + //-----------------------------------------PWM-------------------------- + + Gowin_rPLL pwr_pwm_pll( + .clkout(pwr_pwm_pll_clko), //output clkout + .clkin(ck_1356meg) //input clkin + ); + + wire [11:0] pwm_duty_lf; // LF 模块的 PWM 占空比输出 + wire [11:0] pwm_duty_hf; // HF 模块的 PWM 占空比输出 + + wire [11:0] pwm_duty; // PWM占空比,实际上是高电平长度,和4096做比例 + reg [11:0] pwm_cnt= 12'h0; + + always @(posedge pwr_pwm_pll_clko) pwm_cnt <= pwm_cnt + 1'b1; //计数器 + assign pwr_pwm = (pwm_cnt > pwm_duty); //pwm输出 + + assign pan_en = 1'b1; + assign pdp_en = 1'b1; + + assign pwr_hi = 1'bZ; //使用外部门控时禁用PWRHI,由于是并联的,需要高阻 + assign dbgled = 1'b1; + assign dbg2 = 1'bZ; // 未使用 + + fpga_lf uut_lf ( + .pck0(pck0), + + .spck(spi_sck), + .ncs(spi_ncs), + + .adc_d(adc_d[9:2]), + .cross_lo(cross_lo), + .mosi(spi_mosi), + .ssp_dout(ssp_dout), + .ce(ce_lf), + + .ssp_din(ssp_din_lf), + .ssp_frame(ssp_frame_lf), + .ssp_clk(ssp_clk_lf), + .adc_clk(adc_clk_lf), + .miso(miso_lf), + .pwr_lo(pwr_lo_lf), + .pwr_oe1(pwr_oe1_lf), + .pwr_oe2(pwr_oe2_lf), + .pwr_oe4(pwr_oe4_lf), + .dbg(dbg_lf), + + .pwm_duty(pwm_duty_lf) + ); + + fpga_hf uut_hf ( + .ck_1356meg(ck_1356meg), + + .spck(spi_sck), + .ncs(spi_ncs), + + .adc_d(adc_d[9:2]), + .mosi(spi_mosi), + .ssp_dout(ssp_dout), + .ce(ce_hf), + + .ssp_din(ssp_din_hf), + .ssp_frame(ssp_frame_hf), + .ssp_clk(ssp_clk_hf), + .adc_clk(adc_clk_hf), + .miso(miso_hf), + .pwr_lo(pwr_lo_hf), + .pwr_hi(gate_en), + .pwr_oe1(pwr_oe1_hf), + .pwr_oe2(pwr_oe2_hf), + .pwr_oe4(pwr_oe4_hf), + .dbg(dbg_hf), + + .pwm_duty(pwm_duty_hf) + ); + + assign ssp_din = ~module_sel ? ssp_din_lf : ssp_din_hf; + assign ssp_frame = ~module_sel ? ssp_frame_lf : ssp_frame_hf; + assign ssp_clk = ~module_sel ? ssp_clk_lf : ssp_clk_hf; + assign adc_clk = ~module_sel ? adc_clk_lf : adc_clk_hf; + assign spi_miso = ~module_sel ? miso_lf : miso_hf; + assign pwr_lo = ~module_sel ? pwr_lo_lf : pwr_lo_hf; + //assign pwr_hi = ~module_sel ? pwr_hi_lf : pwr_hi_hf; + assign pwr_oe1 = ~module_sel ? pwr_oe1_lf : pwr_oe1_hf; + assign pwr_oe2 = ~module_sel ? pwr_oe2_lf : pwr_oe2_hf; + assign pwr_oe4 = ~module_sel ? pwr_oe4_lf : pwr_oe4_hf; + assign dbg1 = ~module_sel ? dbg_lf : dbg_hf; + assign pwm_duty = ~module_sel ? pwm_duty_lf : pwm_duty_hf; + +endmodule \ No newline at end of file diff --git a/fpga/pm5/gowin.cst b/fpga/pm5/gowin.cst new file mode 100644 index 000000000..32e1ac5b1 --- /dev/null +++ b/fpga/pm5/gowin.cst @@ -0,0 +1,81 @@ +//Copyright (C)2014-2023 Gowin Semiconductor Corporation. +//All rights reserved. +//File Title: Physical Constraints file +//Tool Version: V1.9.9 (64-bit) +//Part Number: GW1N-UV4QN48C6/I5 +//Device: GW1N-4 +//Device Version: D +//Created Time: Thu 06 04 12:54:44 2026 + +IO_LOC "pdp_en" 42; +IO_PORT "pdp_en" IO_TYPE=LVTTL33 PULL_MODE=NONE DRIVE=8 BANK_VCCIO=3.3; +IO_LOC "pan_en" 24; +IO_PORT "pan_en" IO_TYPE=LVTTL33 PULL_MODE=NONE DRIVE=8 BANK_VCCIO=3.3; +IO_LOC "pwr_pwm" 38; +IO_PORT "pwr_pwm" IO_TYPE=LVTTL33 PULL_MODE=NONE DRIVE=8 BANK_VCCIO=3.3; +IO_LOC "clk_gate" 29; +IO_PORT "clk_gate" IO_TYPE=LVTTL33 PULL_MODE=NONE DRIVE=8 BANK_VCCIO=3.3; +IO_LOC "dbgled" 41; +IO_PORT "dbgled" IO_TYPE=LVTTL33 PULL_MODE=NONE DRIVE=8 BANK_VCCIO=3.3; +IO_LOC "dbg2" 39; +IO_PORT "dbg2" IO_TYPE=LVTTL33 PULL_MODE=NONE DRIVE=8 BANK_VCCIO=3.3; +IO_LOC "dbg1" 40; +IO_PORT "dbg1" IO_TYPE=LVTTL33 PULL_MODE=NONE DRIVE=8 BANK_VCCIO=3.3; +IO_LOC "pwr_oe4" 31; +IO_PORT "pwr_oe4" IO_TYPE=LVTTL33 PULL_MODE=NONE DRIVE=8 BANK_VCCIO=3.3; +IO_LOC "pwr_oe2" 34; +IO_PORT "pwr_oe2" IO_TYPE=LVTTL33 PULL_MODE=NONE DRIVE=8 BANK_VCCIO=3.3; +IO_LOC "pwr_oe1" 32; +IO_PORT "pwr_oe1" IO_TYPE=LVTTL33 PULL_MODE=NONE DRIVE=8 BANK_VCCIO=3.3; +IO_LOC "pwr_lo" 33; +IO_PORT "pwr_lo" IO_TYPE=LVTTL33 PULL_MODE=NONE DRIVE=8 BANK_VCCIO=3.3; +IO_LOC "adc_clk" 13; +IO_PORT "adc_clk" IO_TYPE=LVTTL33 PULL_MODE=NONE DRIVE=8 BANK_VCCIO=3.3; +IO_LOC "ssp_clk" 47; +IO_PORT "ssp_clk" IO_TYPE=LVTTL33 PULL_MODE=NONE DRIVE=8 BANK_VCCIO=3.3; +IO_LOC "ssp_frame" 44; +IO_PORT "ssp_frame" IO_TYPE=LVTTL33 PULL_MODE=NONE DRIVE=8 BANK_VCCIO=3.3; +IO_LOC "ssp_din" 45; +IO_PORT "ssp_din" IO_TYPE=LVTTL33 PULL_MODE=NONE DRIVE=8 BANK_VCCIO=3.3; +IO_LOC "spi_miso" 7; +IO_PORT "spi_miso" IO_TYPE=LVTTL33 PULL_MODE=NONE DRIVE=8 BANK_VCCIO=3.3; +IO_LOC "pwr_hi" 27; +IO_PORT "pwr_hi" IO_TYPE=LVTTL33 PULL_MODE=NONE DRIVE=8 BANK_VCCIO=3.3; +IO_LOC "module_sel" 11; +IO_PORT "module_sel" IO_TYPE=LVTTL33 PULL_MODE=NONE BANK_VCCIO=3.3; +IO_LOC "ssp_dout" 46; +IO_PORT "ssp_dout" IO_TYPE=LVTTL33 PULL_MODE=NONE BANK_VCCIO=3.3; +IO_LOC "spi_mosi" 6; +IO_PORT "spi_mosi" IO_TYPE=LVTTL33 PULL_MODE=NONE BANK_VCCIO=3.3; +IO_LOC "cross_lo" 35; +IO_PORT "cross_lo" IO_TYPE=LVTTL33 PULL_MODE=NONE BANK_VCCIO=3.3; +IO_LOC "adc_d[9]" 14; +IO_PORT "adc_d[9]" IO_TYPE=LVTTL33 PULL_MODE=NONE BANK_VCCIO=3.3; +IO_LOC "adc_d[8]" 15; +IO_PORT "adc_d[8]" IO_TYPE=LVTTL33 PULL_MODE=NONE BANK_VCCIO=3.3; +IO_LOC "adc_d[7]" 16; +IO_PORT "adc_d[7]" IO_TYPE=LVTTL33 PULL_MODE=NONE BANK_VCCIO=3.3; +IO_LOC "adc_d[6]" 17; +IO_PORT "adc_d[6]" IO_TYPE=LVTTL33 PULL_MODE=NONE BANK_VCCIO=3.3; +IO_LOC "adc_d[5]" 18; +IO_PORT "adc_d[5]" IO_TYPE=LVTTL33 PULL_MODE=NONE BANK_VCCIO=3.3; +IO_LOC "adc_d[4]" 19; +IO_PORT "adc_d[4]" IO_TYPE=LVTTL33 PULL_MODE=NONE BANK_VCCIO=3.3; +IO_LOC "adc_d[3]" 20; +IO_PORT "adc_d[3]" IO_TYPE=LVTTL33 PULL_MODE=NONE BANK_VCCIO=3.3; +IO_LOC "adc_d[2]" 21; +IO_PORT "adc_d[2]" IO_TYPE=LVTTL33 PULL_MODE=NONE BANK_VCCIO=3.3; +IO_LOC "spi_ncs" 4; +IO_PORT "spi_ncs" IO_TYPE=LVTTL33 PULL_MODE=NONE BANK_VCCIO=3.3; +IO_LOC "pck0" 30; +IO_PORT "pck0" IO_TYPE=LVTTL33 PULL_MODE=NONE BANK_VCCIO=3.3; +IO_LOC "spi_sck" 5; +IO_PORT "spi_sck" IO_TYPE=LVTTL33 PULL_MODE=NONE BANK_VCCIO=3.3; +IO_LOC "ck_1356meg" 10; +IO_PORT "ck_1356meg" IO_TYPE=LVTTL33 PULL_MODE=NONE BANK_VCCIO=3.3; +IO_LOC "adc_d[1]" 22; +IO_PORT "adc_d[1]" IO_TYPE=LVTTL33 PULL_MODE=NONE BANK_VCCIO=3.3; +IO_LOC "adc_d[0]" 23; +IO_PORT "adc_d[0]" IO_TYPE=LVTTL33 PULL_MODE=NONE BANK_VCCIO=3.3; +IO_LOC "ck_1356meg_b" 28; +IO_PORT "ck_1356meg_b" IO_TYPE=LVTTL33 PULL_MODE=NONE BANK_VCCIO=3.3; diff --git a/fpga/pm5/gowin.sdc b/fpga/pm5/gowin.sdc new file mode 100644 index 000000000..0d5281899 --- /dev/null +++ b/fpga/pm5/gowin.sdc @@ -0,0 +1,11 @@ +//Copyright (C)2014-2026 GOWIN Semiconductor Corporation. +//All rights reserved. +//File Title: Timing Constraints file +//Tool Version: V1.9.9 (64-bit) +//Created Time: 2026-04-20 17:50:38 +create_clock -name CLK_SPI -period 250 -waveform {0 125} [get_ports {spi_sck}] +create_clock -name CLK_NCS -period 1000 -waveform {0 500} [get_ports {spi_ncs}] +create_clock -name clk24 -period 41.667 -waveform {0 20.834} [get_ports {pck0}] +create_clock -name clk1356 -period 73.746 -waveform {0 36.873} [get_ports {ck_1356meg}] +set_clock_groups -asynchronous -group [get_clocks {clk1356}] -group [get_clocks {clk24}] -group [get_clocks {CLK_SPI}] -group [get_clocks {CLK_NCS}] +report_timing -setup -from_clock [get_clocks {clk1356}] -to [get_ports {pwr_hi}] diff --git a/fpga/pm5/gowin_rpll.v b/fpga/pm5/gowin_rpll.v new file mode 100644 index 000000000..00895111a --- /dev/null +++ b/fpga/pm5/gowin_rpll.v @@ -0,0 +1,64 @@ +//Copyright (C)2014-2023 Gowin Semiconductor Corporation. +//All rights reserved. +//File Title: IP file +//Tool Version: V1.9.9 (64-bit) +//Part Number: GW1N-UV4QN48C6/I5 +//Device: GW1N-4 +//Device Version: D +//Created Time: Mon Jul 6 18:07:08 2026 + +module Gowin_rPLL (clkout, clkin); + +output clkout; +input clkin; + +wire lock_o; +wire clkoutp_o; +wire clkoutd_o; +wire clkoutd3_o; +wire gw_gnd; + +assign gw_gnd = 1'b0; + +rPLL rpll_inst ( + .CLKOUT(clkout), + .LOCK(lock_o), + .CLKOUTP(clkoutp_o), + .CLKOUTD(clkoutd_o), + .CLKOUTD3(clkoutd3_o), + .RESET(gw_gnd), + .RESET_P(gw_gnd), + .CLKIN(clkin), + .CLKFB(gw_gnd), + .FBDSEL({gw_gnd,gw_gnd,gw_gnd,gw_gnd,gw_gnd,gw_gnd}), + .IDSEL({gw_gnd,gw_gnd,gw_gnd,gw_gnd,gw_gnd,gw_gnd}), + .ODSEL({gw_gnd,gw_gnd,gw_gnd,gw_gnd,gw_gnd,gw_gnd}), + .PSDA({gw_gnd,gw_gnd,gw_gnd,gw_gnd}), + .DUTYDA({gw_gnd,gw_gnd,gw_gnd,gw_gnd}), + .FDLY({gw_gnd,gw_gnd,gw_gnd,gw_gnd}) +); + +defparam rpll_inst.FCLKIN = "13.56"; +defparam rpll_inst.DYN_IDIV_SEL = "false"; +defparam rpll_inst.IDIV_SEL = 1; +defparam rpll_inst.DYN_FBDIV_SEL = "false"; +defparam rpll_inst.FBDIV_SEL = 58; +defparam rpll_inst.DYN_ODIV_SEL = "false"; +defparam rpll_inst.ODIV_SEL = 2; +defparam rpll_inst.PSDA_SEL = "0000"; +defparam rpll_inst.DYN_DA_EN = "false"; +defparam rpll_inst.DUTYDA_SEL = "1000"; +defparam rpll_inst.CLKOUT_FT_DIR = 1'b1; +defparam rpll_inst.CLKOUTP_FT_DIR = 1'b1; +defparam rpll_inst.CLKOUT_DLY_STEP = 0; +defparam rpll_inst.CLKOUTP_DLY_STEP = 0; +defparam rpll_inst.CLKFB_SEL = "internal"; +defparam rpll_inst.CLKOUT_BYPASS = "false"; +defparam rpll_inst.CLKOUTP_BYPASS = "false"; +defparam rpll_inst.CLKOUTD_BYPASS = "false"; +defparam rpll_inst.DYN_SDIV_SEL = 2; +defparam rpll_inst.CLKOUTD_SRC = "CLKOUT"; +defparam rpll_inst.CLKOUTD3_SRC = "CLKOUT"; +defparam rpll_inst.DEVICE = "GW1N-4D"; + +endmodule //Gowin_rPLL diff --git a/fpga/pm5/run.ys b/fpga/pm5/run.ys new file mode 100644 index 000000000..fbf60070d --- /dev/null +++ b/fpga/pm5/run.ys @@ -0,0 +1,11 @@ +# 手动综合脚本,等价于 proxmark5_fpga.mk 自动生成的步骤。 +# 在 fpga 目录下运行:yosys -s pm5/run.ys (构建时请用 make pm5) + +# 1. 读取源代码和宏定义 +read_verilog -D PM5 -D WITH_TIMODE -D WITH_HF_15 -D WITH_FELICA_PROBE common/define.v common/mux8.v common/clk_divider.v common/lp20khz_1MSa_iir_filter.v common/min_max_tracker.v common/hi_flite.v common/hi_get_trace.v common/hi_iso14443a.v common/hi_reader.v common/hi_simulate.v common/hi_sniffer.v common/lf_edge_detect.v common/lo_adc.v common/lo_edge_detect.v common/lo_passthru.v common/lo_read.v pm5/gowin_rpll.v pm5/fpga_pm5_hf.v pm5/fpga_pm5_lf.v pm5/fpga_pm5_top.v + +# 2. 检查并强制指定顶层 +hierarchy -top fpga_top + +# 3. 进行综合 +synth_gowin -nolutram -json output.json diff --git a/fpga/proxmark3_fpga.mk b/fpga/proxmark3_fpga.mk new file mode 100644 index 000000000..3c4d03334 --- /dev/null +++ b/fpga/proxmark3_fpga.mk @@ -0,0 +1,255 @@ +# +# Proxmark3 / Proxmark3-ULT / iCopy-X FPGA build (Xilinx ISE toolchain) +# +# Invoked by the fpga/Makefile dispatcher, or directly: +# make -C fpga -f proxmark3_fpga.mk [|all|clean] +# +# The top part of this file is used to define custom options for a number of compilation targets +# To define an additional target simply look at the other defined targets and add a new TARGET entry with a unique number and the custom options required + +include $(dir $(lastword $(MAKEFILE_LIST)))common_src.mk + +XILINX_TOOLS_PREFIX= + +# Each target is built into its own separate directory name formed by combining the PREFIX and TARGET names. +# This way the source is not polluted with build files and the build directories are left behind after compilation so logs and reports can be +# examined or can be easily deleted with "make clean" + +# Options to be passed to XST +XST_OPTS_BASE = run +XST_OPTS_BASE += -ifn xst.prj +XST_OPTS_BASE += -ifmt mixed +XST_OPTS_BASE += -ofmt NGC +XST_OPTS_BASE += -lso xst.lso +XST_OPTS_BASE += -top fpga_top +XST_OPTS_BASE += -resource_sharing yes + +# Optimizations for speed (default) +XST_OPTS_SPEED = -opt_mode Speed +XST_OPTS_SPEED += -opt_level 1 +XST_OPTS_SPEED += -fsm_style lut +XST_OPTS_SPEED += -fsm_encoding auto + +# Optimization for reduced space +XST_OPTS_AREA = -opt_mode area +XST_OPTS_AREA += -opt_level 2 +XST_OPTS_AREA += -fsm_style bram +XST_OPTS_AREA += -fsm_encoding compact + +# par specific option (set determistic seed) +PAR_OPTIONS = -t 2 + +# Types of selective module compilation: +# WITH_LF Enables selection of LF modules (and disables all HF) + +# To enable these modules WITH_LF _MUST_ be defined +# WITH_LF0 enable LF reader (generic) +# WITH_LF1 enable LF edge detect (generic) +# WITH_LF2 enable LF passthrough +# WITH_LF3 enable LF ADC (read/write) + +# To enable these modules WITH_LF _MUST_NOT_ be defined +# WITH_HF0 enable HF reader (see also WITH_HF_15 below) +# WITH_HF_15 select "iso15 2sc mode" extensions instead of original +# (the iso15 low-signal reader detection thresholds are selected at runtime +# in hi_reader.v, based on subcarrier/minor mode -- no separate define) +# WITH_HF1 enable HF simulated tag +# WITH_HF2 enable HF ISO14443-A +# WITH_HF3 enable sniff +# WITH_HF4 enable HF ISO18092 FeliCa +# WITH_HF5 enable HF get trace + +# WITH_TIMODE enable TI mode (for SPI_SSC. PM5 only currently) + +# RDV40/Generic - Enable LF and all the LF modules +TARGET1_OPTIONS = -define \{WITH_LF WITH_LF0 WITH_LF1 WITH_LF2 WITH_LF3\} +# RDV40/Generic - Enable all HF modules except Felica +TARGET2_OPTIONS = -define \{WITH_HF0 WITH_HF1 WITH_HF2 WITH_HF3 WITH_HF5\} +# RDV40/Generic - Enable all HF modules except Felica and ISO14443, select HF_15 instead of HF +TARGET3_OPTIONS = -define \{WITH_HF0 WITH_HF1 WITH_HF3 WITH_HF5 WITH_HF_15\} +# RDV40/Generic - Enable all HF modules except ISO14443 +TARGET4_OPTIONS = -define \{WITH_HF0 WITH_HF1 WITH_HF3 WITH_HF4 WITH_HF5 WITH_FELICA_PROBE\} +# ICOPYX +TARGET5_OPTIONS = $(TARGET1_OPTIONS) +# PM3-ULT (xc2s50): same four images as the RDV4 targets +TARGET6_OPTIONS = $(TARGET1_OPTIONS) +TARGET7_OPTIONS = $(TARGET1_OPTIONS) +TARGET8_OPTIONS = $(TARGET1_OPTIONS) +TARGET9_OPTIONS = $(TARGET1_OPTIONS) + +# Here we list the target names +TARGET1_NAME = fpga_pm3_lf +TARGET2_NAME = fpga_pm3_hf +TARGET3_NAME = fpga_pm3_hf_15 +TARGET4_NAME = fpga_pm3_felica +TARGET5_NAME = fpga_icopyx_hf +TARGET6_NAME = fpga_pm3_ult_lf +TARGET7_NAME = fpga_pm3_ult_hf +TARGET8_NAME = fpga_pm3_ult_hf_15 +TARGET9_NAME = fpga_pm3_ult_felica + +# Targets can be compiled for different FPGA flavours +TARGET1_FPGA = xc2s30-5-vq100 +TARGET2_FPGA = $(TARGET1_FPGA) +TARGET3_FPGA = $(TARGET1_FPGA) +TARGET4_FPGA = $(TARGET1_FPGA) +TARGET5_FPGA = xc3s100e-4-vq100 +TARGET6_FPGA = xc2s50-5-tq144 +TARGET7_FPGA = $(TARGET6_FPGA) +TARGET8_FPGA = $(TARGET6_FPGA) +TARGET9_FPGA = $(TARGET6_FPGA) + +# Pin constraints, one file per FPGA flavour +TARGET1_UCF = $(PM3_DIR)/xc2s30-5-vq100.ucf +TARGET2_UCF = $(TARGET1_UCF) +TARGET3_UCF = $(TARGET1_UCF) +TARGET4_UCF = $(TARGET1_UCF) +TARGET5_UCF = $(ICOPYX_DIR)/xc3s100e-4-vq100.ucf +TARGET6_UCF = $(PM3_DIR)/xc2s50-5-tq144.ucf +TARGET7_UCF = $(TARGET6_UCF) +TARGET8_UCF = $(TARGET6_UCF) +TARGET9_UCF = $(TARGET6_UCF) + +# Assemble the final XST options for each target +TARGET1_XST_OPTS = $(XST_OPTS_BASE) $(XST_OPTS_AREA) -p $(TARGET1_FPGA) -ofn $(TARGET1_NAME) $(TARGET1_OPTIONS) +TARGET2_XST_OPTS = $(XST_OPTS_BASE) $(XST_OPTS_AREA) -p $(TARGET2_FPGA) -ofn $(TARGET2_NAME) $(TARGET2_OPTIONS) +TARGET3_XST_OPTS = $(XST_OPTS_BASE) $(XST_OPTS_AREA) -p $(TARGET3_FPGA) -ofn $(TARGET3_NAME) $(TARGET3_OPTIONS) +TARGET4_XST_OPTS = $(XST_OPTS_BASE) $(XST_OPTS_AREA) -p $(TARGET4_FPGA) -ofn $(TARGET4_NAME) $(TARGET4_OPTIONS) +TARGET5_XST_OPTS = $(XST_OPTS_BASE) $(XST_OPTS_SPEED) -p $(TARGET5_FPGA) -ofn $(TARGET5_NAME) $(TARGET5_OPTIONS) +TARGET6_XST_OPTS = $(XST_OPTS_BASE) $(XST_OPTS_SPEED) -p $(TARGET6_FPGA) -ofn $(TARGET6_NAME) $(TARGET6_OPTIONS) +TARGET7_XST_OPTS = $(XST_OPTS_BASE) $(XST_OPTS_SPEED) -p $(TARGET7_FPGA) -ofn $(TARGET7_NAME) $(TARGET7_OPTIONS) +TARGET8_XST_OPTS = $(XST_OPTS_BASE) $(XST_OPTS_SPEED) -p $(TARGET8_FPGA) -ofn $(TARGET8_NAME) $(TARGET8_OPTIONS) +TARGET9_XST_OPTS = $(XST_OPTS_BASE) $(XST_OPTS_SPEED) -p $(TARGET9_FPGA) -ofn $(TARGET9_NAME) $(TARGET9_OPTIONS) + +# Add the files that are unique per target and all the common files +TARGET1_FILES = $(COMMON_HDL) $(PM3_DIR)/fpga_pm3_top.v +TARGET2_FILES = $(TARGET1_FILES) +TARGET3_FILES = $(TARGET1_FILES) +TARGET4_FILES = $(TARGET1_FILES) +TARGET5_FILES = $(COMMON_HDL) $(COMMON_DIR)/mux2_onein.v $(COMMON_DIR)/mux2_oneout.v $(ICOPYX_DIR)/fpga_icopyx_hf.v $(ICOPYX_DIR)/fpga_icopyx_lf.v $(ICOPYX_DIR)/fpga_icopyx_top.v +TARGET6_FILES = $(TARGET1_FILES) +TARGET7_FILES = $(TARGET1_FILES) +TARGET8_FILES = $(TARGET1_FILES) +TARGET9_FILES = $(TARGET1_FILES) + +# List of all valid target FPGA images to build +TARGETS = $(TARGET1_NAME) $(TARGET2_NAME) $(TARGET3_NAME) $(TARGET4_NAME) $(TARGET5_NAME) $(TARGET6_NAME) $(TARGET7_NAME) $(TARGET8_NAME) $(TARGET9_NAME) + +# Verbosity type for ISE tools ise|xflow|silent +VERBOSITY = -intstyle silent + +# Pass the custom variables to the lower make rules +$(TARGET1_NAME).bit: TARGET_FPGA = $(TARGET1_FPGA) +$(TARGET1_NAME).bit: TARGET_UCF = $(TARGET1_UCF) +$(TARGET1_NAME).bit: TARGET_FILES = $(TARGET1_FILES) +$(TARGET1_NAME).bit: TARGET_XST_OPTS = $(TARGET1_XST_OPTS) + +$(TARGET2_NAME).bit: TARGET_FPGA = $(TARGET2_FPGA) +$(TARGET2_NAME).bit: TARGET_UCF = $(TARGET2_UCF) +$(TARGET2_NAME).bit: TARGET_FILES = $(TARGET2_FILES) +$(TARGET2_NAME).bit: TARGET_XST_OPTS = $(TARGET2_XST_OPTS) + +$(TARGET3_NAME).bit: TARGET_FPGA = $(TARGET3_FPGA) +$(TARGET3_NAME).bit: TARGET_UCF = $(TARGET3_UCF) +$(TARGET3_NAME).bit: TARGET_FILES = $(TARGET3_FILES) +$(TARGET3_NAME).bit: TARGET_XST_OPTS = $(TARGET3_XST_OPTS) + +$(TARGET4_NAME).bit: TARGET_FPGA = $(TARGET4_FPGA) +$(TARGET4_NAME).bit: TARGET_UCF = $(TARGET4_UCF) +$(TARGET4_NAME).bit: TARGET_FILES = $(TARGET4_FILES) +$(TARGET4_NAME).bit: TARGET_XST_OPTS = $(TARGET4_XST_OPTS) + +$(TARGET5_NAME).bit: TARGET_FPGA = $(TARGET5_FPGA) +$(TARGET5_NAME).bit: TARGET_UCF = $(TARGET5_UCF) +$(TARGET5_NAME).bit: TARGET_FILES = $(TARGET5_FILES) +$(TARGET5_NAME).bit: TARGET_XST_OPTS = $(TARGET5_XST_OPTS) + +$(TARGET6_NAME).bit: TARGET_FPGA = $(TARGET6_FPGA) +$(TARGET6_NAME).bit: TARGET_UCF = $(TARGET6_UCF) +$(TARGET6_NAME).bit: TARGET_FILES = $(TARGET6_FILES) +$(TARGET6_NAME).bit: TARGET_XST_OPTS = $(TARGET6_XST_OPTS) + +$(TARGET7_NAME).bit: TARGET_FPGA = $(TARGET7_FPGA) +$(TARGET7_NAME).bit: TARGET_UCF = $(TARGET7_UCF) +$(TARGET7_NAME).bit: TARGET_FILES = $(TARGET7_FILES) +$(TARGET7_NAME).bit: TARGET_XST_OPTS = $(TARGET7_XST_OPTS) + +$(TARGET8_NAME).bit: TARGET_FPGA = $(TARGET8_FPGA) +$(TARGET8_NAME).bit: TARGET_UCF = $(TARGET8_UCF) +$(TARGET8_NAME).bit: TARGET_FILES = $(TARGET8_FILES) +$(TARGET8_NAME).bit: TARGET_XST_OPTS = $(TARGET8_XST_OPTS) + +$(TARGET9_NAME).bit: TARGET_FPGA = $(TARGET9_FPGA) +$(TARGET9_NAME).bit: TARGET_UCF = $(TARGET9_UCF) +$(TARGET9_NAME).bit: TARGET_FILES = $(TARGET9_FILES) +$(TARGET9_NAME).bit: TARGET_XST_OPTS = $(TARGET9_XST_OPTS) + +$(TARGETS): + $(Q)$(MKDIR) $(PREFIX)build_$@ + $(Q)$(MAKE) -C $(PREFIX)build_$@ -f ../proxmark3_fpga.mk $(notdir $@).bit + +work: + $(Q)$(RM) xst.prj + $(Q)for item in $(TARGET_FILES); do echo verilog work ../$$item>>xst.prj; done + $(Q)echo work> xst.lso + +%.xst: work + $(Q)$(RM) $@ + $(Q)echo $(TARGET_XST_OPTS)> $@ + +%.ngc: %.xst + $(Q)$(RM) $@ + $(info [-] XST $@) + $(Q)$(XILINX_TOOLS_PREFIX)xst $(VERBOSITY) -ifn $< + +%.ngd: %.ngc + $(Q)$(RM) $@ + $(info [-] NGD $@) + $(Q)$(XILINX_TOOLS_PREFIX)ngdbuild $(VERBOSITY) -quiet -p $(TARGET_FPGA) -nt timestamp -uc ../$(TARGET_UCF) $< $@ + +%_map.ncd: %.ngd + $(Q)$(RM) $@ + $(info [-] MAP $@) + $(Q)$(XILINX_TOOLS_PREFIX)map $(VERBOSITY) -p $(TARGET_FPGA) -o $*_map $* + +%.ncd: %_map.ncd + $(Q)$(RM) $@ + $(info [-] PAR $@) + $(Q)$(XILINX_TOOLS_PREFIX)par $(PAR_OPTIONS) $(VERBOSITY) -w $< $@ + +%.bit: %.ncd + $(Q)$(RM) $@ $*.drc $*.rbt + $(info [=] BITGEN $@) + $(Q)$(XILINX_TOOLS_PREFIX)bitgen $(VERBOSITY) -w $* $@ + $(Q)python3 ../$(STRIP_DATE_TIME) $@ || true + $(Q)$(CP) $@ .. + +# Build all targets +all: $(TARGETS) + +# ALWAYS have some hardcoded text after $(PREFIX) to avoid rm -rf * or rm -rf /* situations if PREFIX is incorrectly set to empty "" or just "/" +clean: + $(Q)$(RMDIR) $(PREFIX)build_* + $(info [-] Build files deleted) + +.DEFAULT: + @if [ "$@" != "all" ] && [ ! "$(filter $@,$(TARGETS))" ]; then \ + make help; \ + else \ + make all; \ + fi + +.PHONY: all help clean + +help: + @echo "################################################################" + @echo "#" + @echo "# - Builds only one of the above listed targets" + @echo "# all - Builds the FPGA bitstreams for all targets" + @echo "# clean - Keeps .bit files but cleans intermediate build files for all targets" + @echo "#" + @echo "#" + @echo "# Valid targets are:" + @echo "# $(TARGETS)" + @echo "#" + @echo "################################################################" diff --git a/fpga/proxmark5_fpga.mk b/fpga/proxmark5_fpga.mk new file mode 100644 index 000000000..853a3b265 --- /dev/null +++ b/fpga/proxmark5_fpga.mk @@ -0,0 +1,171 @@ +# +# Proxmark5 FPGA build (open source toolchain: yosys + nextpnr-himbaechel + apycula) +# +# Invoked by the fpga/Makefile dispatcher, or directly: +# make -C fpga -f proxmark5_fpga.mk [all|clean] +# +# Overridable variables: +# OSS_CAD_SUITE oss-cad-suite root, holds yosys/nextpnr-himbaechel/gowin_pack +# PM5_FAMILY Gowin family, selects the chip database in nextpnr +# PM5_PART exact part, must match the board +# PM5_IDCODE IDCODE the bitstream declares, must match the silicon +# PM5_CST pin constraints, generated by the Gowin IDE +# PM5_SDC timing constraints, generated by the Gowin IDE +# PM5_FREQ fallback clock constraint, used when PM5_SDC is empty +# PM5_DEFINES HDL defines, one image covers both the LF and HF halves + +include $(dir $(lastword $(MAKEFILE_LIST)))common_src.mk + +# oss-cad-suite is looked up next to the checkout and under the usual Desktop +# locations. Leave OSS_CAD_SUITE empty to use tools that are already on PATH +# (i.e. when make runs inside the suite's own shell). +OSS_CAD_SUITE ?= $(firstword $(wildcard \ + $(abspath $(CURDIR)/../../oss-cad-suite) \ + $(HOME)/Desktop/oss-cad-suite \ + $(USERPROFILE)/Desktop/oss-cad-suite)) + + +PM5_FAMILY ?= GW1N-4 +PM5_PART ?= GW1N-UV4QN48C6/I5 +PM5_IDCODE ?= 0x1100381B +PM5_CST ?= $(PM5_DIR)/gowin.cst +PM5_SDC ?= $(PM5_DIR)/gowin.sdc +PM5_FREQ ?= 24 +PM5_DEFINES ?= PM5 WITH_TIMODE WITH_HF_15 WITH_FELICA_PROBE + +# The Gowin IDE generated SDC covers every clock, but nextpnr only takes a +# subset of SDC; it is rewritten into the build directory, leaving the original +# file untouched for the next regeneration from the IDE. See the script for +# what it drops. PM5_FREQ is the fallback for the unconstrained case. +PM5_TIMING = $(if $(PM5_SDC),--sdc $(PM5_NAME).sdc,--freq $(PM5_FREQ)) +PM5_SDC_CLEAN = $(OC_ENV) $(OC_PYTHON) $(COMMON_DIR)/gowin_sdc_clean.py + +PM5_NAME = fpga_pm5 +PM5_OUT = $(PREFIX)build_$(PM5_NAME) + +# The oss-cad-suite launchers need their root, and both bin/ and lib/ on PATH +# (lib/ carries the shared libraries), otherwise they exit without a message. +# The suite is laid out per platform, and each of its own environment scripts +# says what to put where. On Windows the shared libraries sit in lib/ and are +# found through PATH, as environment.bat does. Everywhere else they are found by +# the tools themselves, and adding lib/ to PATH or LD_LIBRARY_PATH makes yosys +# load the suite's libstdc++ instead of the system one and segfault at startup. +# With OSS_CAD_SUITE unset the tools come from PATH, which is what sourcing the +# suite's environment gives you. +ifneq ($(OSS_CAD_SUITE),) +ifneq ($(wildcard $(OSS_CAD_SUITE)/lib/python3.exe),) +OC_PATH = $(OSS_CAD_SUITE)/bin:$(OSS_CAD_SUITE)/lib +OC_PYTHON = $(OSS_CAD_SUITE)/lib/python3.exe +else +OC_PATH = $(OSS_CAD_SUITE)/bin:$(OSS_CAD_SUITE)/py3bin +OC_PYTHON = $(firstword $(wildcard $(OSS_CAD_SUITE)/py3bin/python3 $(OSS_CAD_SUITE)/bin/python3) python3) +endif +OC_ENV = YOSYSHQ_ROOT="$(OSS_CAD_SUITE)/" PATH="$(OC_PATH):$$PATH" PYTHON_EXECUTABLE="$(OC_PYTHON)" +else +OC_ENV = +OC_PYTHON = python3 +endif + +PM5_BUILD_HDL = $(addprefix ../,$(PM5_HDL)) +PM5_DEFS = $(foreach d,$(PM5_DEFINES),-D $(d)) + +.PHONY: all clean help check-tools smoke $(PM5_NAME) + +all: $(PM5_NAME) + +$(PM5_NAME): $(PM5_NAME).fs $(PM5_NAME).bin + +# Only the bitstream is copied next to the Xilinx ones, everything else stays +# in the build directory. Unlike the PM3 targets these recipes run in the fpga +# directory itself, so the destination is this directory, not its parent. +$(PM5_NAME).fs: $(PM5_OUT)/$(PM5_NAME).fs + $(Q)$(CP) $< . + +$(PM5_NAME).bin: $(PM5_OUT)/$(PM5_NAME).bin + $(Q)$(CP) $< . + +# The pin constraints are board specific and are not part of the repository. +$(PM5_CST): + $(error [!] missing $@ -- fill in the PM5 pin constraints, then rerun) + +# The makefiles are prerequisites of the generated files so that editing the +# defines or the source lists regenerates them. +$(PM5_OUT)/$(PM5_NAME).json: $(PM5_HDL) $(MAKEFILE_LIST) | check-tools $(PM5_OUT) + $(info [-] YOSYS $@) + $(Q)$(RM) $@ + $(Q)printf '%s\n' \ + "read_verilog $(PM5_DEFS) $(PM5_BUILD_HDL)" \ + "hierarchy -top fpga_top" \ + "synth_gowin -nolutram -json $(PM5_NAME).json" > $(PM5_OUT)/synth.ys + $(Q)cd $(PM5_OUT) && $(OC_ENV) yosys -q -s synth.ys + +$(PM5_OUT)/$(PM5_NAME).sdc: $(PM5_SDC) $(COMMON_DIR)/gowin_sdc_clean.py $(MAKEFILE_LIST) | $(PM5_OUT) + $(Q)$(PM5_SDC_CLEAN) $< $@ + +$(PM5_OUT)/$(PM5_NAME)_pnr.json: $(PM5_OUT)/$(PM5_NAME).json $(PM5_CST) $(if $(PM5_SDC),$(PM5_OUT)/$(PM5_NAME).sdc) + $(info [=] NEXTPNR $@) + $(Q)cd $(PM5_OUT) && $(OC_ENV) nextpnr-himbaechel \ + --device "$(PM5_PART)" \ + --vopt family=$(PM5_FAMILY) \ + --vopt cst=../$(PM5_CST) \ + $(PM5_TIMING) \ + --json $(PM5_NAME).json \ + --write $(PM5_NAME)_pnr.json + +# TODO: workaround, drop once apycula can target GW1N-4D. The GW1N-4 database +# apycula ships stamps the plain GW1N-4 IDCODE (0x0100381B), which the silicon +# on a PM5 (GW1N-4B/4D, 0x1100381B) rejects: done_final stays 0 and nothing +# drives the antennas. gowin_devid.py rewrites that field to PM5_IDCODE here so +# the image is accepted at all. Remove this step, PM5_IDCODE and the workflow's +# IDCODE check once apycula gains a GW1N-4B/4D target or stops discarding the +# C6/I5 device version from the part number. Until then, suspect the fuse map +# first when a bitstream misbehaves: it comes from the non-D database entry. +$(PM5_OUT)/$(PM5_NAME).fs: $(PM5_OUT)/$(PM5_NAME)_pnr.json $(COMMON_DIR)/gowin_devid.py + $(info [=] GOWIN_PACK $@) + $(Q)cd $(PM5_OUT) && $(OC_ENV) gowin_pack -d $(PM5_FAMILY) -o $(PM5_NAME).fs $(PM5_NAME)_pnr.json + $(Q)$(OC_ENV) $(OC_PYTHON) $(COMMON_DIR)/gowin_devid.py $(PM5_OUT)/$(PM5_NAME).fs $(PM5_IDCODE) + +$(PM5_OUT)/$(PM5_NAME).bin: $(PM5_OUT)/$(PM5_NAME).fs + $(info [=] FS2BIN $@) + $(Q)cd $(PM5_OUT) && $(OC_ENV) $(OC_PYTHON) ../$(COMMON_DIR)/fs2bin.py $(PM5_NAME).fs $(PM5_NAME).bin + +$(PM5_OUT): + $(Q)$(MKDIR) $@ + +check-tools: + $(Q)missing=""; \ + for t in yosys nextpnr-himbaechel gowin_pack; do \ + $(OC_ENV) command -v $$t >/dev/null 2>&1 || missing="$$missing $$t"; \ + done; \ + if [ -n "$$missing" ]; then \ + echo "[!] not found:$$missing"; \ + echo "[!] point OSS_CAD_SUITE at oss-cad-suite, or add its bin/ to PATH"; \ + exit 1; \ + fi + +# Compile a two line design through the same toolchain and environment the +# build uses, so a suite that cannot run fails here with a clear message +# instead of half way through the build. +smoke: | check-tools $(PM5_OUT) + $(Q)$(OC_ENV) yosys -V + $(Q)printf '%s\n' "module smoke(input a, output b);" " assign b = ~a;" "endmodule" > $(PM5_OUT)/smoke.v + $(Q)cd $(PM5_OUT) && $(OC_ENV) yosys -q -p "read_verilog smoke.v; synth_gowin -json smoke.json" + $(Q)test -s $(PM5_OUT)/smoke.json && echo "[=] SMOKE ok" + +# ALWAYS have some hardcoded text after $(PREFIX) to avoid rm -rf * or rm -rf /* situations if PREFIX is incorrectly set to empty "" or just "/" +clean: + $(Q)$(RMDIR) $(PREFIX)build_$(PM5_NAME) + $(info [-] Build files deleted) + +help: + @echo "################################################################" + @echo "#" + @echo "# $(PM5_NAME) - Builds the PM5 bitstream into $(PM5_NAME).fs/.bin" + @echo "# all - same as $(PM5_NAME)" + @echo "# clean - Keeps the bitstream but cleans intermediate build files" + @echo "#" + @echo "# Device: $(PM5_PART) (family $(PM5_FAMILY))" + @echo "# Pins : $(PM5_CST)" + @echo "# Toolchain: $(OSS_CAD_SUITE)" + @echo "#" + @echo "################################################################" diff --git a/fpga/tests/Makefile b/fpga/tests/Makefile index f2ae6d729..1dc96731a 100644 --- a/fpga/tests/Makefile +++ b/fpga/tests/Makefile @@ -8,6 +8,10 @@ MKDIR = mkdir -p TEST_OUTDIR = tb_tmp +# iverilog ships with oss-cad-suite; point at it when it is not on PATH, e.g. +# make IVERILOG=$(HOME)/Desktop/oss-cad-suite/bin/iverilog +IVERILOG ?= iverilog + TB_SOURCES = \ tb_lp20khz_1MSa_iir_filter.v \ tb_min_max_tracker.v \ @@ -22,7 +26,7 @@ TB_DATA = \ all: $(TBS) tests %.vvp: %.v - iverilog -I .. -o $@ $< + $(IVERILOG) -I ../common -o $@ $< clean: rm -rf *.vvp $(TEST_OUTDIR) diff --git a/include/desfire.h b/include/desfire.h index 37716f11d..33cc9d1c1 100644 --- a/include/desfire.h +++ b/include/desfire.h @@ -30,4 +30,46 @@ typedef enum { T_AES = 0x03 } DesfireCryptoAlgorithm; +#define DESFIRE_MAX_ALGO_COUNT 4 // T_DES ... T_AES +#define DESFIRE_MAX_KEY_COUNT 0x0E // key numbers 0x00 ... 0x0D +#define DESFIRE_MAX_APP_COUNT 64 // applications we keep track of per PICC +#define DESFIRE_MAX_FILE_COUNT 32 // file numbers 0x00 ... 0x1F + +// Keys recovered for one application. +// keys[algo][keyno][0] is the found flag, keys[algo][keyno][1..] the key itself. +// `algo` is a DesfireCryptoAlgorithm, `keyno` the DESFire key number. +typedef struct { + uint32_t aid; + uint8_t keys[DESFIRE_MAX_ALGO_COUNT][DESFIRE_MAX_KEY_COUNT][DESFIRE_MAX_KEY_SIZE + 1]; +} desfire_app_keys_t; + +// `hf mfdes etest`: one CMD_HF_DESFIRE_SIM_TEST packet carries one operation. +typedef enum { + DESFIRE_SIM_TEST_BEGIN = 0, // check the image, clear the random queue -> no data + DESFIRE_SIM_TEST_END, // drop the state and the random queue -> no data + DESFIRE_SIM_TEST_SCAN, // RF reset and activation -> iso14a_card_select_t + DESFIRE_SIM_TEST_APDU, // data: one command, native or ISO 7816 wrapped -> the answer + DESFIRE_SIM_TEST_RANDOM, // data: bytes the next RndB / random id draws use + DESFIRE_SIM_TEST_FIELDOFF, // RF reset: session dropped, image re-read -> no data + DESFIRE_SIM_TEST_STATE, // -> desfire_sim_test_state_t +} desfire_sim_test_op_t; + +// bytes the random queue holds, RANDOM answers PM3_EOVFLOW past this +#define DESFIRE_SIM_TEST_RANDOM_MAX 64 + +typedef struct { + uint8_t op; // desfire_sim_test_op_t + uint16_t len; + uint8_t data[]; +} PACKED desfire_sim_test_cmd_t; + +typedef struct { + uint8_t ready; // activated and answering + uint8_t authenticated; + uint8_t auth_keyno; + uint8_t aid[3]; // selected application, wire order + uint8_t random_remaining; // queued bytes not yet drawn + uint8_t random_underflow; // a draw wanted more than was queued, sticky +} PACKED desfire_sim_test_state_t; + #endif diff --git a/include/desfire_em.h b/include/desfire_em.h new file mode 100644 index 000000000..821ad6a17 --- /dev/null +++ b/include/desfire_em.h @@ -0,0 +1,290 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// DESFire card image, as it lives in emulator memory. +// +// The client packs a desfire_dump_t (see client/src/fileutils.h, and +// doc/mfdes_dump_format.md for the json it comes from) into this layout and +// uploads it with eload. The device simulation reads it, and writes back into +// it -- a reader that writes to the simulated card changes this image, so an +// esave afterwards shows what the reader did. That is the difference between +// an emulator and a replay rig. +// +// Layout, inside the CARD_MEMORY_SIZE region: +// +// 0 +---------------------------+ +// | desfire_em_hdr_t | fixed +// +---------------------------+ +// | desfire_em_app_t [] | appcount entries +// | desfire_em_file_t [] | filecount entries grows up +// | desfire_em_key_t [] | keycount entries +// tables_end +// | | +// | ..... free ..... | <- the emulated card's free memory +// | | +// data_start +// | file data regions | grows down +// size +---------------------------+ +// +// Two frontiers rather than fixed-size tables: a card with three files spends a +// few hundred bytes, not the worst case. Tables append as the reader creates +// applications and files; a data region is reserved when a file is created and +// never moves afterwards, so WriteData and WriteRecord are pure writes. The +// only allocation check anywhere is tables_end < data_start, and the space +// between them is what GetFreeMem reports -- so the simulated card fills up and +// refuses with OUT_OF_EEPROM the way a real one does. +// +// Nothing here knows how big emulator memory is. The device reports that to the +// client in capabilities_t, and a platform with more of it holds a bigger card +// with no change to this format. +//----------------------------------------------------------------------------- + +#ifndef __DESFIRE_EM_H +#define __DESFIRE_EM_H + +#include "common.h" +#include "desfire.h" + +#define DESFIRE_EM_MAGIC 0x31534544 // "DES1", little endian +#define DESFIRE_EM_LAYOUT_VERSION 1 + +// Allocation granule. A genuine DESFire rounds NV consumption to 32 bytes: +// measured on a DESFire EV2 2K, a 1 byte file costs 32 and a 33 byte file costs +// 64. Rounding the same way keeps GetFreeMem card-shaped. Note the rounding is +// invisible to a reader otherwise -- GetFileSettings reports the size the file +// was created with, also measured. +// PICC configuration, set by SetConfiguration option 0x00 and kept in hdr.flags. +// Both are one way on a card -- "cannot be reset" -- and the bit positions are +// the config byte's own, so the byte is stored as it arrives. +#define DESFIRE_EM_PICC_NO_FORMAT (1 << 0) // FormatPICC refused from here on +#define DESFIRE_EM_PICC_RANDOM_UID (1 << 1) // anticollision shows a random id + +#define DESFIRE_EM_GRANULE 32 +#define DESFIRE_EM_ROUNDUP(x) (((x) + (DESFIRE_EM_GRANULE - 1)) & ~(DESFIRE_EM_GRANULE - 1)) + +// NV an application costs before its keys. Measured on a DESFire EV2 2K: an +// application with one key costs 96 bytes, with fourteen keys 352. 64 plus the +// key material reproduces the first exactly and the second about 18% low, which +// is close enough for a free-memory figure that only has to look card-shaped -- +// see the note on not reproducing NXP's allocator, below. +#define DESFIRE_EM_APP_OVERHEAD 64 + +// EV1 hard limits. 28 applications is the PICC's own, reported as COUNT_ERROR +// 0xCE; 32 files and 14 keys follow the file/key number ranges 0x00..0x1F and +// 0x00..0x0D. These bound the tables; what actually fits is decided by the +// frontiers, not by these. +#define DESFIRE_EM_MAX_APPS 28 +#define DESFIRE_EM_MAX_FILES 32 +#define DESFIRE_EM_MAX_KEYS DESFIRE_MAX_KEY_COUNT + +// Which generation the image impersonates. The simulation answers a different +// command set for each, so it is stored rather than re-derived from the version +// bytes at run time. Identification bytes are versionhw[3] and [4]: EV1 is +// 01 00, EV2 12 00 or 42 00, EV2 XL 22 00, EV3 33 00, DuoX A0 00. +typedef enum { + DESFIRE_EM_GEN_UNKNOWN = 0, + DESFIRE_EM_GEN_D40 = 1, + DESFIRE_EM_GEN_EV1 = 2, + DESFIRE_EM_GEN_EV2 = 3, + DESFIRE_EM_GEN_EV3 = 4, + DESFIRE_EM_GEN_LIGHT = 5, + DESFIRE_EM_GEN_DUOX = 6, +} desfire_em_gen_t; + +typedef struct { + uint32_t magic; // DESFIRE_EM_MAGIC + uint8_t layout; // DESFIRE_EM_LAYOUT_VERSION + uint8_t generation; // desfire_em_gen_t + uint8_t flags; // desfire_em_picc_flags_t + uint8_t rfu0; + + // card identity, straight from the dump + uint8_t uid[10]; + uint8_t uidlen; + uint8_t atqa[2]; + uint8_t sak; + uint8_t atslen; + uint8_t ats[20]; + + // GetVersion answers over three chained frames and they are not the same + // shape across generations, so each is kept raw + uint8_t versionhw[7]; + uint8_t versionhwlen; + uint8_t versionsw[7]; + uint8_t versionswlen; + uint8_t versionprod[14]; + uint8_t versionprodlen; + + uint8_t signature[56]; // NXP originality signature + uint8_t signaturelen; + uint8_t rfu1; + + // app[0] is the PICC, AID 000000. It holds the PICC master key settings and + // keys and never has files, the same way the json format stores it. + uint8_t appcount; + uint8_t filecount; + uint8_t keycount; + uint8_t rfu2; + + uint16_t app_off; // byte offsets from the start of the image + uint16_t file_off; + uint16_t key_off; + + // the two frontiers. tables grow up to tables_end, file data down from + // data_start, and an allocation only has to leave them apart + uint16_t tables_end; + uint16_t data_start; + uint16_t size; // bytes of emulator memory this image may use + + // Two different limits, and a reader must only ever see the first. + // + // cardsize is the NV the emulated card claims to have, so GetFreeMem + // answers cardsize - reserved and CreateFile refuses with OUT_OF_EEPROM + // once that runs out. Without it a card impersonating a 2K part would + // report several kB free, which no 2K part does. + // + // size is what emulator memory physically holds, and is the harder limit + // of the two. It is never visible to a reader. + uint16_t cardsize; + uint16_t reserved; // NV the card has spent, against cardsize +} PACKED desfire_em_hdr_t; + +// ---------------------------------------------------------------- application + +#define DESFIRE_EM_APP_DELETED (1 << 0) // tombstone, see below +#define DESFIRE_EM_APP_AUTHED (1 << 1) // dump ran authenticated here +#define DESFIRE_EM_APP_ISOFIDS (1 << 2) // application uses ISO file ids + +typedef struct { + uint8_t aid[3]; + uint8_t flags; + uint8_t keysettings; + uint8_t numkeysraw; // key type in bits 6-7, iso-fid flag bit 5, count 0-4 + uint16_t isofid; // 0 = none + uint8_t dfname[16]; + uint8_t dfnamelen; + uint8_t keytype; // DesfireCryptoAlgorithm, one per application +} PACKED desfire_em_app_t; + +// ----------------------------------------------------------------------- file + +// flags bits 0-1 carry the raw 2-bit file communication mode, not a +// DesfireCommunicationMode. Use DesfireFileCommModeToCommMode() to convert. +#define DESFIRE_EM_FILE_COMM_MASK 0x03 +#define DESFIRE_EM_FILE_UNKNOWN (1 << 2) // contents were never read, see below +#define DESFIRE_EM_FILE_LIMCREDIT (1 << 3) // value file, LimitedCredit enabled +#define DESFIRE_EM_FILE_FREEGETVAL (1 << 4) // value file, free GetValue +#define DESFIRE_EM_FILE_DELETED (1 << 5) // tombstone +#define DESFIRE_EM_FILE_DIRTY (1 << 6) // uncommitted writes live in the shadow + +typedef struct { + uint8_t app; // index into the application table + uint8_t num; // file number 0x00..0x1F + uint8_t type; // raw file type byte, 0x00..0x04 for EV1 + uint8_t flags; + uint16_t isofid; // 0 = none + uint16_t rights; // raw access rights word + + uint16_t dataoff; // offset of the committed region + uint16_t datalen; // bytes reserved for it + + // CommitTransaction covers backup data, value and record files; a standard + // data file writes straight through. For the three that are covered, + // shadow_off is a second region of datalen bytes that writes land in until + // CommitTransaction swaps them, or AbortTransaction discards them. Zero + // for standard data files. + uint16_t shadow_off; + + union { + struct { // 0x00 standard, 0x01 backup + uint32_t size; // as created, NOT rounded -- GetFileSettings + } data; // reports this verbatim, measured + struct { // 0x02 value + uint32_t lower; + uint32_t upper; + uint32_t value; + } value; + struct { // 0x03 linear, 0x04 cyclic + uint32_t recordsize; + uint32_t maxrecords; // as created. A cyclic file stores one + uint32_t currecords; // fewer than this, the backup mechanism + } record; // consumes one -- EV1 spec 9.5.9 + } u; +} PACKED desfire_em_file_t; + +// ------------------------------------------------------------------------ key + +// The key algorithm is the application's, so it is not repeated here. A key +// version is readable without knowing the key, so the two are tracked apart: a +// version with no value is the normal shape for a key that was found but never +// recovered, and the simulation must refuse an authentication against it rather +// than authenticate with zeros. +#define DESFIRE_EM_KEY_PRESENT (1 << 0) // we hold the key value +#define DESFIRE_EM_KEY_VERKNOWN (1 << 1) // we read the key version + +typedef struct { + uint8_t app; // index into the application table + uint8_t num; // key number + uint8_t flags; + uint8_t ver; + uint8_t key[DESFIRE_MAX_KEY_SIZE]; +} PACKED desfire_em_key_t; + +//----------------------------------------------------------------------------- +// Notes for whoever implements against this +// +// Tombstones, not compaction. DeleteFile and DeleteApplication set a flag and +// leave the space stranded. That is not a shortcut: a genuine card does not +// give the memory back either. Measured on a DESFire EV2 2K -- 2080 bytes free +// with zero applications before an experiment, 2560 after FormatPICC. Only +// FormatPICC reclaims, and here that is resetting both frontiers. +// +// The unknown flag. A file whose contents could not be read carries +// DESFIRE_EM_FILE_UNKNOWN and its region is reserved but meaningless. The +// simulation must answer an error for it, never zeros. "8 bytes of 00" and "we +// could not read 8 bytes" are different facts and a card image that confuses +// them lies to the reader. +// +// Reservation at CreateFile, in granules: +// standard DESFIRE_EM_ROUNDUP(size) +// backup DESFIRE_EM_ROUNDUP(size) twice, data and shadow +// value one granule twice +// record DESFIRE_EM_ROUNDUP(recordsize * maxrecords) twice +// Reserve the full declared extent, not just the records that exist, so +// WriteRecord never has to grow anything. The json stores only the records +// that exist; eload expands, esave compacts. +// +// This deliberately does not reproduce NXP's own allocator. It is undocumented +// and the numbers do not fit a simple model -- a declared 1024 byte record file +// costs 1088 on real silicon, neither 1x nor 2x. What matters is that +// GetFreeMem is self-consistent and shrinks as the reader writes. +// +// Card capacity. The GetVersion storage size byte codes 2^(n>>1) bytes, but +// that understates what the part actually hands out: a DESFire EV2 2K reports +// storage 0x16, 2048 bytes, and 2560 bytes free when formatted -- measured. So +// the nominal figure is a floor, not the capacity, and cardsize is set to +// whichever is larger of the nominal figure and what the image already holds. +// A dump taken from a real card therefore always fits the card it came from. +// +// Response timing. Everything from SelectApplication onward sits behind the +// ISO14443-4 frame waiting time, which the EV1 ATS sets to FWI 8, 77.33 ms -- +// about 3.7 million ARM cycles at MCK. A software AES block is well under a +// microsecond of that, so responses are computed on demand from this image +// rather than precompiled. The pre-RATS layer is the opposite: ATQA, SAK and +// ATS have no such slack and must be precompiled, as the 14a simulation already +// does. +//----------------------------------------------------------------------------- + +#endif // __DESFIRE_EM_H diff --git a/include/iso18.h b/include/iso18.h index 1fe78de64..b4b2918ca 100644 --- a/include/iso18.h +++ b/include/iso18.h @@ -90,6 +90,8 @@ typedef enum FELICA_COMMAND { // so reading distance and coupling can be measured rather than guessed FELICA_PROBE = (1 << 2), FELICA_RAW = (1 << 3), + // With CONNECT, raw[] holds the two-byte polling system code. + FELICA_SYSTEM_SELECT = (1 << 4), FELICA_APPEND_CRC = (1 << 5), FELICA_NO_SELECT = (1 << 6), FELICA_CLEARTRACE = (1 << 7), diff --git a/include/pm3_cmd.h b/include/pm3_cmd.h index 56f643c35..b1dbf03de 100644 --- a/include/pm3_cmd.h +++ b/include/pm3_cmd.h @@ -276,8 +276,28 @@ typedef struct { // the client accepts a shorter struct from older firmware // PM5 can use this to inform which size they support oo. uint16_t max_cmd_data_size; // device side PM3_CMD_DATA_SIZE + + // Appended in version 11. + // How much emulator memory a card image may use, device side + // CARD_MEMORY_SIZE. The client sizes eload / esave from this instead of + // carrying its own copy of the constant, so a PM5 reporting a larger + // emulator memory needs no client change. + uint16_t em_size; + bool em_allocated : 1; // is a card image resident right now + + // Appended in version 12. + bool compiled_with_bwm : 1; // PM5 built with PLATFORM_EXTRAS=BWM (battery/wireless module) + + // Appended in version 13. + bool compiled_with_cep : 1; // PM5 built with CEP (Flipper Zero, Type-C extended port; on by default, SKIP_CEP=1 to disable) } PACKED capabilities_t; -#define CAPABILITIES_VERSION 9 +// Bump this whenever a command payload changes shape, so a mismatched client and +// firmware refuse to talk instead of misparsing each other. +// 10: CMD_HF_MIFARE_EML_MEMSET gained a flags byte +// 11: capabilities_t gained em_size / em_allocated +// 12: capabilities_t gained compiled_with_bwm +// 13: capabilities_t gained compiled_with_cep +#define CAPABILITIES_VERSION 13 // what a pre-v9 device would have used, it could not tell us #define CAPABILITIES_LEGACY_CMD_DATA_SIZE 512 extern capabilities_t g_pm3_capabilities; @@ -366,7 +386,7 @@ typedef struct { typedef struct { // 64KB SRAM -> 524288 bits(max sample num) < 2^30 - uint32_t samples : +uint32_t samples : LF_SAMPLES_BITS; bool realtime : 1; bool verbose : 1; @@ -541,6 +561,14 @@ typedef struct { // most 4 byte nonces that fit alongside the reply header in one frame #define MFC_MAX_NONCES ((PM3_CMD_DATA_SIZE - sizeof(mf_nonces_resp_t)) / 4) +// ACQ_ENCRYPTED_NONCES does not store bare nonces. It stores pairs: two 4 byte +// encrypted nonces followed by one byte holding both their encrypted parity +// nibbles, high nibble first. num_nonces in the reply counts nonces, so the +// payload is always (num_nonces / 2) * MFC_NONCE_PAIR_SIZE bytes and +// num_nonces is always even. +#define MFC_NONCE_PAIR_SIZE 9 +#define MFC_MAX_NONCE_PAIRS ((PM3_CMD_DATA_SIZE - sizeof(mf_nonces_resp_t)) / MFC_NONCE_PAIR_SIZE) + // CMD_HF_MIFARE_CHKKEYS_FAST payload. // Replaces three bit-packed oldargs: // arg0 = sectorcnt | firstchunk<<8 | lastchunk<<12 | singlesector_params<<16 @@ -587,6 +615,15 @@ typedef struct { uint8_t data[]; } PACKED mf_chinese_blk_t; +// CMD_HF_MIFARE_CIDENT payload. +// key/keytype are only read when is_mfc is set, but the device reads the whole +// struct, so senders must always transmit all of it +typedef struct { + uint8_t is_mfc; + uint8_t keytype; + uint8_t key[6]; +} PACKED mf_chinese_ident_t; + // CMD_HF_MIFARE_GEN3UID payload typedef struct { uint8_t uidlen; @@ -882,11 +919,112 @@ typedef struct { #define CMD_PM5_BWM_SET_CAP 0x0179 // PM5, enable/disable BWM battery charging (AW32001E CEB). Used by `hw bwm charge`. #define CMD_PM5_BWM_CHARGE_EN 0x017A -// PM5, toggle automatic power-off on USB unplug. Used by `hw bwm autooff`. +// PM5, automatic power-off: USB unplug, and idle on battery. Used by `hw bwm autooff`. +// req: [action:u8][enabled:u8][idle_s:u32 LE][unplug:u8, optional] (0xFF / +// 0xFFFFFFFF = keep); a 1-byte req is the old enable flag. resp: +// bwm_autooff_status_t. Persisted on the BWM. #define CMD_PM5_BWM_AUTOOFF 0x017B +// Both actions are non-zero: an old firmware reads byte 0 as the enable flag, +// so a new client can only ever leave it enabled. +#define BWM_AUTOOFF_ACTION_GET 0x01 +#define BWM_AUTOOFF_ACTION_SET 0x02 +#define BWM_AUTOOFF_KEEP_U8 0xFF +#define BWM_AUTOOFF_KEEP_U32 0xFFFFFFFFUL +#define BWM_AUTOOFF_IDLE_MAX_S (7UL * 24 * 3600) // ms tick wraps at 49 days +// Reply of CMD_PM5_BWM_AUTOOFF: the setting plus the live inputs of the idle decision. +typedef struct { + uint8_t enabled; + uint32_t idle_s; // 0 = idle trigger off + uint32_t idle_now_s; // since the last interaction + uint8_t link; // tracked wireless client (LINK_STATE broadcast) + uint8_t ble_live; // module's answer right now: 0 off 1 advertising 2 connected, 0xFF no answer + uint8_t usb; // VUSB now + uint8_t usb_seen; // VUSB seen since boot (arms the unplug trigger) + uint8_t persisted; // 1 = the setting was saved on the module, 0 = module absent or too old + uint8_t unplug; // 1 = power off when USB is pulled (default); 0 = an unplug only restarts the idle clock +} PACKED bwm_autooff_status_t; #define CMD_PM5_BWM_WIFI 0x017C #define CMD_PM5_BWM_SET_VCHG 0x017D #define CMD_PM5_BWM_ESP_OTA 0x017E +#define CMD_PM5_BWM_BLE_NAME 0x017F // payload: [action:u8][name bytes if SET] +#define BWM_BLE_NAME_ACTION_GET 0x00 // resp: current BLE device name string +#define BWM_BLE_NAME_ACTION_SET 0x01 // req: name bytes follow the action byte; BWM reboots to apply +#define BWM_BLE_NAME_MAX_LEN 15 // usable chars; ESP name buffer is 16 incl NUL +// PM5, toggle the power-save idle (48 MHz + WFI when idle). Used by `hw powersave`. +#define CMD_PM5_POWERSAVE 0x0180 +// PM5, BWM power-save switch on the ESP (DFS, light sleep, low-duty advertising; +// persisted on the BWM). Used by `hw bwm powersave`. +#define CMD_PM5_BWM_POWERSAVE 0x0181 // payload: [action:u8][state:u8 if SET]; resp: u8 applied state +#define BWM_POWERSAVE_ACTION_GET 0x00 +#define BWM_POWERSAVE_ACTION_SET 0x01 +// PM5, BWM WiFi modem power-save type (persisted on the ESP). Used by `hw bwm wifipower`. +#define CMD_PM5_BWM_WIFI_PS 0x0182 // payload: [action:u8][mode:u8 if SET]; resp: [mode:u8][wifi_state:u8, 0xFF = WiFi off] +#define BWM_WIFI_PS_ACTION_GET 0x00 +#define BWM_WIFI_PS_ACTION_SET 0x01 +#define BWM_WIFI_PS_NONE 0 // modem never sleeps +#define BWM_WIFI_PS_MIN 1 // sleeps between DTIM beacons (ESP-IDF default) +#define BWM_WIFI_PS_MAX 2 // sleeps for the listen interval +#define BWM_WIFI_STATE_OFF 0xFF // wifi_state byte: WiFi stack down (BLE-only) +// PM5, BWM BLE settings (`hw bwm ble`). req: [action:u8][args]; resp: bwm_ble_status_t +// on success. Unknown fields (module firmware without the command) read 0xFF. +#define CMD_PM5_BWM_BLE 0x0183 +#define BWM_BLE_ACTION_STATUS 0x00 +#define BWM_BLE_ACTION_ENABLE 0x01 // [on:u8], persisted on the module +#define BWM_BLE_ACTION_PAIRING 0x02 // [on:u8], persisted; restarts the stack (drops a BLE client) +#define BWM_BLE_ACTION_KEY 0x03 // [6 ASCII digits], persisted +#define BWM_BLE_ACTION_FORGET 0x04 // [idx:u8, 0xFF = all bonded devices] +#define BWM_BLE_ACTION_TXPOWER 0x05 // [type:u8 0 adv 1 conn][level:u8 esp_power_level_t 0..15, -24 dBm + 3/step, 15 = 20 dBm] +#define BWM_BLE_BONDED_MAX 8 +typedef struct { + uint8_t enabled; // persisted switch + uint8_t state; // 0 off, 1 advertising, 2 client connected + uint8_t bonding; // 1 = pairing with passkey required, SPP characteristic encrypted + char passkey[6]; // ASCII digits, not NUL-terminated + uint8_t txp_adv; // esp_power_level_t index + uint8_t txp_conn; + uint8_t addr[6]; // as the module reports it (big-endian display order) + char name[16]; // NUL-padded + uint8_t bonded_count; + uint8_t bonded[BWM_BLE_BONDED_MAX][7]; // addr[6] + type, first bonded_count valid +} PACKED bwm_ble_status_t; +// Compact battery telemetry shared by `hw status`'s underlying data source and +// any client (e.g. the Flipper Zero FAP) wanting raw numbers instead of free-text +// Dbprintf lines. All fields zeroed if bwm_present is false or gauge_ok is false. +typedef struct { + bool bwm_present; + bool gauge_ok; + uint16_t soc_pct; + uint16_t voltage_mv; + int16_t current_ma; // +charge / -discharge + uint16_t remaining_mah; + uint16_t full_charge_mah; + uint16_t design_cap_mah; + int16_t temp_c10; // tenths of a degree C + uint8_t charger_fault; // 0 = none, else AW32001E REG09 bits masked 0x3F + uint8_t charge_status; // 0=not charging,1=pre-charge,2=charging,3=done + uint8_t health_pct; +} PACKED bwm_battery_info_t; +// PM5, read compact BWM battery telemetry (bwm_battery_info_t). Used by `hw status`'s +// underlying data source and by clients (e.g. the Flipper Zero FAP) that want the raw +// numbers instead of hw status's free-text Dbprintf lines. +#define CMD_PM5_BWM_GET_BATTERY 0x0184 +// PM5, live hardware-status snapshot (CEP handshake state, battery telemetry, +// firmware version) for the Flipper Zero FAP's status page and any future +// client. Always answers PM3_SUCCESS with every field it can - fields for a +// feature this build doesn't have (no WITH_CEP, no WITH_BWM_STATUS) read as +// zero/false rather than the command failing. A client that also wants to +// distinguish "zero" from "not built" should check CMD_CAPABILITIES' +// compiled_with_cep/compiled_with_bwm first. +// req: none. resp: cep_status_t. +#define CMD_CEP_STATUS 0x0185 +typedef struct { + uint8_t cep_active; // cep_is_active(): handshake complete, SPI transport live + bwm_battery_info_t battery; // bwm_read_battery_info(); all-zero if WITH_BWM_STATUS not built + char fw_version[24]; // g_version_information.gitversion, NUL-terminated, may truncate + // Appended in a future version once cep_is_attached() lands (PR #3687, + // not yet merged): a cep_attached byte distinguishing "physically + // present, handshake not yet complete" from "active". +} PACKED cep_status_t; #define BWM_OTA_ACTION_BEGIN 0x00 #define BWM_OTA_ACTION_WRITE 0x01 #define BWM_OTA_ACTION_END 0x02 @@ -993,6 +1131,8 @@ typedef struct { #define CMD_HF_ISO15693_CSETUID 0x0316 #define CMD_HF_ISO15693_CSETUID_V2 0x0333 +#define CMD_HF_ISO15693_CSETUID_V3 0x0334 +#define CMD_HF_ISO15693_CFINALIZE_V3 0x0335 #define CMD_LF_SNIFF_RAW_ADC 0x0360 @@ -1154,10 +1294,12 @@ typedef struct { #define CMD_HF_DESFIRE_READER 0x072c #define CMD_HF_DESFIRE_INFO 0x072d #define CMD_HF_DESFIRE_COMMAND 0x072e +#define CMD_HF_DESFIRE_SIMULATE 0x072f #define CMD_HF_MIFARE_NACK_DETECT 0x0730 #define CMD_HF_MIFARE_STATIC_NONCE 0x0731 #define CMD_HF_MIFARE_STATIC_ENCRYPTED_NONCE 0x0732 +#define CMD_HF_DESFIRE_SIM_TEST 0x0733 // MFU OTP TearOff #define CMD_HF_MFU_OTP_TEAROFF 0x0740 @@ -1176,6 +1318,7 @@ typedef struct { // For ThinFilm Kovio #define CMD_HF_THINFILM_READ 0x0810 #define CMD_HF_THINFILM_SIMULATE 0x0811 +#define CMD_HF_THINFILM_SNIFF 0x0812 // For Atmel CryptoRF #define CMD_HF_CRYPTORF_SIM 0x0820 @@ -1250,6 +1393,15 @@ typedef struct { (len == 4 ? FLAG_4B_UID_IN_DATA : (len == 7 ? FLAG_7B_UID_IN_DATA : (len == 10 ? FLAG_10B_UID_IN_DATA : FLAG_UID_IN_EMUL)))) #define IS_FLAG_UID_IN_EMUL(flags) ((flags & FLAG_MASK_UID) == FLAG_UID_IN_EMUL) +// CMD_HF_MIFARE_EML_MEMSET flags +// a whole-dump upload sets this on its first chunk so the device zeroes what was +// there before writing. A partial update (esetblk) never sets it. +#define MFEMUL_MEMSET_CLEAR 0x01 + +// "hf 14a antifuzz" - which flavour of anticollision abuse to run +#define ANTIFUZZ_MODE_CASCADE 0x00 // grow the reader's UID past cascade level 3 +#define ANTIFUZZ_MODE_COLLISION 0x01 // every answered bit is a collision + // internal constants, use the function macros instead #define MIFARE_4K_MAX_BYTES 4096 #define MIFARE_2K_MAX_BYTES 2048 @@ -1436,6 +1588,9 @@ typedef struct { /* Set if this device understands the chip type command */ #define DEVICE_INFO_FLAG_UNDERSTANDS_CHIP_TYPE (1<<8) +/* Bootrom de-frames BWM DATA_FORWARD as a byte stream (OLD cmds may span frames) */ +#define DEVICE_INFO_FLAG_UNDERSTANDS_BWM_STREAM (1 << 9) + #define BL_VERSION_MAJOR(version) ((uint32_t)(version) >> 22) #define BL_VERSION_MINOR(version) (((uint32_t)(version) >> 12) & 0x3ff) #define BL_VERSION_PATCH(version) ((uint32_t)(version) & 0xfff) diff --git a/include/pmflash.h b/include/pmflash.h index 7969ac4d9..31d895b10 100644 --- a/include/pmflash.h +++ b/include/pmflash.h @@ -100,4 +100,8 @@ typedef struct { uint8_t pages64k; } PACKED spi_flash_t; +// SPIFFS errno values the client has to name when the device reports a failed +// write. Mirrors armsrc/spiffs.h, which is device side only +#define SPIFFS_ERR_FULL_RDV (-10001) + #endif // __PMFLASH_H diff --git a/include/protocols.h b/include/protocols.h index c9f40e843..fda9b4dd2 100644 --- a/include/protocols.h +++ b/include/protocols.h @@ -726,6 +726,8 @@ ISO 7816-4 Basic interindustry commands. For command APDU's. #define MFDES_S_SIGNATURE 0x90 #define MFDES_S_ADDITIONAL_FRAME 0xAF +#define MFDES_S_OPERATION_OK 0x00 +#define MFDES_S_NO_CHANGES 0x0C #define MFDES_E_OUT_OF_EEPROM 0x0E #define MFDES_E_ILLEGAL_COMMAND_CODE 0x1C #define MFDES_E_INTEGRITY_ERROR 0x1E diff --git a/recovery/Makefile b/recovery/Makefile index 22425bb1e..d3f23ee19 100644 --- a/recovery/Makefile +++ b/recovery/Makefile @@ -1,3 +1,15 @@ + +# This Makefile might have been called directly, not via the root Makefile, so: +ifeq ($(PLTNAME),) + PLATFORM_FILE ?= ../Makefile.platform + -include $(PLATFORM_FILE) + -include ../.Makefile.options.cache + include ../common_arm/Makefile.hal + ifeq ($(PLATFORM_CHANGED), true) + $(error platform definitions have been changed, please "make clean" at the root of the project) + endif +endif + include ../common_arm/Makefile.common INSTALLFW = recovery.bin diff --git a/tools/build_all_firmwares.sh b/tools/build_all_firmwares.sh index 091afa270..cdc7b533c 100755 --- a/tools/build_all_firmwares.sh +++ b/tools/build_all_firmwares.sh @@ -22,7 +22,7 @@ echo "Destination: ${DEST:=firmware}" echo "Produce stats?: ${STATS:=false}" # Which parts to skip for the 256kb version? -SKIPS256="SKIP_HITAG=1 SKIP_LEGICRF=1 SKIP_FELICA=1 SKIP_EM4x50=1 SKIP_ISO14443b=1 SKIP_NFCBARCODE=1 SKIP_ZX8211=1 SKIP_LF=1" +SKIPS256="SKIP_HITAG=1 SKIP_LEGICRF=1 SKIP_FELICA=1 SKIP_EM4x50=1 SKIP_EM4x70=1 SKIP_ISO14443b=1 SKIP_NFCBARCODE=1 SKIP_ZX8211=1 SKIP_LF=1 SKIP_DESFIRE_SIM=1" make $MKFLAGS bootrom || exit 1 chmod 644 bootrom/obj/bootrom.elf @@ -32,11 +32,11 @@ mv bootrom/obj/bootrom.elf "$DEST/PM3BOOTROM.elf" # cf armsrc/Standalone/Makefile.hal STANDALONE_MODES=(LF_SKELETON) STANDALONE_MODES+=(LF_EM4100EMUL LF_EM4100RSWB LF_EM4100RSWW LF_EM4100RWC LF_HIDBRUTE LF_HIDFCBRUTE LF_ICEHID LF_MULTIHID LF_NEDAP_SIM LF_NEXID LF_PROXBRUTE LF_PROX2BRUTE LF_SAMYRUN LF_THAREXDE) -STANDALONE_MODES+=(HF_14ASNIFF HF_14BSNIFF HF_15SNIFF HF_15SIM HF_AVEFUL HF_BOG HF_CARDHOPPER HF_COLIN HF_DOEGOX_AUTH0 HF_DOEGOX_COMMIT HF_CRAFTBYTE HF_ICECLASS HF_LEGIC HF_LEGICSIM HF_MATTYRUN HF_MFCSIM HF_MSDSAL HF_REBLAY HF_ST25_TEAROFF HF_TCPRST HF_TMUDFORD HF_UNISNIFF HF_YOUNG HF_EMVPNG) +STANDALONE_MODES+=(HF_14ASNIFF HF_14BSNIFF HF_15SIM HF_15SNIFF HF_AVEFUL HF_BOG HF_CARDHOPPER HF_COLIN HF_CRAFTBYTE HF_DOEGOX_AUTH0 HF_DOEGOX_COMMIT HF_EMVPNG HF_ICECLASS HF_LEGIC HF_LEGIC_RDV4 HF_LEGICSIM HF_MATTYRUN HF_MFCSIM HF_MSDSAL HF_REBLAY HF_ST25_TEAROFF HF_TCPRST HF_TMUDFORD HF_UNISNIFF HF_YOUNG) STANDALONE_MODES+=(DANKARMULTI) STANDALONE_MODES_REQ_BT=(HF_CARDHOPPER HF_REBLAY) STANDALONE_MODES_REQ_SMARTCARD=() -STANDALONE_MODES_REQ_FLASH=(LF_HIDFCBRUTE LF_ICEHID LF_NEXID LF_THAREXDE HF_BOG HF_COLIN HF_ICECLASS HF_LEGICSIM HF_MFCSIM HF_ST25_TEAROFF) +STANDALONE_MODES_REQ_FLASH=(LF_HIDFCBRUTE LF_ICEHID LF_NEXID LF_THAREXDE HF_BOG HF_COLIN HF_ICECLASS HF_LEGIC_RDV4 HF_LEGICSIM HF_MFCSIM HF_ST25_TEAROFF) # PM3GENERIC 256kb, no flash, need to skip some parts to reduce size diff --git a/tools/check_json_uniq.py b/tools/check_json_uniq.py new file mode 100755 index 000000000..01df3ec55 --- /dev/null +++ b/tools/check_json_uniq.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +"""Check the AID resource files for duplicate entries. + +client/resources/aid_desfire.json and aidlist.json are looked up by AID, and +the lookup returns the FIRST match (see find_aiddf_entry() in +client/src/mifare/aiddesfire.c). A second entry with the same AID is therefore +dead data: nothing can ever print it. + +One exception is legitimate. aidsearch.c matches a card's actual response +against "ResponseRegex" to choose between entries that share an AID, so a group +whose members all carry a distinct ResponseRegex is disambiguated at runtime and +is allowed. That is how Apple, Google and Samsung all live on OSE.VAS.01. + +Run with no arguments from anywhere in the tree, or pass files explicitly. +Exits non-zero when a real duplicate is found. +""" + +import json +import os +import sys +from collections import defaultdict + +DEFAULT_FILES = [ + "client/resources/aid_desfire.json", + "client/resources/aidlist.json", +] + +DISAMBIGUATOR = "ResponseRegex" + + +def repo_root(): + here = os.path.abspath(os.path.dirname(__file__)) + return os.path.dirname(here) + + +def check(path): + """Return the number of offending AID groups in one file.""" + try: + with open(path, encoding="utf-8") as fd: + data = json.load(fd) + except FileNotFoundError: + print(" %s: not found, skipped" % path) + return 0 + except json.JSONDecodeError as exc: + print(" %s: invalid json, line %d: %s" % (path, exc.lineno, exc.msg)) + return 1 + + if not isinstance(data, list): + print(" %s: root is not an array" % path) + return 1 + + groups = defaultdict(list) + for idx, entry in enumerate(data): + if not isinstance(entry, dict) or "AID" not in entry: + continue + groups[str(entry["AID"]).upper()].append((idx, entry)) + + bad = 0 + allowed = 0 + + for aid, members in sorted(groups.items()): + if len(members) < 2: + continue + + regexes = [e.get(DISAMBIGUATOR, "") for _, e in members] + if all(regexes) and len(set(regexes)) == len(regexes): + allowed += 1 + print(" %s: AID %s appears %d times, disambiguated by %s ( allowed )" + % (path, aid, len(members), DISAMBIGUATOR)) + continue + + bad += 1 + print(" %s: AID %s appears %d times and is NOT disambiguated" % (path, aid, len(members))) + for idx, entry in members: + print(" index %-5d %-34s %s" % (idx, + entry.get("Name", ""), + entry.get("Vendor", ""))) + print(" only the first is reachable. Merge them, or give each a distinct %s" + % DISAMBIGUATOR) + + if len(groups): + print(" %s: %d entries, %d duplicate group(s) allowed, %d rejected" + % (path, len(data), allowed, bad)) + return bad + + +def main(): + files = sys.argv[1:] + if not files: + root = repo_root() + files = [os.path.join(root, f) for f in DEFAULT_FILES] + + print("Checking AID resource files for duplicate entries") + total = sum(check(f) for f in files) + + if total: + print("\nFAIL: %d duplicate AID group(s)" % total) + return 1 + + print("\nok") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/dfc_converter.py b/tools/dfc_converter.py new file mode 100755 index 000000000..0b27f226e --- /dev/null +++ b/tools/dfc_converter.py @@ -0,0 +1,459 @@ +#!/usr/bin/env python3 +"""Convert DESFire credentials between DFC v4 and Proxmark3 mfdes v1 JSON. + +DFC is the interchange format used by the DESFire Compatible app for Flipper +Zero and Chameleon Ultra. Proxmark3 loads the JSON result with `hf mfdes eload`. +Only features represented by both formats are converted. +""" + +import argparse +import json +import pathlib +import re +import sys + + +class ConversionError(ValueError): + """Input cannot be represented in the destination format.""" + + +FILE_TYPES = { + "Standard Data": (0, "standard"), + "Backup Data": (1, "backup"), + "Value": (2, "value"), + "Linear Record": (3, "linear_record"), + "Cyclic Record": (4, "cyclic_record"), +} +FILE_TYPES_BY_RAW = {raw: (name, token) for name, (raw, token) in FILE_TYPES.items()} +COMM_BY_RAW = {0: "plain", 1: "mac", 2: "plain_rfu", 3: "encrypt"} +COMM_BY_TOKEN = {token: raw for raw, token in COMM_BY_RAW.items()} +STORAGE_CODES = {2048: 0x16, 4096: 0x18, 8192: 0x1A} +GENERATION_VERSION = { + "EV1": (0x01, 0x00, 0x01, 0x04), + "EV2": (0x12, 0x00, 0x02, 0x00), + "EV3": (0x33, 0x00, 0x03, 0x00), +} +MAJOR_GENERATION = {0x01: "EV1", 0x12: "EV2", 0x42: "EV2", 0x22: "EV2", 0x33: "EV3"} +KEY_LENGTHS = {"des": 8, "2tdea": 16, "3tdea": 24, "aes": 16} +HEX_RE = re.compile(r"(?:[0-9A-F]{2})(?: [0-9A-F]{2})*") + + +def compact_hex(value, field, lengths=None): + if not isinstance(value, str): + raise ConversionError(f"{field}: expected a hexadecimal string") + compact = value.replace(" ", "").upper() + if not compact or len(compact) % 2 or re.fullmatch(r"[0-9A-F]+", compact) is None: + raise ConversionError(f"{field}: invalid hexadecimal octets") + if lengths is not None and len(compact) // 2 not in lengths: + expected = " or ".join(str(n) for n in lengths) + raise ConversionError(f"{field}: expected {expected} octets") + return compact + + +def spaced_hex(value, field, lengths=None): + compact = compact_hex(value, field, lengths) + return " ".join(compact[i:i + 2] for i in range(0, len(compact), 2)) + + +def parse_integer(value, field, minimum=None, maximum=None): + try: + number = int(value) if isinstance(value, int) else int(value, 10) + except (TypeError, ValueError) as exc: + raise ConversionError(f"{field}: expected a decimal integer") from exc + if minimum is not None and number < minimum: + raise ConversionError(f"{field}: value is below {minimum}") + if maximum is not None and number > maximum: + raise ConversionError(f"{field}: value is above {maximum}") + return number + + +def parse_dfc_fields(text): + fields = {} + order = [] + for line_number, raw in enumerate(text.splitlines(), 1): + if not raw or raw.startswith("#"): + continue + if raw.endswith(" ") or ": " not in raw: + raise ConversionError(f"line {line_number}: expected 'Key: Value'") + key, value = raw.split(": ", 1) + if not key or key.strip() != key or not value: + raise ConversionError(f"line {line_number}: malformed field") + if key in fields: + raise ConversionError(f"line {line_number}: duplicate field {key!r}") + fields[key] = value + order.append(key) + if order[:2] != ["Filetype", "Version"]: + raise ConversionError("Filetype and Version must be the first two fields") + return fields + + +class DfcReader: + def __init__(self, text): + self.fields = parse_dfc_fields(text) + + def take(self, name, required=True): + value = self.fields.pop(name, None) + if value is None and required: + raise ConversionError(f"missing required field {name!r}") + return value + + def integer(self, name, minimum=None, maximum=None, required=True): + value = self.take(name, required) + if value is None: + return None + return parse_integer(value, name, minimum, maximum) + + def hexa(self, name, lengths=None, required=True): + value = self.take(name, required) + if value is None: + return None + if HEX_RE.fullmatch(value) is None: + raise ConversionError(f"{name}: expected uppercase hexadecimal octets") + return compact_hex(value, name, lengths) + + def token(self, name, allowed): + value = self.take(name) + if value not in allowed: + raise ConversionError(f"{name}: unsupported value {value!r}") + return value + + def flag(self, name, required=True): + value = self.take(name, required) + if value is None: + return None + if value not in ("0", "1"): + raise ConversionError(f"{name}: expected 0 or 1") + return value == "1" + + +def key_type(ks2, keys): + keys = list(keys) + selector = int(ks2, 16) & 0xC0 + if selector == 0x80: + return "aes" + if selector == 0x40: + return "3tdea" + if keys and len(keys[0]["Key"]) == 16: + return "des" + return "2tdea" + + +def read_keys(reader, prefix, ks2): + count = reader.integer(f"{prefix} Key Count", 0, 14) + keys = {} + expected_length = {0x40: 24, 0x80: 16}.get(int(ks2, 16) & 0xC0, 16) + for index in range(count): + name = f"{prefix} Key {index:02X}" + keys[str(index)] = { + "Key": reader.hexa(name, (expected_length,)), + "Version": reader.hexa(f"{name} Version", (1,)), + } + return keys + + +def read_files(reader, prefix): + files = {} + count = reader.integer(f"{prefix} File Count", 0, 32) + for index in range(count): + base = f"{prefix} File {index:02X}" + number = reader.hexa(f"{base} Number", (1,)) + type_name = reader.token(f"{base} Type", set(FILE_TYPES)) + raw, token = FILE_TYPES[type_name] + comm = reader.hexa(f"{base} Communication Settings", (1,)) + comm_value = int(comm, 16) + if comm_value not in COMM_BY_RAW: + raise ConversionError(f"{base} Communication Settings: unsupported value {comm}") + item = { + "Type": token, + "TypeRaw": f"{raw:02X}", + "CommMode": COMM_BY_RAW[comm_value], + "AccessRights": reader.hexa(f"{base} Access Rights", (2,)), + } + iso_id = reader.hexa(f"{base} ISO File ID", (2,), required=False) + if iso_id is not None: + item["ISOFileID"] = iso_id + if raw in (0, 1): + item["FileSize"] = reader.integer(f"{base} Size", 1, 0xFFFFFF) + data = reader.hexa(f"{base} Data", required=False) + complete = reader.flag(f"{base} Data Complete") + if complete and (data is None or len(data) // 2 != item["FileSize"]): + raise ConversionError(f"{base}: complete data must match the file size") + item["Read"] = data is not None + if data is not None: + if len(data) // 2 > item["FileSize"]: + raise ConversionError(f"{base}: data is longer than the file") + item["Data"] = data + elif raw == 2: + item["LowerLimit"] = reader.integer(f"{base} Value Lower Limit", -0x80000000, 0x7FFFFFFF) + item["UpperLimit"] = reader.integer(f"{base} Value Upper Limit", -0x80000000, 0x7FFFFFFF) + item["Value"] = reader.integer(f"{base} Value", item["LowerLimit"], item["UpperLimit"]) + item["LimitedCredit"] = reader.hexa(f"{base} Limited Credit", (1,)) + item["Read"] = True + else: + item["RecordSize"] = reader.integer(f"{base} Record Size", 1, 0xFFFFFF) + item["MaxRecords"] = reader.integer(f"{base} Max Records", 1, 0xFFFFFF) + item["CurRecords"] = reader.integer(f"{base} Record Count", 0, item["MaxRecords"]) + records = {} + record_index = 0 + while f"{base} Record {record_index:02X}" in reader.fields: + records[str(record_index)] = reader.hexa( + f"{base} Record {record_index:02X}", (item["RecordSize"],) + ) + record_index += 1 + complete = reader.flag(f"{base} Record Complete") + if complete and len(records) != item["CurRecords"]: + raise ConversionError(f"{base}: complete records must match Record Count") + item["Read"] = complete + item["Records"] = records + files[number] = item + return files + + +def version_frames(generation, storage): + if generation not in GENERATION_VERSION: + raise ConversionError(f"Card Generation: {generation} is not representable") + storage_code = STORAGE_CODES.get(storage) + if storage_code is None: + raise ConversionError(f"Card Storage: unsupported capacity {storage}") + hw_major, hw_minor, sw_major, sw_minor = GENERATION_VERSION[generation] + return ( + f"040101{hw_major:02X}{hw_minor:02X}{storage_code:02X}05", + f"040101{sw_major:02X}{sw_minor:02X}{storage_code:02X}05", + ) + + +def dfc_to_json(text): + reader = DfcReader(text) + if reader.take("Filetype") != "DFC Credential" or reader.take("Version") != "4": + raise ConversionError("only DFC Credential version 4 is supported") + generation = reader.token("Card Generation", set(GENERATION_VERSION)) + storage = reader.integer("Card Storage", 1) + uid = reader.hexa("UID", (4, 7, 10)) + reader.token("UID Provenance", {"Real", "Random", "Unknown"}) + signature = reader.hexa("Card Static Signature", (56,), required=False) + picc_ks1 = reader.hexa("PICC Key Settings 1", (1,)) + picc_ks2 = reader.hexa("PICC Key Settings 2", (1,)) + reader.token("PICC Authentication Mode", {"D40", "ISO", "AES"}) + picc_keys = read_keys(reader, "PICC", picc_ks2) + + unsupported = ( + "PICC Random ID", "PICC Format Disabled", "PICC SM Disable", + "PICC EV2 Card Capabilities", "PICC Proximity Key", + "PICC Virtual Card Installation ID", "PICC DAM Authentication Key", + ) + present = [name for name in unsupported if name in reader.fields] + if present: + raise ConversionError(f"{present[0]} has no mfdes v1 representation") + ats = reader.hexa("PICC ATS", required=False) or "067577810280" + sak = reader.hexa("PICC SAK", (1,), required=False) or "20" + atqa = reader.hexa("PICC ATQA", (2,), required=False) or "4403" + if reader.integer("PICC File Count", 0, 32) != 0: + raise ConversionError("PICC-level files have no mfdes v1 representation") + + applications = { + "000000": { + "KeySettings": picc_ks1, + "NumKeysRaw": picc_ks2, + "NumKeys": int(picc_ks2, 16) & 0x1F, + "KeyType": key_type(picc_ks2, picc_keys.values()), + "Authenticated": bool(picc_keys), + "Keys": picc_keys, + } + } + app_count = reader.integer("Application Count", 0, 255) + for index in range(app_count): + prefix = f"Application {index:02X}" + aid = reader.hexa(f"{prefix} AID", (3,)) + iso_id = reader.hexa(f"{prefix} ISO File ID", (2,), required=False) + df_name = reader.hexa(f"{prefix} DF Name", required=False) + ks1 = reader.hexa(f"{prefix} Key Settings 1", (1,)) + ks2 = reader.hexa(f"{prefix} Key Settings 2", (1,)) + reader.token(f"{prefix} Authentication Mode", {"D40", "ISO", "AES"}) + if f"{prefix} Key Set Count" in reader.fields: + raise ConversionError(f"{prefix}: key sets have no mfdes v1 representation") + keys = read_keys(reader, prefix, ks2) + app = { + "KeySettings": ks1, + "NumKeysRaw": ks2, + "NumKeys": int(ks2, 16) & 0x1F, + "KeyType": key_type(ks2, keys.values()), + "Authenticated": bool(keys), + "Keys": keys, + "Files": read_files(reader, prefix), + } + if iso_id is not None: + app["ISOFileID"] = iso_id + if df_name is not None: + app["DFName"] = df_name + applications[aid] = app + + if reader.fields: + name = sorted(reader.fields)[0] + raise ConversionError(f"{name}: unsupported DFC field") + version_hw, version_sw = version_frames(generation, storage) + card = { + "UID": uid, + "ATQA": atqa, + "SAK": sak, + "ATS": ats, + "VersionHW": version_hw, + "VersionSW": version_sw, + "VersionProd": uid[:14].ljust(14, "0") + "00000000000124", + } + if signature is not None: + card["Signature"] = signature + return { + "Created": "proxmark3 dfc_converter", + "FileType": "mfdes v1", + "Version": 1, + "Card": card, + "Applications": applications, + } + + +def append_keys(lines, prefix, app): + keys = app.get("Keys", {}) + known = [] + for index in range(14): + item = keys.get(str(index)) + if not item or "Key" not in item: + break + known.append(item) + lines.append(f"{prefix} Key Count: {len(known)}") + key_type_name = app.get("KeyType", "2tdea") + if key_type_name not in KEY_LENGTHS: + raise ConversionError(f"{prefix} KeyType: unsupported value {key_type_name!r}") + for index, item in enumerate(known): + name = f"{prefix} Key {index:02X}" + lines.append(f"{name}: {spaced_hex(item['Key'], name, (KEY_LENGTHS[key_type_name],))}") + version = item.get("Version", "00") + lines.append(f"{name} Version: {spaced_hex(version, name + ' Version', (1,))}") + + +def append_files(lines, prefix, app): + files = app.get("Files", {}) + lines.append(f"{prefix} File Count: {len(files)}") + for index, (number, item) in enumerate(sorted(files.items(), key=lambda pair: int(pair[0], 16))): + base = f"{prefix} File {index:02X}" + raw = int(compact_hex(item.get("TypeRaw", ""), base + " TypeRaw", (1,)), 16) + if raw not in FILE_TYPES_BY_RAW: + raise ConversionError(f"{base}: file type {raw:02X} has no DFC v4 representation") + type_name, _ = FILE_TYPES_BY_RAW[raw] + comm_token = item.get("CommMode") + if comm_token not in COMM_BY_TOKEN: + raise ConversionError(f"{base} CommMode: unsupported value {comm_token!r}") + lines.extend([ + f"{base} Number: {spaced_hex(number, base + ' Number', (1,))}", + f"{base} Type: {type_name}", + f"{base} Communication Settings: {COMM_BY_TOKEN[comm_token]:02X}", + f"{base} Access Rights: {spaced_hex(item['AccessRights'], base + ' Access Rights', (2,))}", + ]) + if "ISOFileID" in item: + lines.append(f"{base} ISO File ID: {spaced_hex(item['ISOFileID'], base + ' ISO File ID', (2,))}") + if raw in (0, 1): + size = parse_integer(item.get("FileSize"), base + " FileSize", 1, 0xFFFFFF) + lines.append(f"{base} Size: {size}") + data = item.get("Data") if item.get("Read") else None + if data is not None: + lines.append(f"{base} Data: {spaced_hex(data, base + ' Data')}") + complete = data is not None and len(compact_hex(data, base + " Data")) // 2 == size + lines.append(f"{base} Data Complete: {int(complete)}") + elif raw == 2: + for field, label in (("LowerLimit", "Value Lower Limit"), ("UpperLimit", "Value Upper Limit"), ("Value", "Value")): + lines.append(f"{base} {label}: {parse_integer(item.get(field), base + ' ' + field, -0x80000000, 0x7FFFFFFF)}") + lines.append(f"{base} Limited Credit: {spaced_hex(item['LimitedCredit'], base + ' Limited Credit', (1,))}") + else: + record_size = parse_integer(item.get("RecordSize"), base + " RecordSize", 1, 0xFFFFFF) + max_records = parse_integer(item.get("MaxRecords"), base + " MaxRecords", 1, 0xFFFFFF) + cur_records = parse_integer(item.get("CurRecords"), base + " CurRecords", 0, max_records) + lines.extend([f"{base} Record Size: {record_size}", f"{base} Max Records: {max_records}", f"{base} Record Count: {cur_records}"]) + records = item.get("Records", {}) + for record_index, record in sorted(records.items(), key=lambda pair: int(pair[0])): + lines.append(f"{base} Record {int(record_index):02X}: {spaced_hex(record, base + ' Record', (record_size,))}") + lines.append(f"{base} Record Complete: {int(bool(item.get('Read')) and len(records) == cur_records)}") + + +def auth_mode(app): + key_type_name = app.get("KeyType", "2tdea") + if key_type_name == "aes": + return "AES" + ks2 = int(compact_hex(app.get("NumKeysRaw", "00"), "NumKeysRaw", (1,)), 16) + return "ISO" if ks2 & 0x20 else "D40" + + +def json_to_dfc(image): + if image.get("FileType") != "mfdes v1" or image.get("Version") != 1: + raise ConversionError("only Proxmark3 mfdes v1 JSON is supported") + card = image.get("Card", {}) + uid = compact_hex(card.get("UID", ""), "Card.UID", (4, 7, 10)) + version_hw = compact_hex(card.get("VersionHW", ""), "Card.VersionHW", (7,)) + generation = MAJOR_GENERATION.get(int(version_hw[6:8], 16)) + if generation is None: + raise ConversionError(f"Card.VersionHW: unsupported generation byte {version_hw[6:8]}") + storage = 1 << (int(version_hw[10:12], 16) >> 1) + applications = image.get("Applications", {}) + picc = applications.get("000000") + if not isinstance(picc, dict): + raise ConversionError("Applications.000000: PICC application is required") + lines = [ + "Filetype: DFC Credential", "Version: 4", f"Card Generation: {generation}", + f"Card Storage: {storage}", f"UID: {spaced_hex(uid, 'Card.UID')}", "UID Provenance: Real", + ] + if "Signature" in card: + lines.append(f"Card Static Signature: {spaced_hex(card['Signature'], 'Card.Signature', (56,))}") + lines.extend([ + f"PICC Key Settings 1: {spaced_hex(picc['KeySettings'], 'PICC Key Settings 1', (1,))}", + f"PICC Key Settings 2: {spaced_hex(picc['NumKeysRaw'], 'PICC Key Settings 2', (1,))}", + f"PICC Authentication Mode: {auth_mode(picc)}", + ]) + append_keys(lines, "PICC", picc) + for field, label, lengths in (("ATS", "PICC ATS", None), ("SAK", "PICC SAK", (1,)), ("ATQA", "PICC ATQA", (2,))): + if field in card: + lines.append(f"{label}: {spaced_hex(card[field], label, lengths)}") + lines.append("PICC File Count: 0") + app_items = [(aid, app) for aid, app in applications.items() if aid != "000000"] + lines.append(f"Application Count: {len(app_items)}") + for index, (aid, app) in enumerate(sorted(app_items)): + prefix = f"Application {index:02X}" + lines.append(f"{prefix} AID: {spaced_hex(aid, prefix + ' AID', (3,))}") + if "ISOFileID" in app: + lines.append(f"{prefix} ISO File ID: {spaced_hex(app['ISOFileID'], prefix + ' ISO File ID', (2,))}") + if "DFName" in app: + lines.append(f"{prefix} DF Name: {spaced_hex(app['DFName'], prefix + ' DF Name')}") + lines.extend([ + f"{prefix} Key Settings 1: {spaced_hex(app['KeySettings'], prefix + ' Key Settings 1', (1,))}", + f"{prefix} Key Settings 2: {spaced_hex(app['NumKeysRaw'], prefix + ' Key Settings 2', (1,))}", + f"{prefix} Authentication Mode: {auth_mode(app)}", + ]) + append_keys(lines, prefix, app) + append_files(lines, prefix, app) + return "\n".join(lines) + "\n" + + +def convert(source, destination): + source_suffix = source.suffix.lower() + destination_suffix = destination.suffix.lower() + if source_suffix == ".dfc" and destination_suffix == ".json": + image = dfc_to_json(source.read_text(encoding="ascii")) + destination.write_text(json.dumps(image, indent=2) + "\n", encoding="utf-8") + elif source_suffix == ".json" and destination_suffix == ".dfc": + image = json.loads(source.read_text(encoding="utf-8")) + destination.write_text(json_to_dfc(image), encoding="ascii") + else: + raise ConversionError("conversion must be .dfc to .json or .json to .dfc") + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("source", type=pathlib.Path, help="input .dfc or .json file") + parser.add_argument("destination", type=pathlib.Path, help="output .json or .dfc file") + args = parser.parse_args(argv) + try: + convert(args.source, args.destination) + except (ConversionError, OSError, json.JSONDecodeError) as exc: + parser.exit(1, f"dfc_converter: {exc}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/dfc_converter_test.py b/tools/dfc_converter_test.py new file mode 100755 index 000000000..340469f77 --- /dev/null +++ b/tools/dfc_converter_test.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 + +import json +import pathlib +import tempfile +import unittest + +import dfc_converter + + +ROOT = pathlib.Path(__file__).resolve().parent.parent +FIXTURES = ROOT / "traces" / "desfire" + + +class DfcConverterTest(unittest.TestCase): + def test_credentials_round_trip(self): + for name in ("H10301-FC69-CN420-factory", "H10301-FC69-CN420-field"): + with self.subTest(name=name), tempfile.TemporaryDirectory() as directory: + source = FIXTURES / f"{name}.dfc" + first_json = pathlib.Path(directory) / "first.json" + second_dfc = pathlib.Path(directory) / "second.dfc" + second_json = pathlib.Path(directory) / "second.json" + dfc_converter.convert(source, first_json) + dfc_converter.convert(first_json, second_dfc) + dfc_converter.convert(second_dfc, second_json) + self.assertEqual( + json.loads(first_json.read_text()), + json.loads(second_json.read_text()), + ) + + def test_rejects_direction_without_known_extensions(self): + with tempfile.TemporaryDirectory() as directory: + path = pathlib.Path(directory) / "credential.txt" + path.write_text("not a credential") + with self.assertRaisesRegex(dfc_converter.ConversionError, "must be"): + dfc_converter.convert(path, path.with_suffix(".json")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/fpga_compress/fpga_compress.c b/tools/fpga_compress/fpga_compress.c index 0f3454d84..740d85346 100644 --- a/tools/fpga_compress/fpga_compress.c +++ b/tools/fpga_compress/fpga_compress.c @@ -32,22 +32,40 @@ int fileno(FILE *); static void usage(void) { fprintf(stdout, "Usage: fpga_compress ... \n"); fprintf(stdout, " Combine n FPGA bitstream files and compress them into one.\n\n"); + fprintf(stdout, " fpga_compress -s \n"); + fprintf(stdout, " Compress into ONE single LZ4 block. Used for the ARM .data section\n\n"); fprintf(stdout, " fpga_compress -v ... \n"); fprintf(stdout, " Extract Version Information from FPGA bitstream files and write it to \n\n"); fprintf(stdout, " fpga_compress -d \n"); fprintf(stdout, " Decompress . Write result to \n\n"); } +// feof() only reports true once a read has already run off the end, so a file +// whose length is an exact multiple of FPGA_INTERLEAVE_SIZE still looks unfinished +// after its last whole chunk. That earned one more interleave round of pure +// padding, which pushed total_size past the buffer and got the whole set rejected +// as "too big" -- PM3ULTIMATE's bitstreams are exactly 243 * 288 bytes. +// Peek one byte instead, so a file that has been read to its last byte counts as +// finished right away. static bool all_feof(FILE *infile[], uint8_t num_infiles) { for (uint16_t i = 0; i < num_infiles; i++) { - if (!feof(infile[i])) { - return false; + + if (feof(infile[i])) { + continue; } + + int c = fgetc(infile[i]); + if (c == EOF) { + continue; + } + + ungetc(c, infile[i]); + return false; } return true; } -static int zlib_compress(FILE *infile[], uint8_t num_infiles, FILE *outfile) { +static int zlib_compress(FILE *infile[], uint8_t num_infiles, FILE *outfile, bool single_block) { uint8_t *fpga_config = calloc(num_infiles * FPGA_CONFIG_SIZE, sizeof(uint8_t)); if (fpga_config == NULL) { @@ -59,9 +77,14 @@ static int zlib_compress(FILE *infile[], uint8_t num_infiles, FILE *outfile) { uint32_t total_size = 0; do { - if (total_size >= num_infiles * FPGA_CONFIG_SIZE) { + // Each round writes num_infiles * FPGA_INTERLEAVE_SIZE bytes, so ask whether + // that round fits rather than whether we have already filled the buffer. + // `>` alone let a round start with the buffer full and overrun it; `>=` + // rejected a set that exactly filled it, which is what the bitstreams of a + // platform sized to FPGA_CONFIG_SIZE do. + if (total_size + (num_infiles * FPGA_INTERLEAVE_SIZE) > num_infiles * FPGA_CONFIG_SIZE) { fprintf(stderr, - "Input files too big (total >= %li bytes). These are probably not PM3 FPGA config files.\n" + "Input files too big (total > %li bytes). These are probably not PM3 FPGA config files.\n" , num_infiles * FPGA_CONFIG_SIZE ); @@ -69,13 +92,23 @@ static int zlib_compress(FILE *infile[], uint8_t num_infiles, FILE *outfile) { return (EXIT_FAILURE); } + // Pad a bitstream that ran out mid chunk with zeroes, so total_size stays a + // whole number of FPGA_INTERLEAVE_SIZE chunks. zlib_decompress() walks the + // output in whole chunks and drops a trailing partial one, so an unpadded + // stream comes back short - 42172 bytes of fpga_pm3_hf.bit returned as 39788. + // + // Not for "-s". That is the .data section, and start.c sizes the + // decompression with __data_end__ - __data_start__. Rounding .data up to a + // chunk boundary makes LZ4_decompress_safe() overrun that and return an + // error, which drops the firmware into the LED panic loop in + // uncompress_data_section(). for (uint16_t j = 0; j < num_infiles; j++) { for (uint16_t k = 0; k < FPGA_INTERLEAVE_SIZE; k++) { uint8_t c = (uint8_t)fgetc(infile[j]); if (!feof(infile[j])) { fpga_config[total_size++] = c; - } else if (num_infiles > 1) { + } else if (single_block == false) { fpga_config[total_size++] = '\0'; } } @@ -83,22 +116,25 @@ static int zlib_compress(FILE *infile[], uint8_t num_infiles, FILE *outfile) { } while (all_feof(infile, num_infiles) == false); - // Block size for the LZ4 stream. Two very different consumers: + // Block size for the LZ4 stream. Two very different consumers, told apart by the + // caller with "-s", never by counting input files: // - // - many infiles: the interleaved FPGA bitstreams. armsrc decompresses them - // one block at a time into a FPGA_RING_BUFFER_BYTES buffer taken from BigBuf + // - default: the interleaved FPGA bitstreams. armsrc decompresses them one + // block at a time into a FPGA_RING_BUFFER_BYTES buffer taken from BigBuf // (see get_from_fpga_combined_stream()), so the block size must match. + // This holds for a single bitstream too. A HF-only build ( SKIP_LF, + // SKIP_FELICA, SKIP_ISO15693 ) hands us just fpga_pm3_hf.bit and it still + // has to come out in ring buffer sized blocks. // - // - one infile: the firmware's .data section. start.c's - // uncompress_data_section() reads ONE 4-byte length and does ONE - // LZ4_decompress_safe(), so this must come out as a SINGLE block - it has no - // loop over blocks, and a short result is not treated as an error, so a - // second block would silently leave the tail of .data uninitialized. - // That is why it gets its own, much larger, block size and must not be - // tied to FPGA_RING_BUFFER_BYTES. + // - "-s": the firmware's .data section. start.c's uncompress_data_section() + // reads ONE 4-byte length and does ONE LZ4_decompress_safe(), so this must + // come out as a SINGLE block - it has no loop over blocks, and a short + // result is not treated as an error, so a second block would silently leave + // the tail of .data uninitialized. That is why it gets its own, much + // larger, block size and must not be tied to FPGA_RING_BUFFER_BYTES. uint32_t buffer_size = FPGA_RING_BUFFER_BYTES; - if (num_infiles == 1) { + if (single_block) { // 1M bytes for now buffer_size = 1024 * 1024; } @@ -123,11 +159,11 @@ static int zlib_compress(FILE *infile[], uint8_t num_infiles, FILE *outfile) { LZ4_streamHC_t *lz4_streamhc = LZ4_createStreamHC(); LZ4_resetStreamHC_fast(lz4_streamhc, LZ4HC_CLEVEL_MAX); - if (num_infiles == 1 && total_size > buffer_size) { + if (single_block && total_size > buffer_size) { fprintf(stderr, "error: %u bytes does not fit in a single %u byte block, and start.c only decompresses one\n" , total_size , buffer_size - ); + ); free(ring_buffer); free(outbuf); free(fpga_config); @@ -547,14 +583,32 @@ int main(int argc, char **argv) { } else { // Compress or generate version info bool generate_version_file = false; + bool single_block = false; uint8_t num_input_files = 0; + uint8_t first_input_file = 1; + if (!strcmp(argv[1], "-v")) { // generate version info generate_version_file = true; + first_input_file = 2; + num_input_files = argc - 3; + } else if (!strcmp(argv[1], "-s")) { // compress one file into a single block + single_block = true; + first_input_file = 2; num_input_files = argc - 3; } else { // compress 1..n fpga files num_input_files = argc - 2; } + if (num_input_files == 0) { + usage(); + return (EXIT_FAILURE); + } + + if (single_block && num_input_files != 1) { + fprintf(stderr, "Error. -s takes exactly one input file\n\n"); + return (EXIT_FAILURE); + } + FILE **infiles = calloc(num_input_files, sizeof(FILE *)); char **infile_names = calloc(num_input_files, sizeof(char *)); if (infiles == NULL || infile_names == NULL) { @@ -564,7 +618,7 @@ int main(int argc, char **argv) { return (EXIT_FAILURE); } for (uint8_t i = 0; i < num_input_files; i++) { - infile_names[i] = argv[i + (generate_version_file ? 2 : 1)]; + infile_names[i] = argv[i + first_input_file]; infiles[i] = fopen(infile_names[i], "rb"); if (infiles[i] == NULL) { fprintf(stderr, "Error. Cannot open input file %s\n\n", infile_names[i]); @@ -592,7 +646,7 @@ int main(int argc, char **argv) { if (generate_version_file) { ret = generate_fpga_version_info(infiles, infile_names, num_input_files, outfile); } else { - ret = zlib_compress(infiles, num_input_files, outfile); + ret = zlib_compress(infiles, num_input_files, outfile, single_block); } // close file handlers diff --git a/tools/pm3_online_tests.sh b/tools/pm3_online_tests.sh index 780903cf2..815405382 100755 --- a/tools/pm3_online_tests.sh +++ b/tools/pm3_online_tests.sh @@ -9,6 +9,7 @@ cd "$PM3PATH" || exit 1 TESTALL=false TESTDESFIREVALUE=false +TESTDESFIREREADER=false TESTHIDWIEGAND=false TESTMFHIDENCODE=false TESTICLASSREADER=false @@ -24,11 +25,12 @@ while (( "$#" )); do case "$1" in -h|--help) echo """ -Usage: $0 [--pm3bin /path/to/pm3] [--pm3port /dev/tty...] [desfire_value|hid_wiegand|mf_hid_encode|iclass_emu|iclass_reader|hitag2] +Usage: $0 [--pm3bin /path/to/pm3] [--pm3port /dev/tty...] [desfire_value|desfire_reader|hid_wiegand|mf_hid_encode|iclass_emu|iclass_reader|hitag2] --pm3bin ...: Specify path to pm3 binary to test --pm3port ...: Specify serial port for client/proxmark3 --manual ...: Pause after successful online LF HID clone/read checks for external reader verification desfire_value: Test DESFire value operations with card + desfire_reader: Load DESFire HID credentials for external reader verification hid_wiegand: Test LF HID T55xx clone and PM3 readback flows mf_hid_encode: Test MIFARE Classic HID encoding flows iclass_emu: Test iCLASS emulator memory load/write/read flows @@ -66,6 +68,11 @@ Usage: $0 [--pm3bin /path/to/pm3] [--pm3port /dev/tty...] [desfire_value|hid_wie TESTDESFIREVALUE=true shift ;; + desfire_reader) + TESTALL=false + TESTDESFIREREADER=true + shift + ;; hid_wiegand) TESTALL=false TESTHIDWIEGAND=true @@ -257,6 +264,13 @@ function CleanupMfHidEncodeCard() { fi } +function CleanupOnlineTests() { + CleanupMfHidEncodeCard + if [ -n "${DFC_FACTORY_JSON:-}" ] || [ -n "${DFC_FIELD_JSON:-}" ]; then + rm -f "${DFC_FACTORY_JSON:-/tmp/pm3-no-dfc-factory}" "${DFC_FIELD_JSON:-/tmp/pm3-no-dfc-field}" + fi +} + function CheckMfHidEncodeRoundTrip() { printf "%-40s" "$1 " @@ -381,7 +395,7 @@ function WaitForEnter() { fi } -trap CleanupMfHidEncodeCard EXIT +trap CleanupOnlineTests EXIT echo -e "${C_BLUE}Iceman Proxmark3 online test tool${C_NC}" echo "" @@ -396,7 +410,7 @@ if command -v git >/dev/null && git rev-parse --is-inside-work-tree >/dev/null 2 fi # Check that user specified a test -if [ "$TESTDESFIREVALUE" = false ] && [ "$TESTHIDWIEGAND" = false ] && [ "$TESTMFHIDENCODE" = false ] && [ "$TESTICLASSEMU" = false ] && [ "$TESTICLASSREADER" = false ] && [ "$TESTSMARTCARD" = false ] && [ "$TESTHITAG2" = false ]; then +if [ "$TESTDESFIREVALUE" = false ] && [ "$TESTDESFIREREADER" = false ] && [ "$TESTHIDWIEGAND" = false ] && [ "$TESTMFHIDENCODE" = false ] && [ "$TESTICLASSEMU" = false ] && [ "$TESTICLASSREADER" = false ] && [ "$TESTSMARTCARD" = false ] && [ "$TESTHITAG2" = false ]; then echo "Error: You must specify a test target. Use -h for help." exit 1 fi @@ -410,19 +424,55 @@ while true; do echo " Formatting card to clean state..." if ! CheckExecute "format card" "$PM3BIN -c 'hf mfdes formatpicc'" "done"; then break; fi - - echo " Running value operation tests..." + + # The PICC serves a file in plain whenever access is granted by the free + # access right (0x0E) instead of by a key we hold, whatever the file + # communication mode says. The client has to work that out per operation, + # so every file below is a different answer to it. No -m flags on purpose: + # the point is that the client derives the mode, not that we ask for one. + echo " Building the fixture..." if ! CheckExecute "card auth test" "$PM3BIN -c 'hf mfdes auth -n 0 -t 2tdea -k 00000000000000000000000000000000 --kdf none'" "authenticated.*succes"; then break; fi - if ! CheckExecute "card app creation" "$PM3BIN -c 'hf mfdes createapp --aid 123456 --ks1 0F --ks2 0E --numkeys 1'" "successfully created"; then break; fi - if ! CheckExecute "card value file creation" "$PM3BIN -c 'hf mfdes createvaluefile --aid 123456 --fid 02 --lower 00000000 --upper 000003E8 --value 00000064'" "created successfully"; then break; fi - if ! CheckExecute "card value get plain" "$PM3BIN -c 'hf mfdes value --aid 123456 --fid 02 --op get -m plain'" "Value.*100"; then break; fi - if ! CheckExecute "card value get mac" "$PM3BIN -c 'hf mfdes value --aid 123456 --fid 02 --op get -m mac'" "Value.*100"; then break; fi - if ! CheckExecute "card value credit plain" "$PM3BIN -c 'hf mfdes value --aid 123456 --fid 02 --op credit -d 00000032 -m plain'" "Value.*changed"; then break; fi - if ! CheckExecute "card value get after credit" "$PM3BIN -c 'hf mfdes value --aid 123456 --fid 02 --op get -m plain'" "Value.*150"; then break; fi - if ! CheckExecute "card value credit mac" "$PM3BIN -c 'hf mfdes value --aid 123456 --fid 02 --op credit -d 0000000A -m mac'" "Value.*changed"; then break; fi - if ! CheckExecute "card value debit plain" "$PM3BIN -c 'hf mfdes value --aid 123456 --fid 02 --op debit -d 00000014 -m plain'" "Value.*changed"; then break; fi - if ! CheckExecute "card value debit mac" "$PM3BIN -c 'hf mfdes value --aid 123456 --fid 02 --op debit -d 00000014 -m mac'" "Value.*changed"; then break; fi - if ! CheckExecute "card value final check" "$PM3BIN -c 'hf mfdes value --aid 123456 --fid 02 --op get -m mac'" "Value.*120"; then break; fi + if ! CheckExecute "card app creation" "$PM3BIN -c 'hf mfdes createapp --aid 123456 --ks1 0F --dstalgo aes --numkeys 2'" "successfully created"; then break; fi + + # data files: free vs key protected, in each communication mode + for F in "00 mac EEEE" "01 mac 0000" "02 encrypt EEEE" "03 encrypt 0000"; do + set -- $F + if ! CheckExecute "data file $1 $2 $3 created" "$PM3BIN -c 'hf mfdes createfile --aid 123456 -n 0 -t aes -k 00000000000000000000000000000000 --fid $1 --amode $2 --size 000008 --rawrights $3'" "created successfully"; then break 2; fi + done + + # value files. 10 is the discriminating one: credit is granted by + # read&write only, which is free here, while debit is also granted by the + # write right, which is key 0 - so credit goes plain and debit goes MAC on + # the same file in the same session. 13 has the FreeValue option, which + # makes GetValue plain on an otherwise fully enciphered file. + if ! CheckExecute "value file 10 mac 00E0 created" "$PM3BIN -c 'hf mfdes createvaluefile --aid 123456 -n 0 -t aes -k 00000000000000000000000000000000 --fid 10 --amode mac --rawrights 00E0 --lower 00000000 --upper 000003E8 --value 00000064'" "created successfully"; then break; fi + if ! CheckExecute "value file 11 mac 0000 created" "$PM3BIN -c 'hf mfdes createvaluefile --aid 123456 -n 0 -t aes -k 00000000000000000000000000000000 --fid 11 --amode mac --rawrights 0000 --lower 00000000 --upper 000003E8 --value 00000064'" "created successfully"; then break; fi + if ! CheckExecute "value file 12 plain EEEE created" "$PM3BIN -c 'hf mfdes createvaluefile --aid 123456 -n 0 -t aes -k 00000000000000000000000000000000 --fid 12 --amode plain --rawrights EEEE --lower 00000000 --upper 000003E8 --value 00000064'" "created successfully"; then break; fi + if ! CheckExecute "value file 13 enc FreeValue created" "$PM3BIN -c 'hf mfdes createvaluefile --aid 123456 -n 0 -t aes -k 00000000000000000000000000000000 --fid 13 --amode encrypt --rawrights 0000 --lcredit 3 --lower 00000000 --upper 000003E8 --value 00000064'" "created successfully"; then break; fi + + echo " Running data file tests..." + for F in 00 01 02 03; do + if ! CheckExecute "data file $F write" "$PM3BIN -c 'hf mfdes write --aid 123456 -n 0 -t aes -k 00000000000000000000000000000000 --fid $F -d A0A1A2A3A4A5A6$F'" "Write data file $F success"; then break 2; fi + if ! CheckExecute "data file $F read back" "$PM3BIN -c 'hf mfdes read --aid 123456 -n 0 -t aes -k 00000000000000000000000000000000 --fid $F'" "A0 A1 A2 A3 A4 A5 A6 $F"; then break 2; fi + done + + # the app has no ISO file ids, so the client's GetISOFileIDs probe is + # refused and the PICC ends the session on it. dump has to notice, or it + # reads the first file's plain content as a response CMAC and loses it. + if ! CheckExecute "dump keeps the session" "$PM3BIN -c 'hf mfdes dump --aid 123456 -n 0 -t aes -k 00000000000000000000000000000000'" "A0 A1 A2 A3 A4 A5 A6 00"; then break; fi + + echo " Running value operation tests..." + for F in 10 11 12; do + if ! CheckExecute "value file $F get" "$PM3BIN -c 'hf mfdes value --aid 123456 -n 0 -t aes -k 00000000000000000000000000000000 --fid $F --op get'" "Value: 100 \\(0x00000064\\)"; then break 2; fi + if ! CheckExecute "value file $F credit" "$PM3BIN -c 'hf mfdes value --aid 123456 -n 0 -t aes -k 00000000000000000000000000000000 --fid $F --op credit -d 00000032'" "Value changed"; then break 2; fi + if ! CheckExecute "value file $F debit" "$PM3BIN -c 'hf mfdes value --aid 123456 -n 0 -t aes -k 00000000000000000000000000000000 --fid $F --op debit -d 00000014'" "Value changed"; then break 2; fi + if ! CheckExecute "value file $F final" "$PM3BIN -c 'hf mfdes value --aid 123456 -n 0 -t aes -k 00000000000000000000000000000000 --fid $F --op get'" "Value: 130 \\(0x00000082\\)"; then break 2; fi + done + + if ! CheckExecute "value file 13 FreeValue get" "$PM3BIN -c 'hf mfdes value --aid 123456 -n 0 -t aes -k 00000000000000000000000000000000 --fid 13 --op get'" "Value: 100 \\(0x00000064\\)"; then break; fi + if ! CheckExecute "value file 13 credit" "$PM3BIN -c 'hf mfdes value --aid 123456 -n 0 -t aes -k 00000000000000000000000000000000 --fid 13 --op credit -d 00000032'" "Value changed"; then break; fi + if ! CheckExecute "value file 13 final" "$PM3BIN -c 'hf mfdes value --aid 123456 -n 0 -t aes -k 00000000000000000000000000000000 --fid 13 --op get'" "Value: 150 \\(0x00000096\\)"; then break; fi + if ! CheckExecute "card cleanup" "$PM3BIN -c 'hf mfdes selectapp --aid 000000; hf mfdes auth -n 0 -t 2tdea -k 00000000000000000000000000000000 --kdf none; hf mfdes deleteapp --aid 123456'" "application.*deleted"; then break; fi echo " card value operation tests completed successfully!" fi @@ -533,6 +583,27 @@ while true; do if ! CheckExecute "hf iclass sim preserves emu" "$PM3CMD -c 'hf iclass eview -s 80' 2>&1 | LC_ALL=C tr -cd '\11\12\15\40-\176' | tr '\n' ' '" "0/0x00.*BD 0C 60 10 F7 FF 12 E0.*6/0x06.*03 03 03 03 00 03 E0 17.*7/0x07.*10 A1 45 91 9E D1 6F 50"; then break; fi fi + if $TESTDESFIREREADER; then + echo -e "\n${C_BLUE}Testing DESFire reader verification${C_NC} ${PM3BIN:=./pm3}" + if ! CheckFileExist "pm3 exists" "$PM3BIN"; then break; fi + PM3CMD="$PM3BIN" + if [ -n "${PM3PORT:-}" ]; then + echo "Using PM3 port: $PM3PORT" + PM3CMD="$PM3CMD -p $PM3PORT" + fi + + DFC_FACTORY_JSON="/tmp/pm3-dfc-factory-$$.json" + DFC_FIELD_JSON="/tmp/pm3-dfc-field-$$.json" + if ! CheckExecute "convert factory DFC" "python3 tools/dfc_converter.py traces/desfire/H10301-FC69-CN420-factory.dfc $DFC_FACTORY_JSON && echo converted" "converted"; then break; fi + if ! CheckExecute "convert field DFC" "python3 tools/dfc_converter.py traces/desfire/H10301-FC69-CN420-field.dfc $DFC_FIELD_JSON && echo converted" "converted"; then break; fi + + WaitForEnter "PRESS ENTER TO START DESFIRE FACTORY SIM, PRESENT THE PM3 TO THE HID READER, CONFIRM: H10301 FC 69 CN 420, THEN PRESS THE PM3 BUTTON TO STOP SIM" + if ! CheckExecute "hf mfdes factory to reader" "$PM3CMD -c 'hf mfdes eload -f $DFC_FACTORY_JSON; hf mfdes sim' 2>&1" "Done!"; then break; fi + WaitForEnter "PRESS ENTER TO START DESFIRE FIELD SIM, PRESENT THE PM3 TO THE HID READER, CONFIRM: H10301 FC 69 CN 420, THEN PRESS THE PM3 BUTTON TO STOP SIM" + if ! CheckExecute "hf mfdes field to reader" "$PM3CMD -c 'hf mfdes eload -f $DFC_FIELD_JSON; hf mfdes sim' 2>&1" "Done!"; then break; fi + rm -f "$DFC_FACTORY_JSON" "$DFC_FIELD_JSON" + fi + # SIM module / ISO 7816 contact card tests. # # Card agnostic: asserts that answers come back and are stable, never what @@ -559,8 +630,8 @@ while true; do if ! CheckExecute "ATR stable over 5 reads" "for i in 1 2 3 4 5; do $PM3CMD -c 'smart info' 2>&1 | grep -oE 'ISO7816-3 ATR\.+ [0-9A-F ]+'; done | sort -u | wc -l" "^ *1$"; then break; fi # any status word will do - the point is that the exchange completed - if ! CheckExecute "T=0 apdu gets a status word" "$PM3CMD -c 'smart raw -a -s -0 -d 00a4040007a0000000041010' 2>&1" "\[[+-]\] [0-9A-Fa-f]{4} \|"; then break; fi - if ! CheckExecute "T=0 answer stable over 3" "for i in 1 2 3; do $PM3CMD -c 'smart raw -a -s -0 -d 00a4040007a0000000041010' 2>&1 | grep -oE '^\[[+-]\] [0-9A-Fa-f]{4}'; done | sort -u | wc -l" "^ *1$"; then break; fi + if ! CheckExecute "T=0 apdu gets a status word" "$PM3CMD -c 'smart raw --t0 -a -s -d 00a4040007a0000000041010' 2>&1" "\[[+-]\] [0-9A-Fa-f]{4} \|"; then break; fi + if ! CheckExecute "T=0 answer stable over 3" "for i in 1 2 3; do $PM3CMD -c 'smart raw --t0 -a -s -d 00a4040007a0000000041010' 2>&1 | grep -oE '^\[[+-]\] [0-9A-Fa-f]{4}'; done | sort -u | wc -l" "^ *1$"; then break; fi # loose guard against the 1200 ms per-read wait coming back echo -n " timing three exchanges... " @@ -574,8 +645,8 @@ while true; do if $PM3CMD -c 'smart info' 2>&1 | grep -q "Protocol T1"; then echo " card offers T=1" if ! CheckExecute "module reports T=1 support" "$PM3CMD -c 'hw status' 2>&1" "T=1, PPS\.+ \( .*supported"; then break; fi - if ! CheckExecute "T=1 apdu gets a status word" "$PM3CMD -c 'smart raw --t1 -s -d 00a4040007a000000004101000' 2>&1" "\[[+-]\] [0-9A-Fa-f]{4} \|"; then break; fi - if ! CheckExecute "T=1 answer stable over 3" "for i in 1 2 3; do $PM3CMD -c 'smart raw --t1 -s -d 00a4040007a000000004101000' 2>&1 | grep -oE '^\[[+-]\] [0-9A-Fa-f]{4}'; done | sort -u | wc -l" "^ *1$"; then break; fi + if ! CheckExecute "T=1 apdu gets a status word" "$PM3CMD -c 'smart raw --t1 -d 00a4040007a000000004101000' 2>&1" "\[[+-]\] [0-9A-Fa-f]{4} \|"; then break; fi + if ! CheckExecute "T=1 answer stable over 3" "for i in 1 2 3; do $PM3CMD -c 'smart raw --t1 -d 00a4040007a000000004101000' 2>&1 | grep -oE '^\[[+-]\] [0-9A-Fa-f]{4}'; done | sort -u | wc -l" "^ *1$"; then break; fi else echo " card is T=0 only, skipping the T=1 checks" fi diff --git a/tools/pm3_tests.sh b/tools/pm3_tests.sh index a63279319..135dc2a76 100755 --- a/tools/pm3_tests.sh +++ b/tools/pm3_tests.sh @@ -297,6 +297,7 @@ while true; do if ! CheckExecute "xorcheck test" "$PYTHON tools/xorcheck.py 04 00 80 64 ba" "final LRC XOR byte value: 5A"; then break; fi if ! CheckExecute "findbits test" "$PYTHON tools/findbits.py 73 0110010101110011" "Match at bit 9: 011001010"; then break; fi if ! CheckExecute "findbits_test test" "$PYTHON tools/findbits_test.py 2>&1" "OK"; then break; fi + if ! CheckExecute "dfc_converter test" "$PYTHON tools/dfc_converter_test.py 2>&1" "OK"; then break; fi if ! CheckExecute "pm3_eml_mfd test" "$PYTHON tools/mfc/pm3_eml_mfd_test.py 2>&1" "OK"; then break; fi if ! CheckExecute "recover_pk test" "$PYTHON tools/recover_pk.py selftests 2>&1" "Tests:.*\(.*ok.*"; then break; fi if ! CheckExecute "mkversion create test" "tools/mkversion.sh --short" 'Iceman/'; then break; fi @@ -337,7 +338,7 @@ while true; do if ! CheckFileExist "staticnested_2x1nt_rf08s exists" "$STATICNESTED2X1NTBIN"; then break; fi if ! CheckFileExist "staticnested_2x1nt_rf08s_1key exists" "$STATICNESTED2X11KNTBIN"; then break; fi # very slow one... - if ! CheckExecute slow "staticnested_0nt test" "$STATICNESTED0NTBIN a13e4902 2e9e49fc 1111 . 7bfc7a5b 1110 a17e4902 50f2abc2 1101; rm keys.dic" "Key ffffffffffff found in 3 arrays"; then break; fi +# if ! CheckExecute slow "staticnested_0nt test" "$STATICNESTED0NTBIN a13e4902 2e9e49fc 1111 . 7bfc7a5b 1110 a17e4902 50f2abc2 1101; rm keys.dic" "Key ffffffffffff found in 3 arrays"; then break; fi if ! CheckExecute "staticnested_1nt 1/2 test" "$STATICNESTED1NTBIN 5c467f63 0 456ace4e da53428d 1001" "found 19823 keys"; then break; fi if ! CheckExecute "staticnested_1nt 2/2 test" "$STATICNESTED1NTBIN 5c467f63 0 e56f9fa2 7a9616b6 1110" "found 34531 keys"; then break; fi if ! CheckExecute "staticnested_2nt test" "$STATICNESTED2NTBIN 461dce03 7eef3586 7fa28c7e 322bc14d 7f62b3d6" "\[ 2 \].*ffffffffff40.*"; then break; fi @@ -468,9 +469,11 @@ while true; do if ! CheckExecute "data qrcode invalid hex" "$CLIENTBIN -c 'data qrcode -d zz' 2>&1" "QR data must contain only hex characters"; then break; fi if ! CheckExecute "data qrcode odd hex" "$CLIENTBIN -c 'data qrcode -d a' 2>&1" "QR data must contain an even number of hex digits"; then break; fi if ! CheckExecute "data qrcode spaced hex" "$CLIENTBIN -c 'data qrcode -d \"aa bb\"' 2>&1" "Spaces are not supported; encode a space byte as 20"; then break; fi + if ! CheckExecute "data modulation keeps trace" "$CLIENTBIN -c 'data load -f traces/lf_Q5_mod-psk1-32-4.pm3; data modulation; data autocorr -w 99999'" "smaller than trace \\( 20000 samples \\)"; then break; fi if ! CheckExecute "mfu pwdgen test" "$CLIENTBIN -c 'hf mfu pwdgen --test'" "Selftest ok"; then break; fi if ! CheckExecute "mfu keygen test" "$CLIENTBIN -c 'hf mfu keygen --uid 11223344556677'" "80 B1 C2 71 D8 A0"; then break; fi if ! CheckExecute "jooki encode test" "$CLIENTBIN -c 'hf jooki encode --test'" "04 28 F4 DA F0 4A 81 \( ok \)"; then break; fi + if ! CheckExecute "vigik signature selftest" "$CLIENTBIN -c 'hf mf view --selftest'" "selftest \\( ok \\)"; then break; fi if ! CheckExecute "analyse regex selftest" "$CLIENTBIN -c 'analyse regex --test'" "Tests \( ok \)"; then break; fi if ! CheckExecute "trace load/list 14a" "$CLIENTBIN -c 'trace load -f traces/hf_14a_mfu.trace; trace list -1 -t 14a;'" "READBLOCK\(8\)"; then break; fi if ! CheckExecute "trace load/list x" "$CLIENTBIN -c 'trace load -f traces/hf_14a_mfu.trace; trace list -x1 -t 14a;'" "0.0101840425"; then break; fi @@ -538,6 +541,12 @@ while true; do if ! CheckExecute "lf GPROXII test" "$CLIENTBIN -c 'data load -f traces/lf_GProx_36_30_14489.pm3; lf search -1'" "Guardall G-Prox II ID found"; then break; fi if ! CheckExecute "lf HID Prox test" "$CLIENTBIN -c 'data load -f traces/lf_HID-proxCardII-05512-11432784-1.pm3;lf search -1'" "HID Prox ID found"; then break; fi if ! CheckExecute "lf IDTECK test" "$CLIENTBIN -c 'data load -f traces/lf_IDTECK_4944544BAC40E069.pm3; lf search -1'" "Idteck ID found"; then break; fi + if ! CheckExecute "lf IDTECK test 2" "$CLIENTBIN -c 'data load -f traces/lf_IDTECK_4944544BAC40E069.pm3; lf idteck demod'" \ + "Card ID 6938688 \( 0x69E040 \) Raw: 4944544BAC40E069"; then break; fi + if ! CheckExecute "lf IDTECK raw test" "$CLIENTBIN -c 'lf idteck demod --raw 4944544B351FBE4B'" \ + "Card ID 4963871 \( 0x4BBE1F \) Raw: 4944544B351FBE4B"; then break; fi + if ! CheckExecute "lf IDTECK reject test" "if ! $CLIENTBIN -c 'lf idteck demod --raw DEADBEEFDEADBEEF' 2>&1 | grep -q 'IDTECK Tag Found'; then echo OK; fi" "OK"; then break; fi + if ! CheckExecute "lf IDTECK no wiegand test" "if ! $CLIENTBIN -c 'lf idteck demod --raw 4944544B351FBE4B' 2>&1 | grep -q 'H10301'; then echo OK; fi" "OK"; then break; fi if ! CheckExecute "lf INDALA test" "$CLIENTBIN -c 'data load -f traces/lf_Indala-504278295.pm3;lf search -1'" "Indala ID found"; then break; fi if ! CheckExecute "lf KERI test" "$CLIENTBIN -c 'data load -f traces/lf_Keri.pm3;lf search -1'" "Pyramid ID found"; then break; fi if ! CheckExecute "lf NEXWATCH test" "$CLIENTBIN -c 'data load -f traces/lf_NEXWATCH_Quadrakey-521512301.pm3;lf search -1 '" "NexWatch ID found"; then break; fi diff --git a/tools/release_tests.sh b/tools/release_tests.sh index 9dd168cc7..649958a3b 100755 --- a/tools/release_tests.sh +++ b/tools/release_tests.sh @@ -11,7 +11,7 @@ set -x make clean && make -j PLATFORM=PM3GENERIC PLATFORM_EXTRAS= STANDALONE=LF_SAMYRUN && tools/pm3_tests.sh --long || exit 1 make clean && make -j PLATFORM=PM3RDV4 PLATFORM_EXTRAS= STANDALONE=HF_ST25_TEAROFF || exit 1 make clean && make -j PLATFORM=PM3RDV4 PLATFORM_EXTRAS=BTADDON STANDALONE=HF_REBLAY || exit 1 -make -j PLATFORM=PM3RDV4 PLATFORM_EXTRAS=BTADDON STANDALONE=HF_REBLAY && if sudo true; then INSTALLSUDO=sudo make install PLATFORM=PM3RDV4 PLATFORM_EXTRAS=BTADDON STANDALONE=HF_REBLAY && ( cd /tmp; proxmark3 -c 'data load -f lf_EM4x05.pm3;lf search -1'|grep 'Valid FDX-B ID found' ) && INSTALLSUDO=sudo make uninstall || exit 1; fi +make -j PLATFORM=PM3RDV4 PLATFORM_EXTRAS=BTADDON STANDALONE=HF_REBLAY && if sudo true; then INSTALLSUDO=sudo make install SKIP_SETCAP=1 PLATFORM=PM3RDV4 PLATFORM_EXTRAS=BTADDON STANDALONE=HF_REBLAY && ( cd /tmp; proxmark3 -c 'data load -f lf_EM4x05.pm3;lf search -1'|grep 'Valid FDX-B ID found' ) && INSTALLSUDO=sudo make uninstall || exit 1; fi ( cd client; rm -rf build; mkdir build;cd build;cmake .. && make -j PLATFORM=PM3GENERIC PLATFORM_EXTRAS= STANDALONE=LF_SAMYRUN && cp -a ../*scripts ../*libs . && ../../tools/pm3_tests.sh --clientbin $(pwd)/proxmark3 client ) || exit 1 ( cd client; rm -rf build; mkdir build;cd build;cmake .. && make -j PLATFORM=PM3RDV4 PLATFORM_EXTRAS= STANDALONE=HF_ST25_TEAROFF ) || exit 1 ( cd client; rm -rf build; mkdir build;cd build;cmake .. && make -j PLATFORM=PM3RDV4 PLATFORM_EXTRAS=BTADDON STANDALONE=HF_REBLAY ) || exit 1 diff --git a/tools/vigik_recover_pk.py b/tools/vigik_recover_pk.py new file mode 100755 index 000000000..75fe67a1f --- /dev/null +++ b/tools/vigik_recover_pk.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +#----------------------------------------------------------------------------- +# Copyright (C) 2026 Iceman. See AUTHORS.md for details. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# See LICENSE.txt for the text of the license. +#------- +# +# Recover the RSA public modulus a VIGIK service signs its cards with, from the cards alone. as described in +# "A common weakness in RSA signatures: extracting public keys from communications and embedded devices", +# Renaud Lifchitz, Hackito Ergo Sum 2014. +# + +import sys +from math import gcd + +PI = [0x0E, 0x03, 0x05, 0x08, 0x09, 0x04, 0x02, 0x0F, + 0x00, 0x0D, 0x0B, 0x06, 0x07, 0x0A, 0x0C, 0x01] + +SIG_LEN = 128 # RSA 1024 +MSG_SLOTS = 64 # message byte slots in the block +VIGIK_AIDS = (0x4910, 0x4916) + + +def shadow(b): + return (PI[b >> 4] << 4) | PI[b & 0x0F] + +def vigik_struct(dump): + if len(dump) < 1024: + return None + + mad = dump[16:32] + secs = [i + 1 for i in range(7) + if int.from_bytes(mad[2 + 2 * i:4 + 2 * i], 'little') in VIGIK_AIDS] + + if not secs: + return None + + buf = dump[0:48] + b''.join(dump[s * 64:s * 64 + 48] for s in secs) + + return buf if len(buf) >= 224 else None + +def signed_message(buf): + return (bytes(8) + buf[0:4] + buf[64:68] + buf[69:70] + buf[88:89] + buf[73:78] + buf[78:80]) + +def iso9796_1_block(msg, clear_top_bit): + z = len(msg) + rev = msg[::-1] + stream = bytes(rev[(i - 1) % z] for i in range(MSG_SLOTS)) + f = bytearray(SIG_LEN) + for i in range(MSG_SLOTS): + f[2 * i] = shadow(stream[i]) + f[2 * i + 1] = stream[i] + f[2 * (MSG_SLOTS - z)] ^= 0x01 + f[SIG_LEN - 1] = ((stream[MSG_SLOTS - 1] & 0x0F) << 4) | 0x06 + if clear_top_bit: + f[0] ^= 0x80 + return int.from_bytes(bytes(f), 'big') + +def card_multiple(buf): + s = int.from_bytes(buf[96:96 + SIG_LEN][::-1], 'big') + msg = signed_message(buf) + out = 1 + for top in (False, True): + f = iso9796_1_block(msg, top) + for v in (s * s - f, s * s + f, 2 * s * s - f, 2 * s * s + f): + if v: + out *= v + return abs(out) + +def strip_small_factors(g, keep_bits=1024): + for p in range(2, 200000): + while g % p == 0 and (g // p).bit_length() >= keep_bits: + g //= p + return g + +def recover(bufs, keep_bits=1024, verbose=False): + g = 0 + for i, buf in enumerate(bufs): + m = card_multiple(buf) + g = m if g == 0 else gcd(g, m) + if verbose: + print(" after card %d: %d bits" % (i + 1, g.bit_length())) + if g.bit_length() < keep_bits: + return None + g = strip_small_factors(g, keep_bits) + return g if g.bit_length() == keep_bits else None + +def main(): + + if len(sys.argv) < 3: + print("Recover the RSA public modulus of a VIGIK service from its cards.") + print("") + print("Usage: %s [...]" % sys.argv[0]) + print("") + print("Dumps are MIFARE Classic 1K binaries.") + print("Two cards of the same service are usually enough") + return 1 + + bufs = [] + for fn in sys.argv[1:]: + with open(fn, 'rb') as fd: + buf = vigik_struct(fd.read()) + if buf is None: + print("%s: no VIGIK application in the MAD, skipped" % fn) + continue + svc = int.from_bytes(buf[64:68], 'little') & 0xFFFF + print("%s: service 0x%04X, uid %s" % (fn, svc, buf[0:4].hex())) + bufs.append(buf) + + if len(bufs) < 2: + print("\nNeed at least two cards signed by the same service.") + return 1 + + print("") + n = recover(bufs, verbose=True) + if n is None: + print("\nNo 1024 bit modulus came out. Are these all the same service?") + return 1 + + print("\nPublic modulus (%d bits):" % n.bit_length()) + h = "%X" % n + for i in range(0, len(h), 64): + print(" %s" % h[i:i + 64]) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/traces/README.md b/traces/README.md index db0ac32e0..80f243fa1 100644 --- a/traces/README.md +++ b/traces/README.md @@ -62,6 +62,9 @@ |lf_sniff_ht2-BC3B8810-acg-reader.pm3 |Sniffing of Hitag2 being read by an HID ACG LF Multitag reader| |lf_sniff_ht2-BC3B8810-frosch-reader.pm3 |Sniffing of Hitag2 being read by a Frosch Hitag reader| |lf_sniff_ht2-BC3B8810-rfidler-reader.pm3 |Sniffing of Hitag2 being read by a RFIDler| +|lf_ht2_pwd_sniff.trace |Sniffing of a genuine Hitag2 in password mode being read by a Paxton reader| +|lf_ht2_crypto_sniff.trace |Sniffing of a Hitag2 in crypto mode, showing the NrAr exchange| +|lf_ht2_pwd_sim.trace |`lf hitag sim` answering a Paxton reader in password mode, recorded by the simulating Proxmark| ## HF traces @@ -124,6 +127,83 @@ mode, so the files differ mainly in that one byte. |--------|-----------| |lf-hitag-CE129911-dump.bin |Hitag2 in password mode (config `0x06`), password `BDF5E846`| |lf_ht2_crypto.bin |Hitag2 in crypto mode (config `0x0E`), key `4F4EBDF5E846`| +|lf_ht2_crypto_1CAEFD13.bin |Hitag2 in crypto mode (config `0x0E`)| |lf_ht2_publicA.bin |Hitag2 in Public Mode A (config `0x02`), Manchester, pages 4-5, carries an EM4102 payload| |lf_ht2_publicB.bin |Hitag2 in Public Mode B (config `0x00`), biphase 32 T0, pages 4-7| |lf_ht2_publicC.bin |Hitag2 in Public Mode C (config `0x04`), biphase 64 T0, pages 4-7| + +## MIFARE DESFire card images + +Card images for `hf mfdes eload`, used by `hf mfdes sim`. All three are in the +`mfdes v1` dump format documented in `doc/mfdes_dump_format.md`. + +The 8K images come off a genuine MIFARE DESFire EV1 8K, UID `04268512A25680`, +batch `B9 0C 17 49 70`, week 27 / 2017, hardware `04010101001A05`, software +`04010101041A05`. + +|filename|description| +|--------|-----------| +|hf-mfdes-ev1-8k-empty.json |EV1 8K straight after `formatpicc`. PICC only, default 2TDEA key, 7936 bytes free| +|hf-mfdes-ev1-4k-empty.json |The same image edited to present as an EV1 4K. **Derived, not dumped from 4K silicon** -- the storage size byte of `VersionHW`/`VersionSW` is changed from `0x1A` to `0x18`, and `FreeMem` set to 3840, the nominal 4096 minus the 256 bytes of overhead the 8K part shows| +|hf-mfdes-ev1-8k-test.json |The same card with three applications and all five EV1 file types, for exercising a simulation| +|hf-mfdes-ev1-8k-test-keys.json |Application keys for the above, in the `mfdes v2` format `hf mfdes chk -j` writes| +|hf-mfdes-ev1-8k-empty-keys.json|Key file for the empty 8K image. Empty by construction, a blank card has no applications| +|hf-mfdes-ev1-4k-empty-keys.json|Key file for the empty 4K image. Likewise empty| + +### Keys + +Every key on this card is the counting sequence `01 02 03 .. 10`, extended to +`.. 18` for the 24 byte 3TDEA keys. The PICC master key is 2TDEA +`0102030405060708090A0B0C0D0E0F10`; each application uses its own algorithm, +and all of its keys are that algorithm's length of the same sequence. + +Deliberately not the all-zero key, and not a key whose two halves match. A +16 byte DES/2TDEA key string whose second half equals the first is handled as a +single DES key by the PICC -- during authentication *and* session key +generation (M134034 8.1) -- and the all-zero key is the common case of that. A +card image keyed with it exercises only the degenerate path: an implementation +that derives the wrong session key still authenticates, and only fails later on +the first MACed or enciphered frame. This sequence has distinct halves, so a +wrong derivation shows up immediately. + +The `mfdes v2` key files carry **application** keys only -- that format has no +place for the PICC master key, because `hf mfdes chk` only walks the application +list and takes the PICC key from `-k`. Hand it in explicitly: + +``` +hf mfdes dump -n 0 -t 2TDEA -k 0102030405060708090A0B0C0D0E0F10 --keys traces/mifare/hf-mfdes-ev1-8k-test-keys.json +``` + +Note that every key is also stored inside the dump itself, under each +application's `Keys` object, so `eload` and `sim` need no key file at all -- +the key files are for reading or rebuilding the physical card. + +`hf-mfdes-ev1-8k-test.json` holds: + +|AID|keys|ISO DF name|files| +|---|----|-----------|-----| +|`010203`|AES, 3 |`test1`|`01` standard 256 B free access, `02` backup 128 B MAC mode, rights `1200`| +|`112233`|2TDEA, 2 |`test2`|`00` value, 1000 with limits [0..10000], `01` linear record, 2 of 8 records, 16 B each| +|`AABBCC`|3TDEA, 5 |`test3`|`05` cyclic record, 1 of 4 records, 24 B each, `03` standard 64 B free access| + +``` +hf mfdes eload -f traces/mifare/hf-mfdes-ev1-8k-test.json +hf mfdes sim +``` + +## ST25TB card images + +`14b v2` dump format, 128 EEPROM blocks of four bytes followed by the system +block. The file name has to carry the UID, `hf 14b view` reads it from there to +work out the chip type and, for MyKey, to derive the session key. + +|filename|description| +|--------|-----------| +|hf-14b-D0021F673CB26556-dump.json |ST25TB04K carrying a COGES v3 MyKey, reset state: no vendor bound, zero credit, empty transaction ring. Blocks 7 and 8 are write protected| + +``` +hf 14b view -f traces/hf-14b-D0021F673CB26556-dump.json +``` + +This is the vector behind `hf 14b view --selftest`, which checks the block +scrambler, the session key and all 48 block checksums against it. diff --git a/traces/desfire/H10301-FC69-CN420-factory.dfc b/traces/desfire/H10301-FC69-CN420-factory.dfc new file mode 100644 index 000000000..f3270f441 --- /dev/null +++ b/traces/desfire/H10301-FC69-CN420-factory.dfc @@ -0,0 +1,33 @@ +Filetype: DFC Credential +Version: 4 +Card Generation: EV1 +Card Storage: 4096 +UID: 04 E9 34 D9 3D 30 9F +UID Provenance: Real +PICC Key Settings 1: 0F +PICC Key Settings 2: 01 +PICC Authentication Mode: D40 +PICC Key Count: 0 +PICC File Count: 0 +Application Count: 1 +Application 00 AID: 53 49 4F +Application 00 Key Settings 1: 0B +Application 00 Key Settings 2: 04 +Application 00 Authentication Mode: D40 +Application 00 Key Count: 4 +Application 00 Key 00: FE 2C 2A DA 64 0E EC 3C 7A 62 A4 48 44 80 AA B2 +Application 00 Key 00 Version: 00 +Application 00 Key 01: B8 B0 D2 EA B8 28 0A 90 0E B6 1A 7A 54 B4 C2 72 +Application 00 Key 01 Version: 00 +Application 00 Key 02: CE A8 EE 9E 50 76 58 26 0C F0 F0 F0 D2 F0 18 96 +Application 00 Key 02 Version: 00 +Application 00 Key 03: 2E E8 6A 56 7A 72 DE 14 34 5A F4 82 C8 E6 BA 48 +Application 00 Key 03 Version: 00 +Application 00 File Count: 1 +Application 00 File 00 Number: 0F +Application 00 File 00 Type: Standard Data +Application 00 File 00 Communication Settings: 01 +Application 00 File 00 Access Rights: 12 30 +Application 00 File 00 Size: 54 +Application 00 File 00 Data: 30 32 81 05 01 EB F9 ED 0A A5 02 05 00 A6 08 81 01 01 04 03 03 00 09 A7 17 85 15 DC 64 60 30 AA D9 D7 95 02 9B 15 DD FD 87 C3 A1 28 15 71 4F C4 A9 02 05 00 05 00 +Application 00 File 00 Data Complete: 1 diff --git a/traces/desfire/H10301-FC69-CN420-field.dfc b/traces/desfire/H10301-FC69-CN420-field.dfc new file mode 100644 index 000000000..9e7e09c4a --- /dev/null +++ b/traces/desfire/H10301-FC69-CN420-field.dfc @@ -0,0 +1,36 @@ +Filetype: DFC Credential +Version: 4 +Card Generation: EV1 +Card Storage: 4096 +UID: 04 A5 AB 54 92 61 76 +UID Provenance: Real +PICC Key Settings 1: 0F +PICC Key Settings 2: 01 +PICC Authentication Mode: D40 +PICC Key Count: 0 +PICC File Count: 0 +Application Count: 1 +Application 00 AID: D3 49 4F +Application 00 ISO File ID: E1 10 +Application 00 DF Name: D2 76 00 00 85 01 00 +Application 00 Key Settings 1: 0B +Application 00 Key Settings 2: 24 +Application 00 Authentication Mode: ISO +Application 00 Key Count: 4 +Application 00 Key 00: 24 B8 9A 7E 0E 7E 32 E2 C2 46 80 10 F0 5E 42 C4 +Application 00 Key 00 Version: 00 +Application 00 Key 01: CA FC 2E 94 64 88 14 64 26 CE F0 FC 18 9C E6 86 +Application 00 Key 01 Version: 00 +Application 00 Key 02: B8 3C C2 D2 2C 66 F6 A8 0C 3C F2 12 02 A2 F4 90 +Application 00 Key 02 Version: 00 +Application 00 Key 03: C8 7E 76 D4 CC 98 70 1C A6 FA 52 F4 FC A6 EA C8 +Application 00 Key 03 Version: 00 +Application 00 File Count: 1 +Application 00 File 00 Number: 0F +Application 00 File 00 Type: Standard Data +Application 00 File 00 Communication Settings: 01 +Application 00 File 00 Access Rights: 12 30 +Application 00 File 00 ISO File ID: 00 0F +Application 00 File 00 Size: 54 +Application 00 File 00 Data: 30 32 81 05 01 AD ED B0 6D A5 02 05 00 A6 08 81 01 01 04 03 03 00 09 A7 17 85 15 1E 74 05 5E 18 0E ED 17 A9 2D C4 D9 C7 6C C5 25 E1 9A F3 40 FF A9 02 05 00 05 00 +Application 00 File 00 Data Complete: 1 diff --git a/traces/hf-14b-D0021F673CB26556-dump.json b/traces/hf-14b-D0021F673CB26556-dump.json new file mode 100644 index 000000000..bfccaef65 --- /dev/null +++ b/traces/hf-14b-D0021F673CB26556-dump.json @@ -0,0 +1,135 @@ +{ + "Created": "proxmark3", + "FileType": "14b v2", + "blocks": { + "0": "FFFFFFFF", + "1": "FFFFFFFF", + "2": "FFFFFFFF", + "3": "FFFFFFFF", + "4": "FFFFFFFF", + "5": "FEFFFFFF", + "6": "FFFFFFFF", + "7": "64954319", + "8": "27102102", + "9": "FFFFFFFF", + "10": "FFFFFFFF", + "11": "FFFFFFFF", + "12": "FFFFFFFF", + "13": "FFFFFFFF", + "14": "FFFFFFFF", + "15": "FFFFFFFF", + "16": "E5640000", + "17": "CF954319", + "18": "EC000001", + "19": "E4040013", + "20": "E1640000", + "21": "CB954319", + "22": "E8000001", + "23": "E0040013", + "24": "8FCD0F48", + "25": "C0820007", + "26": "C0804040", + "27": "C0804000", + "28": "8F8DCF48", + "29": "C042C007", + "30": "C0800040", + "31": "C0800000", + "32": "C040C090", + "33": "65235698", + "34": "C0660113", + "35": "C040C000", + "36": "C0408090", + "37": "65231698", + "38": "C026C113", + "39": "C0408000", + "40": "FFFFFFFF", + "41": "FFFFFFFF", + "42": "FFFFFFFF", + "43": "FFFFFFFF", + "44": "FFFFFFFF", + "45": "FFFFFFFF", + "46": "FFFFFFFF", + "47": "FFFFFFFF", + "48": "FFFFFFFF", + "49": "FFFFFFFF", + "50": "FFFFFFFF", + "51": "FFFFFFFF", + "52": "FFFFFFFF", + "53": "FFFFFFFF", + "54": "FFFFFFFF", + "55": "FFFFFFFF", + "56": "FFFFFFFF", + "57": "FFFFFFFF", + "58": "FFFFFFFF", + "59": "FFFFFFFF", + "60": "FFFFFFFF", + "61": "FFFFFFFF", + "62": "FFFFFFFF", + "63": "B6640000", + "64": "A0954319", + "65": "BD000001", + "66": "B5040013", + "67": "B2640000", + "68": "9C954319", + "69": "B9000001", + "70": "B1040013", + "71": "8F0D0F88", + "72": "80C20047", + "73": "80C04080", + "74": "80C04040", + "75": "4FCDCF88", + "76": "8082C047", + "77": "80C00080", + "78": "80C00040", + "79": "8080C0D0", + "80": "8080C0C0", + "81": "80A60153", + "82": "8080C040", + "83": "808080D0", + "84": "808080C0", + "85": "8066C153", + "86": "80808040", + "87": "FFFFFFFF", + "88": "FFFFFFFF", + "89": "FFFFFFFF", + "90": "FFFFFFFF", + "91": "FFFFFFFF", + "92": "FFFFFFFF", + "93": "FFFFFFFF", + "94": "FFFFFFFF", + "95": "FFFFFFFF", + "96": "FFFFFFFF", + "97": "FFFFFFFF", + "98": "FFFFFFFF", + "99": "FFFFFFFF", + "100": "FFFFFFFF", + "101": "FFFFFFFF", + "102": "FFFFFFFF", + "103": "FFFFFFFF", + "104": "FFFFFFFF", + "105": "FFFFFFFF", + "106": "FFFFFFFF", + "107": "FFFFFFFF", + "108": "FFFFFFFF", + "109": "FFFFFFFF", + "110": "FFFFFFFF", + "111": "FFFFFFFF", + "112": "FFFFFFFF", + "113": "FFFFFFFF", + "114": "FFFFFFFF", + "115": "FFFFFFFF", + "116": "FFFFFFFF", + "117": "FFFFFFFF", + "118": "FFFFFFFF", + "119": "FFFFFFFF", + "120": "FFFFFFFF", + "121": "FFFFFFFF", + "122": "FFFFFFFF", + "123": "FFFFFFFF", + "124": "FFFFFFFF", + "125": "FFFFFFFF", + "126": "FFFFFFFF", + "127": "FFFFFFFF", + "128": "FFFFFFFE" + } +} diff --git a/traces/mifare/hf-mfdes-ev1-4k-empty-keys.json b/traces/mifare/hf-mfdes-ev1-4k-empty-keys.json new file mode 100644 index 000000000..f18fbe887 --- /dev/null +++ b/traces/mifare/hf-mfdes-ev1-4k-empty-keys.json @@ -0,0 +1,11 @@ +{ + "Created": "proxmark3", + "FileType": "mfdes v2", + "Card": { + "UID": "04268512A25680", + "SAK": "20", + "ATQA": "4403", + "ATS": "06757781028002F0" + }, + "Applications": {} +} diff --git a/traces/mifare/hf-mfdes-ev1-4k-empty.json b/traces/mifare/hf-mfdes-ev1-4k-empty.json new file mode 100644 index 000000000..73b7023d7 --- /dev/null +++ b/traces/mifare/hf-mfdes-ev1-4k-empty.json @@ -0,0 +1,30 @@ +{ + "Created": "proxmark3", + "FileType": "mfdes v1", + "Version": 1, + "Card": { + "UID": "04268512A25680", + "ATQA": "4403", + "SAK": "20", + "ATS": "06757781028002F0", + "VersionHW": "04010101001805", + "VersionSW": "04010101041805", + "VersionProd": "04268512A25680B90C1749702717", + "FreeMem": 3840 + }, + "Applications": { + "000000": { + "KeySettings": "0F", + "NumKeysRaw": "01", + "NumKeys": 1, + "KeyType": "2tdea", + "Authenticated": true, + "Keys": { + "0": { + "Version": "00", + "Key": "00000000000000000000000000000000" + } + } + } + } +} diff --git a/traces/mifare/hf-mfdes-ev1-8k-empty-keys.json b/traces/mifare/hf-mfdes-ev1-8k-empty-keys.json new file mode 100644 index 000000000..f18fbe887 --- /dev/null +++ b/traces/mifare/hf-mfdes-ev1-8k-empty-keys.json @@ -0,0 +1,11 @@ +{ + "Created": "proxmark3", + "FileType": "mfdes v2", + "Card": { + "UID": "04268512A25680", + "SAK": "20", + "ATQA": "4403", + "ATS": "06757781028002F0" + }, + "Applications": {} +} diff --git a/traces/mifare/hf-mfdes-ev1-8k-empty.json b/traces/mifare/hf-mfdes-ev1-8k-empty.json new file mode 100644 index 000000000..887fe7dca --- /dev/null +++ b/traces/mifare/hf-mfdes-ev1-8k-empty.json @@ -0,0 +1,30 @@ +{ + "Created": "proxmark3", + "FileType": "mfdes v1", + "Version": 1, + "Card": { + "UID": "04268512A25680", + "ATQA": "4403", + "SAK": "20", + "ATS": "06757781028002F0", + "VersionHW": "04010101001A05", + "VersionSW": "04010101041A05", + "VersionProd": "04268512A25680B90C1749702717", + "FreeMem": 7936 + }, + "Applications": { + "000000": { + "KeySettings": "0F", + "NumKeysRaw": "01", + "NumKeys": 1, + "KeyType": "2tdea", + "Authenticated": true, + "Keys": { + "0": { + "Version": "00", + "Key": "00000000000000000000000000000000" + } + } + } + } +} \ No newline at end of file diff --git a/traces/mifare/hf-mfdes-ev1-8k-test-keys.json b/traces/mifare/hf-mfdes-ev1-8k-test-keys.json new file mode 100644 index 000000000..49e024fbd --- /dev/null +++ b/traces/mifare/hf-mfdes-ev1-8k-test-keys.json @@ -0,0 +1,54 @@ +{ + "Created": "proxmark3", + "FileType": "mfdes v2", + "Card": { + "UID": "04268512A25680", + "SAK": "20", + "ATQA": "4403", + "ATS": "06757781028002F0" + }, + "Applications": { + "010203": { + "AES": { + "0": { + "Key": "0102030405060708090A0B0C0D0E0F10" + }, + "1": { + "Key": "0102030405060708090A0B0C0D0E0F10" + }, + "2": { + "Key": "0102030405060708090A0B0C0D0E0F10" + } + } + }, + "112233": { + "2TDEA": { + "0": { + "Key": "0102030405060708090A0B0C0D0E0F10" + }, + "1": { + "Key": "0102030405060708090A0B0C0D0E0F10" + } + } + }, + "AABBCC": { + "3TDEA": { + "0": { + "Key": "0102030405060708090A0B0C0D0E0F101112131415161718" + }, + "1": { + "Key": "0102030405060708090A0B0C0D0E0F101112131415161718" + }, + "2": { + "Key": "0102030405060708090A0B0C0D0E0F101112131415161718" + }, + "3": { + "Key": "0102030405060708090A0B0C0D0E0F101112131415161718" + }, + "4": { + "Key": "0102030405060708090A0B0C0D0E0F101112131415161718" + } + } + } + } +} \ No newline at end of file diff --git a/traces/mifare/hf-mfdes-ev1-8k-test.json b/traces/mifare/hf-mfdes-ev1-8k-test.json new file mode 100644 index 000000000..3f6cbcfe1 --- /dev/null +++ b/traces/mifare/hf-mfdes-ev1-8k-test.json @@ -0,0 +1,179 @@ +{ + "Created": "proxmark3", + "FileType": "mfdes v1", + "Version": 1, + "Card": { + "UID": "04268512A25680", + "ATQA": "4403", + "SAK": "20", + "ATS": "06757781028002F0", + "VersionHW": "04010101001A05", + "VersionSW": "04010101041A05", + "VersionProd": "04268512A25680B90C1749702717", + "FreeMem": 6400 + }, + "Applications": { + "000000": { + "KeySettings": "0F", + "NumKeysRaw": "01", + "NumKeys": 1, + "KeyType": "2tdea", + "Authenticated": true, + "Keys": { + "0": { + "Version": "00", + "Key": "0102030405060708090A0B0C0D0E0F10" + } + } + }, + "010203": { + "ISOFileID": "1234", + "DFName": "7465737431", + "KeySettings": "0B", + "NumKeysRaw": "83", + "NumKeys": 3, + "KeyType": "aes", + "Authenticated": true, + "Keys": { + "0": { + "Version": "00", + "Key": "0102030405060708090A0B0C0D0E0F10" + }, + "1": { + "Version": "00", + "Key": "0102030405060708090A0B0C0D0E0F10" + }, + "2": { + "Version": "00", + "Key": "0102030405060708090A0B0C0D0E0F10" + } + }, + "Files": { + "01": { + "Type": "standard", + "TypeRaw": "00", + "CommMode": "plain", + "AccessRights": "EEEE", + "ISOFileID": "0001", + "FileSize": 256, + "Read": true, + "Data": "50726F786D61726B3320444553466972652045563120384B20746573742063617264000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + }, + "02": { + "Type": "backup", + "TypeRaw": "01", + "CommMode": "mac", + "AccessRights": "1200", + "ISOFileID": "0002", + "FileSize": 128, + "Read": true, + "Data": "6261636B75702066696C6520636F6E74656E7400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + } + } + }, + "112233": { + "ISOFileID": "2345", + "DFName": "7465737432", + "KeySettings": "0B", + "NumKeysRaw": "02", + "NumKeys": 2, + "KeyType": "2tdea", + "Authenticated": true, + "Keys": { + "0": { + "Version": "00", + "Key": "0102030405060708090A0B0C0D0E0F10" + }, + "1": { + "Version": "00", + "Key": "0102030405060708090A0B0C0D0E0F10" + } + }, + "Files": { + "00": { + "Type": "value", + "TypeRaw": "02", + "CommMode": "plain", + "AccessRights": "EE00", + "LowerLimit": 0, + "UpperLimit": 10000, + "LimitedCredit": "00", + "Value": 1000, + "Read": true + }, + "01": { + "Type": "linear_record", + "TypeRaw": "03", + "CommMode": "plain", + "AccessRights": "EE00", + "ISOFileID": "0011", + "RecordSize": 16, + "MaxRecords": 8, + "CurRecords": 2, + "Read": true, + "Records": { + "0": "6C696E65617220726563202330310000", + "1": "6C696E65617220726563202330320000" + } + } + } + }, + "AABBCC": { + "ISOFileID": "3456", + "DFName": "7465737433", + "KeySettings": "0B", + "NumKeysRaw": "45", + "NumKeys": 5, + "KeyType": "3tdea", + "Authenticated": true, + "Keys": { + "0": { + "Version": "00", + "Key": "0102030405060708090A0B0C0D0E0F101112131415161718" + }, + "1": { + "Version": "00", + "Key": "0102030405060708090A0B0C0D0E0F101112131415161718" + }, + "2": { + "Version": "00", + "Key": "0102030405060708090A0B0C0D0E0F101112131415161718" + }, + "3": { + "Version": "00", + "Key": "0102030405060708090A0B0C0D0E0F101112131415161718" + }, + "4": { + "Version": "00", + "Key": "0102030405060708090A0B0C0D0E0F101112131415161718" + } + }, + "Files": { + "05": { + "Type": "cyclic_record", + "TypeRaw": "04", + "CommMode": "plain", + "AccessRights": "EE00", + "ISOFileID": "0055", + "RecordSize": 24, + "MaxRecords": 4, + "CurRecords": 1, + "Read": true, + "Records": { + "0": "6379636C6963207265636F72642023310000000000000000" + } + }, + "03": { + "Type": "standard", + "TypeRaw": "00", + "CommMode": "plain", + "AccessRights": "EEEE", + "ISOFileID": "0033", + "FileSize": 64, + "Read": true, + "Data": "667265652072656164207374642066696C6500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + } + } + } + } +} \ No newline at end of file