diff --git a/Installation_Instructions/Arch-Linux-Installation-Instructions.md b/Installation_Instructions/Arch-Linux-Installation-Instructions.md
new file mode 100644
index 000000000..28245dbfa
--- /dev/null
+++ b/Installation_Instructions/Arch-Linux-Installation-Instructions.md
@@ -0,0 +1,60 @@
+# Setup and build for ArchLinux
+
+## Notes
+
+Kali and ArchLinux users usually must kill their modem manager in order for the proxmark3 to enumerate properly.
+`sudo apt remove modemmanager`
+
+## Manual Installation
+Run
+```sh
+sudo pacman -Sy base-devel p7zip libusb readline ncurses arm-none-eabi-newlib --needed
+```
+```sh
+yaourt -S termcap
+```
+
+```sh
+sudo apt remove modemmanager
+```
+or
+```sh
+systemctl stop ModemManager
+systemctl disable ModemManager
+```
+
+Clone fork
+```sh
+git clone https://github.com/RfidResearchGroup/proxmark3.git
+```
+
+Get the latest commits
+```sh
+git pull
+```
+
+Install the blacklist rules and add user to dialout group (if you on a Linux/ubuntu/debian).
+If you do this one, you need to logout and login in again to make sure your rights got changed.
+```sh
+make udev
+```
+
+Clean and complete compilation
+```sh
+make clean && make all
+```
+
+Flash the BOOTROM & FULLIMAGE
+```sh
+client/flasher /dev/ttyACM0 -b bootrom/obj/bootrom.elf armsrc/obj/fullimage.elf
+```
+
+Change into the client folder
+```sh
+cd client
+```
+
+Run the client
+```sh
+./proxmark3 /dev/ttyACM0
+```
diff --git a/Installation_Instructions/Coverity-Scan-Config-&-Run.md b/Installation_Instructions/Coverity-Scan-Config-&-Run.md
new file mode 100644
index 000000000..9979c41e1
--- /dev/null
+++ b/Installation_Instructions/Coverity-Scan-Config-&-Run.md
@@ -0,0 +1,24 @@
+
+## Coverity Scan Config & Run
+Download the Coverity Scan Self-buld and install it.
+You will need to configure ARM-NON-EABI- Compiler for it to use:
+
+ Configure
+
+```sh
+cov-configure --comptype gcc --compiler /opt/devkitpro/devkitARM/bin/arm-none-eabi-gcc
+```
+
+Run it (I'm running on Ubuntu)
+
+```sh
+cov-build --dir cov-int make all
+```
+
+Make a tarball
+
+```sh
+tar czvf proxmark3.tgz cov-int
+```
+
+Upload it to coverity.com
diff --git a/Installation_Instructions/Kali-Installation-Instructions.md b/Installation_Instructions/Kali-Installation-Instructions.md
new file mode 100644
index 000000000..4d65afead
--- /dev/null
+++ b/Installation_Instructions/Kali-Installation-Instructions.md
@@ -0,0 +1,98 @@
+# Kali Installation
+Kali users usually must kill their modem manager in order for the proxmark3 to enumerate properly.
+```sh
+sudo apt remove modemmanager
+```
+
+# Video Installation guide
+[](https://youtu.be/t5eBPS6lV3E "Kali Linux Installation Tutorial")
+
+
+---
+## Manual Install
+First what we want to do is get an update for the system. If you need to upgrade do this **before** the install
+An upgrade was carried out prior to following these instructions.
+
+### Update
+```sh
+sudo apt-get update
+```
+### Requirements.
+
+```sh
+sudo apt-get install p7zip git build-essential libreadline5 libreadline-dev \
+libusb-0.1-4 libusb-dev libqt4-dev perl pkg-config wget libncurses5-dev gcc-arm-none-eabi
+```
+If you do get any issues during the requirements installation, I have found it to help using the synaptic package manager.
+
+### Clone Fork
+```sh
+git clone https://github.com/RfidResearchGroup/proxmark3.git
+```
+
+### Change directory into the directory created
+```sh
+cd proxmark3
+```
+
+### Get the latest commits
+```sh
+git pull
+```
+
+### Remove Modem Manager
+```sh
+sudo apt remove modemmanager
+```
+### Reboot Kali
+```sh
+ reboot
+```
+
+### Change directory back to proxmark3
+```sh
+cd proxmark3
+```
+
+### Clean and Compile
+Clean and complete compile
+
+```sh
+ make clean && make all
+```
+### Check Connection
+Once this is complete run the following comands to make sure the proxmark is being picked up by your computer.
+
+```sh
+sudo dmesg | grep -i usb
+```
+It should show up as a CDC device:
+```sh
+[10416.555108] usb 2-1.2: Product: PM3
+[10416.555111] usb 2-1.2: Manufacturer: proxmark.org
+[10416.555871] cdc_acm 2-1.2:1.0: ttyACM0: USB ACM device
+```
+
+### Flash the BOOTROM & FULLIMAGE
+ ```sh
+ client/flasher /dev/ttyACM0 -b bootrom/obj/bootrom.elf armsrc/obj/fullimage.elf
+```
+> **Note** If you have any issues connecting or during the flash, follow the steps listed [here](https://github.com/RfidResearchGroup/proxmark3/issues/35) and use the command sudo apt remove modemmanager
+
+
+### Change into the client folder
+
+```sh
+cd client
+```
+
+### Run the client
+ ```sh
+./proxmark3 /dev/ttyACM0
+```
+
+### Run a test command
+ ```sh
+hw tune
+```
+
diff --git a/Installation_Instructions/Mac-OS-X-Homebrew-Installation-Instructions.md b/Installation_Instructions/Mac-OS-X-Homebrew-Installation-Instructions.md
new file mode 100644
index 000000000..61ab754d5
--- /dev/null
+++ b/Installation_Instructions/Mac-OS-X-Homebrew-Installation-Instructions.md
@@ -0,0 +1,29 @@
+## Homebrew (Mac OS X)
+These instructions comes from @Chrisfu, where I got the proxmark3.rb scriptfile from.
+Further questions about Mac & Homebrew, contact @Chrisfu (https://github.com/chrisfu/)
+
+1. Install homebrew if you haven't yet already done so: http://brew.sh/
+
+2. Tap this repo: `brew tap RfidResearchGroup/proxmark3`
+
+3. Install Proxmark3: `brew install proxmark3` for stable release or `brew install --HEAD proxmark3` for latest non-stable from GitHub.
+
+Upgrading HomeBrew tap formula
+-----------------------------
+*This method is useful for those looking to run bleeding-edge versions of iceman's client. Keep this in mind when attempting to update your HomeBrew tap formula as this procedure could easily cause a build to break if an update is unstable on macOS.*
+
+Tested on macOS High Sierra 10.13.2
+
+*Note: This assumes you have already installed iceman's fork from HomeBrew as mentioned above*
+
+1. Force HomeBrew to pull the latest source from github
+`brew upgrade --fetch-HEAD RfidResearchGroup/proxmark3`
+
+2. Flash the bootloader & fullimage.elf
+ * With your Proxmark3 unplugged from your machine, press and hold the button on your Proxmark 3 as you plug it into a USB port. Continue to hold the button until after this step is complete and the `proxmark3-flasher` command outputs "Have a nice day!"*
+ `$ sudo proxmark3-flasher /dev/tty.usbmodem881 -b /usr/local/Cellar/proxmark3/HEAD-6a710ef/share/firmware/bootrom.elf /usr/local/Cellar/proxmark3/HEAD-6a710ef/share/firmware/fullimage.elf`
+
+
+`$ sudo proxmark3-flasher /dev/tty.usbmodem881 `
+
+4. Enjoy the update
diff --git a/Installation_Instructions/Parrot-OS-Proxmark3-RDV4-installation.md b/Installation_Instructions/Parrot-OS-Proxmark3-RDV4-installation.md
new file mode 100644
index 000000000..7b6187e1a
--- /dev/null
+++ b/Installation_Instructions/Parrot-OS-Proxmark3-RDV4-installation.md
@@ -0,0 +1,98 @@
+
+# Parrot OS Installation
+
+## Notes
+
+Some further notes can be found at @5w0rdfish repo [Proxmark Installation for Parrot OS](https://github.com/5w0rdfish/Proxmark3-RDV4-ParrotOS)
+
+# Video Installation guide
+[](https://youtu.be/Wl9AsrU4igo "ParrotOS Installation Tutorial")
+
+
+---
+## Manual Install
+First what we want to do is get an update for the system. If you need to upgrade do this **before** the install
+
+### Update
+```sh
+sudo apt-get update
+```
+### Requirements.
+
+```sh
+sudo apt-get install p7zip git build-essential libreadline5 libreadline-dev \
+libusb-0.1-4 libusb-dev libqt4-dev perl pkg-config wget libncurses5-dev gcc-arm-none-eabi
+```
+If you do get any issues during the requirements installation, I have found it to help using the synaptic package manager.
+
+### Clone Fork
+```sh
+git clone https://github.com/RfidResearchGroup/proxmark3.git
+```
+
+### Change directory into the directory created
+```sh
+cd proxmark3
+```
+
+### Get the latest commits
+```sh
+git pull
+```
+
+### Make Udev
+Iceman has made the udev script which takes care of the blacklist rules. This should take care of the remove modem manager.
+The make udev command also create's an alias for the pm3 under /dev which you will use to connect to the proxmark.
+
+```sh
+sudo make udev
+```
+
+> **Note** If you have any issues connecting or during the flash, follow the steps listed [here](https://github.com/RfidResearchGroup/proxmark3/issues/35) and use the command sudo apt remove modemmanager
+
+Log out and log back in again. And now we are all set to take the next step.
+
+### Clean and Compile
+Clean and complete compilation *within the proxmark3 folder*
+
+```sh
+ make clean && make all
+```
+### Check Connection
+Once this is complete run the following comands to make sure the proxmark is being picked up by your computer.
+
+```sh
+sudo dmesg | grep -i usb
+```
+It should show up as a CDC device:
+```sh
+[10416.555108] usb 2-1.2: Product: PM3
+[10416.555111] usb 2-1.2: Manufacturer: proxmark.org
+[10416.555871] cdc_acm 2-1.2:1.0: ttyACM0: USB ACM device
+```
+
+### Flash the BOOTROM & FULLIMAGE
+ ```sh
+ client/flasher /dev/ttyACM0 -b bootrom/obj/bootrom.elf armsrc/obj/fullimage.elf
+```
+### Change into the client folder
+
+```sh
+cd client
+```
+### Run the client
+ ``` sh
+./proxmark3 /dev/pm #press tab on the keyboard for it to detect the proxmark
+```
+or
+
+### Run the client
+ ```sh
+./proxmark3 /dev/ttyACM0
+```
+
+### Run a test command
+ ```sh
+hw tune
+```
+
diff --git a/Installation_Instructions/Ubuntu-Installation-Instructions.md b/Installation_Instructions/Ubuntu-Installation-Instructions.md
new file mode 100644
index 000000000..6df3b704e
--- /dev/null
+++ b/Installation_Instructions/Ubuntu-Installation-Instructions.md
@@ -0,0 +1,102 @@
+# Setup and build for UBUNTU
+## Notes
+GC made updates to allow this to build easily on Ubuntu 14.04.2 LTS, 15.10 or 16.04
+See the [Proxmark3 Ubuntu wiki page](https://github.com/Proxmark/proxmark3/wiki/Ubuntu%20Linux)
+
+A nice and cool install script made by @daveio is found here:
+https://github.com/daveio/attacksurface/blob/master/proxmark3/pm3-setup.sh
+
+Iceman has also added this script to the fork.
+https://github.com/RfidResearchGroup/proxmark3/blob/master/install.sh
+
+# Video Installation guide
+[](https://youtu.be/DThmkH8CdMo "Ubuntu Installation Tutorial")
+
+---
+## Manual Installation
+### Update
+
+```sh
+sudo apt-get update
+```
+### Requirements
+
+```sh
+sudo apt-get install p7zip git build-essential libreadline5 libreadline-dev libusb-0.1-4 libusb-dev libqt4-dev perl pkg-config wget libncurses5-dev gcc-arm-none-eabi
+```
+
+### Clone Fork
+
+```sh
+git clone https://github.com/RfidResearchGroup/proxmark3.git
+```
+### Change Directory
+
+```sh
+cd proxmark3
+```
+
+### Get the latest commits
+
+```sh
+git pull
+```
+
+### Install the blacklist rules and add user to dialout group.
+
+```sh
+sudo make udev
+```
+
+### Restart
+Restart Ubuntu
+
+### Enter proxmark folder
+```sh
+cd proxmark3
+```
+### Clean and Compile
+```sh
+make clean && make all
+```
+### Check Connection
+Once this is complete run the following comands to make sure the proxmark is being picked up by your computer.
+
+```sh
+sudo dmesg | grep -i usb
+```
+
+### Flash the BOOTROM & FULLIMAGE
+ ```sh
+ client/flasher /dev/ttyACM0 -b bootrom/obj/bootrom.elf armsrc/obj/fullimage.elf
+```
+
+### Issues
+If you have issues with the install please try the following below or head on over to the proxmark forum.
+#### Remove Modem Manager
+
+```sh
+sudo apt remove modemmanager
+```
+and then restart ubuntu.
+
+### Change into the client folder
+```sh
+cd client
+```
+
+### Run the client
+ ``` sh
+./proxmark3 /dev/pm #press tab on the keyboard for it to detect the proxmark
+```
+or
+
+### Run the client
+ ```sh
+./proxmark3 /dev/ttyACM0
+```
+
+### Run a test command
+ ```sh
+hw tune
+```
diff --git a/Installation_Instructions/Windows-Installation-Instructions.md b/Installation_Instructions/Windows-Installation-Instructions.md
new file mode 100644
index 000000000..6a20a510f
--- /dev/null
+++ b/Installation_Instructions/Windows-Installation-Instructions.md
@@ -0,0 +1,83 @@
+# Building on Windows
+You will need to use the Gator96100 Proxspace package to assist in your windows installation.
+This can be downloaded from https://github.com/Gator96100/ProxSpace/
+
+## Notes
+If you receive gcc errors using v3.1 during build, download and use v2.2. This may help resolve the issue.
+
+- https://github.com/Gator96100/ProxSpace/releases/tag/v3.1 (release v3.1 with gcc v7.3.0 )
+- https://github.com/Gator96100/ProxSpace/releases/tag/v2.2 (release v2.2 with gcc v5.3.0 arm-none-eabi-gcc v7.1.0)
+
+---
+# Video Installation guide
+[](https://youtu.be/zzF0NCMJnYU "Windows Installation Tutorial")
+
+## Manual Installation
+
+### Driver Installation
+
+Install required drivers for your windows installation. You will may need admin privileges to do this.
+(This is covered in the video) Step by step guides are online such as [RiscCorps](https://store.ryscc.com/blogs/news/how-to-install-a-proxmark3-driver-on-windows-10)
+
+### Install Github
+
+Install Github for Windows https://desktop.github.com/
+
+### Download / clone Proxspace repo
+
+Download the required proxspace repo. https://github.com/Gator96100/ProxSpace/
+
+Extract 'ProxSpace' to a location on drive without spaces.
+For example D:\OneDrive\Documents\GitHub is ok whereas C:\My Documents\My Projects\proxspace is not.
+
+### Clone RFID RESEARCH GROUP files
+
+Clone fork
+```sh
+git clone https://github.com/RfidResearchGroup/proxmark3.git
+```
+### Copy files to Proxspace
+
+Copy all the contents from the proxmark3 folder into the proxspace pm3 folder
+
+### Run the .bat
+
+Run runme.bat or runme64.bat depending on your Windows architecture.
+
+Please note you will need to use / as you are using BASH.
+
+### Make
+
+CLEAN COMPILE inside the pm3 window.
+```sh
+make clean && make all
+```
+### Flash the image
+
+Flash the BOOTROM & FULLIMAGE
+```sh
+client/flasher.exe comX -b bootrom/obj/bootrom.elf armsrc/obj/fullimage.elf
+```
+
+### Run the client
+
+Assuming you have Proxmark3 Windows drivers installed you can run the Proxmark software where "X" is the com port number assigned to proxmark3 under Windows.
+
+Change into the client folder
+```sh
+cd client
+```
+
+Run the client
+```sh
+./proxmark3.exe comX
+```
+
+### Test
+
+Check your firmware revision on the Proxmark III with
+```sh
+hw ver
+```
+For basic help type help. Or for help on a set of sub commands type the command followed by help. For example hf mf help.
+Make sure you head over to the use of [proxmark area](https://github.com/5w0rdfish/proxmark3/tree/master/Use_of_Proxmark) to help you get on your way!
diff --git a/Makefile b/Makefile
index 2ad01ba5f..512c9e2db 100644
--- a/Makefile
+++ b/Makefile
@@ -56,7 +56,7 @@ recovery/%: FORCE
$(MAKE) -C recovery $(patsubst recovery/%,%,$@)
FORCE: # Dummy target to force remake in the subdirectories, even if files exist (this Makefile doesn't know about the prerequisites)
-.PHONY: all clean help _test bootrom flash-bootrom os flash-os flash-all recovery client mfkey nounce2key style FORCE
+.PHONY: all clean help _test bootrom flash-bootrom os flash-os flash-all recovery client mfkey nounce2key style checks FORCE
help:
@echo "Multi-OS Makefile"
@@ -76,6 +76,9 @@ help:
@echo "+ mfkey - Make tools/mfkey"
@echo "+ nounce2key - Make tools/nounce2key"
@echo
+ @echo "+ style - Apply some automated source code formatting rules"
+ @echo "+ checks - Detect various encoding issues in source code"
+ @echo
@echo "Possible platforms: try \"make PLATFORM=\" for more info, default is PM3RDV4"
client: client/all
@@ -133,10 +136,15 @@ style:
-exec sh -c "echo >> {}" \;
# Apply astyle on *.c, *.h, *.cpp
find . \( -name "*.[ch]" -or -name "*.cpp" \) -exec astyle --formatted --mode=c --suffix=none \
- --indent=spaces=4 --indent-switches --indent-preprocessor \
+ --indent=spaces=4 --indent-switches \
--keep-one-line-blocks --max-instatement-indent=60 \
--style=google --pad-oper --unpad-paren --pad-header \
--align-pointer=name {} \;
+# Detecting weird codepages.
+checks:
+ find . \( -name "*.[ch]" -or -name "*.cpp" -or -name "*.lua" -or -name "*.py" -or -name "*.pl" -or -name "Makefile" \) \
+ -exec sh -c "cat {} |recode utf8.. >/dev/null || echo {}" \;
+
# Dummy target to test for GNU make availability
_test:
diff --git a/README.md b/README.md
index cfdbacc61..67e31b794 100644
--- a/README.md
+++ b/README.md
@@ -1,71 +1,33 @@
-Proxmark3 RDV40 dedicated repo, based on iceman fork
+Proxmark3 RDV4.0 Dedicated Github
===============
+This repo is based on iceman fork for proxmark3. It is dedicated to bringing the most out of the new features for proxmark3 RDV4.0 new hardware and design.
+
[](https://github.com/RfidResearchGroup/proxmark3/releases/latest)
-## Notice
-This repo is based on iceman fork for proxmark3. It is dedicated to bring the most out of the new features for proxmark3 RDV40 device.
+
-# Donations
-Nothing says thank you as much as a donation, https://www.patreon.com/iceman1001
+---
-## ToC
-
-- Coverity Scan Config & Run
-- Whats changed?
-- Why didn't you based it on offical PM3 Master?
-- Why don't you add this or that functionality?
-- PM3 GUI
-- Development
-- KALI and ARCHLINUX users
-- Setup and build for UBUNTU
-- Setup and build for ArchLinux
-- Homebrew (Mac OS X)
-- Upgrading HomeBrew tap formula
-- Building on Windows
-- Gator96100 distro
-- Build and run
-- Validating proxmark client functionality
-- Run the following commands
-- Quit client
-- First things on your RDV40
-- Verify sim module firmware version
-
-- The end
-
-## Coverity Scan Config & Run
-Download the Coverity Scan Self-buld and install it.
-You will need to configure ARM-NON-EABI- Compiler for it to use:
-
-- Configure
-
-`cov-configure --comptype gcc --compiler /opt/devkitpro/devkitARM/bin/arm-none-eabi-gcc`
-
-- Run it (I'm running on Ubuntu)
-
-`cov-build --dir cov-int make all`
-
-- Make a tarball
-
-`tar czvf proxmark3.tgz cov-int`
-
-- Upload it to coverity.com
+# PROXMARK INSTALLATION AND OVERVIEW
+| FAQ's & Updates | Installation | Use of the Proxmark |
+| ------------- |:-------------:| -----:|
+|[Whats changed?](#whats-changed) | [Setup and build for ArchLinux](/Installation_Instructions/Arch-Linux-Installation-Instructions.md) | [Validating proxmark client functionality](/Use_of_Proxmark/1_Validation.md)|
+|[Development](#development) | [Setup and build for UBUNTU](/Installation_Instructions/Ubuntu-Installation-Instructions.md) | [First Use and Verification](/Use_of_Proxmark/2_Configuration-and-Verification.md) |
+| [Why don't you add this or that functionality?](#why-dont-you-add-this-or-that-functionality) | [Homebrew (Mac OS X) & Upgrading HomeBrew Tap Forumula](/Installation_Instructions/Mac-OS-X-Homebrew-Installation-Instructions.md) | [Commands & Features](/Use_of_Proxmark/3_Commands-and-Features.md)|
+|[Why didn't you based it on offical PM3 Master?](#why-didnt-you-based-it-on-offical-pm3-master) |[ParrotOS Installation ](/Installation_Instructions/Parrot-OS-Proxmark3-RDV4-installation.md)|[PM3 GUI](#pm3-gui)
+|[Notices](#notices)|[Setup and build for Windows](/Installation_Instructions/Windows-Installation-Instructions.md)||
+|[Issues](#issues)|[Coverity Scan Config & Run](/Installation_Instructions/Coverity-Scan-Config-%26-Run.md)||
+||[Kali Linux Installation Instructions](/Installation_Instructions/Kali-Installation-Instructions.md)|
+
+---
## Whats changed?
* added flash memory 256kb.
* added smart card module
* added FPC connector
-
----
-## Why didn't you based it on offical PM3 Master?
-The separation from offical pm3 repo gives us very much freedom to create a firmware/client that suits the RDV40 features. We don't want to mess up the offical pm3 repo with RDV40 specific code.
-
-## Why don't you add this or that functionality?
-Give us a hint, and we'll see if we can't merge in the stuff you have.
-
-## PM3 GUI
-The official PM3-GUI from Gaucho will not work.
-The new universial GUI will work. [Proxmark3 Univerisal GUI](https://github.com/burma69/PM3UniversalGUI)
## Development
This fork now compiles just fine on
@@ -75,248 +37,30 @@ This fork now compiles just fine on
- ParrotOS
- WSL (Windows subsystem linux) on Windows 10
- Docker container
+---
+## Why didn't you based it on offical PM3 Master?
+The separation from offical pm3 repo gives us very much freedom to create a firmware/client that suits the RDV40 features. We don't want to mess up the offical pm3 repo with RDV40 specific code.
-## KALI and ARCHLINUX users
+## Why don't you add this or that functionality?
+Give us a hint, and we'll see if we can't merge in the stuff you have.
+
+## PM3 GUI
+The official PM3-GUI from Gaucho will not work.
+The new universial GUI will work. [Proxmark3 Universal GUI](https://github.com/burma69/PM3UniversalGUI)
+
+## Notices
Kali and ArchLinux users usually must kill their modem manager in order for the proxmark3 to enumerate properly.
-```sh
-sudo apt remove modemmanager
-```
-or
-```sh
-systemctl stop ModemManager
-systemctl disable ModemManager
-```
-
-## Setup and build for UBUNTU
-GC made updates to allow this to build easily on Ubuntu 14.04.2 LTS, 15.10 or 16.04
-See https://github.com/Proxmark/proxmark3/wiki/Ubuntu%20Linux
-
-A nice and cool install script made by @daveio is found here:
-https://github.com/daveio/attacksurface/blob/master/proxmark3/pm3-setup.sh
-I have also added this script to the fork.
-https://github.com/RfidResearchGroup/proxmark3/blob/master/install.sh
-
-- Run
-`sudo apt-get install p7zip git build-essential libreadline5 libreadline-dev libusb-0.1-4 libusb-dev libqt4-dev perl pkg-config wget libncurses5-dev gcc-arm-none-eabi`
-
-- Clone fork
-`git clone https://github.com/RfidResearchGroup/proxmark3.git`
-
-- Get the latest commits
-`git pull`
-
-- Install the blacklist rules and add user to dialout group (if you on a Linux/ubuntu/debian). If you do this one, you need to logout and login in again to make sure your rights got changed.
-`make udev`
-
-- Clean and complete compilation
-`make clean && make all`
-
-- Flash the BOOTROM & FULLIMAGE
-`client/flasher /dev/ttyACM0 -b bootrom/obj/bootrom.elf armsrc/obj/fullimage.elf`
-
-- Change into the client folder
-`cd client`
-
-- Run the client
-`./proxmark3 /dev/ttyACM0`
-
-## Setup and build for ArchLinux
-- Run
-`sudo pacman -Sy base-devel p7zip libusb readline ncurses arm-none-eabi-newlib --needed`
-`yaourt -S termcap`
-
-- Remove modemmanager
`sudo apt remove modemmanager`
+
+## Issues
+Please see the [Proxmark Forum](http://www.proxmark.org/forum/index.php) and see if your issue is listed in the first instance google is your friend :) Questions will be answered via the forum by Iceman and the team.
-- Clone fork
-`git clone https://github.com/RfidResearchGroup/proxmark3.git`
+## The end
-- Get the latest commits
-`git pull`
+[@herrmann1001](https://mobile.twitter.com/herrmann1001) at host iuse.se
+July 2018, Sweden
+updated Feb 2019 [@5w0rdfish](https://mobile.twitter.com/5w0rdFish)
-- Install the blacklist rules and add user to dialout group (if you on a Linux/ubuntu/debian). If you do this one, you need to logout and login in again to make sure your rights got changed.
-`make udev`
+# Donations
+Nothing says thank you as much as a donation, https://www.patreon.com/iceman1001
-- Clean and complete compilation
-`make clean && make all`
-
-- Flash the BOOTROM & FULLIMAGE
-`client/flasher /dev/ttyACM0 -b bootrom/obj/bootrom.elf armsrc/obj/fullimage.elf`
-
-- Change into the client folder
-`cd client`
-
-- Run the client
-`./proxmark3 /dev/ttyACM0`
-
-## Homebrew (Mac OS X)
-These instructions comes from @Chrisfu, where I got the proxmark3.rb scriptfile from.
-Further questions about Mac & Homebrew, contact @Chrisfu (https://github.com/chrisfu/)
-
-1. Install homebrew if you haven't yet already done so: http://brew.sh/
-
-2. Tap this repo: `brew tap RfidResearchGroup/proxmark3`
-
-3. Install Proxmark3: `brew install proxmark3` for stable release or `brew install --HEAD proxmark3` for latest non-stable from GitHub.
-
-Upgrading HomeBrew tap formula
------------------------------
-*This method is useful for those looking to run bleeding-edge versions of iceman's client. Keep this in mind when attempting to update your HomeBrew tap formula as this procedure could easily cause a build to break if an update is unstable on macOS.*
-
-Tested on macOS High Sierra 10.13.2
-
-*Note: This assumes you have already installed iceman's fork from HomeBrew as mentioned above*
-
-1. Force HomeBrew to pull the latest source from github
-`brew upgrade --fetch-HEAD RfidResearchGroup/proxmark3`
-
-2. Flash the bootloader & fullimage.elf
- * With your Proxmark3 unplugged from your machine, press and hold the button on your Proxmark 3 as you plug it into a USB port. Continue to hold the button until after this step is complete and the `proxmark3-flasher` command outputs "Have a nice day!"*
- `$ sudo proxmark3-flasher /dev/tty.usbmodem881 -b /usr/local/Cellar/proxmark3/HEAD-6a710ef/share/firmware/bootrom.elf /usr/local/Cellar/proxmark3/HEAD-6a710ef/share/firmware/fullimage.elf`
-
-
-`$ sudo proxmark3-flasher /dev/tty.usbmodem881 `
-
-4. Enjoy the update
-
-
-## Building on Windows
-
-### Gator96100 distro
-Rather than download and install every one of these packages, a new ProxSpace
-environment archive file will be made available for download on the project
-page at @Gator96100's repo
-
-Afterwards just clone the iceman repo or download someone elses.
-Read instructions on @Gator96100 repo page. (https://github.com/Gator96100/ProxSpace/)
-
-Links
-- https://github.com/Gator96100/ProxSpace/releases/tag/v3.1 (release v3.1 with gcc v7.3.0 )
-- https://github.com/Gator96100/ProxSpace/releases/tag/v2.2 (release v2.2 with gcc v5.3.0 arm-none-eabi-gcc v7.1.0)
-
-
-### Build and run
-
-- Clone fork
-`git clone https://github.com/RfidResearchGroup/proxmark3.git`
-
-- Get the latest commits
-`git pull`
-
-- CLEAN COMPILE
-`make clean && make all`
-
-Assuming you have Proxmark3 Windows drivers installed you can run the Proxmark software where "X" is the com port number assigned to proxmark3 under Windows.
-
-- Flash the BOOTROM & FULLIMAGE
-`client/flasher.exe comX -b bootrom/obj/bootrom.elf armsrc/obj/fullimage.elf`
-
-- Change into the client folder
-`cd client`
-
-- Run the client
-`proxmark3.exe comX`
-
-
-## Validating proxmark client functionality
-
-If all went well you should get some information about the firmware and memory usage as well as the prompt, something like this.
-
->[=] UART Setting serial baudrate 460800
->
->Proxmark3 RFID instrument
->
-> [ CLIENT ]
->
-> client: iceman build for RDV40 with flashmem; smartcard;
->
-> [ ARM ]
->
-> bootrom: iceman/master/4517531c-dirty-unclean 2018-12-13 15:42:24
->
-> os: iceman/master/5a34550a-dirty-unclean 2019-01-07 23:04:07
->
-> [ FPGA ]
->
-> LF image built for 2s30vq100 on 2018/ 9/ 8 at 13:57:51
->
-> HF image built for 2s30vq100 on 2018/ 9/ 3 at 21:40:23
->
-> [ Hardware ]
->
->--= uC: AT91SAM7S512 Rev B
->
->--= Embedded Processor: ARM7TDMI
->
->--= Nonvolatile Program Memory Size: 512K bytes, Used: 247065 bytes (47%) Free: 277223 bytes (53%)
->
->--= Second Nonvolatile Program Memory Size: None
->
->--= Internal SRAM Size: 64K bytes
->
->--= Architecture Identifier: AT91SAM7Sxx Series
->
->--= Nonvolatile Program Memory Type: Embedded Flash Memory
->
-> pm3 -->
-
-### Run the following commands
- pm3 --> hw status
- pm3 --> hw version
- pm3 --> hw tune
-
-You are now ready to use your newly upgraded proxmark3 device. Many commands uses the **h** parameter to show a help text. The client uses a arcaic command structure which will be hard to grasp at first. Here are some commands to start off with.
-
- pm3 --> hf
- pm3 --> hf 14a info
- pm3 --> lf
- pm3 --> lf search
-
-### Quit client
- pm3 --> quit
-
-
-### First things on your RDV40
-You will need to run these commands to make sure your rdv4 is prepared
-
- pm3 --> mem load f default_keys m
- pm3 --> mem load f default_pwd t
- pm3 --> mem load f default_iclass_keys i
- pm3 --> lf t55xx deviceconfig a 29 b 17 c 15 d 47 e 15 p
-
-### Verify sim module firmware version
-To make sure you got the latest sim module firmware.
-_Lastest version is v3.11_
-
- pm3 --> hw status
-
-Find version in the long output, look for these two lines
-
- #db# Smart card module (ISO 7816)
- #db# version.................v2.06
-
-This version is obselete. The following command upgrades your device sim module firmware.
-Don't not turn of your device during the execution of this command.
-
- pm3 --> sc upgrade f ../tools/simmodule/SIM011.BIN
-
-You get the following output, this is a successful execution.
-
- [!] WARNING - Smartcard socket firmware upgrade.
- [!] A dangerous command, do wrong and you will brick the smart card socket
- [+] Smartcard socket firmware uploading to PM3
- ..
- [+] Smartcard socket firmware updating, don't turn off your PM3!
- #db# FW 0000
- #db# FW 0080
- #db# FW 0100
- #db# FW 0180
- #db# FW 0200
- #db# FW 0280
- [+] Smartcard socket firmware upgraded successful
-
-
-## the end
-
-`iceman at host iuse.se`
-`July 2018, Sweden`
diff --git a/Use_of_Proxmark/1_Validation.md b/Use_of_Proxmark/1_Validation.md
new file mode 100644
index 000000000..334150fe8
--- /dev/null
+++ b/Use_of_Proxmark/1_Validation.md
@@ -0,0 +1,57 @@
+## 1. Validating proxmark client functionality
+
+If all went well you should get some information about the firmware and memory usage as well as the prompt, something like this.
+We should be able to answer ..can I connect to my proxmark device? does it respond?
+
+>[=] UART Setting serial baudrate 460800
+>
+>Proxmark3 RFID instrument
+>
+> [ CLIENT ]
+>
+> client: iceman build for RDV40 with flashmem; smartcard;
+>
+> [ ARM ]
+>
+> bootrom: iceman/master/4517531c-dirty-unclean 2018-12-13 15:42:24
+>
+> os: iceman/master/5a34550a-dirty-unclean 2019-01-07 23:04:07
+>
+> [ FPGA ]
+>
+> LF image built for 2s30vq100 on 2018/ 9/ 8 at 13:57:51
+>
+> HF image built for 2s30vq100 on 2018/ 9/ 3 at 21:40:23
+>
+> [ Hardware ]
+>
+>--= uC: AT91SAM7S512 Rev B
+>
+>--= Embedded Processor: ARM7TDMI
+>
+>--= Nonvolatile Program Memory Size: 512K bytes, Used: 247065 bytes (47%) Free: 277223 bytes (53%)
+>
+>--= Second Nonvolatile Program Memory Size: None
+>
+>--= Internal SRAM Size: 64K bytes
+>
+>--= Architecture Identifier: AT91SAM7Sxx Series
+>
+>--= Nonvolatile Program Memory Type: Embedded Flash Memory
+>
+> pm3 -->
+
+### Run the following commands
+ pm3 --> hw status
+ pm3 --> hw version
+ pm3 --> hw tune
+
+You are now ready to use your newly upgraded proxmark3 device. Many commands uses the **h** parameter to show a help text. The client uses a arcaic command structure which will be hard to grasp at first. Here are some commands to start off with.
+
+ pm3 --> hf
+ pm3 --> hf 14a info
+ pm3 --> lf
+ pm3 --> lf search
+
+### Quit client
+ pm3 --> quit
diff --git a/Use_of_Proxmark/2_Configuration-and-Verification.md b/Use_of_Proxmark/2_Configuration-and-Verification.md
new file mode 100644
index 000000000..e226652c6
--- /dev/null
+++ b/Use_of_Proxmark/2_Configuration-and-Verification.md
@@ -0,0 +1,38 @@
+### First things on your RDV40
+You will need to run these commands to make sure your rdv4 is prepared
+
+ pm3 --> mem load f default_keys m
+ pm3 --> mem load f default_pwd t
+ pm3 --> mem load f default_iclass_keys i
+ pm3 --> lf t55xx deviceconfig a 29 b 17 c 15 d 47 e 15 p
+
+### Verify sim module firmware version
+To make sure you got the latest sim module firmware.
+_Lastest version is v3.11_
+
+ pm3 --> hw status
+
+Find version in the long output, look for these two lines
+
+ #db# Smart card module (ISO 7816)
+ #db# version.................v2.06
+
+This version is obselete. The following command upgrades your device sim module firmware.
+Don't not turn of your device during the execution of this command.
+
+ pm3 --> sc upgrade f ../tools/simmodule/SIM011.BIN
+
+You get the following output, this is a successful execution.
+
+ [!] WARNING - Smartcard socket firmware upgrade.
+ [!] A dangerous command, do wrong and you will brick the smart card socket
+ [+] Smartcard socket firmware uploading to PM3
+ ..
+ [+] Smartcard socket firmware updating, don't turn off your PM3!
+ #db# FW 0000
+ #db# FW 0080
+ #db# FW 0100
+ #db# FW 0180
+ #db# FW 0200
+ #db# FW 0280
+ [+] Smartcard socket firmware upgraded successful
diff --git a/Use_of_Proxmark/3_Commands-and-Features.md b/Use_of_Proxmark/3_Commands-and-Features.md
new file mode 100644
index 000000000..ecc9aae0f
--- /dev/null
+++ b/Use_of_Proxmark/3_Commands-and-Features.md
@@ -0,0 +1,21 @@
+
+# Commands and Features
+
+## New Features in RDV4
+
+Further details coming soon
+
+### Run the following commands
+ pm3 --> hw status
+ pm3 --> hw version
+ pm3 --> hw tune
+
+You are now ready to use your newly upgraded proxmark3 device. Many commands uses the **h** parameter to show a help text. The client uses a arcaic command structure which will be hard to grasp at first. Here are some commands to start off with.
+
+ pm3 --> hf
+ pm3 --> hf 14a info
+ pm3 --> lf
+ pm3 --> lf search
+
+### Quit client
+ pm3 --> quit
diff --git a/armsrc/BigBuf.h b/armsrc/BigBuf.h
index bdd2003be..12f2521c6 100644
--- a/armsrc/BigBuf.h
+++ b/armsrc/BigBuf.h
@@ -25,22 +25,22 @@
#define CARD_MEMORY_SIZE 4096
#define DMA_BUFFER_SIZE 256 //128 (how big is the dma?!?
-extern uint8_t *BigBuf_get_addr(void);
-extern uint8_t *BigBuf_get_EM_addr(void);
-extern uint16_t BigBuf_max_traceLen(void);
-extern void BigBuf_Clear(void);
-extern void BigBuf_Clear_ext(bool verbose);
-extern void BigBuf_Clear_keep_EM(void);
-extern void BigBuf_Clear_EM(void);
-extern uint8_t *BigBuf_malloc(uint16_t);
-extern void BigBuf_free(void);
-extern void BigBuf_free_keep_EM(void);
-extern void BigBuf_print_status(void);
-extern uint32_t BigBuf_get_traceLen(void);
-extern void clear_trace(void);
-extern void set_tracing(bool enable);
-extern void set_tracelen(uint32_t value);
-extern bool get_tracing(void);
-extern bool RAMFUNC LogTrace(const uint8_t *btBytes, uint16_t iLen, uint32_t timestamp_start, uint32_t timestamp_end, uint8_t *parity, bool readerToTag);
-extern uint8_t emlSet(uint8_t *data, uint32_t offset, uint32_t length);
+uint8_t *BigBuf_get_addr(void);
+uint8_t *BigBuf_get_EM_addr(void);
+uint16_t BigBuf_max_traceLen(void);
+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);
+void BigBuf_free(void);
+void BigBuf_free_keep_EM(void);
+void BigBuf_print_status(void);
+uint32_t BigBuf_get_traceLen(void);
+void clear_trace(void);
+void set_tracing(bool enable);
+void set_tracelen(uint32_t value);
+bool get_tracing(void);
+bool RAMFUNC LogTrace(const uint8_t *btBytes, uint16_t iLen, uint32_t timestamp_start, uint32_t timestamp_end, uint8_t *parity, bool readerToTag);
+uint8_t emlSet(uint8_t *data, uint32_t offset, uint32_t length);
#endif /* __BIGBUF_H */
diff --git a/armsrc/Makefile b/armsrc/Makefile
index 7a24b109f..5ec73b2b3 100644
--- a/armsrc/Makefile
+++ b/armsrc/Makefile
@@ -60,15 +60,14 @@ APP_CFLAGS = $(PLATFORM_DEFS) \
SRC_LF = lfops.c hitag2_crypto.c hitag2.c hitagS.c lfsampling.c pcf7931.c lfdemod.c
SRC_ISO15693 = iso15693.c iso15693tools.c
-#SRC_ISO14443a = iso14443a.c mifareutil.c mifarecmd.c epa.c mifaresim.c
-SRC_ISO14443a = iso14443a.c mifareutil.c mifarecmd.c epa.c
+SRC_ISO14443a = iso14443a.c mifareutil.c mifarecmd.c epa.c mifaresim.c
SRC_ISO14443b = iso14443b.c
SRC_FELICA = felica.c
SRC_CRAPTO1 = crypto1.c des.c aes.c desfire_key.c desfire_crypto.c mifaredesfire.c
SRC_CRC = crc.c crc16.c crc32.c
SRC_ICLASS = iclass.c optimized_cipher.c
SRC_LEGIC = legicrf.c legicrfsim.c legic_prng.c
-SRC_BEE = bee.c
+# SRC_BEE = bee.c
# RDV40 related hardware support
ifneq (,$(findstring WITH_FLASH,$(APP_CFLAGS)))
@@ -162,7 +161,6 @@ THUMBSRC = start.c \
string.c \
BigBuf.c \
ticks.c \
- random.c \
hfsnoop.c
diff --git a/armsrc/Standalone/hf_bog.c b/armsrc/Standalone/hf_bog.c
index 40f3abba9..36e600392 100644
--- a/armsrc/Standalone/hf_bog.c
+++ b/armsrc/Standalone/hf_bog.c
@@ -85,7 +85,7 @@ void RAMFUNC SniffAndStore(uint8_t param) {
uint8_t *data = dmaBuf;
uint8_t previous_data = 0;
- int dataLen = 0;
+ int dataLen;
bool TagIsActive = false;
bool ReaderIsActive = false;
@@ -110,7 +110,7 @@ void RAMFUNC SniffAndStore(uint8_t param) {
// triggered == false -- to wait first for card
bool triggered = !(param & 0x03);
- uint32_t rsamples = 0;
+ uint32_t my_rsamples = 0;
// Current captured passwords counter
uint8_t auth_attempts = 0;
@@ -151,11 +151,11 @@ void RAMFUNC SniffAndStore(uint8_t param) {
LED_A_OFF();
// Need two samples to feed Miller and Manchester-Decoder
- if (rsamples & 0x01) {
+ if (my_rsamples & 0x01) {
if (!TagIsActive) { // no need to try decoding reader data if the tag is sending
uint8_t readerdata = (previous_data & 0xF0) | (*data >> 4);
- if (MillerDecoding(readerdata, (rsamples - 1) * 4)) {
+ if (MillerDecoding(readerdata, (my_rsamples - 1) * 4)) {
LED_C_ON();
// check - if there is a short 7bit request from reader
@@ -190,7 +190,7 @@ void RAMFUNC SniffAndStore(uint8_t param) {
// no need to try decoding tag data if the reader is sending - and we cannot afford the time
if (!ReaderIsActive) {
uint8_t tagdata = (previous_data << 4) | (*data & 0x0F);
- if (ManchesterDecoding(tagdata, 0, (rsamples - 1) * 4)) {
+ if (ManchesterDecoding(tagdata, 0, (my_rsamples - 1) * 4)) {
LED_B_ON();
if (!LogTrace(receivedResp,
@@ -214,7 +214,7 @@ void RAMFUNC SniffAndStore(uint8_t param) {
}
previous_data = *data;
- rsamples++;
+ my_rsamples++;
data++;
if (data == dmaBuf + DMA_BUFFER_SIZE) {
data = dmaBuf;
diff --git a/armsrc/Standalone/hf_bog.h b/armsrc/Standalone/hf_bog.h
index 8b7d4c695..3dd68b3e2 100644
--- a/armsrc/Standalone/hf_bog.h
+++ b/armsrc/Standalone/hf_bog.h
@@ -6,10 +6,6 @@
// StandAlone Mod
//-----------------------------------------------------------------------------
-#ifndef FALSE
-#define FALSE 0
-#endif
-
#ifndef __HF_BOG_H
#define __HF_BOG_H
@@ -24,8 +20,7 @@
#include
#include "apps.h"
#include "printf.h"
-
#include "parity.h"
-#include "random.h"
+
#endif /* __HF_BOG_H */
diff --git a/armsrc/Standalone/hf_colin.c b/armsrc/Standalone/hf_colin.c
index e6ac015fc..d477fe560 100644
--- a/armsrc/Standalone/hf_colin.c
+++ b/armsrc/Standalone/hf_colin.c
@@ -76,12 +76,14 @@ void cjSetCursLeft() {
void cjTabulize() { DbprintfEx(FLAG_RAWPRINT, "\t\t\t"); }
+/*
void cjPrintKey(uint64_t key, uint8_t *foundKey, uint16_t sectorNo, uint8_t type) {
char tosendkey[13];
sprintf(tosendkey, "%02x%02x%02x%02x%02x%02x", foundKey[0], foundKey[1], foundKey[2], foundKey[3], foundKey[4], foundKey[5]);
cjSetCursRight();
DbprintfEx(FLAG_NOLOG, "SEC: %02x | KEY : %s | TYP: %d", sectorNo, tosendkey, type);
}
+*/
void ReadLastTagFromFlash() {
SpinOff(0);
@@ -89,7 +91,6 @@ void ReadLastTagFromFlash() {
LED_B_ON();
LED_C_ON();
LED_D_ON();
- uint16_t isok = 0;
uint32_t startidx = 0;
uint16_t len = 1024;
@@ -109,7 +110,7 @@ void ReadLastTagFromFlash() {
for (size_t i = 0; i < len; i += size) {
len = MIN((len - i), size);
- isok = Flash_ReadDataCont(startidx + i, mem, len);
+ uint16_t isok = Flash_ReadDataCont(startidx + i, mem, len);
if (isok == len) {
emlSetMem(mem, 0, 64);
} else {
@@ -137,8 +138,6 @@ void WriteTagToFlash(uint8_t index, size_t size) {
LED_C_ON();
LED_D_ON();
- uint8_t isok = 0;
- uint16_t res = 0;
uint32_t len = size;
uint32_t bytes_sent = 0;
uint32_t bytes_remaining = len;
@@ -168,10 +167,10 @@ void WriteTagToFlash(uint8_t index, size_t size) {
memcpy(buff, data + bytes_sent, bytes_in_packet);
bytes_remaining -= bytes_in_packet;
- res = Flash_WriteDataCont(bytes_sent + (index * size), buff, bytes_in_packet);
+ uint16_t res = Flash_WriteDataCont(bytes_sent + (index * size), buff, bytes_in_packet);
bytes_sent += bytes_in_packet;
- isok = (res == bytes_in_packet) ? 1 : 0;
+ uint8_t isok = (res == bytes_in_packet) ? 1 : 0;
if (!isok) {
DbprintfEx(FLAG_NOLOG, "FlashMem write FAILEd [offset %u]", bytes_sent);
@@ -305,14 +304,14 @@ void RunMod() {
// and why not a simple memset abuse to 0xffize the whole space in one go ?
// uint8_t foundKey[2][40][6]; //= [ {0xff} ]; /* C99 abusal 6.7.8.21
uint8_t foundKey[2][40][6];
- for (uint16_t t = 0; t < 2; t++) {
+ for (uint16_t i = 0; i < 2; i++) {
for (uint16_t sectorNo = 0; sectorNo < sectorsCnt; sectorNo++) {
- foundKey[t][sectorNo][0] = 0xFF;
- foundKey[t][sectorNo][1] = 0xFF;
- foundKey[t][sectorNo][2] = 0xFF;
- foundKey[t][sectorNo][3] = 0xFF;
- foundKey[t][sectorNo][4] = 0xFF;
- foundKey[t][sectorNo][5] = 0xFF;
+ foundKey[i][sectorNo][0] = 0xFF;
+ foundKey[i][sectorNo][1] = 0xFF;
+ foundKey[i][sectorNo][2] = 0xFF;
+ foundKey[i][sectorNo][3] = 0xFF;
+ foundKey[i][sectorNo][4] = 0xFF;
+ foundKey[i][sectorNo][5] = 0xFF;
}
}
@@ -465,12 +464,12 @@ failtag:
;
// Type 0 / A first
uint16_t t = 0;
- for (uint16_t sectorNo = 0; sectorNo < sectorsCnt; sectorNo++) {
- num_to_bytes(0x484558414354, 6, foundKey[t][sectorNo]);
- sprintf(tosendkey, "%02x%02x%02x%02x%02x%02x", foundKey[t][sectorNo][0], foundKey[t][sectorNo][1], foundKey[t][sectorNo][2],
- foundKey[t][sectorNo][3], foundKey[t][sectorNo][4], foundKey[t][sectorNo][5]);
+ for (uint16_t s = 0; s < sectorsCnt; s++) {
+ num_to_bytes(0x484558414354, 6, foundKey[t][s]);
+ sprintf(tosendkey, "%02x%02x%02x%02x%02x%02x", foundKey[t][s][0], foundKey[t][s][1], foundKey[t][s][2],
+ foundKey[t][s][3], foundKey[t][s][4], foundKey[t][s][5]);
cjSetCursRight();
- DbprintfEx(FLAG_NOLOG, "SEC: %02x ; KEY : %s ; TYP: %d", sectorNo, tosendkey, t);
+ DbprintfEx(FLAG_NOLOG, "SEC: %02x ; KEY : %s ; TYP: %d", s, tosendkey, t);
}
t = 1;
uint16_t sectorNo = 0;
@@ -611,14 +610,19 @@ failtag:
// emlClearMem();
// A very weak one...
- for (uint16_t t = 0; t < 2; t++) {
- for (uint16_t sectorNo = 0; sectorNo < sectorsCnt; sectorNo++) {
- num_to_bytes(key64, 6, foundKey[t][sectorNo]);
- sprintf(tosendkey, "%02x%02x%02x%02x%02x%02x", foundKey[t][sectorNo][0], foundKey[t][sectorNo][1], foundKey[t][sectorNo][2],
- foundKey[t][sectorNo][3], foundKey[t][sectorNo][4], foundKey[t][sectorNo][5]);
+ for (uint16_t i = 0; i < 2; i++) {
+ for (uint16_t s = 0; s < sectorsCnt; s++) {
+ num_to_bytes(key64, 6, foundKey[i][s]);
+ sprintf(tosendkey, "%02x%02x%02x%02x%02x%02x",
+ foundKey[i][s][0],
+ foundKey[i][s][1],
+ foundKey[i][s][2],
+ foundKey[i][s][3],
+ foundKey[i][s][4],
+ foundKey[i][s][5]
+ );
cjSetCursRight();
-
- DbprintfEx(FLAG_NOLOG, "SEC: %02x ; KEY : %s ; TYP: %d", sectorNo, tosendkey, t);
+ DbprintfEx(FLAG_NOLOG, "SEC: %02x ; KEY : %s ; TYP: %d", s, tosendkey, i);
}
}
trapped = 1;
@@ -644,25 +648,33 @@ failtag:
cjSetCursLeft();
DbprintfEx(FLAG_NOLOG, "%s>>>>>>>>>>>>!*DONE*!<<<<<<<<<<<<<<%s", _GREEN_, _WHITE_);
- ;
+
t = 0;
- for (uint16_t sectorNo = 0; sectorNo < sectorsCnt; sectorNo++) {
- num_to_bytes(0x414c41524f4e, 6, foundKey[t][sectorNo]);
- sprintf(tosendkey, "%02x%02x%02x%02x%02x%02x", foundKey[t][sectorNo][0], foundKey[t][sectorNo][1], foundKey[t][sectorNo][2],
- foundKey[t][sectorNo][3], foundKey[t][sectorNo][4], foundKey[t][sectorNo][5]);
+ for (uint16_t s = 0; s < sectorsCnt; s++) {
+ num_to_bytes(0x414c41524f4e, 6, foundKey[t][s]);
+ sprintf(tosendkey, "%02x%02x%02x%02x%02x%02x",
+ foundKey[t][s][0],
+ foundKey[t][s][1],
+ foundKey[t][s][2],
+ foundKey[t][s][3],
+ foundKey[t][s][4],
+ foundKey[t][s][5]);
cjSetCursRight();
-
- DbprintfEx(FLAG_NOLOG, "SEC: %02x ; KEY : %s ; TYP: %d", sectorNo, tosendkey, t);
- ;
+ DbprintfEx(FLAG_NOLOG, "SEC: %02x ; KEY : %s ; TYP: %d", s, tosendkey, t);
}
- t = 1;
- for (uint16_t sectorNo = 0; sectorNo < sectorsCnt; sectorNo++) {
- num_to_bytes(0x424c41524f4e, 6, foundKey[t][sectorNo]);
- sprintf(tosendkey, "%02x%02x%02x%02x%02x%02x", foundKey[t][sectorNo][0], foundKey[t][sectorNo][1], foundKey[t][sectorNo][2],
- foundKey[t][sectorNo][3], foundKey[t][sectorNo][4], foundKey[t][sectorNo][5]);
- cjSetCursRight();
- DbprintfEx(FLAG_NOLOG, "SEC: %02x ; KEY : %s ; TYP: %d", sectorNo, tosendkey, t);
+ t = 1;
+ for (uint16_t s = 0; s < sectorsCnt; s++) {
+ num_to_bytes(0x424c41524f4e, 6, foundKey[t][s]);
+ sprintf(tosendkey, "%02x%02x%02x%02x%02x%02x",
+ foundKey[t][s][0],
+ foundKey[t][s][1],
+ foundKey[t][s][2],
+ foundKey[t][s][3],
+ foundKey[t][s][4],
+ foundKey[t][s][5]);
+ cjSetCursRight();
+ DbprintfEx(FLAG_NOLOG, "SEC: %02x ; KEY : %s ; TYP: %d", s, tosendkey, t);
}
trapped = 1;
break;
@@ -801,7 +813,6 @@ void e_MifareECardLoad(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *dat
uint8_t numSectors = arg0;
uint8_t keyType = arg1;
- uint64_t ui64Key = 0;
struct Crypto1State mpcs = {0, 0};
struct Crypto1State *pcs;
@@ -823,40 +834,40 @@ void e_MifareECardLoad(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *dat
DbprintfEx(FLAG_RAWPRINT, "Can't select card");
}
- for (uint8_t sectorNo = 0; isOK && sectorNo < numSectors; sectorNo++) {
- ui64Key = emlGetKey(sectorNo, keyType);
- if (sectorNo == 0) {
- if (isOK && mifare_classic_auth(pcs, cjcuid, FirstBlockOfSector(sectorNo), keyType, ui64Key, AUTH_FIRST)) {
+ for (uint8_t s = 0; isOK && s < numSectors; s++) {
+ uint64_t ui64Key = emlGetKey(s, keyType);
+ if (s == 0) {
+ if (isOK && mifare_classic_auth(pcs, cjcuid, FirstBlockOfSector(s), keyType, ui64Key, AUTH_FIRST)) {
isOK = false;
if (MF_DBGLEVEL >= 1)
- DbprintfEx(FLAG_NOLOG, "Sector[%2d]. Auth error", sectorNo);
+ DbprintfEx(FLAG_NOLOG, "Sector[%2d]. Auth error", s);
break;
}
} else {
- if (isOK && mifare_classic_auth(pcs, cjcuid, FirstBlockOfSector(sectorNo), keyType, ui64Key, AUTH_NESTED)) {
+ if (isOK && mifare_classic_auth(pcs, cjcuid, FirstBlockOfSector(s), keyType, ui64Key, AUTH_NESTED)) {
isOK = false;
if (MF_DBGLEVEL >= 1)
- DbprintfEx(FLAG_NOLOG, "Sector[%2d]. Auth nested error", sectorNo);
+ DbprintfEx(FLAG_NOLOG, "Sector[%2d]. Auth nested error", s);
break;
}
}
- for (uint8_t blockNo = 0; isOK && blockNo < NumBlocksPerSector(sectorNo); blockNo++) {
- if (isOK && mifare_classic_readblock(pcs, cjcuid, FirstBlockOfSector(sectorNo) + blockNo, dataoutbuf)) {
+ for (uint8_t blockNo = 0; isOK && blockNo < NumBlocksPerSector(s); blockNo++) {
+ if (isOK && mifare_classic_readblock(pcs, cjcuid, FirstBlockOfSector(s) + blockNo, dataoutbuf)) {
isOK = false;
if (MF_DBGLEVEL >= 1)
- DbprintfEx(FLAG_NOLOG, "Error reading sector %2d block %2d", sectorNo, blockNo);
+ DbprintfEx(FLAG_NOLOG, "Error reading sector %2d block %2d", s, blockNo);
break;
};
if (isOK) {
*datain = 1;
- if (blockNo < NumBlocksPerSector(sectorNo) - 1) {
- emlSetMem(dataoutbuf, FirstBlockOfSector(sectorNo) + blockNo, 1);
+ if (blockNo < NumBlocksPerSector(s) - 1) {
+ emlSetMem(dataoutbuf, FirstBlockOfSector(s) + blockNo, 1);
} else {
// sector trailer, keep the keys, set only the AC
- emlGetMem(dataoutbuf2, FirstBlockOfSector(sectorNo) + blockNo, 1);
+ emlGetMem(dataoutbuf2, FirstBlockOfSector(s) + blockNo, 1);
memcpy(&dataoutbuf2[6], &dataoutbuf[6], 4);
- emlSetMem(dataoutbuf2, FirstBlockOfSector(sectorNo) + blockNo, 1);
+ emlSetMem(dataoutbuf2, FirstBlockOfSector(s) + blockNo, 1);
}
} else {
*datain = 0;
diff --git a/armsrc/Standalone/hf_mattyrun.c b/armsrc/Standalone/hf_mattyrun.c
index 31243739b..1f2fb6f11 100644
--- a/armsrc/Standalone/hf_mattyrun.c
+++ b/armsrc/Standalone/hf_mattyrun.c
@@ -295,17 +295,15 @@ void RunMod() {
/*
Iterates through each sector checking if there is a correct key.
*/
- int key = -1;
- int block = 0;
bool err = 0;
bool allKeysFound = true;
uint32_t size = mfKeysCnt;
for (int type = !keyType; type < 2 && !err; keyType == 2 ? (type++) : (type = 2)) {
- block = blockNo;
+ int block = blockNo;
for (int sec = 0; sec < sectorsCnt && !err; ++sec) {
Dbprintf("\tCurrent sector:%3d, block:%3d, key type: %c, key count: %i ", sec, block, type ? 'B' : 'A', mfKeysCnt);
- key = saMifareChkKeys(block, type, true, size, &keyBlock[0], &key64);
+ int key = saMifareChkKeys(block, type, true, size, &keyBlock[0], &key64);
if (key == -1) {
LED(LED_RED, 50); //red
Dbprintf("\t✕ Key not found for this sector!");
@@ -393,12 +391,12 @@ void RunMod() {
Needs further testing.
*/
if (fillFromEmulator) {
- uint8_t retry = 5, cnt;
+ uint8_t retry = 5;
Dbprintf("\t Trying to dump into blank card.");
int flags = 0;
LED_A_ON(); //yellow
for (int blockNum = 0; blockNum < 16 * 4; blockNum += 1) {
- cnt = 0;
+ uint8_t cnt = 0;
emlGetMem(mblock, blockNum, 1);
// switch on field and send magic sequence
if (blockNum == 0) flags = 0x08 + 0x02;
diff --git a/armsrc/Standalone/hf_young.c b/armsrc/Standalone/hf_young.c
index 4b7a87e99..24e20dd7f 100644
--- a/armsrc/Standalone/hf_young.c
+++ b/armsrc/Standalone/hf_young.c
@@ -166,7 +166,7 @@ void RunMod() {
playing = 1;
} else {
Dbprintf("UID from target tag: %02X%02X%02X%02X", oldBlock0[0], oldBlock0[1], oldBlock0[2], oldBlock0[3]);
- memcpy(newBlock0, oldBlock0, 16);
+ memcpy(newBlock0 + 5, oldBlock0 + 5, 11);
// Copy uid for bank (2nd is for longer UIDs not supported if classic)
memcpy(newBlock0, uids[selected].uid, 4);
diff --git a/armsrc/Standalone/standalone.h b/armsrc/Standalone/standalone.h
index 980bcbf46..334bbc2b4 100644
--- a/armsrc/Standalone/standalone.h
+++ b/armsrc/Standalone/standalone.h
@@ -14,6 +14,6 @@
#include // for bool
#include // PRIu64
-extern void RunMod();
+void RunMod();
#endif /* __STANDALONE_H */
diff --git a/armsrc/appmain.c b/armsrc/appmain.c
index c1967663e..fd0d4cafc 100644
--- a/armsrc/appmain.c
+++ b/armsrc/appmain.c
@@ -23,6 +23,7 @@
#include "lfsampling.h"
#include "BigBuf.h"
#include "mifareutil.h"
+#include "mifaresim.h"
#include "hitag.h"
#define DEBUG 1
@@ -78,10 +79,12 @@ void ToSendStuffBit(int b) {
}
}
+/* useful when debugging new protocol implementations like FeliCa
void PrintToSendBuffer(void) {
DbpString("Printing ToSendBuffer:");
Dbhexdump(ToSendMax, ToSend, 0);
}
+*/
void print_result(char *name, uint8_t *buf, size_t len) {
@@ -159,18 +162,17 @@ void Dbprintf(const char *fmt, ...) {
// prints HEX & ASCII
void Dbhexdump(int len, uint8_t *d, bool bAsci) {
#if DEBUG
- int l = 0, i;
char ascii[9];
while (len > 0) {
- l = (len > 8) ? 8 : len;
+ int l = (len > 8) ? 8 : len;
memcpy(ascii, d, l);
ascii[l] = 0;
// filter safe ascii
- for (i = 0; i < l; i++) {
+ for (int i = 0; i < l; i++) {
if (ascii[i] < 32 || ascii[i] > 126) {
ascii[i] = '.';
}
@@ -230,7 +232,7 @@ uint16_t AvgAdc(int ch) {
void MeasureAntennaTuning(void) {
uint8_t LF_Results[256];
- uint32_t i, adcval = 0, peak = 0, peakv = 0, peakf = 0;
+ uint32_t i, peak = 0, peakv = 0, peakf = 0;
uint32_t v_lf125 = 0, v_lf134 = 0, v_hf = 0; // in mV
memset(LF_Results, 0, sizeof(LF_Results));
@@ -253,7 +255,7 @@ void MeasureAntennaTuning(void) {
WDT_HIT();
FpgaSendCommand(FPGA_CMD_SET_DIVISOR, i);
SpinDelay(20);
- adcval = ((MAX_ADC_LF_VOLTAGE * AvgAdc(ADC_CHAN_LF)) >> 10);
+ uint32_t adcval = ((MAX_ADC_LF_VOLTAGE * AvgAdc(ADC_CHAN_LF)) >> 10);
if (i == 95)
v_lf125 = adcval; // voltage at 125Khz
if (i == 89)
@@ -1177,8 +1179,6 @@ void UsbPacketReceived(uint8_t *packet, int len) {
case CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K: {
LED_B_ON();
uint8_t *mem = BigBuf_get_addr();
- bool isok = false;
- size_t len = 0;
uint32_t startidx = c->arg[0];
uint32_t numofbytes = c->arg[1];
// arg0 = startindex
@@ -1187,8 +1187,8 @@ void UsbPacketReceived(uint8_t *packet, int len) {
//Dbprintf("transfer to client parameters: %" PRIu32 " | %" PRIu32 " | %" PRIu32, startidx, numofbytes, c->arg[2]);
for (size_t i = 0; i < numofbytes; i += USB_CMD_DATA_SIZE) {
- len = MIN((numofbytes - i), USB_CMD_DATA_SIZE);
- isok = cmd_send(CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K, i, len, BigBuf_get_traceLen(), mem + startidx + i, len);
+ size_t len = MIN((numofbytes - i), USB_CMD_DATA_SIZE);
+ bool isok = cmd_send(CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K, i, len, BigBuf_get_traceLen(), mem + startidx + i, len);
if (isok != 0)
Dbprintf("transfer to client failed :: | bytes between %d - %d (%d)", i, i + len, len);
}
@@ -1251,7 +1251,6 @@ void UsbPacketReceived(uint8_t *packet, int len) {
break;
case CMD_FLASHMEM_READ: {
LED_B_ON();
- uint16_t isok = 0;
uint32_t startidx = c->arg[0];
uint16_t len = c->arg[1];
@@ -1269,7 +1268,7 @@ void UsbPacketReceived(uint8_t *packet, int len) {
len = MIN((len - i), size);
Dbprintf("FlashMem reading | %d | %d | %d |", startidx + i, i, len);
- isok = Flash_ReadDataCont(startidx + i, mem, len);
+ uint16_t isok = Flash_ReadDataCont(startidx + i, mem, len);
if (isok == len) {
print_result("Chunk: ", mem, len);
} else {
@@ -1367,8 +1366,6 @@ void UsbPacketReceived(uint8_t *packet, int len) {
LED_B_ON();
uint8_t *mem = BigBuf_malloc(USB_CMD_DATA_SIZE);
- bool isok = false;
- size_t len = 0;
uint32_t startidx = c->arg[0];
uint32_t numofbytes = c->arg[1];
// arg0 = startindex
@@ -1380,9 +1377,9 @@ void UsbPacketReceived(uint8_t *packet, int len) {
}
for (size_t i = 0; i < numofbytes; i += USB_CMD_DATA_SIZE) {
- len = MIN((numofbytes - i), USB_CMD_DATA_SIZE);
+ size_t len = MIN((numofbytes - i), USB_CMD_DATA_SIZE);
- isok = Flash_ReadDataCont(startidx + i, mem, len);
+ bool isok = Flash_ReadDataCont(startidx + i, mem, len);
if (!isok)
Dbprintf("reading flash memory failed :: | bytes between %d - %d", i, len);
diff --git a/armsrc/apps.h b/armsrc/apps.h
index b1a0969f3..b4c38098c 100644
--- a/armsrc/apps.h
+++ b/armsrc/apps.h
@@ -58,15 +58,15 @@ void Dbhexdump(int len, uint8_t *d, bool bAsci);
uint16_t AvgAdc(int ch);
void print_result(char *name, uint8_t *buf, size_t len);
-void PrintToSendBuffer(void);
+//void PrintToSendBuffer(void);
void ToSendStuffBit(int b);
void ToSendReset(void);
void ListenReaderField(int limit);
extern int ToSendMax;
extern uint8_t ToSend[];
-extern void StandAloneMode(void);
-extern void printStandAloneModes(void);
+void StandAloneMode(void);
+void printStandAloneModes(void);
/// lfops.h
extern uint8_t decimation;
@@ -85,9 +85,9 @@ void SimulateTagLowFrequency(int period, int gap, int ledcontrol);
void SimulateTagLowFrequencyBidir(int divisor, int max_bitlen);
void CmdHIDsimTAGEx(uint32_t hi, uint32_t lo, int ledcontrol, int numcycles);
void CmdHIDsimTAG(uint32_t hi, uint32_t lo, int ledcontrol);
-void CmdFSKsimTAG(uint16_t arg1, uint16_t arg2, size_t size, uint8_t *BitStream, int ledcontrol);
-void CmdASKsimTag(uint16_t arg1, uint16_t arg2, size_t size, uint8_t *BitStream, int ledcontrol);
-void CmdPSKsimTag(uint16_t arg1, uint16_t arg2, size_t size, uint8_t *BitStream, int ledcontrol);
+void CmdFSKsimTAG(uint16_t arg1, uint16_t arg2, size_t size, uint8_t *bits, int ledcontrol);
+void CmdASKsimTag(uint16_t arg1, uint16_t arg2, size_t size, uint8_t *bits, int ledcontrol);
+void CmdPSKsimTag(uint16_t arg1, uint16_t arg2, size_t size, uint8_t *bits, int ledcontrol);
void CmdHIDdemodFSK(int findone, uint32_t *high, uint32_t *low, int ledcontrol);
void CmdAWIDdemodFSK(int findone, uint32_t *high, uint32_t *low, int ledcontrol); // Realtime demodulation mode for AWID26
void CmdEM410xdemod(int findone, uint32_t *high, uint64_t *low, int ledcontrol);
@@ -99,8 +99,8 @@ void WriteEM410x(uint32_t card, uint32_t id_hi, uint32_t id_lo);
void CopyIndala64toT55x7(uint32_t hi, uint32_t lo); // Clone Indala 64-bit tag by UID to T55x7
void CopyIndala224toT55x7(uint32_t uid1, uint32_t uid2, uint32_t uid3, uint32_t uid4, uint32_t uid5, uint32_t uid6, uint32_t uid7); // Clone Indala 224-bit tag by UID to T55x7
void T55xxResetRead(void);
-void T55xxWriteBlock(uint32_t Data, uint8_t Block, uint32_t Pwd, uint8_t PwdMode);
-void T55xxWriteBlockExt(uint32_t Data, uint8_t Block, uint32_t Pwd, uint8_t PwdMode);
+void T55xxWriteBlock(uint32_t Data, uint8_t Block, uint32_t Pwd, uint8_t arg);
+void T55xxWriteBlockExt(uint32_t Data, uint8_t Block, uint32_t Pwd, uint8_t arg);
void T55xxReadBlock(uint16_t arg0, uint8_t Block, uint32_t Pwd);
void T55xxWakeUp(uint32_t Pwd);
void T55xx_ChkPwds(void);
@@ -130,20 +130,20 @@ void ReaderIso14443a(UsbCommand *c);
// Also used in iclass.c
//bool RAMFUNC LogTrace(const uint8_t *btBytes, uint16_t len, uint32_t timestamp_start, uint32_t timestamp_end, uint8_t *parity, bool readerToTag);
-void GetParity(const uint8_t *pbtCmd, uint16_t len, uint8_t *parity);
+void GetParity(const uint8_t *pbtCmd, uint16_t len, uint8_t *par);
void iso14a_set_trigger(bool enable);
// also used in emv
-bool prepare_allocated_tag_modulation(tag_response_info_t *response_info);
-int GetIso14443aCommandFromReader(uint8_t *received, uint8_t *parity, int *len);
+//bool prepare_allocated_tag_modulation(tag_response_info_t *response_info);
+//int GetIso14443aCommandFromReader(uint8_t *received, uint8_t *parity, int *len);
// epa.h
void EPA_PACE_Collect_Nonce(UsbCommand *c);
void EPA_PACE_Replay(UsbCommand *c);
// mifarecmd.h
-void MifareReadBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *data);
+void MifareReadBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain);
void MifareUReadBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain);
-void MifareUC_Auth(uint8_t arg0, uint8_t *datain);
+void MifareUC_Auth(uint8_t arg0, uint8_t *keybytes);
void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain);
void MifareReadSector(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain);
void MifareWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain);
@@ -154,7 +154,6 @@ void MifareAcquireEncryptedNonces(uint32_t arg0, uint32_t arg1, uint32_t flags,
void MifareAcquireNonces(uint32_t arg0, uint32_t arg1, uint32_t flags, uint8_t *datain);
void MifareChkKeys(uint16_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain);
void MifareChkKeys_fast(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain);
-void Mifare1ksim(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain);
void MifareSetDbgLvl(uint16_t arg0);
void MifareEMemClr(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain);
void MifareEMemSet(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain);
@@ -212,15 +211,15 @@ void Iso15693InitReader(void);
void RAMFUNC SniffIClass(void);
void SimulateIClass(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain);
void ReaderIClass(uint8_t arg0);
-void ReaderIClass_Replay(uint8_t arg0, uint8_t *MAC);
-void iClass_Authentication(uint8_t *MAC);
+void ReaderIClass_Replay(uint8_t arg0, uint8_t *mac);
+void iClass_Authentication(uint8_t *mac);
void iClass_Authentication_fast(uint64_t arg0, uint64_t arg1, uint8_t *datain);
-void iClass_WriteBlock(uint8_t blockNo, uint8_t *data);
-void iClass_ReadBlk(uint8_t blockNo);
-bool iClass_ReadBlock(uint8_t blockNo, uint8_t *data, uint8_t datalen);
+void iClass_WriteBlock(uint8_t blockno, uint8_t *data);
+void iClass_ReadBlk(uint8_t blockno);
+bool iClass_ReadBlock(uint8_t blockno, uint8_t *data, uint8_t len);
void iClass_Dump(uint8_t blockno, uint8_t numblks);
void iClass_Clone(uint8_t startblock, uint8_t endblock, uint8_t *data);
-void iClass_ReadCheck(uint8_t blockNo, uint8_t keyType);
+void iClass_ReadCheck(uint8_t blockno, uint8_t keytype);
// cmd.h
uint8_t cmd_receive(UsbCommand *cmd);
@@ -230,10 +229,10 @@ uint8_t cmd_send(uint64_t cmd, uint64_t arg0, uint64_t arg1, uint64_t arg2, void
void HfSniff(int, int);
//felica.c
-extern void felica_sendraw(UsbCommand *c);
-extern void felica_sniff(uint32_t samplesToSkip, uint32_t triggersToSkip);
-extern void felica_sim_lite(uint64_t uid);
-extern void felica_dump_lite_s();
+void felica_sendraw(UsbCommand *c);
+void felica_sniff(uint32_t samplesToSkip, uint32_t triggersToSkip);
+void felica_sim_lite(uint64_t uid);
+void felica_dump_lite_s();
#ifdef __cplusplus
diff --git a/armsrc/buzzer.h b/armsrc/buzzer.h
index 801b35a21..082450f04 100644
--- a/armsrc/buzzer.h
+++ b/armsrc/buzzer.h
@@ -20,11 +20,11 @@
#define note_7 506
#define note_8 0
-extern void Ring_BEE_ONCE(uint16_t music_note);
-extern void Ring_BEE_TIME(uint16_t music_note, uint16_t count);
-extern void ring_2_7khz(uint16_t count);
-extern void Ring_ALL(uint16_t count);
-extern void Ring_Little_Star(uint16_t count);
+void Ring_BEE_ONCE(uint16_t music_note);
+void Ring_BEE_TIME(uint16_t music_note, uint16_t count);
+void ring_2_7khz(uint16_t count);
+void Ring_ALL(uint16_t count);
+void Ring_Little_Star(uint16_t count);
#endif
diff --git a/armsrc/flashmem.c b/armsrc/flashmem.c
index 56b564b1d..d2010fe6d 100644
--- a/armsrc/flashmem.c
+++ b/armsrc/flashmem.c
@@ -504,10 +504,12 @@ bool Flash_Erase64k(uint8_t block) {
return true;
}
+/*
// Erase chip
void Flash_EraseChip(void) {
FlashSendLastByte(CHIPERASE);
}
+*/
void Flashmem_print_status(void) {
DbpString("Flash memory");
diff --git a/armsrc/flashmem.h b/armsrc/flashmem.h
index f4258a11b..d899a4d31 100644
--- a/armsrc/flashmem.h
+++ b/armsrc/flashmem.h
@@ -101,9 +101,6 @@
#define MAX_BLOCKS 4
#define MAX_SECTORS 16
-
-
-
#define MCK 48000000
//#define FLASH_BAUD 24000000
#define FLASH_MINFAST 24000000 //33000000
@@ -113,9 +110,8 @@
#define FASTFLASH (FLASHMEM_SPIBAUDRATE > FLASH_MINFAST)
-
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
-extern void Dbprintf(const char *fmt, ...);
+void Dbprintf(const char *fmt, ...);
void FlashmemSetSpiBaudrate(uint32_t baudrate);
bool FlashInit();
@@ -129,7 +125,6 @@ void Flash_TransferAdresse(uint32_t address);
bool Flash_CheckBusy(uint32_t timeout);
-
void Flash_WriteEnable();
bool Flash_WipeMemoryPage(uint8_t page);
bool Flash_WipeMemory();
@@ -137,18 +132,13 @@ bool Flash_Erase4k(uint8_t block, uint8_t sector);
//bool Flash_Erase32k(uint32_t address);
bool Flash_Erase64k(uint8_t block);
-
void Flash_UniqueID(uint8_t *uid);
uint8_t Flash_ReadID(void);
uint16_t Flash_ReadData(uint32_t address, uint8_t *out, uint16_t len);
-
uint16_t Flash_ReadDataCont(uint32_t address, uint8_t *out, uint16_t len);
-
uint16_t Flash_Write(uint32_t address, uint8_t *in, uint16_t len);
uint16_t Flash_WriteData(uint32_t address, uint8_t *in, uint16_t len);
uint16_t Flash_WriteDataCont(uint32_t address, uint8_t *in, uint16_t len);
void Flashmem_print_status(void);
-
-
#endif
diff --git a/armsrc/fpgaloader.c b/armsrc/fpgaloader.c
index 0b94bba45..63957067f 100644
--- a/armsrc/fpgaloader.c
+++ b/armsrc/fpgaloader.c
@@ -229,8 +229,10 @@ static bool reset_fpga_stream(int bitstream_version, z_streamp compressed_fpga_s
compressed_fpga_stream->zalloc = &fpga_inflate_malloc;
compressed_fpga_stream->zfree = &fpga_inflate_free;
- inflateInit2(compressed_fpga_stream, 0);
-
+ int res = inflateInit2(compressed_fpga_stream, 0);
+ if ( res < 0 )
+ return false;
+
fpga_image_ptr = output_buffer;
for (uint16_t i = 0; i < FPGA_BITSTREAM_FIXED_HEADER_SIZE; i++)
diff --git a/armsrc/fpgaloader.h b/armsrc/fpgaloader.h
index ef278cc3e..f9b0e44b0 100644
--- a/armsrc/fpgaloader.h
+++ b/armsrc/fpgaloader.h
@@ -37,7 +37,7 @@ int FpgaGetCurrent(void);
void SetAdcMuxFor(uint32_t whichGpio);
// extern and generel turn off the antenna method
-extern void switch_off(void);
+void switch_off(void);
// definitions for multiple FPGA config files support
#define FPGA_BITSTREAM_LF 1
diff --git a/armsrc/hitag2_crypto.h b/armsrc/hitag2_crypto.h
index 8af1af412..d874955e0 100644
--- a/armsrc/hitag2_crypto.h
+++ b/armsrc/hitag2_crypto.h
@@ -22,13 +22,13 @@ struct hitag2_tag {
uint8_t sectors[12][4];
};
-extern uint32_t _f20(const uint64_t x);
-extern uint64_t _hitag2_init(const uint64_t key, const uint32_t serial, const uint32_t IV);
-extern uint64_t _hitag2_round(uint64_t *state);
-extern uint32_t _hitag2_byte(uint64_t *x);
-extern void hitag2_cipher_reset(struct hitag2_tag *tag, const uint8_t *iv);
-extern int hitag2_cipher_authenticate(uint64_t *cs, const uint8_t *authenticator_is);
-extern int hitag2_cipher_transcrypt(uint64_t *cs, uint8_t *data, uint16_t bytes, uint16_t bits) ;
+uint32_t _f20(const uint64_t x);
+uint64_t _hitag2_init(const uint64_t key, const uint32_t serial, const uint32_t IV);
+uint64_t _hitag2_round(uint64_t *state);
+uint32_t _hitag2_byte(uint64_t *x);
+void hitag2_cipher_reset(struct hitag2_tag *tag, const uint8_t *iv);
+int hitag2_cipher_authenticate(uint64_t *cs, const uint8_t *authenticator_is);
+int hitag2_cipher_transcrypt(uint64_t *cs, uint8_t *data, uint16_t bytes, uint16_t bits) ;
#ifdef __cplusplus
}
#endif
diff --git a/armsrc/hitagS.c b/armsrc/hitagS.c
index cd9573243..5c7bec491 100644
--- a/armsrc/hitagS.c
+++ b/armsrc/hitagS.c
@@ -1451,7 +1451,7 @@ void ReadHitagS(hitag_function htf, hitag_data *htd) {
* Authenticates to the Tag with the given Key or Challenge.
* Writes the given 32Bit data into page_
*/
-void WritePageHitagS(hitag_function htf, hitag_data *htd, int page_) {
+void WritePageHitagS(hitag_function htf, hitag_data *htd, int page) {
StopTicks();
@@ -1467,7 +1467,6 @@ void WritePageHitagS(hitag_function htf, hitag_data *htd, int page_) {
int tag_sof;
int t_wait = HITAG_T_WAIT_MAX;
bool bStop;
- int page = page_;
unsigned char crc;
uint8_t data[4] = {0, 0, 0, 0};
@@ -1509,7 +1508,7 @@ void WritePageHitagS(hitag_function htf, hitag_data *htd, int page_) {
}
}
- Dbprintf("Page: %d", page_);
+ Dbprintf("Page: %d", page);
Dbprintf("DATA: %02X %02X %02X %02X", data[0], data[1], data[2], data[3]);
tag.pstate = HT_READY;
@@ -1582,7 +1581,7 @@ void WritePageHitagS(hitag_function htf, hitag_data *htd, int page_) {
if (rxlen == 0 && tag.tstate == HT_WRITING_PAGE_ACK) {
//no write access on this page
- Dbprintf("no write access on page %d", page_);
+ Dbprintf("no write access on page %d", page);
bStop = !false;
} else if (rxlen == 0 && tag.tstate != HT_WRITING_PAGE_DATA) {
//start the authetication
diff --git a/armsrc/iclass.c b/armsrc/iclass.c
index 1326306b1..fd07a5916 100644
--- a/armsrc/iclass.c
+++ b/armsrc/iclass.c
@@ -855,7 +855,7 @@ void RAMFUNC SniffIClass(void) {
//int datalen = 0;
uint32_t previous_data = 0;
- uint32_t time_0 = 0, time_start = 0, time_stop = 0;
+ uint32_t time_0 = 0, time_start = 0, time_stop;
uint32_t sniffCounter = 0;
bool TagIsActive = false;
bool ReaderIsActive = false;
@@ -1395,7 +1395,7 @@ int doIClassSimulation(int simulationMode, uint8_t *reader_mac_buf) {
// To control where we are in the protocol
uint32_t time_0 = GetCountSspClk();
uint32_t t2r_stime = 0, t2r_etime = 0;
- uint32_t r2t_stime = 0, r2t_etime = 0;
+ uint32_t r2t_stime, r2t_etime = 0;
LED_A_ON();
bool buttonPressed = false;
@@ -1626,7 +1626,7 @@ send:
*/
static int SendIClassAnswer(uint8_t *resp, int respLen, uint16_t delay) {
int i = 0;
- volatile uint8_t b = 0;
+ volatile uint8_t b;
FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_424K_8BIT);
@@ -1720,7 +1720,6 @@ static void TransmitIClassCommand(const uint8_t *cmd, int len, int *samples, int
//-----------------------------------------------------------------------------
void CodeIClassCommand(const uint8_t *cmd, int len) {
int i, j, k;
- uint8_t b;
ToSendReset();
@@ -1732,7 +1731,7 @@ void CodeIClassCommand(const uint8_t *cmd, int len) {
// Modulate the bytes
for (i = 0; i < len; i++) {
- b = cmd[i];
+ uint8_t b = cmd[i];
for (j = 0; j < 4; j++) {
for (k = 0; k < 4; k++) {
@@ -1875,14 +1874,13 @@ void setupIclassReader() {
}
bool sendCmdGetResponseWithRetries(uint8_t *command, size_t cmdsize, uint8_t *resp, uint8_t expected_size, uint8_t retries) {
- uint8_t got_n = 0;
while (retries-- > 0) {
ReaderTransmitIClass(command, cmdsize);
//iceman - if received size is bigger than expected, we smash the stack here
// since its called with fixed sized arrays
- got_n = ReaderReceiveIClass(resp);
+ uint8_t got_n = ReaderReceiveIClass(resp);
// 0xBB is the internal debug separator byte..
if (expected_size != got_n || (resp[0] == 0xBB || resp[7] == 0xBB || resp[2] == 0xBB)) {
@@ -1983,9 +1981,7 @@ void ReaderIClass(uint8_t arg0) {
//Read App Issuer Area block CRC(0x05) => 0xde 0x64
uint8_t readAA[] = { ICLASS_CMD_READ_OR_IDENTIFY, 0x05, 0xde, 0x64};
- int read_status = 0;
uint16_t tryCnt = 0;
- uint8_t result_status = 0;
bool abort_after_read = arg0 & FLAG_ICLASS_READER_ONLY_ONCE; // flag to read until one tag is found successfully
bool try_once = arg0 & FLAG_ICLASS_READER_ONE_TRY; // flag to not to loop continuously, looking for tag
@@ -2008,9 +2004,9 @@ void ReaderIClass(uint8_t arg0) {
}
tryCnt++;
- result_status = 0;
+ uint8_t result_status = 0;
- read_status = handshakeIclassTag_ext(card_data, use_credit_key);
+ int read_status = handshakeIclassTag_ext(card_data, use_credit_key);
if (read_status == 0) continue;
if (read_status == 1) result_status = FLAG_ICLASS_READER_CSN;
@@ -2107,7 +2103,7 @@ void ReaderIClass(uint8_t arg0) {
}
// turn off afterwards
-void ReaderIClass_Replay(uint8_t arg0, uint8_t *MAC) {
+void ReaderIClass_Replay(uint8_t arg0, uint8_t *mac) {
uint8_t cardsize = 0;
uint8_t mem = 0;
@@ -2134,7 +2130,7 @@ void ReaderIClass_Replay(uint8_t arg0, uint8_t *MAC) {
if (read_status < 2) continue;
//for now replay captured auth (as cc not updated)
- memcpy(check + 5, MAC, 4);
+ memcpy(check + 5, mac, 4);
if (!sendCmdGetResponseWithRetries(check, sizeof(check), resp, 4, 5)) {
DbpString("Error: Authentication Fail!");
@@ -2227,8 +2223,8 @@ void ReaderIClass_Replay(uint8_t arg0, uint8_t *MAC) {
// not used. ?!? ( CMD_ICLASS_READCHECK)
// turn off afterwards
-void iClass_ReadCheck(uint8_t blockNo, uint8_t keyType) {
- uint8_t readcheck[] = { keyType, blockNo };
+void iClass_ReadCheck(uint8_t blockno, uint8_t keytype) {
+ uint8_t readcheck[] = { keytype, blockno };
uint8_t resp[] = {0, 0, 0, 0, 0, 0, 0, 0};
size_t isOK = 0;
isOK = sendCmdGetResponseWithRetries(readcheck, sizeof(readcheck), resp, sizeof(resp), 6);
@@ -2348,9 +2344,9 @@ out:
// Tries to read block.
// retries 10times.
-bool iClass_ReadBlock(uint8_t blockNo, uint8_t *data, uint8_t len) {
+bool iClass_ReadBlock(uint8_t blockno, uint8_t *data, uint8_t len) {
uint8_t resp[10];
- uint8_t cmd[] = {ICLASS_CMD_READ_OR_IDENTIFY, blockNo, 0x00, 0x00};
+ uint8_t cmd[] = {ICLASS_CMD_READ_OR_IDENTIFY, blockno, 0x00, 0x00};
AddCrc(cmd + 1, 1);
// expect size 10, retry 5times
bool isOK = sendCmdGetResponseWithRetries(cmd, sizeof(cmd), resp, 10, 5);
@@ -2402,10 +2398,10 @@ void iClass_Dump(uint8_t blockno, uint8_t numblks) {
BigBuf_free();
}
-bool iClass_WriteBlock_ext(uint8_t blockNo, uint8_t *data) {
+bool iClass_WriteBlock_ext(uint8_t blockno, uint8_t *data) {
uint8_t resp[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
- uint8_t write[] = { ICLASS_CMD_UPDATE, blockNo, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
+ uint8_t write[] = { ICLASS_CMD_UPDATE, blockno, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
memcpy(write + 2, data, 12); // data + mac
AddCrc(write + 1, 13);
@@ -2416,7 +2412,7 @@ bool iClass_WriteBlock_ext(uint8_t blockNo, uint8_t *data) {
if (memcmp(write + 2, resp, 8)) {
//if not programming key areas (note key blocks don't get programmed with actual key data it is xor data)
- if (blockNo != 3 && blockNo != 4) {
+ if (blockno != 3 && blockno != 4) {
isOK = sendCmdGetResponseWithRetries(write, sizeof(write), resp, sizeof(resp), 5);
}
}
@@ -2425,8 +2421,8 @@ bool iClass_WriteBlock_ext(uint8_t blockNo, uint8_t *data) {
}
// turn off afterwards
-void iClass_WriteBlock(uint8_t blockNo, uint8_t *data) {
- bool isOK = iClass_WriteBlock_ext(blockNo, data);
+void iClass_WriteBlock(uint8_t blockno, uint8_t *data) {
+ bool isOK = iClass_WriteBlock_ext(blockno, data);
cmd_send(CMD_ACK, isOK, 0, 0, 0, 0);
switch_off();
}
diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c
index bca6b4c1f..6db229d0d 100644
--- a/armsrc/iso14443a.c
+++ b/armsrc/iso14443a.c
@@ -16,9 +16,6 @@ static uint32_t iso14a_timeout;
uint8_t colpos = 0;
int rsamples = 0;
-//int ReqCount;
-//char CollisionIndicators[10*8];
-
uint8_t trigger = 0;
// the block number for the ISO14443-4 PCB
static uint8_t iso14_pcb_blocknum = 0;
@@ -53,17 +50,6 @@ static uint8_t *free_buffer_pointer;
// 1 tick to assign mod_sig_coil
#define DELAY_ARM2AIR_AS_READER (4*16 + 8*16 + 8 + 8 + 1)
-// When the PM acts as tag and is receiving it takes
-// 2 ticks delay in the RF part (for the first falling edge),
-// 3 ticks for the A/D conversion,
-// 8 ticks on average until the start of the SSC transfer,
-// 8 ticks until the SSC samples the first data
-// 7*16 ticks to complete the transfer from FPGA to ARM
-// 8 ticks until the next ssp_clk rising edge
-// 4*16 ticks until we measure the time
-// - 8*16 ticks because we measure the time of the previous transfer
-#define DELAY_AIR2ARM_AS_TAG (2 + 3 + 8 + 8 + 7*16 + 8 + 4*16 - 8*16)
-
// The FPGA will report its internal sending delay in
uint16_t FpgaSendQueueDelay;
// the 5 first bits are the number of bits buffered in mod_sig_buf
@@ -135,12 +121,12 @@ uint32_t iso14a_get_timeout(void) {
//-----------------------------------------------------------------------------
// Generate the parity value for a byte sequence
//-----------------------------------------------------------------------------
-void GetParity(const uint8_t *pbtCmd, uint16_t iLen, uint8_t *par) {
+void GetParity(const uint8_t *pbtCmd, uint16_t len, uint8_t *par) {
uint16_t paritybit_cnt = 0;
uint16_t paritybyte_cnt = 0;
uint8_t parityBits = 0;
- for (uint16_t i = 0; i < iLen; i++) {
+ for (uint16_t i = 0; i < len; i++) {
// Generate the parity bits
parityBits |= ((oddparity8(pbtCmd[i])) << (7 - paritybit_cnt));
if (paritybit_cnt == 7) {
@@ -207,9 +193,9 @@ void UartReset(void) {
Uart.syncBit = 9999;
}
-void UartInit(uint8_t *data, uint8_t *parity) {
+void UartInit(uint8_t *data, uint8_t *par) {
Uart.output = data;
- Uart.parity = parity;
+ Uart.parity = par;
UartReset();
}
@@ -380,9 +366,9 @@ void DemodReset(void) {
Demod.samples = 0;
}
-void DemodInit(uint8_t *data, uint8_t *parity) {
+void DemodInit(uint8_t *data, uint8_t *par) {
Demod.output = data;
- Demod.parity = parity;
+ Demod.parity = par;
DemodReset();
}
@@ -514,8 +500,7 @@ void RAMFUNC SniffIso14443a(uint8_t param) {
uint8_t *data = dmaBuf;
uint8_t previous_data = 0;
- int maxDataLen = 0;
- int dataLen = 0;
+ int maxDataLen = 0, dataLen;
bool TagIsActive = false;
bool ReaderIsActive = false;
@@ -650,7 +635,7 @@ void RAMFUNC SniffIso14443a(uint8_t param) {
//-----------------------------------------------------------------------------
// Prepare tag messages
//-----------------------------------------------------------------------------
-static void CodeIso14443aAsTagPar(const uint8_t *cmd, uint16_t len, uint8_t *parity, bool collision) {
+static void CodeIso14443aAsTagPar(const uint8_t *cmd, uint16_t len, uint8_t *par, bool collision) {
//uint8_t localCol = 0;
ToSendReset();
@@ -693,7 +678,7 @@ static void CodeIso14443aAsTagPar(const uint8_t *cmd, uint16_t len, uint8_t *par
LastProxToAirDuration = 8 * ToSendMax;
} else {
// Get the parity bit
- if (parity[i >> 3] & (0x80 >> (i & 0x0007))) {
+ if (par[i >> 3] & (0x80 >> (i & 0x0007))) {
ToSend[++ToSendMax] = SEC_D;
LastProxToAirDuration = 8 * ToSendMax - 4;
} else {
@@ -755,12 +740,40 @@ static void Code4bitAnswerAsTag(uint8_t cmd) {
ToSendMax++;
}
+static uint8_t *LastReaderTraceTime = NULL;
+
+void EmLogTraceReader(void) {
+ // remember last reader trace start to fix timing info later
+ LastReaderTraceTime = BigBuf_get_addr() + BigBuf_get_traceLen();
+ LogTrace(Uart.output, Uart.len, Uart.startTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true);
+}
+
+static void FixLastReaderTraceTime(uint32_t tag_StartTime) {
+ uint32_t reader_EndTime = Uart.endTime * 16 - DELAY_AIR2ARM_AS_TAG;
+ uint32_t reader_StartTime = Uart.startTime * 16 - DELAY_AIR2ARM_AS_TAG;
+ uint16_t reader_modlen = reader_EndTime - reader_StartTime;
+ uint16_t approx_fdt = tag_StartTime - reader_EndTime;
+ uint16_t exact_fdt = (approx_fdt - 20 + 32) / 64 * 64 + 20;
+ reader_StartTime = tag_StartTime - exact_fdt - reader_modlen;
+ LastReaderTraceTime[0] = (reader_StartTime >> 0) & 0xff;
+ LastReaderTraceTime[1] = (reader_StartTime >> 8) & 0xff;
+ LastReaderTraceTime[2] = (reader_StartTime >> 16) & 0xff;
+ LastReaderTraceTime[3] = (reader_StartTime >> 24) & 0xff;
+}
+
+static void EmLogTraceTag(uint8_t *tag_data, uint16_t tag_len, uint8_t *tag_Parity, uint32_t ProxToAirDuration) {
+ uint32_t tag_StartTime = LastTimeProxToAirStart * 16 + DELAY_ARM2AIR_AS_TAG;
+ uint32_t tag_EndTime = (LastTimeProxToAirStart + ProxToAirDuration) * 16 + DELAY_ARM2AIR_AS_TAG;
+ LogTrace(tag_data, tag_len, tag_StartTime, tag_EndTime, tag_Parity, false);
+ FixLastReaderTraceTime(tag_StartTime);
+}
+
//-----------------------------------------------------------------------------
// Wait for commands from reader
// stop when button is pressed
// or return TRUE when command is captured
//-----------------------------------------------------------------------------
-int GetIso14443aCommandFromReader(uint8_t *received, uint8_t *parity, int *len) {
+static int GetIso14443aCommandFromReader(uint8_t *received, uint8_t *par, int *len) {
// Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
// only, since we are receiving, not transmitting).
// Signal field is off with the appropriate LED
@@ -768,7 +781,7 @@ int GetIso14443aCommandFromReader(uint8_t *received, uint8_t *parity, int *len)
FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_LISTEN);
// Now run a `software UART` on the stream of incoming samples.
- UartInit(received, parity);
+ UartInit(received, par);
// clear RXRDY:
uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
@@ -780,6 +793,7 @@ int GetIso14443aCommandFromReader(uint8_t *received, uint8_t *parity, int *len)
b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
if (MillerDecoding(b, 0)) {
*len = Uart.len;
+ EmLogTraceReader();
return true;
}
}
@@ -787,7 +801,7 @@ int GetIso14443aCommandFromReader(uint8_t *received, uint8_t *parity, int *len)
return false;
}
-bool prepare_tag_modulation(tag_response_info_t *response_info, size_t max_buffer_size) {
+static bool prepare_tag_modulation(tag_response_info_t *response_info, size_t max_buffer_size) {
// Example response, answer to MIFARE Classic read block will be 16 bytes + 2 CRC = 18 bytes
// This will need the following byte array for a modulation sequence
// 144 data bits (18 * 8)
@@ -825,23 +839,21 @@ bool prepare_tag_modulation(tag_response_info_t *response_info, size_t max_buffe
// 47 * 8 data bits, 47 * 1 parity bits, 10 start bits, 10 stop bits, 10 correction bits
#define ALLOCATED_TAG_MODULATION_BUFFER_SIZE 453
-bool prepare_allocated_tag_modulation(tag_response_info_t *response_info) {
- // Retrieve and store the current buffer index
- response_info->modulation = free_buffer_pointer;
+bool prepare_allocated_tag_modulation(tag_response_info_t *response_info, uint8_t **buffer, size_t *max_buffer_size) {
- // Determine the maximum size we can use from our buffer
- size_t max_buffer_size = ALLOCATED_TAG_MODULATION_BUFFER_SIZE;
+ // Retrieve and store the current buffer index
+ response_info->modulation = *buffer;
// Forward the prepare tag modulation function to the inner function
- if (prepare_tag_modulation(response_info, max_buffer_size)) {
- // Update the free buffer offset
- free_buffer_pointer += ToSendMax;
+ if (prepare_tag_modulation(response_info, *max_buffer_size)) {
+ // Update the free buffer offset and the remaining buffer size
+ *buffer += ToSendMax;
+ *max_buffer_size -= ToSendMax;
return true;
} else {
return false;
}
}
-
//-----------------------------------------------------------------------------
// Main loop of simulated tag: receive commands from reader, decide what
// response to send, and send it.
@@ -1040,12 +1052,13 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t *data) {
// allocate buffers:
uint8_t *receivedCmd = BigBuf_malloc(MAX_FRAME_SIZE);
uint8_t *receivedCmdPar = BigBuf_malloc(MAX_PARITY_SIZE);
- free_buffer_pointer = BigBuf_malloc(ALLOCATED_TAG_MODULATION_BUFFER_SIZE);
+ //free_buffer_pointer = BigBuf_malloc(ALLOCATED_TAG_MODULATION_BUFFER_SIZE);
+ size_t free_buffer_size = ALLOCATED_TAG_MODULATION_BUFFER_SIZE;
// Prepare the responses of the anticollision phase
// there will be not enough time to do this at the moment the reader sends it REQA
for (size_t i = 0; i < TAG_RESPONSE_COUNT; i++)
- prepare_allocated_tag_modulation(&responses[i]);
+ prepare_allocated_tag_modulation(&responses[i], &free_buffer_pointer, &free_buffer_size);
int len = 0;
@@ -1121,29 +1134,29 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t *data) {
uint8_t emdata[MAX_FRAME_SIZE];
// first 12 blocks of emu are [getversion answer - check tearing - pack - 0x00 - signature]
int start = (receivedCmd[1] + 12) * 4;
- int len = (receivedCmd[2] - receivedCmd[1] + 1) * 4;
+ len = (receivedCmd[2] - receivedCmd[1] + 1) * 4;
emlGetMemBt(emdata, start, len);
AddCrc14A(emdata, len);
EmSendCmd(emdata, len + 2);
p_response = NULL;
- } else if ((receivedCmd[0] == MIFARE_ULC_WRITE || receivedCmd[0] == MIFARE_ULC_COMP_WRITE) && (tagType == 2 || tagType == 7)) { // Received a WRITE
- // cmd + block + 4/16 bytes data + 2 bytes crc
- if (len == 8 || len == 20) {
- bool isCrcCorrect = CheckCrc14A(receivedCmd, len);
- if (isCrcCorrect) {
- int block = receivedCmd[1] + 12; // first 12 blocks of emu are [getversion answer - check tearing - pack - 0x00 - signature]
- emlSetMem_xt(&receivedCmd[2], block, 1, 4);
- // send ACK
- EmSend4bit(CARD_ACK);
- } else {
- // send NACK 0x1 == crc/parity error
- EmSend4bit(CARD_NACK_PA);
- }
- } else {
- // send NACK 0x0 == invalid argument
- EmSend4bit(CARD_NACK_IV);
- }
- p_response = NULL;
+ } else if ((receivedCmd[0] == MIFARE_ULC_WRITE || receivedCmd[0] == MIFARE_ULC_COMP_WRITE) && (tagType == 2 || tagType == 7)) { // Received a WRITE
+ // cmd + block + 4/16 bytes data + 2 bytes crc
+ if (len == 8 || len == 20) {
+ bool isCrcCorrect = CheckCrc14A(receivedCmd, len);
+ if (isCrcCorrect) {
+ int block = receivedCmd[1] + 12; // first 12 blocks of emu are [getversion answer - check tearing - pack - 0x00 - signature]
+ emlSetMem_xt(&receivedCmd[2], block, 1, 4);
+ // send ACK
+ EmSend4bit(CARD_ACK);
+ } else {
+ // send NACK 0x1 == crc/parity error
+ EmSend4bit(CARD_NACK_PA);
+ }
+ } else {
+ // send NACK 0x0 == invalid argument
+ EmSend4bit(CARD_NACK_IV);
+ }
+ p_response = NULL;
} else if (receivedCmd[0] == MIFARE_ULEV1_READSIG && tagType == 7) { // Received a READ SIGNATURE --
// first 12 blocks of emu are [getversion answer - check tearing - pack - 0x00 - signature]
uint16_t start = 4 * 4;
@@ -1506,7 +1519,7 @@ static void TransmitFor14443a(const uint8_t *cmd, uint16_t len, uint32_t *timing
//-----------------------------------------------------------------------------
// Prepare reader command (in bits, support short frames) to send to FPGA
//-----------------------------------------------------------------------------
-void CodeIso14443aBitsAsReaderPar(const uint8_t *cmd, uint16_t bits, const uint8_t *parity) {
+void CodeIso14443aBitsAsReaderPar(const uint8_t *cmd, uint16_t bits, const uint8_t *par) {
int i, j;
int last = 0;
uint8_t b;
@@ -1545,9 +1558,9 @@ void CodeIso14443aBitsAsReaderPar(const uint8_t *cmd, uint16_t bits, const uint8
}
// Only transmit parity bit if we transmitted a complete byte
- if (j == 8 && parity != NULL) {
+ if (j == 8 && par != NULL) {
// Get the parity bit
- if (parity[i >> 3] & (0x80 >> (i & 0x0007))) {
+ if (par[i >> 3] & (0x80 >> (i & 0x0007))) {
// Sequence X
ToSend[++ToSendMax] = SEC_X;
LastProxToAirDuration = 8 * (ToSendMax + 1) - 2;
@@ -1585,8 +1598,8 @@ void CodeIso14443aBitsAsReaderPar(const uint8_t *cmd, uint16_t bits, const uint8
//-----------------------------------------------------------------------------
// Prepare reader command to send to FPGA
//-----------------------------------------------------------------------------
-void CodeIso14443aAsReaderPar(const uint8_t *cmd, uint16_t len, const uint8_t *parity) {
- CodeIso14443aBitsAsReaderPar(cmd, len * 8, parity);
+void CodeIso14443aAsReaderPar(const uint8_t *cmd, uint16_t len, const uint8_t *par) {
+ CodeIso14443aBitsAsReaderPar(cmd, len * 8, par);
}
//-----------------------------------------------------------------------------
@@ -1594,7 +1607,7 @@ void CodeIso14443aAsReaderPar(const uint8_t *cmd, uint16_t len, const uint8_t *p
// Stop when button is pressed (return 1) or field was gone (return 2)
// Or return 0 when command is captured
//-----------------------------------------------------------------------------
-int EmGetCmd(uint8_t *received, uint16_t *len, uint8_t *parity) {
+int EmGetCmd(uint8_t *received, uint16_t *len, uint8_t *par) {
*len = 0;
uint32_t timer = 0, vtime = 0;
@@ -1618,7 +1631,7 @@ int EmGetCmd(uint8_t *received, uint16_t *len, uint8_t *parity) {
AT91C_BASE_ADC->ADC_CR = AT91C_ADC_START;
// Now run a 'software UART' on the stream of incoming samples.
- UartInit(received, parity);
+ UartInit(received, par);
// Clear RXRDY:
uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
@@ -1634,7 +1647,7 @@ int EmGetCmd(uint8_t *received, uint16_t *len, uint8_t *parity) {
analogAVG += AT91C_BASE_ADC->ADC_CDR[ADC_CHAN_HF];
AT91C_BASE_ADC->ADC_CR = AT91C_ADC_START;
if (analogCnt >= 32) {
- if ((MAX_ADC_HF_VOLTAGE * (analogAVG / analogCnt) >> 10) < MF_MINFIELDV) {
+ if ((MAX_ADC_HF_VOLTAGE_RDV40 * (analogAVG / analogCnt) >> 10) < MF_MINFIELDV) {
vtime = GetTickCount();
if (!timer) timer = vtime;
// 50ms no field --> card to idle state
@@ -1650,6 +1663,7 @@ int EmGetCmd(uint8_t *received, uint16_t *len, uint8_t *parity) {
b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
if (MillerDecoding(b, 0)) {
*len = Uart.len;
+ EmLogTraceReader();
return 0;
}
}
@@ -1768,11 +1782,30 @@ int EmSendCmdEx(uint8_t *resp, uint16_t respLen, bool collision) {
return EmSendCmdParEx(resp, respLen, par, collision);
}
-bool EmLogTrace(uint8_t *reader_data, uint16_t reader_len, uint32_t reader_StartTime, uint32_t reader_EndTime, uint8_t *reader_Parity,
- uint8_t *tag_data, uint16_t tag_len, uint32_t tag_StartTime, uint32_t tag_EndTime, uint8_t *tag_Parity) {
+int EmSendPrecompiledCmd(tag_response_info_t *response_info) {
+ int ret = EmSendCmd14443aRaw(response_info->modulation, response_info->modulation_n);
+
+ // do the tracing for the previous reader request and this tag answer:
+ EmLogTraceTag(response_info->response, response_info->response_n,
+ &(response_info->par), response_info->ProxToAirDuration);
+
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) {
+ Dbprintf("response_info->response %02X", response_info->response);
+ Dbprintf("response_info->response_n %02X", response_info->response_n);
+ Dbprintf("response_info->par %02X", &(response_info->par));
+ }
+
+ return ret;
+}
+
+bool EmLogTrace(uint8_t *reader_data, uint16_t reader_len, uint32_t reader_StartTime,
+ uint32_t reader_EndTime, uint8_t *reader_Parity, uint8_t *tag_data,
+ uint16_t tag_len, uint32_t tag_StartTime, uint32_t tag_EndTime, uint8_t *tag_Parity) {
+
// we cannot exactly measure the end and start of a received command from reader. However we know that the delay from
// end of the received command to start of the tag's (simulated by us) answer is n*128+20 or n*128+84 resp.
// with n >= 9. The start of the tags answer can be measured and therefore the end of the received command be calculated:
+
uint16_t reader_modlen = reader_EndTime - reader_StartTime;
uint16_t approx_fdt = tag_StartTime - reader_EndTime;
uint16_t exact_fdt = (approx_fdt - 20 + 32) / 64 * 64 + 20;
@@ -1850,17 +1883,17 @@ void ReaderTransmit(uint8_t *frame, uint16_t len, uint32_t *timing) {
ReaderTransmitBitsPar(frame, len * 8, par, timing);
}
-int ReaderReceiveOffset(uint8_t *receivedAnswer, uint16_t offset, uint8_t *parity) {
- if (!GetIso14443aAnswerFromTag(receivedAnswer, parity, offset))
+int ReaderReceiveOffset(uint8_t *receivedAnswer, uint16_t offset, uint8_t *par) {
+ if (!GetIso14443aAnswerFromTag(receivedAnswer, par, offset))
return false;
- LogTrace(receivedAnswer, Demod.len, Demod.startTime * 16 - DELAY_AIR2ARM_AS_READER, Demod.endTime * 16 - DELAY_AIR2ARM_AS_READER, parity, false);
+ LogTrace(receivedAnswer, Demod.len, Demod.startTime * 16 - DELAY_AIR2ARM_AS_READER, Demod.endTime * 16 - DELAY_AIR2ARM_AS_READER, par, false);
return Demod.len;
}
-int ReaderReceive(uint8_t *receivedAnswer, uint8_t *parity) {
- if (!GetIso14443aAnswerFromTag(receivedAnswer, parity, 0))
+int ReaderReceive(uint8_t *receivedAnswer, uint8_t *par) {
+ if (!GetIso14443aAnswerFromTag(receivedAnswer, par, 0))
return false;
- LogTrace(receivedAnswer, Demod.len, Demod.startTime * 16 - DELAY_AIR2ARM_AS_READER, Demod.endTime * 16 - DELAY_AIR2ARM_AS_READER, parity, false);
+ LogTrace(receivedAnswer, Demod.len, Demod.startTime * 16 - DELAY_AIR2ARM_AS_READER, Demod.endTime * 16 - DELAY_AIR2ARM_AS_READER, par, false);
return Demod.len;
}
@@ -2962,653 +2995,6 @@ void DetectNACKbug() {
set_tracing(false);
}
-/**
- *MIFARE 1K simulate.
- *
- *@param flags :
- * FLAG_INTERACTIVE - In interactive mode, we are expected to finish the operation with an ACK
- * FLAG_4B_UID_IN_DATA - use 4-byte UID in the data-section
- * FLAG_7B_UID_IN_DATA - use 7-byte UID in the data-section
- * FLAG_10B_UID_IN_DATA - use 10-byte UID in the data-section
- * FLAG_UID_IN_EMUL - use 4-byte UID from emulator memory
- * FLAG_NR_AR_ATTACK - collect NR_AR responses for bruteforcing later
- *@param exitAfterNReads, exit simulation after n blocks have been read, 0 is inifite
-* (unless reader attack mode enabled then it runs util it gets enough nonces to recover all keys attmpted)
- */
-void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t *datain) {
-
- int cardSTATE = MFEMUL_NOFIELD;
- int _UID_LEN = 0; // 4, 7, 10
- int _SECTORS = 16; // 16, 32, 40
- int vHf = 0; // in mV
- int res = 0;
- uint32_t selTimer = 0;
- uint32_t authTimer = 0;
- uint16_t len = 0;
- uint8_t cardWRBL = 0;
- uint8_t cardAUTHSC = 0;
- uint8_t cardAUTHKEY = 0xff; // no authentication
- uint32_t cuid = 0;
- uint32_t ans = 0;
- uint32_t cardINTREG = 0;
- uint8_t cardINTBLOCK = 0;
- struct Crypto1State mpcs = {0, 0};
- struct Crypto1State *pcs;
- pcs = &mpcs;
- uint32_t numReads = 0; // Counts numer of times reader read a block
- uint8_t receivedCmd[MAX_MIFARE_FRAME_SIZE] = {0x00};
- uint8_t decryptedCmd[MAX_MIFARE_FRAME_SIZE] = {0x00};
- uint8_t receivedCmd_par[MAX_MIFARE_PARITY_SIZE] = {0x00};
- uint8_t response[MAX_MIFARE_FRAME_SIZE] = {0x00};
- uint8_t response_par[MAX_MIFARE_PARITY_SIZE] = {0x00};
-
- uint8_t atqa[] = {0x04, 0x00}; // Mifare classic 1k
- uint8_t sak_4[] = {0x0C, 0x00, 0x00}; // CL1 - 4b uid
- uint8_t sak_7[] = {0x0C, 0x00, 0x00}; // CL2 - 7b uid
- uint8_t sak_10[] = {0x0C, 0x00, 0x00}; // CL3 - 10b uid
- // uint8_t sak[] = {0x09, 0x3f, 0xcc }; // Mifare Mini
-
- uint8_t rUIDBCC1[] = {0xde, 0xad, 0xbe, 0xaf, 0x62};
- uint8_t rUIDBCC2[] = {0xde, 0xad, 0xbe, 0xaf, 0x62};
- uint8_t rUIDBCC3[] = {0xde, 0xad, 0xbe, 0xaf, 0x62};
-
- // TAG Nonce - Authenticate response
- uint8_t rAUTH_NT[4];
- uint8_t rAUTH_NT_keystream[4];
- uint32_t nonce = 0;
-
- // uint8_t rAUTH_NT[] = {0x55, 0x41, 0x49, 0x92};// nonce from nested? why this?
- // uint8_t rAUTH_AT[] = {0x00, 0x00, 0x00, 0x00};
-
- // Here, we collect CUID, NT, NR, AR, CUID2, NT2, NR2, AR2
- // This can be used in a reader-only attack.
- nonces_t ar_nr_nonces[ATTACK_KEY_COUNT];
- memset(ar_nr_nonces, 0x00, sizeof(ar_nr_nonces));
-
- // -- Determine the UID
- // Can be set from emulator memory or incoming data
- // Length: 4,7,or 10 bytes
- if ((flags & FLAG_UID_IN_EMUL) == FLAG_UID_IN_EMUL)
- emlGetMemBt(datain, 0, 10); // load 10bytes from EMUL to the datain pointer. to be used below.
-
- if ((flags & FLAG_4B_UID_IN_DATA) == FLAG_4B_UID_IN_DATA) {
- memcpy(rUIDBCC1, datain, 4);
- _UID_LEN = 4;
- } else if ((flags & FLAG_7B_UID_IN_DATA) == FLAG_7B_UID_IN_DATA) {
- memcpy(&rUIDBCC1[1], datain, 3);
- memcpy(rUIDBCC2, datain + 3, 4);
- _UID_LEN = 7;
- } else if ((flags & FLAG_10B_UID_IN_DATA) == FLAG_10B_UID_IN_DATA) {
- memcpy(&rUIDBCC1[1], datain, 3);
- memcpy(&rUIDBCC2[1], datain + 3, 3);
- memcpy(rUIDBCC3, datain + 6, 4);
- _UID_LEN = 10;
- }
-
- switch (_UID_LEN) {
- case 4:
- sak_4[0] &= 0xFB;
- // save CUID
- cuid = bytes_to_num(rUIDBCC1, 4);
- // BCC
- rUIDBCC1[4] = rUIDBCC1[0] ^ rUIDBCC1[1] ^ rUIDBCC1[2] ^ rUIDBCC1[3];
- if (MF_DBGLEVEL >= 2) {
- Dbprintf("4B UID: %02x%02x%02x%02x",
- rUIDBCC1[0],
- rUIDBCC1[1],
- rUIDBCC1[2],
- rUIDBCC1[3]
- );
- }
- break;
- case 7:
- atqa[0] |= 0x40;
- sak_7[0] &= 0xFB;
- // save CUID
- cuid = bytes_to_num(rUIDBCC2, 4);
- // CascadeTag, CT
- rUIDBCC1[0] = 0x88;
- // BCC
- rUIDBCC1[4] = rUIDBCC1[0] ^ rUIDBCC1[1] ^ rUIDBCC1[2] ^ rUIDBCC1[3];
- rUIDBCC2[4] = rUIDBCC2[0] ^ rUIDBCC2[1] ^ rUIDBCC2[2] ^ rUIDBCC2[3];
- if (MF_DBGLEVEL >= 2) {
- Dbprintf("7B UID: %02x %02x %02x %02x %02x %02x %02x",
- rUIDBCC1[1],
- rUIDBCC1[2],
- rUIDBCC1[3],
- rUIDBCC2[0],
- rUIDBCC2[1],
- rUIDBCC2[2],
- rUIDBCC2[3]
- );
- }
- break;
- case 10:
- atqa[0] |= 0x80;
- sak_10[0] &= 0xFB;
- // save CUID
- cuid = bytes_to_num(rUIDBCC3, 4);
- // CascadeTag, CT
- rUIDBCC1[0] = 0x88;
- rUIDBCC2[0] = 0x88;
- // BCC
- rUIDBCC1[4] = rUIDBCC1[0] ^ rUIDBCC1[1] ^ rUIDBCC1[2] ^ rUIDBCC1[3];
- rUIDBCC2[4] = rUIDBCC2[0] ^ rUIDBCC2[1] ^ rUIDBCC2[2] ^ rUIDBCC2[3];
- rUIDBCC3[4] = rUIDBCC3[0] ^ rUIDBCC3[1] ^ rUIDBCC3[2] ^ rUIDBCC3[3];
-
- if (MF_DBGLEVEL >= 2) {
- Dbprintf("10B UID: %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
- rUIDBCC1[1],
- rUIDBCC1[2],
- rUIDBCC1[3],
- rUIDBCC2[1],
- rUIDBCC2[2],
- rUIDBCC2[3],
- rUIDBCC3[0],
- rUIDBCC3[1],
- rUIDBCC3[2],
- rUIDBCC3[3]
- );
- }
- break;
- default:
- break;
- }
- // calc some crcs
- AddCrc14A(sak_4, sizeof(sak_4) - 2);
- AddCrc14A(sak_7, sizeof(sak_7) - 2);
- AddCrc14A(sak_10, sizeof(sak_10) - 2);
-
- // We need to listen to the high-frequency, peak-detected path.
- iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN);
-
- // free eventually allocated BigBuf memory but keep Emulator Memory
- BigBuf_free_keep_EM();
- clear_trace();
- set_tracing(true);
- LED_D_ON();
-
- bool finished = false;
- while (!BUTTON_PRESS() && !finished && !usb_poll_validate_length()) {
- WDT_HIT();
-
- // find reader field
- if (cardSTATE == MFEMUL_NOFIELD) {
-
- vHf = (MAX_ADC_HF_VOLTAGE * AvgAdc(ADC_CHAN_HF)) >> 10;
- if (vHf > MF_MINFIELDV) {
- cardSTATE_TO_IDLE();
- LED_A_ON();
- }
- }
- if (cardSTATE == MFEMUL_NOFIELD) continue;
-
- // Now, get data
- res = EmGetCmd(receivedCmd, &len, receivedCmd_par);
- if (res == 2) { //Field is off!
- cardSTATE = MFEMUL_NOFIELD;
- LEDsoff();
- continue;
- } else if (res == 1) {
- break; // return value 1 means button press
- }
-
- // REQ or WUP request in ANY state and WUP in HALTED state
- // this if-statement doesn't match the specification above. (iceman)
- if (len == 1 && ((receivedCmd[0] == ISO14443A_CMD_REQA && cardSTATE != MFEMUL_HALTED) || receivedCmd[0] == ISO14443A_CMD_WUPA)) {
- selTimer = GetTickCount();
- EmSendCmd(atqa, sizeof(atqa));
- cardSTATE = MFEMUL_SELECT1;
- crypto1_destroy(pcs);
- cardAUTHKEY = 0xff;
- nonce = prng_successor(selTimer, 32);
- num_to_bytes(nonce, 4, rAUTH_NT);
- num_to_bytes(cuid ^ nonce, 4, rAUTH_NT_keystream);
- continue;
- }
-
- switch (cardSTATE) {
- case MFEMUL_NOFIELD:
- case MFEMUL_HALTED:
- case MFEMUL_IDLE: {
- LogTrace(Uart.output, Uart.len, Uart.startTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true);
- break;
- }
- case MFEMUL_SELECT1: {
- if (len == 2 && (receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT && receivedCmd[1] == 0x20)) {
- if (MF_DBGLEVEL >= 4) Dbprintf("SELECT ALL received");
- EmSendCmd(rUIDBCC1, sizeof(rUIDBCC1));
- break;
- }
- // select card
- if (len == 9 &&
- (receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT &&
- receivedCmd[1] == 0x70 &&
- memcmp(&receivedCmd[2], rUIDBCC1, 4) == 0)) {
-
- // SAK 4b
- EmSendCmd(sak_4, sizeof(sak_4));
- switch (_UID_LEN) {
- case 4:
- cardSTATE = MFEMUL_WORK;
- LED_B_ON();
- if (MF_DBGLEVEL >= 4) Dbprintf("--> WORK. anticol1 time: %d", GetTickCount() - selTimer);
- continue;
- case 7:
- case 10:
- cardSTATE = MFEMUL_SELECT2;
- continue;
- default:
- break;
- }
- } else {
- cardSTATE_TO_IDLE();
- }
- break;
- }
- case MFEMUL_SELECT2: {
- if (!len) {
- LogTrace(Uart.output, Uart.len, Uart.startTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true);
- break;
- }
- if (len == 2 && (receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2 && receivedCmd[1] == 0x20)) {
- EmSendCmd(rUIDBCC2, sizeof(rUIDBCC2));
- break;
- }
- if (len == 9 &&
- (receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2 &&
- receivedCmd[1] == 0x70 &&
- memcmp(&receivedCmd[2], rUIDBCC2, 4) == 0)) {
-
- EmSendCmd(sak_7, sizeof(sak_7));
- switch (_UID_LEN) {
- case 7:
- cardSTATE = MFEMUL_WORK;
- LED_B_ON();
- if (MF_DBGLEVEL >= 4) Dbprintf("--> WORK. anticol2 time: %d", GetTickCount() - selTimer);
- continue;
- case 10:
- cardSTATE = MFEMUL_SELECT3;
- continue;
- default:
- break;
- }
- }
- cardSTATE_TO_IDLE();
- break;
- }
- case MFEMUL_SELECT3: {
- if (!len) {
- LogTrace(Uart.output, Uart.len, Uart.startTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true);
- break;
- }
- if (len == 2 && (receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_3 && receivedCmd[1] == 0x20)) {
- EmSendCmd(rUIDBCC3, sizeof(rUIDBCC3));
- break;
- }
- if (len == 9 &&
- (receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_3 &&
- receivedCmd[1] == 0x70 &&
- memcmp(&receivedCmd[2], rUIDBCC3, 4) == 0)) {
-
- EmSendCmd(sak_10, sizeof(sak_10));
- cardSTATE = MFEMUL_WORK;
- LED_B_ON();
- if (MF_DBGLEVEL >= 4) Dbprintf("--> WORK. anticol3 time: %d", GetTickCount() - selTimer);
- break;
- }
- cardSTATE_TO_IDLE();
- break;
- }
- case MFEMUL_AUTH1: {
- if (len != 8) {
- cardSTATE_TO_IDLE();
- LogTrace(Uart.output, Uart.len, Uart.startTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true);
- break;
- }
-
- uint32_t nr = bytes_to_num(receivedCmd, 4);
- uint32_t ar = bytes_to_num(&receivedCmd[4], 4);
-
- // Collect AR/NR per keytype & sector
- if ((flags & FLAG_NR_AR_ATTACK) == FLAG_NR_AR_ATTACK) {
-
- int8_t index = -1;
- int8_t empty = -1;
- for (uint8_t i = 0; i < ATTACK_KEY_COUNT; i++) {
- // find which index to use
- if ((cardAUTHSC == ar_nr_nonces[i].sector) && (cardAUTHKEY == ar_nr_nonces[i].keytype))
- index = i;
-
- // keep track of empty slots.
- if (ar_nr_nonces[i].state == EMPTY)
- empty = i;
- }
- // if no empty slots. Choose first and overwrite.
- if (index == -1) {
- if (empty == -1) {
- index = 0;
- ar_nr_nonces[index].state = EMPTY;
- } else {
- index = empty;
- }
- }
-
- switch (ar_nr_nonces[index].state) {
- case EMPTY: {
- // first nonce collect
- ar_nr_nonces[index].cuid = cuid;
- ar_nr_nonces[index].sector = cardAUTHSC;
- ar_nr_nonces[index].keytype = cardAUTHKEY;
- ar_nr_nonces[index].nonce = nonce;
- ar_nr_nonces[index].nr = nr;
- ar_nr_nonces[index].ar = ar;
- ar_nr_nonces[index].state = FIRST;
- break;
- }
- case FIRST : {
- // second nonce collect
- ar_nr_nonces[index].nonce2 = nonce;
- ar_nr_nonces[index].nr2 = nr;
- ar_nr_nonces[index].ar2 = ar;
- ar_nr_nonces[index].state = SECOND;
-
- // send to client
- cmd_send(CMD_ACK, CMD_SIMULATE_MIFARE_CARD, 0, 0, &ar_nr_nonces[index], sizeof(nonces_t));
-
- ar_nr_nonces[index].state = EMPTY;
- ar_nr_nonces[index].sector = 0;
- ar_nr_nonces[index].keytype = 0;
- break;
- }
- default:
- break;
- }
- }
-
- crypto1_word(pcs, nr, 1);
- uint32_t cardRr = ar ^ crypto1_word(pcs, 0, 0);
-
- //test if auth OK
- if (cardRr != prng_successor(nonce, 64)) {
-
- if (MF_DBGLEVEL >= 3) {
- Dbprintf("AUTH FAILED for sector %d with key %c. [nr=%08x cardRr=%08x] [nt=%08x succ=%08x]"
- , cardAUTHSC
- , (cardAUTHKEY == 0) ? 'A' : 'B'
- , nr
- , cardRr
- , nonce // nt
- , prng_successor(nonce, 64)
- );
- }
- // sends encrypted NACK response to do no wait timeout
- cardSTATE_TO_IDLE();
- EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
- break;
- }
-
-
- /*
- ans = prng_successor(nonce, 96) ^ crypto1_word(pcs, 0, 0);
- num_to_bytes(ans, 4, rAUTH_AT);
- EmSendCmd(rAUTH_AT, sizeof(rAUTH_AT));
- */
-
- ans = prng_successor(nonce, 96);
- num_to_bytes(ans, 4, response);
- mf_crypto1_encrypt(pcs, response, 4, response_par);
- EmSendCmdPar(response, 4, response_par);
-
- LED_C_ON();
-
- if (MF_DBGLEVEL >= 3) {
- Dbprintf("AUTH COMPLETED for sector %d with key %c. time=%d",
- cardAUTHSC,
- cardAUTHKEY == 0 ? 'A' : 'B',
- GetTickCount() - authTimer
- );
- }
- cardSTATE = MFEMUL_WORK;
- break;
- }
- case MFEMUL_WORK: {
- if (len == 0) {
- LogTrace(Uart.output, Uart.len, Uart.startTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true);
- break;
- }
- bool encrypted_data = (cardAUTHKEY != 0xFF) ;
- uint8_t *pRecvCmd = receivedCmd;
-
- if (encrypted_data) {
- // decrypt request to separate buffer, trace log saves encrypted source sequence
- mf_crypto1_decryptEx(pcs, receivedCmd, len, decryptedCmd);
- pRecvCmd = decryptedCmd;
- }
-
- uint8_t block = 0;
- uint8_t sector = 0;
-
- if (len == 4 && (pRecvCmd[0] == MIFARE_AUTH_KEYA ||
- pRecvCmd[0] == MIFARE_AUTH_KEYB)) {
-
- // received block -> sector
- block = pRecvCmd[1];
- sector = MifareBlockToSector(block);
-
- if (cardAUTHSC >= _SECTORS) {
- EmSend4bit(encrypted_data ? mf_crypto1_encrypt4bit(pcs, CARD_NACK_IV) : CARD_NACK_IV);
- if (MF_DBGLEVEL >= 4) Dbprintf("Reader tried to operate (0x%02) on out of range block: %d (0x%02x), nacking", pRecvCmd[0], block, block);
- break;
- }
-
- authTimer = GetTickCount();
- cardAUTHSC = sector;
- cardAUTHKEY = pRecvCmd[0] & 0x1;
- crypto1_destroy(pcs);
-
- // load key into crypto
- crypto1_create(pcs, emlGetKey(cardAUTHSC, cardAUTHKEY));
-
- if (!encrypted_data) {
- // first authentication
- // Update crypto state init (UID ^ NONCE)
- crypto1_word(pcs, cuid ^ nonce, 0);
- EmSendCmd(rAUTH_NT, sizeof(rAUTH_NT));
- } else {
- // nested authentication
- /*
- ans = nonce ^ crypto1_word(pcs, cuid ^ nonce, 0)
- num_to_bytes(ans, 4, rAUTH_AT);
- */
- mf_crypto1_encryptEx(pcs, rAUTH_NT, rAUTH_NT_keystream, response, 4, response_par);
- EmSendCmdPar(response, 4, response_par);
-
- if (MF_DBGLEVEL >= 3) Dbprintf("Reader doing nested authentication for block %d (0x%02x) with key %c", block, block, cardAUTHKEY == 0 ? 'A' : 'B');
- }
-
- cardSTATE = MFEMUL_AUTH1;
- break;
- }
-
- // rule 13 of 7.5.3. in ISO 14443-4. chaining shall be continued
- // BUT... ACK --> NACK
- if (len == 1 && pRecvCmd[0] == CARD_ACK) {
- EmSend4bit(encrypted_data ? mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA) : CARD_NACK_NA);
- break;
- }
-
- // rule 12 of 7.5.3. in ISO 14443-4. R(NAK) --> R(ACK)
- if (len == 1 && pRecvCmd[0] == CARD_NACK_NA) {
- EmSend4bit(encrypted_data ? mf_crypto1_encrypt4bit(pcs, CARD_ACK) : CARD_ACK);
- break;
- }
-
- // halt
- if (len > 1 && pRecvCmd[0] == ISO14443A_CMD_HALT && pRecvCmd[1] == 0x00) {
- LED_B_OFF();
- LED_C_OFF();
- cardSTATE = MFEMUL_HALTED;
- if (MF_DBGLEVEL >= 4) Dbprintf("--> HALTED. Selected time: %d ms", GetTickCount() - selTimer);
- LogTrace(Uart.output, Uart.len, Uart.startTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true);
- cardAUTHKEY = 0xff;
- break;
- }
-
- // RATS
- if (pRecvCmd[0] == ISO14443A_CMD_RATS) {
- EmSend4bit(encrypted_data ? mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA) : CARD_NACK_NA);
- break;
- }
-
- if (pRecvCmd[0] == ISO14443A_CMD_READBLOCK ||
- pRecvCmd[0] == ISO14443A_CMD_WRITEBLOCK ||
- pRecvCmd[0] == MIFARE_CMD_INC ||
- pRecvCmd[0] == MIFARE_CMD_DEC ||
- pRecvCmd[0] == MIFARE_CMD_RESTORE ||
- pRecvCmd[0] == MIFARE_CMD_TRANSFER) {
-
- if (!encrypted_data) {
- EmSend4bit(CARD_NACK_NA);
- if (MF_DBGLEVEL >= 4) Dbprintf("Reader tried to operate (0x%02) under non-encrypted state, nacking", pRecvCmd[0]);
- break;
- }
-
- if (len != 4) {
- EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
- if (MF_DBGLEVEL >= 4) Dbprintf("Request (0x%02) has invalid length, nacking", pRecvCmd[0]);
- break;
- }
-
- block = pRecvCmd[1];
- sector = MifareBlockToSector(block);
-
- if (sector >= _SECTORS) {
- EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
- if (MF_DBGLEVEL >= 4) Dbprintf("Reader tried to operate (0x%02) on out of range block: %d (0x%02x), nacking", pRecvCmd[0], block, block);
- break;
- }
-
- if (sector != cardAUTHSC) {
- EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
- if (MF_DBGLEVEL >= 4) Dbprintf("Reader tried to operate (0x%02) on block (0x%02x) not authenticated for (0x%02x) sector, nacking", pRecvCmd[0], block, cardAUTHSC);
- break;
- }
- }
- // read block
- if (pRecvCmd[0] == ISO14443A_CMD_READBLOCK) {
- if (MF_DBGLEVEL >= 4) Dbprintf("Reader reading block %d (0x%02x)", block, block);
-
- emlGetMem(response, block, 1);
- AddCrc14A(response, 16);
- mf_crypto1_encrypt(pcs, response, 18, response_par);
- EmSendCmdPar(response, 18, response_par);
- numReads++;
- if (exitAfterNReads > 0 && numReads >= exitAfterNReads) {
- Dbprintf("%d reads done, exiting", numReads);
- finished = true;
- }
- break;
- }
- // write block
- if (pRecvCmd[0] == ISO14443A_CMD_WRITEBLOCK) {
- if (MF_DBGLEVEL >= 4) Dbprintf("RECV 0xA0 write block %d (%02x)", block, block);
- EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
- cardSTATE = MFEMUL_WRITEBL2;
- cardWRBL = block;
- break;
- }
- // increment, decrement, restore
- if (pRecvCmd[0] == MIFARE_CMD_INC ||
- pRecvCmd[0] == MIFARE_CMD_DEC ||
- pRecvCmd[0] == MIFARE_CMD_RESTORE) {
-
- if (MF_DBGLEVEL >= 4) Dbprintf("RECV 0x%02x inc(0xC1)/dec(0xC0)/restore(0xC2) block %d (%02x)", pRecvCmd[0], block, block);
-
- if (emlCheckValBl(block)) {
- if (MF_DBGLEVEL >= 4) Dbprintf("Reader tried to operate on block, but emlCheckValBl failed, nacking");
- EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
- break;
- }
- EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
- if (pRecvCmd[0] == MIFARE_CMD_INC) cardSTATE = MFEMUL_INTREG_INC;
- if (pRecvCmd[0] == MIFARE_CMD_DEC) cardSTATE = MFEMUL_INTREG_DEC;
- if (pRecvCmd[0] == MIFARE_CMD_RESTORE) cardSTATE = MFEMUL_INTREG_REST;
- cardWRBL = block;
- break;
- }
- // transfer
- if (pRecvCmd[0] == MIFARE_CMD_TRANSFER) {
- if (MF_DBGLEVEL >= 4) Dbprintf("RECV 0x%02x transfer block %d (%02x)", pRecvCmd[0], block, block);
- if (emlSetValBl(cardINTREG, cardINTBLOCK, block))
- EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
- else
- EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
- break;
- }
- // command not allowed
- if (MF_DBGLEVEL >= 4) Dbprintf("Received command not allowed, nacking");
- EmSend4bit(encrypted_data ? mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA) : CARD_NACK_NA);
- break;
- }
- case MFEMUL_WRITEBL2: {
- if (len == 18) {
- mf_crypto1_decryptEx(pcs, receivedCmd, len, decryptedCmd);
- emlSetMem(decryptedCmd, cardWRBL, 1);
- EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
- cardSTATE = MFEMUL_WORK;
- } else {
- cardSTATE_TO_IDLE();
- LogTrace(Uart.output, Uart.len, Uart.startTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true);
- }
- break;
- }
- case MFEMUL_INTREG_INC: {
- mf_crypto1_decryptEx(pcs, receivedCmd, len, decryptedCmd);
- memcpy(&ans, decryptedCmd, 4);
- if (emlGetValBl(&cardINTREG, &cardINTBLOCK, cardWRBL)) {
- EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
- cardSTATE_TO_IDLE();
- break;
- }
- LogTrace(Uart.output, Uart.len, Uart.startTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true);
- cardINTREG = cardINTREG + ans;
- cardSTATE = MFEMUL_WORK;
- break;
- }
- case MFEMUL_INTREG_DEC: {
- mf_crypto1_decryptEx(pcs, receivedCmd, len, decryptedCmd);
- memcpy(&ans, decryptedCmd, 4);
- if (emlGetValBl(&cardINTREG, &cardINTBLOCK, cardWRBL)) {
- EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
- cardSTATE_TO_IDLE();
- break;
- }
- LogTrace(Uart.output, Uart.len, Uart.startTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true);
- cardINTREG = cardINTREG - ans;
- cardSTATE = MFEMUL_WORK;
- break;
- }
- case MFEMUL_INTREG_REST: {
- mf_crypto1_decryptEx(pcs, receivedCmd, len, decryptedCmd);
- memcpy(&ans, decryptedCmd, 4);
- if (emlGetValBl(&cardINTREG, &cardINTBLOCK, cardWRBL)) {
- EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
- cardSTATE_TO_IDLE();
- break;
- }
- LogTrace(Uart.output, Uart.len, Uart.startTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true);
- cardSTATE = MFEMUL_WORK;
- break;
- }
- }
- }
-
- if (MF_DBGLEVEL >= 1)
- Dbprintf("Emulator stopped. Trace length: %d ", BigBuf_get_traceLen());
-
- cmd_send(CMD_ACK, 1, 0, 0, 0, 0);
- FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
- LEDsoff();
- set_tracing(false);
+void AppendCrc14443a(uint8_t *data, int len) {
+ compute_crc(CRC_14443_A, data, len, data + len, data + len + 1);
}
diff --git a/armsrc/iso14443a.h b/armsrc/iso14443a.h
index 777932540..1e4de4626 100644
--- a/armsrc/iso14443a.h
+++ b/armsrc/iso14443a.h
@@ -27,9 +27,19 @@ extern "C" {
#include "crapto1/crapto1.h"
#include "mifareutil.h"
#include "parity.h"
-#include "random.h"
#include "mifare.h" // structs
+// When the PM acts as tag and is receiving it takes
+// 2 ticks delay in the RF part (for the first falling edge),
+// 3 ticks for the A/D conversion,
+// 8 ticks on average until the start of the SSC transfer,
+// 8 ticks until the SSC samples the first data
+// 7*16 ticks to complete the transfer from FPGA to ARM
+// 8 ticks until the next ssp_clk rising edge
+// 4*16 ticks until we measure the time
+// - 8*16 ticks because we measure the time of the previous transfer
+#define DELAY_AIR2ARM_AS_TAG (2 + 3 + 8 + 8 + 7*16 + 8 + 4*16 - 8*16)
+
typedef struct {
enum {
DEMOD_UNSYNCD,
@@ -95,51 +105,56 @@ typedef struct {
#ifndef CheckCrc14A
# define CheckCrc14A(data, len) check_crc(CRC_14443_A, (data), (len))
-#endif
+#endif
-extern void GetParity(const uint8_t *pbtCmd, uint16_t len, uint8_t *par);
+void GetParity(const uint8_t *pbtCmd, uint16_t len, uint8_t *par);
-extern tDemod *GetDemod(void);
-extern void DemodReset(void);
-extern void DemodInit(uint8_t *data, uint8_t *parity);
-extern tUart *GetUart(void);
-extern void UartReset(void);
-extern void UartInit(uint8_t *data, uint8_t *parity);
-extern RAMFUNC bool MillerDecoding(uint8_t bit, uint32_t non_real_time);
-extern RAMFUNC int ManchesterDecoding(uint8_t bit, uint16_t offset, uint32_t non_real_time);
+tDemod *GetDemod(void);
+void DemodReset(void);
+void DemodInit(uint8_t *data, uint8_t *par);
+tUart *GetUart(void);
+void UartReset(void);
+void UartInit(uint8_t *data, 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);
-extern void RAMFUNC SniffIso14443a(uint8_t param);
-extern void SimulateIso14443aTag(int tagType, int flags, uint8_t *data);
-extern void iso14443a_antifuzz(uint32_t flags);
-extern void ReaderIso14443a(UsbCommand *c);
-extern void ReaderTransmit(uint8_t *frame, uint16_t len, uint32_t *timing);
-extern void ReaderTransmitBitsPar(uint8_t *frame, uint16_t bits, uint8_t *par, uint32_t *timing);
-extern void ReaderTransmitPar(uint8_t *frame, uint16_t len, uint8_t *par, uint32_t *timing);
-extern int ReaderReceive(uint8_t *receivedAnswer, uint8_t *par);
+void RAMFUNC SniffIso14443a(uint8_t param);
+void SimulateIso14443aTag(int tagType, int flags, uint8_t *data);
+void iso14443a_antifuzz(uint32_t flags);
+void ReaderIso14443a(UsbCommand *c);
+void ReaderTransmit(uint8_t *frame, uint16_t len, uint32_t *timing);
+void ReaderTransmitBitsPar(uint8_t *frame, uint16_t bits, uint8_t *par, uint32_t *timing);
+void ReaderTransmitPar(uint8_t *frame, uint16_t len, uint8_t *par, uint32_t *timing);
+int ReaderReceive(uint8_t *receivedAnswer, uint8_t *par);
-extern void iso14443a_setup(uint8_t fpga_minor_mode);
-extern int iso14_apdu(uint8_t *cmd, uint16_t cmd_len, bool send_chaining, void *data, uint8_t *res);
-extern int iso14443a_select_card(uint8_t *uid_ptr, iso14a_card_select_t *resp_data, uint32_t *cuid_ptr, bool anticollision, uint8_t num_cascades, bool no_rats);
-extern int iso14443a_fast_select_card(uint8_t *uid_ptr, uint8_t num_cascades);
-extern void iso14a_set_trigger(bool enable);
+void iso14443a_setup(uint8_t fpga_minor_mode);
+int iso14_apdu(uint8_t *cmd, uint16_t cmd_len, bool send_chaining, void *data, uint8_t *res);
+int iso14443a_select_card(uint8_t *uid_ptr, iso14a_card_select_t *p_card, uint32_t *cuid_ptr, bool anticollision, uint8_t num_cascades, bool no_rats);
+int iso14443a_fast_select_card(uint8_t *uid_ptr, uint8_t num_cascades);
+void iso14a_set_trigger(bool enable);
-extern int EmSendCmd14443aRaw(uint8_t *resp, uint16_t respLen);
-extern int EmSend4bit(uint8_t resp);
-extern int EmSendCmd(uint8_t *resp, uint16_t respLen);
-extern int EmSendCmdEx(uint8_t *resp, uint16_t respLen, bool collision);
-extern int EmGetCmd(uint8_t *received, uint16_t *len, uint8_t *parity);
-extern int EmSendCmdPar(uint8_t *resp, uint16_t respLen, uint8_t *par);
-extern int EmSendCmdParEx(uint8_t *resp, uint16_t respLen, uint8_t *par, bool collision);
-extern int EmSendPrecompiledCmd(tag_response_info_t *response_info);
+int EmSendPrecompiledCmd(tag_response_info_t *response_info);
+int EmSendCmd14443aRaw(uint8_t *resp, uint16_t respLen);
+int EmSend4bit(uint8_t resp);
+int EmSendCmd(uint8_t *resp, uint16_t respLen);
+int EmSendCmdEx(uint8_t *resp, uint16_t respLen, bool collision);
+int EmGetCmd(uint8_t *received, uint16_t *len, uint8_t *par);
+int EmSendCmdPar(uint8_t *resp, uint16_t respLen, uint8_t *par);
+int EmSendCmdParEx(uint8_t *resp, uint16_t respLen, uint8_t *par, bool collision);
+int EmSendPrecompiledCmd(tag_response_info_t *response_info);
+
+void EmLogTraceReader(void);
+
+bool prepare_allocated_tag_modulation(tag_response_info_t *response_info, uint8_t **buffer, size_t *max_buffer_size);
bool EmLogTrace(uint8_t *reader_data, uint16_t reader_len, uint32_t reader_StartTime, uint32_t reader_EndTime, uint8_t *reader_Parity,
uint8_t *tag_data, uint16_t tag_len, uint32_t tag_StartTime, uint32_t tag_EndTime, uint8_t *tag_Parity);
-//extern bool prepare_allocated_tag_modulation(tag_response_info_t *response_info, uint8_t **buffer, size_t *buffer_size);
-
void ReaderMifare(bool first_try, uint8_t block, uint8_t keytype);
void DetectNACKbug();
+void AppendCrc14443a(uint8_t *data, int len);
+
#ifdef __cplusplus
}
#endif
diff --git a/armsrc/iso14443b.h b/armsrc/iso14443b.h
index e3c6c1dc8..cf16d48aa 100644
--- a/armsrc/iso14443b.h
+++ b/armsrc/iso14443b.h
@@ -34,15 +34,15 @@ extern "C" {
# define AddCrc14B(data, len) compute_crc(CRC_14443_B, (data), (len), (data)+(len), (data)+(len)+1)
#endif
-extern void SendRawCommand14443B_Ex(UsbCommand *c);
-extern void iso14443b_setup();
-extern uint8_t iso14443b_apdu(uint8_t const *message, size_t message_length, uint8_t *response);
-extern uint8_t iso14443b_select_card(iso14b_card_select_t *card);
-extern uint8_t iso14443b_select_card_srx(iso14b_card_select_t *card);
+void SendRawCommand14443B_Ex(UsbCommand *c);
+void iso14443b_setup();
+uint8_t iso14443b_apdu(uint8_t const *message, size_t message_length, uint8_t *response);
+uint8_t iso14443b_select_card(iso14b_card_select_t *card);
+uint8_t iso14443b_select_card_srx(iso14b_card_select_t *card);
// testfunctions
-extern void WaitForFpgaDelayQueueIsEmpty(uint16_t delay);
-extern void ClearFpgaShiftingRegisters(void);
+void WaitForFpgaDelayQueueIsEmpty(uint16_t delay);
+void ClearFpgaShiftingRegisters(void);
// States for 14B SIM command
#define SIM_NOFIELD 0
diff --git a/armsrc/iso15693.c b/armsrc/iso15693.c
index 12e9cc815..998c43520 100644
--- a/armsrc/iso15693.c
+++ b/armsrc/iso15693.c
@@ -81,9 +81,9 @@
#define Logic1 Iso15693Logic1
#define FrameEOF Iso15693FrameEOF
-#define Crc(data, len) crc(CRC_15693, (data), (len))
-#define CheckCrc(data, len) check_crc(CRC_15693, (data), (len))
-#define AddCrc(data, len) compute_crc(CRC_15693, (data), (len), (data)+(len), (data)+(len)+1)
+//#define Crc(data, len) Crc(CRC_15693, (data), (len))
+#define CheckCrc15(data, len) check_crc(CRC_15693, (data), (len))
+#define AddCrc15(data, len) compute_crc(CRC_15693, (data), (len), (data)+(len), (data)+(len)+1)
#define sprintUID(target,uid) Iso15693sprintUID((target), (uid))
@@ -621,18 +621,18 @@ void Iso15693InitReader(void) {
// Encode (into the ToSend buffers) an identify request, which is the first
// thing that you must send to a tag to get a response.
-// It expects "out" to be at least CMD_ID_RESP large
-static void BuildIdentifyRequest(uint8_t *out) {
+// It expects "cmdout" to be at least CMD_ID_RESP large
+static void BuildIdentifyRequest(uint8_t *cmdout) {
uint8_t cmd[CMD_ID_RESP] = {0, ISO15_CMD_INVENTORY, 0, 0, 0};
// flags
cmd[0] = ISO15_REQ_SUBCARRIER_SINGLE | ISO15_REQ_DATARATE_HIGH | ISO15_REQ_INVENTORY | ISO15_REQINV_SLOT1;
// no mask
cmd[2] = 0x00;
// CRC
- AddCrc(cmd, 3);
+ AddCrc15(cmd, 3);
// coding as high speed (1 out of 4)
CodeIso15693AsReader(cmd, CMD_ID_RESP);
- memcpy(out, cmd, CMD_ID_RESP);
+ memcpy(cmdout, cmd, CMD_ID_RESP);
}
// uid is in transmission order (which is reverse of display order)
@@ -658,7 +658,7 @@ static void BuildReadBlockRequest(uint8_t **out, uint8_t *uid, uint8_t blockNumb
// Block number to read
cmd[10] = blockNumber;//0x00;
// CRC
- AddCrc(cmd, 11);
+ AddCrc15(cmd, 11);
CodeIso15693AsReader(cmd, CMD_READ_RESP);
memcpy(out, cmd, CMD_ID_RESP);
}
@@ -666,7 +666,7 @@ static void BuildReadBlockRequest(uint8_t **out, uint8_t *uid, uint8_t blockNumb
// Now the VICC>VCD responses when we are simulating a tag
// It expects "out" to be at least CMD_INV_RESP large
-static void BuildInventoryResponse(uint8_t *out, uint8_t *uid) {
+static void BuildInventoryResponse(uint8_t *cmdout, uint8_t *uid) {
uint8_t cmd[CMD_INV_RESP] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
@@ -685,9 +685,9 @@ static void BuildInventoryResponse(uint8_t *out, uint8_t *uid) {
cmd[8] = uid[1]; //0x05;
cmd[9] = uid[0]; //0xe0;
// CRC
- AddCrc(cmd, 10);
+ AddCrc15(cmd, 10);
CodeIso15693AsReader(cmd, CMD_INV_RESP);
- memcpy(out, cmd, CMD_INV_RESP);
+ memcpy(cmdout, cmd, CMD_INV_RESP);
}
// Universal Method for sending to and recv bytes from a tag
@@ -780,7 +780,7 @@ void DbdecodeIso15693Answer(int len, uint8_t *d) {
strncat(status, "No error ", DBD15STATLEN - strlen(status));
}
- if (CheckCrc(d, len))
+ if (CheckCrc15(d, len))
strncat(status, "[+] crc OK", DBD15STATLEN - strlen(status));
else
strncat(status, "[!] crc fail", DBD15STATLEN - strlen(status));
@@ -932,7 +932,7 @@ void BruteforceIso15693Afi(uint32_t speed) {
data[0] = ISO15_REQ_SUBCARRIER_SINGLE | ISO15_REQ_DATARATE_HIGH | ISO15_REQ_INVENTORY | ISO15_REQINV_SLOT1;
data[1] = ISO15_CMD_INVENTORY;
data[2] = 0; // mask length
- AddCrc(data, 3);
+ AddCrc15(data, 3);
datalen += 2;
recvlen = SendDataTag(data, datalen, false, speed, buf);
@@ -951,7 +951,7 @@ void BruteforceIso15693Afi(uint32_t speed) {
for (uint16_t i = 0; i < 256; i++) {
data[2] = i & 0xFF;
- AddCrc(data, 4);
+ AddCrc15(data, 4);
datalen += 2;
recvlen = SendDataTag(data, datalen, false, speed, buf);
WDT_HIT();
diff --git a/armsrc/legicrf.h b/armsrc/legicrf.h
index 1c275a1ed..76c392257 100644
--- a/armsrc/legicrf.h
+++ b/armsrc/legicrf.h
@@ -14,8 +14,8 @@
#include "proxmark3.h"
-extern void LegicRfInfo(void);
-extern void LegicRfReader(uint16_t offset, uint16_t len, uint8_t iv);
-extern void LegicRfWriter(uint16_t offset, uint16_t byte, uint8_t iv, uint8_t *data);
+void LegicRfInfo(void);
+void LegicRfReader(uint16_t offset, uint16_t len, uint8_t iv);
+void LegicRfWriter(uint16_t offset, uint16_t len, uint8_t iv, uint8_t *data);
#endif /* __LEGICRF_H */
diff --git a/armsrc/legicrfsim.h b/armsrc/legicrfsim.h
index da70bff0c..27fce129b 100644
--- a/armsrc/legicrfsim.h
+++ b/armsrc/legicrfsim.h
@@ -14,6 +14,6 @@
#include "proxmark3.h"
-extern void LegicRfSimulate(uint8_t tagtype);
+void LegicRfSimulate(uint8_t tagtype);
#endif /* __LEGICRFSIM_H */
diff --git a/armsrc/lfops.c b/armsrc/lfops.c
index 1e6f22863..cfb93b7d2 100644
--- a/armsrc/lfops.c
+++ b/armsrc/lfops.c
@@ -651,7 +651,7 @@ void SimulateTagLowFrequency(int period, int gap, int ledcontrol) {
#define DEBUG_FRAME_CONTENTS 1
-void SimulateTagLowFrequencyBidir(int divisor, int t0) {
+void SimulateTagLowFrequencyBidir(int divisor, int max_bitlen) {
}
// compose fc/5 fc/8 waveform (FSK1)
@@ -901,7 +901,7 @@ static void stAskSimBit(int *n, uint8_t clock) {
}
// args clock, ask/man or askraw, invert, transmission separator
-void CmdASKsimTag(uint16_t arg1, uint16_t arg2, size_t size, uint8_t *BitStream, int ledcontrol) {
+void CmdASKsimTag(uint16_t arg1, uint16_t arg2, size_t size, uint8_t *bits, int ledcontrol) {
FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
set_tracing(false);
@@ -914,20 +914,20 @@ void CmdASKsimTag(uint16_t arg1, uint16_t arg2, size_t size, uint8_t *BitStream,
if (encoding == 2) { //biphase
uint8_t phase = 0;
for (i = 0; i < size; i++) {
- biphaseSimBit(BitStream[i]^invert, &n, clk, &phase);
+ biphaseSimBit(bits[i]^invert, &n, clk, &phase);
}
if (phase == 1) { //run a second set inverted to keep phase in check
for (i = 0; i < size; i++) {
- biphaseSimBit(BitStream[i]^invert, &n, clk, &phase);
+ biphaseSimBit(bits[i]^invert, &n, clk, &phase);
}
}
} else { // ask/manchester || ask/raw
for (i = 0; i < size; i++) {
- askSimBit(BitStream[i]^invert, &n, clk, encoding);
+ askSimBit(bits[i]^invert, &n, clk, encoding);
}
- if (encoding == 0 && BitStream[0] == BitStream[size - 1]) { //run a second set inverted (for ask/raw || biphase phase)
+ if (encoding == 0 && bits[0] == bits[size - 1]) { //run a second set inverted (for ask/raw || biphase phase)
for (i = 0; i < size; i++) {
- askSimBit(BitStream[i]^invert ^ 1, &n, clk, encoding);
+ askSimBit(bits[i]^invert ^ 1, &n, clk, encoding);
}
}
}
@@ -968,7 +968,7 @@ static void pskSimBit(uint8_t waveLen, int *n, uint8_t clk, uint8_t *curPhase, b
}
// args clock, carrier, invert,
-void CmdPSKsimTag(uint16_t arg1, uint16_t arg2, size_t size, uint8_t *BitStream, int ledcontrol) {
+void CmdPSKsimTag(uint16_t arg1, uint16_t arg2, size_t size, uint8_t *bits, int ledcontrol) {
FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
set_tracing(false);
@@ -978,7 +978,7 @@ void CmdPSKsimTag(uint16_t arg1, uint16_t arg2, size_t size, uint8_t *BitStream,
uint8_t invert = arg2 & 0xFF;
uint8_t curPhase = 0;
for (i = 0; i < size; i++) {
- if (BitStream[i] == curPhase) {
+ if (bits[i] == curPhase) {
pskSimBit(carrier, &n, clk, &curPhase, false);
} else {
pskSimBit(carrier, &n, clk, &curPhase, true);
@@ -997,9 +997,8 @@ void CmdPSKsimTag(uint16_t arg1, uint16_t arg2, size_t size, uint8_t *BitStream,
// loop to get raw HID waveform then FSK demodulate the TAG ID from it
void CmdHIDdemodFSK(int findone, uint32_t *high, uint32_t *low, int ledcontrol) {
uint8_t *dest = BigBuf_get_addr();
- size_t size = 0;
+ size_t size;
uint32_t hi2 = 0, hi = 0, lo = 0;
- int idx = 0;
int dummyIdx = 0;
// Configure to go in 125Khz listen mode
LFSetupFPGAForADC(95, true);
@@ -1015,7 +1014,7 @@ void CmdHIDdemodFSK(int findone, uint32_t *high, uint32_t *low, int ledcontrol)
DoAcquisition_default(-1, true);
// FSK demodulator
size = 50 * 128 * 2; //big enough to catch 2 sequences of largest format
- idx = HIDdemodFSK(dest, &size, &hi2, &hi, &lo, &dummyIdx);
+ int idx = HIDdemodFSK(dest, &size, &hi2, &hi, &lo, &dummyIdx);
if (idx < 0) continue;
if (idx > 0 && lo > 0 && (size == 96 || size == 192)) {
@@ -1029,7 +1028,7 @@ void CmdHIDdemodFSK(int findone, uint32_t *high, uint32_t *low, int ledcontrol)
);
} else { //standard HID tags 44/96 bits
uint8_t bitlen = 0;
- uint32_t fc = 0;
+ uint32_t fac = 0;
uint32_t cardnum = 0;
if (((hi >> 5) & 1) == 1) { //if bit 38 is set then < 37 bit format is used
@@ -1041,35 +1040,35 @@ void CmdHIDdemodFSK(int findone, uint32_t *high, uint32_t *low, int ledcontrol)
idx3++;
}
bitlen = idx3 + 19;
- fc = 0;
+ fac = 0;
cardnum = 0;
if (bitlen == 26) {
cardnum = (lo >> 1) & 0xFFFF;
- fc = (lo >> 17) & 0xFF;
+ fac = (lo >> 17) & 0xFF;
}
if (bitlen == 37) {
cardnum = (lo >> 1) & 0x7FFFF;
- fc = ((hi & 0xF) << 12) | (lo >> 20);
+ fac = ((hi & 0xF) << 12) | (lo >> 20);
}
if (bitlen == 34) {
cardnum = (lo >> 1) & 0xFFFF;
- fc = ((hi & 1) << 15) | (lo >> 17);
+ fac = ((hi & 1) << 15) | (lo >> 17);
}
if (bitlen == 35) {
cardnum = (lo >> 1) & 0xFFFFF;
- fc = ((hi & 1) << 11) | (lo >> 21);
+ fac = ((hi & 1) << 11) | (lo >> 21);
}
} else { //if bit 38 is not set then 37 bit format is used
bitlen = 37;
cardnum = (lo >> 1) & 0x7FFFF;
- fc = ((hi & 0xF) << 12) | (lo >> 20);
+ fac = ((hi & 0xF) << 12) | (lo >> 20);
}
Dbprintf("TAG ID: %x%08x (%d) - Format Len: %dbit - FC: %d - Card: %d",
hi,
lo,
(lo >> 1) & 0xFFFF,
bitlen,
- fc,
+ fac,
cardnum
);
}
@@ -1095,7 +1094,7 @@ void CmdAWIDdemodFSK(int findone, uint32_t *high, uint32_t *low, int ledcontrol)
//big enough to catch 2 sequences of largest format
size_t size = 12800; //50 * 128 * 2;
- int idx = 0, dummyIdx = 0;
+ int dummyIdx = 0;
BigBuf_Clear_keep_EM();
@@ -1109,7 +1108,7 @@ void CmdAWIDdemodFSK(int findone, uint32_t *high, uint32_t *low, int ledcontrol)
DoAcquisition_default(-1, true);
// FSK demodulator
- idx = detectAWID(dest, &size, &dummyIdx);
+ int idx = detectAWID(dest, &size, &dummyIdx);
if (idx <= 0 || size != 96) continue;
// Index map
@@ -1147,16 +1146,16 @@ void CmdAWIDdemodFSK(int findone, uint32_t *high, uint32_t *low, int ledcontrol)
// w = wiegand parity
// (26 bit format shown)
- uint32_t fc = 0;
+ uint32_t fac = 0;
uint32_t cardnum = 0;
uint32_t code1 = 0;
uint32_t code2 = 0;
uint8_t fmtLen = bytebits_to_byte(dest, 8);
if (fmtLen == 26) {
- fc = bytebits_to_byte(dest + 9, 8);
+ fac = bytebits_to_byte(dest + 9, 8);
cardnum = bytebits_to_byte(dest + 17, 16);
code1 = bytebits_to_byte(dest + 8, fmtLen);
- Dbprintf("AWID Found - BitLength: %d, FC: %d, Card: %d - Wiegand: %x, Raw: %08x%08x%08x", fmtLen, fc, cardnum, code1, rawHi2, rawHi, rawLo);
+ Dbprintf("AWID Found - BitLength: %d, FC: %d, Card: %d - Wiegand: %x, Raw: %08x%08x%08x", fmtLen, fac, cardnum, code1, rawHi2, rawHi, rawLo);
} else {
cardnum = bytebits_to_byte(dest + 8 + (fmtLen - 17), 16);
if (fmtLen > 32) {
@@ -1174,8 +1173,6 @@ void CmdAWIDdemodFSK(int findone, uint32_t *high, uint32_t *low, int ledcontrol)
*low = rawLo;
break;
}
- // reset
- idx = 0;
WDT_HIT();
}
FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
@@ -1186,8 +1183,8 @@ void CmdAWIDdemodFSK(int findone, uint32_t *high, uint32_t *low, int ledcontrol)
void CmdEM410xdemod(int findone, uint32_t *high, uint64_t *low, int ledcontrol) {
uint8_t *dest = BigBuf_get_addr();
- size_t size = 0, idx = 0;
- int clk = 0, invert = 0, errCnt = 0, maxErr = 20;
+ size_t size, idx = 0;
+ int clk = 0, invert = 0, errCnt, maxErr = 20;
uint32_t hi = 0;
uint64_t lo = 0;
@@ -1238,7 +1235,7 @@ void CmdEM410xdemod(int findone, uint32_t *high, uint64_t *low, int ledcontrol)
}
WDT_HIT();
hi = lo = size = idx = 0;
- clk = invert = errCnt = 0;
+ clk = invert = 0;
}
FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
DbpString("Stopped");
@@ -1249,7 +1246,7 @@ void CmdIOdemodFSK(int findone, uint32_t *high, uint32_t *low, int ledcontrol) {
uint8_t *dest = BigBuf_get_addr();
- int dummyIdx = 0, idx = 0;
+ int dummyIdx = 0;
uint32_t code = 0, code2 = 0;
uint8_t version = 0, facilitycode = 0, crc = 0;
uint16_t number = 0, calccrc = 0;
@@ -1269,7 +1266,7 @@ void CmdIOdemodFSK(int findone, uint32_t *high, uint32_t *low, int ledcontrol) {
//fskdemod and get start index
WDT_HIT();
- idx = detectIOProx(dest, &size, &dummyIdx);
+ int idx = detectIOProx(dest, &size, &dummyIdx);
if (idx < 0) continue;
//valid tag found
@@ -1325,8 +1322,6 @@ void CmdIOdemodFSK(int findone, uint32_t *high, uint32_t *low, int ledcontrol) {
code = code2 = 0;
version = facilitycode = 0;
number = 0;
- idx = 0;
-
WDT_HIT();
}
FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
@@ -1481,8 +1476,7 @@ void T55xxReadBlock(uint16_t arg0, uint8_t Block, uint32_t Pwd) {
bool PwdMode = arg0 & 0x1;
uint8_t Page = (arg0 & 0x2) >> 1;
bool brute_mem = arg0 & 0x4;
-
- uint32_t i = 0;
+ uint32_t i;
// regular read mode
bool RegReadMode = (Block == 0xFF);
@@ -1771,7 +1765,7 @@ void CopyVikingtoT55xx(uint32_t block1, uint32_t block2, uint8_t Q5) {
#define EM410X_ID_LENGTH 40
void WriteEM410x(uint32_t card, uint32_t id_hi, uint32_t id_lo) {
- int i, id_bit;
+ int i;
uint64_t id = EM410X_HEADER;
uint64_t rev_id = 0; // reversed ID
int c_parity[4]; // column parity
@@ -1790,7 +1784,7 @@ void WriteEM410x(uint32_t card, uint32_t id_hi, uint32_t id_lo) {
}
for (i = 0; i < EM410X_ID_LENGTH; ++i) {
- id_bit = rev_id & 1;
+ int id_bit = rev_id & 1;
if (i % 4 == 0) {
// Don't write row parity bit at start of parsing
@@ -1926,7 +1920,6 @@ uint8_t Prepare_Addr(uint8_t addr) {
//====================================================================
uint8_t Prepare_Data(uint16_t data_low, uint16_t data_hi) {
- register uint8_t line_parity;
register uint8_t column_parity;
register uint8_t i, j;
register uint16_t data;
@@ -1935,7 +1928,7 @@ uint8_t Prepare_Data(uint16_t data_low, uint16_t data_hi) {
column_parity = 0;
for (i = 0; i < 4; i++) {
- line_parity = 0;
+ register uint8_t line_parity = 0;
for (j = 0; j < 8; j++) {
line_parity ^= data;
column_parity ^= (data & 1) << j;
diff --git a/armsrc/lfsampling.c b/armsrc/lfsampling.c
index 7018fbae2..b20f6766b 100644
--- a/armsrc/lfsampling.c
+++ b/armsrc/lfsampling.c
@@ -248,9 +248,9 @@ uint32_t ReadLF(bool activeField, bool silent, int sample_size) {
* Initializes the FPGA for reader-mode (field on), and acquires the samples.
* @return number of bits sampled
**/
-uint32_t SampleLF(bool printCfg, int sample_size) {
+uint32_t SampleLF(bool silent, int sample_size) {
BigBuf_Clear_ext(false);
- return ReadLF(true, printCfg, sample_size);
+ return ReadLF(true, silent, sample_size);
}
/**
* Initializes the FPGA for sniffer-mode (field off), and acquires the samples.
diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c
index f6b7692e2..56049a9cd 100644
--- a/armsrc/mifarecmd.c
+++ b/armsrc/mifarecmd.c
@@ -851,12 +851,13 @@ void MifareAcquireEncryptedNonces(uint32_t arg0, uint32_t arg1, uint32_t flags,
// MIFARE nested authentication.
//
//-----------------------------------------------------------------------------
-void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *datain) {
+void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain) {
// params
uint8_t blockNo = arg0 & 0xff;
uint8_t keyType = (arg0 >> 8) & 0xff;
uint8_t targetBlockNo = arg1 & 0xff;
uint8_t targetKeyType = (arg1 >> 8) & 0xff;
+ // calibrate = arg2
uint64_t ui64Key = 0;
ui64Key = bytes_to_num(datain, 6);
@@ -888,14 +889,14 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat
BigBuf_free();
BigBuf_Clear_ext(false);
- if (calibrate) clear_trace();
+ if (arg2) clear_trace();
set_tracing(true);
// statistics on nonce distance
int16_t isOK = 0;
#define NESTED_MAX_TRIES 12
uint16_t unsuccessfull_tries = 0;
- if (calibrate) { // for first call only. Otherwise reuse previous calibration
+ if (arg2) { // calibrate: for first call only. Otherwise reuse previous calibration
LED_B_ON();
WDT_HIT();
diff --git a/armsrc/mifaredesfire.c b/armsrc/mifaredesfire.c
index 3bbf667b5..6168425bc 100644
--- a/armsrc/mifaredesfire.c
+++ b/armsrc/mifaredesfire.c
@@ -167,8 +167,10 @@ void MifareDesfireGetInformation() {
OnSuccess();
}
-void MifareDES_Auth1(uint8_t mode, uint8_t algo, uint8_t keyno, uint8_t *datain) {
-
+void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) {
+ // mode = arg0
+ // algo = arg1
+ // keyno = arg2
int len = 0;
//uint8_t PICC_MASTER_KEY8[8] = { 0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47};
uint8_t PICC_MASTER_KEY16[16] = { 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f };
@@ -195,25 +197,25 @@ void MifareDES_Auth1(uint8_t mode, uint8_t algo, uint8_t keyno, uint8_t *datain
LED_B_OFF();
LED_C_OFF();
- // 3 olika stt att authenticera. AUTH (CRC16) , AUTH_ISO (CRC32) , AUTH_AES (CRC32)
- // 4 olika crypto algo DES, 3DES, 3K3DES, AES
- // 3 olika kommunikations stt, PLAIN,MAC,CRYPTO
+ // 3 different way to authenticate AUTH (CRC16) , AUTH_ISO (CRC32) , AUTH_AES (CRC32)
+ // 4 different crypto arg1 DES, 3DES, 3K3DES, AES
+ // 3 different communication modes, PLAIN,MAC,CRYPTO
- // des, nyckel 0,
- switch (mode) {
+ // des, key 0,
+ switch (arg0) {
case 1: {
uint8_t keybytes[16];
uint8_t RndA[8] = {0x00};
uint8_t RndB[8] = {0x00};
- if (algo == 2) {
+ if (arg1 == 2) {
if (datain[1] == 0xff) {
memcpy(keybytes, PICC_MASTER_KEY16, 16);
} else {
memcpy(keybytes, datain + 1, datalen);
}
} else {
- if (algo == 1) {
+ if (arg1 == 1) {
if (datain[1] == 0xff) {
memcpy(keybytes, null_key_data8, 8);
} else {
@@ -225,13 +227,13 @@ void MifareDES_Auth1(uint8_t mode, uint8_t algo, uint8_t keyno, uint8_t *datain
struct desfire_key defaultkey = {0};
desfirekey_t key = &defaultkey;
- if (algo == 2)
+ if (arg1 == 2)
Desfire_3des_key_new_with_version(keybytes, key);
- else if (algo == 1)
+ else if (arg1 == 1)
Desfire_des_key_new(keybytes, key);
cmd[0] = AUTHENTICATE;
- cmd[1] = keyno; //keynumber
+ cmd[1] = arg2; //keynumber
len = DesfireAPDU(cmd, 2, resp);
if (!len) {
if (MF_DBGLEVEL >= MF_DBG_ERROR) {
@@ -249,9 +251,9 @@ void MifareDES_Auth1(uint8_t mode, uint8_t algo, uint8_t keyno, uint8_t *datain
}
memcpy(encRndB, resp + 3, 8);
- if (algo == 2)
+ if (arg1 == 2)
tdes_dec(&decRndB, &encRndB, key->data);
- else if (algo == 1)
+ else if (arg1 == 1)
des_dec(&decRndB, &encRndB, key->data);
memcpy(RndB, decRndB, 8);
@@ -262,9 +264,9 @@ void MifareDES_Auth1(uint8_t mode, uint8_t algo, uint8_t keyno, uint8_t *datain
memcpy(RndA, decRndA, 8);
uint8_t encRndA[8] = {0x00};
- if (algo == 2)
+ if (arg1 == 2)
tdes_dec(&encRndA, &decRndA, key->data);
- else if (algo == 1)
+ else if (arg1 == 1)
des_dec(&encRndA, &decRndA, key->data);
memcpy(both, encRndA, 8);
@@ -274,9 +276,9 @@ void MifareDES_Auth1(uint8_t mode, uint8_t algo, uint8_t keyno, uint8_t *datain
}
- if (algo == 2)
+ if (arg1 == 2)
tdes_dec(&encRndB, &decRndB, key->data);
- else if (algo == 1)
+ else if (arg1 == 1)
des_dec(&encRndB, &decRndB, key->data);
memcpy(both + 8, encRndB, 8);
@@ -302,9 +304,9 @@ void MifareDES_Auth1(uint8_t mode, uint8_t algo, uint8_t keyno, uint8_t *datain
memcpy(encRndA, resp + 3, 8);
- if (algo == 2)
+ if (arg1 == 2)
tdes_dec(&encRndA, &encRndA, key->data);
- else if (algo == 1)
+ else if (arg1 == 1)
des_dec(&encRndA, &encRndA, key->data);
rol(decRndA, 8);
@@ -320,9 +322,9 @@ void MifareDES_Auth1(uint8_t mode, uint8_t algo, uint8_t keyno, uint8_t *datain
/*
// Current key is a 3DES key, change it to a DES key
- if (algo == 2) {
+ if (arg1 == 2) {
cmd[0] = CHANGE_KEY;
- cmd[1] = keyno;
+ cmd[1] = arg2;
uint8_t newKey[16] = {0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77};
@@ -362,9 +364,9 @@ void MifareDES_Auth1(uint8_t mode, uint8_t algo, uint8_t keyno, uint8_t *datain
} else {
// Current key is a DES key, change it to a 3DES key
- if (algo == 1) {
+ if (arg1 == 1) {
cmd[0] = CHANGE_KEY;
- cmd[1] = keyno;
+ cmd[1] = arg2;
uint8_t newKey[16] = {0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f};
@@ -406,9 +408,9 @@ void MifareDES_Auth1(uint8_t mode, uint8_t algo, uint8_t keyno, uint8_t *datain
*/
OnSuccess();
- if (algo == 2)
+ if (arg1 == 2)
cmd_send(CMD_ACK, 1, 0, 0, skey->data, 16);
- else if (algo == 1)
+ else if (arg1 == 1)
cmd_send(CMD_ACK, 1, 0, 0, skey->data, 8);
} else {
DbpString("Authentication failed.");
@@ -418,7 +420,7 @@ void MifareDES_Auth1(uint8_t mode, uint8_t algo, uint8_t keyno, uint8_t *datain
}
break;
case 2:
- //SendDesfireCommand(AUTHENTICATE_ISO, &keyno, resp);
+ //SendDesfireCommand(AUTHENTICATE_ISO, &arg2, resp);
break;
case 3: {
@@ -495,7 +497,7 @@ void MifareDES_Auth1(uint8_t mode, uint8_t algo, uint8_t keyno, uint8_t *datain
cmd_send(CMD_ACK, 1, len, 0, resp, len);
}
-// 3 olika ISO stt att skicka data till DESFIRE (direkt, inkapslat, inkapslat ISO)
+// 3 different ISO ways to send data to a DESFIRE (direct, capsuled, capsuled ISO)
// cmd = cmd bytes to send
// cmd_len = length of cmd
// dataout = pointer to response data array
@@ -540,7 +542,7 @@ size_t CreateAPDU(uint8_t *datain, size_t len, uint8_t *dataout) {
uint8_t cmd[cmdlen];
memset(cmd, 0, cmdlen);
- cmd[0] = 0x0A; // 0x0A = skicka cid, 0x02 = ingen cid. Srskilda bitar //
+ cmd[0] = 0x0A; // 0x0A = send cid, 0x02 = no cid.
cmd[0] |= pcb_blocknum; // OR the block number into the PCB
cmd[1] = 0x00; // CID: 0x00 //TODO: allow multiple selected cards
diff --git a/armsrc/mifaresim.c b/armsrc/mifaresim.c
new file mode 100644
index 000000000..d4d998a1a
--- /dev/null
+++ b/armsrc/mifaresim.c
@@ -0,0 +1,1253 @@
+//-----------------------------------------------------------------------------
+// Merlok - June 2011, 2012
+// Gerhard de Koning Gans - May 2008
+// Hagen Fritsch - June 2010
+//
+// This code is licensed to you under the terms of the GNU GPL, version 2 or,
+// at your option, any later version. See the LICENSE.txt file for the text of
+// the license.
+//-----------------------------------------------------------------------------
+// Mifare Classic Card Simulation
+//-----------------------------------------------------------------------------
+
+// Verbose Mode:
+// MF_DBG_NONE 0
+// MF_DBG_ERROR 1
+// MF_DBG_ALL 2
+// MF_DBG_EXTENDED 4
+
+#include "iso14443a.h"
+#include "mifaresim.h"
+#include "iso14443crc.h"
+#include "crapto1/crapto1.h"
+#include "BigBuf.h"
+#include "string.h"
+#include "mifareutil.h"
+#include "fpgaloader.h"
+#include "proxmark3.h"
+#include "usb_cdc.h"
+#include "cmd.h"
+#include "protocols.h"
+#include "apps.h"
+
+static tUart Uart;
+
+uint8_t MifareCardType;
+
+static bool IsTrailerAccessAllowed(uint8_t blockNo, uint8_t keytype, uint8_t action) {
+ uint8_t sector_trailer[16];
+ emlGetMem(sector_trailer, blockNo, 1);
+ uint8_t AC = ((sector_trailer[7] >> 5) & 0x04)
+ | ((sector_trailer[8] >> 2) & 0x02)
+ | ((sector_trailer[8] >> 7) & 0x01);
+ switch (action) {
+ case AC_KEYA_READ: {
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("IsTrailerAccessAllowed: AC_KEYA_READ");
+ return false;
+ }
+ case AC_KEYA_WRITE: {
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("IsTrailerAccessAllowed: AC_KEYA_WRITE");
+ return ((keytype == AUTHKEYA && (AC == 0x00 || AC == 0x01))
+ || (keytype == AUTHKEYB && (AC == 0x04 || AC == 0x03)));
+ }
+ case AC_KEYB_READ: {
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("IsTrailerAccessAllowed: AC_KEYB_READ");
+ return (keytype == AUTHKEYA && (AC == 0x00 || AC == 0x02 || AC == 0x01));
+ }
+ case AC_KEYB_WRITE: {
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("IsTrailerAccessAllowed: AC_KEYB_WRITE");
+ return ((keytype == AUTHKEYA && (AC == 0x00 || AC == 0x04))
+ || (keytype == AUTHKEYB && (AC == 0x04 || AC == 0x03)));
+ }
+ case AC_AC_READ: {
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("IsTrailerAccessAllowed: AC_AC_READ");
+ return ((keytype == AUTHKEYA)
+ || (keytype == AUTHKEYB && !(AC == 0x00 || AC == 0x02 || AC == 0x01)));
+ }
+ case AC_AC_WRITE: {
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("IsTrailerAccessAllowed: AC_AC_WRITE");
+ return ((keytype == AUTHKEYA && (AC == 0x01))
+ || (keytype == AUTHKEYB && (AC == 0x03 || AC == 0x05)));
+ }
+ default:
+ return false;
+ }
+}
+
+
+static bool IsDataAccessAllowed(uint8_t blockNo, uint8_t keytype, uint8_t action) {
+
+ uint8_t sector_trailer[16];
+ emlGetMem(sector_trailer, SectorTrailer(blockNo), 1);
+
+ uint8_t sector_block;
+ if (blockNo <= MIFARE_2K_MAXBLOCK) {
+ sector_block = blockNo & 0x03;
+ } else {
+ sector_block = (blockNo & 0x0f) / 5;
+ }
+
+ uint8_t AC;
+ switch (sector_block) {
+ case 0x00: {
+ AC = ((sector_trailer[7] >> 2) & 0x04)
+ | ((sector_trailer[8] << 1) & 0x02)
+ | ((sector_trailer[8] >> 4) & 0x01);
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("IsDataAccessAllowed: case 0x00 - %02x", AC);
+ break;
+ }
+ case 0x01: {
+ AC = ((sector_trailer[7] >> 3) & 0x04)
+ | ((sector_trailer[8] >> 0) & 0x02)
+ | ((sector_trailer[8] >> 5) & 0x01);
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("IsDataAccessAllowed: case 0x01 - %02x", AC);
+ break;
+ }
+ case 0x02: {
+ AC = ((sector_trailer[7] >> 4) & 0x04)
+ | ((sector_trailer[8] >> 1) & 0x02)
+ | ((sector_trailer[8] >> 6) & 0x01);
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("IsDataAccessAllowed: case 0x02 - %02x", AC);
+ break;
+ }
+ default:
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("IsDataAccessAllowed: Error");
+ return false;
+ }
+
+ switch (action) {
+ case AC_DATA_READ: {
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("IsDataAccessAllowed - AC_DATA_READ: OK");
+ return ((keytype == AUTHKEYA && !(AC == 0x03 || AC == 0x05 || AC == 0x07))
+ || (keytype == AUTHKEYB && !(AC == 0x07)));
+ }
+ case AC_DATA_WRITE: {
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("IsDataAccessAllowed - AC_DATA_WRITE: OK");
+ return ((keytype == AUTHKEYA && (AC == 0x00))
+ || (keytype == AUTHKEYB && (AC == 0x00 || AC == 0x04 || AC == 0x06 || AC == 0x03)));
+ }
+ case AC_DATA_INC: {
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("IsDataAccessAllowed - AC_DATA_INC: OK");
+ return ((keytype == AUTHKEYA && (AC == 0x00))
+ || (keytype == AUTHKEYB && (AC == 0x00 || AC == 0x06)));
+ }
+ case AC_DATA_DEC_TRANS_REST: {
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("AC_DATA_DEC_TRANS_REST: OK");
+ return ((keytype == AUTHKEYA && (AC == 0x00 || AC == 0x06 || AC == 0x01))
+ || (keytype == AUTHKEYB && (AC == 0x00 || AC == 0x06 || AC == 0x01)));
+ }
+ }
+
+ return false;
+}
+
+static bool IsAccessAllowed(uint8_t blockNo, uint8_t keytype, uint8_t action) {
+ if (IsSectorTrailer(blockNo)) {
+ return IsTrailerAccessAllowed(blockNo, keytype, action);
+ } else {
+ return IsDataAccessAllowed(blockNo, keytype, action);
+ }
+}
+
+static void MifareSimInit(uint16_t flags, uint8_t *datain, tag_response_info_t **responses, uint32_t *cuid, uint8_t *uid_len) {
+
+ // SPEC: https://www.nxp.com/docs/en/application-note/AN10833.pdf
+ // ATQA
+
+ static uint8_t rATQA_Mini_4B[] = {0x44, 0x00}; // indicate Mifare classic Mini 4Byte UID
+ static uint8_t rATQA_Mini_7B[] = {0x44, 0x00}; // indicate Mifare classic Mini 7Byte UID
+ static uint8_t rATQA_Mini_10B[] = {0x44, 0x00}; // indicate Mifare classic Mini 10Byte UID
+
+ static uint8_t rATQA_1k_4B[] = {0x04, 0x00}; // indicate Mifare classic 1k 4Byte UID
+ static uint8_t rATQA_1k_7B[] = {0x44, 0x00}; // indicate Mifare classic 1k 7Byte UID
+ static uint8_t rATQA_1k_10B[] = {0x42, 0x00}; // indicate Mifare classic 4k 10Byte UID
+
+ static uint8_t rATQA_2k_4B[] = {0x04, 0x00}; // indicate Mifare classic 2k 4Byte UID
+ static uint8_t rATQA_2k_7B[] = {0x44, 0x00}; // indicate Mifare classic 2k 7Byte UID
+ static uint8_t rATQA_2k_10B[] = {0x42, 0x00}; // indicate Mifare classic 4k 10Byte UID
+
+ static uint8_t rATQA_4k_4B[] = {0x02, 0x00}; // indicate Mifare classic 4k 4Byte UID
+ static uint8_t rATQA_4k_7B[] = {0x42, 0x00}; // indicate Mifare classic 4k 7Byte UID
+ static uint8_t rATQA_4k_10B[] = {0x42, 0x00}; // indicate Mifare classic 4k 10Byte UID
+
+ static uint8_t rATQA[] = {0x00, 0x00};
+
+ // SAK + CRC
+ static uint8_t rSAK_mini[] = {0x09, 0x3f, 0xcc}; // mifare Mini
+ static uint8_t rSAK_1[] = {0x08, 0xb6, 0xdd}; // mifare 1k
+ static uint8_t rSAK_2[] = {0x08, 0xb6, 0xdd}; // mifare 2k
+ static uint8_t rSAK_4[] = {0x18, 0x37, 0xcd}; // mifare 4k
+
+ static uint8_t rUIDBCC1[] = {0x00, 0x00, 0x00, 0x00, 0x00}; // UID 1st cascade level
+ static uint8_t rUIDBCC2[] = {0x00, 0x00, 0x00, 0x00, 0x00}; // UID 2nd cascade level
+ static uint8_t rUIDBCC3[] = {0x00, 0x00, 0x00, 0x00, 0x00}; // UID 3nd cascade level
+
+ static uint8_t rSAK1[] = {0x04, 0xda, 0x17}; // Acknowledge but indicate UID is not finished. Used for any MIFARE Classic CL1 with double UID size
+
+ *uid_len = 0;
+
+ // -- Determine the UID
+ // Can be set from emulator memory or incoming data
+ // Length: 4,7,or 10 bytes
+ if ((flags & FLAG_UID_IN_EMUL) == FLAG_UID_IN_EMUL) {
+ emlGetMemBt(datain, 0, 10); // load 10bytes from EMUL to the datain pointer. to be used below.
+ }
+
+ if ((flags & FLAG_4B_UID_IN_DATA) == FLAG_4B_UID_IN_DATA) { // get UID from datain
+ memcpy(rUIDBCC1, datain, 4);
+ *uid_len = 4;
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("MifareSimInit - FLAG_4B_UID_IN_DATA => Get UID from datain: %02X - Flag: %02X - UIDBCC1: %02X", FLAG_4B_UID_IN_DATA, flags, rUIDBCC1);
+ } else if ((flags & FLAG_7B_UID_IN_DATA) == FLAG_7B_UID_IN_DATA) {
+ memcpy(&rUIDBCC1[1], datain, 3);
+ memcpy(rUIDBCC2, datain + 3, 4);
+ *uid_len = 7;
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("MifareSimInit - FLAG_7B_UID_IN_DATA => Get UID from datain: %02X - Flag: %02X - UIDBCC1: %02X", FLAG_7B_UID_IN_DATA, flags, rUIDBCC1);
+ } else if ((flags & FLAG_10B_UID_IN_DATA) == FLAG_10B_UID_IN_DATA) {
+ memcpy(&rUIDBCC1[1], datain, 3);
+ memcpy(&rUIDBCC2[1], datain + 3, 3);
+ memcpy(rUIDBCC3, datain + 6, 4);
+ *uid_len = 10;
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("MifareSimInit - FLAG_10B_UID_IN_DATA => Get UID from datain: %02X - Flag: %02X - UIDBCC1: %02X", FLAG_10B_UID_IN_DATA, flags, rUIDBCC1);
+ }
+
+ switch (*uid_len) {
+
+ // UID 4B
+ case 4:
+ switch (MifareCardType) {
+ case 0: // Mifare Mini
+ memcpy(rATQA, rATQA_Mini_4B, sizeof rATQA_Mini_4B);
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("=> Using rATQA_Mini_4B");
+ break;
+ case 1: // Mifare 1K
+ memcpy(rATQA, rATQA_1k_4B, sizeof rATQA_1k_4B);
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("=> Using rATQA_1k_4B");
+ break;
+ case 2: // Mifare 2L
+ memcpy(rATQA, rATQA_2k_4B, sizeof rATQA_2k_4B);
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("=> Using rATQA_2k_4B");
+ break;
+ case 4: // Mifare 4K
+ memcpy(rATQA, rATQA_4k_4B, sizeof rATQA_4k_4B);
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("=> Using rATQA_4k_4B");
+ break;
+ }
+
+ // save CUID
+ *cuid = bytes_to_num(rUIDBCC1, 4);
+ // BCC
+ rUIDBCC1[4] = rUIDBCC1[0] ^ rUIDBCC1[1] ^ rUIDBCC1[2] ^ rUIDBCC1[3];
+ if (MF_DBGLEVEL >= MF_DBG_NONE) {
+ Dbprintf("4B UID: %02x%02x%02x%02x", rUIDBCC1[0], rUIDBCC1[1], rUIDBCC1[2], rUIDBCC1[3]);
+ }
+ break;
+
+ // UID 7B
+ case 7:
+
+ switch (MifareCardType) {
+ case 0: // Mifare Mini
+ memcpy(rATQA, rATQA_Mini_7B, sizeof rATQA_Mini_7B);
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("=> Using rATQA_Mini_7B");
+ break;
+ case 1:
+ memcpy(rATQA, rATQA_1k_7B, sizeof rATQA_1k_7B);
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("=> Using rATQA_1k_7B");
+ break;
+ case 2:
+ memcpy(rATQA, rATQA_2k_7B, sizeof rATQA_2k_7B);
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("=> Using rATQA_2k_7B");
+ break;
+ case 4:
+ memcpy(rATQA, rATQA_4k_7B, sizeof rATQA_4k_7B);
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("=> Using rATQA_4k_4B");
+ break;
+ }
+
+ // save CUID
+ *cuid = bytes_to_num(rUIDBCC2, 4);
+ // CascadeTag, CT
+ rUIDBCC1[0] = MIFARE_SELECT_CT;
+ // BCC
+ rUIDBCC1[4] = rUIDBCC1[0] ^ rUIDBCC1[1] ^ rUIDBCC1[2] ^ rUIDBCC1[3];
+ rUIDBCC2[4] = rUIDBCC2[0] ^ rUIDBCC2[1] ^ rUIDBCC2[2] ^ rUIDBCC2[3];
+ if (MF_DBGLEVEL >= MF_DBG_NONE) {
+ Dbprintf("7B UID: %02x %02x %02x %02x %02x %02x %02x",
+ rUIDBCC1[1], rUIDBCC1[2], rUIDBCC1[3], rUIDBCC2[0], rUIDBCC2[1], rUIDBCC2[2], rUIDBCC2[3]);
+ }
+ break;
+
+ // UID 10B
+ case 10:
+ switch (MifareCardType) {
+ case 0: // Mifare Mini
+ memcpy(rATQA, rATQA_Mini_10B, sizeof rATQA_Mini_10B);
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("=> Using rATQA_Mini_10B");
+ break;
+ case 1:
+ memcpy(rATQA, rATQA_1k_10B, sizeof rATQA_1k_10B);
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("=> Using rATQA_1k_10B");
+ break;
+ case 2:
+ memcpy(rATQA, rATQA_2k_10B, sizeof rATQA_2k_10B);
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("=> Using rATQA_2k_10B");
+ break;
+ case 4:
+ memcpy(rATQA, rATQA_4k_10B, sizeof rATQA_4k_10B);
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("=> Using rATQA_4k_10B");
+ break;
+ }
+
+ // save CUID
+ *cuid = bytes_to_num(rUIDBCC3, 4);
+ // CascadeTag, CT
+ rUIDBCC1[0] = MIFARE_SELECT_CT;
+ rUIDBCC2[0] = MIFARE_SELECT_CT;
+ // BCC
+ rUIDBCC1[4] = rUIDBCC1[0] ^ rUIDBCC1[1] ^ rUIDBCC1[2] ^ rUIDBCC1[3];
+ rUIDBCC2[4] = rUIDBCC2[0] ^ rUIDBCC2[1] ^ rUIDBCC2[2] ^ rUIDBCC2[3];
+ rUIDBCC3[4] = rUIDBCC3[0] ^ rUIDBCC3[1] ^ rUIDBCC3[2] ^ rUIDBCC3[3];
+
+ if (MF_DBGLEVEL >= MF_DBG_NONE) {
+ Dbprintf("10B UID: %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
+ rUIDBCC1[1], rUIDBCC1[2], rUIDBCC1[3],
+ rUIDBCC2[1], rUIDBCC2[2], rUIDBCC2[3],
+ rUIDBCC3[0], rUIDBCC3[1], rUIDBCC3[2], rUIDBCC3[3]
+ );
+ }
+ break;
+ default:
+ break;
+ }
+
+ static tag_response_info_t responses_init[TAG_RESPONSE_COUNT] = {
+ { .response = rATQA, .response_n = sizeof(rATQA) }, // Answer to request - respond with card type
+ { .response = rUIDBCC1, .response_n = sizeof(rUIDBCC1) }, // Anticollision cascade1 - respond with first part of uid
+ { .response = rUIDBCC2, .response_n = sizeof(rUIDBCC2) }, // Anticollision cascade2 - respond with 2nd part of uid
+ { .response = rUIDBCC3, .response_n = sizeof(rUIDBCC3) }, // Anticollision cascade3 - respond with 3th part of uid
+ { .response = rSAK_mini, .response_n = sizeof(rSAK_mini) }, //
+ { .response = rSAK_1, .response_n = sizeof(rSAK_1) }, //
+ { .response = rSAK_2, .response_n = sizeof(rSAK_2) }, //
+ { .response = rSAK_4, .response_n = sizeof(rSAK_4) }, //
+ { .response = rSAK1, .response_n = sizeof(rSAK1) } // Acknowledge select - New another cascades
+ };
+
+ // Prepare ("precompile") the responses of the anticollision phase. There will be not enough time to do this at the moment the reader sends its REQA or SELECT
+ // There are 7 predefined responses with a total of 18 bytes data to transmit. Coded responses need one byte per bit to transfer (data, parity, start, stop, correction)
+ // 18 * 8 data bits, 18 * 1 parity bits, 5 start bits, 5 stop bits, 5 correction bits -> need 177 bytes buffer
+
+ uint8_t *free_buffer_pointer = BigBuf_malloc(ALLOCATED_TAG_MODULATION_BUFFER_SIZE);
+ size_t free_buffer_size = ALLOCATED_TAG_MODULATION_BUFFER_SIZE;
+
+ for (size_t i = 0; i < TAG_RESPONSE_COUNT; i++) {
+ prepare_allocated_tag_modulation(&responses_init[i], &free_buffer_pointer, &free_buffer_size);
+ }
+
+ *responses = responses_init;
+
+ // indices into responses array:
+#define ATQA 0
+#define UIDBCC1 1
+#define UIDBCC2 2
+#define UIDBCC3 3
+#define SAK_MINI 4
+#define SAK_1 5
+#define SAK_2 6
+#define SAK_4 7
+#define SAK1 8
+
+}
+
+static bool HasValidCRC(uint8_t *receivedCmd, uint16_t receivedCmd_len) {
+ uint8_t CRC_byte_1, CRC_byte_2;
+ compute_crc(CRC_14443_A, receivedCmd, receivedCmd_len - 2, &CRC_byte_1, &CRC_byte_2);
+ return (receivedCmd[receivedCmd_len - 2] == CRC_byte_1 && receivedCmd[receivedCmd_len - 1] == CRC_byte_2);
+}
+
+
+/**
+*MIFARE 1K simulate.
+*
+*@param flags :
+* FLAG_INTERACTIVE - In interactive mode, we are expected to finish the operation with an ACK
+* FLAG_4B_UID_IN_DATA - means that there is a 4-byte UID in the data-section, we're expected to use that
+* FLAG_7B_UID_IN_DATA - means that there is a 7-byte UID in the data-section, we're expected to use that
+* FLAG_10B_UID_IN_DATA - use 10-byte UID in the data-section not finished
+* FLAG_NR_AR_ATTACK - means we should collect NR_AR responses for bruteforcing later
+*@param exitAfterNReads, exit simulation after n blocks have been read, 0 is infinite ...
+* (unless reader attack mode enabled then it runs util it gets enough nonces to recover all keys attmpted)
+*/
+void Mifare1ksim(uint16_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t *datain) {
+ tag_response_info_t *responses;
+ uint8_t cardSTATE = MFEMUL_NOFIELD;
+ uint8_t uid_len = 0; // 4,7, 10
+ uint32_t cuid = 0;
+
+ int vHf = 0; // in mV
+
+ uint32_t selTimer = 0;
+ uint32_t authTimer = 0;
+
+ uint8_t blockNo;
+
+ uint32_t nr;
+ uint32_t ar;
+
+ bool encrypted_data;
+
+ uint8_t cardWRBL = 0;
+ uint8_t cardAUTHSC = 0;
+ uint8_t cardAUTHKEY = AUTHKEYNONE; // no authentication
+ uint32_t cardRr = 0;
+ uint32_t ans = 0;
+
+ uint32_t cardINTREG = 0;
+ uint8_t cardINTBLOCK = 0;
+ struct Crypto1State mpcs = {0, 0};
+ struct Crypto1State *pcs;
+ pcs = &mpcs;
+
+ uint32_t numReads = 0; //Counts numer of times reader reads a block
+ uint8_t receivedCmd[MAX_MIFARE_FRAME_SIZE] = {0x00};
+ uint8_t receivedCmd_dec[MAX_MIFARE_FRAME_SIZE] = {0x00};
+ uint8_t receivedCmd_par[MAX_MIFARE_PARITY_SIZE] = {0x00};
+ uint16_t receivedCmd_len;
+
+ uint8_t response[MAX_MIFARE_FRAME_SIZE] = {0x00};
+ uint8_t response_par[MAX_MIFARE_PARITY_SIZE] = {0x00};
+
+ uint8_t rAUTH_AT[] = {0x00, 0x00, 0x00, 0x00};
+
+ //Here, we collect UID,sector,keytype,NT,AR,NR,NT2,AR2,NR2
+ // This will be used in the reader-only attack.
+
+ //allow collecting up to 7 sets of nonces to allow recovery of up to 7 keys
+#define ATTACK_KEY_COUNT 7 // keep same as define in cmdhfmf.c -> readerAttack() (Cannot be more than 7)
+ nonces_t ar_nr_resp[ATTACK_KEY_COUNT * 2]; //*2 for 2 separate attack types (nml, moebius) 36 * 7 * 2 bytes = 504 bytes
+ memset(ar_nr_resp, 0x00, sizeof(ar_nr_resp));
+
+ uint8_t ar_nr_collected[ATTACK_KEY_COUNT * 2]; //*2 for 2nd attack type (moebius)
+ memset(ar_nr_collected, 0x00, sizeof(ar_nr_collected));
+ uint8_t nonce1_count = 0;
+ uint8_t nonce2_count = 0;
+ uint8_t moebius_n_count = 0;
+ bool gettingMoebius = false;
+ uint8_t mM = 0; //moebius_modifier for collection storage
+
+ // Authenticate response - nonce
+ uint32_t nonce = 0;
+ // = prng_successor(selTimer, 32) ;
+
+ if ((flags & FLAG_MF_MINI) == FLAG_MF_MINI) {
+ MifareCardType = 0;
+ Dbprintf("Mifare Mini");
+ }
+ if ((flags & FLAG_MF_1K) == FLAG_MF_1K) {
+ MifareCardType = 1;
+ Dbprintf("Mifare 1K");
+ }
+ if ((flags & FLAG_MF_2K) == FLAG_MF_2K) {
+ MifareCardType = 2;
+ Dbprintf("Mifare 2K");
+ }
+ if ((flags & FLAG_MF_4K) == FLAG_MF_4K) {
+ MifareCardType = 4;
+ Dbprintf("Mifare 4K");
+ }
+
+ MifareSimInit(flags, datain, &responses, &cuid, &uid_len);
+
+ // We need to listen to the high-frequency, peak-detected path.
+ iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN);
+
+ // free eventually allocated BigBuf memory but keep Emulator Memory
+ BigBuf_free_keep_EM();
+ // clear trace
+ clear_trace();
+ set_tracing(true);
+ LED_D_ON();
+ ResetSspClk();
+
+ bool finished = false;
+ bool button_pushed = BUTTON_PRESS();
+
+ while (!button_pushed && !finished && !usb_poll_validate_length()) {
+ WDT_HIT();
+
+ // find reader field
+ if (cardSTATE == MFEMUL_NOFIELD) {
+ vHf = (MAX_ADC_HF_VOLTAGE_RDV40 * AvgAdc(ADC_CHAN_HF)) >> 10;
+ if (vHf > MF_MINFIELDV) {
+ cardSTATE_TO_IDLE();
+ LED_A_ON();
+ }
+ button_pushed = BUTTON_PRESS();
+ continue;
+ }
+
+ //Now, get data
+ int res = EmGetCmd(receivedCmd, &receivedCmd_len, receivedCmd_par);
+
+ if (res == 2) { //Field is off!
+ LEDsoff();
+ cardSTATE = MFEMUL_NOFIELD;
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("cardSTATE = MFEMUL_NOFIELD");
+ continue;
+ } else if (res == 1) { // button pressed
+ button_pushed = true;
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Button pressed");
+ break;
+ }
+
+ // WUPA in HALTED state or REQA or WUPA in any other state
+ if (receivedCmd_len == 1 && ((receivedCmd[0] == ISO14443A_CMD_REQA && cardSTATE != MFEMUL_HALTED) || receivedCmd[0] == ISO14443A_CMD_WUPA)) {
+ selTimer = GetTickCount();
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("EmSendPrecompiledCmd(&responses[ATQA]);");
+ EmSendPrecompiledCmd(&responses[ATQA]);
+
+ // init crypto block
+ crypto1_destroy(pcs);
+ cardAUTHKEY = AUTHKEYNONE;
+ nonce = prng_successor(selTimer, 32);
+
+ LED_B_OFF();
+ LED_C_OFF();
+ cardSTATE = MFEMUL_SELECT1;
+ continue;
+ }
+
+ switch (cardSTATE) {
+ case MFEMUL_NOFIELD:
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("MFEMUL_NOFIELD");
+ case MFEMUL_HALTED:
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("MFEMUL_HALTED");
+ case MFEMUL_IDLE: {
+ LogTrace(Uart.output, Uart.len, Uart.startTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true);
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("MFEMUL_IDLE");
+ break;
+ }
+
+ // The anti-collision sequence, which is a mandatory part of the card activation sequence.
+ // It auto with 4-byte UID (= Single Size UID),
+ // 7 -byte UID (= Double Size UID) or 10-byte UID (= Triple Size UID).
+
+ // Cascade Level 1
+ //
+ // In the Cascade Level 1, the card send the anti-collision command CL1 (0x93) and the PICC returns
+ // either the 4-byte UID (UID0...UID4) and one-byte BCC
+ // or a Cascade Tag (CT) followed by the first 3 byte of the UID (UID0...UID2) and onebyte BCC.
+ //
+ // The CT (0x88) indicates that the UID is not yet complete, and another Cascade Level is needed
+ //
+ // The UID0 byte of a 4-byte UID must not be 0x88.
+ // The CL1 then must be selected, using the Select command CL1 (0x93). The PICC returns its SAK CL1, which indicates
+ // whether the UID is complete or not, and (if so),
+ // the type of card and whether the card supports T=CL.
+
+ case MFEMUL_SELECT1: {
+ // select all - 0x93 0x20 (Anti Collision CL1)
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("cardSTATE = MFEMUL_SELECT1 - receivedCmd_len: %d - receivedCmd[0]: %02x - receivedCmd[1]: %02x", receivedCmd_len, receivedCmd[0], receivedCmd[1]);
+ if (receivedCmd_len == 2 && (receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT && receivedCmd[1] == 0x20)) {
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("SELECT ALL CL1 received - EmSendPrecompiledCmd(%02x)", &responses[UIDBCC1]);
+ EmSendPrecompiledCmd(&responses[UIDBCC1]);
+ break;
+ }
+
+ // select card - 0x93 0x70 (Select CL1)
+ if (receivedCmd_len == 9 &&
+ (receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT &&
+ receivedCmd[1] == 0x70 &&
+ memcmp(&receivedCmd[2], responses[UIDBCC1].response, 4) == 0)) {
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("SELECT CL1 %02x%02x%02x%02x received", receivedCmd[2], receivedCmd[3], receivedCmd[4], receivedCmd[5]);
+
+ // Send SAK according UID len
+ switch (uid_len) {
+ case 4:
+ switch (MifareCardType) {
+ case 0:
+ EmSendPrecompiledCmd(&responses[SAK_MINI]);
+ break;
+ case 1:
+ EmSendPrecompiledCmd(&responses[SAK_1]);
+ break;
+ case 2:
+ EmSendPrecompiledCmd(&responses[SAK_2]);
+ break;
+ case 4:
+ EmSendPrecompiledCmd(&responses[SAK_4]);
+ break;
+ }
+
+ LED_B_ON();
+ cardSTATE = MFEMUL_WORK;
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_SELECT1] cardSTATE = MFEMUL_WORK");
+ break;
+ case 7:
+ // SAK => Need another select round
+ EmSendPrecompiledCmd(&responses[SAK1]);
+ cardSTATE = MFEMUL_SELECT2;
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_SELECT1] cardSTATE = MFEMUL_SELECT2");
+ break;
+ case 10:
+ // SAK => Need another select round
+ EmSendPrecompiledCmd(&responses[SAK1]);
+ cardSTATE = MFEMUL_SELECT2;
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_SELECT1] cardSTATE = MFEMUL_SELECT2");
+ break;
+ default:
+ break;
+ } // End Switch (uid_len)
+
+ } else {
+ // IDLE
+ cardSTATE_TO_IDLE();
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_SELECT1] cardSTATE = MFEMUL_IDLE");
+ }
+ // Break Case MFEMUL_SELECT1
+ break;
+ }
+
+
+ // Cascade Level 2
+ //
+ // If the UID is not yet complete, the PCD continues with an anti-collision CL2 command (0x95),
+ // and the PICC returns
+ // • either the last 4 bytes of the Double Size UID (UID3...UID6) and one-byte BCC,
+ // • or a Cascade Tag (CT) followed by the next 3 bytes of the Triple Size UID (UID3...UID5) and one-byte BCC.
+ // The CT (0x88) indicates that the UID is not yet complete, and another Cascade Level has to follow.
+ //
+ // The UID3 byte of a 7 byte or 10-byte UID must not be 0x88
+ // The CL2 then must be selected, using the Select command CL2 (0x95).
+ // The PICC returns its SAK CL2, which indicates
+ // whether the UID is complete or not, and (if so),
+ // the type of card and whether the card supports T=CL.
+
+ // select all cl2 - 0x95 0x20
+
+ case MFEMUL_SELECT2: {
+ if (receivedCmd_len == 2 &&
+ (receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2 && receivedCmd[1] == 0x20)) {
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_SELECT2] SELECT ALL CL2 received");
+ EmSendPrecompiledCmd(&responses[UIDBCC2]);
+ break;
+ }
+
+ // select cl2 card - 0x95 0x70 xxxxxxxxxxxx
+ if (receivedCmd_len == 9 &&
+ (receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2 &&
+ receivedCmd[1] == 0x70 &&
+ memcmp(&receivedCmd[2], responses[UIDBCC2].response, 4) == 0)) {
+
+ switch (uid_len) {
+ case 7:
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_SELECT2] SELECT CL2 %02x%02x%02x%02x received", receivedCmd[2], receivedCmd[3], receivedCmd[4], receivedCmd[5]);
+
+ switch (MifareCardType) {
+ case 0:
+ EmSendPrecompiledCmd(&responses[SAK_MINI]);
+ break;
+ case 1:
+ EmSendPrecompiledCmd(&responses[SAK_1]);
+ break;
+ case 2:
+ EmSendPrecompiledCmd(&responses[SAK_2]);
+ break;
+ case 4:
+ EmSendPrecompiledCmd(&responses[SAK_4]);
+ break;
+ }
+ cardSTATE = MFEMUL_WORK;
+ LED_B_ON();
+ break;
+ case 10:
+ // SAK => Need another select round
+ EmSendPrecompiledCmd(&responses[SAK1]);
+ cardSTATE = MFEMUL_SELECT3;
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_SELECT2] cardSTATE = MFEMUL_SELECT3");
+ default:
+ break;
+ }
+
+ } else {
+ // IDLE
+ cardSTATE_TO_IDLE();
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_SELECT2] cardSTATE = MFEMUL_IDLE");
+ }
+ // Break Case MFEMUL_SELECT2
+ break;
+ }
+
+
+ // Cascade Level 3
+ // Select command CL3 (0x97)
+ //
+ // If the UID is not yet complete, the PCD continues with an anti-collision CL3 command (0x97)
+ // and the PICC returns the last 4 bytes of the Triple Size UID (UID6...UID9) and one-byte BCC.
+ // The PICC returns its SAK CL3, which indicates the type of card and whether the card supports T=CL
+
+ case MFEMUL_SELECT3: {
+ if (!uid_len) {
+ LogTrace(Uart.output, Uart.len, Uart.startTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true);
+ break;
+ }
+ if (receivedCmd_len == 2 && (receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_3 && receivedCmd[1] == 0x20)) {
+ EmSendPrecompiledCmd(&responses[UIDBCC3]);
+ break;
+ }
+ if (receivedCmd_len == 9 &&
+ (receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_3 &&
+ receivedCmd[1] == 0x70 &&
+ memcmp(&receivedCmd[2], responses[UIDBCC3].response, 4) == 0)) {
+
+ switch (MifareCardType) {
+ case 0:
+ EmSendPrecompiledCmd(&responses[SAK_MINI]);
+ break;
+ case 1:
+ EmSendPrecompiledCmd(&responses[SAK_1]);
+ break;
+ case 2:
+ EmSendPrecompiledCmd(&responses[SAK_2]);
+ break;
+ case 4:
+ EmSendPrecompiledCmd(&responses[SAK_4]);
+ break;
+ }
+
+ cardSTATE = MFEMUL_WORK;
+ LED_B_ON();
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) {
+ Dbprintf("[MFEMUL_SELECT3] --> WORK. anticol3 time: %d", GetTickCount() - selTimer);
+ Dbprintf("[MFEMUL_SELECT3] cardSTATE = MFEMUL_WORK");
+ }
+ continue;
+ } else {
+ // IDLE
+ cardSTATE_TO_IDLE();
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_SELECT3] cardSTATE = MFEMUL_IDLE");
+ }
+ // Break Case MFEMUL_SELECT3
+ break;
+ }
+
+ // WORK
+ case MFEMUL_WORK: {
+
+ if (MF_DBGLEVEL >= 1) Dbprintf("[MFEMUL_WORK] Enter in case");
+
+ if (receivedCmd_len != 4) {
+ LogTrace(Uart.output, Uart.len, Uart.startTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true);
+ mf_crypto1_decryptEx(pcs, receivedCmd, receivedCmd_len, receivedCmd_dec);
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] All commands must have exactly 4 bytes: receivedCmd_len=%d - Cmd: %02X", receivedCmd_len, receivedCmd_dec);
+ break;
+ }
+
+ if (receivedCmd_len == 0) {
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] NO CMD received");
+ break;
+ }
+
+ encrypted_data = (cardAUTHKEY != AUTHKEYNONE);
+ if (encrypted_data) {
+ // decrypt seqence
+ mf_crypto1_decryptEx(pcs, receivedCmd, receivedCmd_len, receivedCmd_dec);
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] Decrypt seqence");
+ } else {
+ // Data in clear
+ memcpy(receivedCmd_dec, receivedCmd, receivedCmd_len);
+ }
+
+ if (!HasValidCRC(receivedCmd_dec, receivedCmd_len)) { // all commands must have a valid CRC
+ EmSend4bit(encrypted_data ? mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA) : CARD_NACK_NA);
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] All commands must have a valid CRC %02X (%d)", receivedCmd_dec, receivedCmd_len);
+ break;
+ }
+
+ if (receivedCmd_len == 4 && (receivedCmd_dec[0] == MIFARE_AUTH_KEYA || receivedCmd_dec[0] == MIFARE_AUTH_KEYB)) {
+
+ // Reader asks for AUTH: 6X XX
+ // RCV: 60 XX => Using KEY A
+ // RCV: 61 XX => Using KEY B
+ // XX: Block number
+
+ // if authenticating to a block that shouldn't exist - as long as we are not doing the reader attack
+ if (receivedCmd_dec[1] > MIFARE_4K_MAXBLOCK && !((flags & FLAG_NR_AR_ATTACK) == FLAG_NR_AR_ATTACK)) {
+ EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Reader tried to operate (0x%02x) on out of range block: %d (0x%02x), nacking", receivedCmd_dec[0], receivedCmd_dec[1], receivedCmd_dec[1]);
+ break;
+ }
+
+ authTimer = GetTickCount();
+
+ // received block num -> sector
+ // Example: 6X [00]
+ cardAUTHSC = receivedCmd_dec[1] / 4;
+
+ // cardAUTHKEY: 60 => Auth use Key A
+ // cardAUTHKEY: 61 => Auth use Key B
+ cardAUTHKEY = receivedCmd_dec[0] & 0x01;
+
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] KEY %c: %012" PRIx64, (cardAUTHKEY == 0) ? 'A' : 'B', emlGetKey(cardAUTHSC, cardAUTHKEY));
+
+ // first authentication
+ crypto1_destroy(pcs);
+
+ // Load key into crypto
+ crypto1_create(pcs, emlGetKey(cardAUTHSC, cardAUTHKEY));
+
+ if (!encrypted_data) {
+ // Receive Cmd in clear txt
+ // Update crypto state (UID ^ NONCE)
+ crypto1_word(pcs, cuid ^ nonce, 0);
+ // prepare nonce
+ num_to_bytes(nonce, 4, rAUTH_AT);
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] Reader authenticating for block %d (0x%02x) with key %c - nonce: %02X - ciud: %02X", receivedCmd_dec[1], receivedCmd_dec[1], (cardAUTHKEY == 0) ? 'A' : 'B', rAUTH_AT, cuid);
+ } else {
+ // nested authentication
+ ans = nonce ^ crypto1_word(pcs, cuid ^ nonce, 0);
+ num_to_bytes(ans, 4, rAUTH_AT);
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] Reader doing nested authentication for block %d (0x%02x) with key %c", receivedCmd_dec[1], receivedCmd_dec[1], (cardAUTHKEY == 0) ? 'A' : 'B');
+ }
+
+
+ EmSendCmd(rAUTH_AT, sizeof(rAUTH_AT));
+ cardSTATE = MFEMUL_AUTH1;
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] cardSTATE = MFEMUL_AUTH1 - rAUTH_AT: %02X", rAUTH_AT);
+ continue;
+ }
+
+ // rule 13 of 7.5.3. in ISO 14443-4. chaining shall be continued
+ // BUT... ACK --> NACK
+ if (receivedCmd_len == 1 && receivedCmd_dec[0] == CARD_ACK) {
+ EmSend4bit(encrypted_data ? mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA) : CARD_NACK_NA);
+ break;
+ }
+
+ // rule 12 of 7.5.3. in ISO 14443-4. R(NAK) --> R(ACK)
+ if (receivedCmd_len == 1 && receivedCmd_dec[0] == CARD_NACK_NA) {
+ EmSend4bit(encrypted_data ? mf_crypto1_encrypt4bit(pcs, CARD_ACK) : CARD_ACK);
+ break;
+ }
+
+ //if (!encrypted_data) { // all other commands must be encrypted (authenticated)
+ // if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Commands must be encrypted (authenticated)");
+ // break;
+ //}
+
+ // case MFEMUL_WORK => if Cmd is Read, Write, Inc, Dec, Restore, Transfert
+ if (receivedCmd_dec[0] == ISO14443A_CMD_READBLOCK
+ || receivedCmd_dec[0] == ISO14443A_CMD_WRITEBLOCK
+ || receivedCmd_dec[0] == MIFARE_CMD_INC
+ || receivedCmd_dec[0] == MIFARE_CMD_DEC
+ || receivedCmd_dec[0] == MIFARE_CMD_RESTORE
+ || receivedCmd_dec[0] == MIFARE_CMD_TRANSFER) {
+ // Check if Block num is not too far
+ if (receivedCmd_dec[1] > MIFARE_4K_MAXBLOCK) {
+ EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
+ if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("[MFEMUL_WORK] Reader tried to operate (0x%02x) on out of range block: %d (0x%02x), nacking", receivedCmd_dec[0], receivedCmd_dec[1], receivedCmd_dec[1]);
+ break;
+ }
+ if (receivedCmd_dec[1] / 4 != cardAUTHSC) {
+ EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
+ if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("[MFEMUL_WORK] Reader tried to operate (0x%02x) on block (0x%02x) not authenticated for (0x%02x), nacking", receivedCmd_dec[0], receivedCmd_dec[1], cardAUTHSC);
+ break;
+ }
+ }
+
+ // case MFEMUL_WORK => CMD READ block
+ if (receivedCmd_dec[0] == ISO14443A_CMD_READBLOCK) {
+ blockNo = receivedCmd_dec[1];
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] Reader reading block %d (0x%02x)", blockNo, blockNo);
+ emlGetMem(response, blockNo, 1);
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) {
+ Dbprintf("[MFEMUL_WORK - ISO14443A_CMD_READBLOCK] Data Block[%d]: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", blockNo,
+ response[0], response[1], response[2], response[3], response[4], response[5], response[6],
+ response[7], response[8], response[9], response[10], response[11], response[12], response[13],
+ response[14], response[15]);
+ }
+
+ // Access permission managment:
+ //
+ // Sector Trailer:
+ // - KEY A access
+ // - KEY B access
+ // - AC bits access
+ //
+ // Data block:
+ // - Data access
+
+ // If permission is not allowed, data is cleared (00) in emulator memeory.
+ // ex: a0a1a2a3a4a561e789c1b0b1b2b3b4b5 => 00000000000061e789c1b0b1b2b3b4b5
+
+
+ // Check if selected Block is a Sector Trailer
+ if (IsSectorTrailer(blockNo)) {
+
+ if (!IsAccessAllowed(blockNo, cardAUTHKEY, AC_KEYA_READ)) {
+ memset(response, 0x00, 6); // keyA can never be read
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_WORK - IsSectorTrailer] keyA can never be read - block %d (0x%02x)", blockNo, blockNo);
+ }
+ if (!IsAccessAllowed(blockNo, cardAUTHKEY, AC_KEYB_READ)) {
+ memset(response + 10, 0x00, 6); // keyB cannot be read
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_WORK - IsSectorTrailer] keyB cannot be read - block %d (0x%02x)", blockNo, blockNo);
+ }
+ if (!IsAccessAllowed(blockNo, cardAUTHKEY, AC_AC_READ)) {
+ memset(response + 6, 0x00, 4); // AC bits cannot be read
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_WORK - IsAccessAllowed] AC bits cannot be read - block %d (0x%02x)", blockNo, blockNo);
+ }
+ } else {
+ if (!IsAccessAllowed(blockNo, cardAUTHKEY, AC_DATA_READ)) {
+ memset(response, 0x00, 16); // datablock cannot be read
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_WORK - IsAccessAllowed] Data block %d (0x%02x) cannot be read", blockNo, blockNo);
+ }
+ }
+ AppendCrc14443a(response, 16);
+ mf_crypto1_encrypt(pcs, response, MAX_MIFARE_FRAME_SIZE, response_par);
+ EmSendCmdPar(response, MAX_MIFARE_FRAME_SIZE, response_par);
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) {
+ Dbprintf("[MFEMUL_WORK - EmSendCmdPar] Data Block[%d]: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", blockNo,
+ response[0], response[1], response[2], response[3], response[4], response[5], response[6],
+ response[7], response[8], response[9], response[10], response[11], response[12], response[13],
+ response[14], response[15]);
+ }
+ numReads++;
+
+ if (exitAfterNReads > 0 && numReads == exitAfterNReads) {
+ Dbprintf("[MFEMUL_WORK] %d reads done, exiting", numReads);
+ finished = true;
+ }
+ break;
+
+ } // End receivedCmd_dec[0] == ISO14443A_CMD_READBLOCK
+
+ // case MFEMUL_WORK => CMD WRITEBLOCK
+ if (receivedCmd_dec[0] == ISO14443A_CMD_WRITEBLOCK) {
+ blockNo = receivedCmd_dec[1];
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] RECV 0xA0 write block %d (%02x)", blockNo, blockNo);
+ EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
+ cardWRBL = blockNo;
+ cardSTATE = MFEMUL_WRITEBL2;
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] cardSTATE = MFEMUL_WRITEBL2");
+ break;
+ }
+
+ // case MFEMUL_WORK => CMD INC/DEC/REST
+ if (receivedCmd_dec[0] == MIFARE_CMD_INC || receivedCmd_dec[0] == MIFARE_CMD_DEC || receivedCmd_dec[0] == MIFARE_CMD_RESTORE) {
+ blockNo = receivedCmd_dec[1];
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] RECV 0x%02x inc(0xC1)/dec(0xC0)/restore(0xC2) block %d (%02x)", receivedCmd_dec[0], blockNo, blockNo);
+ if (emlCheckValBl(blockNo)) {
+ if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("[MFEMUL_WORK] Reader tried to operate on block, but emlCheckValBl failed, nacking");
+ EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
+ break;
+ }
+ EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
+ cardWRBL = blockNo;
+
+ // INC
+ if (receivedCmd_dec[0] == MIFARE_CMD_INC) {
+ cardSTATE = MFEMUL_INTREG_INC;
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] cardSTATE = MFEMUL_INTREG_INC");
+ }
+
+ // DEC
+ if (receivedCmd_dec[0] == MIFARE_CMD_DEC) {
+ cardSTATE = MFEMUL_INTREG_DEC;
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] cardSTATE = MFEMUL_INTREG_DEC");
+ }
+
+ // REST
+ if (receivedCmd_dec[0] == MIFARE_CMD_RESTORE) {
+ cardSTATE = MFEMUL_INTREG_REST;
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] cardSTATE = MFEMUL_INTREG_REST");
+ }
+ break;
+
+ } // End case MFEMUL_WORK => CMD INC/DEC/REST
+
+
+ // case MFEMUL_WORK => CMD TRANSFER
+ if (receivedCmd_dec[0] == MIFARE_CMD_TRANSFER) {
+ blockNo = receivedCmd_dec[1];
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] RECV 0x%02x transfer block %d (%02x)", receivedCmd_dec[0], blockNo, blockNo);
+ if (emlSetValBl(cardINTREG, cardINTBLOCK, receivedCmd_dec[1]))
+ EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
+ else
+ EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
+ break;
+ }
+
+ // case MFEMUL_WORK => CMD HALT
+ if (receivedCmd_dec[0] == ISO14443A_CMD_HALT && receivedCmd[1] == 0x00) {
+ LogTrace(Uart.output, Uart.len, Uart.startTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true);
+ LED_B_OFF();
+ LED_C_OFF();
+ cardSTATE = MFEMUL_HALTED;
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] cardSTATE = MFEMUL_HALTED");
+ break;
+ }
+
+ // case MFEMUL_WORK => CMD RATS
+ if (receivedCmd[0] == ISO14443A_CMD_RATS) {
+ EmSend4bit(encrypted_data ? mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA) : CARD_NACK_NA);
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] RCV RATS => NACK");
+ break;
+ }
+
+ // case MFEMUL_WORK => command not allowed
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Received command not allowed, nacking");
+ EmSend4bit(encrypted_data ? mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA) : CARD_NACK_NA);
+ break;
+ }
+
+ // AUTH1
+ case MFEMUL_AUTH1: {
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_AUTH1] Enter case");
+
+ if (receivedCmd_len != 4) {
+ cardSTATE_TO_IDLE();
+ LogTrace(Uart.output, Uart.len, Uart.startTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true);
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("MFEMUL_AUTH1: receivedCmd_len != 8 (%d) => cardSTATE_TO_IDLE())", receivedCmd_len);
+ break;
+ }
+
+ nr = bytes_to_num(receivedCmd, 4);
+ ar = bytes_to_num(&receivedCmd[4], 4);
+
+ // Collect AR/NR per keytype & sector
+ if ((flags & FLAG_NR_AR_ATTACK) == FLAG_NR_AR_ATTACK) {
+ if (MF_DBGLEVEL >= 0) Dbprintf("FLAG_NR_AR_ATTACK");
+ for (uint8_t i = 0; i < ATTACK_KEY_COUNT; i++) {
+ if (ar_nr_collected[i + mM] == 0 || ((cardAUTHSC == ar_nr_resp[i + mM].sector) && (cardAUTHKEY == ar_nr_resp[i + mM].keytype) && (ar_nr_collected[i + mM] > 0))) {
+ // if first auth for sector, or matches sector and keytype of previous auth
+ if (ar_nr_collected[i + mM] < 2) {
+ // if we haven't already collected 2 nonces for this sector
+ if (ar_nr_resp[ar_nr_collected[i + mM]].ar != ar) {
+ // Avoid duplicates... probably not necessary, ar should vary.
+ if (ar_nr_collected[i + mM] == 0) {
+ // first nonce collect
+ ar_nr_resp[i + mM].cuid = cuid;
+ ar_nr_resp[i + mM].sector = cardAUTHSC;
+ ar_nr_resp[i + mM].keytype = cardAUTHKEY;
+ ar_nr_resp[i + mM].nonce = nonce;
+ ar_nr_resp[i + mM].nr = nr;
+ ar_nr_resp[i + mM].ar = ar;
+ nonce1_count++;
+ // add this nonce to first moebius nonce
+ ar_nr_resp[i + ATTACK_KEY_COUNT].cuid = cuid;
+ ar_nr_resp[i + ATTACK_KEY_COUNT].sector = cardAUTHSC;
+ ar_nr_resp[i + ATTACK_KEY_COUNT].keytype = cardAUTHKEY;
+ ar_nr_resp[i + ATTACK_KEY_COUNT].nonce = nonce;
+ ar_nr_resp[i + ATTACK_KEY_COUNT].nr = nr;
+ ar_nr_resp[i + ATTACK_KEY_COUNT].ar = ar;
+ ar_nr_collected[i + ATTACK_KEY_COUNT]++;
+ } else { // second nonce collect (std and moebius)
+ ar_nr_resp[i + mM].nonce2 = nonce;
+ ar_nr_resp[i + mM].nr2 = nr;
+ ar_nr_resp[i + mM].ar2 = ar;
+ if (!gettingMoebius) {
+ nonce2_count++;
+ // check if this was the last second nonce we need for std attack
+ if (nonce2_count == nonce1_count) {
+ // done collecting std test switch to moebius
+ // first finish incrementing last sample
+ ar_nr_collected[i + mM]++;
+ // switch to moebius collection
+ gettingMoebius = true;
+ mM = ATTACK_KEY_COUNT;
+ nonce = nonce * 7;
+ break;
+ }
+ } else {
+ moebius_n_count++;
+ // if we've collected all the nonces we need - finish.
+ if (nonce1_count == moebius_n_count) finished = true;
+ }
+ }
+ ar_nr_collected[i + mM]++;
+ }
+ }
+ // we found right spot for this nonce stop looking
+ break;
+ }
+ }
+ }
+
+ // --- crypto
+ crypto1_word(pcs, nr, 1);
+ cardRr = ar ^ crypto1_word(pcs, 0, 0);
+
+ // test if auth KO
+ if (cardRr != prng_successor(nonce, 64)) {
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) {
+ Dbprintf("[MFEMUL_AUTH1] AUTH FAILED for sector %d with key %c. [nr=%08x cardRr=%08x] [nt=%08x succ=%08x]"
+ , cardAUTHSC
+ , (cardAUTHKEY == 0) ? 'A' : 'B'
+ , nr
+ , cardRr
+ , nonce // nt
+ , prng_successor(nonce, 64)
+ );
+ }
+ cardAUTHKEY = AUTHKEYNONE; // not authenticated
+ // LogTrace(Uart.output, Uart.len, Uart.startTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true);
+ EmSend4bit(CARD_NACK_NA);
+ cardSTATE_TO_IDLE();
+ break;
+ }
+
+ ans = prng_successor(nonce, 96);
+ num_to_bytes(ans, 4, rAUTH_AT);
+ mf_crypto1_encrypt(pcs, rAUTH_AT, 4, response_par);
+ EmSendCmdPar(rAUTH_AT, 4, response_par);
+
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) {
+ Dbprintf("[MFEMUL_AUTH1] AUTH COMPLETED for sector %d with key %c. time=%d",
+ cardAUTHSC,
+ cardAUTHKEY == 0 ? 'A' : 'B',
+ GetTickCount() - authTimer
+ );
+ }
+ LED_C_ON();
+ cardSTATE = MFEMUL_WORK;
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_AUTH1] cardSTATE = MFEMUL_WORK");
+ break;
+ }
+
+ // WRITE BL2
+ case MFEMUL_WRITEBL2: {
+ if (receivedCmd_len == MAX_MIFARE_FRAME_SIZE) {
+ mf_crypto1_decryptEx(pcs, receivedCmd, receivedCmd_len, receivedCmd_dec);
+ if (HasValidCRC(receivedCmd_dec, receivedCmd_len)) {
+ if (IsSectorTrailer(cardWRBL)) {
+ emlGetMem(response, cardWRBL, 1);
+ if (!IsAccessAllowed(cardWRBL, cardAUTHKEY, AC_KEYA_WRITE)) {
+ memcpy(receivedCmd_dec, response, 6); // don't change KeyA
+ }
+ if (!IsAccessAllowed(cardWRBL, cardAUTHKEY, AC_KEYB_WRITE)) {
+ memcpy(receivedCmd_dec + 10, response + 10, 6); // don't change KeyA
+ }
+ if (!IsAccessAllowed(cardWRBL, cardAUTHKEY, AC_AC_WRITE)) {
+ memcpy(receivedCmd_dec + 6, response + 6, 4); // don't change AC bits
+ }
+ } else {
+ if (!IsAccessAllowed(cardWRBL, cardAUTHKEY, AC_DATA_WRITE)) {
+ memcpy(receivedCmd_dec, response, 16); // don't change anything
+ }
+ }
+ emlSetMem(receivedCmd_dec, cardWRBL, 1);
+ EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK)); // always ACK?
+ cardSTATE = MFEMUL_WORK;
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_WRITEBL2] cardSTATE = MFEMUL_WORK");
+ break;
+ }
+ }
+ cardSTATE_TO_IDLE();
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_WRITEBL2] cardSTATE = MFEMUL_IDLE");
+ LogTrace(Uart.output, Uart.len, Uart.startTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true);
+ break;
+ }
+
+ // INC
+ case MFEMUL_INTREG_INC: {
+ if (receivedCmd_len == 6) {
+ mf_crypto1_decryptEx(pcs, receivedCmd, receivedCmd_len, (uint8_t *)&ans);
+ if (emlGetValBl(&cardINTREG, &cardINTBLOCK, cardWRBL)) {
+ EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
+ cardSTATE_TO_IDLE();
+ break;
+ }
+ LogTrace(Uart.output, Uart.len, Uart.startTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true);
+ cardINTREG = cardINTREG + ans;
+
+ cardSTATE = MFEMUL_WORK;
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_INTREG_INC] cardSTATE = MFEMUL_WORK");
+ break;
+ }
+ }
+
+ // DEC
+ case MFEMUL_INTREG_DEC: {
+ if (receivedCmd_len == 6) { // Data is encrypted
+ // Decrypted cmd
+ mf_crypto1_decryptEx(pcs, receivedCmd, receivedCmd_len, (uint8_t *)&ans);
+ if (emlGetValBl(&cardINTREG, &cardINTBLOCK, cardWRBL)) {
+ EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
+ cardSTATE_TO_IDLE();
+ break;
+ }
+ }
+ LogTrace(Uart.output, Uart.len, Uart.startTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true);
+ cardINTREG = cardINTREG - ans;
+ cardSTATE = MFEMUL_WORK;
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_INTREG_DEC] cardSTATE = MFEMUL_WORK");
+ break;
+ }
+
+ // REST
+ case MFEMUL_INTREG_REST: {
+ mf_crypto1_decryptEx(pcs, receivedCmd, receivedCmd_len, (uint8_t *)&ans);
+ if (emlGetValBl(&cardINTREG, &cardINTBLOCK, cardWRBL)) {
+ EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
+ cardSTATE_TO_IDLE();
+ break;
+ }
+ LogTrace(Uart.output, Uart.len, Uart.startTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime * 16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true);
+ cardSTATE = MFEMUL_WORK;
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("[MFEMUL_INTREG_REST] cardSTATE = MFEMUL_WORK");
+ break;
+ }
+
+ } // End Switch Loop
+
+ button_pushed = BUTTON_PRESS();
+
+ } // End While Loop
+
+
+ // NR AR ATTACK
+ if (((flags & FLAG_NR_AR_ATTACK) == FLAG_NR_AR_ATTACK) && (MF_DBGLEVEL >= 1)) {
+ for (uint8_t i = 0; i < ATTACK_KEY_COUNT; i++) {
+ if (ar_nr_collected[i] == 2) {
+ Dbprintf("Collected two pairs of AR/NR which can be used to extract %s from reader for sector %d:", (i < ATTACK_KEY_COUNT / 2) ? "keyA" : "keyB", ar_nr_resp[i].sector);
+ Dbprintf("../tools/mfkey/mfkey32 %08x %08x %08x %08x %08x %08x",
+ ar_nr_resp[i].cuid, //UID
+ ar_nr_resp[i].nonce, //NT
+ ar_nr_resp[i].nr, //NR1
+ ar_nr_resp[i].ar, //AR1
+ ar_nr_resp[i].nr2, //NR2
+ ar_nr_resp[i].ar2 //AR2
+ );
+ }
+ }
+ }
+
+ for (uint8_t i = ATTACK_KEY_COUNT; i < ATTACK_KEY_COUNT * 2; i++) {
+ if (ar_nr_collected[i] == 2) {
+ Dbprintf("Collected two pairs of AR/NR which can be used to extract %s from reader for sector %d:", (i < ATTACK_KEY_COUNT / 2) ? "keyA" : "keyB", ar_nr_resp[i].sector);
+ Dbprintf("../tools/mfkey/mfkey32v2 %08x %08x %08x %08x %08x %08x %08x",
+ ar_nr_resp[i].cuid, //UID
+ ar_nr_resp[i].nonce, //NT
+ ar_nr_resp[i].nr, //NR1
+ ar_nr_resp[i].ar, //AR1
+ ar_nr_resp[i].nonce2,//NT2
+ ar_nr_resp[i].nr2, //NR2
+ ar_nr_resp[i].ar2 //AR2
+ );
+ }
+ }
+
+ if (MF_DBGLEVEL >= 1) {
+ Dbprintf("Emulator stopped. Tracing: %d trace length: %d ", get_tracing(), BigBuf_get_traceLen());
+ }
+
+
+ if ((flags & FLAG_INTERACTIVE) == FLAG_INTERACTIVE) { // Interactive mode flag, means we need to send ACK
+ //Send the collected ar_nr in the response
+ cmd_send(CMD_ACK, CMD_SIMULATE_MIFARE_CARD, button_pushed, 0, &ar_nr_resp, sizeof(ar_nr_resp));
+ }
+
+ FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
+ LEDsoff();
+ set_tracing(false);
+
+}
diff --git a/armsrc/mifaresim.h b/armsrc/mifaresim.h
new file mode 100644
index 000000000..65eabdf68
--- /dev/null
+++ b/armsrc/mifaresim.h
@@ -0,0 +1,44 @@
+//-----------------------------------------------------------------------------
+// Merlok - June 2011, 2012
+// Gerhard de Koning Gans - May 2008
+// Hagen Fritsch - June 2010
+//
+// This code is licensed to you under the terms of the GNU GPL, version 2 or,
+// at your option, any later version. See the LICENSE.txt file for the text of
+// the license.
+//-----------------------------------------------------------------------------
+// Mifare Classic Card Simulation
+//-----------------------------------------------------------------------------
+
+#ifndef __MIFARESIM_H
+#define __MIFARESIM_H
+
+#include
+
+void Mifare1ksim(uint16_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t *datain);
+
+#define AC_DATA_READ 0
+#define AC_DATA_WRITE 1
+#define AC_DATA_INC 2
+#define AC_DATA_DEC_TRANS_REST 3
+#define AC_KEYA_READ 0
+#define AC_KEYA_WRITE 1
+#define AC_KEYB_READ 2
+#define AC_KEYB_WRITE 3
+#define AC_AC_READ 4
+#define AC_AC_WRITE 5
+
+#define AUTHKEYA 0
+#define AUTHKEYB 1
+#define AUTHKEYNONE 0xff
+
+#define TAG_RESPONSE_COUNT 9 // number of precompiled responses
+
+// Prepare ("precompile") the responses of the anticollision phase.
+// There will be not enough time to do this at the moment the reader sends its REQA or SELECT
+// There are 7 predefined responses with a total of 18 bytes data to transmit.
+// Coded responses need one byte per bit to transfer (data, parity, start, stop, correction)
+// 18 * 8 data bits, 18 * 1 parity bits, 5 start bits, 5 stop bits, 5 correction bits -> need 177 bytes buffer
+#define ALLOCATED_TAG_MODULATION_BUFFER_SIZE 512 // number of bytes required for precompiled response
+
+#endif
diff --git a/armsrc/mifareutil.c b/armsrc/mifareutil.c
index 4cb3bd9ea..233b143fe 100644
--- a/armsrc/mifareutil.c
+++ b/armsrc/mifareutil.c
@@ -596,7 +596,7 @@ void emlClearMem(void) {
memset(emCARD, 0, CARD_MEMORY_SIZE);
// fill sectors trailer data
- for (uint16_t b = 3; b < 256; ((b < 127) ? (b += 4) : (b += 16)))
+ for (uint16_t b = 3; b <= MIFARE_4K_MAXBLOCK; ((b <= MIFARE_2K_MAXBLOCK) ? (b += 4) : (b += 16)))
emlSetMem((uint8_t *)trailer, b, 1);
// uid
@@ -604,6 +604,19 @@ void emlClearMem(void) {
return;
}
+uint8_t SectorTrailer(uint8_t blockNo) {
+ if (blockNo <= MIFARE_2K_MAXBLOCK) {
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Sector Trailer for block %d : %d", blockNo, (blockNo | 0x03));
+ return (blockNo | 0x03);
+ } else {
+ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Sector Trailer for block %d : %d", blockNo, (blockNo | 0x0f));
+ return (blockNo | 0x0f);
+ }
+}
+
+bool IsSectorTrailer(uint8_t blockNo) {
+ return (blockNo == SectorTrailer(blockNo));
+}
// Mifare desfire commands
int mifare_sendcmd_special(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t *data, uint8_t *answer, uint8_t *answer_parity, uint32_t *timing) {
diff --git a/armsrc/mifareutil.h b/armsrc/mifareutil.h
index 62cc1bbff..570af2629 100644
--- a/armsrc/mifareutil.h
+++ b/armsrc/mifareutil.h
@@ -21,7 +21,6 @@
#include "iso14443a.h"
#include "crapto1/crapto1.h"
#include "des.h"
-#include "random.h" // fast_prand, prand
// mifare authentication
#define CRYPT_NONE 0
@@ -33,12 +32,26 @@
#define AUTHENTICATION_TIMEOUT 848 // card times out 1ms after wrong authentication (according to NXP documentation)
#define PRE_AUTHENTICATION_LEADTIME 400 // some (non standard) cards need a pause after select before they are ready for first authentication
-// mifare 4bit card answers
-#define CARD_ACK 0x0A // 1010 - ACK
-#define CARD_NACK_NA 0x04 // 0100 - NACK, not allowed (command not allowed)
-#define CARD_NACK_TR 0x05 // 0101 - NACK, transmission error
+// reader voltage field detector
+#define MF_MINFIELDV 4000
+// debug
+// 0 - no debug messages 1 - error messages 2 - all messages 4 - extended debug mode
+#define MF_DBG_NONE 0
+#define MF_DBG_ERROR 1
+#define MF_DBG_ALL 2
+#define MF_DBG_EXTENDED 4
+// Mifare 4k/2k/1k/mini Max Block / Max Sector
+#define MIFARE_4K_MAXBLOCK 256
+#define MIFARE_2K_MAXBLOCK 128
+#define MIFARE_1K_MAXBLOCK 64
+#define MIFARE_MINI_MAXBLOCK 20
+
+#define MIFARE_MINI_MAXSECTOR 5
+#define MIFARE_1K_MAXSECTOR 16
+#define MIFARE_2K_MAXSECTOR 32
+#define MIFARE_4K_MAXSECTOR 40
//mifare emulator states
#define MFEMUL_NOFIELD 0
@@ -47,7 +60,6 @@
#define MFEMUL_SELECT2 3
#define MFEMUL_SELECT3 4
#define MFEMUL_AUTH1 5
-#define MFEMUL_AUTH2 6
#define MFEMUL_WORK 7
#define MFEMUL_WRITEBL2 8
#define MFEMUL_INTREG_INC 9
@@ -74,8 +86,8 @@ int mifare_classic_halt_ex(struct Crypto1State *pcs);
int mifare_classic_writeblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t *blockData);
// Ultralight/NTAG...
-int mifare_ul_ev1_auth(uint8_t *key, uint8_t *pack);
-int mifare_ultra_auth(uint8_t *key);
+int mifare_ul_ev1_auth(uint8_t *keybytes, uint8_t *pack);
+int mifare_ultra_auth(uint8_t *keybytes);
int mifare_ultra_readblock(uint8_t blockNo, uint8_t *blockData);
//int mifare_ultra_writeblock_compat(uint8_t blockNo, uint8_t *blockData);
int mifare_ultra_writeblock(uint8_t blockNo, uint8_t *blockData);
@@ -88,7 +100,7 @@ int mifare_desfire_des_auth1(uint32_t uid, uint8_t *blockData);
int mifare_desfire_des_auth2(uint32_t uid, uint8_t *key, uint8_t *blockData);
// crypto functions
-void mf_crypto1_decrypt(struct Crypto1State *pcs, uint8_t *receivedCmd, int len);
+void mf_crypto1_decrypt(struct Crypto1State *pcs, uint8_t *data, int len);
void mf_crypto1_decryptEx(struct Crypto1State *pcs, uint8_t *data_in, int len, uint8_t *data_out);
void mf_crypto1_encrypt(struct Crypto1State *pcs, uint8_t *data, uint16_t len, uint8_t *par);
void mf_crypto1_encryptEx(struct Crypto1State *pcs, uint8_t *data_in, uint8_t *keystream, uint8_t *data_out, uint16_t len, uint8_t *par);
@@ -98,6 +110,9 @@ uint8_t mf_crypto1_encrypt4bit(struct Crypto1State *pcs, uint8_t data);
uint8_t NumBlocksPerSector(uint8_t sectorNo);
uint8_t FirstBlockOfSector(uint8_t sectorNo);
+bool IsSectorTrailer(uint8_t blockNo);
+uint8_t SectorTrailer(uint8_t blockNo);
+
// emulator functions
void emlClearMem(void);
void emlSetMem(uint8_t *data, int blockNum, int blocksCount);
diff --git a/armsrc/pcf7931.h b/armsrc/pcf7931.h
index b8121c29f..5e3c5a8e4 100644
--- a/armsrc/pcf7931.h
+++ b/armsrc/pcf7931.h
@@ -8,8 +8,8 @@
#include "string.h"
size_t DemodPCF7931(uint8_t **outBlocks);
-bool IsBlock0PCF7931(uint8_t *Block);
-bool IsBlock1PCF7931(uint8_t *Block);
+bool IsBlock0PCF7931(uint8_t *block);
+bool IsBlock1PCF7931(uint8_t *block);
void ReadPCF7931();
void SendCmdPCF7931(uint32_t *tab);
bool AddBytePCF7931(uint8_t byte, uint32_t *tab, int32_t l, int32_t p);
diff --git a/armsrc/printf.h b/armsrc/printf.h
index 616752ed6..ff0143790 100644
--- a/armsrc/printf.h
+++ b/armsrc/printf.h
@@ -15,7 +15,7 @@
#include
#include "string.h"
-int kvsprintf(const char *format, void *arg, int radix, va_list ap) __attribute__((format(printf, 1, 0)));
+int kvsprintf(const char *fmt, void *arg, int radix, va_list ap) __attribute__((format(printf, 1, 0)));
int vsprintf(char *dest, const char *fmt, va_list ap) __attribute__((format(printf, 2, 0)));
int sprintf(char *dest, const char *fmt, ...) __attribute__((format(printf, 2, 3)));
diff --git a/armsrc/start.c b/armsrc/start.c
index b5947bdf3..0b48fc601 100644
--- a/armsrc/start.c
+++ b/armsrc/start.c
@@ -48,7 +48,9 @@ static void uncompress_data_section(void) {
data_section.opaque = NULL;
// initialize zlib for inflate
- inflateInit2(&data_section, 15);
+ int res = inflateInit2(&data_section, 15);
+ if ( res < 0 )
+ return;
// uncompress data segment to RAM
inflate(&data_section, Z_FINISH);
diff --git a/armsrc/ticks.h b/armsrc/ticks.h
index d24d2aac5..c6715e177 100644
--- a/armsrc/ticks.h
+++ b/armsrc/ticks.h
@@ -37,11 +37,11 @@ void StartCountSspClk();
void ResetSspClk(void);
uint32_t RAMFUNC GetCountSspClk();
-extern void StartTicks(void);
-extern uint32_t GetTicks(void);
-extern void WaitTicks(uint32_t ticks);
-extern void WaitUS(uint16_t us);
-extern void WaitMS(uint16_t ms);
+void StartTicks(void);
+uint32_t GetTicks(void);
+void WaitTicks(uint32_t ticks);
+void WaitUS(uint16_t us);
+void WaitMS(uint16_t ms);
-extern void StopTicks(void);
+void StopTicks(void);
#endif
diff --git a/armsrc/util.h b/armsrc/util.h
index 15f93d1f9..fc519fe43 100644
--- a/armsrc/util.h
+++ b/armsrc/util.h
@@ -84,9 +84,9 @@
size_t nbytes(size_t nbits);
-extern uint32_t reflect(uint32_t v, int b); // used in crc.c ...
-extern uint8_t reflect8(uint8_t b); // dedicated 8bit reversal
-extern uint16_t reflect16(uint16_t b); // dedicated 16bit reversal
+uint32_t reflect(uint32_t v, int b); // used in crc.c ...
+uint8_t reflect8(uint8_t b); // dedicated 8bit reversal
+uint16_t reflect16(uint16_t b); // dedicated 16bit reversal
void num_to_bytes(uint64_t n, size_t len, uint8_t *dest);
uint64_t bytes_to_num(uint8_t *src, size_t len);
diff --git a/bootrom/bootrom.c b/bootrom/bootrom.c
index 53a33f525..e5cb77ff7 100644
--- a/bootrom/bootrom.c
+++ b/bootrom/bootrom.c
@@ -311,10 +311,9 @@ void BootROM(void) {
common_area.magic = COMMON_AREA_MAGIC;
common_area.version = 1;
- common_area.flags.bootrom_present = 1;
}
-
common_area.flags.bootrom_present = 1;
+
if (common_area.command == COMMON_AREA_COMMAND_ENTER_FLASH_MODE) {
common_area.command = COMMON_AREA_COMMAND_NONE;
flash_mode(1);
diff --git a/client/cliparser/argtable3.c b/client/cliparser/argtable3.c
index 0750ed601..e1bedbb4f 100644
--- a/client/cliparser/argtable3.c
+++ b/client/cliparser/argtable3.c
@@ -2960,10 +2960,19 @@ static int trex_class(TRex *exp) {
while (*exp->_p != ']' && exp->_p != exp->_eol) {
if (*exp->_p == '-' && first != -1) {
int r, t;
- if (*exp->_p++ == ']') trex_error(exp, _SC("unfinished range"));
+ if (*exp->_p++ == ']') {
+ trex_error(exp, _SC("unfinished range"));
+ }
+
r = trex_newnode(exp, OP_RANGE);
- if (first > *exp->_p) trex_error(exp, _SC("invalid range"));
- if (exp->_nodes[first].type == OP_CCLASS) trex_error(exp, _SC("cannot use character classes in ranges"));
+ if (first > *exp->_p) {
+ trex_error(exp, _SC("invalid range"));
+ }
+
+ if (exp->_nodes[first].type == OP_CCLASS) {
+ trex_error(exp, _SC("cannot use character classes in ranges"));
+ }
+
exp->_nodes[r].left = exp->_nodes[first].type;
t = trex_escapechar(exp);
exp->_nodes[r].right = t;
@@ -2984,8 +2993,6 @@ static int trex_class(TRex *exp) {
if (first != -1) {
int c = first;
exp->_nodes[chain].next = c;
- chain = c;
- first = -1;
}
/* hack? */
exp->_nodes[ret].left = exp->_nodes[ret].next;
@@ -3263,7 +3270,6 @@ static const TRexChar *trex_matchnode(TRex *exp, TRexNode *node, const TRexChar
return asd;
}
return NULL;
- break;
}
case OP_EXPR:
case OP_NOCAPEXPR: {
@@ -4542,8 +4548,9 @@ void arg_print_formatted(FILE *fp,
const unsigned colwidth = (rmargin - lmargin) + 1;
/* Someone doesn't like us... */
- if (line_end < line_start)
- { fprintf(fp, "%s\n", text); }
+ if (line_end == line_start) {
+ fprintf(fp, "%s\n", text);
+ }
while (line_end - 1 > line_start) {
/* Eat leading whitespaces. This is essential because while
diff --git a/client/cliparser/argtable3.h b/client/cliparser/argtable3.h
index a442ec0d5..c3ec479ea 100644
--- a/client/cliparser/argtable3.h
+++ b/client/cliparser/argtable3.h
@@ -271,7 +271,7 @@ struct arg_date *arg_daten(const char *shortopts,
int maxcount,
const char *glossary);
-struct arg_end *arg_end(int maxerrors);
+struct arg_end *arg_end(int maxcount);
/**** other functions *******************************************/
diff --git a/client/cliparser/cliparser.c b/client/cliparser/cliparser.c
index 766cf9ba4..6bba6f58b 100644
--- a/client/cliparser/cliparser.c
+++ b/client/cliparser/cliparser.c
@@ -26,7 +26,6 @@ int CLIParserInit(char *vprogramName, char *vprogramHint, char *vprogramHelp) {
programHint = vprogramHint;
programHelp = vprogramHelp;
memset(buf, 0x00, 500);
-
return 0;
}
@@ -155,12 +154,12 @@ int CLIParamHexToBuf(struct arg_str *argstr, uint8_t *data, int maxdatalen, int
*datalen = 0;
int ibuf = 0;
- uint8_t buf[256] = {0};
- int res = CLIParamStrToBuf(argstr, buf, maxdatalen * 2, &ibuf); // *2 because here HEX
+ uint8_t tmp_buf[256] = {0};
+ int res = CLIParamStrToBuf(argstr, tmp_buf, maxdatalen * 2, &ibuf); // *2 because here HEX
if (res || !ibuf)
return res;
- switch (param_gethex_to_eol((char *)buf, 0, data, maxdatalen, datalen)) {
+ switch (param_gethex_to_eol((char *)tmp_buf, 0, data, maxdatalen, datalen)) {
case 1:
printf("Parameter error: Invalid HEX value.\n");
return 1;
@@ -180,15 +179,15 @@ int CLIParamStrToBuf(struct arg_str *argstr, uint8_t *data, int maxdatalen, int
if (!argstr->count)
return 0;
- uint8_t buf[256] = {0};
+ uint8_t tmp_buf[256] = {0};
int ibuf = 0;
for (int i = 0; i < argstr->count; i++) {
int len = strlen(argstr->sval[i]);
- memcpy(&buf[ibuf], argstr->sval[i], len);
+ memcpy(&tmp_buf[ibuf], argstr->sval[i], len);
ibuf += len;
}
- buf[ibuf] = 0;
+ tmp_buf[ibuf] = 0;
if (!ibuf)
return 0;
@@ -196,7 +195,7 @@ int CLIParamStrToBuf(struct arg_str *argstr, uint8_t *data, int maxdatalen, int
if (ibuf > maxdatalen)
return 2;
- memcpy(data, buf, ibuf);
+ memcpy(data, tmp_buf, ibuf);
*datalen = ibuf;
return 0;
diff --git a/client/cliparser/cliparser.h b/client/cliparser/cliparser.h
index d42cd50b6..d1fa19bce 100644
--- a/client/cliparser/cliparser.h
+++ b/client/cliparser/cliparser.h
@@ -31,11 +31,11 @@
#define CLIGetHexWithReturn(paramnum, data, datalen) if (CLIParamHexToBuf(arg_get_str(paramnum), data, sizeof(data), datalen)) {CLIParserFree();return 1;}
#define CLIGetStrWithReturn(paramnum, data, datalen) if (CLIParamStrToBuf(arg_get_str(paramnum), data, sizeof(data), datalen)) {CLIParserFree();return 1;}
-extern int CLIParserInit(char *vprogramName, char *vprogramHint, char *vprogramHelp);
-extern int CLIParserParseString(const char *str, void *argtable[], size_t vargtableLen, bool allowEmptyExec);
-extern int CLIParserParseStringEx(const char *str, void *vargtable[], size_t vargtableLen, bool allowEmptyExec, bool clueData);
-extern int CLIParserParseArg(int argc, char **argv, void *argtable[], size_t vargtableLen, bool allowEmptyExec);
-extern void CLIParserFree();
+int CLIParserInit(char *vprogramName, char *vprogramHint, char *vprogramHelp);
+int CLIParserParseString(const char *str, void *vargtable[], size_t vargtableLen, bool allowEmptyExec);
+int CLIParserParseStringEx(const char *str, void *vargtable[], size_t vargtableLen, bool allowEmptyExec, bool clueData);
+int CLIParserParseArg(int argc, char **argv, void *vargtable[], size_t vargtableLen, bool allowEmptyExec);
+void CLIParserFree();
-extern int CLIParamHexToBuf(struct arg_str *argstr, uint8_t *data, int maxdatalen, int *datalen);
-extern int CLIParamStrToBuf(struct arg_str *argstr, uint8_t *data, int maxdatalen, int *datalen);
+int CLIParamHexToBuf(struct arg_str *argstr, uint8_t *data, int maxdatalen, int *datalen);
+int CLIParamStrToBuf(struct arg_str *argstr, uint8_t *data, int maxdatalen, int *datalen);
diff --git a/client/cmdanalyse.c b/client/cmdanalyse.c
index 1813917aa..3bd3f08cb 100644
--- a/client/cmdanalyse.c
+++ b/client/cmdanalyse.c
@@ -300,7 +300,7 @@ int CmdAnalyseCRC(const char *Cmd) {
// ISO14443 crc B
compute_crc(CRC_14443_B, data, len, &b1, &b2);
uint16_t crcBB_1 = b1 << 8 | b2;
- uint16_t bbb = crc(CRC_14443_B, data, len);
+ uint16_t bbb = Crc(CRC_14443_B, data, len);
PrintAndLogEx(NORMAL, "ISO14443 crc B | %04x == %04x \n", crcBB_1, bbb);
@@ -321,40 +321,40 @@ int CmdAnalyseCRC(const char *Cmd) {
PrintAndLogEx(NORMAL, "CRC16 based\n\n");
// input from commandline
- PrintAndLogEx(NORMAL, "CCITT | %X (29B1 expected)", crc(CRC_CCITT, dataStr, sizeof(dataStr)));
+ PrintAndLogEx(NORMAL, "CCITT | %X (29B1 expected)", Crc(CRC_CCITT, dataStr, sizeof(dataStr)));
uint8_t poll[] = {0xb2, 0x4d, 0x12, 0x01, 0x01, 0x2e, 0x3d, 0x17, 0x26, 0x47, 0x80, 0x95, 0x00, 0xf1, 0x00, 0x00, 0x00, 0x01, 0x43, 0x00, 0xb3, 0x7f};
- PrintAndLogEx(NORMAL, "FeliCa | %04X (B37F expected)", crc(CRC_FELICA, poll + 2, sizeof(poll) - 4));
- PrintAndLogEx(NORMAL, "FeliCa | %04X (0000 expected)", crc(CRC_FELICA, poll + 2, sizeof(poll) - 2));
+ PrintAndLogEx(NORMAL, "FeliCa | %04X (B37F expected)", Crc(CRC_FELICA, poll + 2, sizeof(poll) - 4));
+ PrintAndLogEx(NORMAL, "FeliCa | %04X (0000 expected)", Crc(CRC_FELICA, poll + 2, sizeof(poll) - 2));
uint8_t sel_corr[] = { 0x40, 0xe1, 0xe1, 0xff, 0xfe, 0x5f, 0x02, 0x3c, 0x43, 0x01};
- PrintAndLogEx(NORMAL, "iCLASS | %04x (0143 expected)", crc(CRC_ICLASS, sel_corr, sizeof(sel_corr) - 2));
+ PrintAndLogEx(NORMAL, "iCLASS | %04x (0143 expected)", Crc(CRC_ICLASS, sel_corr, sizeof(sel_corr) - 2));
PrintAndLogEx(NORMAL, "---------------------------------------------------------------\n\n\n");
// ISO14443 crc A
compute_crc(CRC_14443_A, dataStr, sizeof(dataStr), &b1, &b2);
uint16_t crcAA = b1 << 8 | b2;
- PrintAndLogEx(NORMAL, "ISO14443 crc A | %04x or %04x (BF05 expected)\n", crcAA, crc(CRC_14443_A, dataStr, sizeof(dataStr)));
+ PrintAndLogEx(NORMAL, "ISO14443 crc A | %04x or %04x (BF05 expected)\n", crcAA, Crc(CRC_14443_A, dataStr, sizeof(dataStr)));
// ISO14443 crc B
compute_crc(CRC_14443_B, dataStr, sizeof(dataStr), &b1, &b2);
uint16_t crcBB = b1 << 8 | b2;
- PrintAndLogEx(NORMAL, "ISO14443 crc B | %04x or %04x (906E expected)\n", crcBB, crc(CRC_14443_B, dataStr, sizeof(dataStr)));
+ PrintAndLogEx(NORMAL, "ISO14443 crc B | %04x or %04x (906E expected)\n", crcBB, Crc(CRC_14443_B, dataStr, sizeof(dataStr)));
// ISO15693 crc (x.25)
compute_crc(CRC_15693, dataStr, sizeof(dataStr), &b1, &b2);
uint16_t crcCC = b1 << 8 | b2;
- PrintAndLogEx(NORMAL, "ISO15693 crc X25| %04x or %04x (906E expected)\n", crcCC, crc(CRC_15693, dataStr, sizeof(dataStr)));
+ PrintAndLogEx(NORMAL, "ISO15693 crc X25| %04x or %04x (906E expected)\n", crcCC, Crc(CRC_15693, dataStr, sizeof(dataStr)));
// ICLASS
compute_crc(CRC_ICLASS, dataStr, sizeof(dataStr), &b1, &b2);
uint16_t crcDD = b1 << 8 | b2;
- PrintAndLogEx(NORMAL, "ICLASS crc | %04x or %04x\n", crcDD, crc(CRC_ICLASS, dataStr, sizeof(dataStr)));
+ PrintAndLogEx(NORMAL, "ICLASS crc | %04x or %04x\n", crcDD, Crc(CRC_ICLASS, dataStr, sizeof(dataStr)));
// FeliCa
compute_crc(CRC_FELICA, dataStr, sizeof(dataStr), &b1, &b2);
uint16_t crcEE = b1 << 8 | b2;
- PrintAndLogEx(NORMAL, "FeliCa | %04x or %04x (31C3 expected)\n", crcEE, crc(CRC_FELICA, dataStr, sizeof(dataStr)));
+ PrintAndLogEx(NORMAL, "FeliCa | %04x or %04x (31C3 expected)\n", crcEE, Crc(CRC_FELICA, dataStr, sizeof(dataStr)));
free(data);
return 0;
@@ -615,7 +615,7 @@ int CmdAnalyseA(const char *Cmd) {
}
*/
- return 0;
+// return 0;
// 14443-A
uint8_t u14_c[] = {0x09, 0x78, 0x00, 0x92, 0x02, 0x54, 0x13, 0x02, 0x04, 0x2d, 0xe8 }; // atqs w crc
diff --git a/client/cmdcrc.h b/client/cmdcrc.h
index ba9540c45..f52727c2c 100644
--- a/client/cmdcrc.h
+++ b/client/cmdcrc.h
@@ -28,9 +28,9 @@
#include "ui.h"
#include "util.h"
-extern int CmdCrc(const char *Cmd);
+int CmdCrc(const char *Cmd);
-extern int CmdrevengSearch(const char *Cmd);
-extern int GetModels(char *Models[], int *count, uint8_t *width);
-extern int RunModel(char *inModel, char *inHexStr, bool reverse, char endian, char *result);
+int CmdrevengSearch(const char *Cmd);
+int GetModels(char *Models[], int *count, uint8_t *width);
+int RunModel(char *inModel, char *inHexStr, bool reverse, char endian, char *result);
#endif
diff --git a/client/cmddata.c b/client/cmddata.c
index 5b3074433..f413a77ef 100644
--- a/client/cmddata.c
+++ b/client/cmddata.c
@@ -237,26 +237,26 @@ int usage_data_fsktonrz() {
//set the demod buffer with given array of binary (one bit per byte)
//by marshmellow
-void setDemodBuf(uint8_t *buf, size_t size, size_t start_idx) {
- if (buf == NULL) return;
+void setDemodBuff(uint8_t *buff, size_t size, size_t start_idx) {
+ if (buff == NULL) return;
if (size > MAX_DEMOD_BUF_LEN - start_idx)
size = MAX_DEMOD_BUF_LEN - start_idx;
for (size_t i = 0; i < size; i++)
- DemodBuffer[i] = buf[start_idx++];
+ DemodBuffer[i] = buff[start_idx++];
DemodBufferLen = size;
}
-bool getDemodBuf(uint8_t *buf, size_t *size) {
- if (buf == NULL) return false;
+bool getDemodBuff(uint8_t *buff, size_t *size) {
+ if (buff == NULL) return false;
if (size == NULL) return false;
if (*size == 0) return false;
*size = (*size > DemodBufferLen) ? DemodBufferLen : *size;
- memcpy(buf, DemodBuffer, *size);
+ memcpy(buff, DemodBuffer, *size);
return true;
}
@@ -521,7 +521,7 @@ int ASKDemod_ext(const char *Cmd, bool verbose, bool emSearch, uint8_t askType,
if (verbose) PrintAndLogEx(DEBUG, "DEBUG: (ASKDemod_ext) Using clock:%d, invert:%d, bits found:%d", clk, invert, BitLen);
//output
- setDemodBuf(bits, BitLen, 0);
+ setDemodBuff(bits, BitLen, 0);
setClockGrid(clk, startIdx);
if (verbose) {
@@ -608,7 +608,7 @@ int Cmdmandecoderaw(const char *Cmd) {
size_t idx = 0;
if (Em410xDecode(bits, &size, &idx, &hi, &id) == 1) {
//need to adjust to set bitstream back to manchester encoded data
- //setDemodBuf(bits, size, idx);
+ //setDemodBuff(bits, size, idx);
printEM410x(hi, id);
}
}
@@ -638,7 +638,7 @@ int CmdBiphaseDecodeRaw(const char *Cmd) {
uint8_t bits[MAX_DEMOD_BUF_LEN] = {0};
size = sizeof(bits);
- if (!getDemodBuf(bits, &size)) return 0;
+ if (!getDemodBuff(bits, &size)) return 0;
errCnt = BiphaseRawDecode(bits, &size, &offset, invert);
if (errCnt < 0) {
@@ -658,7 +658,7 @@ int CmdBiphaseDecodeRaw(const char *Cmd) {
//remove first bit from raw demod
if (offset)
- setDemodBuf(DemodBuffer, DemodBufferLen - offset, offset);
+ setDemodBuff(DemodBuffer, DemodBufferLen - offset, offset);
setClockGrid(g_DemodClock, g_DemodStartIdx + g_DemodClock * offset / 2);
return 1;
@@ -696,7 +696,7 @@ int ASKbiphaseDemod(const char *Cmd, bool verbose) {
return 0;
}
//success set DemodBuffer and return
- setDemodBuf(BitStream, size, 0);
+ setDemodBuff(BitStream, size, 0);
setClockGrid(clk, startIdx + clk * offset / 2);
if (g_debugMode || verbose) {
PrintAndLogEx(NORMAL, "Biphase Decoded using offset: %d - clock: %d - # errors:%d - data:", offset, clk, errCnt);
@@ -1067,7 +1067,7 @@ int FSKrawDemod(const char *Cmd, bool verbose) {
int startIdx = 0;
int size = fskdemod(bits, BitLen, rfLen, invert, fchigh, fclow, &startIdx);
if (size > 0) {
- setDemodBuf(bits, size, 0);
+ setDemodBuff(bits, size, 0);
setClockGrid(rfLen, startIdx);
// Now output the bitstream to the scrollback by line of 16 bits
@@ -1135,7 +1135,7 @@ int PSKDemod(const char *Cmd, bool verbose) {
}
}
//prime demod buffer for output
- setDemodBuf(bits, bitlen, 0);
+ setDemodBuff(bits, bitlen, 0);
setClockGrid(clk, startIdx);
return 1;
}
@@ -1185,7 +1185,7 @@ int CmdIdteckDemod(const char *Cmd) {
return 0;
}
}
- setDemodBuf(DemodBuffer, 64, idx);
+ setDemodBuff(DemodBuffer, 64, idx);
//got a good demod
uint32_t id = 0;
@@ -1238,7 +1238,7 @@ int NRZrawDemod(const char *Cmd, bool verbose) {
}
if (verbose || g_debugMode) PrintAndLogEx(DEBUG, "DEBUG: (NRZrawDemod) Tried NRZ Demod using Clock: %d - invert: %d - Bits Found: %d", clk, invert, BitLen);
//prime demod buffer for output
- setDemodBuf(bits, BitLen, 0);
+ setDemodBuff(bits, BitLen, 0);
setClockGrid(clk, clkStartIdx);
@@ -1973,13 +1973,13 @@ int FSKToNRZ(int *data, int *dataLen, int clk, int LowToneFC, int HighToneFC) {
int firstClockEdge = 0;
ans = fskClocks((uint8_t *) &LowToneFC, (uint8_t *) &HighToneFC, (uint8_t *) &clk, &firstClockEdge);
if (g_debugMode > 1) {
- PrintAndLog("DEBUG FSKtoNRZ: detected clocks: fc_low %i, fc_high %i, clk %i, firstClockEdge %i, ans %u", LowToneFC, HighToneFC, clk, firstClockEdge, ans);
+ PrintAndLogEx(NORMAL, "DEBUG FSKtoNRZ: detected clocks: fc_low %i, fc_high %i, clk %i, firstClockEdge %i, ans %u", LowToneFC, HighToneFC, clk, firstClockEdge, ans);
}
}
// currently only know fsk modulations with field clocks < 10 samples and > 4 samples. filter out to remove false positives (and possibly destroying ask/psk modulated waves...)
if (ans == 0 || clk == 0 || LowToneFC == 0 || HighToneFC == 0 || LowToneFC > 10 || HighToneFC < 4) {
if (g_debugMode > 1) {
- PrintAndLog("DEBUG FSKtoNRZ: no fsk clocks found");
+ PrintAndLogEx(NORMAL,"DEBUG FSKtoNRZ: no fsk clocks found");
}
return 0;
}
diff --git a/client/cmddata.h b/client/cmddata.h
index 1091c48c2..cca722ed4 100644
--- a/client/cmddata.h
+++ b/client/cmddata.h
@@ -36,8 +36,8 @@ command_t *CmdDataCommands();
int CmdData(const char *Cmd);
void printDemodBuff(void);
-void setDemodBuf(uint8_t *buff, size_t size, size_t startIdx);
-bool getDemodBuf(uint8_t *buff, size_t *size);
+void setDemodBuff(uint8_t *buff, size_t size, size_t start_idx);
+bool getDemodBuff(uint8_t *buff, size_t *size);
void save_restoreDB(uint8_t saveOpt);// option '1' to save DemodBuffer any other to restore
int CmdPrintDemodBuff(const char *Cmd);
@@ -84,7 +84,7 @@ int NRZrawDemod(const char *Cmd, bool verbose);
int getSamples(int n, bool silent);
void setClockGrid(int clk, int offset);
int directionalThreshold(const int *in, int *out, size_t len, int8_t up, int8_t down);
-extern int AskEdgeDetect(const int *in, int *out, int len, int threshold);
+int AskEdgeDetect(const int *in, int *out, int len, int threshold);
int CmdDataIIR(const char *Cmd);
diff --git a/client/cmdflashmem.h b/client/cmdflashmem.h
index 9f946908c..1cf06c1bc 100644
--- a/client/cmdflashmem.h
+++ b/client/cmdflashmem.h
@@ -33,13 +33,13 @@ typedef enum {
DICTIONARY_ICLASS
} Dictionary_t;
-extern int CmdFlashMem(const char *Cmd);
+int CmdFlashMem(const char *Cmd);
-extern int CmdFlashMemRead(const char *Cmd);
-extern int CmdFlashMemLoad(const char *Cmd);
-extern int CmdFlashMemSave(const char *Cmd);
-extern int CmdFlashMemWipe(const char *Cmd);
-extern int CmdFlashMemInfo(const char *Cmd);
+int CmdFlashMemRead(const char *Cmd);
+int CmdFlashMemLoad(const char *Cmd);
+int CmdFlashMemSave(const char *Cmd);
+int CmdFlashMemWipe(const char *Cmd);
+int CmdFlashMemInfo(const char *Cmd);
#endif
#endif
diff --git a/client/cmdhf.h b/client/cmdhf.h
index 9e41f2138..3237e1df6 100644
--- a/client/cmdhf.h
+++ b/client/cmdhf.h
@@ -33,11 +33,11 @@
#include "cmdhffido.h" // FIDO authenticators
#include "cmdtrace.h" // trace list
-extern int CmdHF(const char *Cmd);
-extern int CmdHFTune(const char *Cmd);
-extern int CmdHFSearch(const char *Cmd);
-extern int CmdHFSniff(const char *Cmd);
+int CmdHF(const char *Cmd);
+int CmdHFTune(const char *Cmd);
+int CmdHFSearch(const char *Cmd);
+int CmdHFSniff(const char *Cmd);
-extern int usage_hf_search();
-extern int usage_hf_sniff();
+int usage_hf_search();
+int usage_hf_sniff();
#endif
diff --git a/client/cmdhf14a.c b/client/cmdhf14a.c
index 0894c578f..75f30f6f8 100644
--- a/client/cmdhf14a.c
+++ b/client/cmdhf14a.c
@@ -15,7 +15,7 @@
bool APDUInFramingEnable = true;
static int CmdHelp(const char *Cmd);
-static int waitCmd(uint8_t iLen);
+static int waitCmd(uint8_t iSelect);
static const manufactureName manufactureMapping[] = {
// ID, "Vendor Country"
@@ -238,30 +238,30 @@ int Hf14443_4aGetCardData(iso14a_card_select_t *card) {
uint64_t select_status = resp.arg[0]; // 0: couldn't read, 1: OK, with ATS, 2: OK, no ATS, 3: proprietary Anticollision
if (select_status == 0) {
- PrintAndLog("E->iso14443a card select failed");
+ PrintAndLogEx(ERR, "E->iso14443a card select failed");
return 1;
}
if (select_status == 2) {
- PrintAndLog("E->Card doesn't support iso14443-4 mode");
+ PrintAndLogEx(ERR, "E->Card doesn't support iso14443-4 mode");
return 1;
}
if (select_status == 3) {
- PrintAndLog("E->Card doesn't support standard iso14443-3 anticollision");
- PrintAndLog("\tATQA : %02x %02x", card->atqa[1], card->atqa[0]);
+ PrintAndLogEx(NORMAL, "E->Card doesn't support standard iso14443-3 anticollision");
+ PrintAndLogEx(NORMAL, "\tATQA : %02x %02x", card->atqa[1], card->atqa[0]);
return 1;
}
- PrintAndLog(" UID: %s", sprint_hex(card->uid, card->uidlen));
- PrintAndLog("ATQA: %02x %02x", card->atqa[1], card->atqa[0]);
- PrintAndLog(" SAK: %02x [%" PRIu64 "]", card->sak, resp.arg[0]);
+ PrintAndLogEx(NORMAL, " UID: %s", sprint_hex(card->uid, card->uidlen));
+ PrintAndLogEx(NORMAL, "ATQA: %02x %02x", card->atqa[1], card->atqa[0]);
+ PrintAndLogEx(NORMAL, " SAK: %02x [%" PRIu64 "]", card->sak, resp.arg[0]);
if (card->ats_len < 3) { // a valid ATS consists of at least the length byte (TL) and 2 CRC bytes
- PrintAndLog("E-> Error ATS length(%d) : %s", card->ats_len, sprint_hex(card->ats, card->ats_len));
+ PrintAndLogEx(NORMAL, "E-> Error ATS length(%d) : %s", card->ats_len, sprint_hex(card->ats, card->ats_len));
return 1;
}
- PrintAndLog(" ATS: %s", sprint_hex(card->ats, card->ats_len));
-
+
+ PrintAndLogEx(NORMAL, " ATS: %s", sprint_hex(card->ats, card->ats_len));
return 0;
}
@@ -418,7 +418,6 @@ int CmdHF14AInfo(const char *Cmd) {
c.arg[2] = 0;
clearCommandBuffer();
SendCommand(&c);
- UsbCommand resp;
WaitForResponse(CMD_ACK, &resp);
memcpy(&card, (iso14a_card_select_t *)resp.d.asBytes, sizeof(iso14a_card_select_t));
@@ -692,8 +691,8 @@ int CmdHF14ACUIDs(const char *Cmd) {
PrintAndLogEx(WARNING, "card select failed.");
} else {
char uid_string[20];
- for (uint16_t i = 0; i < card->uidlen; i++) {
- sprintf(&uid_string[2 * i], "%02X", card->uid[i]);
+ for (uint16_t m = 0; m < card->uidlen; m++) {
+ sprintf(&uid_string[2 * m], "%02X", card->uid[m]);
}
PrintAndLogEx(NORMAL, "%s", uid_string);
}
diff --git a/client/cmdhf14a.h b/client/cmdhf14a.h
index 6020b6f8b..e218a398f 100644
--- a/client/cmdhf14a.h
+++ b/client/cmdhf14a.h
@@ -39,23 +39,23 @@ typedef struct {
char *desc;
} manufactureName;
-extern int CmdHF14A(const char *Cmd);
-extern int CmdHF14AList(const char *Cmd);
-extern int CmdHF14AReader(const char *Cmd);
-extern int CmdHF14AInfo(const char *Cmd);
-extern int CmdHF14ASim(const char *Cmd);
-extern int CmdHF14ASniff(const char *Cmd);
-extern int CmdHF14ACmdRaw(const char *Cmd);
-extern int CmdHF14ACUIDs(const char *Cmd);
-extern int CmdHF14AAntiFuzz(const char *Cmd);
+int CmdHF14A(const char *Cmd);
+int CmdHF14AList(const char *Cmd);
+int CmdHF14AReader(const char *Cmd);
+int CmdHF14AInfo(const char *Cmd);
+int CmdHF14ASim(const char *Cmd);
+int CmdHF14ASniff(const char *Cmd);
+int CmdHF14ACmdRaw(const char *Cmd);
+int CmdHF14ACUIDs(const char *Cmd);
+int CmdHF14AAntiFuzz(const char *Cmd);
-extern char *getTagInfo(uint8_t uid);
-extern int Hf14443_4aGetCardData(iso14a_card_select_t *card);
-extern int ExchangeAPDU14a(uint8_t *datain, int datainlen, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen);
-extern int ExchangeRAW14a(uint8_t *datain, int datainlen, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen);
+char *getTagInfo(uint8_t uid);
+int Hf14443_4aGetCardData(iso14a_card_select_t *card);
+int ExchangeAPDU14a(uint8_t *datain, int datainlen, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen);
+int ExchangeRAW14a(uint8_t *datain, int datainlen, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen);
-extern int usage_hf_14a_sim(void);
-extern int usage_hf_14a_sniff(void);
-extern int usage_hf_14a_raw(void);
-extern int usage_hf_14a_antifuzz(void);
+int usage_hf_14a_sim(void);
+int usage_hf_14a_sniff(void);
+int usage_hf_14a_raw(void);
+int usage_hf_14a_antifuzz(void);
#endif
diff --git a/client/cmdhf14b.h b/client/cmdhf14b.h
index 56114af94..f2d78778c 100644
--- a/client/cmdhf14b.h
+++ b/client/cmdhf14b.h
@@ -37,23 +37,23 @@ int usage_hf_14b_sim(void);
int usage_hf_14b_read_srx(void);
int usage_hf_14b_write_srx(void);
-extern int CmdHF14B(const char *Cmd);
-extern int CmdHF14BList(const char *Cmd);
-extern int CmdHF14BInfo(const char *Cmd);
-extern int CmdHF14BSim(const char *Cmd);
-extern int CmdHF14BSniff(const char *Cmd);
-extern int CmdHF14BWrite(const char *cmd);
-extern int CmdHF14BReader(const char *Cmd);
+int CmdHF14B(const char *Cmd);
+int CmdHF14BList(const char *Cmd);
+int CmdHF14BInfo(const char *Cmd);
+int CmdHF14BSim(const char *Cmd);
+int CmdHF14BSniff(const char *Cmd);
+int CmdHF14BWrite(const char *cmd);
+int CmdHF14BReader(const char *Cmd);
-extern int CmdHF14BDump(const char *Cmd);
+int CmdHF14BDump(const char *Cmd);
-extern bool HF14BInfo(bool verbose);
-extern bool HF14BReader(bool verbose);
-extern int CmdHF14BCmdRaw(const char *Cmd);
+bool HF14BInfo(bool verbose);
+bool HF14BReader(bool verbose);
+int CmdHF14BCmdRaw(const char *Cmd);
// SRi ST Microelectronics read/write
-extern int CmdHF14BReadSri(const char *Cmd);
-extern int CmdHF14BWriteSri(const char *Cmd);
+int CmdHF14BReadSri(const char *Cmd);
+int CmdHF14BWriteSri(const char *Cmd);
bool waitCmd14b(bool verbose);
#endif
diff --git a/client/cmdhf15.c b/client/cmdhf15.c
index 55e4aa478..877469fd5 100644
--- a/client/cmdhf15.c
+++ b/client/cmdhf15.c
@@ -29,9 +29,9 @@
#define Logic1 Iso15693Logic1
#define FrameEOF Iso15693FrameEOF
-#define Crc(data, len) crc(CRC_15693, (data), (len))
-#define CheckCrc(data, len) check_crc(CRC_15693, (data), (len))
-#define AddCrc(data, len) compute_crc(CRC_15693, (data), (len), (data)+(len), (data)+(len)+1)
+#define Crc15(data, len) Crc(CRC_15693, (data), (len))
+#define CheckCrc15(data, len) check_crc(CRC_15693, (data), (len))
+#define AddCrc15(data, len) compute_crc(CRC_15693, (data), (len), (data)+(len), (data)+(len)+1)
#define sprintUID(target, uid) Iso15693sprintUID((target), (uid))
@@ -198,7 +198,7 @@ int getUID(uint8_t *buf) {
c.d.asBytes[1] = ISO15_CMD_INVENTORY;
c.d.asBytes[2] = 0; // mask length
- AddCrc(c.d.asBytes, 3);
+ AddCrc15(c.d.asBytes, 3);
c.arg[0] = 5; // len
uint8_t retry;
@@ -212,7 +212,7 @@ int getUID(uint8_t *buf) {
if (WaitForResponseTimeout(CMD_ACK, &resp, 2000)) {
uint8_t resplen = resp.arg[0];
- if (resplen >= 12 && CheckCrc(resp.d.asBytes, 12)) {
+ if (resplen >= 12 && CheckCrc15(resp.d.asBytes, 12)) {
memcpy(buf, resp.d.asBytes + 2, 8);
return 1;
}
@@ -479,7 +479,7 @@ int CmdHF15Demod(const char *Cmd) {
for (i = 0; i < k; i++)
PrintAndLogEx(NORMAL, "# %2d: %02x ", i, outBuf[i]);
- PrintAndLogEx(NORMAL, "CRC %04x", Crc(outBuf, k - 2));
+ PrintAndLogEx(NORMAL, "CRC %04x", Crc15(outBuf, k - 2));
return 0;
}
@@ -519,7 +519,7 @@ int CmdHF15Info(const char *Cmd) {
if (!prepareHF15Cmd(&cmd, &c, ISO15_CMD_SYSINFO))
return 0;
- AddCrc(req, c.arg[0]);
+ AddCrc15(req, c.arg[0]);
c.arg[0] += 2;
//PrintAndLogEx(NORMAL, "cmd %s", sprint_hex(c.d.asBytes, reqlen) );
@@ -721,7 +721,7 @@ int CmdHF15Dump(const char *Cmd) {
for (int retry = 0; retry < 5; retry++) {
req[10] = blocknum;
- AddCrc(req, 11);
+ AddCrc15(req, 11);
c.arg[0] = 13;
clearCommandBuffer();
@@ -737,7 +737,7 @@ int CmdHF15Dump(const char *Cmd) {
recv = resp.d.asBytes;
- if (!CheckCrc(recv, len)) {
+ if (!CheckCrc15(recv, len)) {
PrintAndLogEx(FAILED, "crc fail");
continue;
}
@@ -848,7 +848,7 @@ int CmdHF15Restore(const char *Cmd) {
}
PrintAndLogEx(INFO, "Restoring data blocks.");
-
+
while (1) {
tried = 0;
hex[0] = 0x00;
@@ -958,7 +958,7 @@ int CmdHF15Raw(const char *Cmd) {
}
if (crc) {
- AddCrc(data, datalen);
+ AddCrc15(data, datalen);
datalen += 2;
}
@@ -1099,7 +1099,7 @@ int CmdHF15Readmulti(const char *Cmd) {
req[reqlen++] = pagenum;
req[reqlen++] = pagecount;
- AddCrc(req, reqlen);
+ AddCrc15(req, reqlen);
c.arg[0] = reqlen + 2;
clearCommandBuffer();
@@ -1118,7 +1118,7 @@ int CmdHF15Readmulti(const char *Cmd) {
recv = resp.d.asBytes;
- if (!CheckCrc(recv, status)) {
+ if (!CheckCrc15(recv, status)) {
PrintAndLogEx(FAILED, "CRC failed");
return 2;
}
@@ -1178,7 +1178,7 @@ int CmdHF15Read(const char *Cmd) {
req[reqlen++] = (uint8_t)blocknum;
- AddCrc(req, reqlen);
+ AddCrc15(req, reqlen);
c.arg[0] = reqlen + 2;
@@ -1198,7 +1198,7 @@ int CmdHF15Read(const char *Cmd) {
recv = resp.d.asBytes;
- if (!CheckCrc(recv, status)) {
+ if (!CheckCrc15(recv, status)) {
PrintAndLogEx(NORMAL, "CRC failed");
return 2;
}
@@ -1261,7 +1261,7 @@ int CmdHF15Write(const char *Cmd) {
req[reqlen++] = temp & 0xff;
cmd2 += 2;
}
- AddCrc(req, reqlen);
+ AddCrc15(req, reqlen);
c.arg[0] = reqlen + 2;
PrintAndLogEx(NORMAL, "iso15693 writing to page %02d (0x%02X) | data ", pagenum, pagenum);
@@ -1282,7 +1282,7 @@ int CmdHF15Write(const char *Cmd) {
recv = resp.d.asBytes;
- if (!CheckCrc(recv, status)) {
+ if (!CheckCrc15(recv, status)) {
PrintAndLogEx(FAILED, "CRC failed");
return 2;
}
diff --git a/client/cmdhf15.h b/client/cmdhf15.h
index 942fd2952..5a3753100 100644
--- a/client/cmdhf15.h
+++ b/client/cmdhf15.h
@@ -28,38 +28,38 @@
int CmdHF15(const char *Cmd);
-extern int HF15Reader(const char *Cmd, bool verbose);
+int HF15Reader(const char *Cmd, bool verbose);
-extern int CmdHF15Demod(const char *Cmd);
-extern int CmdHF15Samples(const char *Cmd);
-extern int CmdHF15Info(const char *Cmd);
-extern int CmdHF15Record(const char *Cmd);
-extern int CmdHF15Reader(const char *Cmd);
-extern int CmdHF15Sim(const char *Cmd);
-extern int CmdHF15Afi(const char *Cmd);
-extern int CmdHF15Dump(const char *Cmd);
-extern int CmdHF15Raw(const char *cmd);
-extern int CmdHF15Readmulti(const char *Cmd);
-extern int CmdHF15Read(const char *Cmd);
-extern int CmdHF15Write(const char *Cmd);
+int CmdHF15Demod(const char *Cmd);
+int CmdHF15Samples(const char *Cmd);
+int CmdHF15Info(const char *Cmd);
+int CmdHF15Record(const char *Cmd);
+int CmdHF15Reader(const char *Cmd);
+int CmdHF15Sim(const char *Cmd);
+int CmdHF15Afi(const char *Cmd);
+int CmdHF15Dump(const char *Cmd);
+int CmdHF15Raw(const char *Cmd);
+int CmdHF15Readmulti(const char *Cmd);
+int CmdHF15Read(const char *Cmd);
+int CmdHF15Write(const char *Cmd);
-extern int CmdHF15Help(const char *Cmd);
+int CmdHF15Help(const char *Cmd);
// usages
-extern int usage_15_demod(void);
-extern int usage_15_samples(void);
-extern int usage_15_info(void);
-extern int usage_15_record(void);
-extern int usage_15_reader(void);
-extern int usage_15_sim(void);
-extern int usage_15_findafi(void);
-extern int usage_15_dump(void);
-extern int usage_15_restore(void);
-extern int usage_15_raw(void);
+int usage_15_demod(void);
+int usage_15_samples(void);
+int usage_15_info(void);
+int usage_15_record(void);
+int usage_15_reader(void);
+int usage_15_sim(void);
+int usage_15_findafi(void);
+int usage_15_dump(void);
+int usage_15_restore(void);
+int usage_15_raw(void);
-extern int usage_15_read(void);
-extern int usage_15_write(void);
-extern int usage_15_readmulti(void);
+int usage_15_read(void);
+int usage_15_write(void);
+int usage_15_readmulti(void);
-extern int prepareHF15Cmd(char **cmd, UsbCommand *c, uint8_t iso15cmd);
+int prepareHF15Cmd(char **cmd, UsbCommand *c, uint8_t iso15cmd);
#endif
diff --git a/client/cmdhfepa.c b/client/cmdhfepa.c
index 0386155c1..ecd185783 100644
--- a/client/cmdhfepa.c
+++ b/client/cmdhfepa.c
@@ -61,8 +61,8 @@ int CmdHFEPACollectPACENonces(const char *Cmd) {
// perform the PACE protocol by replaying APDUs
int CmdHFEPAPACEReplay(const char *Cmd) {
// the 4 APDUs which are replayed + their lengths
- uint8_t msesa_apdu[41], gn_apdu[8], map_apdu[75];
- uint8_t pka_apdu[75], ma_apdu[18], apdu_lengths[5] = {0};
+ uint8_t msesa_apdu[41] = {0}, gn_apdu[8] = {0}, map_apdu[75] = {0};
+ uint8_t pka_apdu[75] = {0}, ma_apdu[18] = {0}, apdu_lengths[5] = {0};
// pointers to the arrays to be able to iterate
uint8_t *apdus[] = {msesa_apdu, gn_apdu, map_apdu, pka_apdu, ma_apdu};
@@ -74,15 +74,18 @@ int CmdHFEPAPACEReplay(const char *Cmd) {
// Proxmark response
UsbCommand resp;
- int skip = 0, skip_add = 0, scan_return = 0;
+ int skip = 0, skip_add = 0, scan_return;
// for each APDU
for (int i = 0; i < sizeof(apdu_lengths); i++) {
// scan to next space or end of string
while (Cmd[skip] != ' ' && Cmd[skip] != '\0') {
// convert
- scan_return = sscanf(Cmd + skip, "%2X%n",
+ scan_return = sscanf(Cmd + skip,
+ "%2X%n",
(unsigned int *)(apdus[i] + apdu_lengths[i]),
- &skip_add);
+ &skip_add
+ );
+
if (scan_return < 1) {
PrintAndLogEx(NORMAL, (char *)usage_msg);
PrintAndLogEx(WARNING, "Not enough APDUs! Try again!");
diff --git a/client/cmdhfepa.h b/client/cmdhfepa.h
index 914ce4c5d..c526c6eb0 100644
--- a/client/cmdhfepa.h
+++ b/client/cmdhfepa.h
@@ -25,8 +25,8 @@
#include "util_posix.h"
-extern int CmdHFEPA(const char *Cmd);
-extern int CmdHFEPACollectPACENonces(const char *Cmd);
-extern int CmdHFEPAPACEReplay(const char *Cmd);
+int CmdHFEPA(const char *Cmd);
+int CmdHFEPACollectPACENonces(const char *Cmd);
+int CmdHFEPAPACEReplay(const char *Cmd);
#endif // CMDHFEPA_H__
diff --git a/client/cmdhffelica.h b/client/cmdhffelica.h
index 80a09f7d3..6eeb5b44f 100644
--- a/client/cmdhffelica.h
+++ b/client/cmdhffelica.h
@@ -26,21 +26,21 @@
#include "cmdhf.h" // list cmd
#include "mifare.h" // felica_card_select_t struct
-extern int CmdHFFelica(const char *Cmd);
-extern int CmdHFFelicaList(const char *Cmd);
-extern int CmdHFFelicaReader(const char *Cmd);
-extern int CmdHFFelicaSim(const char *Cmd);
-extern int CmdHFFelicaSniff(const char *Cmd);
-extern int CmdHFFelicaCmdRaw(const char *Cmd);
+int CmdHFFelica(const char *Cmd);
+int CmdHFFelicaList(const char *Cmd);
+int CmdHFFelicaReader(const char *Cmd);
+int CmdHFFelicaSim(const char *Cmd);
+int CmdHFFelicaSniff(const char *Cmd);
+int CmdHFFelicaCmdRaw(const char *Cmd);
-extern int usage_hf_felica_sim(void);
-extern int usage_hf_felica_sniff(void);
-extern int usage_hf_fFelica_raw(void);
+int usage_hf_felica_sim(void);
+int usage_hf_felica_sniff(void);
+int usage_hf_fFelica_raw(void);
void waitCmdFelica(uint8_t iSelect);
//temp
-extern int CmdHFFelicaSimLite(const char *Cmd);
-extern int CmdHFFelicaDumpLite(const char *Cmd);
+int CmdHFFelicaSimLite(const char *Cmd);
+int CmdHFFelicaDumpLite(const char *Cmd);
#endif
diff --git a/client/cmdhffido.h b/client/cmdhffido.h
index 96f9153ed..b54f53118 100644
--- a/client/cmdhffido.h
+++ b/client/cmdhffido.h
@@ -21,7 +21,7 @@
#ifndef CMDHFFIDO_H__
#define CMDHFFIDO_H__
-extern int CmdHFFido(const char *Cmd);
+int CmdHFFido(const char *Cmd);
#endif
diff --git a/client/cmdhficlass.c b/client/cmdhficlass.c
index 39a25019c..5688fb8e1 100644
--- a/client/cmdhficlass.c
+++ b/client/cmdhficlass.c
@@ -405,7 +405,7 @@ int CmdHFiClassSim(const char *Cmd) {
break;
size_t datalen = NUM_CSNS * 24;
- void *dump = calloc(datalen, sizeof(uint8_t));
+ uint8_t *dump = calloc(datalen, sizeof(uint8_t));
if (!dump) {
PrintAndLogEx(WARNING, "Failed to allocate memory");
return 2;
@@ -458,7 +458,7 @@ int CmdHFiClassSim(const char *Cmd) {
break;
size_t datalen = NUM_CSNS * 24;
- void *dump = calloc(datalen, sizeof(uint8_t));
+ uint8_t *dump = calloc(datalen, sizeof(uint8_t));
if (!dump) {
PrintAndLogEx(WARNING, "Failed to allocate memory");
return 2;
@@ -636,7 +636,7 @@ int CmdHFiClassELoad(const char *Cmd) {
long fsize = ftell(f);
fseek(f, 0, SEEK_SET);
- if (fsize < 0) {
+ if (fsize <= 0) {
PrintAndLogDevice(WARNING, "error, when getting filesize");
fclose(f);
return 1;
@@ -729,7 +729,7 @@ int CmdHFiClassDecrypt(const char *Cmd) {
long fsize = ftell(f);
fseek(f, 0, SEEK_SET);
- if (fsize < 0) {
+ if (fsize <= 0) {
PrintAndLogEx(WARNING, "error, when getting filesize");
fclose(f);
return 2;
@@ -1109,7 +1109,7 @@ int CmdHFiClassReader_Dump(const char *Cmd) {
PrintAndLogEx(WARNING, "command execute timeout 2");
return 0;
}
- uint8_t isOK = resp.arg[0] & 0xff;
+ isOK = resp.arg[0] & 0xff;
blocksRead = resp.arg[1];
if (!isOK && !blocksRead) {
PrintAndLogEx(WARNING, "read block failed 2");
@@ -1609,7 +1609,7 @@ int CmdHFiClassReadTagFile(const char *Cmd) {
long fsize = ftell(f);
fseek(f, 0, SEEK_SET);
- if (fsize < 0) {
+ if (fsize <= 0) {
PrintAndLogEx(WARNING, "Error, when getting filesize");
fclose(f);
return 1;
@@ -1766,7 +1766,7 @@ static int loadKeys(char *filename) {
long fsize = ftell(f);
fseek(f, 0, SEEK_SET);
- if (fsize < 0) {
+ if (fsize <= 0) {
PrintAndLogEx(WARNING, "Error, when getting filesize");
fclose(f);
return 1;
@@ -2194,7 +2194,6 @@ int CmdHFiClassLookUp(const char *Cmd) {
}
cmdp += 2;
break;
- break;
case 'e':
use_elite = true;
cmdp++;
diff --git a/client/cmdhficlass.h b/client/cmdhficlass.h
index dff0d0b24..01dfd0076 100644
--- a/client/cmdhficlass.h
+++ b/client/cmdhficlass.h
@@ -52,29 +52,29 @@ typedef struct iclass_prekey {
int CmdHFiClass(const char *Cmd);
-extern int CmdHFiClassCalcNewKey(const char *Cmd);
-extern int CmdHFiClassCloneTag(const char *Cmd);
-extern int CmdHFiClassDecrypt(const char *Cmd);
-extern int CmdHFiClassEncryptBlk(const char *Cmd);
-extern int CmdHFiClassELoad(const char *Cmd);
-extern int CmdHFiClassList(const char *Cmd);
-extern int HFiClassReader(const char *Cmd, bool loop, bool verbose);
-extern int CmdHFiClassReader(const char *Cmd);
-extern int CmdHFiClassReader_Dump(const char *Cmd);
-extern int CmdHFiClassReader_Replay(const char *Cmd);
-extern int CmdHFiClassReadKeyFile(const char *filename);
-extern int CmdHFiClassReadTagFile(const char *Cmd);
-extern int CmdHFiClass_ReadBlock(const char *Cmd);
-extern int CmdHFiClass_TestMac(const char *Cmd);
-extern int CmdHFiClassManageKeys(const char *Cmd);
-extern int CmdHFiClass_loclass(const char *Cmd);
-extern int CmdHFiClassSniff(const char *Cmd);
-extern int CmdHFiClassSim(const char *Cmd);
-extern int CmdHFiClassWriteKeyFile(const char *Cmd);
-extern int CmdHFiClass_WriteBlock(const char *Cmd);
-extern int CmdHFiClassCheckKeys(const char *Cmd);
-extern int CmdHFiClassLookUp(const char *Cmd);
-extern int CmdHFiClassPermuteKey(const char *Cmd);
+int CmdHFiClassCalcNewKey(const char *Cmd);
+int CmdHFiClassCloneTag(const char *Cmd);
+int CmdHFiClassDecrypt(const char *Cmd);
+int CmdHFiClassEncryptBlk(const char *Cmd);
+int CmdHFiClassELoad(const char *Cmd);
+int CmdHFiClassList(const char *Cmd);
+int HFiClassReader(const char *Cmd, bool loop, bool verbose);
+int CmdHFiClassReader(const char *Cmd);
+int CmdHFiClassReader_Dump(const char *Cmd);
+int CmdHFiClassReader_Replay(const char *Cmd);
+int CmdHFiClassReadKeyFile(const char *filename);
+int CmdHFiClassReadTagFile(const char *Cmd);
+int CmdHFiClass_ReadBlock(const char *Cmd);
+int CmdHFiClass_TestMac(const char *Cmd);
+int CmdHFiClassManageKeys(const char *Cmd);
+int CmdHFiClass_loclass(const char *Cmd);
+int CmdHFiClassSniff(const char *Cmd);
+int CmdHFiClassSim(const char *Cmd);
+int CmdHFiClassWriteKeyFile(const char *Cmd);
+int CmdHFiClass_WriteBlock(const char *Cmd);
+int CmdHFiClassCheckKeys(const char *Cmd);
+int CmdHFiClassLookUp(const char *Cmd);
+int CmdHFiClassPermuteKey(const char *Cmd);
void printIclassDumpContents(uint8_t *iclass_dump, uint8_t startblock, uint8_t endblock, size_t filesize);
void HFiClassCalcDivKey(uint8_t *CSN, uint8_t *KEY, uint8_t *div_key, bool elite);
diff --git a/client/cmdhflegic.h b/client/cmdhflegic.h
index 6ee08253c..9bd8d98ac 100644
--- a/client/cmdhflegic.h
+++ b/client/cmdhflegic.h
@@ -26,19 +26,19 @@
int CmdHFLegic(const char *Cmd);
-extern int CmdLegicInfo(const char *Cmd);
-extern int CmdLegicRdmem(const char *Cmd);
-extern int CmdLegicLoad(const char *Cmd);
-extern int CmdLegicRfSim(const char *Cmd);
-extern int CmdLegicRfWrite(const char *Cmd);
-extern int CmdLegicCalcCrc(const char *Cmd);
-extern int CmdLegicDump(const char *Cmd);
-extern int CmdLegicRestore(const char *Cmd);
-extern int CmdLegicReader(const char *Cmd);
-extern int CmdLegicELoad(const char *Cmd);
-extern int CmdLegicESave(const char *Cmd);
-extern int CmdLegicList(const char *Cmd);
-extern int CmdLegicWipe(const char *Cmd);
+int CmdLegicInfo(const char *Cmd);
+int CmdLegicRdmem(const char *Cmd);
+int CmdLegicLoad(const char *Cmd);
+int CmdLegicRfSim(const char *Cmd);
+int CmdLegicRfWrite(const char *Cmd);
+int CmdLegicCalcCrc(const char *Cmd);
+int CmdLegicDump(const char *Cmd);
+int CmdLegicRestore(const char *Cmd);
+int CmdLegicReader(const char *Cmd);
+int CmdLegicELoad(const char *Cmd);
+int CmdLegicESave(const char *Cmd);
+int CmdLegicList(const char *Cmd);
+int CmdLegicWipe(const char *Cmd);
int HFLegicReader(const char *Cmd, bool verbose);
int legic_print_type(uint32_t tagtype, uint8_t spaces);
diff --git a/client/cmdhflist.h b/client/cmdhflist.h
index 105328b9b..35a5493ff 100644
--- a/client/cmdhflist.h
+++ b/client/cmdhflist.h
@@ -51,31 +51,32 @@ typedef struct {
uint32_t ks2; // ar ^ ar_enc
uint32_t ks3; // at ^ at_enc
} TAuthData;
-extern void ClearAuthData();
-extern uint8_t iso14443A_CRC_check(bool isResponse, uint8_t *d, uint8_t n);
-extern uint8_t iso14443B_CRC_check(uint8_t *d, uint8_t n);
-extern uint8_t mifare_CRC_check(bool isResponse, uint8_t *data, uint8_t len);
-extern uint8_t iso15693_CRC_check(uint8_t *d, uint8_t n);
-extern uint8_t iclass_CRC_check(bool isResponse, uint8_t *d, uint8_t n);
+void ClearAuthData();
+
+uint8_t iso14443A_CRC_check(bool isResponse, uint8_t *d, uint8_t n);
+uint8_t iso14443B_CRC_check(uint8_t *d, uint8_t n);
+uint8_t mifare_CRC_check(bool isResponse, uint8_t *data, uint8_t len);
+uint8_t iso15693_CRC_check(uint8_t *d, uint8_t n);
+uint8_t iclass_CRC_check(bool isResponse, uint8_t *d, uint8_t n);
int applyIso14443a(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize);
-extern void annotateIclass(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize);
-extern void annotateIso15693(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize);
-extern void annotateTopaz(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize);
-extern void annotateLegic(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize);
-extern void annotateFelica(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize);
-extern void annotateIso7816(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize);
-extern void annotateIso14443b(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize);
-extern void annotateIso14443a(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize);
-extern void annotateMfDesfire(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize);
-extern void annotateMifare(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize, uint8_t *parity, uint8_t paritysize, bool isResponse);
+void annotateIclass(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize);
+void annotateIso15693(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize);
+void annotateTopaz(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize);
+void annotateLegic(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize);
+void annotateFelica(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize);
+void annotateIso7816(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize);
+void annotateIso14443b(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize);
+void annotateIso14443a(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize);
+void annotateMfDesfire(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize);
+void annotateMifare(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize, uint8_t *parity, uint8_t paritysize, bool isResponse);
-extern bool DecodeMifareData(uint8_t *cmd, uint8_t cmdsize, uint8_t *parity, bool isResponse, uint8_t *mfData, size_t *mfDataLen);
-extern bool NTParityChk(TAuthData *ad, uint32_t ntx);
-extern bool NestedCheckKey(uint64_t key, TAuthData *ad, uint8_t *cmd, uint8_t cmdsize, uint8_t *parity);
-extern bool CheckCrypto1Parity(uint8_t *cmd_enc, uint8_t cmdsize, uint8_t *cmd, uint8_t *parity_enc);
-extern uint64_t GetCrypto1ProbableKey(TAuthData *ad);
+bool DecodeMifareData(uint8_t *cmd, uint8_t cmdsize, uint8_t *parity, bool isResponse, uint8_t *mfData, size_t *mfDataLen);
+bool NTParityChk(TAuthData *ad, uint32_t ntx);
+bool NestedCheckKey(uint64_t key, TAuthData *ad, uint8_t *cmd, uint8_t cmdsize, uint8_t *parity);
+bool CheckCrypto1Parity(uint8_t *cmd_enc, uint8_t cmdsize, uint8_t *cmd, uint8_t *parity_enc);
+uint64_t GetCrypto1ProbableKey(TAuthData *ad);
#endif // CMDHFLIST
diff --git a/client/cmdhfmf.c b/client/cmdhfmf.c
index 1a236cdc4..4706017cb 100644
--- a/client/cmdhfmf.c
+++ b/client/cmdhfmf.c
@@ -69,6 +69,10 @@ int usage_hf14_mf1ksim(void) {
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " h this help");
PrintAndLogEx(NORMAL, " u (Optional) UID 4,7 or 10bytes. If not specified, the UID 4b from emulator memory will be used");
+ PrintAndLogEx(NORMAL, " t (Optional) 0 = MIFARE Mini");
+ PrintAndLogEx(NORMAL, " 1 = MIFARE Classic 1k (Default)");
+ PrintAndLogEx(NORMAL, " 1 = MIFARE Classic 2k");
+ PrintAndLogEx(NORMAL, " 4 = MIFARE Classic 4k");
PrintAndLogEx(NORMAL, " n (Optional) Automatically exit simulation after blocks have been read by reader. 0 = infinite");
PrintAndLogEx(NORMAL, " i (Optional) Interactive, means that console will not be returned until simulation finishes or is aborted");
PrintAndLogEx(NORMAL, " x (Optional) Crack, performs the 'reader attack', nr/ar attack against a reader");
@@ -1056,7 +1060,7 @@ int CmdHF14AMfRestore(const char *Cmd) {
}
}
fclose(fdump);
- PrintAndLogEx(INFO, "Finish restore");
+ PrintAndLogEx(INFO, "Finish restore");
return 0;
}
@@ -1679,7 +1683,7 @@ int CmdHF14AMfChk_fast(const char *Cmd) {
PrintAndLogEx(SUCCESS, "Running strategy %u", strategy);
// main keychunk loop
- for (uint32_t i = 0; i < keycnt; i += chunksize) {
+ for (i = 0; i < keycnt; i += chunksize) {
if (ukbhit()) {
int gc = getchar();
@@ -1713,7 +1717,7 @@ out:
// check..
uint8_t found_keys = 0;
- for (uint8_t i = 0; i < sectorsCnt; ++i) {
+ for (i = 0; i < sectorsCnt; ++i) {
if (e_sector[i].foundKey[0])
found_keys++;
@@ -1730,7 +1734,7 @@ out:
if (transferToEml) {
uint8_t block[16] = {0x00};
- for (uint8_t i = 0; i < sectorsCnt; ++i) {
+ for ( i = 0; i < sectorsCnt; ++i) {
mfEmlGetMem(block, FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1, 1);
if (e_sector[i].foundKey[0])
num_to_bytes(e_sector[i].Key[0], 6, block);
@@ -1925,7 +1929,7 @@ int CmdHF14AMfChk(const char *Cmd) {
}
// empty e_sector
- for (int i = 0; i < SectorsCnt; ++i) {
+ for (i = 0; i < SectorsCnt; ++i) {
e_sector[i].Key[0] = 0xffffffffffff;
e_sector[i].Key[1] = 0xffffffffffff;
e_sector[i].foundKey[0] = false;
@@ -1944,7 +1948,7 @@ int CmdHF14AMfChk(const char *Cmd) {
for (trgKeyType = (keyType == 2) ? 0 : keyType; trgKeyType < 2; (keyType == 2) ? (++trgKeyType) : (trgKeyType = 2)) {
int b = blockNo;
- for (int i = 0; i < SectorsCnt; ++i) {
+ for (i = 0; i < SectorsCnt; ++i) {
// skip already found keys.
if (e_sector[i].foundKey[trgKeyType]) continue;
@@ -2018,7 +2022,7 @@ out:
if (transferToEml) {
uint8_t block[16] = {0x00};
- for (uint8_t i = 0; i < SectorsCnt; ++i) {
+ for (i = 0; i < SectorsCnt; ++i) {
mfEmlGetMem(block, FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1, 1);
if (e_sector[i].foundKey[0])
num_to_bytes(e_sector[i].Key[0], 6, block);
@@ -2132,7 +2136,7 @@ int CmdHF14AMf1kSim(const char *Cmd) {
uint8_t uid[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
uint8_t exitAfterNReads = 0;
- uint8_t flags = (FLAG_UID_IN_EMUL | FLAG_4B_UID_IN_DATA);
+ uint16_t flags = (FLAG_UID_IN_EMUL | FLAG_4B_UID_IN_DATA);
int uidlen = 0;
uint8_t cmdp = 0;
bool errors = false, verbose = false, setEmulatorMem = false;
@@ -2154,6 +2158,31 @@ int CmdHF14AMf1kSim(const char *Cmd) {
exitAfterNReads = param_get8(Cmd, cmdp + 1);
cmdp += 2;
break;
+ case 't':
+ switch (param_get8(Cmd, cmdp + 1)) {
+ case 0:
+ // Mifare MINI
+ flags |= FLAG_MF_MINI;
+ break;
+ case 1:
+ // Mifare Classic 1k
+ flags |= FLAG_MF_1K;
+ break;
+ case 2:
+ // Mifare Classic 2k
+ flags |= FLAG_MF_2K;
+ break;
+ case 4:
+ // Mifare Classic 4k
+ flags |= FLAG_MF_4K;
+ break;
+ default:
+ // Mifare Classic 1k
+ flags |= FLAG_MF_1K;
+ break;
+ }
+ cmdp += 2;
+ break;
case 'u':
param_gethex_ex(Cmd, cmdp + 1, uid, &uidlen);
switch (uidlen) {
diff --git a/client/cmdhfmf.h b/client/cmdhfmf.h
index 699aaa33e..0e471580b 100644
--- a/client/cmdhfmf.h
+++ b/client/cmdhfmf.h
@@ -33,41 +33,41 @@
#include "cliparser/cliparser.h" // argtable
#include "hardnested/hardnested_bf_core.h" // SetSIMDInstr
-extern int CmdHFMF(const char *Cmd);
+int CmdHFMF(const char *Cmd);
-extern int CmdHF14AMfList(const char *Cmd);
-extern int CmdHF14AMfDbg(const char *Cmd);
-extern int CmdHF14AMfRdBl(const char *Cmd);
-extern int CmdHF14AMfURdBl(const char *Cmd);
-extern int CmdHF14AMfRdSc(const char *Cmd);
-extern int CmdHF14SMfURdCard(const char *Cmd);
-extern int CmdHF14AMfDump(const char *Cmd);
-extern int CmdHF14AMfRestore(const char *Cmd);
-extern int CmdHF14AMfWrBl(const char *Cmd);
-extern int CmdHF14AMfUWrBl(const char *Cmd);
-extern int CmdHF14AMfChk(const char *Cmd);
-extern int CmdHF14AMfDarkside(const char *Cmd);
-extern int CmdHF14AMfNested(const char *Cmd);
-extern int CmdHF14AMfNestedHard(const char *Cmd);
-//extern int CmdHF14AMfSniff(const char* Cmd);
-extern int CmdHF14AMf1kSim(const char *Cmd);
-extern int CmdHF14AMfKeyBrute(const char *Cmd);
-extern int CmdHF14AMfEClear(const char *Cmd);
-extern int CmdHF14AMfEGet(const char *Cmd);
-extern int CmdHF14AMfESet(const char *Cmd);
-extern int CmdHF14AMfELoad(const char *Cmd);
-extern int CmdHF14AMfESave(const char *Cmd);
-extern int CmdHF14AMfECFill(const char *Cmd);
-extern int CmdHF14AMfEKeyPrn(const char *Cmd);
-extern int CmdHF14AMfCSetUID(const char *Cmd);
-extern int CmdHF14AMfCSetBlk(const char *Cmd);
-extern int CmdHF14AMfCGetBlk(const char *Cmd);
-extern int CmdHF14AMfCGetSc(const char *Cmd);
-extern int CmdHF14AMfCLoad(const char *Cmd);
-extern int CmdHF14AMfCSave(const char *Cmd);
-extern int CmdHf14MfDecryptBytes(const char *Cmd);
-extern int CmdHf14AMfSetMod(const char *Cmd);
-extern int CmdHf14AMfNack(const char *Cmd);
+int CmdHF14AMfList(const char *Cmd);
+int CmdHF14AMfDbg(const char *Cmd);
+int CmdHF14AMfRdBl(const char *Cmd);
+int CmdHF14AMfURdBl(const char *Cmd);
+int CmdHF14AMfRdSc(const char *Cmd);
+int CmdHF14SMfURdCard(const char *Cmd);
+int CmdHF14AMfDump(const char *Cmd);
+int CmdHF14AMfRestore(const char *Cmd);
+int CmdHF14AMfWrBl(const char *Cmd);
+int CmdHF14AMfUWrBl(const char *Cmd);
+int CmdHF14AMfChk(const char *Cmd);
+int CmdHF14AMfDarkside(const char *Cmd);
+int CmdHF14AMfNested(const char *Cmd);
+int CmdHF14AMfNestedHard(const char *Cmd);
+//int CmdHF14AMfSniff(const char* Cmd);
+int CmdHF14AMf1kSim(const char *Cmd);
+int CmdHF14AMfKeyBrute(const char *Cmd);
+int CmdHF14AMfEClear(const char *Cmd);
+int CmdHF14AMfEGet(const char *Cmd);
+int CmdHF14AMfESet(const char *Cmd);
+int CmdHF14AMfELoad(const char *Cmd);
+int CmdHF14AMfESave(const char *Cmd);
+int CmdHF14AMfECFill(const char *Cmd);
+int CmdHF14AMfEKeyPrn(const char *Cmd);
+int CmdHF14AMfCSetUID(const char *Cmd);
+int CmdHF14AMfCSetBlk(const char *Cmd);
+int CmdHF14AMfCGetBlk(const char *Cmd);
+int CmdHF14AMfCGetSc(const char *Cmd);
+int CmdHF14AMfCLoad(const char *Cmd);
+int CmdHF14AMfCSave(const char *Cmd);
+int CmdHf14MfDecryptBytes(const char *Cmd);
+int CmdHf14AMfSetMod(const char *Cmd);
+int CmdHf14AMfNack(const char *Cmd);
void showSectorTable(void);
void readerAttack(nonces_t data, bool setEmulatorMem, bool verbose);
diff --git a/client/cmdhfmfdes.h b/client/cmdhfmfdes.h
index 9aeb7dbeb..6f2f0fa3f 100644
--- a/client/cmdhfmfdes.h
+++ b/client/cmdhfmfdes.h
@@ -11,9 +11,9 @@
#define __MFDESFIRE_H
int CmdHFMFDes(const char *Cmd);
-int CmdHF14ADesAuth(const char *cmd);
-int CmdHF14ADesRb(const char *cmd);
-int CmdHF14ADesWb(const char *cmd);
+int CmdHF14ADesAuth(const char *Cmd);
+int CmdHF14ADesRb(const char *Cmd);
+int CmdHF14ADesWb(const char *Cmd);
int CmdHF14ADesInfo(const char *Cmd);
int CmdHF14ADesEnumApplications(const char *Cmd);
diff --git a/client/cmdhfmfdesfire.h b/client/cmdhfmfdesfire.h
index cc5481b0e..46737c684 100644
--- a/client/cmdhfmfdesfire.h
+++ b/client/cmdhfmfdesfire.h
@@ -1,5 +1,4 @@
-static int CmdHelp(const char *Cmd);
int CmdHF14AMfDESAuth(const char *Cmd);
int CmdHFMFDesfire(const char *Cmd);
int CmdHelp(const char *Cmd);
diff --git a/client/cmdhfmfhard.c b/client/cmdhfmfhard.c
index 415bcbaa2..99afc6b01 100644
--- a/client/cmdhfmfhard.c
+++ b/client/cmdhfmfhard.c
@@ -1284,7 +1284,6 @@ static void simulate_MFplus_RNG(uint32_t test_cuid, uint64_t test_key, uint32_t
}
-
static void simulate_acquire_nonces() {
time_t time1 = time(NULL);
last_sample_clock = 0;
@@ -1292,7 +1291,7 @@ static void simulate_acquire_nonces() {
hardnested_stage = CHECK_1ST_BYTES;
bool acquisition_completed = false;
uint32_t total_num_nonces = 0;
- float brute_force;
+ float brute_force_depth;
bool reported_suma8 = false;
cuid = (rand() & 0xff) << 24 | (rand() & 0xff) << 16 | (rand() & 0xff) << 8 | (rand() & 0xff);
@@ -1331,19 +1330,19 @@ static void simulate_acquire_nonces() {
apply_sum_a0();
}
update_nonce_data(true);
- acquisition_completed = shrink_key_space(&brute_force);
+ acquisition_completed = shrink_key_space(&brute_force_depth);
if (!reported_suma8) {
char progress_string[80];
sprintf(progress_string, "Apply Sum property. Sum(a0) = %d", sums[first_byte_Sum]);
- hardnested_print_progress(num_acquired_nonces, progress_string, brute_force, 0);
+ hardnested_print_progress(num_acquired_nonces, progress_string, brute_force_depth, 0);
reported_suma8 = true;
} else {
- hardnested_print_progress(num_acquired_nonces, "Apply bit flip properties", brute_force, 0);
+ hardnested_print_progress(num_acquired_nonces, "Apply bit flip properties", brute_force_depth, 0);
}
} else {
update_nonce_data(true);
- acquisition_completed = shrink_key_space(&brute_force);
- hardnested_print_progress(num_acquired_nonces, "Apply bit flip properties", brute_force, 0);
+ acquisition_completed = shrink_key_space(&brute_force_depth);
+ hardnested_print_progress(num_acquired_nonces, "Apply bit flip properties", brute_force_depth, 0);
}
} while (!acquisition_completed);
@@ -1366,10 +1365,9 @@ static int acquire_nonces(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_
bool field_off = false;
hardnested_stage = CHECK_1ST_BYTES;
bool acquisition_completed = false;
- uint32_t flags = 0;
uint8_t write_buf[9];
- uint32_t total_num_nonces = 0;
- float brute_force;
+ //uint32_t total_num_nonces = 0;
+ float brute_force_depth;
bool reported_suma8 = false;
char progress_text[80];
FILE *fnonces = NULL;
@@ -1380,7 +1378,7 @@ static int acquire_nonces(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_
clearCommandBuffer();
do {
- flags = 0;
+ uint32_t flags = 0;
flags |= initialize ? 0x0001 : 0;
flags |= slow ? 0x0002 : 0;
flags |= field_off ? 0x0004 : 0;
@@ -1395,9 +1393,9 @@ static int acquire_nonces(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_
if (initialize) {
if (!WaitForResponseTimeout(CMD_ACK, &resp, 3000)) {
//strange second call (iceman)
- UsbCommand c = {CMD_MIFARE_ACQUIRE_ENCRYPTED_NONCES, {blockNo + keyType * 0x100, trgBlockNo + trgKeyType * 0x100, 4}};
+ UsbCommand c1 = {CMD_MIFARE_ACQUIRE_ENCRYPTED_NONCES, {blockNo + keyType * 0x100, trgBlockNo + trgKeyType * 0x100, 4}};
clearCommandBuffer();
- SendCommand(&c);
+ SendCommand(&c1);
return 1;
}
if (resp.arg[0]) return resp.arg[0]; // error during nested_hard
@@ -1439,7 +1437,7 @@ static int acquire_nonces(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_
}
bufp += 9;
}
- total_num_nonces += num_sampled_nonces;
+ //total_num_nonces += num_sampled_nonces;
if (first_byte_num == 256) {
if (hardnested_stage == CHECK_1ST_BYTES) {
@@ -1453,19 +1451,19 @@ static int acquire_nonces(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_
apply_sum_a0();
}
update_nonce_data(true);
- acquisition_completed = shrink_key_space(&brute_force);
+ acquisition_completed = shrink_key_space(&brute_force_depth);
if (!reported_suma8) {
char progress_string[80];
sprintf(progress_string, "Apply Sum property. Sum(a0) = %d", sums[first_byte_Sum]);
- hardnested_print_progress(num_acquired_nonces, progress_string, brute_force, 0);
+ hardnested_print_progress(num_acquired_nonces, progress_string, brute_force_depth, 0);
reported_suma8 = true;
} else {
- hardnested_print_progress(num_acquired_nonces, "Apply bit flip properties", brute_force, 0);
+ hardnested_print_progress(num_acquired_nonces, "Apply bit flip properties", brute_force_depth, 0);
}
} else {
update_nonce_data(true);
- acquisition_completed = shrink_key_space(&brute_force);
- hardnested_print_progress(num_acquired_nonces, "Apply bit flip properties", brute_force, 0);
+ acquisition_completed = shrink_key_space(&brute_force_depth);
+ hardnested_print_progress(num_acquired_nonces, "Apply bit flip properties", brute_force_depth, 0);
}
}
@@ -1652,7 +1650,8 @@ static uint_fast8_t reverse(uint_fast8_t b) {
static bool all_bitflips_match(uint8_t byte, uint32_t state, odd_even_t odd_even) {
- uint32_t masks[2][8] = {{0x00fffff0, 0x00fffff8, 0x00fffff8, 0x00fffffc, 0x00fffffc, 0x00fffffe, 0x00fffffe, 0x00ffffff},
+ uint32_t masks[2][8] = {
+ {0x00fffff0, 0x00fffff8, 0x00fffff8, 0x00fffffc, 0x00fffffc, 0x00fffffe, 0x00fffffe, 0x00ffffff},
{0x00fffff0, 0x00fffff0, 0x00fffff8, 0x00fffff8, 0x00fffffc, 0x00fffffc, 0x00fffffe, 0x00fffffe}
};
@@ -1664,6 +1663,7 @@ static bool all_bitflips_match(uint8_t byte, uint32_t state, odd_even_t odd_even
bool found_match = false;
for (uint8_t remaining_bits = 0; remaining_bits <= (~mask & 0xff); remaining_bits++) {
if (remaining_bits_match(num_common, bytes_diff, state, (state & mask) | remaining_bits, odd_even)) {
+
#ifdef DEBUG_KEY_ELIMINATION
if (bitflips_match(byte2, (state & mask) | remaining_bits, odd_even, true)) {
#else
@@ -1674,7 +1674,9 @@ static bool all_bitflips_match(uint8_t byte, uint32_t state, odd_even_t odd_even
}
}
}
+
if (!found_match) {
+
#ifdef DEBUG_KEY_ELIMINATION
if (known_target_key != -1 && state == test_state[odd_even]) {
PrintAndLogEx(NORMAL, "all_bitflips_match() 1st Byte: %s test state (0x%06x): Eliminated. Bytes = %02x, %02x, Common Bits = %d\n",
@@ -1694,7 +1696,6 @@ static bool all_bitflips_match(uint8_t byte, uint32_t state, odd_even_t odd_even
return true;
}
-
static void bitarray_to_list(uint8_t byte, uint32_t *bitarray, uint32_t *state_list, uint32_t *len, odd_even_t odd_even) {
uint32_t *p = state_list;
for (uint32_t state = next_state(bitarray, -1L); state < (1 << 24); state = next_state(bitarray, state)) {
@@ -1716,7 +1717,7 @@ static void add_cached_states(statelist_t *candidates, uint16_t part_sum_a0, uin
static void add_matching_states(statelist_t *candidates, uint8_t part_sum_a0, uint8_t part_sum_a8, odd_even_t odd_even) {
- uint32_t worstcase_size = 1 << 20;
+ const uint32_t worstcase_size = 1 << 20;
candidates->states[odd_even] = (uint32_t *)malloc(sizeof(uint32_t) * worstcase_size);
if (candidates->states[odd_even] == NULL) {
PrintAndLogEx(WARNING, "Out of memory error in add_matching_states() - statelist.\n");
@@ -1773,28 +1774,26 @@ static statelist_t *add_more_candidates(void) {
return new_candidates;
}
-
static void add_bitflip_candidates(uint8_t byte) {
- statelist_t *candidates = add_more_candidates();
+ statelist_t *candidates1 = add_more_candidates();
for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) {
uint32_t worstcase_size = nonces[byte].num_states_bitarray[odd_even] + 1;
- candidates->states[odd_even] = (uint32_t *)malloc(sizeof(uint32_t) * worstcase_size);
- if (candidates->states[odd_even] == NULL) {
+ candidates1->states[odd_even] = (uint32_t *)malloc(sizeof(uint32_t) * worstcase_size);
+ if (candidates1->states[odd_even] == NULL) {
PrintAndLogEx(WARNING, "Out of memory error in add_bitflip_candidates().\n");
exit(4);
}
- bitarray_to_list(byte, nonces[byte].states_bitarray[odd_even], candidates->states[odd_even], &(candidates->len[odd_even]), odd_even);
+ bitarray_to_list(byte, nonces[byte].states_bitarray[odd_even], candidates1->states[odd_even], &(candidates1->len[odd_even]), odd_even);
- if (candidates->len[odd_even] + 1 < worstcase_size) {
- candidates->states[odd_even] = realloc(candidates->states[odd_even], sizeof(uint32_t) * (candidates->len[odd_even] + 1));
+ if (candidates1->len[odd_even] + 1 < worstcase_size) {
+ candidates1->states[odd_even] = realloc(candidates1->states[odd_even], sizeof(uint32_t) * (candidates1->len[odd_even] + 1));
}
}
return;
}
-
static bool TestIfKeyExists(uint64_t key) {
struct Crypto1State *pcs;
pcs = crypto1_create(key);
@@ -1840,7 +1839,6 @@ static bool TestIfKeyExists(uint64_t key) {
return false;
}
-
static work_status_t book_of_work[NUM_PART_SUMS][NUM_PART_SUMS][NUM_PART_SUMS][NUM_PART_SUMS];
static void init_book_of_work(void) {
@@ -2014,12 +2012,12 @@ static void generate_candidates(uint8_t sum_a0_idx, uint8_t sum_a8_idx) {
// create and run worker threads
pthread_t thread_id[NUM_REDUCTION_WORKING_THREADS];
- uint16_t sums[NUM_REDUCTION_WORKING_THREADS][3];
+ uint16_t sums1[NUM_REDUCTION_WORKING_THREADS][3];
for (uint16_t i = 0; i < NUM_REDUCTION_WORKING_THREADS; i++) {
- sums[i][0] = sum_a0_idx;
- sums[i][1] = sum_a8_idx;
- sums[i][2] = i + 1;
- pthread_create(thread_id + i, NULL, generate_candidates_worker_thread, sums[i]);
+ sums1[i][0] = sum_a0_idx;
+ sums1[i][1] = sum_a8_idx;
+ sums1[i][2] = i + 1;
+ pthread_create(thread_id + i, NULL, generate_candidates_worker_thread, sums1[i]);
}
// wait for threads to terminate:
@@ -2046,7 +2044,6 @@ static void generate_candidates(uint8_t sum_a0_idx, uint8_t sum_a8_idx) {
hardnested_print_progress(num_acquired_nonces, "Apply Sum(a8) and all bytes bitflip properties", nonces[best_first_bytes[0]].expected_num_brute_force, 0);
}
-
static void free_candidates_memory(statelist_t *sl) {
if (sl == NULL)
return;
@@ -2055,7 +2052,6 @@ static void free_candidates_memory(statelist_t *sl) {
free(sl);
}
-
static void pre_XOR_nonces(void) {
// prepare acquired nonces for faster brute forcing.
@@ -2086,56 +2082,51 @@ static uint16_t SumProperty(struct Crypto1State *s) {
return (sum_odd * (16 - sum_even) + (16 - sum_odd) * sum_even);
}
-
static void Tests() {
- if (known_target_key != -1) {
- for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) {
- uint32_t *bitset = nonces[best_first_bytes[0]].states_bitarray[odd_even];
- if (!test_bit24(bitset, test_state[odd_even])) {
- PrintAndLogEx(NORMAL, "\nBUG: known target key's %s state is not member of first nonce byte's (0x%02x) states_bitarray!\n",
- odd_even == EVEN_STATE ? "even" : "odd ",
- best_first_bytes[0]);
- }
+
+ if (known_target_key == -1)
+ return;
+
+ for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) {
+ uint32_t *bitset = nonces[best_first_bytes[0]].states_bitarray[odd_even];
+ if (!test_bit24(bitset, test_state[odd_even])) {
+ PrintAndLogEx(NORMAL, "\nBUG: known target key's %s state is not member of first nonce byte's (0x%02x) states_bitarray!\n",
+ odd_even == EVEN_STATE ? "even" : "odd ",
+ best_first_bytes[0]);
}
}
-
- if (known_target_key != -1) {
- for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) {
- uint32_t *bitset = all_bitflips_bitarray[odd_even];
- if (!test_bit24(bitset, test_state[odd_even])) {
- PrintAndLogEx(NORMAL, "\nBUG: known target key's %s state is not member of all_bitflips_bitarray!\n",
- odd_even == EVEN_STATE ? "even" : "odd ");
- }
+ for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) {
+ uint32_t *bitset = all_bitflips_bitarray[odd_even];
+ if (!test_bit24(bitset, test_state[odd_even])) {
+ PrintAndLogEx(NORMAL, "\nBUG: known target key's %s state is not member of all_bitflips_bitarray!\n",
+ odd_even == EVEN_STATE ? "even" : "odd ");
}
}
}
-
static void Tests2(void) {
- if (known_target_key != -1) {
- for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) {
- uint32_t *bitset = nonces[best_first_byte_smallest_bitarray].states_bitarray[odd_even];
- if (!test_bit24(bitset, test_state[odd_even])) {
- PrintAndLogEx(NORMAL, "\nBUG: known target key's %s state is not member of first nonce byte's (0x%02x) states_bitarray!\n",
- odd_even == EVEN_STATE ? "even" : "odd ",
- best_first_byte_smallest_bitarray);
- }
+
+ if (known_target_key == -1)
+ return;
+
+ for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) {
+ uint32_t *bitset = nonces[best_first_byte_smallest_bitarray].states_bitarray[odd_even];
+ if (!test_bit24(bitset, test_state[odd_even])) {
+ PrintAndLogEx(NORMAL, "\nBUG: known target key's %s state is not member of first nonce byte's (0x%02x) states_bitarray!\n",
+ odd_even == EVEN_STATE ? "even" : "odd ",
+ best_first_byte_smallest_bitarray);
}
}
-
- if (known_target_key != -1) {
- for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) {
- uint32_t *bitset = all_bitflips_bitarray[odd_even];
- if (!test_bit24(bitset, test_state[odd_even])) {
- PrintAndLogEx(NORMAL, "\nBUG: known target key's %s state is not member of all_bitflips_bitarray!\n",
- odd_even == EVEN_STATE ? "even" : "odd ");
- }
+
+ for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) {
+ uint32_t *bitset = all_bitflips_bitarray[odd_even];
+ if (!test_bit24(bitset, test_state[odd_even])) {
+ PrintAndLogEx(NORMAL, "\nBUG: known target key's %s state is not member of all_bitflips_bitarray!\n",
+ odd_even == EVEN_STATE ? "even" : "odd ");
}
}
-
}
-
static uint16_t real_sum_a8 = 0;
static void set_test_state(uint8_t byte) {
@@ -2148,7 +2139,6 @@ static void set_test_state(uint8_t byte) {
crypto1_destroy(pcs);
}
-
int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *trgkey, bool nonce_file_read, bool nonce_file_write, bool slow, int tests, uint64_t *foundkey, char *filename) {
char progress_text[80];
char instr_set[12] = {0};
@@ -2176,6 +2166,7 @@ int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBloc
hardnested_print_progress(0, progress_text, (float)(1LL << 47), 0);
sprintf(progress_text, "Starting Test #%" PRIu32 " ...", i + 1);
hardnested_print_progress(0, progress_text, (float)(1LL << 47), 0);
+
if (trgkey != NULL) {
known_target_key = bytes_to_num(trgkey, 6);
} else {
@@ -2257,9 +2248,18 @@ int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBloc
}
}
#ifdef DEBUG_KEY_ELIMINATION
- fprintf(fstats, "%1.1f;%1.0f;%d;%s\n", log(num_keys_tested) / log(2.0), (float)num_keys_tested / brute_force_per_second, key_found, failstr);
+ fprintf(fstats, "%1.1f;%1.0f;%c;%s\n",
+ log(num_keys_tested) / log(2.0),
+ (float)num_keys_tested / brute_force_per_second,
+ key_found ? 'Y' : 'N',
+ failstr
+ );
#else
- fprintf(fstats, "%1.0f;%d\n", log(num_keys_tested) / log(2.0), (float)num_keys_tested / brute_force_per_second, key_found);
+ fprintf(fstats, "%1.0f;%d\n",
+ log(num_keys_tested) / log(2.0),
+ (float)num_keys_tested / brute_force_per_second,
+ key_found
+ );
#endif
free_nonces_memory();
@@ -2293,8 +2293,8 @@ int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBloc
}
hardnested_stage = CHECK_1ST_BYTES | CHECK_2ND_BYTES;
update_nonce_data(false);
- float brute_force;
- shrink_key_space(&brute_force);
+ float brute_force_depth;
+ shrink_key_space(&brute_force_depth);
} else { // acquire nonces.
uint16_t is_OK = acquire_nonces(blockNo, keyType, key, trgBlockNo, trgKeyType, nonce_file_write, slow, filename);
if (is_OK != 0) {
@@ -2304,7 +2304,6 @@ int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBloc
free_bitarray(all_bitflips_bitarray[EVEN_STATE]);
free_sum_bitarrays();
free_part_sum_bitarrays();
-
return is_OK;
}
}
@@ -2373,7 +2372,6 @@ int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBloc
// and calculate new expected number of brute forces
update_expected_brute_force(best_first_bytes[0]);
}
-
}
}
@@ -2383,6 +2381,5 @@ int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBloc
free_sum_bitarrays();
free_part_sum_bitarrays();
}
-
return 0;
}
diff --git a/client/cmdhfmfhard.h b/client/cmdhfmfhard.h
index e39358c7f..7d3e4fa0b 100644
--- a/client/cmdhfmfhard.h
+++ b/client/cmdhfmfhard.h
@@ -41,8 +41,8 @@ typedef struct noncelist {
noncelistentry_t *first;
} noncelist_t;
-extern int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *trgkey, bool nonce_file_read, bool nonce_file_write, bool slow, int tests, uint64_t *foundkey, char *filename);
-extern void hardnested_print_progress(uint32_t nonces, char *activity, float brute_force, uint64_t min_diff_print_time);
+int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *trgkey, bool nonce_file_read, bool nonce_file_write, bool slow, int tests, uint64_t *foundkey, char *filename);
+void hardnested_print_progress(uint32_t nonces, char *activity, float brute_force, uint64_t min_diff_print_time);
#endif
diff --git a/client/cmdhfmfp.c b/client/cmdhfmfp.c
index 7178591a2..942000755 100644
--- a/client/cmdhfmfp.c
+++ b/client/cmdhfmfp.c
@@ -385,7 +385,7 @@ int CmdHFMFPRdbl(const char *cmd) {
}
if (blocksCount > 1 && mfIsSectorTrailer(blockn)) {
- PrintAndLog("WARNING: trailer!");
+ PrintAndLogEx(WARNING, "WARNING: trailer!");
}
uint8_t sectorNum = mfSectorNum(blockn & 0xff);
diff --git a/client/cmdhfmfp.h b/client/cmdhfmfp.h
index ed9d36b79..76917315b 100644
--- a/client/cmdhfmfp.h
+++ b/client/cmdhfmfp.h
@@ -12,7 +12,7 @@
#include "mifare/mifaredefault.h"
-extern int CmdHFMFP(const char *Cmd);
+int CmdHFMFP(const char *Cmd);
#endif
diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c
index 956cc1a70..45c67bcb3 100644
--- a/client/cmdhfmfu.c
+++ b/client/cmdhfmfu.c
@@ -1134,8 +1134,6 @@ int CmdHF14AMfUInfo(const char *Cmd) {
// hasAuthKey, if we was called with key, skip test.
if (!authlim && !hasAuthKey) {
PrintAndLogEx(NORMAL, "\n--- Known EV1/NTAG passwords.");
- len = 0;
-
// test pwd gen A
num_to_bytes(ul_ev1_pwdgenA(card.uid), 4, key);
len = ulev1_requestAuthentication(key, pack, sizeof(pack));
@@ -2078,7 +2076,7 @@ int CmdHF14AMfURestore(const char *Cmd) {
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
fseek(f, 0, SEEK_SET);
- if (fsize < 0) {
+ if (fsize <= 0) {
PrintAndLogEx(WARNING, "Error, when getting filesize");
fclose(f);
return 1;
@@ -2223,7 +2221,7 @@ int CmdHF14AMfURestore(const char *Cmd) {
DropField();
free(dump);
- PrintAndLogEx(INFO, "Finish restore");
+ PrintAndLogEx(INFO, "Finish restore");
return 0;
}
//
diff --git a/client/cmdhfmfu.h b/client/cmdhfmfu.h
index 6be4beb6c..28f79d086 100644
--- a/client/cmdhfmfu.h
+++ b/client/cmdhfmfu.h
@@ -25,40 +25,40 @@ typedef struct {
uint8_t data[1024];
} mfu_dump_t;
-extern int CmdHF14AMfUWrBl(const char *Cmd);
-extern int CmdHF14AMfURdBl(const char *Cmd);
+int CmdHF14AMfUWrBl(const char *Cmd);
+int CmdHF14AMfURdBl(const char *Cmd);
//Crypto Cards
-extern int CmdHF14AMfucAuth(const char *Cmd);
-extern int CmdHF14AMfucSetPwd(const char *Cmd);
-extern int CmdHF14AMfucSetUid(const char *Cmd);
-extern int CmdHF14AMfuGenDiverseKeys(const char *Cmd);
-extern int CmdHF14AMfuPwdGen(const char *Cmd);
+int CmdHF14AMfucAuth(const char *Cmd);
+int CmdHF14AMfucSetPwd(const char *Cmd);
+int CmdHF14AMfucSetUid(const char *Cmd);
+int CmdHF14AMfuGenDiverseKeys(const char *Cmd);
+int CmdHF14AMfuPwdGen(const char *Cmd);
//general stuff
-extern int CmdHF14AMfUDump(const char *Cmd);
-extern int CmdHF14AMfURestore(const char *Cmd);
-extern int CmdHF14AMfUInfo(const char *Cmd);
-extern int CmdHF14AMfUeLoad(const char *Cmd);
-extern int CmdHF14AMfUSim(const char *Cmd);
+int CmdHF14AMfUDump(const char *Cmd);
+int CmdHF14AMfURestore(const char *Cmd);
+int CmdHF14AMfUInfo(const char *Cmd);
+int CmdHF14AMfUeLoad(const char *Cmd);
+int CmdHF14AMfUSim(const char *Cmd);
-extern uint32_t GetHF14AMfU_Type(void);
-extern int ul_print_type(uint32_t tagtype, uint8_t spacer);
+uint32_t GetHF14AMfU_Type(void);
+int ul_print_type(uint32_t tagtype, uint8_t spaces);
void printMFUdump(mfu_dump_t *card);
void printMFUdumpEx(mfu_dump_t *card, uint16_t pages, uint8_t startpage);
-extern int usage_hf_mfu_info(void);
-extern int usage_hf_mfu_dump(void);
-extern int usage_hf_mfu_rdbl(void);
-extern int usage_hf_mfu_wrbl(void);
-extern int usage_hf_mfu_eload(void);
-extern int usage_hf_mfu_sim(void);
-extern int usage_hf_mfu_ucauth(void);
-extern int usage_hf_mfu_ucsetpwd(void);
-extern int usage_hf_mfu_ucsetuid(void);
-extern int usage_hf_mfu_gendiverse(void);
-extern int usage_hf_mfu_pwdgen(void);
+int usage_hf_mfu_info(void);
+int usage_hf_mfu_dump(void);
+int usage_hf_mfu_rdbl(void);
+int usage_hf_mfu_wrbl(void);
+int usage_hf_mfu_eload(void);
+int usage_hf_mfu_sim(void);
+int usage_hf_mfu_ucauth(void);
+int usage_hf_mfu_ucsetpwd(void);
+int usage_hf_mfu_ucsetuid(void);
+int usage_hf_mfu_gendiverse(void);
+int usage_hf_mfu_pwdgen(void);
int CmdHFMFUltra(const char *Cmd);
diff --git a/client/cmdhftopaz.h b/client/cmdhftopaz.h
index e6ba1bdcb..551031778 100644
--- a/client/cmdhftopaz.h
+++ b/client/cmdhftopaz.h
@@ -25,10 +25,10 @@
#include "protocols.h"
#include "cmdhf.h"
-extern int CmdHFTopaz(const char *Cmd);
-extern int CmdHFTopazReader(const char *Cmd);
-extern int CmdHFTopazSim(const char *Cmd);
-extern int CmdHFTopazCmdRaw(const char *Cmd);
-extern int CmdHFTopazList(const char *Cmd);
+int CmdHFTopaz(const char *Cmd);
+int CmdHFTopazReader(const char *Cmd);
+int CmdHFTopazSim(const char *Cmd);
+int CmdHFTopazCmdRaw(const char *Cmd);
+int CmdHFTopazList(const char *Cmd);
#endif
diff --git a/client/cmdlf.c b/client/cmdlf.c
index 263e73749..1246b5f04 100644
--- a/client/cmdlf.c
+++ b/client/cmdlf.c
@@ -228,7 +228,7 @@ int CmdFlexdemod(const char *Cmd) {
i = start;
for (bit = 0; bit < 64; bit++) {
sum = 0;
- for (int j = 0; j < 16; j++) {
+ for (j = 0; j < 16; j++) {
sum += data[i++];
}
bits[bit] = (sum > 0) ? 1 : 0;
@@ -509,7 +509,7 @@ int CmdLFfskSim(const char *Cmd) {
}
}
} else {
- setDemodBuf(data, dataLen, 0);
+ setDemodBuff(data, dataLen, 0);
}
//default if not found
@@ -603,7 +603,7 @@ int CmdLFaskSim(const char *Cmd) {
if (clk == 0)
clk = GetAskClock("0", false);
} else {
- setDemodBuf(data, dataLen, 0);
+ setDemodBuff(data, dataLen, 0);
}
if (clk == 0) clk = 64;
if (encoding == 0) clk /= 2; //askraw needs to double the clock speed
@@ -704,7 +704,7 @@ int CmdLFpskSim(const char *Cmd) {
PrintAndLogEx(NORMAL, "carrier: %d", carrier);
} else {
- setDemodBuf(data, dataLen, 0);
+ setDemodBuff(data, dataLen, 0);
}
if (clk == 0) clk = 32;
diff --git a/client/cmdlf.h b/client/cmdlf.h
index ca3de7eb4..bf914d21a 100644
--- a/client/cmdlf.h
+++ b/client/cmdlf.h
@@ -55,28 +55,28 @@
int CmdLF(const char *Cmd);
-extern int CmdLFSetConfig(const char *Cmd);
+int CmdLFSetConfig(const char *Cmd);
-extern int CmdLFCommandRead(const char *Cmd);
-extern int CmdFlexdemod(const char *Cmd);
-extern int CmdLFRead(const char *Cmd);
-extern int CmdLFSim(const char *Cmd);
-extern int CmdLFaskSim(const char *Cmd);
-extern int CmdLFfskSim(const char *Cmd);
-extern int CmdLFpskSim(const char *Cmd);
-extern int CmdLFSimBidir(const char *Cmd);
-extern int CmdLFSniff(const char *Cmd);
-extern int CmdVchDemod(const char *Cmd);
-extern int CmdLFfind(const char *Cmd);
+int CmdLFCommandRead(const char *Cmd);
+int CmdFlexdemod(const char *Cmd);
+int CmdLFRead(const char *Cmd);
+int CmdLFSim(const char *Cmd);
+int CmdLFaskSim(const char *Cmd);
+int CmdLFfskSim(const char *Cmd);
+int CmdLFpskSim(const char *Cmd);
+int CmdLFSimBidir(const char *Cmd);
+int CmdLFSniff(const char *Cmd);
+int CmdVchDemod(const char *Cmd);
+int CmdLFfind(const char *Cmd);
-extern bool lf_read(bool silent, uint32_t samples);
+bool lf_read(bool silent, uint32_t samples);
// usages helptext
-extern int usage_lf_cmdread(void);
-extern int usage_lf_read(void);
-extern int usage_lf_sniff(void);
-extern int usage_lf_config(void);
-extern int usage_lf_simfsk(void);
-extern int usage_lf_simask(void);
-extern int usage_lf_simpsk(void);
+int usage_lf_cmdread(void);
+int usage_lf_read(void);
+int usage_lf_sniff(void);
+int usage_lf_config(void);
+int usage_lf_simfsk(void);
+int usage_lf_simask(void);
+int usage_lf_simpsk(void);
#endif
diff --git a/client/cmdlfawid.c b/client/cmdlfawid.c
index 72fc913da..72bd48a07 100644
--- a/client/cmdlfawid.c
+++ b/client/cmdlfawid.c
@@ -267,7 +267,7 @@ int CmdAWIDDemod(const char *Cmd) {
return 0;
}
- setDemodBuf(bits, size, idx);
+ setDemodBuff(bits, size, idx);
setClockGrid(50, waveIdx + (idx * 50));
diff --git a/client/cmdlfawid.h b/client/cmdlfawid.h
index edee0473c..e971225e2 100644
--- a/client/cmdlfawid.h
+++ b/client/cmdlfawid.h
@@ -24,17 +24,17 @@
#include "util_posix.h"
-extern int CmdLFAWID(const char *Cmd);
-extern int CmdAWIDDemod(const char *Cmd);
-extern int CmdAWIDRead(const char *Cmd);
-extern int CmdAWIDSim(const char *Cmd);
-extern int CmdAWIDClone(const char *Cmd);
-extern int CmdAWIDBrute(const char *Cmd);
-extern int getAWIDBits(uint8_t fmtlen, uint32_t fc, uint32_t cn, uint8_t *bits);
+int CmdLFAWID(const char *Cmd);
+int CmdAWIDDemod(const char *Cmd);
+int CmdAWIDRead(const char *Cmd);
+int CmdAWIDSim(const char *Cmd);
+int CmdAWIDClone(const char *Cmd);
+int CmdAWIDBrute(const char *Cmd);
+int getAWIDBits(uint8_t fmtlen, uint32_t fc, uint32_t cn, uint8_t *bits);
-extern int usage_lf_awid_read(void);
-extern int usage_lf_awid_sim(void);
-extern int usage_lf_awid_clone(void);
-extern int usage_lf_awid_brute(void);
+int usage_lf_awid_read(void);
+int usage_lf_awid_sim(void);
+int usage_lf_awid_clone(void);
+int usage_lf_awid_brute(void);
#endif
diff --git a/client/cmdlfcotag.c b/client/cmdlfcotag.c
index ec26c89ff..53b0d0451 100644
--- a/client/cmdlfcotag.c
+++ b/client/cmdlfcotag.c
@@ -40,7 +40,7 @@ int CmdCOTAGDemod(const char *Cmd) {
return -1;
}
- setDemodBuf(bits, bitlen, 0);
+ setDemodBuff(bits, bitlen, 0);
//got a good demod
uint16_t cn = bytebits_to_byteLSBF(bits + 1, 16);
diff --git a/client/cmdlfcotag.h b/client/cmdlfcotag.h
index b774b12a8..7b0922019 100644
--- a/client/cmdlfcotag.h
+++ b/client/cmdlfcotag.h
@@ -23,9 +23,9 @@
#define COTAG_BITS 264
#endif
-extern int CmdLFCOTAG(const char *Cmd);
-extern int CmdCOTAGRead(const char *Cmd);
-extern int CmdCOTAGDemod(const char *Cmd);
+int CmdLFCOTAG(const char *Cmd);
+int CmdCOTAGRead(const char *Cmd);
+int CmdCOTAGDemod(const char *Cmd);
-extern int usage_lf_cotag_read(void);
+int usage_lf_cotag_read(void);
#endif
diff --git a/client/cmdlfem4x.c b/client/cmdlfem4x.c
index e6da5da33..e9998269d 100644
--- a/client/cmdlfem4x.c
+++ b/client/cmdlfem4x.c
@@ -254,13 +254,12 @@ void printEM410x(uint32_t hi, uint64_t id) {
PrintAndLogEx(SUCCESS, "EM410x %s pattern found", (hi) ? "XL" : "");
- uint64_t iii = 1;
+ uint64_t n = 1;
uint64_t id2lo = 0;
- uint32_t ii = 0;
- uint32_t i = 0;
- for (ii = 5; ii > 0; ii--) {
+ uint8_t m, i = 0;
+ for (m = 5; m > 0; m--) {
for (i = 0; i < 8; i++) {
- id2lo = (id2lo << 1LL) | ((id & (iii << (i + ((ii - 1) * 8)))) >> (i + ((ii - 1) * 8)));
+ id2lo = (id2lo << 1LL) | ((id & (n << (i + ((m - 1) * 8)))) >> (i + ((m - 1) * 8)));
}
}
@@ -299,10 +298,9 @@ void printEM410x(uint32_t hi, uint64_t id) {
uint32_t p1id = (id & 0xFFFFFF);
uint8_t arr[32] = {0x00};
- int i = 0;
int j = 23;
- for (; i < 24; ++i, --j) {
- arr[i] = (p1id >> i) & 1;
+ for (int k = 0 ; k < 24; ++k, --j) {
+ arr[k] = (p1id >> k) & 1;
}
uint32_t p1 = 0;
@@ -356,7 +354,7 @@ int AskEm410xDecode(bool verbose, uint32_t *hi, uint64_t *lo) {
size_t idx = 0;
uint8_t bits[512] = {0};
size_t size = sizeof(bits);
- if (!getDemodBuf(bits, &size)) {
+ if (!getDemodBuff(bits, &size)) {
PrintAndLogEx(DEBUG, "DEBUG: Error - Em410x problem during copy from ASK demod");
return 0;
}
@@ -381,7 +379,7 @@ int AskEm410xDecode(bool verbose, uint32_t *hi, uint64_t *lo) {
}
//set GraphBuffer for clone or sim command
- setDemodBuf(DemodBuffer, (size == 40) ? 64 : 128, idx + 1);
+ setDemodBuff(DemodBuffer, (size == 40) ? 64 : 128, idx + 1);
setClockGrid(g_DemodClock, g_DemodStartIdx + ((idx + 1)*g_DemodClock));
PrintAndLogEx(DEBUG, "DEBUG: Em410x idx: %d, Len: %d, Printing Demod Buffer:", idx, size);
@@ -1109,7 +1107,7 @@ bool setDemodBufferEM(uint32_t *word, size_t idx) {
PrintAndLogEx(DEBUG, "DEBUG: Error - EM, failed removing parity");
return false;
}
- setDemodBuf(DemodBuffer, 32, 0);
+ setDemodBuff(DemodBuffer, 32, 0);
*word = bytebits_to_byteLSBF(DemodBuffer, 32);
return true;
}
@@ -1225,9 +1223,8 @@ int CmdEM4x05Write(const char *Cmd) {
if (strlen(Cmd) == 0 || ctmp == 'h') return usage_lf_em4x05_write();
bool usePwd = false;
- uint8_t addr = 50; // default to invalid address
- uint32_t data = 0; // default to blank data
- uint32_t pwd = 1; // default to blank password
+ uint8_t addr;
+ uint32_t data, pwd;
addr = param_get8ex(Cmd, 0, 50, 10);
data = param_get32ex(Cmd, 1, 0, 16);
diff --git a/client/cmdlfem4x.h b/client/cmdlfem4x.h
index d01dedc57..383b9fa57 100644
--- a/client/cmdlfem4x.h
+++ b/client/cmdlfem4x.h
@@ -25,44 +25,43 @@
#include "cmdlf.h"
#include "lfdemod.h"
-extern int CmdLFEM4X(const char *Cmd);
+int CmdLFEM4X(const char *Cmd);
+int CmdEM410xDemod(const char *Cmd);
+int CmdEM410xRead(const char *Cmd);
+int CmdEM410xSim(const char *Cmd);
+int CmdEM410xBrute(const char *Cmd);
+int CmdEM410xWatch(const char *Cmd);
+int CmdEM410xWatchnSpoof(const char *Cmd);
+int CmdEM410xWrite(const char *Cmd);
+int CmdEM4x05Dump(const char *Cmd);
+int CmdEM4x05Info(const char *Cmd);
+int CmdEM4x05Read(const char *Cmd);
+int CmdEM4x05Write(const char *Cmd);
+int CmdEM4x50Read(const char *Cmd);
+int CmdEM4x50Write(const char *Cmd);
+int CmdEM4x50Dump(const char *Cmd);
-extern int CmdEM410xDemod(const char *Cmd);
-extern int CmdEM410xRead(const char *Cmd);
-extern int CmdEM410xSim(const char *Cmd);
-extern int CmdEM410xBrute(const char *Cmd);
-extern int CmdEM410xWatch(const char *Cmd);
-extern int CmdEM410xWatchnSpoof(const char *Cmd);
-extern int CmdEM410xWrite(const char *Cmd);
-extern int CmdEM4x05Dump(const char *Cmd);
-extern int CmdEM4x05Info(const char *Cmd);
-extern int CmdEM4x05Read(const char *Cmd);
-extern int CmdEM4x05Write(const char *Cmd);
-extern int CmdEM4x50Read(const char *Cmd);
-extern int CmdEM4x50Write(const char *Cmd);
-extern int CmdEM4x50Dump(const char *Cmd);
-
-extern int EM4x50Read(const char *Cmd, bool verbose);
+int EM4x50Read(const char *Cmd, bool verbose);
bool EM4x05IsBlock0(uint32_t *word);
-extern void printEM410x(uint32_t hi, uint64_t id);
-extern int AskEm410xDecode(bool verbose, uint32_t *hi, uint64_t *lo);
-extern int AskEm410xDemod(const char *Cmd, uint32_t *hi, uint64_t *lo, bool verbose);
+void printEM410x(uint32_t hi, uint64_t id);
+int AskEm410xDecode(bool verbose, uint32_t *hi, uint64_t *lo);
+int AskEm410xDemod(const char *Cmd, uint32_t *hi, uint64_t *lo, bool verbose);
-extern int usage_lf_em410x_sim(void);
-extern int usage_lf_em410x_ws(void);
-extern int usage_lf_em410x_clone(void);
-extern int usage_lf_em410x_sim(void);
-extern int usage_lf_em410x_brute(void);
+int usage_lf_em410x_sim(void);
+int usage_lf_em410x_ws(void);
+int usage_lf_em410x_clone(void);
+int usage_lf_em410x_sim(void);
+int usage_lf_em410x_brute(void);
-extern int usage_lf_em4x50_dump(void);
-extern int usage_lf_em4x50_read(void);
-extern int usage_lf_em4x50_write(void);
+int usage_lf_em4x50_dump(void);
+int usage_lf_em4x50_read(void);
+int usage_lf_em4x50_write(void);
-extern int usage_lf_em4x05_dump(void);
-extern int usage_lf_em4x05_read(void);
-extern int usage_lf_em4x05_write(void);
-extern int usage_lf_em4x05_info(void);
+int usage_lf_em4x05_dump(void);
+int usage_lf_em4x05_read(void);
+int usage_lf_em4x05_write(void);
+int usage_lf_em4x05_info(void);
#endif
diff --git a/client/cmdlffdx.c b/client/cmdlffdx.c
index 972ef9627..46dd0c8ca 100644
--- a/client/cmdlffdx.c
+++ b/client/cmdlffdx.c
@@ -186,7 +186,7 @@ int CmdFDXBdemodBI(const char *Cmd) {
return 0;
}
- setDemodBuf(bs, 128, preambleIndex);
+ setDemodBuff(bs, 128, preambleIndex);
// remove marker bits (1's every 9th digit after preamble) (pType = 2)
size = removeParity(bs, preambleIndex + 11, 9, 2, 117);
@@ -256,7 +256,7 @@ int CmdFdxDemod(const char *Cmd) {
}
// set and leave DemodBuffer intact
- setDemodBuf(DemodBuffer, 128, preambleIndex);
+ setDemodBuff(DemodBuffer, 128, preambleIndex);
setClockGrid(g_DemodClock, g_DemodStartIdx + (preambleIndex * g_DemodClock));
// remove marker bits (1's every 9th digit after preamble) (pType = 2)
size = removeParity(DemodBuffer, 11, 9, 2, 117);
diff --git a/client/cmdlffdx.h b/client/cmdlffdx.h
index 1ae12633a..1bc2428fc 100644
--- a/client/cmdlffdx.h
+++ b/client/cmdlffdx.h
@@ -19,17 +19,17 @@
#include "protocols.h" // for T55xx config register definitions
#include "lfdemod.h" // parityTest
-extern int CmdLFFdx(const char *Cmd);
-extern int CmdFdxClone(const char *Cmd);
-extern int CmdFdxSim(const char *Cmd);
-extern int CmdFdxRead(const char *Cmd);
-extern int CmdFdxDemod(const char *Cmd);
+int CmdLFFdx(const char *Cmd);
+int CmdFdxClone(const char *Cmd);
+int CmdFdxSim(const char *Cmd);
+int CmdFdxRead(const char *Cmd);
+int CmdFdxDemod(const char *Cmd);
int getFDXBits(uint64_t national_id, uint16_t country, uint8_t isanimal, uint8_t isextended, uint32_t extended, uint8_t *bits);
-extern int usage_lf_fdx_clone(void);
-extern int usage_lf_fdx_sim(void);
-extern int usage_lf_fdx_read(void);
-extern int usage_lf_fdx_demod(void);
+int usage_lf_fdx_clone(void);
+int usage_lf_fdx_sim(void);
+int usage_lf_fdx_read(void);
+int usage_lf_fdx_demod(void);
#endif
diff --git a/client/cmdlfguard.c b/client/cmdlfguard.c
index a3f8bbec9..1f89a87ef 100644
--- a/client/cmdlfguard.c
+++ b/client/cmdlfguard.c
@@ -220,7 +220,7 @@ int CmdGuardDemod(const char *Cmd) {
PrintAndLogEx(DEBUG, "DEBUG: gProxII byte %u after xor: %02x", (unsigned int)idx, ByteStream[idx]);
}
- setDemodBuf(DemodBuffer, 96, preambleIndex);
+ setDemodBuff(DemodBuffer, 96, preambleIndex);
setClockGrid(g_DemodClock, g_DemodStartIdx + (preambleIndex * g_DemodClock));
//ByteStream contains 8 Bytes (64 bits) of decrypted raw tag data
diff --git a/client/cmdlfguard.h b/client/cmdlfguard.h
index b01a99aff..749307bea 100644
--- a/client/cmdlfguard.h
+++ b/client/cmdlfguard.h
@@ -22,12 +22,12 @@
#include "lfdemod.h" // parityTest
#include "crc.h"
-extern int CmdLFGuard(const char *Cmd);
-extern int CmdGuardDemod(const char *Cmd);
-extern int CmdGuardRead(const char *Cmd);
-extern int CmdGuardClone(const char *Cmd);
-extern int CmdGuardSim(const char *Cmd);
+int CmdLFGuard(const char *Cmd);
+int CmdGuardDemod(const char *Cmd);
+int CmdGuardRead(const char *Cmd);
+int CmdGuardClone(const char *Cmd);
+int CmdGuardSim(const char *Cmd);
-extern int usage_lf_guard_clone(void);
-extern int usage_lf_quard_sim(void);
+int usage_lf_guard_clone(void);
+int usage_lf_quard_sim(void);
#endif
diff --git a/client/cmdlfhid.c b/client/cmdlfhid.c
index c0d55f977..9dbb721cd 100644
--- a/client/cmdlfhid.c
+++ b/client/cmdlfhid.c
@@ -155,7 +155,7 @@ int CmdHIDDemod(const char *Cmd) {
return 0;
}
- setDemodBuf(bits, size, idx);
+ setDemodBuff(bits, size, idx);
setClockGrid(50, waveIdx + (idx * 50));
if (hi2 == 0 && hi == 0 && lo == 0) {
@@ -459,8 +459,8 @@ int CmdHIDWiegand(const char *Cmd) {
uint8_t *bs = bits;
memset(bs, 0, sizeof(bits));
- uint8_t ctmp = param_getchar(Cmd, 0);
- if (strlen(Cmd) == 0 || strlen(Cmd) < 3 || ctmp == 'H' || ctmp == 'h') return usage_lf_hid_wiegand();
+ uint8_t ctmp = tolower(param_getchar(Cmd, 0));
+ if (strlen(Cmd) < 3 || ctmp == 'h') return usage_lf_hid_wiegand();
oem = param_get8(Cmd, 0);
fc = param_get32ex(Cmd, 1, 0, 10);
diff --git a/client/cmdlfhid.h b/client/cmdlfhid.h
index 48d6f63a2..422658822 100644
--- a/client/cmdlfhid.h
+++ b/client/cmdlfhid.h
@@ -24,20 +24,20 @@
#include "util_posix.h"
#include "lfdemod.h"
-extern int CmdLFHID(const char *Cmd);
-extern int CmdHIDDemod(const char *Cmd);
-extern int CmdHIDRead(const char *Cmd);
-extern int CmdHIDSim(const char *Cmd);
-extern int CmdHIDClone(const char *Cmd);
-extern int CmdHIDWiegand(const char *Cmd);
-extern int CmdHIDBrute(const char *Cmd);
+int CmdLFHID(const char *Cmd);
+int CmdHIDDemod(const char *Cmd);
+int CmdHIDRead(const char *Cmd);
+int CmdHIDSim(const char *Cmd);
+int CmdHIDClone(const char *Cmd);
+int CmdHIDWiegand(const char *Cmd);
+int CmdHIDBrute(const char *Cmd);
-extern int usage_lf_hid_read(void);
-extern int usage_lf_hid_wiegand(void);
-extern int usage_lf_hid_sim(void);
-extern int usage_lf_hid_clone(void);
-extern int usage_lf_hid_brute(void);
+int usage_lf_hid_read(void);
+int usage_lf_hid_wiegand(void);
+int usage_lf_hid_sim(void);
+int usage_lf_hid_clone(void);
+int usage_lf_hid_brute(void);
//void calc26(uint16_t fc, uint32_t cardno, uint8_t *out);
-extern void calcWiegand(uint8_t fmtlen, uint16_t fc, uint64_t cardno, uint8_t *bits);
+void calcWiegand(uint8_t fmtlen, uint16_t fc, uint64_t cardno, uint8_t *bits);
#endif
diff --git a/client/cmdlfhitag.h b/client/cmdlfhitag.h
index eb5bb2dd0..650e5d892 100644
--- a/client/cmdlfhitag.h
+++ b/client/cmdlfhitag.h
@@ -11,15 +11,15 @@
#ifndef CMDLFHITAG_H__
#define CMDLFHITAG_H__
-extern int CmdLFHitag(const char *Cmd);
+int CmdLFHitag(const char *Cmd);
-extern int CmdLFHitagList(const char *Cmd);
-extern int CmdLFHitagSniff(const char *Cmd);
-extern int CmdLFHitagSim(const char *Cmd);
-extern int CmdLFHitagInfo(const char *Cmd);
-extern int CmdLFHitagReader(const char *Cmd);
-extern int CmdLFHitagCheckChallenges(const char *Cmd);
-extern int CmdLFHitagWriter(const char *Cmd);
-extern int CmdLFHitagDump(const char *cmd);
+int CmdLFHitagList(const char *Cmd);
+int CmdLFHitagSniff(const char *Cmd);
+int CmdLFHitagSim(const char *Cmd);
+int CmdLFHitagInfo(const char *Cmd);
+int CmdLFHitagReader(const char *Cmd);
+int CmdLFHitagCheckChallenges(const char *Cmd);
+int CmdLFHitagWriter(const char *Cmd);
+int CmdLFHitagDump(const char *Cmd);
#endif
diff --git a/client/cmdlfindala.c b/client/cmdlfindala.c
index c6be8bd29..257e85894 100644
--- a/client/cmdlfindala.c
+++ b/client/cmdlfindala.c
@@ -208,7 +208,7 @@ int CmdIndalaDemod(const char *Cmd) {
PrintAndLogEx(DEBUG, "DEBUG: Error - Indala: error demoding psk idx: %d", idx);
return 0;
}
- setDemodBuf(DemodBuffer, size, idx);
+ setDemodBuff(DemodBuffer, size, idx);
setClockGrid(g_DemodClock, g_DemodStartIdx + (idx * g_DemodClock));
//convert UID to HEX
@@ -265,16 +265,18 @@ int CmdIndalaDemod(const char *Cmd) {
uid5 = bytebits_to_byte(DemodBuffer + 128, 32);
uid6 = bytebits_to_byte(DemodBuffer + 160, 32);
uid7 = bytebits_to_byte(DemodBuffer + 192, 32);
- PrintAndLogEx(SUCCESS, "Indala Found - bitlength %d, UID = 0x%x%08x%08x%08x%08x%08x%08x"
- , DemodBufferLen
- , uid1
- , uid2
- , uid3
- , uid4
- , uid5
- , uid6
- , uid7
- );
+ PrintAndLogEx(
+ SUCCESS
+ , "Indala Found - bitlength %d, Raw 0x%x%08x%08x%08x%08x%08x%08x"
+ , DemodBufferLen
+ , uid1
+ , uid2
+ , uid3
+ , uid4
+ , uid5
+ , uid6
+ , uid7
+ );
}
if (g_debugMode) {
@@ -444,9 +446,8 @@ int CmdIndalaDemodAlt(const char *Cmd) {
}
// Checking UID against next occurrences
- int failed = 0;
for (; i + uidlen <= rawbit;) {
- failed = 0;
+ int failed = 0;
for (bit = 0; bit < uidlen; bit++) {
if (bits[bit] != rawbits[i++]) {
failed = 1;
@@ -466,14 +467,13 @@ int CmdIndalaDemodAlt(const char *Cmd) {
// since this changes graphbuffer data.
GraphTraceLen = 32 * uidlen;
i = 0;
- int phase = 0;
+ int phase;
for (bit = 0; bit < uidlen; bit++) {
if (bits[bit] == 0) {
phase = 0;
} else {
phase = 1;
}
- int j;
for (j = 0; j < 32; j++) {
GraphBuffer[i++] = phase;
phase = !phase;
@@ -558,7 +558,7 @@ int CmdIndalaClone(const char *Cmd) {
UsbCommand c = {0, {0, 0, 0}};
if (isLongUid) {
- PrintAndLogEx(INFO, "Preparing to clone Indala 224bit tag with UID %s", sprint_hex(data, datalen));
+ PrintAndLogEx(INFO, "Preparing to clone Indala 224bit tag with RawID %s", sprint_hex(data, datalen));
c.cmd = CMD_INDALA_CLONE_TAG_L;
c.d.asDwords[0] = bytes_to_num(data, 4);
c.d.asDwords[1] = bytes_to_num(data + 4, 4);
@@ -568,7 +568,7 @@ int CmdIndalaClone(const char *Cmd) {
c.d.asDwords[5] = bytes_to_num(data + 20, 4);
c.d.asDwords[6] = bytes_to_num(data + 24, 4);
} else {
- PrintAndLogEx(INFO, "Preparing to clone Indala 64bit tag with UID %s", sprint_hex(data, datalen));
+ PrintAndLogEx(INFO, "Preparing to clone Indala 64bit tag with RawID %s", sprint_hex(data, datalen));
c.cmd = CMD_INDALA_CLONE_TAG;
c.d.asDwords[0] = bytes_to_num(data, 4);
c.d.asDwords[1] = bytes_to_num(data + 4, 4);
diff --git a/client/cmdlfindala.h b/client/cmdlfindala.h
index 8352421cc..7bfdd1eae 100644
--- a/client/cmdlfindala.h
+++ b/client/cmdlfindala.h
@@ -23,19 +23,19 @@
#include "cmddata.h"
#include "cmdlf.h" // lf_read
-extern int CmdLFINDALA(const char *Cmd);
+int CmdLFINDALA(const char *Cmd);
-extern int CmdIndalaDemod(const char *Cmd);
-extern int CmdIndalaDemodAlt(const char *Cmd);
-extern int CmdIndalaRead(const char *Cmd);
-extern int CmdIndalaClone(const char *Cmd);
-extern int CmdIndalaSim(const char *Cmd);
+int CmdIndalaDemod(const char *Cmd);
+int CmdIndalaDemodAlt(const char *Cmd);
+int CmdIndalaRead(const char *Cmd);
+int CmdIndalaClone(const char *Cmd);
+int CmdIndalaSim(const char *Cmd);
-extern int detectIndala26(uint8_t *bitStream, size_t *size, uint8_t *invert);
-extern int detectIndala64(uint8_t *bitStream, size_t *size, uint8_t *invert);
-extern int detectIndala224(uint8_t *bitStream, size_t *size, uint8_t *invert);
+int detectIndala26(uint8_t *bitStream, size_t *size, uint8_t *invert);
+int detectIndala64(uint8_t *bitStream, size_t *size, uint8_t *invert);
+int detectIndala224(uint8_t *bitStream, size_t *size, uint8_t *invert);
-extern int usage_lf_indala_demod(void);
-extern int usage_lf_indala_clone(void);
-extern int usage_lf_indala_sim(void);
+int usage_lf_indala_demod(void);
+int usage_lf_indala_clone(void);
+int usage_lf_indala_sim(void);
#endif
diff --git a/client/cmdlfio.c b/client/cmdlfio.c
index df994b1a1..ae18ec4f7 100644
--- a/client/cmdlfio.c
+++ b/client/cmdlfio.c
@@ -112,7 +112,7 @@ int CmdIOProxDemod(const char *Cmd) {
}
return 0;
}
- setDemodBuf(bits, size, idx);
+ setDemodBuff(bits, size, idx);
setClockGrid(64, waveIdx + (idx * 64));
if (idx == 0) {
diff --git a/client/cmdlfio.h b/client/cmdlfio.h
index 6bdb4b88f..5066fee87 100644
--- a/client/cmdlfio.h
+++ b/client/cmdlfio.h
@@ -16,15 +16,15 @@
#include "cmdmain.h"
#include "cmddata.h"
-extern int CmdLFIO(const char *Cmd);
-extern int CmdIOProxDemod(const char *Cmd);
-extern int CmdIOProxRead(const char *Cmd);
-extern int CmdIOProxSim(const char *Cmd);
-extern int CmdIOProxClone(const char *Cmd);
+int CmdLFIO(const char *Cmd);
+int CmdIOProxDemod(const char *Cmd);
+int CmdIOProxRead(const char *Cmd);
+int CmdIOProxSim(const char *Cmd);
+int CmdIOProxClone(const char *Cmd);
int getIOProxBits(uint8_t version, uint8_t fc, uint16_t cn, uint8_t *bits);
-extern int usage_lf_io_read(void);
-extern int usage_lf_io_clone(void);
-extern int usage_lf_io_sim(void);
+int usage_lf_io_read(void);
+int usage_lf_io_clone(void);
+int usage_lf_io_sim(void);
#endif
diff --git a/client/cmdlfjablotron.c b/client/cmdlfjablotron.c
index e445b20b6..08312db4b 100644
--- a/client/cmdlfjablotron.c
+++ b/client/cmdlfjablotron.c
@@ -117,7 +117,7 @@ int CmdJablotronDemod(const char *Cmd) {
return 0;
}
- setDemodBuf(DemodBuffer, 64, ans);
+ setDemodBuff(DemodBuffer, 64, ans);
setClockGrid(g_DemodClock, g_DemodStartIdx + (ans * g_DemodClock));
//got a good demod
diff --git a/client/cmdlfjablotron.h b/client/cmdlfjablotron.h
index 127157e67..5079a6f76 100644
--- a/client/cmdlfjablotron.h
+++ b/client/cmdlfjablotron.h
@@ -22,20 +22,20 @@
#include "protocols.h" // for T55xx config register definitions
#include "lfdemod.h" // parityTest
-extern int CmdLFJablotron(const char *Cmd);
+int CmdLFJablotron(const char *Cmd);
-extern int CmdJablotronDemod(const char *Cmd);
-extern int CmdJablotronRead(const char *Cmd);
-extern int CmdJablotronClone(const char *Cmd);
-extern int CmdJablotronSim(const char *Cmd);
+int CmdJablotronDemod(const char *Cmd);
+int CmdJablotronRead(const char *Cmd);
+int CmdJablotronClone(const char *Cmd);
+int CmdJablotronSim(const char *Cmd);
-extern int detectJablotron(uint8_t *bits, size_t *size);
-extern int getJablotronBits(uint64_t fullcode, uint8_t *bits);
+int detectJablotron(uint8_t *bits, size_t *size);
+int getJablotronBits(uint64_t fullcode, uint8_t *bits);
-//extern int usage_lf_jablotron_demod(void);
-//extern int usage_lf_jablotron_read(void);
-extern int usage_lf_jablotron_clone(void);
-extern int usage_lf_jablotron_sim(void);
+//int usage_lf_jablotron_demod(void);
+//int usage_lf_jablotron_read(void);
+int usage_lf_jablotron_clone(void);
+int usage_lf_jablotron_sim(void);
#endif
diff --git a/client/cmdlfkeri.c b/client/cmdlfkeri.c
index 199e639a9..c3df3e7be 100644
--- a/client/cmdlfkeri.c
+++ b/client/cmdlfkeri.c
@@ -84,7 +84,7 @@ int CmdKeriDemod(const char *Cmd) {
return 0;
}
- setDemodBuf(DemodBuffer, size, idx);
+ setDemodBuff(DemodBuffer, size, idx);
setClockGrid(g_DemodClock, g_DemodStartIdx + (idx * g_DemodClock));
//got a good demod
diff --git a/client/cmdlfkeri.h b/client/cmdlfkeri.h
index ed0629b37..b2e1c89ad 100644
--- a/client/cmdlfkeri.h
+++ b/client/cmdlfkeri.h
@@ -22,15 +22,15 @@
#include "protocols.h" // for T55xx config register definitions
#include "lfdemod.h" // preamble test
-extern int CmdLFKeri(const char *Cmd);
-extern int CmdKeriRead(const char *Cmd);
-extern int CmdKeriDemod(const char *Cmd);
-extern int CmdKeriClone(const char *Cmd);
-extern int CmdKeriSim(const char *Cmd);
+int CmdLFKeri(const char *Cmd);
+int CmdKeriRead(const char *Cmd);
+int CmdKeriDemod(const char *Cmd);
+int CmdKeriClone(const char *Cmd);
+int CmdKeriSim(const char *Cmd);
-extern int detectKeri(uint8_t *dest, size_t *size, bool *invert);
+int detectKeri(uint8_t *dest, size_t *size, bool *invert);
-extern int usage_lf_keri_clone(void);
-extern int usage_lf_keri_sim(void);
+int usage_lf_keri_clone(void);
+int usage_lf_keri_sim(void);
#endif
diff --git a/client/cmdlfnedap.c b/client/cmdlfnedap.c
index 320f07d6a..e03401e84 100644
--- a/client/cmdlfnedap.c
+++ b/client/cmdlfnedap.c
@@ -165,7 +165,7 @@ int CmdLFNedapDemod(const char *Cmd) {
raw[1] = bytebits_to_byte(DemodBuffer + idx + 64, 32);
raw[2] = bytebits_to_byte(DemodBuffer + idx + 32, 32);
raw[3] = bytebits_to_byte(DemodBuffer + idx, 32);
- setDemodBuf(DemodBuffer, 128, idx);
+ setDemodBuff(DemodBuffer, 128, idx);
setClockGrid(g_DemodClock, g_DemodStartIdx + (idx * g_DemodClock));
uint8_t firstParity = GetParity(DemodBuffer, EVEN, 63);
diff --git a/client/cmdlfnedap.h b/client/cmdlfnedap.h
index fd10c5e76..6cacfd638 100644
--- a/client/cmdlfnedap.h
+++ b/client/cmdlfnedap.h
@@ -22,17 +22,17 @@
#include "lfdemod.h" // parityTest
#include "crc.h"
-extern int CmdLFNedap(const char *Cmd);
-extern int CmdLFNedapDemod(const char *Cmd);
-extern int CmdLFNedapRead(const char *Cmd);
-//extern int CmdLFNedapClone(const char *Cmd);
-extern int CmdLFNedapSim(const char *Cmd);
-extern int CmdLFNedapChk(const char *Cmd);
+int CmdLFNedap(const char *Cmd);
+int CmdLFNedapDemod(const char *Cmd);
+int CmdLFNedapRead(const char *Cmd);
+//int CmdLFNedapClone(const char *Cmd);
+int CmdLFNedapSim(const char *Cmd);
+int CmdLFNedapChk(const char *Cmd);
-extern int detectNedap(uint8_t *dest, size_t *size);
+int detectNedap(uint8_t *dest, size_t *size);
-extern int usage_lf_nedap_read(void);
-//extern int usage_lf_nedap_clone(void);
-extern int usage_lf_nedap_sim(void);
+int usage_lf_nedap_read(void);
+//int usage_lf_nedap_clone(void);
+int usage_lf_nedap_sim(void);
#endif
diff --git a/client/cmdlfnexwatch.c b/client/cmdlfnexwatch.c
index 3d5c1083b..ffe3bd785 100644
--- a/client/cmdlfnexwatch.c
+++ b/client/cmdlfnexwatch.c
@@ -57,7 +57,7 @@ int CmdNexWatchDemod(const char *Cmd) {
return 0;
}
- setDemodBuf(DemodBuffer, size, idx + 4);
+ setDemodBuff(DemodBuffer, size, idx + 4);
setClockGrid(g_DemodClock, g_DemodStartIdx + ((idx + 4)*g_DemodClock));
idx = 8 + 32; // 8 = preamble, 32 = reserved bits (always 0)
diff --git a/client/cmdlfnexwatch.h b/client/cmdlfnexwatch.h
index 82782926a..7b08c1294 100644
--- a/client/cmdlfnexwatch.h
+++ b/client/cmdlfnexwatch.h
@@ -22,9 +22,9 @@
#include "cmdlf.h"
#include "lfdemod.h"
-extern int CmdLFNEXWATCH(const char *Cmd);
-extern int CmdNexWatchDemod(const char *Cmd);
-extern int CmdNexWatchRead(const char *Cmd);
+int CmdLFNEXWATCH(const char *Cmd);
+int CmdNexWatchDemod(const char *Cmd);
+int CmdNexWatchRead(const char *Cmd);
-extern int detectNexWatch(uint8_t *dest, size_t *size, bool *invert);
+int detectNexWatch(uint8_t *dest, size_t *size, bool *invert);
#endif
diff --git a/client/cmdlfnoralsy.c b/client/cmdlfnoralsy.c
index 0f515ba43..e2c4a5c90 100644
--- a/client/cmdlfnoralsy.c
+++ b/client/cmdlfnoralsy.c
@@ -128,7 +128,7 @@ int CmdNoralsyDemod(const char *Cmd) {
}
return 0;
}
- setDemodBuf(DemodBuffer, 96, ans);
+ setDemodBuff(DemodBuffer, 96, ans);
setClockGrid(g_DemodClock, g_DemodStartIdx + (ans * g_DemodClock));
//got a good demod
diff --git a/client/cmdlfnoralsy.h b/client/cmdlfnoralsy.h
index 63065a0d6..c9986d0ea 100644
--- a/client/cmdlfnoralsy.h
+++ b/client/cmdlfnoralsy.h
@@ -22,17 +22,17 @@
#include "protocols.h" // for T55xx config register definitions
#include "lfdemod.h" // parityTest
-extern int CmdLFNoralsy(const char *Cmd);
-extern int CmdNoralsyDemod(const char *Cmd);
-extern int CmdNoralsyRead(const char *Cmd);
-extern int CmdNoralsyClone(const char *Cmd);
-extern int CmdNoralsySim(const char *Cmd);
+int CmdLFNoralsy(const char *Cmd);
+int CmdNoralsyDemod(const char *Cmd);
+int CmdNoralsyRead(const char *Cmd);
+int CmdNoralsyClone(const char *Cmd);
+int CmdNoralsySim(const char *Cmd);
int getnoralsyBits(uint32_t id, uint16_t year, uint8_t *bits);
-extern int usage_lf_noralsy_clone(void);
-extern int usage_lf_noralsy_sim(void);
-//extern int usage_lf_noralsy_read(void);
-//extern int usage_lf_noralsy_demod(void);
+int usage_lf_noralsy_clone(void);
+int usage_lf_noralsy_sim(void);
+//int usage_lf_noralsy_read(void);
+//int usage_lf_noralsy_demod(void);
#endif
diff --git a/client/cmdlfpac.c b/client/cmdlfpac.c
index 643e5295f..7c7742d95 100644
--- a/client/cmdlfpac.c
+++ b/client/cmdlfpac.c
@@ -46,7 +46,7 @@ int CmdPacDemod(const char *Cmd) {
return 0;
}
- setDemodBuf(DemodBuffer, 128, ans);
+ setDemodBuff(DemodBuffer, 128, ans);
setClockGrid(g_DemodClock, g_DemodStartIdx + (ans * g_DemodClock));
//got a good demod
diff --git a/client/cmdlfpac.h b/client/cmdlfpac.h
index 88e97a42e..54b2b3366 100644
--- a/client/cmdlfpac.h
+++ b/client/cmdlfpac.h
@@ -21,10 +21,10 @@
#include "cmdlf.h"
#include "lfdemod.h" // preamble test
-extern int CmdLFPac(const char *Cmd);
-extern int CmdPacRead(const char *Cmd);
-extern int CmdPacDemod(const char *Cmd);
+int CmdLFPac(const char *Cmd);
+int CmdPacRead(const char *Cmd);
+int CmdPacDemod(const char *Cmd);
-extern int detectPac(uint8_t *dest, size_t *size);
+int detectPac(uint8_t *dest, size_t *size);
#endif
diff --git a/client/cmdlfparadox.c b/client/cmdlfparadox.c
index 23d45bc27..5cca09b4e 100644
--- a/client/cmdlfparadox.c
+++ b/client/cmdlfparadox.c
@@ -108,7 +108,7 @@ int CmdParadoxDemod(const char *Cmd) {
return 0;
}
- setDemodBuf(bits, size, idx);
+ setDemodBuff(bits, size, idx);
setClockGrid(50, waveIdx + (idx * 50));
if (hi2 == 0 && hi == 0 && lo == 0) {
diff --git a/client/cmdlfparadox.h b/client/cmdlfparadox.h
index 44045f114..1b6211716 100644
--- a/client/cmdlfparadox.h
+++ b/client/cmdlfparadox.h
@@ -8,12 +8,12 @@
//-----------------------------------------------------------------------------
#ifndef CMDLFPARADOX_H__
#define CMDLFPARADOX_H__
-extern int CmdLFParadox(const char *Cmd);
-extern int CmdParadoxDemod(const char *Cmd);
-extern int CmdParadoxRead(const char *Cmd);
+int CmdLFParadox(const char *Cmd);
+int CmdParadoxDemod(const char *Cmd);
+int CmdParadoxRead(const char *Cmd);
-//extern int CmdParadoxClone(const char *Cmd);
-extern int CmdParadoxSim(const char *Cmd);
+//int CmdParadoxClone(const char *Cmd);
+int CmdParadoxSim(const char *Cmd);
-extern int detectParadox(uint8_t *dest, size_t *size, uint32_t *hi2, uint32_t *hi, uint32_t *lo, int *waveStartIdx);
+int detectParadox(uint8_t *dest, size_t *size, uint32_t *hi2, uint32_t *hi, uint32_t *lo, int *waveStartIdx);
#endif
diff --git a/client/cmdlfpresco.c b/client/cmdlfpresco.c
index b76cdf5e3..cff86c88b 100644
--- a/client/cmdlfpresco.c
+++ b/client/cmdlfpresco.c
@@ -144,7 +144,7 @@ int CmdPrescoDemod(const char *Cmd) {
PrintAndLogEx(DEBUG, "DEBUG: Error - Presco: ans: %d", ans);
return 0;
}
- setDemodBuf(DemodBuffer, 128, ans);
+ setDemodBuff(DemodBuffer, 128, ans);
setClockGrid(g_DemodClock, g_DemodStartIdx + (ans * g_DemodClock));
//got a good demod
diff --git a/client/cmdlfpresco.h b/client/cmdlfpresco.h
index 563f0ac98..9c84f75b6 100644
--- a/client/cmdlfpresco.h
+++ b/client/cmdlfpresco.h
@@ -21,16 +21,16 @@
#include "protocols.h" // for T55xx config register definitions
#include "lfdemod.h" // parityTest
-extern int CmdLFPresco(const char *Cmd);
-extern int CmdPrescoRead(const char *Cmd);
-extern int CmdPrescoDemod(const char *Cmd);
-extern int CmdPrescoClone(const char *Cmd);
-extern int CmdPrescoSim(const char *Cmd);
+int CmdLFPresco(const char *Cmd);
+int CmdPrescoRead(const char *Cmd);
+int CmdPrescoDemod(const char *Cmd);
+int CmdPrescoClone(const char *Cmd);
+int CmdPrescoSim(const char *Cmd);
-extern int detectPresco(uint8_t *dest, size_t *size);
-int GetWiegandFromPresco(const char *id, uint32_t *sitecode, uint32_t *usercode, uint32_t *fullcode, bool *Q5);
+int detectPresco(uint8_t *dest, size_t *size);
+int GetWiegandFromPresco(const char *Cmd, uint32_t *sitecode, uint32_t *usercode, uint32_t *fullcode, bool *Q5);
-extern int usage_lf_presco_clone(void);
-extern int usage_lf_presco_sim(void);
+int usage_lf_presco_clone(void);
+int usage_lf_presco_sim(void);
#endif
diff --git a/client/cmdlfpyramid.c b/client/cmdlfpyramid.c
index 169c07194..0be39300f 100644
--- a/client/cmdlfpyramid.c
+++ b/client/cmdlfpyramid.c
@@ -131,7 +131,7 @@ int CmdPyramidDemod(const char *Cmd) {
PrintAndLogEx(DEBUG, "DEBUG: Error - Pyramid: error demoding fsk idx: %d", idx);
return 0;
}
- setDemodBuf(bits, size, idx);
+ setDemodBuff(bits, size, idx);
setClockGrid(50, waveIdx + (idx * 50));
// Index map
@@ -224,16 +224,15 @@ int CmdPyramidDemod(const char *Cmd) {
fc = bytebits_to_byte(bits + 53, 10);
cardnum = bytebits_to_byte(bits + 63, 32);
PrintAndLogEx(SUCCESS, "Pyramid ID Found - BitLength: %d, FC: %d, Card: %d - Raw: %08x%08x%08x%08x", fmtLen, fc, cardnum, rawHi3, rawHi2, rawHi, rawLo);
+ } else if (fmtLen > 32) {
+ cardnum = bytebits_to_byte(bits + 81, 16);
+ //code1 = bytebits_to_byte(bits+(size-fmtLen),fmtLen-32);
+ //code2 = bytebits_to_byte(bits+(size-32),32);
+ PrintAndLogEx(SUCCESS, "Pyramid ID Found - BitLength: %d -unknown BitLength- (%d), Raw: %08x%08x%08x%08x", fmtLen, cardnum, rawHi3, rawHi2, rawHi, rawLo);
} else {
cardnum = bytebits_to_byte(bits + 81, 16);
- if (fmtLen > 32) {
- //code1 = bytebits_to_byte(bits+(size-fmtLen),fmtLen-32);
- //code2 = bytebits_to_byte(bits+(size-32),32);
- PrintAndLogEx(SUCCESS, "Pyramid ID Found - BitLength: %d -unknown BitLength- (%d), Raw: %08x%08x%08x%08x", fmtLen, cardnum, rawHi3, rawHi2, rawHi, rawLo);
- } else {
- //code1 = bytebits_to_byte(bits+(size-fmtLen),fmtLen);
- PrintAndLogEx(SUCCESS, "Pyramid ID Found - BitLength: %d -unknown BitLength- (%d), Raw: %08x%08x%08x%08x", fmtLen, cardnum, rawHi3, rawHi2, rawHi, rawLo);
- }
+ //code1 = bytebits_to_byte(bits+(size-fmtLen),fmtLen);
+ PrintAndLogEx(SUCCESS, "Pyramid ID Found - BitLength: %d -unknown BitLength- (%d), Raw: %08x%08x%08x%08x", fmtLen, cardnum, rawHi3, rawHi2, rawHi, rawLo);
}
PrintAndLogEx(DEBUG, "DEBUG: Pyramid: checksum : 0x%02X - %02X - %s"
diff --git a/client/cmdlfpyramid.h b/client/cmdlfpyramid.h
index 425914bbb..fe2b62ef9 100644
--- a/client/cmdlfpyramid.h
+++ b/client/cmdlfpyramid.h
@@ -22,15 +22,15 @@
#include "lfdemod.h" // parityTest
#include "crc.h"
-extern int CmdLFPyramid(const char *Cmd);
-extern int CmdPyramidDemod(const char *Cmd);
-extern int CmdPyramidRead(const char *Cmd);
-extern int CmdPyramidClone(const char *Cmd);
-extern int CmdPyramidSim(const char *Cmd);
+int CmdLFPyramid(const char *Cmd);
+int CmdPyramidDemod(const char *Cmd);
+int CmdPyramidRead(const char *Cmd);
+int CmdPyramidClone(const char *Cmd);
+int CmdPyramidSim(const char *Cmd);
-extern int detectPyramid(uint8_t *dest, size_t *size, int *waveStartIdx);
+int detectPyramid(uint8_t *dest, size_t *size, int *waveStartIdx);
-extern int usage_lf_pyramid_clone(void);
-extern int usage_lf_pyramid_sim(void);
+int usage_lf_pyramid_clone(void);
+int usage_lf_pyramid_sim(void);
#endif
diff --git a/client/cmdlfsecurakey.c b/client/cmdlfsecurakey.c
index 527aba839..1f14f8083 100644
--- a/client/cmdlfsecurakey.c
+++ b/client/cmdlfsecurakey.c
@@ -47,7 +47,7 @@ int CmdSecurakeyDemod(const char *Cmd) {
PrintAndLogEx(DEBUG, "DEBUG: Error - Securakey: ans: %d", ans);
return 0;
}
- setDemodBuf(DemodBuffer, 96, ans);
+ setDemodBuff(DemodBuffer, 96, ans);
setClockGrid(g_DemodClock, g_DemodStartIdx + (ans * g_DemodClock));
//got a good demod
diff --git a/client/cmdlfsecurakey.h b/client/cmdlfsecurakey.h
index 5155c2ada..bdeae02b7 100644
--- a/client/cmdlfsecurakey.h
+++ b/client/cmdlfsecurakey.h
@@ -24,11 +24,11 @@
#include "lfdemod.h" // preamble test
#include "parity.h" // for wiegand parity test
-extern int CmdLFSecurakey(const char *Cmd);
-//extern int CmdSecurakeyClone(const char *Cmd);
-//extern int CmdSecurakeySim(const char *Cmd);
-extern int CmdSecurakeyRead(const char *Cmd);
-extern int CmdSecurakeyDemod(const char *Cmd);
+int CmdLFSecurakey(const char *Cmd);
+//int CmdSecurakeyClone(const char *Cmd);
+//int CmdSecurakeySim(const char *Cmd);
+int CmdSecurakeyRead(const char *Cmd);
+int CmdSecurakeyDemod(const char *Cmd);
#endif
diff --git a/client/cmdlft55xx.c b/client/cmdlft55xx.c
index b25054b2d..835df18f2 100644
--- a/client/cmdlft55xx.c
+++ b/client/cmdlft55xx.c
@@ -379,9 +379,7 @@ int T55xxReadBlock(uint8_t block, bool page1, bool usepwd, bool override, uint32
if (!AquireData(page1, block, usepwd, password)) return 0;
if (!DecodeT55xxBlock()) return 0;
- char blk[10] = {0};
- sprintf(blk, "%02d", block);
- printT55xxBlock(blk);
+ printT55xxBlock(block);
return 1;
}
@@ -547,7 +545,7 @@ int CmdT55xxDetect(const char *Cmd) {
}
if (!tryDetectModulation())
- PrintAndLogEx(WARNING, "Could not detect modulation automatically. Try setting it manually with " _YELLOW_("\'lf t55xx config\'") );
+ PrintAndLogEx(WARNING, "Could not detect modulation automatically. Try setting it manually with " _YELLOW_("\'lf t55xx config\'"));
return 0;
}
@@ -767,7 +765,7 @@ bool GetT55xxBlockData(uint32_t *blockdata) {
return false;
uint8_t idx = config.offset;
-
+
if (idx + 32 > DemodBufferLen) {
PrintAndLogEx(WARNING, "The configured offset %d is too big. Possible offset: %d)", idx, DemodBufferLen - 32);
return false;
@@ -777,7 +775,7 @@ bool GetT55xxBlockData(uint32_t *blockdata) {
return true;
}
-void printT55xxBlock(const char *blockNum) {
+void printT55xxBlock(uint8_t blockNum) {
uint32_t blockData = 0;
uint8_t bytes[4] = {0};
@@ -787,7 +785,7 @@ void printT55xxBlock(const char *blockNum) {
num_to_bytes(blockData, 4, bytes);
- PrintAndLogEx(NORMAL, " %s | %08X | %s | %s", blockNum, blockData, sprint_bin(DemodBuffer + config.offset, 32), sprint_ascii(bytes, 4));
+ PrintAndLogEx(NORMAL, " %02d | %08X | %s | %s", blockNum, blockData, sprint_bin(DemodBuffer + config.offset, 32), sprint_ascii(bytes, 4));
}
bool testModulation(uint8_t mode, uint8_t modread) {
@@ -1292,13 +1290,8 @@ static void printT5x7KnownBlock0(uint32_t b0) {
snprintf(s + strlen(s), sizeof(s) - strlen(s), "T55x7 Raw ");
break;
case T55X7_EM_UNIQUE_CONFIG_BLOCK:
- snprintf(s + strlen(s), sizeof(s) - strlen(s), "EM Unique ");
+ snprintf(s + strlen(s), sizeof(s) - strlen(s), "EM unique, Paxton ");
break;
- /*
- case T55X7_EM_PAXTON_CONFIG_BLOCK:
- snprintf(s + strlen(s), sizeof(s)-strlen(s), "EM Paxton ");
- break;
- */
case T55X7_FDXB_CONFIG_BLOCK:
snprintf(s + strlen(s), sizeof(s) - strlen(s), "FDXB ");
break;
@@ -1339,10 +1332,8 @@ static void printT5x7KnownBlock0(uint32_t b0) {
break;
}
- if (strlen(s) > 0) {
- PrintAndLogEx(NORMAL, " Known T55x7 Config block found : " _YELLOW_("%s"), s);
- PrintAndLogEx(NORMAL, "-------------------------------------------------------------");
- }
+ if (strlen(s) > 0)
+ PrintAndLogEx(NORMAL, "\n Config block match : " _YELLOW_("%s"), s);
}
int CmdT55xxInfo(const char *Cmd) {
@@ -1476,9 +1467,12 @@ int CmdT55xxInfo(const char *Cmd) {
PrintAndLogEx(NORMAL, " Block 0 : 0x%08X", block0);
else
PrintAndLogEx(NORMAL, " Block 0 : 0x%08X %s", block0, sprint_bin(DemodBuffer + config.offset, 32));
- PrintAndLogEx(NORMAL, "-------------------------------------------------------------");
+
if (((!gotdata) && (!config.Q5)) || (gotdata && (!dataasq5)))
printT5x7KnownBlock0(block0);
+
+ PrintAndLogEx(NORMAL, "-------------------------------------------------------------");
+
return 0;
}
diff --git a/client/cmdlft55xx.h b/client/cmdlft55xx.h
index ce990bebd..71526b997 100644
--- a/client/cmdlft55xx.h
+++ b/client/cmdlft55xx.h
@@ -137,17 +137,17 @@ typedef struct {
t55xx_conf_block_t Get_t55xx_Config(void);
void Set_t55xx_Config(t55xx_conf_block_t conf);
-extern int CmdLFT55XX(const char *Cmd);
-extern int CmdT55xxChk(const char *Cmd);
-extern int CmdT55xxBruteForce(const char *Cmd);
-extern int CmdT55xxSetConfig(const char *Cmd);
-extern int CmdT55xxReadBlock(const char *Cmd);
-extern int CmdT55xxWriteBlock(const char *Cmd);
-extern int CmdT55xxReadTrace(const char *Cmd);
-extern int CmdT55xxInfo(const char *Cmd);
-extern int CmdT55xxDetect(const char *Cmd);
-extern int CmdResetRead(const char *Cmd);
-extern int CmdT55xxWipe(const char *Cmd);
+int CmdLFT55XX(const char *Cmd);
+int CmdT55xxChk(const char *Cmd);
+int CmdT55xxBruteForce(const char *Cmd);
+int CmdT55xxSetConfig(const char *Cmd);
+int CmdT55xxReadBlock(const char *Cmd);
+int CmdT55xxWriteBlock(const char *Cmd);
+int CmdT55xxReadTrace(const char *Cmd);
+int CmdT55xxInfo(const char *Cmd);
+int CmdT55xxDetect(const char *Cmd);
+int CmdResetRead(const char *Cmd);
+int CmdT55xxWipe(const char *Cmd);
char *GetPskCfStr(uint32_t id, bool q5);
char *GetBitRateStr(uint32_t id, bool xmode);
@@ -157,19 +157,19 @@ char *GetModulationStr(uint32_t id, bool xmode);
char *GetModelStrFromCID(uint32_t cid);
char *GetSelectedModulationStr(uint8_t id);
void printT5xxHeader(uint8_t page);
-void printT55xxBlock(const char *demodStr);
+void printT55xxBlock(uint8_t blockNum);
int printConfiguration(t55xx_conf_block_t b);
-extern int T55xxReadBlock(uint8_t block, bool page1, bool usepwd, bool override, uint32_t password);
+int T55xxReadBlock(uint8_t block, bool page1, bool usepwd, bool override, uint32_t password);
bool GetT55xxBlockData(uint32_t *blockdata);
bool DecodeT55xxBlock(void);
-extern bool tryDetectModulation(void);
+bool tryDetectModulation(void);
bool testKnownConfigBlock(uint32_t block0);
-extern bool tryDetectP1(bool getData);
+bool tryDetectP1(bool getData);
bool test(uint8_t mode, uint8_t *offset, int *fndBitRate, uint8_t clk, bool *Q5);
int special(const char *Cmd);
-extern bool AquireData(uint8_t page, uint8_t block, bool pwdmode, uint32_t password);
+bool AquireData(uint8_t page, uint8_t block, bool pwdmode, uint32_t password);
int tryOnePassword(uint32_t password);
void printT55x7Trace(t55x7_tracedata_t data, uint8_t repeat);
diff --git a/client/cmdlfviking.c b/client/cmdlfviking.c
index 6c4a408b1..49b4ccf2f 100644
--- a/client/cmdlfviking.c
+++ b/client/cmdlfviking.c
@@ -90,7 +90,7 @@ int CmdVikingDemod(const char *Cmd) {
uint8_t checksum = bytebits_to_byte(DemodBuffer + ans + 32 + 24, 8);
PrintAndLogEx(SUCCESS, "Viking Tag Found: Card ID %08X, Checksum: %02X", cardid, checksum);
PrintAndLogEx(SUCCESS, "Raw: %08X%08X", raw1, raw2);
- setDemodBuf(DemodBuffer, 64, ans);
+ setDemodBuff(DemodBuffer, 64, ans);
setClockGrid(g_DemodClock, g_DemodStartIdx + (ans * g_DemodClock));
return 1;
}
diff --git a/client/cmdlfviking.h b/client/cmdlfviking.h
index 503534eaf..96b4e9ac4 100644
--- a/client/cmdlfviking.h
+++ b/client/cmdlfviking.h
@@ -21,16 +21,16 @@
#include "cmdlf.h"
#include "lfdemod.h"
-extern int CmdLFViking(const char *Cmd);
+int CmdLFViking(const char *Cmd);
-extern int CmdVikingDemod(const char *Cmd);
-extern int CmdVikingRead(const char *Cmd);
-extern int CmdVikingClone(const char *Cmd);
-extern int CmdVikingSim(const char *Cmd);
+int CmdVikingDemod(const char *Cmd);
+int CmdVikingRead(const char *Cmd);
+int CmdVikingClone(const char *Cmd);
+int CmdVikingSim(const char *Cmd);
-extern int detectViking(uint8_t *dest, size_t *size);
+int detectViking(uint8_t *dest, size_t *size);
-extern int usage_lf_viking_clone(void);
-extern int usage_lf_viking_sim(void);
+int usage_lf_viking_clone(void);
+int usage_lf_viking_sim(void);
#endif
diff --git a/client/cmdlfvisa2000.c b/client/cmdlfvisa2000.c
index 82bf491c2..3dcc7cf04 100644
--- a/client/cmdlfvisa2000.c
+++ b/client/cmdlfvisa2000.c
@@ -122,7 +122,7 @@ int CmdVisa2kDemod(const char *Cmd) {
save_restoreGB(GRAPH_RESTORE);
return 0;
}
- setDemodBuf(DemodBuffer, 96, ans);
+ setDemodBuff(DemodBuffer, 96, ans);
setClockGrid(g_DemodClock, g_DemodStartIdx + (ans * g_DemodClock));
//got a good demod
diff --git a/client/cmdlfvisa2000.h b/client/cmdlfvisa2000.h
index a266fa76e..cb0b102de 100644
--- a/client/cmdlfvisa2000.h
+++ b/client/cmdlfvisa2000.h
@@ -21,19 +21,19 @@
#include "cmdlf.h"
#include "protocols.h" // for T55xx config register definitions
#include "lfdemod.h" // parityTest
-extern int CmdLFVisa2k(const char *Cmd);
+int CmdLFVisa2k(const char *Cmd);
-extern int CmdVisa2kDemod(const char *Cmd);
-extern int CmdVisa2kRead(const char *Cmd);
-extern int CmdVisa2kClone(const char *Cmd);
-extern int CmdVisa2kSim(const char *Cmd);
+int CmdVisa2kDemod(const char *Cmd);
+int CmdVisa2kRead(const char *Cmd);
+int CmdVisa2kClone(const char *Cmd);
+int CmdVisa2kSim(const char *Cmd);
int getvisa2kBits(uint64_t fullcode, uint8_t *bits);
-extern int detectVisa2k(uint8_t *dest, size_t *size);
+int detectVisa2k(uint8_t *dest, size_t *size);
-extern int usage_lf_visa2k_clone(void);
-extern int usage_lf_visa2k_sim(void);
-//extern int usage_lf_visa2k_read(void);
-//extern int usage_lf_visa2k_demod(void);
+int usage_lf_visa2k_clone(void);
+int usage_lf_visa2k_sim(void);
+//int usage_lf_visa2k_read(void);
+//int usage_lf_visa2k_demod(void);
#endif
diff --git a/client/cmdmain.h b/client/cmdmain.h
index d5ac8e5a4..c729f8d77 100644
--- a/client/cmdmain.h
+++ b/client/cmdmain.h
@@ -41,7 +41,7 @@
#include "cmdsmartcard.h" // rdv40 smart card ISO7816 commands
#endif
-extern int CommandReceived(char *Cmd);
-extern command_t *getTopLevelCommandTable();
+int CommandReceived(char *Cmd);
+command_t *getTopLevelCommandTable();
#endif
diff --git a/client/cmdscript.h b/client/cmdscript.h
index fb915d950..55d735c0a 100644
--- a/client/cmdscript.h
+++ b/client/cmdscript.h
@@ -11,8 +11,8 @@
#ifndef CMDSCRIPT_H__
#define CMDSCRIPT_H__
-extern int CmdScript(const char *Cmd);
+int CmdScript(const char *Cmd);
-extern int CmdScriptList(const char *Cmd);
-extern int CmdScriptRun(const char *Cmd);
+int CmdScriptList(const char *Cmd);
+int CmdScriptRun(const char *Cmd);
#endif
diff --git a/client/cmdsmartcard.c b/client/cmdsmartcard.c
index 2a0216aa7..6d99dc98c 100644
--- a/client/cmdsmartcard.c
+++ b/client/cmdsmartcard.c
@@ -195,7 +195,7 @@ static int PrintATR(uint8_t *atr, size_t atrlen) {
uint8_t T0 = atr[1];
uint8_t K = T0 & 0x0F;
- uint8_t TD1 = 0, T1len = 0, TD1len = 0, TDilen = 0;
+ uint8_t T1len = 0, TD1len = 0, TDilen = 0;
bool protocol_T0_present = true;
bool protocol_T15_present = false;
@@ -215,7 +215,7 @@ static int PrintATR(uint8_t *atr, size_t atrlen) {
}
if (T0 & 0x80) {
- TD1 = atr[2 + T1len];
+ uint8_t TD1 = atr[2 + T1len];
PrintAndLog("\t- TD1 (First offered transmission protocol, presence of TA2..TD2) [ 0x%02x ] Protocol T%d", TD1, TD1 & 0x0f);
protocol_T0_present = false;
if ((TD1 & 0x0f) == 0) {
@@ -645,7 +645,7 @@ int CmdSmartUpgrade(const char *Cmd) {
long fsize = ftell(f);
fseek(f, 0, SEEK_SET);
- if (fsize < 0) {
+ if (fsize <= 0) {
PrintAndLogEx(WARNING, "error, when getting filesize");
fclose(f);
return 1;
@@ -659,9 +659,7 @@ int CmdSmartUpgrade(const char *Cmd) {
}
size_t firmware_size = fread(dump, 1, fsize, f);
- if (f) {
- fclose(f);
- }
+ fclose(f);
// load sha512 file
f = fopen(sha512filename, "rb");
@@ -676,7 +674,7 @@ int CmdSmartUpgrade(const char *Cmd) {
fsize = ftell(f);
fseek(f, 0, SEEK_SET);
- if (fsize < 0) {
+ if (fsize < 0) {
PrintAndLogEx(FAILED, "Could not determine size of SHA-512 file");
fclose(f);
free(dump);
@@ -694,24 +692,23 @@ int CmdSmartUpgrade(const char *Cmd) {
size_t bytes_read = fread(hashstring, 1, 128, f);
hashstring[128] = '\0';
- if (f)
- fclose(f);
+ fclose(f);
- uint8_t hash1[64];
- if (bytes_read != 128 || param_gethex(hashstring, 0, hash1, 128)) {
+ uint8_t hash_1[64];
+ if (bytes_read != 128 || param_gethex(hashstring, 0, hash_1, 128)) {
PrintAndLogEx(FAILED, "Couldn't read SHA-512 file");
free(dump);
return 1;
}
- uint8_t hash2[64];
- if (sha512hash(dump, firmware_size, hash2)) {
+ uint8_t hash_2[64];
+ if (sha512hash(dump, firmware_size, hash_2)) {
PrintAndLogEx(FAILED, "Couldn't calculate SHA-512 of firmware");
free(dump);
return 1;
}
- if (memcmp(hash1, hash2, 64)) {
+ if (memcmp(hash_1, hash_2, 64)) {
PrintAndLogEx(FAILED, "Couldn't verify integrity of firmware file " _RED_("(wrong SHA-512 hash)"));
free(dump);
return 1;
@@ -951,7 +948,6 @@ static void smart_brute_prim() {
if (!buf)
return;
- int len = 0;
uint8_t get_card_data[] = {
0x80, 0xCA, 0x9F, 0x13, 0x00,
0x80, 0xCA, 0x9F, 0x17, 0x00,
@@ -959,27 +955,25 @@ static void smart_brute_prim() {
0x80, 0xCA, 0x9F, 0x4f, 0x00
};
- UsbCommand c = {CMD_SMART_RAW, {SC_RAW_T0, 5, 0}};
-
PrintAndLogEx(INFO, "Reading primitives");
+ UsbCommand c = {CMD_SMART_RAW, {SC_RAW_T0, 5, 0}};
+
for (int i = 0; i < sizeof(get_card_data); i += 5) {
memcpy(c.d.asBytes, get_card_data + i, 5);
clearCommandBuffer();
SendCommand(&c);
- len = smart_responseEx(buf, true);
+ int len = smart_responseEx(buf, true);
if (len > 2) {
-
// if ( decodeTLV ) {
// if (!TLVPrintFromBuffer(buf, len-2)) {
PrintAndLogEx(SUCCESS, "\tHEX %d |: %s", len, sprint_hex(buf, len));
// }
// }
}
- len = 0;
}
free(buf);
}
@@ -990,7 +984,7 @@ static int smart_brute_sfi(bool decodeTLV) {
if (!buf)
return 1;
- int len = 0;
+ int len;
// READ RECORD
uint8_t READ_RECORD[] = {0x00, 0xB2, 0x00, 0x00, 0x00};
UsbCommand c = {CMD_SMART_RAW, {SC_RAW_T0, sizeof(READ_RECORD), 0}};
@@ -1107,7 +1101,7 @@ int CmdSmartBruteforceSFI(const char *Cmd) {
//Validations
if (errors) return usage_sm_brute();
- const char *SELECT = "00a40400%02x%s";
+ const char *SELECT = "00a40400%02zu%s";
// uint8_t GENERATE_AC[] = {0x80, 0xAE};
// uint8_t GET_CHALLENGE[] = {0x00, 0x84, 0x00};
diff --git a/client/cmdsmartcard.h b/client/cmdsmartcard.h
index 251859761..1e94499af 100644
--- a/client/cmdsmartcard.h
+++ b/client/cmdsmartcard.h
@@ -27,18 +27,18 @@
#include "emv/dump.h" // dump_buffer
#include "crypto/libpcrypto.h" // sha512hash
-extern int CmdSmartcard(const char *Cmd);
+int CmdSmartcard(const char *Cmd);
-extern int CmdSmartRaw(const char *cmd);
-extern int CmdSmartUpgrade(const char *cmd);
-extern int CmdSmartInfo(const char *cmd);
-extern int CmdSmartReader(const char *Cmd);
+int CmdSmartRaw(const char *Cmd);
+int CmdSmartUpgrade(const char *Cmd);
+int CmdSmartInfo(const char *Cmd);
+int CmdSmartReader(const char *Cmd);
-extern bool smart_select(bool silent, smart_card_atr_t *atr);
-extern int ExchangeAPDUSC(uint8_t *datain, int datainlen, bool activateCard, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen);
+bool smart_select(bool silent, smart_card_atr_t *atr);
+int ExchangeAPDUSC(uint8_t *datain, int datainlen, bool activateCard, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen);
-extern int usage_sm_raw(void);
-extern int usage_sm_reader(void);
-extern int usage_sm_info(void);
-extern int usage_sm_upgrade(void);
+int usage_sm_raw(void);
+int usage_sm_reader(void);
+int usage_sm_info(void);
+int usage_sm_upgrade(void);
#endif
diff --git a/client/cmdtrace.h b/client/cmdtrace.h
index 0d370123d..0191bf0e1 100644
--- a/client/cmdtrace.h
+++ b/client/cmdtrace.h
@@ -27,14 +27,14 @@
#include "comms.h" // for sending cmds to device. GetFromBigBuf
#include "loclass/fileutils.h" // for saveFile
-extern int CmdTrace(const char *Cmd);
+int CmdTrace(const char *Cmd);
-extern int CmdTraceList(const char *Cmd);
-extern int CmdTraceLoad(const char *Cmd);
-extern int CmdTraceSave(const char *Cmd);
+int CmdTraceList(const char *Cmd);
+int CmdTraceLoad(const char *Cmd);
+int CmdTraceSave(const char *Cmd);
// usages helptext
-extern int usage_trace_list(void);
-extern int usage_trace_load(void);
-extern int usage_trace_save(void);
+int usage_trace_list(void);
+int usage_trace_load(void);
+int usage_trace_save(void);
#endif
diff --git a/client/comms.h b/client/comms.h
index b0687ac60..b8e33beee 100644
--- a/client/comms.h
+++ b/client/comms.h
@@ -62,7 +62,7 @@ bool WaitForResponseTimeoutW(uint32_t cmd, UsbCommand *response, size_t ms_timeo
bool WaitForResponseTimeout(uint32_t cmd, UsbCommand *response, size_t ms_timeout);
bool WaitForResponse(uint32_t cmd, UsbCommand *response);
-extern bool GetFromDevice(DeviceMemType_t memtype, uint8_t *dest, uint32_t bytes, uint32_t start_index, UsbCommand *response, size_t ms_timeout, bool show_warning);
+bool GetFromDevice(DeviceMemType_t memtype, uint8_t *dest, uint32_t bytes, uint32_t start_index, UsbCommand *response, size_t ms_timeout, bool show_warning);
#endif
diff --git a/client/crypto/asn1dump.c b/client/crypto/asn1dump.c
index b62d83cbc..c55244286 100644
--- a/client/crypto/asn1dump.c
+++ b/client/crypto/asn1dump.c
@@ -323,7 +323,7 @@ bool asn1_tag_dump(const struct tlv *tlv, FILE *f, int level, bool *candump) {
const struct asn1_tag *tag = asn1_get_tag(tlv);
PRINT_INDENT(level);
- fprintf(f, "--%2hx[%02zx] '%s':", tlv->tag, tlv->len, tag->name);
+ fprintf(f, "--%2x[%02zx] '%s':", tlv->tag, tlv->len, tag->name);
switch (tag->type) {
case ASN1_TAG_GENERIC:
diff --git a/client/crypto/asn1dump.h b/client/crypto/asn1dump.h
index 1aadf487c..c7aef7e39 100644
--- a/client/crypto/asn1dump.h
+++ b/client/crypto/asn1dump.h
@@ -16,6 +16,6 @@
#include
#include "emv/tlv.h"
-extern bool asn1_tag_dump(const struct tlv *tlv, FILE *f, int level, bool *candump);
+bool asn1_tag_dump(const struct tlv *tlv, FILE *f, int level, bool *candump);
#endif /* asn1utils.h */
diff --git a/client/crypto/asn1utils.h b/client/crypto/asn1utils.h
index 19f8ded70..60c94e34a 100644
--- a/client/crypto/asn1utils.h
+++ b/client/crypto/asn1utils.h
@@ -15,7 +15,7 @@
#include
#include
-extern int asn1_print(uint8_t *asn1buf, size_t asn1buflen, char *indent);
-extern int ecdsa_asn1_get_signature(uint8_t *signature, size_t signaturelen, uint8_t *rval, uint8_t *sval);
+int asn1_print(uint8_t *asn1buf, size_t asn1buflen, char *indent);
+int ecdsa_asn1_get_signature(uint8_t *signature, size_t signaturelen, uint8_t *rval, uint8_t *sval);
#endif /* asn1utils.h */
diff --git a/client/crypto/libpcrypto.c b/client/crypto/libpcrypto.c
index 095d16af3..0def5b2f7 100644
--- a/client/crypto/libpcrypto.c
+++ b/client/crypto/libpcrypto.c
@@ -69,15 +69,15 @@ int aes_cmac(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *mac, int length
}
int aes_cmac8(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *mac, int length) {
- uint8_t cmac[16] = {0};
+ uint8_t cmac_tmp[16] = {0};
memset(mac, 0x00, 8);
- int res = aes_cmac(iv, key, input, cmac, length);
+ int res = aes_cmac(iv, key, input, cmac_tmp, length);
if (res)
return res;
for (int i = 0; i < 8; i++)
- mac[i] = cmac[i * 2 + 1];
+ mac[i] = cmac_tmp[i * 2 + 1];
return 0;
}
@@ -382,13 +382,13 @@ int ecdsa_nist_test(bool verbose) {
res = 1;
goto exit;
}
- if (verbose)
+
+ if (verbose) {
printf("passed\n");
-
- // random ecdsa test
- if (verbose)
printf(" ECDSA binary signature create/check test: ");
-
+ }
+
+ // random ecdsa test
uint8_t key_d[32] = {0};
uint8_t key_xy[32 * 2 + 2] = {0};
memset(signature, 0x00, sizeof(signature));
diff --git a/client/crypto/libpcrypto.h b/client/crypto/libpcrypto.h
index 2cb4644a8..38d37b66a 100644
--- a/client/crypto/libpcrypto.h
+++ b/client/crypto/libpcrypto.h
@@ -16,20 +16,20 @@
#include
#include
-extern int aes_encode(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *output, int length);
-extern int aes_decode(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *output, int length);
-extern int aes_cmac(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *mac, int length);
-extern int aes_cmac8(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *mac, int length);
+int aes_encode(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *output, int length);
+int aes_decode(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *output, int length);
+int aes_cmac(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *mac, int length);
+int aes_cmac8(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *mac, int length);
-extern int sha256hash(uint8_t *input, int length, uint8_t *hash);
-extern int sha512hash(uint8_t *input, int length, uint8_t *hash);
+int sha256hash(uint8_t *input, int length, uint8_t *hash);
+int sha512hash(uint8_t *input, int length, uint8_t *hash);
-extern int ecdsa_key_create(uint8_t *key_d, uint8_t *key_xy);
-extern int ecdsa_public_key_from_pk(mbedtls_pk_context *pk, uint8_t *key, size_t keylen);
-extern int ecdsa_signature_create(uint8_t *key_d, uint8_t *key_xy, uint8_t *input, int length, uint8_t *signature, size_t *signaturelen);
-extern int ecdsa_signature_verify(uint8_t *key_xy, uint8_t *input, int length, uint8_t *signature, size_t signaturelen);
-extern char *ecdsa_get_error(int ret);
+int ecdsa_key_create(uint8_t *key_d, uint8_t *key_xy);
+int ecdsa_public_key_from_pk(mbedtls_pk_context *pk, uint8_t *key, size_t keylen);
+int ecdsa_signature_create(uint8_t *key_d, uint8_t *key_xy, uint8_t *input, int length, uint8_t *signature, size_t *signaturelen);
+int ecdsa_signature_verify(uint8_t *key_xy, uint8_t *input, int length, uint8_t *signature, size_t signaturelen);
+char *ecdsa_get_error(int ret);
-extern int ecdsa_nist_test(bool verbose);
+int ecdsa_nist_test(bool verbose);
#endif /* libpcrypto.h */
diff --git a/client/emv/apduinfo.h b/client/emv/apduinfo.h
index 054aeec91..d7811dbc6 100644
--- a/client/emv/apduinfo.h
+++ b/client/emv/apduinfo.h
@@ -28,7 +28,7 @@ typedef struct {
const char *Description;
} APDUCode;
-extern const APDUCode *const GetAPDUCode(uint8_t sw1, uint8_t sw2);
-extern const char *GetAPDUCodeDescription(uint8_t sw1, uint8_t sw2);
+const APDUCode *const GetAPDUCode(uint8_t sw1, uint8_t sw2);
+const char *GetAPDUCodeDescription(uint8_t sw1, uint8_t sw2);
#endif
diff --git a/client/emv/cmdemv.h b/client/emv/cmdemv.h
index c91f75606..739909215 100644
--- a/client/emv/cmdemv.h
+++ b/client/emv/cmdemv.h
@@ -29,12 +29,12 @@
int CmdEMV(const char *Cmd);
-extern int CmdEMVSelect(const char *cmd);
-extern int CmdEMVSearch(const char *cmd);
-extern int CmdEMVPPSE(const char *cmd);
-extern int CmdEMVExec(const char *cmd);
-extern int CmdEMVGetrng(const char *Cmd);
-extern int CmdEMVList(const char *Cmd);
-extern int CmdEMVRoca(const char *Cmd);
+int CmdEMVSelect(const char *cmd);
+int CmdEMVSearch(const char *cmd);
+int CmdEMVPPSE(const char *cmd);
+int CmdEMVExec(const char *cmd);
+int CmdEMVGetrng(const char *Cmd);
+int CmdEMVList(const char *Cmd);
+int CmdEMVRoca(const char *Cmd);
#endif
diff --git a/client/emv/crypto_polarssl.c b/client/emv/crypto_polarssl.c
index e1f59ddf3..ff5a867a9 100644
--- a/client/emv/crypto_polarssl.c
+++ b/client/emv/crypto_polarssl.c
@@ -208,7 +208,7 @@ static unsigned char *crypto_pk_polarssl_encrypt(const struct crypto_pk *_cp, co
res = mbedtls_rsa_public(&cp->ctx, buf, result);
if (res) {
- printf("RSA encrypt failed. Error: %x data len: %zd key len: %zd\n", res * -1, len, keylen);
+ printf("RSA encrypt failed. Error: %x data len: %zu key len: %zu\n", res * -1, len, keylen);
free(result);
return NULL;
}
@@ -234,7 +234,7 @@ static unsigned char *crypto_pk_polarssl_decrypt(const struct crypto_pk *_cp, co
res = mbedtls_rsa_private(&cp->ctx, NULL, NULL, buf, result); // CHECK???
if (res) {
- printf("RSA decrypt failed. Error: %x data len: %zd key len: %zd\n", res * -1, len, keylen);
+ printf("RSA decrypt failed. Error: %x data len: %zu key len: %zu\n", res * -1, len, keylen);
free(result);
return NULL;
}
@@ -248,7 +248,6 @@ static size_t crypto_pk_polarssl_get_nbits(const struct crypto_pk *_cp) {
struct crypto_pk_polarssl *cp = (struct crypto_pk_polarssl *)_cp;
return cp->ctx.len * 8;
- return 0;
}
static unsigned char *crypto_pk_polarssl_get_parameter(const struct crypto_pk *_cp, unsigned param, size_t *plen) {
@@ -270,7 +269,7 @@ static unsigned char *crypto_pk_polarssl_get_parameter(const struct crypto_pk *_
mbedtls_mpi_write_binary(&cp->ctx.E, result, *plen);
break;
default:
- printf("Error get parameter. Param=%d", param);
+ printf("Error get parameter. Param = %u", param);
break;
}
diff --git a/client/emv/dol.h b/client/emv/dol.h
index 9b1b51656..496ae66f5 100644
--- a/client/emv/dol.h
+++ b/client/emv/dol.h
@@ -20,6 +20,6 @@
#include
struct tlv *dol_process(const struct tlv *tlv, const struct tlvdb *tlvdb, tlv_tag_t tag);
-struct tlvdb *dol_parse(const struct tlv *tlv, const unsigned char *buf, size_t len);
+struct tlvdb *dol_parse(const struct tlv *tlv, const unsigned char *data, size_t data_len);
#endif
diff --git a/client/emv/emv_pk.c b/client/emv/emv_pk.c
index 4c6afa88e..9b5f2e714 100644
--- a/client/emv/emv_pk.c
+++ b/client/emv/emv_pk.c
@@ -483,7 +483,7 @@ struct emv_pk *emv_pk_get_ca_pk(const unsigned char *rid, unsigned char idx) {
if (!pk)
return NULL;
- printf("Verifying CA PK for %02hhx:%02hhx:%02hhx:%02hhx:%02hhx IDX %02hhx %zd bits...",
+ printf("Verifying CA PK for %02hhx:%02hhx:%02hhx:%02hhx:%02hhx IDX %02hhx %zu bits...",
pk->rid[0],
pk->rid[1],
pk->rid[2],
diff --git a/client/emv/emv_pki.c b/client/emv/emv_pki.c
index 33d4eeb16..cb2486bb4 100644
--- a/client/emv/emv_pki.c
+++ b/client/emv/emv_pki.c
@@ -332,7 +332,7 @@ unsigned char *emv_pki_sdatl_fill(const struct tlvdb *db, size_t *sdatl_len) {
*sdatl_len = 0;
const struct tlv *sda_tl = tlvdb_get(db, 0x9f4a, NULL);
- if (!sda_tl || sda_tl->len <= 0)
+ if (!sda_tl || sda_tl->len == 0)
return NULL;
for (int i = 0; i < sda_tl->len; i++) {
diff --git a/client/emv/emv_pki.h b/client/emv/emv_pki.h
index 6cc4a97d1..91ff60166 100644
--- a/client/emv/emv_pki.h
+++ b/client/emv/emv_pki.h
@@ -21,17 +21,17 @@
#include
-extern void PKISetStrictExecution(bool se);
+void PKISetStrictExecution(bool se);
unsigned char *emv_pki_sdatl_fill(const struct tlvdb *db, size_t *sdatl_len);
struct emv_pk *emv_pki_recover_issuer_cert(const struct emv_pk *pk, struct tlvdb *db);
struct emv_pk *emv_pki_recover_icc_cert(const struct emv_pk *pk, struct tlvdb *db, const struct tlv *sda_tlv);
struct emv_pk *emv_pki_recover_icc_pe_cert(const struct emv_pk *pk, struct tlvdb *db);
-struct tlvdb *emv_pki_recover_dac(const struct emv_pk *pk, const struct tlvdb *db, const struct tlv *sda_tlv);
-struct tlvdb *emv_pki_recover_dac_ex(const struct emv_pk *pk, const struct tlvdb *db, const struct tlv *sda_tlv, bool showData);
-struct tlvdb *emv_pki_recover_idn(const struct emv_pk *pk, const struct tlvdb *db, const struct tlv *dyn_tlv);
-struct tlvdb *emv_pki_recover_idn_ex(const struct emv_pk *pk, const struct tlvdb *db, const struct tlv *dyn_tlv, bool showData);
+struct tlvdb *emv_pki_recover_dac(const struct emv_pk *enc_pk, const struct tlvdb *db, const struct tlv *sda_tlv);
+struct tlvdb *emv_pki_recover_dac_ex(const struct emv_pk *enc_pk, const struct tlvdb *db, const struct tlv *sda_tlv, bool showData);
+struct tlvdb *emv_pki_recover_idn(const struct emv_pk *enc_pk, const struct tlvdb *db, const struct tlv *dyn_tlv);
+struct tlvdb *emv_pki_recover_idn_ex(const struct emv_pk *enc_pk, const struct tlvdb *db, const struct tlv *dyn_tlv, bool showData);
struct tlvdb *emv_pki_recover_atc_ex(const struct emv_pk *enc_pk, const struct tlvdb *db, bool showData);
struct tlvdb *emv_pki_perform_cda(const struct emv_pk *enc_pk, const struct tlvdb *db,
const struct tlvdb *this_db,
diff --git a/client/emv/emv_roca.c b/client/emv/emv_roca.c
index 3a89020c7..c0d0d419d 100644
--- a/client/emv/emv_roca.c
+++ b/client/emv/emv_roca.c
@@ -84,7 +84,7 @@ void print_mpi(const char *msg, int radix, const mbedtls_mpi *X) {
size_t len = 0;
mbedtls_mpi_write_string(X, radix, Xchar, sizeof(Xchar), &len);
- printf("%s[%ld] %s\n", msg, len, Xchar);
+ printf("%s[%zu] %s\n", msg, len, Xchar);
}
bool emv_rocacheck(const unsigned char *buf, size_t buflen, bool verbose) {
diff --git a/client/emv/emv_roca.h b/client/emv/emv_roca.h
index 2830ce9c5..6663ce710 100644
--- a/client/emv/emv_roca.h
+++ b/client/emv/emv_roca.h
@@ -31,8 +31,8 @@
#define ROCA_PRINTS_LENGTH 17
-extern bool emv_rocacheck(const unsigned char *buf, size_t buflen, bool verbose);
-extern int roca_self_test(void);
+bool emv_rocacheck(const unsigned char *buf, size_t buflen, bool verbose);
+int roca_self_test(void);
#endif
diff --git a/client/emv/emv_tags.c b/client/emv/emv_tags.c
index 605707a65..dc6503f4b 100644
--- a/client/emv/emv_tags.c
+++ b/client/emv/emv_tags.c
@@ -490,7 +490,7 @@ static void emv_tag_dump_dol(const struct tlv *tlv, const struct emv_tag *tag, F
doltag = emv_get_tag(&doltlv);
PRINT_INDENT(level);
- fprintf(f, "\tTag %4hx len %02zx ('%s')\n", doltlv.tag, doltlv.len, doltag->name);
+ fprintf(f, "\tTag %4x len %02zx ('%s')\n", doltlv.tag, doltlv.len, doltag->name);
}
}
@@ -537,7 +537,7 @@ static void emv_tag_dump_numeric(const struct tlv *tlv, const struct emv_tag *ta
static void emv_tag_dump_yymmdd(const struct tlv *tlv, const struct emv_tag *tag, FILE *f, int level) {
PRINT_INDENT(level);
- fprintf(f, "\tDate: 20%02ld.%ld.%ld\n",
+ fprintf(f, "\tDate: 20%02lu.%lu.%lu\n",
emv_value_numeric(tlv, 0, 2),
emv_value_numeric(tlv, 2, 4),
emv_value_numeric(tlv, 4, 6));
@@ -667,9 +667,9 @@ static void emv_tag_dump_cvm_list(const struct tlv *tlv, const struct emv_tag *t
Y = emv_get_binary(tlv->value + 4);
PRINT_INDENT(level);
- fprintf(f, "\tX: %d\n", X);
+ fprintf(f, "\tX: %u\n", X);
PRINT_INDENT(level);
- fprintf(f, "\tY: %d\n", Y);
+ fprintf(f, "\tY: %u\n", Y);
for (i = 8; i < tlv->len; i += 2) {
const char *method;
@@ -773,7 +773,7 @@ bool emv_tag_dump(const struct tlv *tlv, FILE *f, int level) {
const struct emv_tag *tag = emv_get_tag(tlv);
PRINT_INDENT(level);
- fprintf(f, "--%2hx[%02zx] '%s':", tlv->tag, tlv->len, tag->name);
+ fprintf(f, "--%2x[%02zx] '%s':", tlv->tag, tlv->len, tag->name);
switch (tag->type) {
case EMV_TAG_GENERIC:
diff --git a/client/emv/emvcore.c b/client/emv/emvcore.c
index 43d6ddaf1..d30c307d4 100644
--- a/client/emv/emvcore.c
+++ b/client/emv/emvcore.c
@@ -34,24 +34,24 @@ typedef struct {
static const TAIDList AIDlist [] = {
// Visa International
- { CV_VISA, "A00000000305076010"}, // VISA ELO Credit
- { CV_VISA, "A0000000031010" }, // VISA Debit/Credit (Classic)
- { CV_VISA, "A000000003101001" }, // VISA Credit
- { CV_VISA, "A000000003101002" }, // VISA Debit
- { CV_VISA, "A0000000032010" }, // VISA Electron
- { CV_VISA, "A0000000032020" }, // VISA
- { CV_VISA, "A0000000033010" }, // VISA Interlink
- { CV_VISA, "A0000000034010" }, // VISA Specific
- { CV_VISA, "A0000000035010" }, // VISA Specific
- { CV_VISA, "A0000000036010" }, // Domestic Visa Cash Stored Value
- { CV_VISA, "A0000000036020" }, // International Visa Cash Stored Value
- { CV_VISA, "A0000000038002" }, // VISA Auth, VisaRemAuthen EMV-CAP (DPA)
- { CV_VISA, "A0000000038010" }, // VISA Plus
- { CV_VISA, "A0000000039010" }, // VISA Loyalty
- { CV_VISA, "A000000003999910" }, // VISA Proprietary ATM
+ { CV_VISA, "A00000000305076010" }, // VISA ELO Credit
+ { CV_VISA, "A0000000031010" }, // VISA Debit/Credit (Classic)
+ { CV_VISA, "A000000003101001" }, // VISA Credit
+ { CV_VISA, "A000000003101002" }, // VISA Debit
+ { CV_VISA, "A0000000032010" }, // VISA Electron
+ { CV_VISA, "A0000000032020" }, // VISA
+ { CV_VISA, "A0000000033010" }, // VISA Interlink
+ { CV_VISA, "A0000000034010" }, // VISA Specific
+ { CV_VISA, "A0000000035010" }, // VISA Specific
+ { CV_VISA, "A0000000036010" }, // Domestic Visa Cash Stored Value
+ { CV_VISA, "A0000000036020" }, // International Visa Cash Stored Value
+ { CV_VISA, "A0000000038002" }, // VISA Auth, VisaRemAuthen EMV-CAP (DPA)
+ { CV_VISA, "A0000000038010" }, // VISA Plus
+ { CV_VISA, "A0000000039010" }, // VISA Loyalty
+ { CV_VISA, "A000000003999910" }, // VISA Proprietary ATM
// Visa USA
- { CV_VISA, "A000000098" }, // Debit Card
- { CV_VISA, "A0000000980848" }, // Debit Card
+ { CV_VISA, "A000000098" }, // Debit Card
+ { CV_VISA, "A0000000980848" }, // Debit Card
// Mastercard International
{ CV_MASTERCARD, "A00000000401" }, // MasterCard PayPass
{ CV_MASTERCARD, "A0000000041010" }, // MasterCard Credit
@@ -66,6 +66,7 @@ static const TAIDList AIDlist [] = {
{ CV_MASTERCARD, "A0000000046000" }, // Cirrus
{ CV_MASTERCARD, "A0000000048002" }, // SecureCode Auth EMV-CAP
{ CV_MASTERCARD, "A0000000049999" }, // MasterCard PayPass
+ { CV_MASTERCARD, "B012345678" }, // Maestro TEST Used for development
// American Express
{ CV_AMERICANEXPRESS, "A000000025" },
{ CV_AMERICANEXPRESS, "A0000000250000" },
@@ -82,11 +83,41 @@ static const TAIDList AIDlist [] = {
// JCB CO., LTD.
{ CV_JCB, "A00000006510" }, // JCB
{ CV_JCB, "A0000000651010" }, // JCB J Smart Credit
+ // Switch Card Services Ltd.
+ { CV_SWITCH, "A0000000050001" }, // Maestro UK
+ { CV_SWITCH, "A0000000050002" }, // Solo
+ // Diners Club International Ltd.
+ { CV_DINERS, "A0000001523010" }, // Discover, Pulse D Pas Discover Card
+ { CV_DINERS, "A0000001524010" }, // Discover, Discover Debit Common Card
// Other
- { CV_OTHER, "A0000001544442" }, // Banricompras Debito - Banrisul - Banco do Estado do Rio Grande do SUL - S.A.
- { CV_OTHER, "F0000000030001" }, // BRADESCO
- { CV_OTHER, "A0000005241010" }, // RuPay - RuPay
- { CV_OTHER, "D5780000021010" } // Bankaxept - Bankaxept
+ { CV_OTHER, "A00000002401" }, // Midland Bank Plc - Self Service
+ { CV_OTHER, "A0000000291010" }, // LINK Interchange Network Ltd - Link / American Express
+ { CV_OTHER, "A00000006900" }, // Société Européenne de Monnaie Electronique SEME - Moneo
+ { CV_OTHER, "A000000077010000021000000000003B" }, // Oberthur Technologies France - Visa AEPN
+ { CV_OTHER, "A0000001211010" }, // PBS Danmark A/S - Denmark - Dankort (VISA GEM Vision) - Danish domestic debit card
+ { CV_OTHER, "A0000001410001" }, // Associazione Bancaria Italiana - Italy - PagoBANCOMAT - CoGeBan Consorzio BANCOMAT (Italian domestic debit card)
+ { CV_OTHER, "A0000001544442" }, // Banricompras Debito - Banrisul - Banco do Estado do Rio Grande do SUL - S.A.
+ { CV_OTHER, "A000000172950001" }, // Financial Information Service Co. Ltd. - Taiwan - BAROC Financial Application Taiwan- The Bankers Association of the Republic of China
+ { CV_OTHER, "A0000001850002" }, // Post Office Limited - United Kingdom - UK Post Office Account card
+ { CV_OTHER, "A0000002281010" }, // Saudi Arabian Monetary Agency (SAMA) - Kingdom of Saudi Arabia - SPAN (M/Chip) - SPAN2 (Saudi Payments Network) - Saudi Arabia domestic credit/debit card (Saudi Arabia Monetary Agency)
+ { CV_OTHER, "A0000002282010" }, // Saudi Arabian Monetary Agency (SAMA) - Kingdom of Saudi Arabia - SPAN (VIS) - SPAN2 (Saudi Payments Network) - Saudi Arabia domestic credit/debit card (Saudi Arabia Monetary Agency)
+ { CV_OTHER, "A0000002771010" }, // Interac Association - Canada - INTERAC - Canadian domestic credit/debit card
+ { CV_OTHER, "A00000031510100528" }, // Currence Holding/PIN BV - The Netherlands- Currence PuC
+ { CV_OTHER, "A0000003156020" }, // Currence Holding/PIN BV - The Netherlands - Chipknip
+ { CV_OTHER, "A0000003591010028001" }, // Euro Alliance of Payment Schemes s.c.r.l. (EAPS) - Belgium - Girocard EAPS - ZKA (Germany)
+ { CV_OTHER, "A0000003710001" }, // Verve - Nigeria - InterSwitch Verve Card - Nigerian local switch company
+ { CV_OTHER, "A0000004540010" }, // eTranzact - Nigeria - Etranzact Genesis Card - Nigerian local switch company
+ { CV_OTHER, "A0000004540011" }, // eTranzact - Nigeria - Etranzact Genesis Card 2 - Nigerian local switch company
+ { CV_OTHER, "A0000004766C" }, // Google - United States - GOOGLE_PAYMENT_AID
+ { CV_OTHER, "A0000005241010" }, // RuPay - India - RuPay - RuPay (India)
+ { CV_OTHER, "A0000006723010" }, // TROY - Turkey - TROY chip credit card - Turkey's Payment Method
+ { CV_OTHER, "A0000006723020" }, // TROY - Turkey - TROY chip debit card - Turkey's Payment Method
+ { CV_OTHER, "A0000007705850" }, // Indian Oil Corporation Limited - India - XTRAPOWER Fleet Card Program - Indian Oil’s Pre Paid Program
+ { CV_OTHER, "D27600002545500100" }, // ZKA - Germany - Girocard - ZKA Girocard (Geldkarte) (Germany)
+ { CV_OTHER, "D4100000030001" }, // KS X 6923/6924 (T-Money, South Korea and Snapper+, Wellington, New Zealand)
+ { CV_OTHER, "D5280050218002" }, // The Netherlands - ? - (Netherlands)
+ { CV_OTHER, "D5780000021010" }, // Bankaxept Norway Bankaxept Norwegian domestic debit card
+ { CV_OTHER, "F0000000030001" }, // BRADESCO - Brazilian Bank Banco Bradesco
};
static const size_t AIDlistLen = sizeof(AIDlist) / sizeof(TAIDList);
@@ -403,6 +434,8 @@ int EMVSearchPSE(EMVCommandChannel channel, bool ActivateField, bool LeaveFieldO
int res;
bool fileFound = false;
+ char *PSE_or_PPSE = PSENum == 1 ? "PSE" : "PPSE";
+
// select PPSE
res = EMVSelectPSE(channel, ActivateField, true, PSENum, data, sizeof(data), &datalen, &sw);
@@ -452,7 +485,7 @@ int EMVSearchPSE(EMVCommandChannel channel, bool ActivateField, bool LeaveFieldO
if (tsfi) {
struct tlvdb *tsfitmp = tlvdb_find_path(tsfi, (tlv_tag_t[]) {0x70, 0x61, 0x00});
if (!tsfitmp) {
- PrintAndLogEx(FAILED, "SFI 0x%02d don't have records.", sfidatalen[ui]);
+ PrintAndLogEx(FAILED, "SFI 0x%02d doesn't have any records.", sfidatalen[ui]);
continue;
}
res = EMVCheckAID(channel, decodeTLV, tsfitmp, tlv);
@@ -472,14 +505,14 @@ int EMVSearchPSE(EMVCommandChannel channel, bool ActivateField, bool LeaveFieldO
}
if (!fileFound)
- PrintAndLogEx(FAILED, "PPSE don't have records.");
+ PrintAndLogEx(FAILED, "PPSE doesn't have any records.");
tlvdb_free(t);
} else {
- PrintAndLogEx(WARNING, "PPSE ERROR: Can't get TLV from response.");
+ PrintAndLogEx(WARNING, "%s ERROR: Can't get TLV from response.", PSE_or_PPSE);
}
} else {
- PrintAndLogEx(WARNING, "PPSE ERROR: Can't select PPSE AID. Error: %d", res);
+ PrintAndLogEx(WARNING, "%s ERROR: Can't select PPSE AID. Error: %d", PSE_or_PPSE, res);
}
if (!LeaveFieldON)
@@ -798,7 +831,7 @@ int trDDA(EMVCommandChannel channel, bool decodeTLV, struct tlvdb *tlv) {
return 4;
}
- PrintAndLogEx(NORMAL, "\n* * Calc DDOL");
+ PrintAndLogEx(NORMAL, "\n* Calc DDOL");
const struct tlv *ddol_tlv = tlvdb_get(tlv, 0x9f49, NULL);
if (!ddol_tlv) {
ddol_tlv = &default_ddol_tlv;
@@ -816,7 +849,7 @@ int trDDA(EMVCommandChannel channel, bool decodeTLV, struct tlvdb *tlv) {
PrintAndLogEx(NORMAL, "DDOL data[%d]: %s", ddol_data_tlv->len, sprint_hex(ddol_data_tlv->value, ddol_data_tlv->len));
- PrintAndLogEx(NORMAL, "\n* * Internal Authenticate");
+ PrintAndLogEx(NORMAL, "\n* Internal Authenticate");
int res = EMVInternalAuthenticate(channel, true, (uint8_t *)ddol_data_tlv->value, ddol_data_tlv->len, buf, sizeof(buf), &len, &sw, NULL);
if (res) {
PrintAndLogEx(WARNING, "Internal Authenticate error(%d): %4x. Exit...", res, sw);
@@ -843,7 +876,7 @@ int trDDA(EMVCommandChannel channel, bool decodeTLV, struct tlvdb *tlv) {
tlvdb_free(t80);
if (decodeTLV) {
- PrintAndLogEx(NORMAL, "* * * Decode response format 1:");
+ PrintAndLogEx(NORMAL, "* * Decode response format 1:");
TLVPrintFromTLV(dda_db);
}
}
@@ -934,7 +967,7 @@ int trCDA(struct tlvdb *tlv, struct tlvdb *ac_tlv, struct tlv *pdol_data_tlv, st
struct emv_pk *icc_pk = emv_pki_recover_icc_cert(issuer_pk, tlv, sda_tlv);
if (!icc_pk) {
- PrintAndLogEx(WARNING, "Error: ICC setrificate not found. Exit.");
+ PrintAndLogEx(WARNING, "Error: ICC certificate not found. Exit.");
emv_pk_free(pk);
emv_pk_free(issuer_pk);
return 2;
@@ -976,7 +1009,7 @@ int trCDA(struct tlvdb *tlv, struct tlvdb *ac_tlv, struct tlv *pdol_data_tlv, st
PrintAndLogEx(NORMAL, "CDA verified OK.");
tlvdb_add(tlv, idn_db);
} else {
- PrintAndLogEx(NORMAL, "\nERROR: CDA verify error");
+ PrintAndLogEx(ERR, "\nERROR: CDA verify error");
}
emv_pk_free(pk);
@@ -989,14 +1022,14 @@ int RecoveryCertificates(struct tlvdb *tlvRoot, json_t *root) {
struct emv_pk *pk = get_ca_pk(tlvRoot);
if (!pk) {
- PrintAndLog("ERROR: Key not found. Exit.");
+ PrintAndLogEx(ERR, "ERROR: Key not found. Exit.");
return 1;
}
struct emv_pk *issuer_pk = emv_pki_recover_issuer_cert(pk, tlvRoot);
if (!issuer_pk) {
emv_pk_free(pk);
- PrintAndLog("WARNING: Issuer certificate not found. Exit.");
+ PrintAndLogEx(WARNING, "WARNING: Issuer certificate not found. Exit.");
return 2;
}
PrintAndLogEx(SUCCESS, "Issuer PK recovered. RID %02hhx:%02hhx:%02hhx:%02hhx:%02hhx IDX %02hhx CSN %02hhx:%02hhx:%02hhx",
diff --git a/client/emv/emvcore.h b/client/emv/emvcore.h
index 7e9afabf7..25adc2b85 100644
--- a/client/emv/emvcore.h
+++ b/client/emv/emvcore.h
@@ -61,48 +61,50 @@ enum CardPSVendor {
CV_AMERICANEXPRESS,
CV_JCB,
CV_CB,
+ CV_SWITCH,
+ CV_DINERS,
CV_OTHER,
};
-extern enum CardPSVendor GetCardPSVendor(uint8_t *AID, size_t AIDlen);
+enum CardPSVendor GetCardPSVendor(uint8_t *AID, size_t AIDlen);
-extern bool TLVPrintFromBuffer(uint8_t *data, int datalen);
-extern void TLVPrintFromTLV(struct tlvdb *tlv);
-extern void TLVPrintFromTLVLev(struct tlvdb *tlv, int level);
-extern void TLVPrintAIDlistFromSelectTLV(struct tlvdb *tlv);
+bool TLVPrintFromBuffer(uint8_t *data, int datalen);
+void TLVPrintFromTLV(struct tlvdb *tlv);
+void TLVPrintFromTLVLev(struct tlvdb *tlv, int level);
+void TLVPrintAIDlistFromSelectTLV(struct tlvdb *tlv);
-extern struct tlvdb *GetPANFromTrack2(const struct tlv *track2);
-extern struct tlvdb *GetdCVVRawFromTrack2(const struct tlv *track2);
+struct tlvdb *GetPANFromTrack2(const struct tlv *track2);
+struct tlvdb *GetdCVVRawFromTrack2(const struct tlv *track2);
-extern void SetAPDULogging(bool logging);
+void SetAPDULogging(bool logging);
// exchange
-extern int EMVExchange(EMVCommandChannel channel, bool LeaveFieldON, sAPDU apdu, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw, struct tlvdb *tlv);
+int EMVExchange(EMVCommandChannel channel, bool LeaveFieldON, sAPDU apdu, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw, struct tlvdb *tlv);
// search application
-extern int EMVSearchPSE(EMVCommandChannel channel, bool ActivateField, bool LeaveFieldON, uint8_t PSENum, bool decodeTLV, struct tlvdb *tlv);
-extern int EMVSearch(EMVCommandChannel channel, bool ActivateField, bool LeaveFieldON, bool decodeTLV, struct tlvdb *tlv);
-extern int EMVSelectPSE(EMVCommandChannel channel, bool ActivateField, bool LeaveFieldON, uint8_t PSENum, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw);
-extern int EMVSelect(EMVCommandChannel channel, bool ActivateField, bool LeaveFieldON, uint8_t *AID, size_t AIDLen, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw, struct tlvdb *tlv);
+int EMVSearchPSE(EMVCommandChannel channel, bool ActivateField, bool LeaveFieldON, uint8_t PSENum, bool decodeTLV, struct tlvdb *tlv);
+int EMVSearch(EMVCommandChannel channel, bool ActivateField, bool LeaveFieldON, bool decodeTLV, struct tlvdb *tlv);
+int EMVSelectPSE(EMVCommandChannel channel, bool ActivateField, bool LeaveFieldON, uint8_t PSENum, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw);
+int EMVSelect(EMVCommandChannel channel, bool ActivateField, bool LeaveFieldON, uint8_t *AID, size_t AIDLen, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw, struct tlvdb *tlv);
// select application
-extern int EMVSelectApplication(struct tlvdb *tlv, uint8_t *AID, size_t *AIDlen);
+int EMVSelectApplication(struct tlvdb *tlv, uint8_t *AID, size_t *AIDlen);
// Get Processing Options
-extern int EMVGPO(EMVCommandChannel channel, bool LeaveFieldON, uint8_t *PDOL, size_t PDOLLen, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw, struct tlvdb *tlv);
-extern int EMVReadRecord(EMVCommandChannel channel, bool LeaveFieldON, uint8_t SFI, uint8_t SFIrec, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw, struct tlvdb *tlv);
+int EMVGPO(EMVCommandChannel channel, bool LeaveFieldON, uint8_t *PDOL, size_t PDOLLen, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw, struct tlvdb *tlv);
+int EMVReadRecord(EMVCommandChannel channel, bool LeaveFieldON, uint8_t SFI, uint8_t SFIrec, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw, struct tlvdb *tlv);
// AC
-extern int EMVGenerateChallenge(EMVCommandChannel channel, bool LeaveFieldON, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw, struct tlvdb *tlv);
-extern int EMVAC(EMVCommandChannel channel, bool LeaveFieldON, uint8_t RefControl, uint8_t *CDOL, size_t CDOLLen, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw, struct tlvdb *tlv);
+int EMVGenerateChallenge(EMVCommandChannel channel, bool LeaveFieldON, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw, struct tlvdb *tlv);
+int EMVAC(EMVCommandChannel channel, bool LeaveFieldON, uint8_t RefControl, uint8_t *CDOL, size_t CDOLLen, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw, struct tlvdb *tlv);
// DDA
-extern int EMVInternalAuthenticate(EMVCommandChannel channel, bool LeaveFieldON, uint8_t *DDOL, size_t DDOLLen, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw, struct tlvdb *tlv);
+int EMVInternalAuthenticate(EMVCommandChannel channel, bool LeaveFieldON, uint8_t *DDOL, size_t DDOLLen, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw, struct tlvdb *tlv);
// Mastercard
int MSCComputeCryptoChecksum(EMVCommandChannel channel, bool LeaveFieldON, uint8_t *UDOL, uint8_t UDOLlen, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw, struct tlvdb *tlv);
// Auth
-extern int trSDA(struct tlvdb *tlv);
-extern int trDDA(EMVCommandChannel channel, bool decodeTLV, struct tlvdb *tlv);
-extern int trCDA(struct tlvdb *tlv, struct tlvdb *ac_tlv, struct tlv *pdol_data_tlv, struct tlv *ac_data_tlv);
+int trSDA(struct tlvdb *tlv);
+int trDDA(EMVCommandChannel channel, bool decodeTLV, struct tlvdb *tlv);
+int trCDA(struct tlvdb *tlv, struct tlvdb *ac_tlv, struct tlv *pdol_data_tlv, struct tlv *ac_data_tlv);
-extern int RecoveryCertificates(struct tlvdb *tlvRoot, json_t *root);
+int RecoveryCertificates(struct tlvdb *tlvRoot, json_t *root);
-extern struct emv_pk *get_ca_pk(struct tlvdb *db);
+struct emv_pk *get_ca_pk(struct tlvdb *db);
#endif
diff --git a/client/emv/emvjson.h b/client/emv/emvjson.h
index 18326083f..23cfba545 100644
--- a/client/emv/emvjson.h
+++ b/client/emv/emvjson.h
@@ -18,24 +18,24 @@ typedef struct {
char *Name;
} ApplicationDataElm;
-extern char *GetApplicationDataName(tlv_tag_t tag);
+char *GetApplicationDataName(tlv_tag_t tag);
-extern int JsonSaveJsonObject(json_t *root, char *path, json_t *value);
-extern int JsonSaveStr(json_t *root, char *path, char *value);
-extern int JsonSaveInt(json_t *root, char *path, int value);
-extern int JsonSaveBufAsHexCompact(json_t *elm, char *path, uint8_t *data, size_t datalen);
-extern int JsonSaveBufAsHex(json_t *elm, char *path, uint8_t *data, size_t datalen);
-extern int JsonSaveHex(json_t *elm, char *path, uint64_t data, int datalen);
+int JsonSaveJsonObject(json_t *root, char *path, json_t *value);
+int JsonSaveStr(json_t *root, char *path, char *value);
+int JsonSaveInt(json_t *root, char *path, int value);
+int JsonSaveBufAsHexCompact(json_t *elm, char *path, uint8_t *data, size_t datalen);
+int JsonSaveBufAsHex(json_t *elm, char *path, uint8_t *data, size_t datalen);
+int JsonSaveHex(json_t *elm, char *path, uint64_t data, int datalen);
-extern int JsonSaveTLVValue(json_t *root, char *path, struct tlvdb *tlvdbelm);
-extern int JsonSaveTLVElm(json_t *elm, char *path, struct tlv *tlvelm, bool saveName, bool saveValue, bool saveAppDataLink);
-extern int JsonSaveTLVTreeElm(json_t *elm, char *path, struct tlvdb *tlvdbelm, bool saveName, bool saveValue, bool saveAppDataLink);
+int JsonSaveTLVValue(json_t *root, char *path, struct tlvdb *tlvdbelm);
+int JsonSaveTLVElm(json_t *elm, char *path, struct tlv *tlvelm, bool saveName, bool saveValue, bool saveAppDataLink);
+int JsonSaveTLVTreeElm(json_t *elm, char *path, struct tlvdb *tlvdbelm, bool saveName, bool saveValue, bool saveAppDataLink);
-extern int JsonSaveTLVTree(json_t *root, json_t *elm, char *path, struct tlvdb *tlvdbelm);
+int JsonSaveTLVTree(json_t *root, json_t *elm, char *path, struct tlvdb *tlvdbelm);
-extern int JsonLoadStr(json_t *root, char *path, char *value);
-extern int JsonLoadBufAsHex(json_t *elm, char *path, uint8_t *data, size_t maxbufferlen, size_t *datalen);
+int JsonLoadStr(json_t *root, char *path, char *value);
+int JsonLoadBufAsHex(json_t *elm, char *path, uint8_t *data, size_t maxbufferlen, size_t *datalen);
-extern bool ParamLoadFromJson(struct tlvdb *tlv);
+bool ParamLoadFromJson(struct tlvdb *tlv);
#endif
diff --git a/client/emv/test/cda_test.h b/client/emv/test/cda_test.h
index 8d80043cd..e535c2eee 100644
--- a/client/emv/test/cda_test.h
+++ b/client/emv/test/cda_test.h
@@ -15,4 +15,4 @@
#include
-extern int exec_cda_test(bool verbose);
+int exec_cda_test(bool verbose);
diff --git a/client/emv/test/crypto_test.h b/client/emv/test/crypto_test.h
index 04159c4f0..afc8a1515 100644
--- a/client/emv/test/crypto_test.h
+++ b/client/emv/test/crypto_test.h
@@ -15,4 +15,4 @@
#include
-extern int exec_crypto_test(bool verbose);
+int exec_crypto_test(bool verbose);
diff --git a/client/emv/test/cryptotest.c b/client/emv/test/cryptotest.c
index 39043e544..4bb49f039 100644
--- a/client/emv/test/cryptotest.c
+++ b/client/emv/test/cryptotest.c
@@ -94,7 +94,7 @@ int ExecuteCryptoTests(bool verbose) {
res = roca_self_test();
if (res) TestFail = true;
- PrintAndLog("\n--------------------------");
+ PrintAndLogEx(NORMAL, "\n--------------------------");
if (TestFail)
PrintAndLogEx(FAILED, "\tTest(s) [ %s ]", _RED_("FAIL"));
diff --git a/client/emv/test/cryptotest.h b/client/emv/test/cryptotest.h
index 5c6aaae2d..671de244e 100644
--- a/client/emv/test/cryptotest.h
+++ b/client/emv/test/cryptotest.h
@@ -10,4 +10,4 @@
#include
-extern int ExecuteCryptoTests(bool verbose);
+int ExecuteCryptoTests(bool verbose);
diff --git a/client/emv/test/dda_test.h b/client/emv/test/dda_test.h
index 1ae1a0660..34381938a 100644
--- a/client/emv/test/dda_test.h
+++ b/client/emv/test/dda_test.h
@@ -15,4 +15,4 @@
#include
-extern int exec_dda_test(bool verbose);
+int exec_dda_test(bool verbose);
diff --git a/client/emv/test/sda_test.h b/client/emv/test/sda_test.h
index 8d47aa9b3..696a17f9b 100644
--- a/client/emv/test/sda_test.h
+++ b/client/emv/test/sda_test.h
@@ -13,4 +13,4 @@
* Lesser General Public License for more details.
*/
-extern int exec_sda_test(bool verbose);
+int exec_sda_test(bool verbose);
diff --git a/client/fido/cbortools.h b/client/fido/cbortools.h
index 1e3fa8c0f..d42506658 100644
--- a/client/fido/cbortools.h
+++ b/client/fido/cbortools.h
@@ -21,18 +21,18 @@
#define cbor_check_if(r) if ((r) != CborNoError) {return r;} else
#define cbor_check(r) if ((r) != CborNoError) return r;
-extern int TinyCborPrintFIDOPackage(uint8_t cmdCode, bool isResponse, uint8_t *data, size_t length);
-extern int JsonToCbor(json_t *elm, CborEncoder *encoder);
+int TinyCborPrintFIDOPackage(uint8_t cmdCode, bool isResponse, uint8_t *data, size_t length);
+int JsonToCbor(json_t *elm, CborEncoder *encoder);
-extern int CborMapGetKeyById(CborParser *parser, CborValue *map, uint8_t *data, size_t dataLen, int key);
-extern CborError CborGetArrayBinStringValue(CborValue *elm, uint8_t *data, size_t maxdatalen, size_t *datalen);
-extern CborError CborGetArrayBinStringValueEx(CborValue *elm, uint8_t *data, size_t maxdatalen, size_t *datalen, uint8_t *delimeter, size_t delimeterlen);
-extern CborError CborGetBinStringValue(CborValue *elm, uint8_t *data, size_t maxdatalen, size_t *datalen);
-extern CborError CborGetArrayStringValue(CborValue *elm, char *data, size_t maxdatalen, size_t *datalen, char *delimeter);
-extern CborError CborGetStringValue(CborValue *elm, char *data, size_t maxdatalen, size_t *datalen);
-extern CborError CborGetStringValueBuf(CborValue *elm);
+int CborMapGetKeyById(CborParser *parser, CborValue *map, uint8_t *data, size_t dataLen, int key);
+CborError CborGetArrayBinStringValue(CborValue *elm, uint8_t *data, size_t maxdatalen, size_t *datalen);
+CborError CborGetArrayBinStringValueEx(CborValue *elm, uint8_t *data, size_t maxdatalen, size_t *datalen, uint8_t *delimeter, size_t delimeterlen);
+CborError CborGetBinStringValue(CborValue *elm, uint8_t *data, size_t maxdatalen, size_t *datalen);
+CborError CborGetArrayStringValue(CborValue *elm, char *data, size_t maxdatalen, size_t *datalen, char *delimeter);
+CborError CborGetStringValue(CborValue *elm, char *data, size_t maxdatalen, size_t *datalen);
+CborError CborGetStringValueBuf(CborValue *elm);
-extern int CBOREncodeElm(json_t *root, char *rootElmId, CborEncoder *encoder);
-extern CborError CBOREncodeClientDataHash(json_t *root, CborEncoder *encoder);
+int CBOREncodeElm(json_t *root, char *rootElmId, CborEncoder *encoder);
+CborError CBOREncodeClientDataHash(json_t *root, CborEncoder *encoder);
#endif /* __CBORTOOLS_H__ */
diff --git a/client/fido/cose.h b/client/fido/cose.h
index 850652fc4..f8f28aabf 100644
--- a/client/fido/cose.h
+++ b/client/fido/cose.h
@@ -17,11 +17,11 @@
#include
#include
-extern const char *GetCOSEAlgName(int id);
-extern const char *GetCOSEAlgDescription(int id);
-extern const char *GetCOSEktyDescription(int id);
-extern const char *GetCOSECurveDescription(int id);
+const char *GetCOSEAlgName(int id);
+const char *GetCOSEAlgDescription(int id);
+const char *GetCOSEktyDescription(int id);
+const char *GetCOSECurveDescription(int id);
-extern int COSEGetECDSAKey(uint8_t *data, size_t datalen, bool verbose, uint8_t *public_key);
+int COSEGetECDSAKey(uint8_t *data, size_t datalen, bool verbose, uint8_t *public_key);
#endif /* __COSE_H__ */
diff --git a/client/fido/fidocore.h b/client/fido/fidocore.h
index 60923a44b..676dd2646 100644
--- a/client/fido/fidocore.h
+++ b/client/fido/fidocore.h
@@ -35,23 +35,23 @@ typedef enum {
ptResponse,
} fido2PacketType;
-extern int FIDOSelect(bool ActivateField, bool LeaveFieldON, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw);
-extern int FIDOExchange(sAPDU apdu, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw);
-extern int FIDORegister(uint8_t *params, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw);
-extern int FIDOAuthentication(uint8_t *params, uint8_t paramslen, uint8_t controlb, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw);
-extern int FIDO2GetInfo(uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw);
-extern int FIDO2MakeCredential(uint8_t *params, uint8_t paramslen, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw);
-extern int FIDO2GetAssertion(uint8_t *params, uint8_t paramslen, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw);
+int FIDOSelect(bool ActivateField, bool LeaveFieldON, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw);
+int FIDOExchange(sAPDU apdu, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw);
+int FIDORegister(uint8_t *params, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw);
+int FIDOAuthentication(uint8_t *params, uint8_t paramslen, uint8_t controlb, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw);
+int FIDO2GetInfo(uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw);
+int FIDO2MakeCredential(uint8_t *params, uint8_t paramslen, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw);
+int FIDO2GetAssertion(uint8_t *params, uint8_t paramslen, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw);
-extern int FIDOCheckDERAndGetKey(uint8_t *der, size_t derLen, bool verbose, uint8_t *publicKey, size_t publicKeyMaxLen);
+int FIDOCheckDERAndGetKey(uint8_t *der, size_t derLen, bool verbose, uint8_t *publicKey, size_t publicKeyMaxLen);
-extern char *fido2GetCmdMemberDescription(uint8_t cmdCode, bool isResponse, int memberNum);
-extern char *fido2GetCmdErrorDescription(uint8_t errorCode);
+char *fido2GetCmdMemberDescription(uint8_t cmdCode, bool isResponse, int memberNum);
+char *fido2GetCmdErrorDescription(uint8_t errorCode);
-extern bool CheckrpIdHash(json_t *json, uint8_t *hash);
-extern int FIDO2CreateMakeCredentionalReq(json_t *root, uint8_t *data, size_t maxdatalen, size_t *datalen);
-extern int FIDO2MakeCredentionalParseRes(json_t *root, uint8_t *data, size_t dataLen, bool verbose, bool verbose2, bool showCBOR, bool showDERTLV);
-extern int FIDO2CreateGetAssertionReq(json_t *root, uint8_t *data, size_t maxdatalen, size_t *datalen, bool createAllowList);
-extern int FIDO2GetAssertionParseRes(json_t *root, uint8_t *data, size_t dataLen, bool verbose, bool verbose2, bool showCBOR);
+bool CheckrpIdHash(json_t *json, uint8_t *hash);
+int FIDO2CreateMakeCredentionalReq(json_t *root, uint8_t *data, size_t maxdatalen, size_t *datalen);
+int FIDO2MakeCredentionalParseRes(json_t *root, uint8_t *data, size_t dataLen, bool verbose, bool verbose2, bool showCBOR, bool showDERTLV);
+int FIDO2CreateGetAssertionReq(json_t *root, uint8_t *data, size_t maxdatalen, size_t *datalen, bool createAllowList);
+int FIDO2GetAssertionParseRes(json_t *root, uint8_t *data, size_t dataLen, bool verbose, bool verbose2, bool showCBOR);
#endif /* __FIDOCORE_H__ */
diff --git a/client/flasher.c b/client/flasher.c
index bc744b339..be74ef8e6 100644
--- a/client/flasher.c
+++ b/client/flasher.c
@@ -22,12 +22,12 @@
void cmd_debug(UsbCommand *c) {
// Debug
- printf("UsbCommand length[len=%zd]\n", sizeof(UsbCommand));
- printf(" cmd[len=%zd]: %016" PRIx64"\n", sizeof(c->cmd), c->cmd);
- printf(" arg0[len=%zd]: %016" PRIx64"\n", sizeof(c->arg[0]), c->arg[0]);
- printf(" arg1[len=%zd]: %016" PRIx64"\n", sizeof(c->arg[1]), c->arg[1]);
- printf(" arg2[len=%zd]: %016" PRIx64"\n", sizeof(c->arg[2]), c->arg[2]);
- printf(" data[len=%zd]: ", sizeof(c->d.asBytes));
+ printf("UsbCommand length[len=%zu]\n", sizeof(UsbCommand));
+ printf(" cmd[len=%zu]: %016" PRIx64"\n", sizeof(c->cmd), c->cmd);
+ printf(" arg0[len=%zu]: %016" PRIx64"\n", sizeof(c->arg[0]), c->arg[0]);
+ printf(" arg1[len=%zu]: %016" PRIx64"\n", sizeof(c->arg[1]), c->arg[1]);
+ printf(" arg2[len=%zu]: %016" PRIx64"\n", sizeof(c->arg[2]), c->arg[2]);
+ printf(" data[len=%zu]: ", sizeof(c->d.asBytes));
for (size_t i = 0; i < 16; i++)
printf("%02x", c->d.asBytes[i]);
diff --git a/client/fpga_compress.c b/client/fpga_compress.c
index 0f4220632..4b0350c06 100644
--- a/client/fpga_compress.c
+++ b/client/fpga_compress.c
@@ -98,12 +98,12 @@ int zlib_compress(FILE *infile[], uint8_t num_infiles, FILE *outfile, bool hardn
#if __WORDSIZE == 64
"Input file too big (> %" PRIu64 " bytes). This is probably not a hardnested bitflip state table.\n"
#else
- "Input file too big (> %lu bytes). This is probably not a hardnested bitflip state table.\n"
+ "Input file too big (> %li bytes). This is probably not a hardnested bitflip state table.\n"
#endif
, HARDNESTED_TABLE_SIZE);
} else {
- fprintf(stderr, "Input files too big (total > %lu bytes). These are probably not PM3 FPGA config files.\n", num_infiles * FPGA_CONFIG_SIZE);
+ fprintf(stderr, "Input files too big (total > %li bytes). These are probably not PM3 FPGA config files.\n", num_infiles * FPGA_CONFIG_SIZE);
}
for (uint16_t j = 0; j < num_infiles; j++) {
fclose(infile[j]);
@@ -206,7 +206,9 @@ int zlib_decompress(FILE *infile, FILE *outfile) {
compressed_fpga_stream.opaque = Z_NULL;
ret = inflateInit2(&compressed_fpga_stream, 0);
-
+ if ( ret < 0 )
+ return (EXIT_FAILURE);
+
do {
if (compressed_fpga_stream.avail_in == 0) {
compressed_fpga_stream.next_in = inbuf;
diff --git a/client/graph.c b/client/graph.c
index 4decd40c8..1557efb7d 100644
--- a/client/graph.c
+++ b/client/graph.c
@@ -59,8 +59,8 @@ void save_restoreGB(uint8_t saveOpt) {
return;
}
-void setGraphBuf(uint8_t *buf, size_t size) {
- if (buf == NULL) return;
+void setGraphBuf(uint8_t *buff, size_t size) {
+ if (buff == NULL) return;
ClearGraph(false);
@@ -68,21 +68,21 @@ void setGraphBuf(uint8_t *buf, size_t size) {
size = MAX_GRAPH_TRACE_LEN;
for (uint32_t i = 0; i < size; ++i)
- GraphBuffer[i] = buf[i] - 128;
+ GraphBuffer[i] = buff[i] - 128;
GraphTraceLen = size;
RepaintGraphWindow();
return;
}
-size_t getFromGraphBuf(uint8_t *buf) {
- if (buf == NULL) return 0;
+size_t getFromGraphBuf(uint8_t *buff) {
+ if (buff == NULL) return 0;
uint32_t i;
for (i = 0; i < GraphTraceLen; ++i) {
//trim
if (GraphBuffer[i] > 127) GraphBuffer[i] = 127;
if (GraphBuffer[i] < -127) GraphBuffer[i] = -127;
- buf[i] = (uint8_t)(GraphBuffer[i] + 128);
+ buff[i] = (uint8_t)(GraphBuffer[i] + 128);
}
return i;
}
diff --git a/client/hardnested/hardnested_bf_core.h b/client/hardnested/hardnested_bf_core.h
index bd0e83c68..872fa2d08 100644
--- a/client/hardnested/hardnested_bf_core.h
+++ b/client/hardnested/hardnested_bf_core.h
@@ -61,10 +61,10 @@ typedef enum {
SIMD_MMX,
SIMD_NONE,
} SIMDExecInstr;
-extern void SetSIMDInstr(SIMDExecInstr instr);
-extern SIMDExecInstr GetSIMDInstrAuto();
+void SetSIMDInstr(SIMDExecInstr instr);
+SIMDExecInstr GetSIMDInstrAuto();
-extern const uint64_t crack_states_bitsliced(uint32_t cuid, uint8_t *best_first_bytes, statelist_t *p, uint32_t *keys_found, uint64_t *num_keys_tested, uint32_t nonces_to_bruteforce, uint8_t *bf_test_nonces_2nd_byte, noncelist_t *nonces);
-extern void bitslice_test_nonces(uint32_t nonces_to_bruteforce, uint32_t *bf_test_nonces, uint8_t *bf_test_nonce_par);
+const uint64_t crack_states_bitsliced(uint32_t cuid, uint8_t *best_first_bytes, statelist_t *p, uint32_t *keys_found, uint64_t *num_keys_tested, uint32_t nonces_to_bruteforce, uint8_t *bf_test_nonce_2nd_byte, noncelist_t *nonces);
+void bitslice_test_nonces(uint32_t nonces_to_bruteforce, uint32_t *bf_test_nonce, uint8_t *bf_test_nonce_par);
#endif
diff --git a/client/hardnested/hardnested_bitarray_core.c b/client/hardnested/hardnested_bitarray_core.c
index 788d95597..e9e84aa40 100644
--- a/client/hardnested/hardnested_bitarray_core.c
+++ b/client/hardnested/hardnested_bitarray_core.c
@@ -593,8 +593,8 @@ uint32_t bitcount(uint32_t a) {
return (*bitcount_function_p)(a);
}
-uint32_t count_states(uint32_t *bitarray) {
- return (*count_states_function_p)(bitarray);
+uint32_t count_states(uint32_t *A) {
+ return (*count_states_function_p)(A);
}
void bitarray_AND(uint32_t *A, uint32_t *B) {
diff --git a/client/hardnested/hardnested_bitarray_core.h b/client/hardnested/hardnested_bitarray_core.h
index b12fcf89d..91515b57f 100644
--- a/client/hardnested/hardnested_bitarray_core.h
+++ b/client/hardnested/hardnested_bitarray_core.h
@@ -52,18 +52,18 @@ THE SOFTWARE.
#include
-extern uint32_t *malloc_bitarray(uint32_t x);
-extern void free_bitarray(uint32_t *x);
-extern uint32_t bitcount(uint32_t a);
-extern uint32_t count_states(uint32_t *A);
-extern void bitarray_AND(uint32_t *A, uint32_t *B);
-extern void bitarray_low20_AND(uint32_t *A, uint32_t *B);
-extern uint32_t count_bitarray_AND(uint32_t *A, uint32_t *B);
-extern uint32_t count_bitarray_low20_AND(uint32_t *A, uint32_t *B);
-extern void bitarray_AND4(uint32_t *A, uint32_t *B, uint32_t *C, uint32_t *D);
-extern void bitarray_OR(uint32_t *A, uint32_t *B);
-extern uint32_t count_bitarray_AND2(uint32_t *A, uint32_t *B);
-extern uint32_t count_bitarray_AND3(uint32_t *A, uint32_t *B, uint32_t *C);
-extern uint32_t count_bitarray_AND4(uint32_t *A, uint32_t *B, uint32_t *C, uint32_t *D);
+uint32_t *malloc_bitarray(uint32_t x);
+void free_bitarray(uint32_t *x);
+uint32_t bitcount(uint32_t a);
+uint32_t count_states(uint32_t *A);
+void bitarray_AND(uint32_t *A, uint32_t *B);
+void bitarray_low20_AND(uint32_t *A, uint32_t *B);
+uint32_t count_bitarray_AND(uint32_t *A, uint32_t *B);
+uint32_t count_bitarray_low20_AND(uint32_t *A, uint32_t *B);
+void bitarray_AND4(uint32_t *A, uint32_t *B, uint32_t *C, uint32_t *D);
+void bitarray_OR(uint32_t *A, uint32_t *B);
+uint32_t count_bitarray_AND2(uint32_t *A, uint32_t *B);
+uint32_t count_bitarray_AND3(uint32_t *A, uint32_t *B, uint32_t *C);
+uint32_t count_bitarray_AND4(uint32_t *A, uint32_t *B, uint32_t *C, uint32_t *D);
#endif
diff --git a/client/hardnested/hardnested_bruteforce.h b/client/hardnested/hardnested_bruteforce.h
index c104e69ac..180e537d8 100644
--- a/client/hardnested/hardnested_bruteforce.h
+++ b/client/hardnested/hardnested_bruteforce.h
@@ -27,10 +27,10 @@ typedef struct {
void *next;
} statelist_t;
-extern void prepare_bf_test_nonces(noncelist_t *nonces, uint8_t best_first_byte);
-extern bool brute_force_bs(float *bf_rate, statelist_t *candidates, uint32_t cuid, uint32_t num_acquired_nonces, uint64_t maximum_states, noncelist_t *nonces, uint8_t *best_first_bytes, uint64_t *found_key);
-extern float brute_force_benchmark();
-extern uint8_t trailing_zeros(uint8_t byte);
-extern bool verify_key(uint32_t cuid, noncelist_t *nonces, uint8_t *best_first_bytes, uint32_t odd, uint32_t even);
+void prepare_bf_test_nonces(noncelist_t *nonces, uint8_t best_first_byte);
+bool brute_force_bs(float *bf_rate, statelist_t *candidates, uint32_t cuid, uint32_t num_acquired_nonces, uint64_t maximum_states, noncelist_t *nonces, uint8_t *best_first_bytes, uint64_t *found_key);
+float brute_force_benchmark();
+uint8_t trailing_zeros(uint8_t byte);
+bool verify_key(uint32_t cuid, noncelist_t *nonces, uint8_t *best_first_bytes, uint32_t odd, uint32_t even);
#endif
diff --git a/client/hid-flasher/flash.c b/client/hid-flasher/flash.c
index 020be9e87..967888e17 100644
--- a/client/hid-flasher/flash.c
+++ b/client/hid-flasher/flash.c
@@ -180,7 +180,7 @@ static int check_segs(flash_file_t *ctx, int can_write_bl) {
// Load an ELF file and prepare it for flashing
int flash_load(flash_file_t *ctx, const char *name, int can_write_bl) {
- FILE *fd = NULL;
+ FILE *fd;
Elf32_Ehdr ehdr;
Elf32_Phdr *phdrs = NULL;
int num_phdrs;
@@ -413,7 +413,7 @@ int flash_write(flash_file_t *ctx) {
uint32_t blocks = (length + BLOCK_SIZE - 1) / BLOCK_SIZE;
uint32_t end = seg->start + length;
- fprintf(stderr, " 0x%08x..0x%08x [0x%x / %d blocks]",
+ fprintf(stderr, " 0x%08x..0x%08x [0x%x / %u blocks]",
seg->start, end - 1, length, blocks);
int block = 0;
@@ -427,7 +427,7 @@ int flash_write(flash_file_t *ctx) {
if (write_block(baddr, data, block_size) < 0) {
fprintf(stderr, " ERROR\n");
- fprintf(stderr, "Error writing block %d of %d\n", block, blocks);
+ fprintf(stderr, "Error writing block %d of %u\n", block, blocks);
return -1;
}
diff --git a/client/hid-flasher/proxusb.c b/client/hid-flasher/proxusb.c
index f7ff5d489..7563429d8 100644
--- a/client/hid-flasher/proxusb.c
+++ b/client/hid-flasher/proxusb.c
@@ -166,7 +166,7 @@ usb_dev_handle *findProxmark(int verbose, unsigned int *iface) {
usb_dev_handle *OpenProxmark(int verbose) {
int ret;
- usb_dev_handle *handle = NULL;
+ usb_dev_handle *handle;
unsigned int iface;
handle = findProxmark(verbose, &iface);
diff --git a/client/jansson/jansson.h b/client/jansson/jansson.h
index b832a791f..6f42d68c1 100644
--- a/client/jansson/jansson.h
+++ b/client/jansson/jansson.h
@@ -243,7 +243,7 @@ int json_array_append_new(json_t *json, json_t *value);
int json_array_insert_new(json_t *json, size_t index, json_t *value);
int json_array_remove(json_t *json, size_t index);
int json_array_clear(json_t *json);
-int json_array_extend(json_t *json, json_t *other);
+int json_array_extend(json_t *json, json_t *other_json);
static JSON_INLINE
int json_array_set(json_t *array, size_t ind, json_t *value) {
@@ -262,16 +262,16 @@ int json_array_insert(json_t *array, size_t ind, json_t *value) {
const char *json_string_value(const json_t *json);
size_t json_string_length(const json_t *json);
-json_int_t json_integer_value(const json_t *integer);
-double json_real_value(const json_t *real);
+json_int_t json_integer_value(const json_t *json);
+double json_real_value(const json_t *json);
double json_number_value(const json_t *json);
int json_string_set(json_t *json, const char *value);
int json_string_setn(json_t *json, const char *value, size_t len);
int json_string_set_nocheck(json_t *json, const char *value);
int json_string_setn_nocheck(json_t *json, const char *value, size_t len);
-int json_integer_set(json_t *integer, json_int_t value);
-int json_real_set(json_t *real, double value);
+int json_integer_set(json_t *json, json_int_t value);
+int json_real_set(json_t *json, double value);
/* pack, unpack */
@@ -294,13 +294,13 @@ json_t *json_vsprintf(const char *fmt, va_list ap) JANSSON_ATTRS(warn_unused_res
/* equality */
-int json_equal(const json_t *value1, const json_t *value2);
+int json_equal(const json_t *json1, const json_t *json2);
/* copying */
-json_t *json_copy(json_t *value) JANSSON_ATTRS(warn_unused_result);
-json_t *json_deep_copy(const json_t *value) JANSSON_ATTRS(warn_unused_result);
+json_t *json_copy(json_t *json) JANSSON_ATTRS(warn_unused_result);
+json_t *json_deep_copy(const json_t *json) JANSSON_ATTRS(warn_unused_result);
json_t *json_path_get(const json_t *json, const char *path);
int json_path_set_new(json_t *json, const char *path, json_t *value, size_t flags, json_error_t *error);
@@ -320,12 +320,12 @@ int json_path_set(json_t *json, const char *path, json_t *value, size_t flags, j
typedef size_t (*json_load_callback_t)(void *buffer, size_t buflen, void *data);
-json_t *json_loads(const char *input, size_t flags, json_error_t *error) JANSSON_ATTRS(warn_unused_result);
+json_t *json_loads(const char *string, size_t flags, json_error_t *error) JANSSON_ATTRS(warn_unused_result);
json_t *json_loadb(const char *buffer, size_t buflen, size_t flags, json_error_t *error) JANSSON_ATTRS(warn_unused_result);
json_t *json_loadf(FILE *input, size_t flags, json_error_t *error) JANSSON_ATTRS(warn_unused_result);
json_t *json_loadfd(int input, size_t flags, json_error_t *error) JANSSON_ATTRS(warn_unused_result);
json_t *json_load_file(const char *path, size_t flags, json_error_t *error) JANSSON_ATTRS(warn_unused_result);
-json_t *json_load_callback(json_load_callback_t callback, void *data, size_t flags, json_error_t *error) JANSSON_ATTRS(warn_unused_result);
+json_t *json_load_callback(json_load_callback_t callback, void *arg, size_t flags, json_error_t *error) JANSSON_ATTRS(warn_unused_result);
/* encoding */
diff --git a/client/jansson/jansson_private.h b/client/jansson/jansson_private.h
index 5957f70b2..094d79e75 100644
--- a/client/jansson/jansson_private.h
+++ b/client/jansson/jansson_private.h
@@ -84,12 +84,11 @@ void jsonp_error_vset(json_error_t *error, int line, int column,
/* Locale independent string<->double conversions */
int jsonp_strtod(strbuffer_t *strbuffer, double *out);
-int jsonp_dtostr(char *buffer, size_t size, double value, int prec);
+int jsonp_dtostr(char *buffer, size_t size, double value, int precision);
/* Wrappers for custom memory functions */
void *jsonp_malloc(size_t size) JANSSON_ATTRS(warn_unused_result);
void jsonp_free(void *ptr);
-char *jsonp_strndup(const char *str, size_t length) JANSSON_ATTRS(warn_unused_result);
char *jsonp_strdup(const char *str) JANSSON_ATTRS(warn_unused_result);
char *jsonp_strndup(const char *str, size_t len) JANSSON_ATTRS(warn_unused_result);
diff --git a/client/jansson/utf.c b/client/jansson/utf.c
index 003c422bd..61f0a381b 100644
--- a/client/jansson/utf.c
+++ b/client/jansson/utf.c
@@ -122,7 +122,7 @@ const char *utf8_iterate(const char *buffer, size_t bufsize, int32_t *codepoint)
return buffer;
count = utf8_check_first(buffer[0]);
- if (count <= 0)
+ if (count == 0)
return NULL;
if (count == 1)
diff --git a/client/jansson/utf.h b/client/jansson/utf.h
index e182df78f..0ca69253e 100644
--- a/client/jansson/utf.h
+++ b/client/jansson/utf.h
@@ -20,7 +20,7 @@ int utf8_encode(int32_t codepoint, char *buffer, size_t *size);
size_t utf8_check_first(char byte);
size_t utf8_check_full(const char *buffer, size_t size, int32_t *codepoint);
-const char *utf8_iterate(const char *buffer, size_t size, int32_t *codepoint);
+const char *utf8_iterate(const char *buffer, size_t bufsize, int32_t *codepoint);
int utf8_check_string(const char *string, size_t length);
diff --git a/client/loclass/elite_crack.c b/client/loclass/elite_crack.c
index 038d8e475..5a280e7c1 100644
--- a/client/loclass/elite_crack.c
+++ b/client/loclass/elite_crack.c
@@ -539,7 +539,7 @@ int bruteforceFile(const char *filename, uint16_t keytable[]) {
long fsize = ftell(f);
fseek(f, 0, SEEK_SET);
- if (fsize < 0) {
+ if (fsize <= 0) {
PrintAndLogDevice(WARNING, "Error, when getting filesize");
fclose(f);
return 1;
diff --git a/client/loclass/fileutils.c b/client/loclass/fileutils.c
index 4ac77633a..d85adc0c8 100644
--- a/client/loclass/fileutils.c
+++ b/client/loclass/fileutils.c
@@ -292,7 +292,7 @@ int loadFile(const char *preferredName, const char *suffix, void *data, size_t m
long fsize = ftell(f);
fseek(f, 0, SEEK_SET);
- if (fsize < 0) {
+ if (fsize <= 0) {
PrintAndLogDevice(FAILED, "error, when getting filesize");
retval = 1;
goto out;
@@ -405,13 +405,13 @@ int loadFileJSON(const char *preferredName, const char *suffix, void *data, size
root = json_load_file(fileName, 0, &error);
if (!root) {
- PrintAndLog("ERROR: json " _YELLOW_("%s") " error on line %d: %s", fileName, error.line, error.text);
+ PrintAndLogEx(ERR, "ERROR: json " _YELLOW_("%s") " error on line %d: %s", fileName, error.line, error.text);
retval = 2;
goto out;
}
if (!json_is_object(root)) {
- PrintAndLog("ERROR: Invalid json " _YELLOW_("%s") " format. root must be an object.", fileName);
+ PrintAndLogEx(ERR, "ERROR: Invalid json " _YELLOW_("%s") " format. root must be an object.", fileName);
retval = 3;
goto out;
}
diff --git a/client/loclass/fileutils.h b/client/loclass/fileutils.h
index 7b358331a..ddc906725 100644
--- a/client/loclass/fileutils.h
+++ b/client/loclass/fileutils.h
@@ -75,7 +75,7 @@ int fileExists(const char *filename);
* @param datalen the length of the data
* @return 0 for ok, 1 for failz
*/
-extern int saveFile(const char *preferredName, const char *suffix, const void *data, size_t datalen);
+int saveFile(const char *preferredName, const char *suffix, const void *data, size_t datalen);
/**
* @brief Utility function to save data to a textfile (EML). This method takes a preferred name, but if that
@@ -89,7 +89,7 @@ extern int saveFile(const char *preferredName, const char *suffix, const void *d
* @param blocksize the length of one row
* @return 0 for ok, 1 for failz
*/
-extern int saveFileEML(const char *preferredName, const char *suffix, uint8_t *data, size_t datalen, size_t blocksize);
+int saveFileEML(const char *preferredName, const char *suffix, uint8_t *data, size_t datalen, size_t blocksize);
/** STUB
* @brief Utility function to save JSON data to a file. This method takes a preferred name, but if that
@@ -103,7 +103,7 @@ extern int saveFileEML(const char *preferredName, const char *suffix, uint8_t *d
* @param datalen the length of the data
* @return 0 for ok, 1 for failz
*/
-extern int saveFileJSON(const char *preferredName, const char *suffix, JSONFileType ftype, uint8_t *data, size_t datalen);
+int saveFileJSON(const char *preferredName, const char *suffix, JSONFileType ftype, uint8_t *data, size_t datalen);
/** STUB
* @brief Utility function to load data from a binary file. This method takes a preferred name.
@@ -116,7 +116,7 @@ extern int saveFileJSON(const char *preferredName, const char *suffix, JSONFileT
* @param datalen the number of bytes loaded from file
* @return 0 for ok, 1 for failz
*/
-extern int loadFile(const char *preferredName, const char *suffix, void *data, size_t maxdatalen, size_t *datalen);
+int loadFile(const char *preferredName, const char *suffix, void *data, size_t maxdatalen, size_t *datalen);
/**
* @brief Utility function to load data from a textfile (EML). This method takes a preferred name.
@@ -128,7 +128,7 @@ extern int loadFile(const char *preferredName, const char *suffix, void *data, s
* @param datalen the number of bytes loaded from file
* @return 0 for ok, 1 for failz
*/
-extern int loadFileEML(const char *preferredName, const char *suffix, void *data, size_t *datalen);
+int loadFileEML(const char *preferredName, const char *suffix, void *data, size_t *datalen);
/**
* @brief Utility function to load data from a JSON textfile. This method takes a preferred name.
@@ -141,7 +141,7 @@ extern int loadFileEML(const char *preferredName, const char *suffix, void *data
* @param datalen the number of bytes loaded from file
* @return 0 for ok, 1 for failz
*/
-extern int loadFileJSON(const char *preferredName, const char *suffix, void *data, size_t maxdatalen, size_t *datalen);
+int loadFileJSON(const char *preferredName, const char *suffix, void *data, size_t maxdatalen, size_t *datalen);
/**
@@ -156,7 +156,7 @@ extern int loadFileJSON(const char *preferredName, const char *suffix, void *dat
* @param keylen the number of bytes a key per row is
* @return 0 for ok, 1 for failz
*/
-extern int loadFileDICTIONARY(const char *preferredName, const char *suffix, void *data, size_t *datalen, uint8_t keylen, uint16_t *keycnt);
+int loadFileDICTIONARY(const char *preferredName, const char *suffix, void *data, size_t *datalen, uint8_t keylen, uint16_t *keycnt);
#define PrintAndLogDevice(level, format, args...) PrintAndLogEx(level, format , ## args)
#else
diff --git a/client/loclass/hash1_brute.h b/client/loclass/hash1_brute.h
index 4debebd0d..b26ad96d1 100644
--- a/client/loclass/hash1_brute.h
+++ b/client/loclass/hash1_brute.h
@@ -1,5 +1,5 @@
#ifndef HASH1_BRUTE_H
#define HASH1_BRUTE_H
-extern void brute_hash1();
+void brute_hash1();
#endif // HASH1_BRUTE_H
diff --git a/client/loclass/ikeys.c b/client/loclass/ikeys.c
index 16985ccb8..d7c965421 100644
--- a/client/loclass/ikeys.c
+++ b/client/loclass/ikeys.c
@@ -679,8 +679,7 @@ static bool readKeyFile(uint8_t key[8]) {
if (bytes_read == 8)
retval = true;
- if (f)
- fclose(f);
+ fclose(f);
return retval;
}
diff --git a/client/mifare/mad.h b/client/mifare/mad.h
index 89fcd795c..d1028e06a 100644
--- a/client/mifare/mad.h
+++ b/client/mifare/mad.h
@@ -20,10 +20,10 @@ typedef struct {
const char *Description;
} madAIDDescr;
-extern int MADCheck(uint8_t *sector0, uint8_t *sector10, bool verbose, bool *haveMAD2);
-extern int MADDecode(uint8_t *sector0, uint8_t *sector10, uint16_t *mad, size_t *madlen);
-extern int MAD1DecodeAndPrint(uint8_t *sector, bool verbose, bool *haveMAD2);
-extern int MAD2DecodeAndPrint(uint8_t *sector, bool verbose);
+int MADCheck(uint8_t *sector0, uint8_t *sector10, bool verbose, bool *haveMAD2);
+int MADDecode(uint8_t *sector0, uint8_t *sector10, uint16_t *mad, size_t *madlen);
+int MAD1DecodeAndPrint(uint8_t *sector, bool verbose, bool *haveMAD2);
+int MAD2DecodeAndPrint(uint8_t *sector, bool verbose);
#endif // _MAD_H_
diff --git a/client/mifare/mfkey.h b/client/mifare/mfkey.h
index 0f8ba8069..4af5175a1 100644
--- a/client/mifare/mfkey.h
+++ b/client/mifare/mfkey.h
@@ -19,12 +19,12 @@
#include "mifare.h"
#include "crapto1/crapto1.h"
-extern uint32_t nonce2key(uint32_t uid, uint32_t nt, uint32_t nr, uint32_t ar, uint64_t par_info, uint64_t ks_info, uint64_t **keys);
-extern bool mfkey32(nonces_t data, uint64_t *outputkey);
-extern bool mfkey32_moebius(nonces_t data, uint64_t *outputkey);
-extern int mfkey64(nonces_t data, uint64_t *outputkey);
+uint32_t nonce2key(uint32_t uid, uint32_t nt, uint32_t nr, uint32_t ar, uint64_t par_info, uint64_t ks_info, uint64_t **keys);
+bool mfkey32(nonces_t data, uint64_t *outputkey);
+bool mfkey32_moebius(nonces_t data, uint64_t *outputkey);
+int mfkey64(nonces_t data, uint64_t *outputkey);
-extern int compare_uint64(const void *a, const void *b);
-extern uint32_t intersection(uint64_t *listA, uint64_t *listB);
+int compare_uint64(const void *a, const void *b);
+uint32_t intersection(uint64_t *listA, uint64_t *listB);
#endif
diff --git a/client/mifare/mifare4.c b/client/mifare/mifare4.c
index b3d40dd57..f3189f37f 100644
--- a/client/mifare/mifare4.c
+++ b/client/mifare/mifare4.c
@@ -164,7 +164,7 @@ int CalculateMAC(mf4Session *session, MACType_t mtype, uint8_t blockNum, uint8_t
}
if (verbose)
- PrintAndLog("MAC data[%d]: %s", macdatalen, sprint_hex(macdata, macdatalen));
+ PrintAndLogEx(NORMAL, "MAC data[%d]: %s", macdatalen, sprint_hex(macdata, macdatalen));
return aes_cmac8(NULL, session->Kmac, macdata, mac, macdatalen);
}
@@ -285,7 +285,7 @@ int MifareAuth4(mf4Session *session, uint8_t *keyn, uint8_t *key, bool activateF
DropField();
if (verbose)
- PrintAndLog("");
+ PrintAndLogEx(NORMAL, "");
if (session) {
session->Authenticated = true;
diff --git a/client/mifare/mifare4.h b/client/mifare/mifare4.h
index e33e69fd2..d403bdd94 100644
--- a/client/mifare/mifare4.h
+++ b/client/mifare/mifare4.h
@@ -43,25 +43,25 @@ typedef struct {
char *description;
} AccessConditions_t;
-extern void mfpSetVerboseMode(bool verbose);
-extern const char *mfpGetErrorDescription(uint8_t errorCode);
+void mfpSetVerboseMode(bool verbose);
+const char *mfpGetErrorDescription(uint8_t errorCode);
-extern int CalculateMAC(mf4Session *session, MACType_t mtype, uint8_t blockNum, uint8_t blockCount, uint8_t *data, int datalen, uint8_t *mac, bool verbose);
-extern int MifareAuth4(mf4Session *session, uint8_t *keyn, uint8_t *key, bool activateField, bool leaveSignalON, bool verbose);
+int CalculateMAC(mf4Session *session, MACType_t mtype, uint8_t blockNum, uint8_t blockCount, uint8_t *data, int datalen, uint8_t *mac, bool verbose);
+int MifareAuth4(mf4Session *session, uint8_t *keyn, uint8_t *key, bool activateField, bool leaveSignalON, bool verbose);
-extern int MFPWritePerso(uint8_t *keyNum, uint8_t *key, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen);
-extern int MFPCommitPerso(bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen);
-extern int MFPReadBlock(mf4Session *session, bool plain, uint8_t blockNum, uint8_t blockCount, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen, uint8_t *mac);
-extern int MFPWriteBlock(mf4Session *session, uint8_t blockNum, uint8_t *data, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen, uint8_t *mac);
-extern int mfpReadSector(uint8_t sectorNo, uint8_t keyType, uint8_t *key, uint8_t *dataout, bool verbose);
+int MFPWritePerso(uint8_t *keyNum, uint8_t *key, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen);
+int MFPCommitPerso(bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen);
+int MFPReadBlock(mf4Session *session, bool plain, uint8_t blockNum, uint8_t blockCount, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen, uint8_t *mac);
+int MFPWriteBlock(mf4Session *session, uint8_t blockNum, uint8_t *data, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen, uint8_t *mac);
+int mfpReadSector(uint8_t sectorNo, uint8_t keyType, uint8_t *key, uint8_t *dataout, bool verbose);
-extern char *mfGetAccessConditionsDesc(uint8_t blockn, uint8_t *data);
+char *mfGetAccessConditionsDesc(uint8_t blockn, uint8_t *data);
-extern uint8_t mfNumBlocksPerSector(uint8_t sectorNo);
-extern uint8_t mfFirstBlockOfSector(uint8_t sectorNo);
-extern uint8_t mfSectorTrailer(uint8_t blockNo);
-extern bool mfIsSectorTrailer(uint8_t blockNo);
-extern uint8_t mfSectorNum(uint8_t blockNo);
+uint8_t mfNumBlocksPerSector(uint8_t sectorNo);
+uint8_t mfFirstBlockOfSector(uint8_t sectorNo);
+uint8_t mfSectorTrailer(uint8_t blockNo);
+bool mfIsSectorTrailer(uint8_t blockNo);
+uint8_t mfSectorNum(uint8_t blockNo);
#endif // mifare4.h
diff --git a/client/mifare/mifarehost.c b/client/mifare/mifarehost.c
index 9c99f95a3..181d41e87 100644
--- a/client/mifare/mifarehost.c
+++ b/client/mifare/mifarehost.c
@@ -15,8 +15,6 @@ int mfDarkside(uint8_t blockno, uint8_t key_type, uint64_t *key) {
uint32_t nt = 0, nr = 0, ar = 0;
uint64_t par_list = 0, ks_list = 0;
uint64_t *keylist = NULL, *last_keylist = NULL;
- uint32_t keycount = 0;
- int16_t isOK = 0;
UsbCommand c = {CMD_READER_MIFARE, {true, blockno, key_type}};
@@ -49,7 +47,7 @@ int mfDarkside(uint8_t blockno, uint8_t key_type, uint64_t *key) {
UsbCommand resp;
if (WaitForResponseTimeout(CMD_ACK, &resp, 2000)) {
- isOK = resp.arg[0];
+ int16_t isOK = resp.arg[0];
if (isOK < 0)
return isOK;
@@ -69,7 +67,7 @@ int mfDarkside(uint8_t blockno, uint8_t key_type, uint64_t *key) {
}
c.arg[0] = false;
- keycount = nonce2key(uid, nt, nr, ar, par_list, ks_list, &keylist);
+ uint32_t keycount = nonce2key(uid, nt, nr, ar, par_list, ks_list, &keylist);
if (keycount == 0) {
PrintAndLogEx(FAILED, "key not found (lfsr_common_prefix list is null). Nt=%08x", nt);
@@ -383,7 +381,7 @@ int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo,
uint32_t max_keys = keycnt > (USB_CMD_DATA_SIZE / 6) ? (USB_CMD_DATA_SIZE / 6) : keycnt;
uint8_t keyBlock[USB_CMD_DATA_SIZE] = {0x00};
- for (int i = 0; i < keycnt; i += max_keys) {
+ for (i = 0; i < keycnt; i += max_keys) {
int size = keycnt - i > max_keys ? max_keys : keycnt - i;
@@ -502,14 +500,13 @@ int mfCSetUID(uint8_t *uid, uint8_t *atqa, uint8_t *sak, uint8_t *oldUID, uint8_
int mfCSetBlock(uint8_t blockNo, uint8_t *data, uint8_t *uid, uint8_t params) {
- uint8_t isOK = 0;
UsbCommand c = {CMD_MIFARE_CSETBLOCK, {params, blockNo, 0}};
memcpy(c.d.asBytes, data, 16);
clearCommandBuffer();
SendCommand(&c);
UsbCommand resp;
if (WaitForResponseTimeout(CMD_ACK, &resp, 1500)) {
- isOK = resp.arg[0] & 0xff;
+ uint8_t isOK = resp.arg[0] & 0xff;
if (uid != NULL)
memcpy(uid, resp.d.asBytes, 4);
if (!isOK)
@@ -522,13 +519,12 @@ int mfCSetBlock(uint8_t blockNo, uint8_t *data, uint8_t *uid, uint8_t params) {
}
int mfCGetBlock(uint8_t blockNo, uint8_t *data, uint8_t params) {
- uint8_t isOK = 0;
UsbCommand c = {CMD_MIFARE_CGETBLOCK, {params, blockNo, 0}};
clearCommandBuffer();
SendCommand(&c);
UsbCommand resp;
if (WaitForResponseTimeout(CMD_ACK, &resp, 1500)) {
- isOK = resp.arg[0] & 0xff;
+ uint8_t isOK = resp.arg[0] & 0xff;
if (!isOK)
return 2;
memcpy(data, resp.d.asBytes, 16);
@@ -555,15 +551,8 @@ static uint8_t traceCurKey = 0;
struct Crypto1State *traceCrypto1 = NULL;
struct Crypto1State *revstate = NULL;
-uint64_t key = 0;
-uint32_t ks2 = 0;
-uint32_t ks3 = 0;
uint32_t cuid = 0; // uid part used for crypto1.
-uint32_t nt = 0; // tag challenge
-uint32_t nr_enc = 0; // encrypted reader challenge
-uint32_t ar_enc = 0; // encrypted reader response
-uint32_t at_enc = 0; // encrypted tag response
int isTraceCardEmpty(void) {
return ((traceCard[0] == 0) && (traceCard[1] == 0) && (traceCard[2] == 0) && (traceCard[3] == 0));
@@ -605,18 +594,14 @@ int loadTraceCard(uint8_t *tuid, uint8_t uidlen) {
memset(buf, 0, sizeof(buf));
if (fgets(buf, sizeof(buf), f) == NULL) {
PrintAndLogEx(FAILED, "No trace file found or reading error.");
- if (f) {
- fclose(f);
- }
+ fclose(f);
return 2;
}
if (strlen(buf) < 32) {
if (feof(f)) break;
PrintAndLogEx(FAILED, "File content error. Block data must include 32 HEX symbols");
- if (f) {
- fclose(f);
- }
+ fclose(f);
return 2;
}
for (i = 0; i < 32; i += 2) {
@@ -628,9 +613,7 @@ int loadTraceCard(uint8_t *tuid, uint8_t uidlen) {
blockNum++;
}
- if (f) {
- fclose(f);
- }
+ fclose(f);
return 0;
}
@@ -677,14 +660,11 @@ int mfTraceInit(uint8_t *tuid, uint8_t uidlen, uint8_t *atqa, uint8_t sak, bool
}
void mf_crypto1_decrypt(struct Crypto1State *pcs, uint8_t *data, int len, bool isEncrypted) {
- uint8_t bt = 0;
- int i;
-
if (len != 1) {
- for (i = 0; i < len; i++)
+ for (int i = 0; i < len; i++)
data[i] = crypto1_byte(pcs, 0x00, isEncrypted) ^ data[i];
} else {
- bt = 0;
+ uint8_t bt = 0;
bt |= (crypto1_bit(pcs, 0, isEncrypted) ^ BIT(data[0], 0)) << 0;
bt |= (crypto1_bit(pcs, 0, isEncrypted) ^ BIT(data[0], 1)) << 1;
bt |= (crypto1_bit(pcs, 0, isEncrypted) ^ BIT(data[0], 2)) << 2;
@@ -694,7 +674,10 @@ void mf_crypto1_decrypt(struct Crypto1State *pcs, uint8_t *data, int len, bool i
}
int mfTraceDecode(uint8_t *data_src, int len, bool wantSaveToEmlFile) {
-
+ uint32_t nt = 0; // tag challenge
+ uint32_t nr_enc = 0; // encrypted reader challenge
+ uint32_t ar_enc = 0; // encrypted reader response
+ uint32_t at_enc = 0; // encrypted tag response
if (traceState == TRACE_ERROR)
return 1;
@@ -792,7 +775,7 @@ int mfTraceDecode(uint8_t *data_src, int len, bool wantSaveToEmlFile) {
case TRACE_AUTH1:
if (len == 4) {
traceState = TRACE_AUTH2;
- nt = bytes_to_num(data, 4);
+ //nt = bytes_to_num(data, 4);
return 0;
} else {
traceState = TRACE_ERROR;
@@ -802,8 +785,8 @@ int mfTraceDecode(uint8_t *data_src, int len, bool wantSaveToEmlFile) {
case TRACE_AUTH2:
if (len == 8) {
traceState = TRACE_AUTH_OK;
- nr_enc = bytes_to_num(data, 4);
- ar_enc = bytes_to_num(data + 4, 4);
+ //nr_enc = bytes_to_num(data, 4);
+ //ar_enc = bytes_to_num(data + 4, 4);
return 0;
} else {
traceState = TRACE_ERROR;
@@ -813,11 +796,13 @@ int mfTraceDecode(uint8_t *data_src, int len, bool wantSaveToEmlFile) {
case TRACE_AUTH_OK:
if (len == 4) {
traceState = TRACE_IDLE;
+ // encrypted tag response
at_enc = bytes_to_num(data, 4);
// mfkey64 recover key.
- ks2 = ar_enc ^ prng_successor(nt, 64);
- ks3 = at_enc ^ prng_successor(nt, 96);
+ uint64_t key = 0;
+ uint32_t ks2 = ar_enc ^ prng_successor(nt, 64);
+ uint32_t ks3 = at_enc ^ prng_successor(nt, 96);
revstate = lfsr_recovery64(ks2, ks3);
lfsr_rollback_word(revstate, 0, 0);
lfsr_rollback_word(revstate, 0, 0);
@@ -850,7 +835,7 @@ int mfTraceDecode(uint8_t *data_src, int len, bool wantSaveToEmlFile) {
} else {
PrintAndLogEx(NORMAL, "[!] nested key recovery not implemented!\n");
- at_enc = bytes_to_num(data, 4);
+ //at_enc = bytes_to_num(data, 4);
crypto1_destroy(traceCrypto1);
traceState = TRACE_ERROR;
}
@@ -865,8 +850,8 @@ int mfTraceDecode(uint8_t *data_src, int len, bool wantSaveToEmlFile) {
int tryDecryptWord(uint32_t nt, uint32_t ar_enc, uint32_t at_enc, uint8_t *data, int len) {
PrintAndLogEx(SUCCESS, "\nencrypted data: [%s]", sprint_hex(data, len));
struct Crypto1State *s;
- ks2 = ar_enc ^ prng_successor(nt, 64);
- ks3 = at_enc ^ prng_successor(nt, 96);
+ uint32_t ks2 = ar_enc ^ prng_successor(nt, 64);
+ uint32_t ks3 = at_enc ^ prng_successor(nt, 96);
s = lfsr_recovery64(ks2, ks3);
mf_crypto1_decrypt(s, data, len, false);
PrintAndLogEx(SUCCESS, "decrypted data: [%s]", sprint_hex(data, len));
@@ -960,7 +945,6 @@ int detect_classic_nackbug(bool verbose) {
int gc = getchar();
(void)gc;
return -1;
- break;
}
if (WaitForResponseTimeout(CMD_ACK, &resp, 500)) {
diff --git a/client/mifare/mifarehost.h b/client/mifare/mifarehost.h
index 626d2cd07..fd3935d41 100644
--- a/client/mifare/mifarehost.h
+++ b/client/mifare/mifarehost.h
@@ -69,35 +69,35 @@ typedef struct {
extern char logHexFileName[FILE_PATH_SIZE];
-extern int mfDarkside(uint8_t blockno, uint8_t key_type, uint64_t *key);
-extern int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *ResultKeys, bool calibrate);
-extern int mfCheckKeys(uint8_t blockNo, uint8_t keyType, bool clear_trace, uint8_t keycnt, uint8_t *keyBlock, uint64_t *key);
-extern int mfCheckKeys_fast(uint8_t sectorsCnt, uint8_t firstChunk, uint8_t lastChunk,
- uint8_t strategy, uint32_t size, uint8_t *keyBlock, sector_t *e_sector, bool use_flashmemory);
-extern int mfKeyBrute(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint64_t *resultkey);
+int mfDarkside(uint8_t blockno, uint8_t key_type, uint64_t *key);
+int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *resultKey, bool calibrate);
+int mfCheckKeys(uint8_t blockNo, uint8_t keyType, bool clear_trace, uint8_t keycnt, uint8_t *keyBlock, uint64_t *key);
+int mfCheckKeys_fast(uint8_t sectorsCnt, uint8_t firstChunk, uint8_t lastChunk,
+ uint8_t strategy, uint32_t size, uint8_t *keyBlock, sector_t *e_sector, bool use_flashmemory);
+int mfKeyBrute(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint64_t *resultkey);
-extern int mfReadSector(uint8_t sectorNo, uint8_t keyType, uint8_t *key, uint8_t *data);
+int mfReadSector(uint8_t sectorNo, uint8_t keyType, uint8_t *key, uint8_t *data);
-extern int mfEmlGetMem(uint8_t *data, int blockNum, int blocksCount);
-extern int mfEmlSetMem(uint8_t *data, int blockNum, int blocksCount);
-extern int mfEmlSetMem_xt(uint8_t *data, int blockNum, int blocksCount, int blockBtWidth);
+int mfEmlGetMem(uint8_t *data, int blockNum, int blocksCount);
+int mfEmlSetMem(uint8_t *data, int blockNum, int blocksCount);
+int mfEmlSetMem_xt(uint8_t *data, int blockNum, int blocksCount, int blockBtWidth);
-extern int mfCSetUID(uint8_t *uid, uint8_t *atqa, uint8_t *sak, uint8_t *oldUID, uint8_t wipecard);
-extern int mfCSetBlock(uint8_t blockNo, uint8_t *data, uint8_t *uid, uint8_t params);
-extern int mfCGetBlock(uint8_t blockNo, uint8_t *data, uint8_t params);
+int mfCSetUID(uint8_t *uid, uint8_t *atqa, uint8_t *sak, uint8_t *oldUID, uint8_t wipecard);
+int mfCSetBlock(uint8_t blockNo, uint8_t *data, uint8_t *uid, uint8_t params);
+int mfCGetBlock(uint8_t blockNo, uint8_t *data, uint8_t params);
-extern int mfTraceInit(uint8_t *tuid, uint8_t uidlen, uint8_t *atqa, uint8_t sak, bool wantSaveToEmlFile);
-extern int mfTraceDecode(uint8_t *data_src, int len, bool wantSaveToEmlFile);
+int mfTraceInit(uint8_t *tuid, uint8_t uidlen, uint8_t *atqa, uint8_t sak, bool wantSaveToEmlFile);
+int mfTraceDecode(uint8_t *data_src, int len, bool wantSaveToEmlFile);
-extern int isTraceCardEmpty(void);
-extern int isBlockEmpty(int blockN);
-extern int isBlockTrailer(int blockN);
-extern int loadTraceCard(uint8_t *tuid, uint8_t uidlen);
-extern int saveTraceCard(void);
-extern int tryDecryptWord(uint32_t nt, uint32_t ar_enc, uint32_t at_enc, uint8_t *data, int len);
+int isTraceCardEmpty(void);
+int isBlockEmpty(int blockN);
+int isBlockTrailer(int blockN);
+int loadTraceCard(uint8_t *tuid, uint8_t uidlen);
+int saveTraceCard(void);
+int tryDecryptWord(uint32_t nt, uint32_t ar_enc, uint32_t at_enc, uint8_t *data, int len);
-extern int detect_classic_prng(void);
-extern int detect_classic_nackbug(bool verbose);
-extern void detect_classic_magic(void);
-extern void mf_crypto1_decrypt(struct Crypto1State *pcs, uint8_t *data, int len, bool isEncrypted);
+int detect_classic_prng(void);
+int detect_classic_nackbug(bool verbose);
+void detect_classic_magic(void);
+void mf_crypto1_decrypt(struct Crypto1State *pcs, uint8_t *data, int len, bool isEncrypted);
#endif
diff --git a/client/mifare/ndef.c b/client/mifare/ndef.c
index b888d8269..12f89b53e 100644
--- a/client/mifare/ndef.c
+++ b/client/mifare/ndef.c
@@ -115,7 +115,6 @@ int ndefDecodeHeader(uint8_t *data, size_t datalen, NDEFHeader_t *header) {
if (header->IDLenPresent) {
header->IDLen = (header->ShortRecordBit ? (data[3]) : (data[6]));
- header->Payload = header->Type + header->TypeLen;
} else {
header->IDLen = 0;
}
@@ -344,7 +343,6 @@ int NDEFDecodeAndPrint(uint8_t *ndef, size_t ndefLen, bool verbose) {
case 0xfe: {
PrintAndLogEx(INFO, "-- NDEF Terminator. Done.");
return 0;
- break;
}
default: {
PrintAndLogEx(ERR, "unknown tag 0x%02x", ndef[indx]);
diff --git a/client/mifare/ndef.h b/client/mifare/ndef.h
index 1130ebba7..1737a6082 100644
--- a/client/mifare/ndef.h
+++ b/client/mifare/ndef.h
@@ -57,6 +57,6 @@ typedef struct {
uint8_t *ID;
} NDEFHeader_t;
-extern int NDEFDecodeAndPrint(uint8_t *ndef, size_t ndefLen, bool verbose);
+int NDEFDecodeAndPrint(uint8_t *ndef, size_t ndefLen, bool verbose);
#endif // _NDEF_H_
diff --git a/client/proxgui.h b/client/proxgui.h
index 5f6d8bd2a..0d43e7823 100644
--- a/client/proxgui.h
+++ b/client/proxgui.h
@@ -35,11 +35,11 @@ extern int offline;
extern bool GridLocked;
//Operations defined in data_operations
-//extern int autoCorr(const int* in, int *out, size_t len, int window);
-extern int AskEdgeDetect(const int *in, int *out, int len, int threshold);
-extern int AutoCorrelate(const int *in, int *out, size_t len, int window, bool SaveGrph, bool verbose);
-extern int directionalThreshold(const int *in, int *out, size_t len, int8_t up, int8_t down);
-extern void save_restoreGB(uint8_t saveOpt);
+//int autoCorr(const int* in, int *out, size_t len, int window);
+int AskEdgeDetect(const int *in, int *out, int len, int threshold);
+int AutoCorrelate(const int *in, int *out, size_t len, int window, bool SaveGrph, bool verbose);
+int directionalThreshold(const int *in, int *out, size_t len, int8_t up, int8_t down);
+void save_restoreGB(uint8_t saveOpt);
#define GRAPH_SAVE 1
#define GRAPH_RESTORE 0
diff --git a/client/reveng/reveng.h b/client/reveng/reveng.h
index 110b3f620..59a5f901a 100644
--- a/client/reveng/reveng.h
+++ b/client/reveng/reveng.h
@@ -99,7 +99,7 @@
typedef BMP_T bmp_t;
extern int bmpbit, bmpsub;
-extern void setbmp(void);
+void setbmp(void);
/* poly.c */
#define P_REFIN 1
@@ -139,41 +139,41 @@ typedef struct {
/* left-justified in each word */
} poly_t;
-extern poly_t filtop(FILE *input, unsigned long length, int flags, int bperhx);
-extern poly_t strtop(const char *string, int flags, int bperhx);
-extern char *ptostr(const poly_t poly, int flags, int bperhx);
-extern char *pxsubs(const poly_t poly, int flags, int bperhx, unsigned long start, unsigned long end);
-extern poly_t pclone(const poly_t poly);
-extern void pcpy(poly_t *dest, const poly_t src);
-extern void pcanon(poly_t *poly);
-extern void pnorm(poly_t *poly);
-extern void psnorm(poly_t *poly);
-extern void pchop(poly_t *poly);
-extern void pkchop(poly_t *poly);
-extern unsigned long plen(const poly_t poly);
-extern int pcmp(const poly_t *a, const poly_t *b);
-extern int psncmp(const poly_t *a, const poly_t *b);
-extern int ptst(const poly_t poly);
-extern unsigned long pfirst(const poly_t poly);
-extern unsigned long plast(const poly_t poly);
-extern poly_t psubs(const poly_t src, unsigned long head, unsigned long start, unsigned long end, unsigned long tail);
-extern void pright(poly_t *poly, unsigned long length);
-extern void pshift(poly_t *dest, const poly_t src, unsigned long head, unsigned long start, unsigned long end, unsigned long tail);
-extern void ppaste(poly_t *dest, const poly_t src, unsigned long skip, unsigned long seek, unsigned long end, unsigned long fulllength);
-extern void pdiff(poly_t *dest, const poly_t src, unsigned long ofs);
-extern void psum(poly_t *dest, const poly_t src, unsigned long ofs);
-extern void prev(poly_t *poly);
-extern void prevch(poly_t *poly, int bperhx);
-extern void prcp(poly_t *poly);
-extern void pinv(poly_t *poly);
-extern poly_t pmod(const poly_t dividend, const poly_t divisor);
-extern poly_t pcrc(const poly_t message, const poly_t divisor, const poly_t init, const poly_t xorout, int flags);
-extern int piter(poly_t *poly);
-extern void palloc(poly_t *poly, unsigned long length);
-extern void pfree(poly_t *poly);
-extern void praloc(poly_t *poly, unsigned long length);
-extern int pmpar(const poly_t poly, const poly_t mask);
-extern int pident(const poly_t a, const poly_t b);
+poly_t filtop(FILE *input, unsigned long length, int flags, int bperhx);
+poly_t strtop(const char *string, int flags, int bperhx);
+char *ptostr(const poly_t poly, int flags, int bperhx);
+char *pxsubs(const poly_t poly, int flags, int bperhx, unsigned long start, unsigned long end);
+poly_t pclone(const poly_t poly);
+void pcpy(poly_t *dest, const poly_t src);
+void pcanon(poly_t *poly);
+void pnorm(poly_t *poly);
+void psnorm(poly_t *poly);
+void pchop(poly_t *poly);
+void pkchop(poly_t *poly);
+unsigned long plen(const poly_t poly);
+int pcmp(const poly_t *a, const poly_t *b);
+int psncmp(const poly_t *a, const poly_t *b);
+int ptst(const poly_t poly);
+unsigned long pfirst(const poly_t poly);
+unsigned long plast(const poly_t poly);
+poly_t psubs(const poly_t src, unsigned long head, unsigned long start, unsigned long end, unsigned long tail);
+void pright(poly_t *poly, unsigned long length);
+void pshift(poly_t *dest, const poly_t src, unsigned long head, unsigned long start, unsigned long end, unsigned long tail);
+void ppaste(poly_t *dest, const poly_t src, unsigned long skip, unsigned long seek, unsigned long end, unsigned long fulllength);
+void pdiff(poly_t *dest, const poly_t src, unsigned long ofs);
+void psum(poly_t *dest, const poly_t src, unsigned long ofs);
+void prev(poly_t *poly);
+void prevch(poly_t *poly, int bperhx);
+void prcp(poly_t *poly);
+void pinv(poly_t *poly);
+poly_t pmod(const poly_t dividend, const poly_t divisor);
+poly_t pcrc(const poly_t message, const poly_t divisor, const poly_t init, const poly_t xorout, int flags);
+int piter(poly_t *poly);
+void palloc(poly_t *poly, unsigned long length);
+void pfree(poly_t *poly);
+void praloc(poly_t *poly, unsigned long length);
+int pmpar(const poly_t poly, const poly_t mask);
+int pident(const poly_t a, const poly_t b);
/* model.c */
@@ -190,23 +190,23 @@ typedef struct {
const char *name; /* optional canonical name of the model */
} model_t;
-extern void mcpy(model_t *dest, const model_t *src);
-extern void mfree(model_t *model);
-extern int mcmp(const model_t *a, const model_t *b);
-extern char *mtostr(const model_t *model);
-extern void mcanon(model_t *model);
-extern void mcheck(model_t *model);
-extern void mrev(model_t *model);
-extern void mnovel(model_t *model);
+void mcpy(model_t *dest, const model_t *src);
+void mfree(model_t *model);
+int mcmp(const model_t *a, const model_t *b);
+char *mtostr(const model_t *model);
+void mcanon(model_t *model);
+void mcheck(model_t *model);
+void mrev(model_t *model);
+void mnovel(model_t *model);
/* preset.c */
#define M_OVERWR 1
-extern int mbynam(model_t *dest, const char *key);
-extern void mbynum(model_t *dest, int num);
-extern int mcount(void);
-extern char *mnames(void);
-extern void mmatch(model_t *model, int flags);
+int mbynam(model_t *dest, const char *key);
+void mbynum(model_t *dest, int num);
+int mcount(void);
+char *mnames(void);
+void mmatch(model_t *model, int flags);
/* reveng.c */
#define R_HAVEP 1
@@ -218,7 +218,7 @@ extern void mmatch(model_t *model, int flags);
#define R_SPMASK 0x7FFFFFFUL
-extern model_t *reveng(const model_t *guess, const poly_t qpoly, int rflags, int args, const poly_t *argpolys);
+model_t *reveng(const model_t *guess, const poly_t qpoly, int rflags, int args, const poly_t *argpolys);
/* cli.c */
#define C_INFILE 1
@@ -228,9 +228,9 @@ extern model_t *reveng(const model_t *guess, const poly_t qpoly, int rflags, int
#define BUFFER 32768
-extern int reveng_main(int argc, char *argv[]);
-extern void ufound(const model_t *model);
-extern void uerror(const char *msg);
-extern void uprog(const poly_t gpoly, int flags, unsigned long seq);
+int reveng_main(int argc, char *argv[]);
+void ufound(const model_t *model);
+void uerror(const char *msg);
+void uprog(const poly_t gpoly, int flags, unsigned long seq);
#endif /* REVENG_H */
diff --git a/client/scandir.h b/client/scandir.h
index 7155c5a79..905431cbe 100644
--- a/client/scandir.h
+++ b/client/scandir.h
@@ -15,8 +15,8 @@
#include
#ifdef _WIN32
-extern int scandir(const char *dir, struct dirent ***namelist, int (*select)(const struct dirent *), int (*compar)(const struct dirent **, const struct dirent **));
-extern int alphasort(const struct dirent **a, const struct dirent **b);
+int scandir(const char *dir, struct dirent ***namelist, int (*select)(const struct dirent *), int (*compar)(const struct dirent **, const struct dirent **));
+int alphasort(const struct dirent **a, const struct dirent **b);
#endif // _WIN32
#endif // SCANDIR_H__
diff --git a/client/scripting.c b/client/scripting.c
index f3afb18d4..9c84bbf93 100644
--- a/client/scripting.c
+++ b/client/scripting.c
@@ -467,7 +467,7 @@ static int l_crc16(lua_State *L) {
size_t size;
const char *p_str = luaL_checklstring(L, 1, &size);
- uint16_t checksum = crc(CRC_CCITT, (uint8_t *) p_str, size);
+ uint16_t checksum = Crc(CRC_CCITT, (uint8_t *) p_str, size);
lua_pushunsigned(L, checksum);
return 1;
}
@@ -702,46 +702,46 @@ static int l_keygen_algoD(lua_State *L) {
}
/*
-Read T55Xx block.
+Read T55Xx block.
param1 uint8_t block
param2 bool page1
param3 bool override
param4 uint32_t password
*/
static int l_T55xx_readblock(lua_State *L) {
-
+
//Check number of arguments
int n = lua_gettop(L);
- if ( n != 4 ) {
- return returnToLuaWithError(L, "Wrong number of arguments, got %d bytes, expected 4", n);
+ if (n != 4) {
+ return returnToLuaWithError(L, "Wrong number of arguments, got %d bytes, expected 4", n);
}
-
+
uint32_t block, usepage1, override, password;
bool usepwd;
size_t size;
-
+
const char *p_blockno = luaL_checklstring(L, 1, &size);
if (size < 1 || size > 2) return returnToLuaWithError(L, "Wrong size of blockNo, got %d, expected 1 or 2", (int) size);
sscanf(p_blockno, "%x", &block);
-
+
const char *p_usepage1 = luaL_checklstring(L, 2, &size);
if (size != 1) return returnToLuaWithError(L, "Wrong size of usePage1, got %d, expected 1", (int) size);
sscanf(p_usepage1, "%x", &usepage1);
-
+
const char *p_override = luaL_checklstring(L, 3, &size);
if (size != 1) return returnToLuaWithError(L, "Wrong size of override, got %d, expected 1", (int) size);
sscanf(p_override, "%x", &override);
-
+
const char *p_pwd = luaL_checklstring(L, 4, &size);
- if ( size == 0 ) {
+ if (size == 0) {
usepwd = false;
} else {
if (size != 8) return returnToLuaWithError(L, "Wrong size of pwd, got %d , expected 8", (int) size);
sscanf(p_pwd, "%08x", &password);
usepwd = true;
- }
-
+ }
+
//Password mode
if (usepwd) {
// try reading the config block and verify that PWD bit is set before doing this!
@@ -767,16 +767,16 @@ static int l_T55xx_readblock(lua_State *L) {
if (!AquireData(usepage1, block, usepwd, password)) {
return returnToLuaWithError(L, "Failed to aquire data from card");
}
-
+
if (!DecodeT55xxBlock()) {
return returnToLuaWithError(L, "Failed to decode signal");
}
-
+
uint32_t blockData = 0;
if (GetT55xxBlockData(&blockData) == false) {
return returnToLuaWithError(L, "Failed to get actual data");
}
-
+
lua_pushunsigned(L, blockData);
return 1;
}
@@ -785,10 +785,9 @@ static int l_T55xx_readblock(lua_State *L) {
// arg 2 = use GB
static int l_T55xx_detect(lua_State *L) {
bool useGB = false, usepwd = false, isok;
- uint32_t password;
- uint32_t gb;
+ uint32_t gb, password = 0;
size_t size;
-
+
//Check number of arguments
int n = lua_gettop(L);
@@ -797,15 +796,15 @@ static int l_T55xx_detect(lua_State *L) {
const char *p_gb = luaL_checklstring(L, 2, &size);
if (size != 1) return returnToLuaWithError(L, "Wrong size of useGB, got %d , expected 1", (int) size);
sscanf(p_gb, "%u", &gb);
- useGB = ( gb ) ? true : false;
- printf("p_gb size %u | %c \n", size, useGB ? 'Y':'N');
+ useGB = (gb) ? true : false;
+ printf("p_gb size %zu | %c \n", size, useGB ? 'Y' : 'N');
}
case 1: {
const char *p_pwd = luaL_checklstring(L, 1, &size);
- if ( size == 0 ) {
+ if (size == 0) {
usepwd = false;
} else {
-
+
if (size != 8) return returnToLuaWithError(L, "Wrong size of pwd, got %d , expected 8", (int) size);
sscanf(p_pwd, "%08x", &password);
usepwd = true;
@@ -815,24 +814,24 @@ static int l_T55xx_detect(lua_State *L) {
default :
break;
}
-
+
if (!useGB) {
-
+
isok = AquireData(T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, usepwd, password);
- if ( isok == false ) {
+ if (isok == false) {
// signal error by returning Nil, errorstring
lua_pushnil(L);
lua_pushstring(L, "Failed to aquire LF signal data");
return 2;
}
}
-
+
isok = tryDetectModulation();
- if ( isok == false ) {
+ if (isok == false) {
// signal error by returning Nil, errorstring
lua_pushnil(L);
lua_pushstring(L, "Could not detect modulation automatically. Try setting it manually with \'lf t55xx config\'");
- return 2;
+ return 2;
}
lua_pushinteger(L, isok);
diff --git a/client/scripts/test_t55x7.lua b/client/scripts/test_t55x7.lua
new file mode 100644
index 000000000..710df0c3f
--- /dev/null
+++ b/client/scripts/test_t55x7.lua
@@ -0,0 +1,327 @@
+local cmds = require('commands')
+local getopt = require('getopt')
+local bin = require('bin')
+local utils = require('utils')
+
+local format=string.format
+local floor=math.floor
+
+copyright = ''
+author = "Iceman"
+version = ''
+desc =[[
+This script will program a T55x7 TAG with a configuration and four blocks of data.
+It will then try to detect and read back those block data and compare if read data matches the expected data.
+
+
+lf t55xx wipe
+lf t55xx detect
+lf t55xx write b 1 d 00000000
+lf t55xx write b 2 d ffffffff
+lf t55xx write b 3 d 80000000
+lf t55xx write b 4 d 00000001
+
+Loop:
+
+try write different configuration blocks, and read block1-4 and comparing the read values with the values used to write.
+
+testsuit for T55XX commands demodulation
+
+]]
+example = [[
+ 1. script run test_t55x7
+]]
+usage = [[
+
+script run test_t55x7
+
+Arguments:
+ -h this help
+]]
+
+local TIMEOUT = 2000 -- Shouldn't take longer than 2 seconds
+local DEBUG = false -- the debug flag
+local total_tests = 0
+local total_pass = 0
+
+local data_blocks_cmds = {
+ [1] = '00000000',
+ [2] = 'ffffffff',
+ [3] = '80000000',
+ [4] = '00000001',
+}
+
+---
+-- A debug printout-function
+local function dbg(args)
+ if not DEBUG then
+ return
+ end
+
+ if type(args) == "table" then
+ local i = 1
+ while args[i] do
+ dbg(args[i])
+ i = i+1
+ end
+ else
+ print("###", args)
+ end
+end
+---
+-- This is only meant to be used when errors occur
+local function oops(err)
+ print("ERROR: ",err)
+end
+---
+-- Usage help
+local function help()
+ print(copyright)
+ print(author)
+ print(version)
+ print(desc)
+ print("Example usage")
+ print(example)
+end
+---
+-- Exit message
+local function exitMsg(msg)
+ print( string.rep('--',20) )
+ print( string.rep('--',20) )
+ print(msg)
+ print()
+end
+---
+-- ask/fsk/psk configuration blocks to test
+local function GetConfigs( modulation )
+
+ local t = {}
+
+ t['PSK1'] = {
+ [1] = '00001040',
+ [2] = '00041040',
+ [3] = '00081040',
+ [4] = '000c1040',
+ [5] = '00101040',
+ [6] = '00141040',
+ [7] = '00181040',
+ [8] = '001c1040',
+ }
+
+ t['PSK2'] = {
+ [1] = '00002040',
+ [2] = '00042040',
+ [3] = '00082040',
+ [4] = '000c2040',
+ [5] = '00102040',
+ [6] = '00142040',
+ [7] = '00182040',
+ [8] = '001c2040',
+ }
+
+ t['PSK3'] = {
+ [1] = '00003040',
+ [2] = '00043040',
+ [3] = '00083040',
+ [4] = '000c3040',
+ [5] = '00103040',
+ [6] = '00143040',
+ [7] = '00183040',
+ [8] = '001c3040',
+ }
+
+ t['FSK1'] = {
+ [1] = '00004040',
+ [2] = '00004040',
+ [3] = '00044040',
+ [4] = '00084040',
+ [5] = '000c4040',
+ [6] = '00104040',
+ [7] = '00144040',
+ [8] = '00184040',
+ [9] = '001c4040',
+ }
+
+ t['FSK2'] = {
+ [1] = '00005040',
+ [2] = '00045040',
+ [3] = '00085040',
+ [4] = '000c5040',
+ [5] = '00105040',
+ [6] = '00145040',
+ [7] = '00185040',
+ [8] = '001c5040',
+ }
+
+ t['FSK1A'] = {
+ [1] = '00006040',
+ [2] = '00046040',
+ [3] = '00086040',
+ [4] = '000c6040',
+ [5] = '00106040',
+ [6] = '00146040',
+ [7] = '00186040',
+ [8] = '001c6040',
+ }
+
+ t['FSK2A'] = {
+ [1] = '00007040',
+ [2] = '00047040',
+ [3] = '00087040',
+ [4] = '000c7040',
+ [5] = '00107040',
+ [6] = '00147040',
+ [7] = '00187040',
+ [8] = '001c7040',
+ }
+
+ t['ASK'] = {
+ [1] = '00008040',
+ [2] = '00048040',
+ [3] = '00088040',
+ [4] = '000c8040',
+ [5] = '00108040',
+ [6] = '00148040',
+ [7] = '00188040',
+ [8] = '001c8040',
+ }
+
+ t['BI'] = {
+ [1] = '00010040',
+ [2] = '00050040',
+ [3] = '00090040',
+ [4] = '000d0040',
+ [5] = '00110040',
+ [6] = '00150040',
+ [7] = '00190040',
+ [8] = '001d0040',
+ }
+
+ return t[modulation:upper()]
+end
+---
+-- lf t55xx wipe
+local function WipeCard()
+
+ print('Wiping card')
+ core.console('lf t55xx wipe')
+
+ print('Detecting card')
+ local res, msg = core.t55xx_detect()
+ if not res then
+ oops("Can't detect modulation. Test failed.")
+ core.console("rem [ERR:DETECT:WIPED] Failed to detect after wipe")
+ return false
+ else
+ local wipe_data_cmd = "lf t55xx write b %s d %s"
+ for _ = 1, #data_blocks_cmds do
+ local val = data_blocks_cmds[_]
+ local c = string.format(wipe_data_cmd, _, val)
+ core.console(c)
+ end
+ return true
+ end
+end
+---
+-- lf t55xx read
+local function CheckReadBlock(block)
+ local data, msg
+ -- blockno, page1, override, pwd
+ data, msg = core.t55xx_readblock(block, "0", "0", "")
+ if not data then
+ return ""
+ end
+ return ('%08X'):format(data)
+end
+
+local function test(modulation)
+
+ local process_block0_cmds = {}
+ local y
+ local block = "00"
+
+ local s = ('Start test of %s'):format(modulation)
+ print(s)
+
+ process_block0_cmds = GetConfigs(modulation)
+
+ if process_block0_cmds == nil then return oops('Cant find modulation '..modulation) end
+
+ for _ = 1, #process_block0_cmds do
+
+ local p_config_cmd = process_block0_cmds[_]
+ local errors = 0
+ core.clearCommandBuffer()
+
+ -- Write Config block
+ dbg(('lf t55xx write b 0 d %s'):format(p_config_cmd))
+ local config = tonumber(p_config_cmd, 16)
+ local writecmd = Command:new{cmd = cmds.CMD_T55XX_WRITE_BLOCK,arg1 = config, arg2 = block, arg3 = '00', data = '00'}
+ local err = core.SendCommand(writecmd:getBytes())
+ if err then return oops(err) end
+ local response = core.WaitForResponseTimeout(cmds.CMD_ACK,TIMEOUT)
+
+ -- Detect
+ local res, msg = core.t55xx_detect()
+ if not res then
+ print("can't detect modulation, skip to next config")
+ core.console(format("rem [ERR:DETECT:%s] Failed to detect modulation", p_config_cmd))
+ core.console(format('rem [SUMMARY:%s] FAIL detection', p_config_cmd))
+ total_tests = total_tests + #data_blocks_cmds
+ else
+ -- Loop block1-2
+ for _ = 1, #data_blocks_cmds do
+ total_tests = total_tests + 1
+ local val = data_blocks_cmds[_]
+ local blockdata, msg = CheckReadBlock(_)
+ if blockdata:lower() ~= val:lower() then
+ print( ('Test %s == %s Failed'):format(val, blockdata))
+ core.console( format('rem [ERR:READ:%s:%d] block %d: read %s instead of %s', p_config_cmd, _, _, blockdata, val))
+ errors = errors+1
+ else
+ print( ('Test %s == %s OK'):format(val, blockdata))
+ total_pass = total_pass + 1
+ end
+ end
+ if errors >0 then
+ core.console( format('rem [SUMMARY:%s] FAIL %d test%s', p_config_cmd, errors, errors > 1 and "s" or ""))
+ else
+ core.console( format('rem [SUMMARY:%s] PASS all tests', p_config_cmd))
+ end
+ end
+ end
+end
+
+local function main(args)
+
+ print( string.rep('--',20) )
+ print( string.rep('--',20) )
+
+ -- Arguments for the script
+ for o, arg in getopt.getopt(args, 'h') do
+ if o == "h" then return help() end
+ end
+
+ core.clearCommandBuffer()
+ local res
+
+ -- Adjust this table to set which configurations should be tested
+-- local test_modes = { 'PSK1', 'PSK2', 'PSK3', 'FSK1', 'FSK2', 'FSK1A', 'FSK2A', 'ASK', 'BI' }
+ local test_modes = { 'ASK', 'PSK1' }
+
+ for _ = 1, #test_modes do
+ res = WipeCard()
+ if res then
+ print (test_modes[_])
+ test(test_modes[_])
+ else
+ exitMsg('Abort!')
+ return
+ end
+ end
+
+ exitMsg('Tests finished')
+ core.console( format('rem [SUMMARY] Success rate: %d/%d tests passed%s', total_pass, total_tests, total_pass < total_tests and ", help me improving that number!" or " \\o/"))
+
+end
+main(args)
diff --git a/client/tinycbor/cbor.h b/client/tinycbor/cbor.h
index a6175d3ab..238a2717f 100644
--- a/client/tinycbor/cbor.h
+++ b/client/tinycbor/cbor.h
@@ -409,7 +409,7 @@ CBOR_PRIVATE_API CborError _cbor_value_copy_string(const CborValue *value, void
CBOR_PRIVATE_API CborError _cbor_value_dup_string(const CborValue *value, void **buffer,
size_t *buflen, CborValue *next);
-CBOR_API CborError cbor_value_calculate_string_length(const CborValue *value, size_t *length);
+CBOR_API CborError cbor_value_calculate_string_length(const CborValue *value, size_t *len);
CBOR_INLINE_API CborError cbor_value_copy_text_string(const CborValue *value, char *buffer,
size_t *buflen, CborValue *next) {
diff --git a/client/tinycbor/cborinternal_p.h b/client/tinycbor/cborinternal_p.h
index 8609ce2ad..d971fa478 100644
--- a/client/tinycbor/cborinternal_p.h
+++ b/client/tinycbor/cborinternal_p.h
@@ -49,45 +49,45 @@ static inline double decode_half(unsigned short half) {
/* software implementation of float-to-fp16 conversions */
static inline unsigned short encode_half(double val) {
uint64_t v;
- int sign, exp, mant;
+ int sign, exp1, mant;
memcpy(&v, &val, sizeof(v));
sign = v >> 63 << 15;
- exp = (v >> 52) & 0x7ff;
+ exp1 = (v >> 52) & 0x7ff;
mant = v << 12 >> 12 >> (53 - 11); /* keep only the 11 most significant bits of the mantissa */
- exp -= 1023;
- if (exp == 1024) {
+ exp1 -= 1023;
+ if (exp1 == 1024) {
/* infinity or NaN */
- exp = 16;
+ exp1 = 16;
mant >>= 1;
- } else if (exp >= 16) {
+ } else if (exp1 >= 16) {
/* overflow, as largest number */
- exp = 15;
+ exp1 = 15;
mant = 1023;
- } else if (exp >= -14) {
+ } else if (exp1 >= -14) {
/* regular normal */
- } else if (exp >= -24) {
+ } else if (exp1 >= -24) {
/* subnormal */
mant |= 1024;
- mant >>= -(exp + 14);
- exp = -15;
+ mant >>= -(exp1 + 14);
+ exp1 = -15;
} else {
/* underflow, make zero */
return 0;
}
/* safe cast here as bit operations above guarantee not to overflow */
- return (unsigned short)(sign | ((exp + 15) << 10) | mant);
+ return (unsigned short)(sign | ((exp1 + 15) << 10) | mant);
}
/* this function was copied & adapted from RFC 7049 Appendix D */
static inline double decode_half(unsigned short half) {
- int exp = (half >> 10) & 0x1f;
+ int exp1 = (half >> 10) & 0x1f;
int mant = half & 0x3ff;
double val;
- if (exp == 0) val = ldexp(mant, -24);
- else if (exp != 31) val = ldexp(mant + 1024, exp - 25);
+ if (exp1 == 0) val = ldexp(mant, -24);
+ else if (exp1 != 31) val = ldexp(mant + 1024, exp1 - 25);
else val = mant == 0 ? INFINITY : NAN;
- return half & 0x8000 ? -val : val;
+ return (half & 0x8000) ? -val : val;
}
# endif
#endif /* CBOR_NO_HALF_FLOAT_TYPE */
diff --git a/client/tinycbor/cborparser.c b/client/tinycbor/cborparser.c
index 23e87f98a..2dade3a0d 100644
--- a/client/tinycbor/cborparser.c
+++ b/client/tinycbor/cborparser.c
@@ -208,7 +208,6 @@ static bool is_fixed_type(uint8_t type) {
static CborError preparse_value(CborValue *it) {
const CborParser *parser = it->parser;
- it->type = CborInvalidType;
/* are we at the end? */
if (it->ptr == parser->end)
diff --git a/client/tinycbor/cbortojson.c b/client/tinycbor/cbortojson.c
index 533e6a721..3ea90cee8 100644
--- a/client/tinycbor/cbortojson.c
+++ b/client/tinycbor/cbortojson.c
@@ -284,8 +284,7 @@ static CborError add_value_metadata(FILE *out, CborType type, const ConversionSt
type = flags & FinalTypeMask;
flags &= ~(FinalTypeMask | TypeWasTagged);
- if (fprintf(out, "\"tag\":\"%" PRIu64 "\"%s", status->lastTag,
- flags & ~TypeWasTagged ? "," : "") < 0)
+ if (fprintf(out, "\"tag\":\"%" PRIu64 "\"%s", status->lastTag, (flags & ~TypeWasTagged) ? "," : "") < 0)
return CborErrorIO;
}
@@ -300,11 +299,10 @@ static CborError add_value_metadata(FILE *out, CborType type, const ConversionSt
if (fprintf(out, ",\"v\":\"nan\"") < 0)
return CborErrorIO;
if (flags & NumberWasInfinite)
- if (fprintf(out, ",\"v\":\"%sinf\"", flags & NumberWasNegative ? "-" : "") < 0)
+ if (fprintf(out, ",\"v\":\"%sinf\"", (flags & NumberWasNegative) ? "-" : "") < 0)
return CborErrorIO;
if (flags & NumberPrecisionWasLost)
- if (fprintf(out, ",\"v\":\"%c%" PRIx64 "\"", flags & NumberWasNegative ? '-' : '+',
- status->originalNumber) < 0)
+ if (fprintf(out, ",\"v\":\"%c%" PRIx64 "\"", (flags & NumberWasNegative) ? '-' : '+', status->originalNumber) < 0)
return CborErrorIO;
if (type == CborSimpleType)
if (fprintf(out, ",\"v\":%d", (int)status->originalNumber) < 0)
diff --git a/client/ui.c b/client/ui.c
index d0318dba5..216fbccff 100644
--- a/client/ui.c
+++ b/client/ui.c
@@ -21,6 +21,8 @@ bool showDemod = true;
pthread_mutex_t print_lock = PTHREAD_MUTEX_INITIALIZER;
static char *logfilename = "proxmark3.log";
+float complex cexpf(float complex Z);
+
void PrintAndLogOptions(char *str[][2], size_t size, size_t space) {
char buff[2000] = "Options:\n";
char format[2000] = "";
@@ -53,7 +55,6 @@ void PrintAndLogEx(logLevel_t level, char *fmt, ...) {
char buffer[MAX_PRINT_BUFFER] = {0};
char buffer2[MAX_PRINT_BUFFER + 20] = {0};
char *token = NULL;
- int size = 0;
// {NORMAL, SUCCESS, INFO, FAILED, WARNING, ERR, DEBUG}
static char *prefixes[7] = { "", "[+] ", "[=] ", "[-] ", "[!] ", "[!!] ", "[#] "};
@@ -101,7 +102,7 @@ void PrintAndLogEx(logLevel_t level, char *fmt, ...) {
while (token != NULL) {
- size = strlen(buffer2);
+ size_t size = strlen(buffer2);
if (strlen(token))
snprintf(buffer2 + size, sizeof(buffer2) - size, "%s%s\n", prefix, token);
@@ -210,13 +211,11 @@ void iceIIR_Butterworth(int *data, const size_t len) {
float b[3] = {0.003621681514929, 0.007243363029857, 0.003621681514929};
float a[3] = {1.000000000000000, -1.822694925196308, 0.837181651256023};
- float sample = 0; // input sample read from array
- float complex x_prime = 1.0f; // save sample for estimating frequency
- float complex x;
-
for (i = 0; i < adjustedLen; ++i) {
- sample = data[i];
+ float sample = data[i]; // input sample read from array
+ float complex x_prime = 1.0f; // save sample for estimating frequency
+ float complex x;
// remove DC offset and mix to complex baseband
x = (sample - 127.5f) * cexpf(_Complex_I * 2 * M_PI * fc * i);
@@ -251,18 +250,14 @@ void iceSimple_Filter(int *data, const size_t len, uint8_t k) {
#define FILTER_SHIFT 4
int32_t filter_reg = 0;
- int16_t input, output;
int8_t shift = (k <= 8) ? k : FILTER_SHIFT;
for (int i = 0; i < len; ++i) {
-
- input = data[i];
// Update filter with current sample
- filter_reg = filter_reg - (filter_reg >> shift) + input;
+ filter_reg = filter_reg - (filter_reg >> shift) + data[i];
// Scale output for unity gain
- output = filter_reg >> shift;
- data[i] = output;
+ data[i] = filter_reg >> shift;
}
}
diff --git a/client/ui.h b/client/ui.h
index 827c3828e..cace7e6fd 100644
--- a/client/ui.h
+++ b/client/ui.h
@@ -33,10 +33,10 @@ void ShowGui(void);
void HideGraphWindow(void);
void ShowGraphWindow(void);
void RepaintGraphWindow(void);
-extern void PrintAndLog(char *fmt, ...);
+void PrintAndLog(char *fmt, ...);
void PrintAndLogOptions(char *str[][2], size_t size, size_t space);
void PrintAndLogEx(logLevel_t level, char *fmt, ...);
-extern void SetLogFilename(char *fn);
+void SetLogFilename(char *fn);
void SetFlushAfterWrite(bool value);
extern double CursorScaleFactor;
@@ -44,10 +44,8 @@ extern int PlotGridX, PlotGridY, PlotGridXdefault, PlotGridYdefault, CursorCPos,
extern bool GridLocked;
extern bool showDemod;
-//extern uint8_t g_debugMode;
-
extern pthread_mutex_t print_lock;
-extern void iceIIR_Butterworth(int *data, const size_t len);
-extern void iceSimple_Filter(int *data, const size_t len, uint8_t k);
+void iceIIR_Butterworth(int *data, const size_t len);
+void iceSimple_Filter(int *data, const size_t len, uint8_t k);
#endif
diff --git a/client/util.c b/client/util.c
index 8be1aa896..f69138947 100644
--- a/client/util.c
+++ b/client/util.c
@@ -128,13 +128,13 @@ int FillBuffer(uint8_t *data, size_t maxDataLength, size_t *dataLength, ...) {
va_start(valist, dataLength);
uint8_t *vdata = NULL;
- size_t vlength = 0;
+
do {
vdata = va_arg(valist, uint8_t *);
if (!vdata)
break;
- vlength = va_arg(valist, size_t);
+ size_t vlength = va_arg(valist, size_t);
if (*dataLength + vlength > maxDataLength) {
va_end(valist);
return 1;
@@ -650,12 +650,10 @@ https://github.com/ApertureLabsLtd/RFIDler/blob/master/firmware/Pic32/RFIDler.X/
int hextobinarray(char *target, char *source) {
int length, i, count = 0;
char *start = source;
- char x;
-
length = strlen(source);
// process 4 bits (1 hex digit) at a time
while (length--) {
- x = *(source++);
+ char x = *(source++);
// capitalize
if (x >= 'a' && x <= 'f')
x -= 32;
@@ -837,11 +835,11 @@ uint32_t reflect(uint32_t v, int b) {
}
uint64_t HornerScheme(uint64_t num, uint64_t divider, uint64_t factor) {
- uint64_t remainder = 0, quotient = 0, result = 0;
- remainder = num % divider;
+ uint64_t remaind = 0, quotient = 0, result = 0;
+ remaind = num % divider;
quotient = num / divider;
- if (!(quotient == 0 && remainder == 0))
- result += HornerScheme(quotient, divider, factor) * factor + remainder;
+ if (!(quotient == 0 && remaind == 0))
+ result += HornerScheme(quotient, divider, factor) * factor + remaind;
return result;
}
diff --git a/client/util.h b/client/util.h
index cf5f97360..dcd702fb0 100644
--- a/client/util.h
+++ b/client/util.h
@@ -174,7 +174,7 @@
#ifndef DropField
#define DropField() { \
- UsbCommand c = {CMD_READER_ISO_14443a, {0,0,0}}; clearCommandBuffer(); SendCommand(&c); \
+ UsbCommand c_drop = {CMD_READER_ISO_14443a, {0,0,0}}; clearCommandBuffer(); SendCommand(&c_drop); \
}
#endif
@@ -186,81 +186,81 @@
}
#endif
-extern uint8_t g_debugMode;
+uint8_t g_debugMode;
-extern int ukbhit(void);
-extern void AddLogLine(char *fn, char *data, char *c);
-extern void AddLogHex(char *fn, char *extData, const uint8_t *data, const size_t len);
-extern void AddLogUint64(char *fn, char *data, const uint64_t value);
-extern void AddLogCurrentDT(char *fn);
-extern void FillFileNameByUID(char *filenamePrefix, uint8_t *uid, const char *ext, int uidlen);
+int ukbhit(void);
+void AddLogLine(char *fn, char *data, char *c);
+void AddLogHex(char *fn, char *extData, const uint8_t *data, const size_t len);
+void AddLogUint64(char *fn, char *data, const uint64_t value);
+void AddLogCurrentDT(char *fn);
+void FillFileNameByUID(char *filenamePrefix, uint8_t *uid, const char *ext, int uidlen);
// fill buffer from structure [{uint8_t data, size_t length},...]
-extern int FillBuffer(uint8_t *data, size_t maxDataLength, size_t *dataLength, ...);
+int FillBuffer(uint8_t *data, size_t maxDataLength, size_t *dataLength, ...);
-extern bool CheckStringIsHEXValue(const char *value);
-extern void hex_to_buffer(const uint8_t *buf, const uint8_t *hex_data, const size_t hex_len,
- const size_t hex_max_len, const size_t min_str_len, const size_t spaces_between,
- bool uppercase);
+bool CheckStringIsHEXValue(const char *value);
+void hex_to_buffer(const uint8_t *buf, const uint8_t *hex_data, const size_t hex_len,
+ const size_t hex_max_len, const size_t min_str_len, const size_t spaces_between,
+ bool uppercase);
-extern void print_hex(const uint8_t *data, const size_t len);
-extern void print_hex_break(const uint8_t *data, const size_t len, const uint8_t breaks);
-extern char *sprint_hex(const uint8_t *data, const size_t len);
-extern char *sprint_hex_inrow(const uint8_t *data, const size_t len);
-extern char *sprint_hex_inrow_ex(const uint8_t *data, const size_t len, const size_t min_str_len);
-extern char *sprint_hex_inrow_spaces(const uint8_t *data, const size_t len, size_t spaces_between);
-extern char *sprint_bin(const uint8_t *data, const size_t len);
-extern char *sprint_bin_break(const uint8_t *data, const size_t len, const uint8_t breaks);
-extern char *sprint_hex_ascii(const uint8_t *data, const size_t len);
-extern char *sprint_ascii(const uint8_t *data, const size_t len);
-extern char *sprint_ascii_ex(const uint8_t *data, const size_t len, const size_t min_str_len);
+void print_hex(const uint8_t *data, const size_t len);
+void print_hex_break(const uint8_t *data, const size_t len, const uint8_t breaks);
+char *sprint_hex(const uint8_t *data, const size_t len);
+char *sprint_hex_inrow(const uint8_t *data, const size_t len);
+char *sprint_hex_inrow_ex(const uint8_t *data, const size_t len, const size_t min_str_len);
+char *sprint_hex_inrow_spaces(const uint8_t *data, const size_t len, size_t spaces_between);
+char *sprint_bin(const uint8_t *data, const size_t len);
+char *sprint_bin_break(const uint8_t *data, const size_t len, const uint8_t breaks);
+char *sprint_hex_ascii(const uint8_t *data, const size_t len);
+char *sprint_ascii(const uint8_t *data, const size_t len);
+char *sprint_ascii_ex(const uint8_t *data, const size_t len, const size_t min_str_len);
-extern void print_blocks(uint32_t *data, size_t len);
+void print_blocks(uint32_t *data, size_t len);
-extern void num_to_bytes(uint64_t n, size_t len, uint8_t *dest);
-extern uint64_t bytes_to_num(uint8_t *src, size_t len);
-extern void num_to_bytebits(uint64_t n, size_t len, uint8_t *dest);
-extern void num_to_bytebitsLSBF(uint64_t n, size_t len, uint8_t *dest);
-extern uint8_t *SwapEndian64(const uint8_t *src, const size_t len, const uint8_t blockSize);
-extern void SwapEndian64ex(const uint8_t *src, const size_t len, const uint8_t blockSize, uint8_t *dest);
+void num_to_bytes(uint64_t n, size_t len, uint8_t *dest);
+uint64_t bytes_to_num(uint8_t *src, size_t len);
+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);
+uint8_t *SwapEndian64(const uint8_t *src, const size_t len, const uint8_t blockSize);
+void SwapEndian64ex(const uint8_t *src, const size_t len, const uint8_t blockSize, uint8_t *dest);
-extern int param_getlength(const char *line, int paramnum);
-extern char param_getchar(const char *line, int paramnum);
-extern char param_getchar_indx(const char *line, int indx, int paramnum);
-extern int param_getptr(const char *line, int *bg, int *en, int paramnum);
-extern uint8_t param_get8(const char *line, int paramnum);
-extern uint8_t param_get8ex(const char *line, int paramnum, int deflt, int base);
-extern uint32_t param_get32ex(const char *line, int paramnum, int deflt, int base);
-extern uint64_t param_get64ex(const char *line, int paramnum, int deflt, int base);
-extern uint8_t param_getdec(const char *line, int paramnum, uint8_t *destination);
-extern uint8_t param_isdec(const char *line, int paramnum);
-extern int param_gethex(const char *line, int paramnum, uint8_t *data, int hexcnt);
-extern int param_gethex_ex(const char *line, int paramnum, uint8_t *data, int *hexcnt);
-extern int param_gethex_to_eol(const char *line, int paramnum, uint8_t *data, int maxdatalen, int *datalen);
-extern int param_getstr(const char *line, int paramnum, char *str, size_t buffersize);
+int param_getlength(const char *line, int paramnum);
+char param_getchar(const char *line, int paramnum);
+char param_getchar_indx(const char *line, int indx, int paramnum);
+int param_getptr(const char *line, int *bg, int *en, int paramnum);
+uint8_t param_get8(const char *line, int paramnum);
+uint8_t param_get8ex(const char *line, int paramnum, int deflt, int base);
+uint32_t param_get32ex(const char *line, int paramnum, int deflt, int base);
+uint64_t param_get64ex(const char *line, int paramnum, int deflt, int base);
+uint8_t param_getdec(const char *line, int paramnum, uint8_t *destination);
+uint8_t param_isdec(const char *line, int paramnum);
+int param_gethex(const char *line, int paramnum, uint8_t *data, int hexcnt);
+int param_gethex_ex(const char *line, int paramnum, uint8_t *data, int *hexcnt);
+int param_gethex_to_eol(const char *line, int paramnum, uint8_t *data, int maxdatalen, int *datalen);
+int param_getstr(const char *line, int paramnum, char *str, size_t buffersize);
-extern int hextobinarray(char *target, char *source);
-extern int hextobinstring(char *target, char *source);
-extern int binarraytohex(char *target, const size_t targetlen, char *source, size_t srclen);
-extern void binarraytobinstring(char *target, char *source, int length);
-extern uint8_t GetParity(uint8_t *bits, uint8_t type, int length);
-extern void wiegand_add_parity(uint8_t *target, uint8_t *source, uint8_t length);
+int hextobinarray(char *target, char *source);
+int hextobinstring(char *target, char *source);
+int binarraytohex(char *target, const size_t targetlen, char *source, size_t srclen);
+void binarraytobinstring(char *target, char *source, int length);
+uint8_t GetParity(uint8_t *bits, uint8_t type, int length);
+void wiegand_add_parity(uint8_t *target, uint8_t *source, uint8_t length);
-extern void xor(unsigned char *dst, unsigned char *src, size_t len);
-extern int32_t le24toh(uint8_t data[3]);
+void xor(unsigned char *dst, unsigned char *src, size_t len);
+int32_t le24toh(uint8_t data[3]);
-extern uint32_t PackBits(uint8_t start, uint8_t len, uint8_t *bits);
-extern void rol(uint8_t *data, const size_t len);
-extern uint32_t reflect(uint32_t v, int b);
-extern uint8_t reflect8(uint8_t b); // dedicated 8bit reversal
-extern uint16_t reflect16(uint16_t b); // dedicated 16bit reversal
-extern uint64_t HornerScheme(uint64_t num, uint64_t divider, uint64_t factor);
+uint32_t PackBits(uint8_t start, uint8_t len, uint8_t *bits);
+void rol(uint8_t *data, const size_t len);
+uint32_t reflect(uint32_t v, int b);
+uint8_t reflect8(uint8_t b); // dedicated 8bit reversal
+uint16_t reflect16(uint16_t b); // dedicated 16bit reversal
+uint64_t HornerScheme(uint64_t num, uint64_t divider, uint64_t factor);
-extern int num_CPUs(void); // number of logical CPUs
+int num_CPUs(void); // number of logical CPUs
-extern void str_lower(char *s); // converts string to lower case
-extern bool str_startswith(const char *s, const char *pre); // check for prefix in string
-extern void strcleanrn(char *buf, size_t len);
-extern void strcreplace(char *buf, size_t len, char from, char to);
-extern char *strmcopy(char *buf);
+void str_lower(char *s); // converts string to lower case
+bool str_startswith(const char *s, const char *pre); // check for prefix in string
+void strcleanrn(char *buf, size_t len);
+void strcreplace(char *buf, size_t len, char from, char to);
+char *strmcopy(char *buf);
#endif
diff --git a/client/whereami.c b/client/whereami.c
index fe61273d2..9ecfd2870 100644
--- a/client/whereami.c
+++ b/client/whereami.c
@@ -287,11 +287,9 @@ int WAI_PREFIX(getModulePath)(char *out, int capacity, int *dirname_length) {
memcpy(out, resolved, length);
if (dirname_length) {
- int i;
-
- for (i = length - 1; i >= 0; --i) {
- if (out[i] == '/') {
- *dirname_length = i;
+ for (int j = length - 1; j >= 0; --j) {
+ if (out[j] == '/') {
+ *dirname_length = j;
break;
}
}
diff --git a/common/crapto1/crapto1.c b/common/crapto1/crapto1.c
index 417ac1c86..ea496e1c4 100644
--- a/common/crapto1/crapto1.c
+++ b/common/crapto1/crapto1.c
@@ -154,7 +154,7 @@ struct Crypto1State *lfsr_recovery32(uint32_t ks2, uint32_t in) {
// allocate memory for out of place bucket_sort
bucket_array_t bucket;
- for (uint32_t i = 0; i < 2; i++) {
+ for (i = 0; i < 2; i++) {
for (uint32_t j = 0; j <= 0xff; j++) {
bucket[i][j].head = malloc(sizeof(uint32_t) << 14);
if (!bucket[i][j].head) {
@@ -184,7 +184,7 @@ struct Crypto1State *lfsr_recovery32(uint32_t ks2, uint32_t in) {
recover(odd_head, odd_tail, oks, even_head, even_tail, eks, 11, statelist, in << 1, bucket);
out:
- for (uint32_t i = 0; i < 2; i++)
+ for (i = 0; i < 2; i++)
for (uint32_t j = 0; j <= 0xff; j++)
free(bucket[i][j].head);
free(odd_head);
diff --git a/common/crapto1/crapto1.h b/common/crapto1/crapto1.h
index 251a25089..49a784cf9 100644
--- a/common/crapto1/crapto1.h
+++ b/common/crapto1/crapto1.h
@@ -51,7 +51,7 @@ uint8_t lfsr_rollback_bit(struct Crypto1State *s, uint32_t in, int fb);
uint8_t lfsr_rollback_byte(struct Crypto1State *s, uint32_t in, int fb);
uint32_t lfsr_rollback_word(struct Crypto1State *s, uint32_t in, int fb);
int nonce_distance(uint32_t from, uint32_t to);
-extern bool validate_prng_nonce(uint32_t nonce);
+bool validate_prng_nonce(uint32_t nonce);
#define FOREACH_VALID_NONCE(N, FILTER, FSIZE)\
uint32_t __n = 0,__M = 0, N = 0;\
int __i;\
diff --git a/common/crc.c b/common/crc.c
index 2ad7609b1..c3bd90064 100644
--- a/common/crc.c
+++ b/common/crc.c
@@ -107,12 +107,12 @@ uint32_t CRC8Mad(uint8_t *buff, size_t size) {
return crc_finish(&crc);
}
// width=4 poly=0xC, reversed poly=0x7 init=0x5 refin=true refout=true xorout=0x0000 check= name="CRC-4/LEGIC"
-uint32_t CRC4Legic(uint8_t *cmd, size_t size) {
+uint32_t CRC4Legic(uint8_t *buff, size_t size) {
crc_t crc;
crc_init_ref(&crc, 4, 0x19 >> 1, 0x5, 0, true, true);
crc_update2(&crc, 1, 1); /* CMD_READ */
- crc_update2(&crc, cmd[0], 8);
- crc_update2(&crc, cmd[1], 8);
+ crc_update2(&crc, buff[0], 8);
+ crc_update2(&crc, buff[1], 8);
return reflect(crc_finish(&crc), 4);
}
// width=8 poly=0x63, reversed poly=0x8D init=0x55 refin=true refout=true xorout=0x0000 check=0xC6 name="CRC-8/LEGIC"
diff --git a/common/crc.h b/common/crc.h
index 368758f40..7cb9caff9 100644
--- a/common/crc.h
+++ b/common/crc.h
@@ -12,7 +12,7 @@
#include "common.h" //stdint, stddef, stdbool
#include "util.h" // reflect, bswap_16
-typedef struct crc {
+typedef struct crc_ctx {
uint32_t state;
int order;
uint32_t polynom;
@@ -30,25 +30,25 @@ typedef struct crc {
* refin is the setting for reversing (bitwise) the bytes during crc
* refot is the setting for reversing (bitwise) the crc byte before returning it.
*/
-extern void crc_init_ref(crc_t *crc, int order, uint32_t polynom, uint32_t initial_value, uint32_t final_xor, bool refin, bool refout);
+void crc_init_ref(crc_t *crc, int order, uint32_t polynom, uint32_t initial_value, uint32_t final_xor, bool refin, bool refout);
/* Initialize a crc structure. order is the order of the polynom, e.g. 32 for a CRC-32
* polynom is the CRC polynom. initial_value is the initial value of a clean state.
* final_xor is XORed onto the state before returning it from crc_result(). */
-extern void crc_init(crc_t *crc, int order, uint32_t polynom, uint32_t initial_value, uint32_t final_xor);
+void crc_init(crc_t *crc, int order, uint32_t polynom, uint32_t initial_value, uint32_t final_xor);
/* Update the crc state. data is the data of length data_width bits (only the
* data_width lower-most bits are used).
*/
-extern void crc_update(crc_t *crc, uint32_t data, int data_width);
-extern void crc_update2(crc_t *crc, uint32_t data, int data_width);
+void crc_update(crc_t *crc, uint32_t data, int data_width);
+void crc_update2(crc_t *crc, uint32_t data, int data_width);
/* Clean the crc state, e.g. reset it to initial_value */
-extern void crc_clear(crc_t *crc);
+void crc_clear(crc_t *crc);
/* Get the result of the crc calculation */
-extern uint32_t crc_finish(crc_t *crc);
+uint32_t crc_finish(crc_t *crc);
// Calculate CRC-8/Maxim checksum
uint32_t CRC8Maxim(uint8_t *buff, size_t size);
@@ -64,14 +64,14 @@ uint32_t CRC8Legic(uint8_t *buff, size_t size);
/* Static initialization of a crc structure */
#define CRC_INITIALIZER(_order, _polynom, _initial_value, _final_xor) { \
- .state = ((_initial_value) & ((1L<<(_order))-1)), \
- .order = (_order), \
- .polynom = (_polynom), \
- .initial_value = (_initial_value), \
- .final_xor = (_final_xor), \
- .mask = ((1L<<(_order))-1) \
- .refin = false, \
- .refout = false \
- }
+ .state = ((_initial_value) & ((1L<<(_order))-1)), \
+ .order = (_order), \
+ .polynom = (_polynom), \
+ .initial_value = (_initial_value), \
+ .final_xor = (_final_xor), \
+ .mask = ((1L<<(_order))-1) \
+ .refin = false, \
+ .refout = false \
+}
#endif /* __CRC_H */
diff --git a/common/crc16.c b/common/crc16.c
index 69ada3b24..1396c0fe8 100644
--- a/common/crc16.c
+++ b/common/crc16.c
@@ -9,21 +9,21 @@
static uint16_t crc_table[256];
static bool crc_table_init = false;
-static CrcType_t crc_type = CRC_NONE;
+static CrcType_t current_crc_type = CRC_NONE;
-void init_table(CrcType_t ct) {
+void init_table(CrcType_t crctype) {
// same crc algo, and initialised already
- if (ct == crc_type && crc_table_init)
+ if (crctype == current_crc_type && crc_table_init)
return;
// not the same crc algo. reset table.
- if (ct != crc_type)
+ if (crctype != current_crc_type)
reset_table();
- crc_type = ct;
+ current_crc_type = crctype;
- switch (ct) {
+ switch (crctype) {
case CRC_14443_A:
case CRC_14443_B:
case CRC_15693:
@@ -44,7 +44,7 @@ void init_table(CrcType_t ct) {
break;
default:
crc_table_init = false;
- crc_type = CRC_NONE;
+ current_crc_type = CRC_NONE;
break;
}
}
@@ -80,7 +80,7 @@ void generate_table(uint16_t polynomial, bool refin) {
void reset_table(void) {
memset(crc_table, 0, sizeof(crc_table));
crc_table_init = false;
- crc_type = CRC_NONE;
+ current_crc_type = CRC_NONE;
}
// table lookup LUT solution
@@ -191,7 +191,7 @@ void compute_crc(CrcType_t ct, const uint8_t *d, size_t n, uint8_t *first, uint8
*first = (crc & 0xFF);
*second = ((crc >> 8) & 0xFF);
}
-uint16_t crc(CrcType_t ct, const uint8_t *d, size_t n) {
+uint16_t Crc(CrcType_t ct, const uint8_t *d, size_t n) {
// can't calc a crc on less than 3 byte. (1byte + 2 crc bytes)
if (n < 3) return 0;
diff --git a/common/crc16.h b/common/crc16.h
index 9a202f514..843cc07e5 100644
--- a/common/crc16.h
+++ b/common/crc16.h
@@ -32,9 +32,9 @@ typedef enum {
uint16_t update_crc16_ex(uint16_t crc, uint8_t c, uint16_t polynomial);
uint16_t update_crc16(uint16_t crc, uint8_t c);
-uint16_t crc16(uint8_t const *message, size_t length, uint16_t remainder, uint16_t polynomial, bool refin, bool refout);
+uint16_t crc16(uint8_t const *d, size_t length, uint16_t remainder, uint16_t polynomial, bool refin, bool refout);
-uint16_t crc(CrcType_t ct, const uint8_t *d, size_t n);
+uint16_t Crc(CrcType_t ct, const uint8_t *d, size_t n);
void compute_crc(CrcType_t ct, const uint8_t *d, size_t n, uint8_t *first, uint8_t *second);
bool check_crc(CrcType_t ct, const uint8_t *d, size_t n);
diff --git a/common/i2c.c b/common/i2c.c
index 80fb2690c..ad0f8964c 100644
--- a/common/i2c.c
+++ b/common/i2c.c
@@ -26,7 +26,7 @@
volatile unsigned long c;
-// ֱʹѭʱһѭ 6 ָ48M Delay=1 Ϊ 200kbps
+// 直接使用循环来延时,一个循环 6 条指令,48M, Delay=1 大概为 200kbps
// timer.
// I2CSpinDelayClk(4) = 12.31us
// I2CSpinDelayClk(1) = 3.07us
@@ -467,8 +467,7 @@ int16_t I2C_BufferRead(uint8_t *data, uint8_t len, uint8_t device_cmd, uint8_t d
*data = (uint8_t)tmp & 0xFF;
len--;
-
- // ȡĵһֽΪ
+ // 读取的第一个字节为后续长度
// The first byte in response is the message length
if (!readcount && (len > *data)) {
len = *data;
diff --git a/common/lfdemod.c b/common/lfdemod.c
index 0d33091a6..abf7d82fe 100644
--- a/common/lfdemod.c
+++ b/common/lfdemod.c
@@ -51,7 +51,7 @@
//to allow debug print calls when used not on dev
//void dummy(char *fmt, ...){}
-extern void Dbprintf(const char *fmt, ...);
+void Dbprintf(const char *fmt, ...);
#ifndef ON_DEVICE
#include "ui.h"
@@ -445,11 +445,11 @@ int ManchesterEncode(uint8_t *bits, size_t size) {
// by marshmellow
// to detect a wave that has heavily clipped (clean) samples
-// loop 512 samples, if 250 of them is deemed maxed out, we assume the wave is clipped.
+// loop 1024 samples, if 250 of them is deemed maxed out, we assume the wave is clipped.
bool DetectCleanAskWave(uint8_t *dest, size_t size, uint8_t high, uint8_t low) {
bool allArePeaks = true;
uint16_t cntPeaks = 0;
- size_t loopEnd = 512 + 160;
+ size_t loopEnd = 1024 + 160;
// sanity check
if (loopEnd > size) loopEnd = size;
@@ -463,7 +463,8 @@ bool DetectCleanAskWave(uint8_t *dest, size_t size, uint8_t high, uint8_t low) {
}
if (!allArePeaks) {
- if (cntPeaks > 250) return true;
+ if (g_debugMode == 2) prnt("DEBUG DetectCleanAskWave: peaks (200) %u", cntPeaks);
+ if (cntPeaks > 200) return true;
}
return allArePeaks;
}
@@ -520,12 +521,12 @@ int DetectStrongAskClock(uint8_t *dest, size_t size, int high, int low, int *clo
int foo = getClosestClock(minClk);
if (foo > 0) {
- for (uint8_t i = 0; i < 10; i++) {
- if (tmpclk[i][0] == foo) {
- tmpclk[i][1]++;
+ for (uint8_t j = 0; j < 10; j++) {
+ if (tmpclk[j][0] == foo) {
+ tmpclk[j][1]++;
- if (tmpclk[i][2] == 0) {
- tmpclk[i][2] = shortestWaveIdx;
+ if (tmpclk[j][2] == 0) {
+ tmpclk[j][2] = shortestWaveIdx;
}
break;
}
@@ -535,18 +536,18 @@ int DetectStrongAskClock(uint8_t *dest, size_t size, int high, int low, int *clo
// find the clock with most hits and it the first index it was encountered.
int max = 0;
- for (uint8_t i = 0; i < 10; i++) {
+ for (uint8_t j = 0; j < 10; j++) {
if (g_debugMode == 2) {
prnt("DEBUG, ASK, clocks %u | hits %u | idx %u"
- , tmpclk[i][0]
- , tmpclk[i][1]
- , tmpclk[i][2]
+ , tmpclk[j][0]
+ , tmpclk[j][1]
+ , tmpclk[j][2]
);
}
- if (max < tmpclk[i][1]) {
- *clock = tmpclk[i][0];
- shortestWaveIdx = tmpclk[i][2];
- max = tmpclk[i][1];
+ if (max < tmpclk[j][1]) {
+ *clock = tmpclk[j][0];
+ shortestWaveIdx = tmpclk[j][2];
+ max = tmpclk[j][1];
}
}
@@ -983,10 +984,10 @@ int DetectPSKClock(uint8_t *dest, size_t size, int clock, size_t *firstPhaseShif
if (*fc != 2 && *fc != 4 && *fc != 8) return 0;
- size_t waveStart = 0, waveEnd = 0, firstFullWave = 0, lastClkBit = 0;
+ size_t waveStart, waveEnd, firstFullWave = 0, lastClkBit;
- uint8_t clkCnt, tol = 1;
- uint16_t peakcnt = 0, errCnt = 0, waveLenCnt = 0, fullWaveLen = 0;
+ uint8_t clkCnt, tol;
+ uint16_t peakcnt, errCnt, waveLenCnt, fullWaveLen = 0;
uint16_t bestErr[] = {1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000};
uint16_t peaksdet[] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
@@ -1018,7 +1019,6 @@ int DetectPSKClock(uint8_t *dest, size_t size, int clock, size_t *firstPhaseShif
if (dest[i] < dest[i + 1] && dest[i + 1] >= dest[i + 2]) {
if (waveStart == 0) {
waveStart = i + 1;
- waveLenCnt = 0;
} else { //waveEnd
waveEnd = i + 1;
waveLenCnt = waveEnd - waveStart;
@@ -1614,25 +1614,19 @@ int askdemod(uint8_t *bits, size_t *size, int *clk, int *invert, int maxErr, uin
// by marshmellow - demodulate NRZ wave - requires a read with strong signal
// peaks invert bit (high=1 low=0) each clock cycle = 1 bit determined by last peak
int nrzRawDemod(uint8_t *dest, size_t *size, int *clk, int *invert, int *startIdx) {
- if (signalprop.isnoise) return -1;
+
+ if (signalprop.isnoise) {
+ if (g_debugMode == 2) prnt("DEBUG nrzRawDemod: just noise detected - quitting");
+ return -1;
+ }
size_t clkStartIdx = 0;
*clk = DetectNRZClock(dest, *size, *clk, &clkStartIdx);
if (*clk == 0) return -2;
- size_t i, gLen = 4096;
- if (gLen > *size)
- gLen = *size - 20;
-
-
- // just noise - no super good detection. good enough
- if (signalprop.isnoise) {
- if (g_debugMode == 2) prnt("DEBUG nrzRawDemod: just noise detected - quitting");
- return -3;
- }
-
+ size_t i;
int high, low;
- //getHiLo(dest, gLen, &high, &low, 75, 75);
+
getHiLo(&high, &low, 75, 75);
getHiLo(&high, &low, 75, 75);
@@ -1671,12 +1665,9 @@ size_t fsk_wave_demod(uint8_t *dest, size_t size, uint8_t fchigh, uint8_t fclow,
if (fclow == 0) fclow = 8;
//set the threshold close to 0 (graph) or 128 std to avoid static
- size_t preLastSample = 0;
- size_t LastSample = 0;
- size_t currSample = 0;
- size_t last_transition = 0;
- size_t idx = 1;
- size_t numBits = 0;
+ size_t preLastSample, LastSample = 0;
+ size_t currSample = 0, last_transition = 0;
+ size_t idx, numBits = 0;
//find start of modulating data in trace
idx = findModStart(dest, size, fchigh);
@@ -1870,8 +1861,8 @@ int pskRawDemod_ext(uint8_t *dest, size_t *size, int *clock, int *invert, int *s
uint8_t curPhase = *invert;
uint8_t fc = 0;
- size_t i = 0, numBits = 0, waveStart = 1, waveEnd = 0, firstFullWave = 0, lastClkBit = 0;
- uint16_t fullWaveLen = 0, waveLenCnt = 0, avgWaveVal = 0;
+ size_t i = 0, numBits = 0, waveStart = 1, waveEnd, firstFullWave = 0, lastClkBit = 0;
+ uint16_t fullWaveLen = 0, waveLenCnt, avgWaveVal = 0;
uint16_t errCnt = 0, errCnt2 = 0;
*clock = DetectPSKClock(dest, *size, *clock, &firstFullWave, &curPhase, &fc);
@@ -1899,8 +1890,11 @@ int pskRawDemod_ext(uint8_t *dest, size_t *size, int *clock, int *invert, int *s
*startIdx = firstFullWave - (*clock * numBits) + 2;
//set start of wave as clock align
lastClkBit = firstFullWave;
- if (g_debugMode == 2) prnt("DEBUG PSK: firstFullWave: %u, waveLen: %u, startIdx %i", firstFullWave, fullWaveLen, *startIdx);
- if (g_debugMode == 2) prnt("DEBUG PSK: clk: %d, lastClkBit: %u, fc: %u", *clock, lastClkBit, fc);
+ if (g_debugMode == 2) {
+ prnt("DEBUG PSK: firstFullWave: %u, waveLen: %u, startIdx %i", firstFullWave, fullWaveLen, *startIdx);
+ prnt("DEBUG PSK: clk: %d, lastClkBit: %u, fc: %u", *clock, lastClkBit, fc);
+ }
+
waveStart = 0;
dest[numBits++] = curPhase; //set first read bit
for (i = firstFullWave + fullWaveLen - 1; i < *size - 3; i++) {
@@ -1908,14 +1902,20 @@ int pskRawDemod_ext(uint8_t *dest, size_t *size, int *clock, int *invert, int *s
if (dest[i] + fc < dest[i + 1] && dest[i + 1] >= dest[i + 2]) {
if (waveStart == 0) {
waveStart = i + 1;
- waveLenCnt = 0;
avgWaveVal = dest[i + 1];
} else { //waveEnd
waveEnd = i + 1;
waveLenCnt = waveEnd - waveStart;
if (waveLenCnt > fc) {
//this wave is a phase shift
- //prnt("DEBUG: phase shift at: %d, len: %d, nextClk: %d, i: %d, fc: %d",waveStart,waveLenCnt,lastClkBit+*clock-tol,i+1,fc);
+ /*
+ prnt("DEBUG: phase shift at: %d, len: %d, nextClk: %d, i: %d, fc: %d"
+ , waveStart
+ , waveLenCnt
+ , lastClkBit + *clock - tol
+ , i + 1
+ , fc);
+ */
if (i + 1 >= lastClkBit + *clock - tol) { //should be a clock bit
curPhase ^= 1;
dest[numBits++] = curPhase;
diff --git a/common/lfdemod.h b/common/lfdemod.h
index 6256aa0bc..32421dea0 100644
--- a/common/lfdemod.h
+++ b/common/lfdemod.h
@@ -45,42 +45,42 @@ void getNextHigh(uint8_t *samples, size_t size, int high, size_t *i);
bool loadWaveCounters(uint8_t *samples, size_t size, int lowToLowWaveLen[], int highToLowWaveLen[], int *waveCnt, int *skip, int *minClk, int *high, int *low);
size_t pskFindFirstPhaseShift(uint8_t *samples, size_t size, uint8_t *curPhase, size_t waveStart, uint16_t fc, uint16_t *fullWaveLen);
-extern size_t addParity(uint8_t *src, uint8_t *dest, uint8_t sourceLen, uint8_t pLen, uint8_t pType);
-extern int askdemod(uint8_t *bits, size_t *size, int *clk, int *invert, int maxErr, uint8_t amp, uint8_t askType);
-extern int askdemod_ext(uint8_t *bits, size_t *size, int *clk, int *invert, int maxErr, uint8_t amp, uint8_t askType, int *startIdx);
-extern void askAmp(uint8_t *bits, size_t size);
-extern int BiphaseRawDecode(uint8_t *bits, size_t *size, int *offset, int invert);
-extern uint8_t bits_to_array(const uint8_t *bits, size_t size, uint8_t *dest);
-extern uint32_t bytebits_to_byte(uint8_t *src, size_t numbits);
-extern uint32_t bytebits_to_byteLSBF(uint8_t *src, size_t numbits);
-extern uint16_t countFC(uint8_t *bits, size_t size, bool fskAdj);
-extern int DetectASKClock(uint8_t *dest, size_t size, int *clock, int maxErr);
-extern bool DetectCleanAskWave(uint8_t *dest, size_t size, uint8_t high, uint8_t low);
-extern uint8_t detectFSKClk(uint8_t *bits, size_t size, uint8_t fcHigh, uint8_t fcLow, int *firstClockEdge);
-extern int DetectNRZClock(uint8_t *dest, size_t size, int clock, size_t *clockStartIdx);
-extern int DetectPSKClock(uint8_t *dest, size_t size, int clock, size_t *firstPhaseShift, uint8_t *curPhase, uint8_t *fc);
-extern int DetectStrongAskClock(uint8_t *dest, size_t size, int high, int low, int *clock);
-extern bool DetectST(uint8_t *buffer, size_t *size, int *foundclock, size_t *ststart, size_t *stend);
-extern size_t fskdemod(uint8_t *dest, size_t size, uint8_t rfLen, uint8_t invert, uint8_t fchigh, uint8_t fclow, int *start_idx);
-//extern void getHiLo(uint8_t *bits, size_t size, int *high, int *low, uint8_t fuzzHi, uint8_t fuzzLo);
-extern void getHiLo(int *high, int *low, uint8_t fuzzHi, uint8_t fuzzLo);
-extern uint32_t manchesterEncode2Bytes(uint16_t datain);
-extern int ManchesterEncode(uint8_t *bits, size_t size);
-extern int manrawdecode(uint8_t *bits, size_t *size, uint8_t invert, uint8_t *alignPos);
-extern int nrzRawDemod(uint8_t *dest, size_t *size, int *clk, int *invert, int *startIdx);
-extern bool parityTest(uint32_t bits, uint8_t bitLen, uint8_t pType);
-extern bool preambleSearch(uint8_t *bits, uint8_t *preamble, size_t pLen, size_t *size, size_t *startIdx);
-extern bool preambleSearchEx(uint8_t *bits, uint8_t *preamble, size_t pLen, size_t *size, size_t *startIdx, bool findone);
-extern int pskRawDemod(uint8_t *dest, size_t *size, int *clock, int *invert);
-extern int pskRawDemod_ext(uint8_t *dest, size_t *size, int *clock, int *invert, int *startIdx);
-extern void psk2TOpsk1(uint8_t *bits, size_t size);
-extern void psk1TOpsk2(uint8_t *bits, size_t size);
-extern size_t removeParity(uint8_t *bits, size_t startIdx, uint8_t pLen, uint8_t pType, size_t bLen);
+size_t addParity(uint8_t *src, uint8_t *dest, uint8_t sourceLen, uint8_t pLen, uint8_t pType);
+int askdemod(uint8_t *bits, size_t *size, int *clk, int *invert, int maxErr, uint8_t amp, uint8_t askType);
+int askdemod_ext(uint8_t *bits, size_t *size, int *clk, int *invert, int maxErr, uint8_t amp, uint8_t askType, int *startIdx);
+void askAmp(uint8_t *bits, size_t size);
+int BiphaseRawDecode(uint8_t *bits, size_t *size, int *offset, int invert);
+uint8_t bits_to_array(const uint8_t *bits, size_t size, uint8_t *dest);
+uint32_t bytebits_to_byte(uint8_t *src, size_t numbits);
+uint32_t bytebits_to_byteLSBF(uint8_t *src, size_t numbits);
+uint16_t countFC(uint8_t *bits, size_t size, bool fskAdj);
+int DetectASKClock(uint8_t *dest, size_t size, int *clock, int maxErr);
+bool DetectCleanAskWave(uint8_t *dest, size_t size, uint8_t high, uint8_t low);
+uint8_t detectFSKClk(uint8_t *bits, size_t size, uint8_t fcHigh, uint8_t fcLow, int *firstClockEdge);
+int DetectNRZClock(uint8_t *dest, size_t size, int clock, size_t *clockStartIdx);
+int DetectPSKClock(uint8_t *dest, size_t size, int clock, size_t *firstPhaseShift, uint8_t *curPhase, uint8_t *fc);
+int DetectStrongAskClock(uint8_t *dest, size_t size, int high, int low, int *clock);
+bool DetectST(uint8_t *buffer, size_t *size, int *foundclock, size_t *ststart, size_t *stend);
+size_t fskdemod(uint8_t *dest, size_t size, uint8_t rfLen, uint8_t invert, uint8_t fchigh, uint8_t fclow, int *start_idx);
+//void getHiLo(uint8_t *bits, size_t size, int *high, int *low, uint8_t fuzzHi, uint8_t fuzzLo);
+void getHiLo(int *high, int *low, uint8_t fuzzHi, uint8_t fuzzLo);
+uint32_t manchesterEncode2Bytes(uint16_t datain);
+int ManchesterEncode(uint8_t *bits, size_t size);
+int manrawdecode(uint8_t *bits, size_t *size, uint8_t invert, uint8_t *alignPos);
+int nrzRawDemod(uint8_t *dest, size_t *size, int *clk, int *invert, int *startIdx);
+bool parityTest(uint32_t bits, uint8_t bitLen, uint8_t pType);
+bool preambleSearch(uint8_t *bits, uint8_t *preamble, size_t pLen, size_t *size, size_t *startIdx);
+bool preambleSearchEx(uint8_t *bits, uint8_t *preamble, size_t pLen, size_t *size, size_t *startIdx, bool findone);
+int pskRawDemod(uint8_t *dest, size_t *size, int *clock, int *invert);
+int pskRawDemod_ext(uint8_t *dest, size_t *size, int *clock, int *invert, int *startIdx);
+void psk2TOpsk1(uint8_t *bits, size_t size);
+void psk1TOpsk2(uint8_t *bits, size_t size);
+size_t removeParity(uint8_t *bits, size_t startIdx, uint8_t pLen, uint8_t pType, size_t bLen);
//tag specific
-extern int detectAWID(uint8_t *dest, size_t *size, int *waveStartIdx);
-extern int Em410xDecode(uint8_t *dest, size_t *size, size_t *startIdx, uint32_t *hi, uint64_t *lo);
-extern int HIDdemodFSK(uint8_t *dest, size_t *size, uint32_t *hi2, uint32_t *hi, uint32_t *lo, int *waveStartIdx);
-extern int detectIdteck(uint8_t *dest, size_t *size);
-extern int detectIOProx(uint8_t *dest, size_t *size, int *waveStartIdx);
+int detectAWID(uint8_t *dest, size_t *size, int *waveStartIdx);
+int Em410xDecode(uint8_t *bits, size_t *size, size_t *start_idx, uint32_t *hi, uint64_t *lo);
+int HIDdemodFSK(uint8_t *dest, size_t *size, uint32_t *hi2, uint32_t *hi, uint32_t *lo, int *waveStartIdx);
+int detectIdteck(uint8_t *dest, size_t *size);
+int detectIOProx(uint8_t *dest, size_t *size, int *waveStartIdx);
#endif
diff --git a/common/protocols.h b/common/protocols.h
index 1752d75ed..f85ebb49b 100644
--- a/common/protocols.h
+++ b/common/protocols.h
@@ -152,6 +152,7 @@ ISO 7816-4 Basic interindustry commands. For command APDU's.
#define ISO14443A_CMD_HALT 0x50
#define ISO14443A_CMD_RATS 0xE0
+#define MIFARE_SELECT_CT 0x88
#define MIFARE_AUTH_KEYA 0x60
#define MIFARE_AUTH_KEYB 0x61
#define MIFARE_MAGICWUPC1 0x40
diff --git a/common/random.c b/common/random.c
deleted file mode 100644
index a6e714c4c..000000000
--- a/common/random.c
+++ /dev/null
@@ -1,30 +0,0 @@
-#include "random.h"
-
-static uint32_t g_nextrandom;
-
-/* Generates a (non-cryptographically secure) 32-bit random number.
- *
- * We don't have an implementation of the "rand" function. Instead we use a
- * method of seeding with the time it took to call "autoseed" from first run.
- *
- * https://github.com/Proxmark/proxmark3/pull/209/commits/f9c1dcd9f6e68a8c07cffed697a9c4c8caed6015
- *
- * Iceman, rand needs to be fast.
- * https://software.intel.com/en-us/articles/fast-random-number-generator-on-the-intel-pentiumr-4-processor/
- */
-
-inline void fast_prand() {
- fast_prandEx(GetTickCount());
-}
-inline void fast_prandEx(uint32_t seed) {
- g_nextrandom = seed;
-}
-
-uint32_t prand() {
-// g_nextrandom *= 6364136223846793005;
-// g_nextrandom += 1;
-//return (uint32_t)(g_nextrandom >> 32) % 0xffffffff;
- g_nextrandom = (214013 * g_nextrandom + 2531011);
- return (g_nextrandom >> 16) & 0xFFFF;
-}
-
diff --git a/common/random.h b/common/random.h
deleted file mode 100644
index 85c90dd38..000000000
--- a/common/random.h
+++ /dev/null
@@ -1,21 +0,0 @@
-//-----------------------------------------------------------------------------
-// Micolous Jan 2017
-// Iceman Jan 2017
-// This code is licensed to you under the terms of the GNU GPL, version 2 or,
-// at your option, any later version. See the LICENSE.txt file for the text of
-// the license.
-//-----------------------------------------------------------------------------
-// pseudo rng generator. To be used when PM3 simulates Mifare tag.
-// i.e. 'hf mf sim'
-// 'hf 14a sim'
-//-----------------------------------------------------------------------------
-
-#ifndef __RANDOM_H
-#define __RANDOM_H
-
-#include "common.h"
-#include "ticks.h"
-void fast_prand();
-void fast_prandEx(uint32_t seed);
-uint32_t prand();
-#endif
diff --git a/common/usb_cdc.h b/common/usb_cdc.h
index 1e735faa6..3b95a11c1 100644
--- a/common/usb_cdc.h
+++ b/common/usb_cdc.h
@@ -41,23 +41,23 @@
#include "proxmark3.h" // USB_CONNECT()
#include "common.h"
-extern void usb_disable();
-extern void usb_enable();
-extern bool usb_check();
-extern bool usb_poll();
-extern bool usb_poll_validate_length();
-extern uint32_t usb_read(uint8_t *data, size_t len);
-extern uint32_t usb_write(const uint8_t *data, const size_t len);
+void usb_disable();
+void usb_enable();
+bool usb_check();
+bool usb_poll();
+bool usb_poll_validate_length();
+uint32_t usb_read(uint8_t *data, size_t len);
+uint32_t usb_write(const uint8_t *data, const size_t len);
-extern void SetUSBreconnect(int value);
-extern int GetUSBreconnect(void);
-extern void SetUSBconfigured(int value);
-extern int GetUSBconfigured(void);
+void SetUSBreconnect(int value);
+int GetUSBreconnect(void);
+void SetUSBconfigured(int value);
+int GetUSBconfigured(void);
-extern void AT91F_USB_SendData(AT91PS_UDP pUdp, const char *pData, uint32_t length);
-extern void AT91F_USB_SendZlp(AT91PS_UDP pUdp);
-extern void AT91F_USB_SendStall(AT91PS_UDP pUdp);
-extern void AT91F_CDC_Enumerate();
+void AT91F_USB_SendData(AT91PS_UDP pUdp, const char *pData, uint32_t length);
+void AT91F_USB_SendZlp(AT91PS_UDP pUdp);
+void AT91F_USB_SendStall(AT91PS_UDP pUdp);
+void AT91F_CDC_Enumerate();
#endif // _USB_CDC_H_
diff --git a/common/wiegand.c b/common/wiegand.c
index 3e90c61b6..cd4fb3eb6 100644
--- a/common/wiegand.c
+++ b/common/wiegand.c
@@ -72,20 +72,20 @@ size_t removeParity(uint8_t *bits, size_t startIdx, uint8_t pLen, uint8_t pType,
// Make sure *dest is long enough to store original sourceLen + #_of_parities_to_be_added
/*
* @brief addParity
-* @param bits pointer to the source bitstream of binary values
+* @param src pointer to the source bitstream of binary values
* @param dest pointer to the destination where parities together with bits are added.
* @param sourceLen number of
* @param pLen length bits to be checked
* @param pType EVEN|ODD|2 (always 1's)|3 (always 0's)
* @return
*/
-size_t addParity(uint8_t *bits, uint8_t *dest, uint8_t sourceLen, uint8_t pLen, uint8_t pType) {
+size_t addParity(uint8_t *src, uint8_t *dest, uint8_t sourceLen, uint8_t pLen, uint8_t pType) {
uint32_t parityWd = 0;
size_t j = 0, bitCnt = 0;
for (int word = 0; word < sourceLen; word += pLen - 1) {
for (int bit = 0; bit < pLen - 1; ++bit) {
- parityWd = (parityWd << 1) | bits[word + bit];
- dest[j++] = (bits[word + bit]);
+ parityWd = (parityWd << 1) | src[word + bit];
+ dest[j++] = (src[word + bit]);
}
// if parity fails then return 0
diff --git a/include/legic_prng.h b/include/legic_prng.h
index 16855ab90..8f37e04a1 100644
--- a/include/legic_prng.h
+++ b/include/legic_prng.h
@@ -10,9 +10,9 @@
#define __LEGIC_PRNG_H
#include
-extern void legic_prng_init(uint8_t iv);
-extern void legic_prng_forward(int count);
-extern uint8_t legic_prng_get_bit();
-extern uint32_t legic_prng_get_bits(uint8_t len);
+void legic_prng_init(uint8_t iv);
+void legic_prng_forward(int count);
+uint8_t legic_prng_get_bit();
+uint32_t legic_prng_get_bits(uint8_t len);
#endif
diff --git a/include/mifare.h b/include/mifare.h
index 68bc700b3..410250593 100644
--- a/include/mifare.h
+++ b/include/mifare.h
@@ -47,10 +47,11 @@ typedef enum ISO14A_COMMAND {
typedef struct {
uint8_t *response;
- size_t response_n;
uint8_t *modulation;
- size_t modulation_n;
+ uint16_t response_n;
+ uint16_t modulation_n;
uint32_t ProxToAirDuration;
+ uint8_t par; // enough for precalculated parity of 8 Byte responses
} tag_response_info_t;
//-----------------------------------------------------------------------------
// ISO 14443B
diff --git a/include/usb_cmd.h b/include/usb_cmd.h
index 113cc7e57..57f2c46fd 100644
--- a/include/usb_cmd.h
+++ b/include/usb_cmd.h
@@ -296,7 +296,10 @@ typedef struct {
#define FLAG_10B_UID_IN_DATA 0x08
#define FLAG_UID_IN_EMUL 0x10
#define FLAG_NR_AR_ATTACK 0x20
-//#define FLAG_RANDOM_NONCE 0x40
+#define FLAG_MF_MINI 0x80
+#define FLAG_MF_1K 0x100
+#define FLAG_MF_2K 0x200
+#define FLAG_MF_4K 0x400
//Iclass reader flags
#define FLAG_ICLASS_READER_ONLY_ONCE 0x01
diff --git a/prox.png b/prox.png
new file mode 100644
index 000000000..1fce7e315
Binary files /dev/null and b/prox.png differ
diff --git a/tools/nonce2key/crapto1.c b/tools/nonce2key/crapto1.c
index 559e12872..9026a57bb 100644
--- a/tools/nonce2key/crapto1.c
+++ b/tools/nonce2key/crapto1.c
@@ -77,10 +77,9 @@ static void bucket_sort_intersect(uint32_t *const estart, uint32_t *const estop,
// write back intersecting buckets as sorted list.
// fill in bucket_info with head and tail of the bucket contents in the list and number of non-empty buckets.
- uint32_t nonempty_bucket;
for (uint32_t i = 0; i < 2; i++) {
p1 = start[i];
- nonempty_bucket = 0;
+ uint32_t nonempty_bucket = 0;
for (uint32_t j = 0x00; j <= 0xff; j++) {
if (bucket[0][j].bp != bucket[0][j].head && bucket[1][j].bp != bucket[1][j].head) { // non-empty intersecting buckets only
bucket_info->bucket_info[i][nonempty_bucket].head = p1;
@@ -146,13 +145,12 @@ static struct Crypto1State *
recover(uint32_t *o_head, uint32_t *o_tail, uint32_t oks,
uint32_t *e_head, uint32_t *e_tail, uint32_t eks, int rem,
struct Crypto1State *sl, uint32_t in, bucket_array_t bucket) {
- uint32_t *o, *e;
bucket_info_t bucket_info;
if (rem == -1) {
- for (e = e_head; e <= e_tail; ++e) {
- *e = *e << 1 ^ parity(*e & LF_POLY_EVEN) ^ !!(in & 4);
- for (o = o_head; o <= o_tail; ++o, ++sl) {
+ for (uint32_t *e = e_head; e <= e_tail; ++e) {
+ *e = *e << 1 ^ parity(*e & LF_POLY_EVEN) ^ (!!(in & 4));
+ for (uint32_t *o = o_head; o <= o_tail; ++o, ++sl) {
sl->even = *o;
sl->odd = *e ^ parity(*o & LF_POLY_ODD);
sl[1].odd = sl[1].even = 0;
@@ -193,12 +191,11 @@ struct Crypto1State *lfsr_recovery32(uint32_t ks2, uint32_t in) {
struct Crypto1State *statelist;
uint32_t *odd_head = 0, *odd_tail = 0, oks = 0;
uint32_t *even_head = 0, *even_tail = 0, eks = 0;
- int i;
// split the keystream into an odd and even part
- for (i = 31; i >= 0; i -= 2)
+ for (int i = 31; i >= 0; i -= 2)
oks = oks << 1 | BEBIT(ks2, i);
- for (i = 30; i >= 0; i -= 2)
+ for (int i = 30; i >= 0; i -= 2)
eks = eks << 1 | BEBIT(ks2, i);
odd_head = odd_tail = malloc(sizeof(uint32_t) << 21);
@@ -225,7 +222,7 @@ struct Crypto1State *lfsr_recovery32(uint32_t ks2, uint32_t in) {
}
// initialize statelists: add all possible states which would result into the rightmost 2 bits of the keystream
- for (i = 1 << 20; i >= 0; --i) {
+ for (int i = 1 << 20; i >= 0; --i) {
if (filter(i) == (oks & 1))
*++odd_tail = i;
if (filter(i) == (eks & 1))
@@ -233,7 +230,7 @@ struct Crypto1State *lfsr_recovery32(uint32_t ks2, uint32_t in) {
}
// extend the statelists. Look at the next 8 Bits of the keystream (4 Bit each odd and even):
- for (i = 0; i < 4; i++) {
+ for (uint8_t i = 0; i < 4; i++) {
extend_table_simple(odd_head, &odd_tail, (oks >>= 1) & 1);
extend_table_simple(even_head, &even_tail, (eks >>= 1) & 1);
}
@@ -362,7 +359,7 @@ uint8_t lfsr_rollback_bit(struct Crypto1State *s, uint32_t in, int fb) {
out ^= LF_POLY_EVEN & (s->even >>= 1);
out ^= LF_POLY_ODD & s->odd;
out ^= !!in;
- out ^= (ret = filter(s->odd)) & !!fb;
+ out ^= (ret = filter(s->odd)) & (!!fb);
s->even |= parity(out) << 23;
return ret;
@@ -498,21 +495,21 @@ uint32_t *lfsr_prefix_ks(uint8_t ks[8], int isodd) {
* helper function which eliminates possible secret states using parity bits
*/
static struct Crypto1State *check_pfx_parity(uint32_t prefix, uint32_t rresp, uint8_t parities[8][8], uint32_t odd, uint32_t even, struct Crypto1State *sl) {
- uint32_t ks1, nr, ks2, rr, ks3, c, good = 1;
+ uint32_t good = 1;
- for (c = 0; good && c < 8; ++c) {
+ for (uint32_t c = 0; good && c < 8; ++c) {
sl->odd = odd ^ fastfwd[1][c];
sl->even = even ^ fastfwd[0][c];
lfsr_rollback_bit(sl, 0, 0);
lfsr_rollback_bit(sl, 0, 0);
- ks3 = lfsr_rollback_bit(sl, 0, 0);
- ks2 = lfsr_rollback_word(sl, 0, 0);
- ks1 = lfsr_rollback_word(sl, prefix | c << 5, 1);
+ uint32_t ks3 = lfsr_rollback_bit(sl, 0, 0);
+ uint32_t ks2 = lfsr_rollback_word(sl, 0, 0);
+ uint32_t ks1 = lfsr_rollback_word(sl, prefix | c << 5, 1);
- nr = ks1 ^ (prefix | c << 5);
- rr = ks2 ^ rresp;
+ uint32_t nr = ks1 ^ (prefix | c << 5);
+ uint32_t rr = ks2 ^ rresp;
good &= parity(nr & 0x000000ff) ^ parities[c][3] ^ BIT(ks2, 24);
good &= parity(rr & 0xff000000) ^ parities[c][4] ^ BIT(ks2, 16);
diff --git a/tools/nonce2key/crypto1.c b/tools/nonce2key/crypto1.c
index cdb0ffc14..0c3f97b88 100644
--- a/tools/nonce2key/crypto1.c
+++ b/tools/nonce2key/crypto1.c
@@ -49,7 +49,7 @@ uint8_t crypto1_bit(struct Crypto1State *s, uint8_t in, int is_encrypted) {
uint32_t tmp;
uint8_t ret = filter(s->odd);
- feedin = ret & !!is_encrypted;
+ feedin = ret & (!!is_encrypted);
feedin ^= !!in;
feedin ^= LF_POLY_ODD & s->odd;
feedin ^= LF_POLY_EVEN & s->even;
diff --git a/uart/uart_posix.c b/uart/uart_posix.c
index 92af6774a..fc5eced7f 100644
--- a/uart/uart_posix.c
+++ b/uart/uart_posix.c
@@ -206,7 +206,7 @@ serial_port uart_open(const char *pcPortName, uint32_t speed) {
}
}
}
- printf("[=] UART Setting serial baudrate %i\n", speed);
+ printf("[=] UART Setting serial baudrate %u\n", speed);
return sp;
}
@@ -231,7 +231,6 @@ void uart_close(const serial_port sp) {
}
bool uart_receive(const serial_port sp, uint8_t *pbtRx, size_t pszMaxRxLen, size_t *pszRxLen) {
- int res;
int byteCount;
fd_set rfds;
struct timeval tv;
@@ -244,7 +243,7 @@ bool uart_receive(const serial_port sp, uint8_t *pbtRx, size_t pszMaxRxLen, size
FD_ZERO(&rfds);
FD_SET(((serial_port_unix *)sp)->fd, &rfds);
tv = timeout;
- res = select(((serial_port_unix *)sp)->fd + 1, &rfds, NULL, NULL, &tv);
+ int res = select(((serial_port_unix *)sp)->fd + 1, &rfds, NULL, NULL, &tv);
// Read error
if (res < 0) {
@@ -290,7 +289,6 @@ bool uart_receive(const serial_port sp, uint8_t *pbtRx, size_t pszMaxRxLen, size
}
bool uart_send(const serial_port sp, const uint8_t *pbtTx, const size_t len) {
- int32_t res;
size_t pos = 0;
fd_set rfds;
struct timeval tv;
@@ -300,7 +298,7 @@ bool uart_send(const serial_port sp, const uint8_t *pbtTx, const size_t len) {
FD_ZERO(&rfds);
FD_SET(((serial_port_unix *)sp)->fd, &rfds);
tv = timeout;
- res = select(((serial_port_unix *)sp)->fd + 1, NULL, &rfds, NULL, &tv);
+ int res = select(((serial_port_unix *)sp)->fd + 1, NULL, &rfds, NULL, &tv);
// Write error
if (res < 0) {